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::{BufWriter, Write};
6use std::path::Path;
7use std::process::ExitCode;
8use std::time::Duration;
9
10use either::Either;
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<Either<anstream::Stdout, BufWriter<anstream::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(|| {
116            let stdout = anstream::stdout();
117            if stdout.is_terminal() {
118                Either::Left(stdout)
119            } else {
120                Either::Right(BufWriter::new(stdout))
121            }
122        });
123        Self {
124            stdout,
125            output_file,
126            buffer: Vec::new(),
127        }
128    }
129
130    /// Flush standard output and commit the buffer to the output file.
131    pub async fn commit(mut self) -> std::io::Result<()> {
132        self.flush()?;
133
134        if let Some(output_file) = self.output_file {
135            let stream = anstream::adapter::strip_bytes(&self.buffer).into_vec();
136
137            // Devices and pipes must be opened directly: an atomic rename would replace them
138            // with a regular file. Follow symlinks when checking the destination's file type.
139            let metadata = fs_err::symlink_metadata(output_file);
140            let is_symlink = metadata.as_ref().is_ok_and(Metadata::is_symlink);
141            let metadata = if is_symlink {
142                fs_err::metadata(output_file)
143            } else {
144                metadata
145            };
146            match metadata {
147                Ok(metadata) if !metadata.is_file() => {
148                    return fs_err::tokio::write(output_file, &stream).await;
149                }
150                Ok(_) => {}
151                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
152                Err(err) => return Err(err),
153            }
154
155            if let Some(parent_dir) = output_file.parent() {
156                fs_err::create_dir_all(parent_dir)?;
157            }
158
159            // If the output file is an existing symlink, write to the destination instead.
160            let output_file = if is_symlink {
161                Cow::Owned(output_file.with_file_name(fs_err::read_link(output_file)?))
162            } else {
163                Cow::Borrowed(output_file)
164            };
165            uv_fs::write_atomic(output_file, &stream).await?;
166        }
167        Ok(())
168    }
169}
170
171impl Write for OutputWriter<'_> {
172    /// Write to both standard output and the output buffer, if present.
173    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
174        // Write to the buffer.
175        if self.output_file.is_some() {
176            self.buffer.write_all(buf)?;
177        }
178
179        // Write to standard output.
180        if let Some(stdout) = &mut self.stdout {
181            stdout.write_all(buf)?;
182        }
183
184        Ok(buf.len())
185    }
186
187    fn flush(&mut self) -> std::io::Result<()> {
188        if let Some(stdout) = &mut self.stdout {
189            stdout.flush()?;
190        }
191        Ok(())
192    }
193}
194
195/// Given a list of names, return a conjunction of the names (e.g., "Alice, Bob, and Charlie").
196pub fn conjunction(names: Vec<String>) -> String {
197    let mut names = names.into_iter();
198    let first = names.next();
199    let last = names.next_back();
200    match (first, last) {
201        (Some(first), Some(last)) => {
202            let mut result = first;
203            let mut comma = false;
204            for name in names {
205                result.push_str(", ");
206                result.push_str(&name);
207                comma = true;
208            }
209            if comma {
210                result.push_str(", and ");
211            } else {
212                result.push_str(" and ");
213            }
214            result.push_str(&last);
215            result
216        }
217        (Some(first), None) => first,
218        _ => String::new(),
219    }
220}