coffee_roast/
lib.rs

1// Copyright 2024 tison <wander4096@gmail.com>
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::PathBuf;
16
17#[allow(dead_code)]
18pub(crate) mod sys;
19
20pub mod error;
21pub mod java_vm;
22
23pub fn find_java_home() -> anyhow::Result<PathBuf> {
24    match std::env::var("JAVA_HOME") {
25        Ok(home) if !home.is_empty() => Ok(PathBuf::from(home)),
26        _ => {
27            let mut exec = which::which("java")?;
28            exec.pop();
29            exec.pop();
30            Ok(exec)
31        }
32    }
33}
34
35pub fn find_file_within_java_home(file: &str) -> anyhow::Result<PathBuf> {
36    let java_home = find_java_home()?;
37    walkdir::WalkDir::new(java_home)
38        .into_iter()
39        .filter_map(|e| e.ok())
40        .find(|e| e.file_name() == file)
41        .map(|e| e.into_path())
42        .ok_or_else(|| anyhow::anyhow!("{} not found in JAVA_HOME", file))
43}
44
45pub fn find_jvm_lib() -> anyhow::Result<PathBuf> {
46    let libname = libloading::library_filename("jvm");
47    find_file_within_java_home(&libname.to_string_lossy())
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_find_java_home_and_dyn_lib() {
56        let java_home = find_java_home().unwrap();
57        assert!(java_home.exists());
58        println!("JAVA_HOME: {}", java_home.to_string_lossy());
59
60        let jvm_lib = find_jvm_lib().unwrap();
61        assert!(jvm_lib.exists());
62        println!("JVM Library: {:?}", jvm_lib.to_string_lossy());
63    }
64}