Skip to content

Commit

Permalink
refactor: use anyhow to rewrite the error handling process
Browse files Browse the repository at this point in the history
Signed-off-by: The1111mp <[email protected]>
  • Loading branch information
1111mp committed Apr 30, 2024
1 parent e29f8f7 commit 19903a8
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 157 deletions.
27 changes: 1 addition & 26 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use lazy_static::lazy_static;
use serde_json::{from_str, json, Value};
#[cfg(unix)]
use std::os::unix::fs;
use std::{env, ffi::OsString, io::ErrorKind, path::PathBuf, process::ExitStatus};
use std::{env, ffi::OsString, io::ErrorKind, path::PathBuf};

lazy_static! {
pub static ref NVMD_PATH: PathBuf = get_nvmd_path();
Expand Down Expand Up @@ -237,28 +237,3 @@ fn default_home_dir() -> Result<PathBuf, ErrorKind> {
home.push(".nvmd");
Ok(home)
}

pub enum Error {
Message(String),
Code(i32),
}

pub trait IntoResult<T> {
fn into_result(self) -> Result<T, Error>;
}

impl IntoResult<()> for Result<ExitStatus, String> {
fn into_result(self) -> Result<(), Error> {
match self {
Ok(status) => {
if status.success() {
Ok(())
} else {
let code = status.code().unwrap_or(1);
Err(Error::Code(code))
}
}
Err(err) => Err(Error::Message(err)),
}
}
}
16 changes: 8 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ mod command;
mod common;
mod run;

use common::{Error, IntoResult};
use run::execute;

fn main() {
let result = execute().into_result();
let result = execute();
match result {
Ok(()) => {
process::exit(0);
}
Err(Error::Code(code)) => {
Ok(exit_status) => {
// If the code method returns None (meaning the process exited due to receiving a signal)
// Extract the exit code, using the default value 0 if the process terminated due to a signal
let code = exit_status.code().unwrap_or(0);
process::exit(code);
}
Err(Error::Message(msg)) => {
eprintln!("nvm-desktop: {}", msg);
Err(error) => {
// Print error messages to standard error output
eprintln!("nvm-desktop: {}", error);
process::exit(1);
}
}
Expand Down
14 changes: 6 additions & 8 deletions src/run/binary.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use super::{anyhow, Result};
use super::{ExitStatus, OsStr, OsString};

use crate::{
command as CommandTool,
common::{ENV_PATH, INSTALLTION_PATH, VERSION},
};

pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus, String> {
pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus> {
let mut lib_path = INSTALLTION_PATH.clone();
lib_path.push(VERSION.clone());
if cfg!(unix) {
Expand All @@ -15,16 +16,13 @@ pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus, Stri
lib_path.push(exe);

if !lib_path.exists() {
return Err(String::from("command not found: ") + exe.to_str().unwrap());
return Err(anyhow!("command not found: {:?}", exe));
}

let child = CommandTool::create_command(exe)
let status = CommandTool::create_command(exe)
.env("PATH", ENV_PATH.clone())
.args(args)
.status();
.status()?;

match child {
Ok(status) => Ok(status),
Err(_) => Err(String::from("failed to execute process")),
}
Ok(status)
}
38 changes: 17 additions & 21 deletions src/run/corepack.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::{anyhow, Result};
use super::{ExitStatus, OsStr, OsString};

use lazy_static::lazy_static;
Expand All @@ -23,35 +24,30 @@ lazy_static! {
// `which corepack`, but this can be tweaked by explicitly passing the install
// directory via the `--install-directory` flag.

pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus, String> {
pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus> {
if ENV_PATH.is_empty() {
return Err(String::from("command not found: ") + exe.to_str().unwrap());
return Err(anyhow!("command not found: {:?}", exe));
}

let child = CommandTool::create_command(exe)
let status = CommandTool::create_command(exe)
.env("PATH", ENV_PATH.clone())
.args(args)
.status();

match child {
Ok(status) => {
let install_directory = args.contains(&INSTALL_DIRECTORY);
// corepack enable ..
// No special handling is required when using the "--install-directory" option
if args.contains(&ENABLE) && !install_directory {
corepack_enable(args);
}
.status()?;

// corepack disable ..
// No special handling is required when using the "--install-directory" option
if args.contains(&DISABLE) && !install_directory {
corepack_disable(args);
}
let install_directory = args.contains(&INSTALL_DIRECTORY);
// corepack enable ..
// No special handling is required when using the "--install-directory" option
if args.contains(&ENABLE) && !install_directory {
corepack_enable(args);
}

Ok(status)
}
Err(_) => Err(String::from("failed to execute process")),
// corepack disable ..
// No special handling is required when using the "--install-directory" option
if args.contains(&DISABLE) && !install_directory {
corepack_disable(args);
}

Ok(status)
}

fn corepack_enable(args: &[OsString]) {
Expand Down
14 changes: 6 additions & 8 deletions src/run/engine.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use super::{anyhow, Result};
use super::{ExitStatus, OsStr, OsString};

use crate::{command as CommandTool, common::ENV_PATH};

pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus, String> {
pub(super) fn command(exe: &OsStr, args: &[OsString]) -> Result<ExitStatus> {
if ENV_PATH.is_empty() {
return Err(String::from("command not found: ") + exe.to_str().unwrap());
return Err(anyhow!("command not found: {:?}", exe));
}

let child = CommandTool::create_command(exe)
let status = CommandTool::create_command(exe)
.env("PATH", ENV_PATH.clone())
.args(args)
.status();
.status()?;

match child {
Ok(status) => Ok(status),
Err(_) => Err(String::from("failed to execute process")),
}
Ok(status)
}
3 changes: 2 additions & 1 deletion src/run/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::{anyhow, Result};
use std::{
env::{self, ArgsOs},
ffi::{OsStr, OsString},
Expand All @@ -12,7 +13,7 @@ mod engine;
mod npm;
mod nvmd;

pub fn execute() -> Result<ExitStatus, String> {
pub fn execute() -> Result<ExitStatus> {
let mut native_args = env::args_os();
let exe = get_tool_name(&mut native_args).expect("get tool name error");
let args: Vec<_> = native_args.collect();
Expand Down
Loading

0 comments on commit 19903a8

Please sign in to comment.