Skip to main content

uv_command_support/
lib.rs

1//! Output and process primitives shared by uv command implementations.
2
3use std::borrow::Cow;
4use std::io::stdout;
5use std::path::Path;
6use std::process::ExitCode;
7use std::time::Duration;
8
9use anstream::AutoStream;
10
11pub mod child;
12mod printer;
13pub mod progress;
14pub mod update_shell;
15
16pub use printer::{Printer, Stderr, Stdout};
17
18/// The process status for a command that completed without a final error to render.
19#[derive(Copy, Clone)]
20pub enum ExitStatus {
21    /// The command succeeded.
22    Success,
23
24    /// The command reported a failure caused by user input.
25    Failure,
26
27    /// The command reported an unexpected failure.
28    Error,
29
30    /// The command's exit status is propagated from an external command.
31    External(u8),
32}
33
34/// A command error propagated to the entrypoint for exit-status selection.
35#[derive(Debug, thiserror::Error)]
36pub enum UvError {
37    /// An error caused by invalid or unsatisfiable user input.
38    #[error(transparent)]
39    User(anyhow::Error),
40
41    /// An error caused by invalid command-line arguments.
42    #[error(transparent)]
43    Argument(anyhow::Error),
44
45    /// An unexpected internal or environmental error.
46    #[error(transparent)]
47    Unexpected(anyhow::Error),
48}
49
50impl UvError {
51    /// Create a user-facing error.
52    pub fn user(error: impl Into<anyhow::Error>) -> Self {
53        Self::User(error.into())
54    }
55
56    /// Create an argument error.
57    pub fn argument(error: anyhow::Error) -> Self {
58        Self::Argument(error)
59    }
60
61    /// Create an unexpected error.
62    pub fn unexpected(error: anyhow::Error) -> Self {
63        Self::Unexpected(error)
64    }
65
66    /// Add command-specific context to a user error without changing unexpected errors.
67    #[must_use]
68    pub fn map_user(self, context: impl FnOnce(anyhow::Error) -> anyhow::Error) -> Self {
69        match self {
70            Self::User(error) => Self::User(context(error)),
71            Self::Argument(error) => Self::Argument(error),
72            Self::Unexpected(error) => Self::Unexpected(error),
73        }
74    }
75}
76
77impl From<ExitStatus> for ExitCode {
78    fn from(status: ExitStatus) -> Self {
79        match status {
80            ExitStatus::Success => Self::from(0),
81            ExitStatus::Failure => Self::from(1),
82            ExitStatus::Error => Self::from(2),
83            ExitStatus::External(code) => Self::from(code),
84        }
85    }
86}
87
88/// Format a duration as a human-readable string, Cargo-style.
89pub fn elapsed(duration: Duration) -> String {
90    let secs = duration.as_secs();
91    let ms = duration.subsec_millis();
92
93    if secs >= 60 {
94        format!("{}m {:02}s", secs / 60, secs % 60)
95    } else if secs > 0 {
96        format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
97    } else if ms > 0 {
98        format!("{ms}ms")
99    } else {
100        format!("0.{:02}ms", duration.subsec_nanos() / 10_000)
101    }
102}
103
104/// A multicasting writer that writes to both the standard output and an output file, if present.
105pub struct OutputWriter<'a> {
106    stdout: Option<AutoStream<std::io::Stdout>>,
107    output_file: Option<&'a Path>,
108    buffer: Vec<u8>,
109}
110
111impl<'a> OutputWriter<'a> {
112    /// Create a new output writer.
113    pub fn new(include_stdout: bool, output_file: Option<&'a Path>) -> Self {
114        let stdout = include_stdout.then(|| AutoStream::<std::io::Stdout>::auto(stdout()));
115        Self {
116            stdout,
117            output_file,
118            buffer: Vec::new(),
119        }
120    }
121
122    /// Commit the buffer to the output file.
123    pub async fn commit(self) -> std::io::Result<()> {
124        if let Some(output_file) = self.output_file {
125            if let Some(parent_dir) = output_file.parent() {
126                fs_err::create_dir_all(parent_dir)?;
127            }
128
129            // If the output file is an existing symlink, write to the destination instead.
130            let output_file = fs_err::read_link(output_file)
131                .map(Cow::Owned)
132                .unwrap_or(Cow::Borrowed(output_file));
133            let stream = anstream::adapter::strip_bytes(&self.buffer).into_vec();
134            uv_fs::write_atomic(output_file, &stream).await?;
135        }
136        Ok(())
137    }
138}
139
140impl std::io::Write for OutputWriter<'_> {
141    /// Write to both standard output and the output buffer, if present.
142    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
143        // Write to the buffer.
144        if self.output_file.is_some() {
145            self.buffer.write_all(buf)?;
146        }
147
148        // Write to standard output.
149        if let Some(stdout) = &mut self.stdout {
150            stdout.write_all(buf)?;
151        }
152
153        Ok(buf.len())
154    }
155
156    fn flush(&mut self) -> std::io::Result<()> {
157        if let Some(stdout) = &mut self.stdout {
158            stdout.flush()?;
159        }
160        Ok(())
161    }
162}
163
164/// Given a list of names, return a conjunction of the names (e.g., "Alice, Bob, and Charlie").
165pub fn conjunction(names: Vec<String>) -> String {
166    let mut names = names.into_iter();
167    let first = names.next();
168    let last = names.next_back();
169    match (first, last) {
170        (Some(first), Some(last)) => {
171            let mut result = first;
172            let mut comma = false;
173            for name in names {
174                result.push_str(", ");
175                result.push_str(&name);
176                comma = true;
177            }
178            if comma {
179                result.push_str(", and ");
180            } else {
181                result.push_str(" and ");
182            }
183            result.push_str(&last);
184            result
185        }
186        (Some(first), None) => first,
187        _ => String::new(),
188    }
189}