| 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 |
|
| 7 |
use std::env; |
| 8 |
use std::path::{Path, PathBuf}; |
| 9 |
|
| 10 |
#[cfg(target_os = "macos")] |
| 11 |
pub 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)] |
| 24 |
fn 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))] |
| 39 |
fn 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. |
| 45 |
pub 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. |
| 51 |
pub 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 |
} |