From 50bc5d9134f3093fc23d7f2136463f08b9a0a68b Mon Sep 17 00:00:00 2001 From: Thomas O'Donnell Date: Sat, 13 Mar 2021 17:09:40 +0100 Subject: [PATCH] fix(java): use consistent separators for java path (#2455) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(java): use consistent separators for java path This switches us from just appending `/bin/java` to `$JAVA_HOME` to treating `$JAVA_HOME` as a path. This should fix any issues on Windows where $JAVA_HOME might use `\` rather than `/`. * test(java): add test for JAVA_HOME * refactor: remove duplicate defaults * perf: sligntly better java path perf * Update src/modules/java.rs Co-authored-by: Dario Vladović * Update src/modules/java.rs Co-authored-by: Dario Vladović * Update src/modules/java.rs Co-authored-by: Dario Vladović Co-authored-by: Dario Vladović --- src/modules/java.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/src/modules/java.rs b/src/modules/java.rs index 36a7abf5..5c87d402 100644 --- a/src/modules/java.rs +++ b/src/modules/java.rs @@ -1,5 +1,6 @@ use crate::configs::java::JavaConfig; use crate::formatter::StringFormatter; +use std::path::PathBuf; use super::{Context, Module, RootModuleConfig}; @@ -54,12 +55,19 @@ pub fn module<'a>(context: &'a Context) -> Option> { } fn get_java_version(context: &Context) -> Option { - let java_command = match context.get_env("JAVA_HOME") { - Some(java_home) => format!("{}/bin/java", java_home), - None => String::from("java"), - }; + let java_command = context + .get_env("JAVA_HOME") + .map(PathBuf::from) + .and_then(|path| { + path.join("bin") + .join("java") + .into_os_string() + .into_string() + .ok() + }) + .unwrap_or_else(|| String::from("java")); - let output = context.exec_cmd(&java_command.as_str(), &["-Xinternalversion"])?; + let output = context.exec_cmd(&java_command, &["-Xinternalversion"])?; let java_version = if output.stdout.is_empty() { output.stderr } else { @@ -263,4 +271,25 @@ mod tests { assert_eq!(expected, actual); dir.close() } + + #[test] + fn test_java_home() -> io::Result<()> { + let dir = tempfile::tempdir()?; + File::create(dir.path().join("Main.java"))?.sync_all()?; + let java_home: PathBuf = ["a", "b", "c"].iter().collect(); + let java_bin = java_home.join("bin").join("java"); + + let actual = ModuleRenderer::new("java") + .env("JAVA_HOME", java_home.to_str().unwrap()) + .cmd(&format!("{} -Xinternalversion", java_bin.to_str().unwrap()), + Some(CommandOutput { + stdout: "OpenJDK 64-Bit Server VM (11.0.4+11-LTS-sapmachine) for linux-amd64 JRE (11.0.4+11-LTS-sapmachine), built on Jul 17 2019 08:58:43 by \"\" with gcc 7.3.0".to_owned(), + stderr: String::new(), + })) + .path(dir.path()) + .collect(); + let expected = Some(format!("via {}", Color::Red.dimmed().paint("☕ v11.0.4 "))); + assert_eq!(expected, actual); + dir.close() + } }