java_manager/local.rs
1//! Functions for accessing Java from the local environment.
2
3use crate::JavaInfo;
4use std::env;
5
6/// Returns a `JavaInfo` for the Java installation pointed to by the `JAVA_HOME`
7/// environment variable, if set and valid.
8///
9/// This function reads the `JAVA_HOME` variable, treats it as a path, and attempts
10/// to create a `JavaInfo` from it. If the variable is not set or if the resulting
11/// `JavaInfo` cannot be created (e.g., the path does not contain a valid Java),
12/// `None` is returned.
13///
14/// # Examples
15///
16/// ```no_run
17/// use java_manager::java_home;
18///
19/// if let Some(java) = java_home() {
20/// println!("JAVA_HOME points to Java version {}", java.version);
21/// } else {
22/// println!("JAVA_HOME is not set or invalid");
23/// }
24/// ```
25pub fn java_home() -> Option<JavaInfo> {
26 env::var("JAVA_HOME")
27 .ok()
28 .and_then(|path| JavaInfo::new(path).ok())
29}
30
31#[cfg(test)]
32mod tests {
33 #[test]
34 fn test_java_home_not_set() {
35 let previous = std::env::var_os("JAVA_HOME");
36 // SAFETY: single-threaded test, no other code depends on JAVA_HOME
37 unsafe {
38 std::env::remove_var("JAVA_HOME");
39 }
40 let result = super::java_home();
41 assert!(result.is_none());
42 if let Some(val) = previous {
43 // SAFETY: restoring original value
44 unsafe {
45 std::env::set_var("JAVA_HOME", &val);
46 }
47 }
48 }
49
50 #[test]
51 fn test_java_home_invalid_path() {
52 let previous = std::env::var_os("JAVA_HOME");
53 // SAFETY: single-threaded test
54 unsafe {
55 std::env::set_var("JAVA_HOME", "/nonexistent/java/home");
56 }
57 let result = super::java_home();
58 assert!(result.is_none());
59 if let Some(val) = previous {
60 unsafe {
61 std::env::set_var("JAVA_HOME", &val);
62 }
63 } else {
64 unsafe {
65 std::env::remove_var("JAVA_HOME");
66 }
67 }
68 }
69}