Skip to content

Commit 935b76e

Browse files
committed
Move cjdk fetch settings into scyjava.config
1 parent b4edf11 commit 935b76e

File tree

3 files changed

+142
-38
lines changed

3 files changed

+142
-38
lines changed

src/scyjava/_cjdk_fetch.py

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
"""
2+
Utility functions for fetching JDK/JRE and Maven.
3+
"""
4+
15
from __future__ import annotations
26

37
import logging
@@ -9,21 +13,23 @@
913
import cjdk
1014
import jpype
1115

16+
import scyjava.config
17+
1218
if TYPE_CHECKING:
1319
from pathlib import Path
1420

1521
_logger = logging.getLogger(__name__)
16-
_DEFAULT_MAVEN_URL = "tgz+https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz" # noqa: E501
17-
_DEFAULT_MAVEN_SHA = "a555254d6b53d267965a3404ecb14e53c3827c09c3b94b5678835887ab404556bfaf78dcfe03ba76fa2508649dca8531c74bca4d5846513522404d48e8c4ac8b" # noqa: E501
18-
_DEFAULT_JAVA_VENDOR = "zulu-jre"
19-
_DEFAULT_JAVA_VERSION = "11"
2022

2123

2224
def ensure_jvm_available() -> None:
2325
"""Ensure that the JVM is available and Maven is installed."""
24-
if not is_jvm_available():
26+
fetch = scyjava.config.get_fetch_java()
27+
if fetch == "never":
28+
# Not allowed to use cjdk.
29+
return
30+
if fetch == "always" or not is_jvm_available():
2531
cjdk_fetch_java()
26-
if not shutil.which("mvn"):
32+
if fetch == "always" or not shutil.which("mvn"):
2733
cjdk_fetch_maven()
2834

2935

@@ -47,27 +53,27 @@ def _silent_check_output(*args, **kwargs):
4753
return True
4854

4955

50-
def cjdk_fetch_java(vendor: str = "", version: str = "") -> None:
56+
def cjdk_fetch_java(vendor: str | None = None, version: str | None = None) -> None:
5157
"""Fetch java using cjdk and add it to the PATH."""
52-
if not vendor:
53-
vendor = os.getenv("JAVA_VENDOR", _DEFAULT_JAVA_VENDOR)
54-
version = os.getenv("JAVA_VERSION", _DEFAULT_JAVA_VERSION)
58+
if vendor is None:
59+
vendor = scyjava.config.get_java_vendor()
60+
if version is None:
61+
version = scyjava.config.get_java_version()
5562

56-
_logger.info(f"No JVM found, fetching {vendor}:{version} using cjdk...")
57-
home = cjdk.java_home(vendor=vendor, version=version)
58-
_add_to_path(str(home / "bin"))
59-
os.environ["JAVA_HOME"] = str(home)
63+
_logger.info(f"Fetching {vendor}:{version} using cjdk...")
64+
java_home = cjdk.java_home(vendor=vendor, version=version)
65+
_logger.debug(f"java_home -> {java_home}")
66+
_add_to_path(str(java_home / "bin"), front=True)
67+
os.environ["JAVA_HOME"] = str(java_home)
6068

6169

6270
def cjdk_fetch_maven(url: str = "", sha: str = "") -> None:
6371
"""Fetch Maven using cjdk and add it to the PATH."""
64-
# if url was passed as an argument, or env_var, use it with provided sha
72+
# if url was passed as an argument, use it with provided sha
6573
# otherwise, use default values for both
66-
if url := url or os.getenv("MAVEN_URL", ""):
67-
sha = sha or os.getenv("MAVEN_SHA", "")
68-
else:
69-
url = _DEFAULT_MAVEN_URL
70-
sha = _DEFAULT_MAVEN_SHA
74+
if not url:
75+
url = scyjava.config.get_maven_url()
76+
sha = scyjava.config.get_maven_sha()
7177

7278
# fix urls to have proper prefix for cjdk
7379
if url.startswith("http"):
@@ -88,7 +94,9 @@ def cjdk_fetch_maven(url: str = "", sha: str = "") -> None:
8894
)
8995
kwargs = {sha_lengths[sha_len]: sha}
9096

97+
_logger.info("Fetching Maven using cjdk...")
9198
maven_dir = cjdk.cache_package("Maven", url, **kwargs)
99+
_logger.debug(f"maven_dir -> {maven_dir}")
92100
if maven_bin := next(maven_dir.rglob("apache-maven-*/**/mvn"), None):
93101
_add_to_path(maven_bin.parent, front=True)
94102
else: # pragma: no cover

src/scyjava/_jvm.py

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import scyjava.config
2020
from scyjava.config import Mode, mode
21+
from scyjava._cjdk_fetch import ensure_jvm_available
2122

2223
_logger = logging.getLogger(__name__)
2324

@@ -106,7 +107,7 @@ def jvm_version() -> tuple[int, ...]:
106107
return tuple(map(int, m.group(1).split(".")))
107108

108109

109-
def start_jvm(options=None, *, fetch_java: bool = True) -> None:
110+
def start_jvm(*options) -> None:
110111
"""
111112
Explicitly connect to the Java virtual machine (JVM). Only one JVM can
112113
be active; does nothing if the JVM has already been started. Calling
@@ -118,19 +119,6 @@ def start_jvm(options=None, *, fetch_java: bool = True) -> None:
118119
List of options to pass to the JVM.
119120
For example: ['-Dfoo=bar', '-XX:+UnlockExperimentalVMOptions']
120121
See also scyjava.config.add_options.
121-
:param fetch_java:
122-
If True (default), when a JVM/or maven cannot be located on the system,
123-
[`cjdk`](https://github.com/cachedjdk/cjdk) will be used to download
124-
a JRE distribution and set up the JVM. The following environment variables
125-
may be used to configure the JRE and Maven distributions to download:
126-
* `JAVA_VENDOR`: The vendor of the JRE distribution to download.
127-
Defaults to "zulu-jre".
128-
* `JAVA_VERSION`: The version of the JRE distribution to download.
129-
Defaults to "11".
130-
* `MAVEN_URL`: The URL of the Maven distribution to download.
131-
Defaults to https://dlcdn.apache.org/maven/maven-3/3.9.9/
132-
* `MAVEN_SHA`: The SHA512 hash of the Maven distribution to download, if
133-
providing a custom MAVEN_URL.
134122
"""
135123
# if JVM is already running -- break
136124
if jvm_started():
@@ -147,10 +135,8 @@ def start_jvm(options=None, *, fetch_java: bool = True) -> None:
147135
# use the logger to notify user that endpoints are being added
148136
_logger.debug("Adding jars from endpoints {0}".format(endpoints))
149137

150-
if fetch_java:
151-
from scyjava._cjdk_fetch import ensure_jvm_available
152-
153-
ensure_jvm_available()
138+
# download JDK/JRE and Maven as appropriate
139+
ensure_jvm_available()
154140

155141
# get endpoints and add to JPype class path
156142
if len(endpoints) > 0:

src/scyjava/config.py

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@
1010

1111
_logger = _logging.getLogger(__name__)
1212

13+
# Constraints on the Java installation to be used.
14+
_fetch_java: str = "auto"
15+
_java_vendor: str = "zulu-jre"
16+
_java_version: str = "11"
17+
_maven_url: str = "tgz+https://dlcdn.apache.org/maven/maven-3/3.9.9/binaries/apache-maven-3.9.9-bin.tar.gz" # noqa: E501
18+
_maven_sha: str = "a555254d6b53d267965a3404ecb14e53c3827c09c3b94b5678835887ab404556bfaf78dcfe03ba76fa2508649dca8531c74bca4d5846513522404d48e8c4ac8b" # noqa: E501
19+
1320
endpoints: list[str] = []
1421

1522
_repositories = {"scijava.public": _scijava_public()}
@@ -35,6 +42,109 @@ class Mode(_enum.Enum):
3542
mode = Mode.JPYPE
3643

3744

45+
def set_java_constraints(
46+
fetch: str | bool | None = None,
47+
vendor: str | None = None,
48+
version: str | None = None,
49+
maven_url: str | None = None,
50+
maven_sha: str | None = None,
51+
) -> None:
52+
"""
53+
Set constraints on the version of Java to be used.
54+
55+
:param fetch:
56+
If "auto" (default), when a JVM/or maven cannot be located on the system,
57+
[`cjdk`](https://github.com/cachedjdk/cjdk) will be used to download
58+
a JDK/JRE distribution and set up the JVM.
59+
If "always", cjdk will always be used; if "never", cjdk will never be used.
60+
:param vendor:
61+
The vendor of the JDK/JRE distribution for cjdk to download and cache.
62+
Defaults to "zulu-jre". See the cjdk documentation for details.
63+
:param version:
64+
Expression defining the Java version for cjdk to download and cache.
65+
Defaults to "11". See the cjdk documentation for details.
66+
:param maven_url:
67+
URL of the Maven distribution for cjdk to download and cache.
68+
Defaults to the Maven 3.9.9 binary distribution from dlcdn.apache.org.
69+
:param maven_sha:
70+
The SHA512 (or SHA256 or SHA1) hash of the Maven distribution to download,
71+
if providing a custom maven_url.
72+
"""
73+
global _fetch_java, _java_vendor, _java_version, _maven_url, _maven_sha
74+
if fetch is not None:
75+
if isinstance(fetch, bool):
76+
# Be nice and allow boolean values as a convenience.
77+
fetch = "always" if fetch else "never"
78+
expected = ["auto", "always", "never"]
79+
if fetch not in expected:
80+
raise ValueError(f"Fetch mode {fetch} is not one of {expected}")
81+
_fetch_java = fetch
82+
if vendor is not None:
83+
_java_vendor = vendor
84+
if version is not None:
85+
_java_version = version
86+
if maven_url is not None:
87+
_maven_url = maven_url
88+
_maven_sha = ""
89+
if maven_sha is not None:
90+
_maven_sha = maven_sha
91+
92+
93+
def get_fetch_java() -> str:
94+
"""
95+
Get whether [`cjdk`](https://github.com/cachedjdk/cjdk)
96+
will be used to download a JDK/JRE distribution and set up the JVM.
97+
To set this value, see set_java_constraints.
98+
99+
:return:
100+
"always" for cjdk to obtain the JDK/JRE;
101+
"never" for cjdk *not* to obtain a JDK/JRE;
102+
"auto" for cjdk to be used only when a JVM/or Maven is not on the system path.
103+
"""
104+
return _fetch_java
105+
106+
107+
def get_java_vendor() -> str:
108+
"""
109+
Get the vendor of the JDK/JRE distribution to download.
110+
Vendor of the Java installation for cjdk to download and cache.
111+
To set this value, see set_java_constraints.
112+
113+
:return: String defining the desired JDK/JRE vendor for downloaded JDK/JREs.
114+
"""
115+
return _java_vendor
116+
117+
118+
def get_java_version() -> str:
119+
"""
120+
Expression defining the Java version for cjdk to download and cache.
121+
To set this value, see set_java_constraints.
122+
123+
:return: String defining the desired JDK/JRE version for downloaded JDK/JREs.
124+
"""
125+
return _java_version
126+
127+
128+
def get_maven_url() -> str:
129+
"""
130+
The URL of the Maven distribution to download.
131+
To set this value, see set_java_constraints.
132+
133+
:return: URL pointing to the Maven distribution.
134+
"""
135+
return _maven_url
136+
137+
138+
def get_maven_sha() -> str:
139+
"""
140+
The SHA512 (or SHA256 or SHA1) hash of the Maven distribution to download,
141+
if providing a custom maven_url. To set this value, see set_java_constraints.
142+
143+
:return: Hash value of the Maven distribution, or empty string to skip hash check.
144+
"""
145+
return _maven_sha
146+
147+
38148
def add_repositories(*args, **kwargs) -> None:
39149
"""
40150
Add one or more Maven repositories to be used by jgo for downloading dependencies.

0 commit comments

Comments
 (0)