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