Merge pull request #1 from SergioGasquez/fix/remove-anyhow

Use miette as main error crate
This commit is contained in:
Sergio Gasquez Arcos 2022-11-15 14:55:14 +01:00 committed by GitHub
commit 20993fc710
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 67 additions and 38 deletions

View File

@ -38,6 +38,9 @@ pub enum Error {
#[error("{} Unsuported file extension: '{0}'", emoji::ERROR)]
UnsuportedFileExtension(String),
// Toolchain - Rust
#[diagnostic(code(espup::toolchain::rust::failed_to_get_latest_version))]
#[error("{} Failed To serialize Json from string.", emoji::ERROR)]
FailedToSerializeJson,
#[diagnostic(code(espup::toolchain::rust::xtensa_rust_already_installed))]
#[error("{} Previous installation of Rust Toolchain exists in: '{0}'. Please, remove the directory before new installation.", emoji::ERROR)]
XtensaToolchainAlreadyInstalled(String),
@ -52,6 +55,16 @@ pub enum Error {
RustupDetectionError(String),
#[error(transparent)]
CmdError(#[from] embuild::cmd::CmdError),
// Toolchain - ESP-IDF
#[diagnostic(code(espup::toolchain::espidf::failed_to_instatiate_cmake))]
#[error("{} Failed to add CMake to ESP-IDF tools", emoji::ERROR)]
FailedToInstantiateCmake,
#[diagnostic(code(espup::toolchain::espidf::failed_to_create_esp_idf_install_closure))]
#[error("{} Failed to create ESP-IDF install closure", emoji::ERROR)]
FailedToCreateEspIdfInstallClosure,
#[diagnostic(code(espup::toolchain::espidf::failed_to_install_esp_idf))]
#[error("{} Failed to install ESP-IDF", emoji::ERROR)]
FailedToInstallEspIdf,
// Main
#[diagnostic(code(espup::wrong_windows_arguments))]
#[error(
@ -59,4 +72,10 @@ pub enum Error {
emoji::ERROR
)]
WrongWindowsArguments,
#[diagnostic(code(espup::failed_to_remove_directory))]
#[error(
"{} Failed to remove '{0}' direcretory. Please, manually verify that the directory is properly removed.",
emoji::ERROR
)]
FailedToRemoveDirectory(String),
}

View File

@ -1,4 +1,3 @@
use anyhow::Result;
use clap::Parser;
use directories_next::ProjectDirs;
use dirs::home_dir;
@ -6,11 +5,10 @@ use embuild::{
cmd,
espidf::{parse_esp_idf_git_ref, EspIdfRemote},
};
#[cfg(windows)]
use espup::error::Error;
use espup::{
config::Config,
emoji,
error::Error,
host_triple::get_host_triple,
logging::initialize_logger,
targets::{parse_targets, Target},
@ -27,6 +25,7 @@ use espup::{
update::check_for_update,
};
use log::{debug, info, warn};
use miette::Result;
use std::{
collections::HashSet,
fs::{remove_dir_all, remove_file, File},
@ -130,7 +129,7 @@ pub struct UninstallOpts {
}
/// Installs the Rust for ESP chips environment
fn install(args: InstallOpts) -> Result<()> {
fn install(args: InstallOpts) -> Result<(), Error> {
initialize_logger(&args.log_level);
check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
info!("{} Installing esp-rs", emoji::DISC);
@ -246,7 +245,7 @@ fn install(args: InstallOpts) -> Result<()> {
}
/// Uninstalls the Rust for ESP chips environment
fn uninstall(args: UninstallOpts) -> Result<()> {
fn uninstall(args: UninstallOpts) -> Result<(), Error> {
initialize_logger(&args.log_level);
check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
@ -304,7 +303,7 @@ fn uninstall(args: UninstallOpts) -> Result<()> {
}
/// Updates Xtensa Rust toolchain.
fn update(args: UpdateOpts) -> Result<()> {
fn update(args: UpdateOpts) -> Result<(), Error> {
initialize_logger(&args.log_level);
check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
@ -349,7 +348,7 @@ fn update(args: UpdateOpts) -> Result<()> {
Ok(())
}
fn main() -> Result<()> {
fn main() -> Result<(), Error> {
match Cli::parse().subcommand {
SubCommand::Install(args) => install(*args),
SubCommand::Update(args) => update(args),
@ -358,7 +357,7 @@ fn main() -> Result<()> {
}
/// Deletes dist folder.
fn clear_dist_folder() -> Result<()> {
fn clear_dist_folder() -> Result<(), Error> {
let dist_path = PathBuf::from(get_dist_path(""));
if dist_path.exists() {
info!("{} Clearing dist folder", emoji::WRENCH);
@ -368,7 +367,7 @@ fn clear_dist_folder() -> Result<()> {
}
/// Returns the absolute path to the export file, uses the DEFAULT_EXPORT_FILE if no arg is provided.
fn get_export_file(export_file: Option<PathBuf>) -> Result<PathBuf> {
fn get_export_file(export_file: Option<PathBuf>) -> Result<PathBuf, Error> {
if let Some(export_file) = export_file {
if export_file.is_absolute() {
Ok(export_file)
@ -383,7 +382,7 @@ fn get_export_file(export_file: Option<PathBuf>) -> Result<PathBuf> {
}
/// Creates the export file with the necessary environment variables.
fn export_environment(export_file: &PathBuf, exports: &[String]) -> Result<()> {
fn export_environment(export_file: &PathBuf, exports: &[String]) -> Result<(), Error> {
info!("{} Creating export file", emoji::WRENCH);
let mut file = File::create(export_file)?;
for e in exports.iter() {

View File

@ -2,18 +2,19 @@
use crate::{
emoji,
error::Error,
targets::Target,
toolchain::{
gcc::{get_toolchain_name, get_ulp_toolchain_name},
get_home_dir,
},
};
use anyhow::{Context, Result};
use embuild::{espidf, espidf::EspIdfRemote, git};
use log::{debug, info};
use std::collections::HashSet;
use miette::Result;
use std::{
collections::hash_map::DefaultHasher,
collections::HashSet,
env,
fs::remove_dir_all,
hash::{Hash, Hasher},
@ -64,18 +65,22 @@ pub struct EspIdfRepo {
impl EspIdfRepo {
/// Installs esp-idf.
pub fn install(self) -> Result<Vec<String>> {
pub fn install(self) -> Result<Vec<String>, Error> {
let cmake_generator = DEFAULT_CMAKE_GENERATOR;
let mut exports: Vec<String> = Vec::new();
// A closure to specify which tools `idf-tools.py` should install.
let make_tools = move |repo: &git::Repository,
version: &Result<espidf::EspIdfVersion>|
-> Result<Vec<espidf::Tools>> {
version: &anyhow::Result<espidf::EspIdfVersion>|
-> anyhow::Result<Vec<espidf::Tools>> {
let version_str = match version {
Ok(v) => format!("v{v}"),
Err(_) => "(unknown version)".to_string(),
};
info!(
"{} Using esp-idf {} at '{}'",
emoji::INFO,
espidf::EspIdfVersion::format(version),
version_str,
repo.worktree().display()
);
@ -99,7 +104,8 @@ impl EspIdfRepo {
subtools.push("cmake".to_string())
}
_ => {
tools.push(espidf::Tools::cmake()?);
tools
.push(espidf::Tools::cmake().map_err(|_| Error::FailedToInstantiateCmake)?);
}
}
#[cfg(windows)]
@ -119,13 +125,15 @@ impl EspIdfRepo {
Ok(tools)
};
let install = |esp_idf_origin: espidf::EspIdfOrigin| -> Result<espidf::EspIdf> {
espidf::Installer::new(esp_idf_origin)
.install_dir(Some(self.install_path.clone()))
.with_tools(make_tools)
.install()
.context("Could not install esp-idf")
};
let install =
|esp_idf_origin: espidf::EspIdfOrigin| -> anyhow::Result<espidf::EspIdf, Error> {
espidf::Installer::new(esp_idf_origin)
.install_dir(Some(self.install_path.clone()))
.with_tools(make_tools)
.install()
.map_err(|_| Error::FailedToCreateEspIdfInstallClosure)
};
let repo = espidf::EspIdfRemote {
git_ref: espidf::parse_esp_idf_git_ref(&self.version),
@ -134,7 +142,7 @@ impl EspIdfRepo {
let espidf_origin = espidf::EspIdfOrigin::Managed(repo.clone());
#[cfg(unix)]
let espidf = install(espidf_origin)?;
let espidf = install(espidf_origin).map_err(|_| Error::FailedToInstallEspIdf)?;
#[cfg(windows)]
install(espidf_origin)?;
let espidf_dir = get_install_path(repo);

View File

@ -2,13 +2,14 @@
use crate::{
emoji,
error::Error,
host_triple::HostTriple,
targets::Target,
toolchain::{download_file, espidf::get_tool_path},
};
use anyhow::Result;
use embuild::espidf::EspIdfVersion;
use log::{debug, info, warn};
use miette::Result;
use std::{
collections::HashSet,
path::{Path, PathBuf},
@ -43,7 +44,7 @@ impl Gcc {
}
/// Installs the gcc toolchain.
pub fn install(&self) -> Result<()> {
pub fn install(&self) -> Result<(), Error> {
let target_dir = format!("{}/{}-{}", self.toolchain_name, self.release, self.version);
let gcc_path = get_tool_path(&target_dir);
let extension = get_artifact_extension(&self.host_triple);
@ -140,7 +141,7 @@ pub fn get_ulp_toolchain_name(target: Target, version: Option<&EspIdfVersion>) -
pub fn install_gcc_targets(
targets: &HashSet<Target>,
host_triple: &HostTriple,
) -> Result<Vec<String>> {
) -> Result<Vec<String>, Error> {
info!("{} Installing gcc for build targets", emoji::WRENCH);
let mut exports: Vec<String> = Vec::new();
for target in targets {

View File

@ -2,11 +2,12 @@
use crate::{
emoji,
error::Error,
host_triple::HostTriple,
toolchain::{download_file, espidf::get_tool_path},
};
use anyhow::{Ok, Result};
use log::{info, warn};
use miette::Result;
use std::path::{Path, PathBuf};
const DEFAULT_LLVM_REPOSITORY: &str = "https://github.com/espressif/llvm-project/releases/download";
@ -48,7 +49,7 @@ impl Llvm {
}
/// Installs the LLVM toolchain.
pub fn install(&self) -> Result<Vec<String>> {
pub fn install(&self) -> Result<Vec<String>, Error> {
let mut exports: Vec<String> = Vec::new();
if Path::new(&self.path).exists() {

View File

@ -1,8 +1,8 @@
use crate::{emoji, error::Error};
use anyhow::Result;
use dirs::home_dir;
use flate2::bufread::GzDecoder;
use log::info;
use miette::Result;
use std::{
fs::{create_dir_all, File},
io::{copy, BufReader},

View File

@ -6,9 +6,9 @@ use crate::{
host_triple::HostTriple,
toolchain::{download_file, espidf::get_dist_path, get_home_dir},
};
use anyhow::Result;
use embuild::cmd;
use log::{debug, info, warn};
use miette::Result;
use regex::Regex;
use reqwest::header;
use serde::{Deserialize, Serialize};
@ -49,7 +49,7 @@ pub struct XtensaRust {
impl XtensaRust {
/// Get the latest version of Xtensa Rust toolchain.
pub fn get_latest_version() -> Result<String> {
pub fn get_latest_version() -> Result<String, Error> {
let mut headers = header::HeaderMap::new();
headers.insert("Accept", "application/vnd.github.v3+json".parse().unwrap());
@ -63,7 +63,8 @@ impl XtensaRust {
.headers(headers)
.send()?
.text()?;
let json: serde_json::Value = serde_json::from_str(&res)?;
let json: serde_json::Value =
serde_json::from_str(&res).map_err(|_| Error::FailedToSerializeJson)?;
let mut version = json["tag_name"].to_string();
version.retain(|c| c != 'v' && c != '"');
@ -187,7 +188,7 @@ impl XtensaRust {
}
/// Removes the Xtensa Rust toolchain.
pub fn uninstall(&self) -> Result<()> {
pub fn uninstall(&self) -> Result<(), Error> {
info!("{} Uninstalling Xtensa Rust toolchain", emoji::WRENCH);
remove_dir_all(&self.toolchain_destination)?;
Ok(())
@ -202,7 +203,7 @@ pub struct Crate {
impl Crate {
/// Installs a crate.
pub fn install(&self) -> Result<()> {
pub fn install(&self) -> Result<(), Error> {
#[cfg(unix)]
let crate_path = format!("{}/bin/{}", get_cargo_home().display(), self.name);
#[cfg(windows)]
@ -229,7 +230,7 @@ impl Crate {
}
}
pub fn install_extra_crates(crates: &HashSet<Crate>) -> Result<()> {
pub fn install_extra_crates(crates: &HashSet<Crate>) -> Result<(), Error> {
debug!(
"{} Installing the following crates: {:#?}",
emoji::DEBUG,
@ -355,7 +356,7 @@ fn install_rustup(nightly_version: &str) -> Result<(), Error> {
}
/// Installs the RiscV target.
pub fn install_riscv_target(nightly_version: &str) -> Result<()> {
pub fn install_riscv_target(nightly_version: &str) -> Result<(), Error> {
info!("{} Installing Riscv target", emoji::WRENCH);
cmd!(
"rustup",