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