uv_command_support/
lib.rs1use 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#[derive(Copy, Clone)]
21pub enum ExitStatus {
22 Success,
24
25 Failure,
27
28 Error,
30
31 External(u8),
33}
34
35#[derive(Debug, thiserror::Error)]
37pub enum UvError {
38 #[error(transparent)]
40 User(anyhow::Error),
41
42 #[error(transparent)]
44 Argument(anyhow::Error),
45
46 #[error(transparent)]
48 Unexpected(anyhow::Error),
49}
50
51impl UvError {
52 pub fn user(error: impl Into<anyhow::Error>) -> Self {
54 Self::User(error.into())
55 }
56
57 pub fn argument(error: anyhow::Error) -> Self {
59 Self::Argument(error)
60 }
61
62 pub fn unexpected(error: anyhow::Error) -> Self {
64 Self::Unexpected(error)
65 }
66
67 #[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
89pub 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
105pub 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 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 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 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 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 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
174 if self.output_file.is_some() {
176 self.buffer.write_all(buf)?;
177 }
178
179 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
195pub 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}