uv_command_support/
lib.rs1use 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#[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<AutoStream<std::io::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(|| AutoStream::<std::io::Stdout>::auto(stdout()));
116 Self {
117 stdout,
118 output_file,
119 buffer: Vec::new(),
120 }
121 }
122
123 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 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 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 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
165 if self.output_file.is_some() {
167 self.buffer.write_all(buf)?;
168 }
169
170 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
186pub 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}