Skip to main content

docsrs_cli/
platform.rs

1//! Cross-platform filesystem and console helpers.
2//!
3//! Keeps `#[cfg]` conditionals out of business modules. Product code uses
4//! [`PathBuf`] / [`Path`] only — no hardcoded `/` or `\\` separators.
5//!
6//! # Out of scope (agent-first network CLI)
7//!
8//! - Browser/Chrome path discovery (no external browser binary)
9//! - Windows console UTF-8 code-page bootstrap via raw Win32 (would require
10//!   `unsafe` or a windows-only crate; product has zero `unsafe` in `src/`)
11//! - WASM / WASI targets (HTTP client + tokio signal surface is native OS)
12//! - Seccomp / landlock / Job Objects (one-shot short-lived process)
13
14use std::path::Path;
15
16/// Restrict a regular file to owner read/write on Unix (`0o600`).
17///
18/// No-op on non-Unix (ACLs inherit from the parent directory).
19/// Best-effort: I/O errors are ignored so a permission failure never
20/// aborts a successful cache write path.
21pub(crate) fn restrict_private_file(path: &Path) {
22    #[cfg(unix)]
23    {
24        use std::fs;
25        use std::os::unix::fs::PermissionsExt;
26        if let Ok(meta) = fs::metadata(path) {
27            let mut perms = meta.permissions();
28            perms.set_mode(0o600);
29            let _ = fs::set_permissions(path, perms);
30        }
31    }
32    #[cfg(not(unix))]
33    {
34        let _ = path;
35    }
36}
37
38/// Restrict a directory to owner rwx on Unix (`0o700`).
39///
40/// No-op on non-Unix. Best-effort (see [`restrict_private_file`]).
41pub(crate) fn restrict_private_dir(path: &Path) {
42    #[cfg(unix)]
43    {
44        use std::fs;
45        use std::os::unix::fs::PermissionsExt;
46        if let Ok(meta) = fs::metadata(path) {
47            let mut perms = meta.permissions();
48            perms.set_mode(0o700);
49            let _ = fs::set_permissions(path, perms);
50        }
51    }
52    #[cfg(not(unix))]
53    {
54        let _ = path;
55    }
56}
57
58/// Whether ANSI colors should be used for stderr diagnostics.
59///
60/// Precedence (first match wins disable):
61/// 1. `--no-color` CLI flag
62/// 2. `NO_COLOR` present in the environment (any value, including empty)
63/// 3. `TERM=dumb`
64///
65/// Then `CLICOLOR_FORCE` with a non-empty value other than `0` forces colors on.
66/// Otherwise colors default to enabled for the tracing fmt layer (historical
67/// agent CLI behavior: stderr may be captured without a TTY).
68pub(crate) fn ansi_colors_enabled(no_color: bool) -> bool {
69    if no_color {
70        return false;
71    }
72    if std::env::var_os("NO_COLOR").is_some() {
73        return false;
74    }
75    if std::env::var_os("TERM").is_some_and(|t| t == "dumb") {
76        return false;
77    }
78    if let Some(v) = std::env::var_os("CLICOLOR_FORCE") {
79        if !v.is_empty() && v != "0" {
80            return true;
81        }
82    }
83    true
84}
85
86/// Compact platform identity for doctor / version diagnostics.
87pub(crate) fn platform_detail() -> String {
88    format!(
89        "{}-{} ({})",
90        std::env::consts::ARCH,
91        std::env::consts::OS,
92        std::env::consts::FAMILY
93    )
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use std::fs;
100    use std::path::PathBuf;
101
102    #[test]
103    fn platform_detail_is_non_empty() {
104        let d = platform_detail();
105        assert!(d.contains(std::env::consts::OS));
106        assert!(d.contains(std::env::consts::ARCH));
107    }
108
109    #[test]
110    fn restrict_private_file_is_noop_or_tightens_unix() {
111        let dir = tempfile::tempdir().unwrap();
112        let path = dir.path().join("secret.bin");
113        fs::write(&path, b"x").unwrap();
114        restrict_private_file(&path);
115        #[cfg(unix)]
116        {
117            use std::os::unix::fs::PermissionsExt;
118            let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
119            assert_eq!(mode, 0o600);
120        }
121        #[cfg(not(unix))]
122        {
123            let _ = path;
124        }
125    }
126
127    #[test]
128    fn restrict_private_dir_is_noop_or_tightens_unix() {
129        let dir = tempfile::tempdir().unwrap();
130        let nested: PathBuf = dir.path().join("nested");
131        fs::create_dir_all(&nested).unwrap();
132        restrict_private_dir(&nested);
133        #[cfg(unix)]
134        {
135            use std::os::unix::fs::PermissionsExt;
136            let mode = fs::metadata(&nested).unwrap().permissions().mode() & 0o777;
137            assert_eq!(mode, 0o700);
138        }
139    }
140
141    #[test]
142    fn ansi_disabled_when_no_color_flag() {
143        assert!(!ansi_colors_enabled(true));
144    }
145}