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;
45mod 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;
57pub mod lints;
58mod lockserver;
59pub mod log_message;
60pub mod logger;
61pub mod machine_message;
62pub mod network;
63mod once;
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    // ALLOWED: `RUSTUP_HOME` should only be read from process env, otherwise
79    // other tools may point to executables from incompatible distributions.
80    #[allow(clippy::disallowed_methods)]
81    std::env::var_os("RUSTUP_HOME").is_some()
82}
83
84pub fn elapsed(duration: Duration) -> String {
85    let secs = duration.as_secs();
86
87    if secs >= 60 {
88        format!("{}m {:02}s", secs / 60, secs % 60)
89    } else {
90        format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
91    }
92}
93
94/// Formats a number of bytes into a human readable SI-prefixed size.
95pub struct HumanBytes(pub u64);
96
97impl std::fmt::Display for HumanBytes {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
100        let bytes = self.0 as f32;
101        let i = ((bytes.log2() / 10.0) as usize).min(UNITS.len() - 1);
102        let unit = UNITS[i];
103        let size = bytes / 1024_f32.powi(i as i32);
104
105        // Don't show a fractional number of bytes.
106        if i == 0 {
107            return write!(f, "{size}{unit}");
108        }
109
110        let Some(precision) = f.precision() else {
111            return write!(f, "{size}{unit}");
112        };
113        write!(f, "{size:.precision$}{unit}",)
114    }
115}
116
117pub fn indented_lines(text: &str) -> String {
118    text.lines()
119        .map(|line| {
120            if line.is_empty() {
121                String::from("\n")
122            } else {
123                format!("  {}\n", line)
124            }
125        })
126        .collect()
127}
128
129pub fn truncate_with_ellipsis(s: &str, max_width: usize) -> String {
130    // We should truncate at grapheme-boundary and compute character-widths,
131    // yet the dependencies on unicode-segmentation and unicode-width are
132    // not worth it.
133    let mut chars = s.chars();
134    let mut prefix = (&mut chars).take(max_width - 1).collect::<String>();
135    if chars.next().is_some() {
136        prefix.push('…');
137    }
138    prefix
139}
140
141#[cfg(not(windows))]
142#[inline]
143pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
144    std::fs::canonicalize(&path)
145}
146
147#[cfg(windows)]
148#[inline]
149pub fn try_canonicalize<P: AsRef<Path>>(path: P) -> std::io::Result<PathBuf> {
150    use std::io::Error;
151    use std::io::ErrorKind;
152
153    // On Windows `canonicalize` may fail, so we fall back to getting an absolute path.
154    std::fs::canonicalize(&path).or_else(|_| {
155        // Return an error if a file does not exist for better compatibility with `canonicalize`
156        if !path.as_ref().try_exists()? {
157            return Err(Error::new(ErrorKind::NotFound, "the path was not found"));
158        }
159        std::path::absolute(&path)
160    })
161}
162
163/// Get the current [`umask`] value.
164///
165/// [`umask`]: https://man7.org/linux/man-pages/man2/umask.2.html
166#[cfg(unix)]
167pub fn get_umask() -> u32 {
168    use std::sync::OnceLock;
169    static UMASK: OnceLock<libc::mode_t> = OnceLock::new();
170    // SAFETY: Syscalls are unsafe. Calling `umask` twice is even unsafer for
171    // multithreading program, since it doesn't provide a way to retrieve the
172    // value without modifications. We use a static `OnceLock` here to ensure
173    // it only gets call once during the entire program lifetime.
174    *UMASK.get_or_init(|| unsafe {
175        let umask = libc::umask(0o022);
176        libc::umask(umask);
177        umask
178    }) as u32 // it is u16 on macos
179}
180
181#[cfg(test)]
182mod test {
183    use super::*;
184
185    #[track_caller]
186    fn t(bytes: u64, expected: &str) {
187        assert_eq!(&HumanBytes(bytes).to_string(), expected);
188    }
189
190    #[test]
191    fn test_human_readable_bytes() {
192        t(0, "0B");
193        t(8, "8B");
194        t(1000, "1000B");
195        t(1024, "1KiB");
196        t(1024 * 420 + 512, "420.5KiB");
197        t(1024 * 1024, "1MiB");
198        t(1024 * 1024 + 1024 * 256, "1.25MiB");
199        t(1024 * 1024 * 1024, "1GiB");
200        t((1024. * 1024. * 1024. * 1.2345) as u64, "1.2345GiB");
201        t(1024 * 1024 * 1024 * 1024, "1TiB");
202        t(1024 * 1024 * 1024 * 1024 * 1024, "1PiB");
203        t(1024 * 1024 * 1024 * 1024 * 1024 * 1024, "1EiB");
204        t(u64::MAX, "16EiB");
205
206        assert_eq!(
207            &format!("{:.3}", HumanBytes((1024. * 1.23456) as u64)),
208            "1.234KiB"
209        );
210    }
211}