Skip to main content

hermit_resources/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Discovery of resources shipped beside the Hermit executable.
10
11use std::env;
12use std::ffi::OsStr;
13use std::io;
14use std::path::Path;
15use std::path::PathBuf;
16
17/// Environment variable selecting a Hermit installation directory.
18// TODO-HUMAN-REVIEW(PR-1002): Review the unified installation-directory contract.
19pub const INSTALL_DIR_ENV: &str = "HERMIT_INSTALL_DIR";
20
21fn invoked_executable(argv0: Option<&OsStr>, current_dir: &Path) -> Option<PathBuf> {
22    let argv0 = Path::new(argv0?);
23    if !argv0.is_absolute() && argv0.components().count() <= 1 {
24        return None;
25    }
26    Some(if argv0.is_absolute() {
27        argv0.to_path_buf()
28    } else {
29        current_dir.join(argv0)
30    })
31}
32
33fn has_resources(directory: &Path) -> bool {
34    directory.join("rsrcs").is_dir()
35}
36
37fn discover_install_dir_from(
38    explicit: Option<&OsStr>,
39    argv0: Option<&OsStr>,
40    executable: &Path,
41    current_dir: &Path,
42) -> io::Result<Option<PathBuf>> {
43    if let Some(explicit) = explicit {
44        if explicit.is_empty() {
45            return Err(io::Error::new(
46                io::ErrorKind::InvalidInput,
47                format!("{INSTALL_DIR_ENV} is empty"),
48            ));
49        }
50        return Ok(Some(PathBuf::from(explicit)));
51    }
52
53    let invoked = invoked_executable(argv0, current_dir);
54    let invoked_directory = invoked.as_deref().and_then(Path::parent);
55    let executable_directory = executable.parent();
56    let built_in_place = executable_directory
57        .and_then(Path::parent)
58        .map(|target| target.join("install_pkg"));
59
60    Ok(invoked_directory
61        .filter(|directory| has_resources(directory))
62        .map(Path::to_path_buf)
63        .or_else(|| {
64            executable_directory
65                .filter(|directory| has_resources(directory))
66                .map(Path::to_path_buf)
67        })
68        .or_else(|| built_in_place.filter(|directory| has_resources(directory))))
69}
70
71/// Returns the selected installation directory, if a packaged installation is available.
72// TODO-HUMAN-REVIEW(PR-1002): Review executable-relative resource discovery.
73pub fn install_dir() -> io::Result<Option<PathBuf>> {
74    let executable = env::current_exe()?;
75    let current_dir = env::current_dir()?;
76    discover_install_dir_from(
77        env::var_os(INSTALL_DIR_ENV).as_deref(),
78        env::args_os().next().as_deref(),
79        &executable,
80        &current_dir,
81    )
82}
83
84/// Returns a path below the selected installation's `rsrcs` directory.
85// TODO-HUMAN-REVIEW(PR-1002): Review the shared backend-resource layout.
86pub fn resource(relative: impl AsRef<Path>) -> io::Result<Option<PathBuf>> {
87    Ok(install_dir()?.map(|directory| directory.join("rsrcs").join(relative)))
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    fn test_directory(name: &str) -> PathBuf {
95        let directory =
96            env::temp_dir().join(format!("hermit-resources-{name}-{}", std::process::id()));
97        let _ = std::fs::remove_dir_all(&directory);
98        std::fs::create_dir_all(&directory).unwrap();
99        directory
100    }
101
102    #[test]
103    fn explicit_install_directory_has_priority() {
104        let root = test_directory("explicit");
105        let discovered = discover_install_dir_from(
106            Some(root.as_os_str()),
107            None,
108            Path::new("/tmp/target/release/hermit"),
109            Path::new("/tmp"),
110        )
111        .unwrap();
112        assert_eq!(discovered.as_deref(), Some(root.as_path()));
113        std::fs::remove_dir_all(root).unwrap();
114    }
115
116    #[test]
117    fn invoked_symlink_location_finds_colocated_resources() {
118        let root = test_directory("argv0");
119        std::fs::create_dir(root.join("rsrcs")).unwrap();
120        let invoked = root.join("hermit");
121        let discovered = discover_install_dir_from(
122            None,
123            Some(invoked.as_os_str()),
124            Path::new("/tmp/target/release/hermit"),
125            Path::new("/tmp"),
126        )
127        .unwrap();
128        assert_eq!(discovered.as_deref(), Some(root.as_path()));
129        std::fs::remove_dir_all(root).unwrap();
130    }
131
132    #[test]
133    fn release_binary_finds_target_install_package() {
134        let root = test_directory("build-tree");
135        let install = root.join("install_pkg");
136        std::fs::create_dir_all(install.join("rsrcs")).unwrap();
137        let executable = root.join("release/hermit");
138        let discovered = discover_install_dir_from(None, None, &executable, &root).unwrap();
139        assert_eq!(discovered.as_deref(), Some(install.as_path()));
140        std::fs::remove_dir_all(root).unwrap();
141    }
142
143    #[test]
144    fn empty_explicit_directory_is_rejected() {
145        let error = discover_install_dir_from(
146            Some(OsStr::new("")),
147            None,
148            Path::new("/tmp/hermit"),
149            Path::new("/tmp"),
150        )
151        .unwrap_err();
152        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
153    }
154}