1use std::collections::HashSet;
2use std::env::consts::EXE_SUFFIX;
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use futures::future::join_all;
7use futures::stream::{self, StreamExt};
8use tokio::fs;
9use tokio::process::Command;
10
11use crate::runtime::{
12 RuntimeValidationMode,
13 error::{Error, Result},
14 provider::RuntimeProvider,
15};
16
17const JAVA_INFO_PROBE_TIMEOUT: Duration = Duration::from_secs(15);
18const JAVA_INFO_PROBE_CONCURRENCY: usize = 8;
19const JAVA_PROBE_ENV_VARIABLES: &[&str] = &[
20 "JAVA_HOME",
21 "JRE_HOME",
22 "JAVA_ARGS",
23 "CLASSPATH",
24 "JAVA_TOOL_OPTIONS",
25 "_JAVA_OPTIONS",
26 "JAVA_OPTIONS",
27 "JDK_JAVA_OPTIONS",
28];
29
30#[derive(Debug, Default, Clone)]
31pub struct DistributionReleaseData {
32 pub implementor: Option<String>,
34 pub architecture: Option<String>,
37 pub major_version: Option<String>,
39 pub jre_version: Option<String>,
41 pub jvm_version: Option<String>,
43}
44
45#[derive(Debug, Clone)]
46pub struct Distribution {
47 release: Option<DistributionReleaseData>,
49
50 path: PathBuf,
53
54 provider: &'static str,
57}
58
59impl DistributionReleaseData {
60 pub fn java_major_version(&self) -> Option<usize> {
61 self.major_version
62 .as_deref()
63 .and_then(Self::parse_java_major_version)
64 }
65
66 pub fn matches_java_major_version(&self, major_version: usize) -> bool {
67 self.java_major_version()
68 .is_some_and(|current| current == major_version)
69 }
70
71 pub async fn parse_from_commandline(root: &Path) -> Result<Self> {
72 let java_exe = root.join("bin").join(format!("java{EXE_SUFFIX}"));
73 let mut command = Command::new(&java_exe);
74 command.arg("-XshowSettings:properties").kill_on_drop(true);
75 for variable_name in JAVA_PROBE_ENV_VARIABLES {
76 command.env_remove(variable_name);
77 }
78
79 let output = tokio::time::timeout(JAVA_INFO_PROBE_TIMEOUT, command.output())
80 .await
81 .map_err(|_| Error::ProbeTimeout {
82 executable: java_exe.clone(),
83 timeout_secs: JAVA_INFO_PROBE_TIMEOUT.as_secs(),
84 })?
85 .map_err(|source| Error::ProbeSpawn {
86 executable: java_exe.clone(),
87 source,
88 })?;
89
90 if !output.status.success() {
91 return Err(Error::ProbeFailed {
92 executable: java_exe,
93 status: output.status,
94 });
95 }
96
97 let release = Self::parse_properties(&String::from_utf8_lossy(&output.stderr));
98 if release.java_major_version().is_none() {
99 return Err(Error::ProbeMissingVersion {
100 executable: java_exe,
101 });
102 }
103
104 Ok(release)
105 }
106
107 pub async fn parse_from_release(root: &Path) -> Result<Self> {
108 let release_path = root.join("release");
109 let content =
110 fs::read_to_string(&release_path)
111 .await
112 .map_err(|source| Error::ReadRelease {
113 path: release_path.clone(),
114 source,
115 })?;
116 let release = Self::parse_release_properties(&content);
117 if release.java_major_version().is_none() {
118 return Err(Error::ReleaseMissingVersion { path: release_path });
119 }
120
121 Ok(release)
122 }
123
124 pub async fn parse(root: &Path) -> Result<Self> {
125 let release_path = root.join("release");
126 let release_exists =
127 fs::try_exists(&release_path)
128 .await
129 .map_err(|source| Error::CheckRelease {
130 path: release_path.clone(),
131 source,
132 })?;
133
134 if release_exists {
135 Self::parse_from_release(root).await
136 } else {
137 Self::parse_from_commandline(root).await
138 }
139 }
140
141 pub fn is_lts(&self) -> bool {
142 self.major_version
143 .as_deref()
144 .and_then(Self::parse_java_major_version)
145 .is_some_and(|version| matches!(version, 8 | 11 | 17 | 21))
146 }
147
148 fn parse_properties(output: &str) -> Self {
149 let mut implementor = None;
150 let mut architecture = None;
151 let mut major_version = None;
152 let mut jre_version = None;
153 let mut jvm_version = None;
154
155 for (key, value) in Self::property_pairs(output) {
156 match key {
157 "java.vm.vendor" => implementor = Some(value.to_string()),
158 "os.arch" => architecture = Some(value.to_string()),
159 "java.specification.version" => major_version = Some(value.to_string()),
160 "java.version" => jre_version = Some(value.to_string()),
161 "java.vm.version" => jvm_version = Some(value.to_string()),
162 _ => {}
163 }
164 }
165
166 Self {
167 implementor,
168 architecture,
169 major_version,
170 jre_version,
171 jvm_version,
172 }
173 }
174
175 fn parse_release_properties(output: &str) -> Self {
176 let mut implementor = None;
177 let mut architecture = None;
178 let mut major_version = None;
179 let mut jre_version = None;
180 let mut jvm_version = None;
181
182 for (key, value) in Self::property_pairs(output) {
183 let value = value.trim_matches('"');
184 match key {
185 "IMPLEMENTOR" => implementor = Some(value.to_string()),
186 "OS_ARCH" => architecture = Some(value.to_string()),
187 "JAVA_VERSION" => jre_version = Some(value.to_string()),
188 "JAVA_RUNTIME_VERSION" => jvm_version = Some(value.to_string()),
189 _ => {}
190 }
191 }
192
193 if let Some(ref ver) = jre_version {
195 major_version = Self::parse_java_major_version(ver).map(|value| value.to_string());
196 }
197
198 Self {
199 implementor,
200 architecture,
201 major_version,
202 jre_version,
203 jvm_version,
204 }
205 }
206
207 fn property_pairs(output: &str) -> impl Iterator<Item = (&str, &str)> {
208 output.lines().filter_map(|line| {
209 let (key, value) = line.trim().split_once('=')?;
210 Some((key.trim(), value.trim()))
211 })
212 }
213
214 fn parse_java_major_version(version: &str) -> Option<usize> {
215 let normalized = version.trim();
216 if let Some(legacy) = normalized.strip_prefix("1.") {
217 return legacy
218 .split(['.', '_', '-'])
219 .next()
220 .and_then(|value| value.parse::<usize>().ok());
221 }
222
223 normalized
224 .split(['.', '_', '-'])
225 .next()
226 .and_then(|value| value.parse::<usize>().ok())
227 }
228}
229
230impl Distribution {
231 pub(crate) async fn build_from_root(root: PathBuf, provider: &'static str) -> Result<Self> {
232 let requested_root = root.clone();
233 let root =
234 fs::canonicalize(&root)
235 .await
236 .map_err(|source| Error::CanonicalizeRuntimeRoot {
237 path: root.clone(),
238 source,
239 })?;
240 let release = DistributionReleaseData::parse(&root)
241 .await
242 .map_err(|source| Error::DetermineRuntimeProperties {
243 path: requested_root,
244 source: Box::new(source),
245 })?;
246
247 Ok(Self {
248 release: Some(release),
249 path: root,
250 provider,
251 })
252 }
253
254 pub async fn from_providers<O>(providers: Vec<std::sync::Arc<dyn RuntimeProvider>>) -> O
255 where
256 O: FromIterator<Self>,
257 {
258 let provider_lists = join_all(
259 providers
260 .into_iter()
261 .map(|provider| async move { (provider.name(), provider.list().await) }),
262 )
263 .await;
264
265 let mut probes = Vec::new();
266 for (name, paths) in provider_lists {
267 for path in paths {
268 let candidate_path = path.clone();
269 probes.push(async move {
270 Distribution::build_from_root(path, name)
271 .await
272 .map_err(|source| Error::BuildDistribution {
273 provider: name,
274 path: candidate_path,
275 source: Box::new(source),
276 })
277 });
278 }
279 }
280
281 let distributions: Vec<Self> = stream::iter(probes)
282 .buffer_unordered(JAVA_INFO_PROBE_CONCURRENCY)
283 .filter_map(|result| async move {
284 match result {
285 Ok(distribution) => Some(distribution),
286 Err(error) => {
287 tracing::warn!(%error, "skip invalid Java runtime candidate");
288 None
289 }
290 }
291 })
292 .collect()
293 .await;
294
295 let mut seen_paths = HashSet::with_capacity(distributions.len());
296 let mut unique_distributions: Vec<Self> = distributions
297 .into_iter()
298 .filter(|distribution| seen_paths.insert(distribution.path.clone()))
299 .collect();
300 unique_distributions.sort_by(Self::compare_priority);
301 unique_distributions.into_iter().collect()
302 }
303
304 fn compare_priority(&self, other: &Self) -> std::cmp::Ordering {
305 let self_version = self
306 .release
307 .as_ref()
308 .and_then(|release| release.jre_version.as_deref());
309 let other_version = other
310 .release
311 .as_ref()
312 .and_then(|release| release.jre_version.as_deref());
313
314 other
315 .java_major_version()
316 .cmp(&self.java_major_version())
317 .then_with(|| ordering::compare_release_versions(other_version, self_version))
318 .then_with(|| self.path.cmp(&other.path))
319 }
320
321 pub fn matches_java_major_version(&self, major_version: usize) -> bool {
322 self.release
323 .as_ref()
324 .is_some_and(|release| release.matches_java_major_version(major_version))
325 }
326
327 pub fn java_major_version(&self) -> Option<usize> {
328 self.release
329 .as_ref()
330 .and_then(DistributionReleaseData::java_major_version)
331 }
332
333 pub fn release(&self) -> Option<&DistributionReleaseData> {
334 self.release.as_ref()
335 }
336
337 pub fn path(&self) -> &Path {
338 &self.path
339 }
340
341 pub fn provider(&self) -> &'static str {
342 self.provider
343 }
344
345 pub fn executable(&self) -> PathBuf {
346 self.path.join("bin").join(format!("java{EXE_SUFFIX}"))
347 }
348
349 pub fn executablew(&self) -> Option<PathBuf> {
357 #[cfg(windows)]
358 {
359 let windowed = self.path.join("bin").join(format!("javaw{EXE_SUFFIX}"));
360 if windowed.exists() {
361 return Some(windowed);
362 }
363 }
364
365 None
366 }
367
368 pub fn require_compatible(
369 &self,
370 required_major_version: usize,
371 validation_mode: RuntimeValidationMode,
372 ) -> Result<()> {
373 if validation_mode == RuntimeValidationMode::Disabled {
374 return Ok(());
375 }
376
377 let actual_major_version =
378 self.java_major_version()
379 .ok_or_else(|| Error::RuntimeVersionUnknown {
380 path: self.path.clone(),
381 })?;
382 if actual_major_version != required_major_version {
383 return Err(Error::VersionMismatch {
384 actual: actual_major_version,
385 expected: required_major_version,
386 path: self.path.clone(),
387 });
388 }
389
390 Ok(())
391 }
392}
393
394mod ordering {
395 use std::cmp::Ordering;
396
397 pub(super) fn compare_release_versions(left: Option<&str>, right: Option<&str>) -> Ordering {
398 match (left, right) {
399 (Some(left), Some(right)) => {
400 let mut left_components = version_components(left).peekable();
401 let mut right_components = version_components(right).peekable();
402 if left_components.peek().is_none() || right_components.peek().is_none() {
403 left.cmp(right)
404 } else {
405 left_components.cmp(right_components)
406 }
407 }
408 (Some(_), None) => Ordering::Greater,
409 (None, Some(_)) => Ordering::Less,
410 (None, None) => Ordering::Equal,
411 }
412 }
413
414 fn version_components(version: &str) -> impl Iterator<Item = u64> + '_ {
415 version
416 .split(|character: char| !character.is_ascii_digit())
417 .filter(|component| !component.is_empty())
418 .filter_map(|component| component.parse::<u64>().ok())
419 }
420}
421
422#[tokio::test]
423async fn default_providers_return_deduplicated_distributions_sorted_by_major_version() {
424 use super::providers::default_providers;
425
426 let distributions: Vec<_> = Distribution::from_providers(default_providers()).await;
427 let mut paths: Vec<_> = distributions
428 .iter()
429 .map(|distribution| distribution.path.clone())
430 .collect();
431 let path_count = paths.len();
432 paths.sort();
433 paths.dedup();
434
435 assert_eq!(paths.len(), path_count);
436 assert!(
437 distributions
438 .iter()
439 .all(|distribution| distribution.java_major_version().is_some())
440 );
441 assert!(
442 distributions
443 .windows(2)
444 .all(|pair| { pair[0].java_major_version() >= pair[1].java_major_version() })
445 );
446 println!("{:#?}", distributions);
447}
448
449#[test]
450fn parse_properties_uses_exact_keys_and_unquotes_release_values() {
451 let diagnostic = r#"
452 java.vm.vendor = Eclipse Adoptium
453 os.arch = amd64
454 java.specification.version = 21
455 java.version = 21.0.5
456 java.version.date = 2024-10-15
457 java.vm.version = 21.0.5+11-LTS
458 "#;
459 let release = DistributionReleaseData::parse_properties(diagnostic);
460 assert_eq!(release.jre_version.as_deref(), Some("21.0.5"));
461 assert_eq!(release.jvm_version.as_deref(), Some("21.0.5+11-LTS"));
462 assert_eq!(release.java_major_version(), Some(21));
463
464 let release_file = r#"
465 IMPLEMENTOR="Eclipse Adoptium"
466 OS_ARCH="x86_64"
467 JAVA_VERSION="1.8.0_452"
468 JAVA_VERSION_DATE="2025-01-21"
469 JAVA_RUNTIME_VERSION="1.8.0_452-b09"
470 "#;
471 let release = DistributionReleaseData::parse_release_properties(release_file);
472 assert_eq!(release.implementor.as_deref(), Some("Eclipse Adoptium"));
473 assert_eq!(release.jre_version.as_deref(), Some("1.8.0_452"));
474 assert_eq!(release.java_major_version(), Some(8));
475}