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