Skip to main content

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