mozrunner/
path.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! Provides utilities for searching the system path.
6
7use std::env;
8use std::path::{Path, PathBuf};
9
10#[cfg(target_os = "macos")]
11pub fn is_app_bundle(path: &Path) -> bool {
12    if path.is_dir() {
13        let mut info_plist = path.to_path_buf();
14        info_plist.push("Contents");
15        info_plist.push("Info.plist");
16
17        return info_plist.exists();
18    }
19
20    false
21}
22
23#[cfg(unix)]
24fn is_executable(path: &Path) -> bool {
25    use std::fs;
26    use std::os::unix::fs::PermissionsExt;
27
28    // Permissions are a set of four 4-bit bitflags, represented by a single octal
29    // digit.  The lowest bit of each of the last three values represents the
30    // executable permission for all, group and user, repsectively.  We assume the
31    // file is executable if any of these are set.
32    match fs::metadata(path).ok() {
33        Some(meta) => meta.permissions().mode() & 0o111 != 0,
34        None => false,
35    }
36}
37
38#[cfg(not(unix))]
39fn is_executable(_: &Path) -> bool {
40    true
41}
42
43/// Determines if the path is an executable binary.  That is, if it exists, is
44/// a file, and is executable where applicable.
45pub fn is_binary(path: &Path) -> bool {
46    path.exists() && path.is_file() && is_executable(path)
47}
48
49/// Searches the system path (`PATH`) for an executable binary and returns the
50/// first match, or `None` if not found.
51pub fn find_binary(binary_name: &str) -> Option<PathBuf> {
52    env::var_os("PATH").and_then(|path_env| {
53        for mut path in env::split_paths(&path_env) {
54            path.push(binary_name);
55            if is_binary(&path) {
56                return Some(path);
57            }
58        }
59        None
60    })
61}