java_runtimes/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
pub mod detector;
pub mod error;
#[cfg(test)]
mod tests;
use crate::error::{Error, ErrorKind};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::env;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Struct [`JavaRuntime`] Represents a java runtime in specific path.
///
/// To detect java runtimes from specific path in filesystem, see [`detector`]
///
/// # Examples
///
/// ```rs
/// JavaRuntime::from_java_exe(r"D:\java\jdk-17.0.4.1\bin\java.exe".as_ref());
/// JavaRuntime::from_java_exe(r"../../runtimes/jdk-1.8.0_291/bin/java".as_ref());
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct JavaRuntime {
os: String,
path: PathBuf,
version_string: String,
}
impl JavaRuntime {
/// Used to match the version string in the command output
///
const VERSION_PATTERN: &'static str = r#".*"((\d+)\.(\d+)([\d._]+)?)".*"#;
/// Create a [`JavaRuntime`] object from the path of java executable file
///
/// It executes command `java -version` to get the version information
pub fn from_java_exe(path: &Path) -> Result<Self, Error> {
let mut java = Self {
os: env::consts::OS.to_string(),
path: path.to_path_buf(),
version_string: String::new(),
};
java.update()?;
Ok(java)
}
/// Mannually create a [`JavaRuntime`] instance, without checking if it's available
///
/// # Argument
///
/// * `os` Got from [`env::consts::OS`]
/// * `path` The path of java executable file, can be either relative or absolute
/// * `version_string` can be like `"17.0.4.1"` or the output of command `java -version`
///
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
/// use std::env;
/// use std::path::Path;
///
/// let java_exe_path = Path::new("../java/jdk-17.0.4.1/bin/java");
/// let version_outputs = r#"java version "17.0.4.1" 2022-08-18 LTS
/// Java(TM) SE Runtime Environment (build 17.0.4.1+1-LTS-2)
/// Java HotSpot(TM) 64-Bit Server VM (build 17.0.4.1+1-LTS-2, mixed mode, sharing)
/// "#;
/// let runtime = JavaRuntime::new(env::consts::OS, java_exe_path, version_outputs).unwrap();
/// assert_eq!(runtime.get_version_string(), "17.0.4.1");
/// assert!(runtime.is_same_os());
/// ```
pub fn new(os: &str, path: &Path, version_string: &str) -> Result<Self, Error> {
let version_string = Self::extract_version(version_string)?;
Ok(Self {
os: os.to_string(),
path: path.to_path_buf(),
version_string: version_string.to_string(),
})
}
/// Get the operating system of the java runtime
///
/// The os string comes from [`env::consts::OS`] when this object was created.
pub fn get_os(&self) -> &str {
&self.os
}
pub fn is_windows(&self) -> bool {
self.os == "windows"
}
/// Get the path of java executable file
///
/// It can be absolute or relative, depends on how you created it.
///
/// # Examples
///
/// * `D:\Java\jdk-17.0.4.1\bin\java.exe` (Windows, absolute)
/// * `../../runtimes/jdk-1.8.0_291/bin/java` (Linux, relative)
pub fn get_executable(&self) -> &Path {
&self.path
}
/// Returns `true` if the `Path` has a root.
///
/// Refer to [`Path::has_root`]
///
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// let runtime = JavaRuntime::new("linux", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// assert!(runtime.has_root());
///
/// let runtime = JavaRuntime::new("windows", r"D:\jdk\bin\java.exe".as_ref(), "21.0.3").unwrap();
/// assert!(runtime.has_root());
///
/// let runtime = JavaRuntime::new("linux", "../jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// assert!(!runtime.has_root());
///
/// let runtime = JavaRuntime::new("windows", r"..\jdk\bin\java.exe".as_ref(), "21.0.3").unwrap();
/// assert!(!runtime.has_root());
/// ```
pub fn has_root(&self) -> bool {
self.path.has_root()
}
/// Get the version string
///
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// let runtime = JavaRuntime::new("linux", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// assert_eq!(runtime.get_version_string(), "21.0.3");
/// ```
pub fn get_version_string(&self) -> &str {
&self.version_string
}
/// Check if this is the same os as current
pub fn is_same_os(&self) -> bool {
self.os == env::consts::OS
}
/// Create a new [`JavaRuntime`] with absolute path.
///
/// # Errors
///
/// Returns an [`Err`] if the current working directory value is invalid. Refer to [`env::current_dir`]
///
/// Possible cases:
///
/// * Current directory does not exist.
/// * There are insufficient permissions to access the current directory.
pub fn to_absolute(&self) -> Result<Self, Error> {
let cwd = env::current_dir().or(Err(Error::new(ErrorKind::InvalidWorkDir)))?;
let path_absolute = self.path.join(cwd);
let new_runtime = Self::new(&self.os, &path_absolute, &self.version_string)?;
Ok(new_runtime)
}
/// Try executing `java -version` and parse the output to get the version.
///
/// If success, it will update the version value in this [`JavaRuntime`] instance.
pub fn update(&mut self) -> Result<(), Error> {
if !Self::looks_like_java_executable_file(&self.path) {
return Err(Error::new(ErrorKind::LooksNotLikeJavaExecutableFile(
self.path.clone(),
)));
}
let output = Command::new(&self.path)
.arg("-version")
.output()
.map_err(|err| Error::new(ErrorKind::JavaOutputFailed(err)))?;
if output.status.success() {
let version_output = String::from_utf8_lossy(&output.stderr).to_string();
self.version_string = Self::extract_version(&version_output)?;
Ok(())
} else {
Err(Error::new(ErrorKind::GettingJavaVersionFailed(
self.path.clone(),
)))
}
}
/// Test if this runtime is available currently
///
/// It executes command `java -version` to see if it works
pub fn is_available(&self) -> bool {
self.is_same_os() && Self::from_java_exe(&self.path).is_ok()
}
/// Parse version string
///
/// # Return
///
/// `(version_string, version_major)`
///
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// assert_eq!(JavaRuntime::extract_version("1.8.0_333").unwrap(), "1.8.0_333");
/// assert_eq!(JavaRuntime::extract_version("17.0.4.1").unwrap(), "17.0.4.1");
/// assert_eq!(JavaRuntime::extract_version("\"17.0.4.1").unwrap(), "17.0.4.1");
/// assert_eq!(JavaRuntime::extract_version("java version \"17.0.4.1\"").unwrap(), "17.0.4.1");
/// ```
pub fn extract_version(version_string: &str) -> Result<String, Error> {
Ok(Regex::new(Self::VERSION_PATTERN)
.unwrap()
.captures(&format!("\"{}\"", &version_string))
.ok_or(Error::new(ErrorKind::NoJavaVersionStringFound))?
.get(1)
.ok_or(Error::new(ErrorKind::NoJavaVersionStringFound))?
.as_str()
.to_string())
}
/// Check if the given path looks like a java executable file
///
/// The file must exists.
///
/// The given path must be `**/bin/java.exe` in windows, or `**/bin/java` in unix
fn looks_like_java_executable_file(path: &Path) -> bool {
if !path.is_file() {
return false;
}
// to absolute
let path_absolute = match path.canonicalize() {
Ok(path) => path,
_ => return false,
};
// check file name
if let Some(file_name) = path_absolute.file_name() {
if file_name == Self::get_java_executable_name() {
// check parent name
if let Some(parent) = path_absolute.parent() {
if let Some(dir_name) = parent.file_name() {
if dir_name == "bin" {
return true;
}
}
}
}
}
false
}
/// # Examples
/// * `java.exe` (windows)
/// * `java` (linux)
fn get_java_executable_name() -> OsString {
let mut java_exe = OsString::from("java");
java_exe.push(env::consts::EXE_SUFFIX);
java_exe
}
}
impl Clone for JavaRuntime {
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// let r1 = JavaRuntime::new("linux", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// let r2 = r1.clone();
///
/// assert_eq!(r1, r2);
/// ```
fn clone(&self) -> Self {
Self {
os: self.os.clone(),
path: self.path.clone(),
version_string: self.version_string.clone(),
}
}
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// let mut r1 = JavaRuntime::new("windows", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// let r2 = JavaRuntime::new("windows", r"D:\jdk\bin\java.exe".as_ref(), "21.0.3").unwrap();
///
/// r1.clone_from(&r2);
/// assert_eq!(r1, r2);
/// ```
fn clone_from(&mut self, source: &Self) {
self.os = source.os.clone();
self.path = source.path.clone();
self.version_string = source.version_string.clone();
}
}
impl PartialEq for JavaRuntime {
/// # Examples
///
/// ```rust
/// use java_runtimes::JavaRuntime;
///
/// let r1 = JavaRuntime::new("linux", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// let r2 = JavaRuntime::new("linux", "/jdk/bin/java".as_ref(), "21.0.3").unwrap();
/// let r3 = JavaRuntime::new("windows", r"D:\jdk\bin\java.exe".as_ref(), "21.0.3").unwrap();
/// let r4 = JavaRuntime::new("windows", r"D:\jdk-17\bin\java.exe".as_ref(), "21.0.3").unwrap();
///
/// assert_eq!(r1, r2);
/// assert_ne!(r1, r3);
/// assert_ne!(r2, r3);
/// assert_ne!(r2, r4);
/// assert_ne!(r3, r4);
/// ```
fn eq(&self, other: &Self) -> bool {
self.os == other.os && self.path == other.path
}
fn ne(&self, other: &Self) -> bool {
!self.eq(other)
}
}