use std::borrow::Cow;
use std::fs::Metadata;
use std::io::{BufWriter, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::Duration;
use either::Either;
pub mod child;
mod printer;
pub mod progress;
pub mod update_shell;
pub use printer::{Printer, Stderr, Stdout};
#[derive(Copy, Clone)]
pub enum ExitStatus {
Success,
Failure,
Error,
External(u8),
}
#[derive(Debug, thiserror::Error)]
pub enum UvError {
#[error(transparent)]
User(anyhow::Error),
#[error(transparent)]
Argument(anyhow::Error),
#[error(transparent)]
Unexpected(anyhow::Error),
}
impl UvError {
pub fn user(error: impl Into<anyhow::Error>) -> Self {
Self::User(error.into())
}
pub fn argument(error: anyhow::Error) -> Self {
Self::Argument(error)
}
pub fn unexpected(error: anyhow::Error) -> Self {
Self::Unexpected(error)
}
#[must_use]
pub fn map_user(self, context: impl FnOnce(anyhow::Error) -> anyhow::Error) -> Self {
match self {
Self::User(error) => Self::User(context(error)),
Self::Argument(error) => Self::Argument(error),
Self::Unexpected(error) => Self::Unexpected(error),
}
}
}
impl From<ExitStatus> for ExitCode {
fn from(status: ExitStatus) -> Self {
match status {
ExitStatus::Success => Self::from(0),
ExitStatus::Failure => Self::from(1),
ExitStatus::Error => Self::from(2),
ExitStatus::External(code) => Self::from(code),
}
}
}
pub fn elapsed(duration: Duration) -> String {
let secs = duration.as_secs();
let ms = duration.subsec_millis();
if secs >= 60 {
format!("{}m {:02}s", secs / 60, secs % 60)
} else if secs > 0 {
format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
} else if ms > 0 {
format!("{ms}ms")
} else {
format!("0.{:02}ms", duration.subsec_nanos() / 10_000)
}
}
pub struct OutputWriter<'a> {
stdout: Option<Either<anstream::Stdout, BufWriter<anstream::Stdout>>>,
output_file: Option<&'a Path>,
buffer: Vec<u8>,
}
impl<'a> OutputWriter<'a> {
pub fn new(include_stdout: bool, output_file: Option<&'a Path>) -> Self {
let stdout = include_stdout.then(|| {
let stdout = anstream::stdout();
if stdout.is_terminal() {
Either::Left(stdout)
} else {
Either::Right(BufWriter::new(stdout))
}
});
Self {
stdout,
output_file,
buffer: Vec::new(),
}
}
pub async fn commit(mut self) -> std::io::Result<()> {
self.flush()?;
if let Some(output_file) = self.output_file {
let stream = anstream::adapter::strip_bytes(&self.buffer).into_vec();
let metadata = fs_err::symlink_metadata(output_file);
let is_symlink = metadata.as_ref().is_ok_and(Metadata::is_symlink);
let metadata = if is_symlink {
fs_err::metadata(output_file)
} else {
metadata
};
match metadata {
Ok(metadata) if !metadata.is_file() => {
return fs_err::tokio::write(output_file, &stream).await;
}
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
}
if let Some(parent_dir) = output_file.parent() {
fs_err::create_dir_all(parent_dir)?;
}
let output_file = if is_symlink {
Cow::Owned(output_file.with_file_name(fs_err::read_link(output_file)?))
} else {
Cow::Borrowed(output_file)
};
uv_fs::write_atomic(output_file, &stream).await?;
}
Ok(())
}
}
impl Write for OutputWriter<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if self.output_file.is_some() {
self.buffer.write_all(buf)?;
}
if let Some(stdout) = &mut self.stdout {
stdout.write_all(buf)?;
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if let Some(stdout) = &mut self.stdout {
stdout.flush()?;
}
Ok(())
}
}
pub fn conjunction(names: Vec<String>) -> String {
let mut names = names.into_iter();
let first = names.next();
let last = names.next_back();
match (first, last) {
(Some(first), Some(last)) => {
let mut result = first;
let mut comma = false;
for name in names {
result.push_str(", ");
result.push_str(&name);
comma = true;
}
if comma {
result.push_str(", and ");
} else {
result.push_str(" and ");
}
result.push_str(&last);
result
}
(Some(first), None) => first,
_ => String::new(),
}
}