Skip to content

Commit

Permalink
migrate from failure to anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
syphar committed Dec 19, 2022
1 parent ad5e792 commit 1797642
Show file tree
Hide file tree
Showing 24 changed files with 172 additions and 185 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ unstable-toolchain-ci = []

[dependencies]
http = "0.2"
failure = "0.1.3"
anyhow = { version = "1.0.68", features = ["backtrace"]}
futures-util = "0.3.5"
log = "0.4.6"
tokio = { version = "1.0", features = ["process", "time", "io-util", "rt", "rt-multi-thread"] }
Expand Down
10 changes: 5 additions & 5 deletions src/build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::cmd::{Command, MountKind, Runnable, SandboxBuilder};
use crate::prepare::Prepare;
use crate::{Crate, Toolchain, Workspace};
use failure::Error;
use anyhow::Result;
use std::path::PathBuf;
use std::vec::Vec;

Expand Down Expand Up @@ -131,7 +131,7 @@ impl<'a> BuildBuilder<'a> {
/// })?;
/// # Ok(())
/// # }
pub fn run<R, F: FnOnce(&Build) -> Result<R, Error>>(self, f: F) -> Result<R, Error> {
pub fn run<R, F: FnOnce(&Build) -> Result<R>>(self, f: F) -> Result<R> {
self.build_dir
.run(self.toolchain, self.krate, self.sandbox, self.patches, f)
}
Expand Down Expand Up @@ -181,14 +181,14 @@ impl BuildDirectory {
}
}

pub(crate) fn run<R, F: FnOnce(&Build) -> Result<R, Error>>(
pub(crate) fn run<R, F: FnOnce(&Build) -> Result<R>>(
&mut self,
toolchain: &Toolchain,
krate: &Crate,
sandbox: SandboxBuilder,
patches: Vec<CratePatch>,
f: F,
) -> Result<R, Error> {
) -> Result<R> {
let source_dir = self.source_dir();
if source_dir.exists() {
crate::utils::remove_dir_all(&source_dir)?;
Expand All @@ -209,7 +209,7 @@ impl BuildDirectory {
}

/// Remove all the contents of the build directory, freeing disk space.
pub fn purge(&mut self) -> Result<(), Error> {
pub fn purge(&mut self) -> Result<()> {
let build_dir = self.build_dir();
if build_dir.exists() {
crate::utils::remove_dir_all(&build_dir)?;
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ impl<'w, 'pl> Command<'w, 'pl> {
}
};

let mut cmd = AsyncCommand::new(&binary);
let mut cmd = AsyncCommand::new(binary);
cmd.args(&self.args);

if managed_by_rustwide {
Expand Down
14 changes: 7 additions & 7 deletions src/crates/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::CrateTrait;
use crate::cmd::{Command, ProcessLinesActions};
use crate::prepare::PrepareError;
use crate::Workspace;
use failure::{Error, ResultExt};
use anyhow::{Context as _, Result};
use log::{info, warn};
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -63,7 +63,7 @@ impl GitRepo {
}

impl CrateTrait for GitRepo {
fn fetch(&self, workspace: &Workspace) -> Result<(), Error> {
fn fetch(&self, workspace: &Workspace) -> Result<()> {
// The credential helper that suppresses the password prompt shows this message when a
// repository requires authentication:
//
Expand All @@ -86,7 +86,7 @@ impl CrateTrait for GitRepo {
.cd(&path)
.process_lines(&mut detect_private_repositories)
.run()
.with_context(|_| format!("failed to update {}", self.url))
.with_context(|| format!("failed to update {}", self.url))
} else {
info!("cloning repository {}", self.url);
Command::new(workspace, "git")
Expand All @@ -95,7 +95,7 @@ impl CrateTrait for GitRepo {
.args(&[&path])
.process_lines(&mut detect_private_repositories)
.run()
.with_context(|_| format!("failed to clone {}", self.url))
.with_context(|| format!("failed to clone {}", self.url))
};

if private_repository && res.is_err() {
Expand All @@ -105,20 +105,20 @@ impl CrateTrait for GitRepo {
}
}

fn purge_from_cache(&self, workspace: &Workspace) -> Result<(), Error> {
fn purge_from_cache(&self, workspace: &Workspace) -> Result<()> {
let path = self.cached_path(workspace);
if path.exists() {
crate::utils::remove_dir_all(&path)?;
}
Ok(())
}

fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<(), Error> {
fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<()> {
Command::new(workspace, "git")
.args(&["clone"])
.args(&[self.cached_path(workspace).as_path(), dest])
.run()
.with_context(|_| format!("failed to checkout {}", self.url))?;
.with_context(|| format!("failed to checkout {}", self.url))?;
Ok(())
}
}
Expand Down
18 changes: 9 additions & 9 deletions src/crates/local.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::CrateTrait;
use crate::Workspace;
use failure::Error;
use anyhow::Result;
use log::info;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
Expand All @@ -16,17 +16,17 @@ impl Local {
}

impl CrateTrait for Local {
fn fetch(&self, _workspace: &Workspace) -> Result<(), Error> {
fn fetch(&self, _workspace: &Workspace) -> Result<()> {
// There is no fetch to do for a local crate.
Ok(())
}

fn purge_from_cache(&self, _workspace: &Workspace) -> Result<(), Error> {
fn purge_from_cache(&self, _workspace: &Workspace) -> Result<()> {
// There is no cache to purge for a local crate.
Ok(())
}

fn copy_source_to(&self, _workspace: &Workspace, dest: &Path) -> Result<(), Error> {
fn copy_source_to(&self, _workspace: &Workspace, dest: &Path) -> Result<()> {
info!(
"copying local crate from {} to {}",
self.path.display(),
Expand All @@ -43,7 +43,7 @@ impl std::fmt::Display for Local {
}
}

fn copy_dir(src: &Path, dest: &Path) -> Result<(), Error> {
fn copy_dir(src: &Path, dest: &Path) -> Result<()> {
let src = crate::utils::normalize_path(src);
let dest = crate::utils::normalize_path(dest);

Expand Down Expand Up @@ -75,10 +75,10 @@ fn copy_dir(src: &Path, dest: &Path) -> Result<(), Error> {

#[cfg(test)]
mod tests {
use failure::Error;
use anyhow::Result;

#[test]
fn test_copy_dir() -> Result<(), Error> {
fn test_copy_dir() -> Result<()> {
let tmp_src = tempfile::tempdir()?;
let tmp_dest = tempfile::tempdir()?;

Expand All @@ -99,7 +99,7 @@ mod tests {
}

#[test]
fn test_no_copy_target() -> Result<(), Error> {
fn test_no_copy_target() -> Result<()> {
let (src, dest) = (tempfile::tempdir()?, tempfile::tempdir()?);
std::fs::create_dir(src.path().join("target"))?;
std::fs::write(
Expand All @@ -116,7 +116,7 @@ mod tests {
}

#[test]
fn test_copy_symlinks() -> Result<(), Error> {
fn test_copy_symlinks() -> Result<()> {
use std::{fs, os, path::Path};

let tmp_src = tempfile::tempdir()?;
Expand Down
14 changes: 7 additions & 7 deletions src/crates/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ mod local;
mod registry;

use crate::Workspace;
use failure::Error;
use anyhow::Result;
use log::info;
use std::path::Path;

pub use registry::AlternativeRegistry;

trait CrateTrait: std::fmt::Display {
fn fetch(&self, workspace: &Workspace) -> Result<(), Error>;
fn purge_from_cache(&self, workspace: &Workspace) -> Result<(), Error>;
fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<(), Error>;
fn fetch(&self, workspace: &Workspace) -> Result<()>;
fn purge_from_cache(&self, workspace: &Workspace) -> Result<()>;
fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<()>;
}

enum CrateType {
Expand Down Expand Up @@ -56,12 +56,12 @@ impl Crate {

/// Fetch the crate's source code and cache it in the workspace. This method will reach out to
/// the network for some crate types.
pub fn fetch(&self, workspace: &Workspace) -> Result<(), Error> {
pub fn fetch(&self, workspace: &Workspace) -> Result<()> {
self.as_trait().fetch(workspace)
}

/// Remove the cached copy of this crate. The method will do nothing if the crate isn't cached.
pub fn purge_from_cache(&self, workspace: &Workspace) -> Result<(), Error> {
pub fn purge_from_cache(&self, workspace: &Workspace) -> Result<()> {
self.as_trait().purge_from_cache(workspace)
}

Expand All @@ -75,7 +75,7 @@ impl Crate {
}
}

pub(crate) fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<(), Error> {
pub(crate) fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<()> {
if dest.exists() {
info!(
"crate source directory {} already exists, cleaning it up",
Expand Down
28 changes: 13 additions & 15 deletions src/crates/registry.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::CrateTrait;
use crate::Workspace;
use failure::{Error, ResultExt};
use anyhow::{Context as _, Result};
use flate2::read::GzDecoder;
use log::info;
use std::fs::File;
Expand Down Expand Up @@ -88,7 +88,7 @@ impl RegistryCrate {
.join(format!("{}-{}.crate", self.name, self.version))
}

fn fetch_url(&self, workspace: &Workspace) -> Result<String, Error> {
fn fetch_url(&self, workspace: &Workspace) -> Result<String> {
match &self.registry {
Registry::CratesIo => Ok(format!(
"{0}/{1}/{1}-{2}.crate",
Expand Down Expand Up @@ -122,7 +122,7 @@ impl RegistryCrate {
git2::build::RepoBuilder::new()
.fetch_options(fo)
.clone(url, &index_path)
.with_context(|_| format!("unable to update_index at {}", url))?;
.with_context(|| format!("unable to update_index at {}", url))?;
info!("cloned registry index");
}
let config = std::fs::read_to_string(index_path.join("config.json"))?;
Expand Down Expand Up @@ -151,7 +151,7 @@ impl RegistryCrate {
}

impl CrateTrait for RegistryCrate {
fn fetch(&self, workspace: &Workspace) -> Result<(), Error> {
fn fetch(&self, workspace: &Workspace) -> Result<()> {
let local = self.cache_path(workspace);
if local.exists() {
info!("crate {} {} is already in cache", self.name, self.version);
Expand All @@ -165,23 +165,23 @@ impl CrateTrait for RegistryCrate {

workspace
.http_client()
.get(&self.fetch_url(workspace)?)
.get(self.fetch_url(workspace)?)
.send()?
.error_for_status()?
.write_to(&mut BufWriter::new(File::create(&local)?))?;

Ok(())
}

fn purge_from_cache(&self, workspace: &Workspace) -> Result<(), Error> {
fn purge_from_cache(&self, workspace: &Workspace) -> Result<()> {
let path = self.cache_path(workspace);
if path.exists() {
crate::utils::remove_file(&path)?;
}
Ok(())
}

fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<(), Error> {
fn copy_source_to(&self, workspace: &Workspace, dest: &Path) -> Result<()> {
let cached = self.cache_path(workspace);
let mut file = File::open(cached)?;
let mut tar = Archive::new(GzDecoder::new(BufReader::new(&mut file)));
Expand All @@ -194,12 +194,10 @@ impl CrateTrait for RegistryCrate {
);
if let Err(err) = unpack_without_first_dir(&mut tar, dest) {
let _ = crate::utils::remove_dir_all(dest);
Err(err
.context(format!(
"unable to download {} version {}",
self.name, self.version
))
.into())
Err(err.context(format!(
"unable to download {} version {}",
self.name, self.version
)))
} else {
Ok(())
}
Expand All @@ -218,7 +216,7 @@ impl std::fmt::Display for RegistryCrate {
}
}

fn unpack_without_first_dir<R: Read>(archive: &mut Archive<R>, path: &Path) -> Result<(), Error> {
fn unpack_without_first_dir<R: Read>(archive: &mut Archive<R>, path: &Path) -> Result<()> {
let entries = archive.entries()?;
for entry in entries {
let mut entry = entry?;
Expand All @@ -230,7 +228,7 @@ fn unpack_without_first_dir<R: Read>(archive: &mut Archive<R>, path: &Path) -> R
let mut components = relpath.components();
// Throw away the first path component
components.next();
let full_path = path.join(&components.as_path());
let full_path = path.join(components.as_path());
if let Some(parent) = full_path.parent() {
std::fs::create_dir_all(parent)?;
}
Expand Down
10 changes: 5 additions & 5 deletions src/inside_docker.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::cmd::Command;
use crate::workspace::Workspace;
use failure::Error;
use anyhow::Result;
use getrandom::getrandom;
use log::info;

Expand All @@ -11,7 +11,7 @@ pub(crate) struct CurrentContainer {
}

impl CurrentContainer {
pub(crate) fn detect(workspace: &Workspace) -> Result<Option<Self>, Error> {
pub(crate) fn detect(workspace: &Workspace) -> Result<Option<Self>> {
if let Some(id) = probe_container_id(workspace)? {
info!("inspecting the current container");
let inspect = Command::new(workspace, "docker")
Expand All @@ -22,7 +22,7 @@ impl CurrentContainer {
let content = inspect.stdout_lines().join("\n");
let mut metadata: Vec<Metadata> = serde_json::from_str(&content)?;
if metadata.len() != 1 {
failure::bail!("invalid output returned by `docker inspect`");
anyhow::bail!("invalid output returned by `docker inspect`");
}
Ok(Some(CurrentContainer {
metadata: metadata.pop().unwrap(),
Expand All @@ -44,7 +44,7 @@ impl CurrentContainer {
/// This function uses a simpler but slower method to get the ID: a file with a random string is
/// created in the temp directory, the list of all the containers is fetched from Docker and then
/// `cat` is executed inside each of them to check whether they have the same random string.
pub(crate) fn probe_container_id(workspace: &Workspace) -> Result<Option<String>, Error> {
pub(crate) fn probe_container_id(workspace: &Workspace) -> Result<Option<String>> {
info!("detecting the ID of the container where rustwide is running");

// Create the probe on the current file system
Expand All @@ -69,7 +69,7 @@ pub(crate) fn probe_container_id(workspace: &Workspace) -> Result<Option<String>
.log_output(false)
.log_command(false)
.run_capture();
if let Ok(&[ref probed]) = res.as_ref().map(|out| out.stdout_lines()) {
if let Ok([ref probed]) = res.as_ref().map(|out| out.stdout_lines()) {
if *probed == probe_content {
info!("probe successful, this is container ID {}", id);
return Ok(Some(id.clone()));
Expand Down
Loading

0 comments on commit 1797642

Please sign in to comment.