Use color_eyre (#173)

This commit is contained in:
Rebecca Turner
2022-11-11 09:39:29 -05:00
committed by GitHub
parent 1b49b70833
commit fd369d1872
34 changed files with 216 additions and 72 deletions

View File

@@ -4,8 +4,9 @@ use std::fmt::Display;
use std::process::Child;
use std::process::{Command, ExitStatus, Output};
use anyhow::anyhow;
use anyhow::Context;
use color_eyre::eyre;
use color_eyre::eyre::eyre;
use color_eyre::eyre::Context;
use crate::error::TopgradeError;
@@ -18,17 +19,17 @@ pub struct Utf8Output {
}
impl TryFrom<Output> for Utf8Output {
type Error = anyhow::Error;
type Error = eyre::Error;
fn try_from(Output { status, stdout, stderr }: Output) -> Result<Self, Self::Error> {
let stdout = String::from_utf8(stdout).map_err(|err| {
anyhow!(
eyre!(
"Stdout contained invalid UTF-8: {}",
String::from_utf8_lossy(err.as_bytes())
)
})?;
let stderr = String::from_utf8(stderr).map_err(|err| {
anyhow!(
eyre!(
"Stderr contained invalid UTF-8: {}",
String::from_utf8_lossy(err.as_bytes())
)
@@ -39,17 +40,17 @@ impl TryFrom<Output> for Utf8Output {
}
impl TryFrom<&Output> for Utf8Output {
type Error = anyhow::Error;
type Error = eyre::Error;
fn try_from(Output { status, stdout, stderr }: &Output) -> Result<Self, Self::Error> {
let stdout = String::from_utf8(stdout.to_vec()).map_err(|err| {
anyhow!(
eyre!(
"Stdout contained invalid UTF-8: {}",
String::from_utf8_lossy(err.as_bytes())
)
})?;
let stderr = String::from_utf8(stderr.to_vec()).map_err(|err| {
anyhow!(
eyre!(
"Stderr contained invalid UTF-8: {}",
String::from_utf8_lossy(err.as_bytes())
)
@@ -85,7 +86,7 @@ pub trait CommandExt {
///
/// Returns an `Err` if the command failed to execute or returned a non-zero exit code.
#[track_caller]
fn output_checked(&mut self) -> anyhow::Result<Output> {
fn output_checked(&mut self) -> eyre::Result<Output> {
self.output_checked_with(|output: &Output| if output.status.success() { Ok(()) } else { Err(()) })
}
@@ -94,7 +95,7 @@ pub trait CommandExt {
/// Returns an `Err` if the command failed to execute, returned a non-zero exit code, or if the
/// output contains invalid UTF-8.
#[track_caller]
fn output_checked_utf8(&mut self) -> anyhow::Result<Utf8Output> {
fn output_checked_utf8(&mut self) -> eyre::Result<Utf8Output> {
let output = self.output_checked()?;
output.try_into()
}
@@ -106,7 +107,7 @@ pub trait CommandExt {
/// (This lets the caller substitute their own notion of "success" instead of assuming
/// non-zero exit codes indicate success.)
#[track_caller]
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> anyhow::Result<Output>;
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> eyre::Result<Output>;
/// Like [`output_checked_with`], but also decodes Stdout and Stderr as UTF-8.
///
@@ -116,7 +117,7 @@ pub trait CommandExt {
fn output_checked_with_utf8(
&mut self,
succeeded: impl Fn(&Utf8Output) -> Result<(), ()>,
) -> anyhow::Result<Utf8Output> {
) -> eyre::Result<Utf8Output> {
// This decodes the Stdout and Stderr as UTF-8 twice...
let output =
self.output_checked_with(|output| output.try_into().map_err(|_| ()).and_then(|o| succeeded(&o)))?;
@@ -129,7 +130,7 @@ pub trait CommandExt {
/// Returns `Ok` if the command executes successfully, returns `Err` if the command fails to
/// execute or returns a non-zero exit code.
#[track_caller]
fn status_checked(&mut self) -> anyhow::Result<()> {
fn status_checked(&mut self) -> eyre::Result<()> {
self.status_checked_with(|status| if status.success() { Ok(()) } else { Err(()) })
}
@@ -141,18 +142,18 @@ pub trait CommandExt {
/// (This lets the caller substitute their own notion of "success" instead of assuming
/// non-zero exit codes indicate success.)
#[track_caller]
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> anyhow::Result<()>;
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> eyre::Result<()>;
/// Like [`Command::spawn`], but gives a nice error message if the command fails to
/// execute.
#[track_caller]
fn spawn_checked(&mut self) -> anyhow::Result<Self::Child>;
fn spawn_checked(&mut self) -> eyre::Result<Self::Child>;
}
impl CommandExt for Command {
type Child = Child;
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> anyhow::Result<Output> {
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> eyre::Result<Output> {
let command = log(self);
// This is where we implement `output_checked`, which is what we prefer to use instead of
@@ -187,7 +188,7 @@ impl CommandExt for Command {
}
}
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> anyhow::Result<()> {
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> eyre::Result<()> {
let command = log(self);
let message = format!("Failed to execute `{command}`");
@@ -207,7 +208,7 @@ impl CommandExt for Command {
}
}
fn spawn_checked(&mut self) -> anyhow::Result<Self::Child> {
fn spawn_checked(&mut self) -> eyre::Result<Self::Child> {
let command = log(self);
let message = format!("Failed to execute `{command}`");

View File

@@ -5,9 +5,10 @@ use std::path::PathBuf;
use std::process::Command;
use std::{env, fs};
use anyhow::Context;
use anyhow::Result;
use clap::{ArgEnum, Parser};
use color_eyre::eyre;
use color_eyre::eyre::Context;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use log::debug;
use regex::Regex;
@@ -635,7 +636,7 @@ impl Config {
}
/// Extra Tmux arguments
pub fn tmux_arguments(&self) -> anyhow::Result<Vec<String>> {
pub fn tmux_arguments(&self) -> eyre::Result<Vec<String>> {
let args = &self.config_file.tmux_arguments.as_deref().unwrap_or_default();
shell_words::split(args)
// The only time the parse failed is in case of a missing close quote.

View File

@@ -3,7 +3,7 @@ use crate::executor::RunType;
use crate::git::Git;
use crate::utils::require_option;
use crate::{config::Config, executor::Executor};
use anyhow::Result;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use std::path::{Path, PathBuf};

View File

@@ -3,7 +3,8 @@ use std::ffi::{OsStr, OsString};
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Output};
use anyhow::Result;
use color_eyre::eyre;
use color_eyre::eyre::Result;
use log::debug;
use crate::command::CommandExt;
@@ -240,7 +241,7 @@ impl CommandExt for Executor {
// TODO: It might be nice to make `output_checked_with` return something that has a
// variant for wet/dry runs.
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> anyhow::Result<Output> {
fn output_checked_with(&mut self, succeeded: impl Fn(&Output) -> Result<(), ()>) -> eyre::Result<Output> {
match self {
Executor::Wet(c) => c.output_checked_with(succeeded),
Executor::Dry(c) => {
@@ -250,7 +251,7 @@ impl CommandExt for Executor {
}
}
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> anyhow::Result<()> {
fn status_checked_with(&mut self, succeeded: impl Fn(ExitStatus) -> Result<(), ()>) -> eyre::Result<()> {
match self {
Executor::Wet(c) => c.status_checked_with(succeeded),
Executor::Dry(c) => {
@@ -260,7 +261,7 @@ impl CommandExt for Executor {
}
}
fn spawn_checked(&mut self) -> anyhow::Result<Self::Child> {
fn spawn_checked(&mut self) -> eyre::Result<Self::Child> {
self.spawn()
}
}

View File

@@ -4,9 +4,9 @@ use std::env;
use std::io;
use std::process::exit;
use anyhow::Context;
use anyhow::{anyhow, Result};
use clap::{crate_version, Parser};
use color_eyre::eyre::Context;
use color_eyre::eyre::{eyre, Result};
use console::Key;
use log::debug;
use log::LevelFilter;
@@ -36,9 +36,10 @@ mod terminal;
mod utils;
fn run() -> Result<()> {
color_eyre::install()?;
ctrlc::set_handler();
let base_dirs = directories::BaseDirs::new().ok_or_else(|| anyhow!("No base directories"))?;
let base_dirs = directories::BaseDirs::new().ok_or_else(|| eyre!("No base directories"))?;
let opt = CommandLineArgs::parse();
@@ -526,7 +527,7 @@ fn main() {
.is_some());
if !skip_print {
// The `Debug` implementation of `anyhow::Result` prints a multi-line
// The `Debug` implementation of `eyre::Result` prints a multi-line
// error message that includes all the 'causes' added with
// `.with_context(...)` calls.
println!("Error: {:?}", error);

View File

@@ -3,7 +3,7 @@ use crate::error::{DryRun, SkipStep};
use crate::execution_context::ExecutionContext;
use crate::report::{Report, StepResult};
use crate::{config::Step, terminal::should_retry};
use anyhow::Result;
use color_eyre::eyre::Result;
use log::debug;
use std::borrow::Cow;
use std::fmt::Debug;

View File

@@ -1,6 +1,6 @@
#![cfg(windows)]
use anyhow::Result;
use color_eyre::eyre::Result;
use log::{debug, error};
use std::{env::current_exe, fs, path::PathBuf};

View File

@@ -3,7 +3,7 @@ use std::env;
use std::os::unix::process::CommandExt as _;
use std::process::Command;
use anyhow::{bail, Result};
use color_eyre::eyre::{bail, Result};
use self_update_crate::backends::github::Update;
use self_update_crate::update::UpdateStatus;

View File

@@ -1,4 +1,6 @@
use anyhow::{Context, Result};
use color_eyre::eyre::eyre;
use color_eyre::eyre::Context;
use color_eyre::eyre::Result;
use crate::command::CommandExt;
use crate::error::{self, TopgradeError};
@@ -108,6 +110,6 @@ pub fn run_containers(ctx: &ExecutionContext) -> Result<()> {
if success {
Ok(())
} else {
Err(anyhow::anyhow!(error::StepFailed))
Err(eyre!(error::StepFailed))
}
}

View File

@@ -2,7 +2,7 @@
use std::env;
use std::path::{Path, PathBuf};
use anyhow::Result;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use crate::command::CommandExt;

View File

@@ -5,7 +5,9 @@ use std::process::Command;
use std::{env, path::Path};
use std::{fs, io::Write};
use anyhow::{Context, Result};
use color_eyre::eyre::eyre;
use color_eyre::eyre::Context;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use log::debug;
use tempfile::tempfile_in;
@@ -154,7 +156,7 @@ pub fn run_micro(run_type: RunType) -> Result<()> {
if stdout.contains("Nothing to install / update") || stdout.contains("One or more plugins installed") {
Ok(())
} else {
Err(anyhow::anyhow!("micro output does not indicate success: {}", stdout))
Err(eyre!("micro output does not indicate success: {}", stdout))
}
}

View File

@@ -3,7 +3,7 @@ use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use anyhow::{anyhow, Result};
use color_eyre::eyre::{eyre, Result};
use console::style;
use futures::stream::{iter, FuturesUnordered};
use futures::StreamExt;
@@ -37,7 +37,7 @@ pub struct Repositories<'a> {
fn output_checked_utf8(output: Output) -> Result<()> {
if !(output.status.success()) {
let stderr = String::from_utf8(output.stderr).unwrap();
Err(anyhow!(stderr))
Err(eyre!(stderr))
} else {
Ok(())
}

View File

@@ -1,6 +1,6 @@
use crate::terminal::print_separator;
use crate::utils::require;
use anyhow::Result;
use color_eyre::eyre::Result;
use crate::execution_context::ExecutionContext;

View File

@@ -4,7 +4,7 @@ use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::process::Command;
use anyhow::Result;
use color_eyre::eyre::Result;
use log::debug;
#[cfg(target_os = "linux")]
use nix::unistd::Uid;

View File

@@ -2,7 +2,7 @@ use crate::execution_context::ExecutionContext;
use crate::terminal::print_separator;
use crate::utils::require;
use crate::Step;
use anyhow::Result;
use color_eyre::eyre::Result;
pub fn upgrade_packages(ctx: &ExecutionContext) -> Result<()> {
//let pkg = require("pkg")?;

View File

@@ -3,7 +3,8 @@ use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::Result;
use color_eyre::eyre;
use color_eyre::eyre::Result;
use walkdir::WalkDir;
use crate::command::CommandExt;
@@ -301,7 +302,7 @@ pub fn get_arch_package_manager(ctx: &ExecutionContext) -> Option<Box<dyn ArchPa
pub fn upgrade_arch_linux(ctx: &ExecutionContext) -> Result<()> {
let package_manager =
get_arch_package_manager(ctx).ok_or_else(|| anyhow::Error::from(TopgradeError::FailedGettingPackageManager))?;
get_arch_package_manager(ctx).ok_or_else(|| eyre::Report::from(TopgradeError::FailedGettingPackageManager))?;
package_manager.upgrade(ctx)
}

View File

@@ -1,7 +1,7 @@
use crate::executor::RunType;
use crate::terminal::print_separator;
use crate::utils::require_option;
use anyhow::Result;
use color_eyre::eyre::Result;
use std::path::PathBuf;
use std::process::Command;

View File

@@ -1,7 +1,7 @@
use crate::executor::RunType;
use crate::terminal::print_separator;
use crate::utils::require_option;
use anyhow::Result;
use color_eyre::eyre::Result;
use std::path::PathBuf;
use std::process::Command;

View File

@@ -1,7 +1,7 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::Result;
use color_eyre::eyre::Result;
use ini::Ini;
use log::{debug, warn};

View File

@@ -3,7 +3,7 @@ use crate::execution_context::ExecutionContext;
use crate::executor::RunType;
use crate::terminal::{print_separator, prompt_yesno};
use crate::{utils::require, Step};
use anyhow::Result;
use color_eyre::eyre::Result;
use log::debug;
use std::fs;
use std::process::Command;

View File

@@ -1,7 +1,7 @@
use crate::executor::RunType;
use crate::terminal::print_separator;
use crate::utils::require_option;
use anyhow::Result;
use color_eyre::eyre::Result;
use std::path::PathBuf;
pub fn upgrade_openbsd(sudo: Option<&PathBuf>, run_type: RunType) -> Result<()> {

View File

@@ -6,7 +6,7 @@ use std::{env, path::Path};
use crate::command::CommandExt;
use crate::Step;
use anyhow::Result;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use home;
use ini::Ini;

View File

@@ -2,7 +2,7 @@ use std::convert::TryFrom;
use std::path::Path;
use std::{ffi::OsStr, process::Command};
use anyhow::Result;
use color_eyre::eyre::Result;
use log::debug;
use crate::command::CommandExt;

View File

@@ -3,7 +3,7 @@ use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use anyhow::Result;
use color_eyre::eyre::Result;
use crate::command::CommandExt;
use crate::execution_context::ExecutionContext;

View File

@@ -1,4 +1,4 @@
use anyhow::Result;
use color_eyre::eyre::Result;
use crate::{
command::CommandExt, error::SkipStep, execution_context::ExecutionContext, terminal::print_separator, utils,

View File

@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::{fmt::Display, rc::Rc, str::FromStr};
use anyhow::Result;
use color_eyre::eyre::Result;
use log::{debug, error};
use regex::Regex;
use strum::EnumString;

View File

@@ -2,7 +2,7 @@ use std::env;
use std::path::PathBuf;
use std::process::{exit, Command};
use anyhow::Result;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use crate::command::CommandExt;

View File

@@ -1,4 +1,4 @@
use anyhow::Result;
use color_eyre::eyre::Result;
use crate::command::CommandExt;
use crate::config::Step;

View File

@@ -1,6 +1,6 @@
use crate::command::CommandExt;
use crate::error::{SkipStep, TopgradeError};
use anyhow::Result;
use color_eyre::eyre::Result;
use crate::executor::{Executor, ExecutorOutput, RunType};
use crate::terminal::print_separator;

View File

@@ -2,7 +2,7 @@ use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::Result;
use color_eyre::eyre::Result;
use directories::BaseDirs;
use log::debug;
use walkdir::WalkDir;

View File

@@ -7,8 +7,9 @@ use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Context;
use chrono::{Local, Timelike};
use color_eyre::eyre;
use color_eyre::eyre::Context;
use console::{style, Key, Term};
use lazy_static::lazy_static;
use log::{debug, error};
@@ -36,7 +37,7 @@ pub fn shell() -> &'static str {
which("pwsh").map(|_| "pwsh").unwrap_or("powershell")
}
pub fn run_shell() -> anyhow::Result<()> {
pub fn run_shell() -> eyre::Result<()> {
Command::new(shell()).env("IN_TOPGRADE", "1").status_checked()
}
@@ -213,7 +214,7 @@ impl Terminal {
}
}
#[allow(unused_variables)]
fn should_retry(&mut self, interrupted: bool, step_name: &str) -> anyhow::Result<bool> {
fn should_retry(&mut self, interrupted: bool, step_name: &str) -> eyre::Result<bool> {
if self.width.is_none() {
return Ok(false);
}
@@ -269,7 +270,7 @@ impl Default for Terminal {
}
}
pub fn should_retry(interrupted: bool, step_name: &str) -> anyhow::Result<bool> {
pub fn should_retry(interrupted: bool, step_name: &str) -> eyre::Result<bool> {
TERMINAL.lock().unwrap().should_retry(interrupted, step_name)
}

View File

@@ -1,5 +1,5 @@
use crate::error::SkipStep;
use anyhow::Result;
use color_eyre::eyre::Result;
use log::{debug, error};
use std::env;