cargo/util/
mod.rs

1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4pub use self::canonical_url::CanonicalUrl;
5pub use self::context::{ConfigValue, GlobalContext, homedir};
6pub(crate) use self::counter::MetricsCounter;
7pub use self::dependency_queue::DependencyQueue;
8pub use self::diagnostic_server::RustfixDiagnosticServer;
9pub use self::edit_distance::{closest, closest_msg, edit_distance};
10pub use self::errors::CliError;
11pub use self::errors::{CargoResult, CliResult, internal};
12pub use self::flock::{FileLock, Filesystem};
13pub use self::graph::Graph;
14pub use self::hasher::StableHasher;
15pub use self::hex::{hash_u64, short_hash, to_hex};
16pub use self::hostname::hostname;
17pub use self::into_url::IntoUrl;
18pub use self::into_url_with_base::IntoUrlWithBase;
19pub(crate) use self::io::LimitErrorReader;
20pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted};
21pub use self::logger::BuildLogger;
22pub use self::once::OnceExt;
23pub use self::progress::{Progress, ProgressStyle};
24pub use self::queue::Queue;
25pub use self::rustc::Rustc;
26pub use self::semver_ext::{OptVersionReq, VersionExt};
27pub use self::vcs::{FossilRepo, GitRepo, HgRepo, PijulRepo, existing_vcs_repo};
28pub use self::workspace::{
29    add_path_args, path_args, print_available_benches, print_available_binaries,
30    print_available_examples, print_available_packages, print_available_tests,
31};
32
33pub mod auth;
34pub mod cache_lock;
35mod canonical_url;
36pub mod command_prelude;
37pub mod context;
38mod counter;
39pub mod cpu;
40pub mod credential;
41mod dependency_queue;
42pub mod diagnostic_server;
43pub mod edit_distance;
44pub mod errors;
45pub mod flock;
46pub mod frontmatter;
47pub mod graph;
48mod hasher;
49pub mod hex;
50mod hostname;
51pub mod important_paths;
52pub mod interning;
53pub mod into_url;
54mod into_url_with_base;
55mod io;
56pub mod job;
57mod lockserver;
58pub mod log_message;
59pub mod logger;
60pub mod machine_message;
61pub mod network;
62mod once;
63pub mod open;
64mod progress;
65mod queue;
66pub mod restricted_names;
67pub mod rustc;
68mod semver_eval_ext;
69mod semver_ext;
70pub mod sqlite;
71pub mod style;
72pub mod toml;
73pub mod toml_mut;
74mod vcs;
75mod workspace;
76
77pub fn is_rustup() -> bool {
78    #[expect(clippy::disallowed_methods, reason = "consistency with rustup")]
79    std::env::var_os("RUSTUP_HOME").is_some()
80}
81
82pub fn elapsed(duration: Duration) -> String {
83    let secs = duration.as_secs();
84
85    if secs >= 60 {
86        format!("{}m {:02}s", secs / 60, secs % 60)
87    } else {
88        format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
89    }
90}
91
92/// Formats a number of bytes into a human readable SI-prefixed size.
93pub struct HumanBytes(pub u64);
94
95impl std::fmt::Display for HumanBytes {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
98        let bytes = self.0 as f32;
99        let i = ((bytes.log2() / 10.0) as usize).min(UNITS.len() - 1);
100        let unit = UNITS[i];
101        let size = bytes / 1024_f32.powi(i as i32);
102
103        // Don't show a fractional number of bytes.
104        if i == 0 {
105            return write!(f, "{size}{unit}");
106        }
107
108        let Some(precision) = f.precision() else {
109            return write!(f, "{size}{unit}");
110        };
111        write!(f, "{size:.precision$}{unit}",)
112    }
113}
114
115pub fn indented_lines(text: &str) -> String {
116    text.lines()
117        .map(|line| {
118            if line.is_empty() {
119                String::from("\n")
120            } else {
121                format!("  {}\n", line)
122            }
123        })
124        .collect()
125}
126
127pub fn truncate_with_ellipsis(s: &str, max_width: usize) -> String {
128    // We should truncate at grapheme-boundary and compute character-widths,
129    // yet the dependencies on unicode-segmentation and unicode-width are
130    // not worth it.
131    let mut chars = s.chars();
132    let mut prefix = (&mut chars).take(max_width - 1).collect::<String>();
133    if chars.next().is_some() {
134        prefix.push('…');
135    }
136    prefix
137}
138
139#[cfg(not(windows))]
140#[inline]
141pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
142    std::fs::canonicalize(&path)
143}
144
145#[cfg(windows)]
146#[inline]
147pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
148    use std::io::Error;
149    use std::io::ErrorKind;
150
151    // On Windows `canonicalize` may fail, so we fall back to getting an absolute path.
152    std::fs::canonicalize(&path).or_else(|_| {
153        // Return an error if a file does not exist for better compatibility with `canonicalize`
154        if !path.as_ref().try_exists()? {
155            return Err(Error::new(ErrorKind::NotFound, "the path was not found"));
156        }
157        std::path::absolute(&path)
158    })
159}
160
161/// Get the current [`umask`] value.
162///
163/// [`umask`]: https://man7.org/linux/man-pages/man2/umask.2.html
164#[cfg(unix)]
165pub fn get_umask() -> u32 {
166    use std::sync::OnceLock;
167    static UMASK: OnceLock<libc::mode_t> = OnceLock::new();
168    // SAFETY: Syscalls are unsafe. Calling `umask` twice is even unsafer for
169    // multithreading program, since it doesn't provide a way to retrieve the
170    // value without modifications. We use a static `OnceLock` here to ensure
171    // it only gets call once during the entire program lifetime.
172    *UMASK.get_or_init(|| unsafe {
173        let umask = libc::umask(0o022);
174        libc::umask(umask);
175        umask
176    }) as u32 // it is u16 on macos
177}
178
179#[cfg(test)]
180mod test {
181    use super::*;
182
183    #[track_caller]
184    fn t(bytes: u64, expected: &str) {
185        assert_eq!(&HumanBytes(bytes).to_string(), expected);
186    }
187
188    #[test]
189    fn test_human_readable_bytes() {
190        t(0, "0B");
191        t(8, "8B");
192        t(1000, "1000B");
193        t(1024, "1KiB");
194        t(1024 * 420 + 512, "420.5KiB");
195        t(1024 * 1024, "1MiB");
196        t(1024 * 1024 + 1024 * 256, "1.25MiB");
197        t(1024 * 1024 * 1024, "1GiB");
198        t((1024. * 1024. * 1024. * 1.2345) as u64, "1.2345GiB");
199        t(1024 * 1024 * 1024 * 1024, "1TiB");
200        t(1024 * 1024 * 1024 * 1024 * 1024, "1PiB");
201        t(1024 * 1024 * 1024 * 1024 * 1024 * 1024, "1EiB");
202        t(u64::MAX, "16EiB");
203
204        assert_eq!(
205            &format!("{:.3}", HumanBytes((1024. * 1.23456) as u64)),
206            "1.234KiB"
207        );
208    }
209}