Skip to content

Commit

Permalink
CLI: Replace io::Error with anyhow::Error
Browse files Browse the repository at this point in the history
- Error messages in Location were also improved
  • Loading branch information
AmmarAbouZor committed Feb 24, 2024
1 parent 4d33763 commit 5f2c3a7
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 76 deletions.
7 changes: 7 additions & 0 deletions cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.80"
async-trait = "0.1.73"
clap = { version = "4.4.4", features = ["derive"] }
console = "0.15.7"
Expand Down
3 changes: 2 additions & 1 deletion cli/src/fstools.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
extern crate fs_extra;
use anyhow::Error;
use fs_extra::dir::{copy_with_progress, CopyOptions, TransitProcess, TransitProcessResult};
use std::sync::mpsc;
use std::{fs, io::Error, path::PathBuf};
use std::{fs, path::PathBuf};

use crate::tracker::get_tracker;

Expand Down
30 changes: 8 additions & 22 deletions cli/src/location.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use anyhow::{bail, Context, Error};
use git2::Repository;

use std::path::Path;
use std::{
env::current_dir,
io::{Error, ErrorKind},
path::PathBuf,
};
use std::{env::current_dir, path::PathBuf};

use tokio::sync::OnceCell;

Expand All @@ -19,29 +16,18 @@ pub struct Location {
impl Location {
pub fn new() -> Result<Location, Error> {
let current_dir = current_dir()?;
let root: PathBuf = match Repository::discover(current_dir) {
Ok(repo) => {
let Some(root) = repo.workdir() else {
return Err(Error::new(
ErrorKind::NotFound,
"Fail to find project's root location",
));
};

root.into()
}
Err(err) => return Err(Error::new(ErrorKind::NotFound, err)),
let repo =
Repository::discover(current_dir).context("Fail to find chipmunk root directory")?;
let Some(root) = repo.workdir() else {
bail!("Fail to find chipmunk root directory")
};

// Make sure we are in the chipmunk repository
// Note: This check will fail if the structure of the repo changes
if root.join("application").is_dir() && root.join("developing").is_dir() {
Ok(Self { root })
Ok(Self { root: root.into() })
} else {
Err(Error::new(
ErrorKind::NotFound,
"Fail to find project's root location",
))
bail!("Fail to find project's root location")
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ mod spawner;
mod target;
mod tracker;

use anyhow::{bail, Error};
use clap::{Parser, Subcommand};
use futures::future::join_all;
use location::init_location;
use modules::Manager;
use spawner::SpawnResult;
use std::{
fs::File,
io::{self, stdout, Error, ErrorKind, Stdout},
io::{self, stdout, Stdout},
path::PathBuf,
};
use target::Target;
Expand Down Expand Up @@ -180,7 +181,7 @@ async fn main() -> Result<(), Error> {
}
}
if !success {
return Err(Error::new(ErrorKind::Other, "Some task were failed"));
bail!("Some task were failed")
}
Ok(())
}
Expand Down
28 changes: 11 additions & 17 deletions cli/src/modules/app.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use super::{Kind, Manager};
use crate::{fstools, location::get_root, spawner::SpawnResult, Target};
use anyhow::{bail, Context, Error};
use async_trait::async_trait;
use std::{
fs,
io::{Error, ErrorKind},
path::PathBuf,
};
use std::{fs, path::PathBuf};

const PATH: &str = "application/holder";

Expand Down Expand Up @@ -37,16 +34,13 @@ impl Manager for Module {
Some(String::from("yarn install"))
}
async fn after(&self, prod: bool) -> Result<Option<SpawnResult>, Error> {
let src = Target::Client.get().dist_path(prod).ok_or(Error::new(
ErrorKind::NotFound,
"Fail to get client artifacts",
))?;
let src = Target::Client
.get()
.dist_path(prod)
.context("Fail to get client artifacts")?;
let dest = self.cwd().join("dist");
if !src.exists() {
return Err(Error::new(
ErrorKind::NotFound,
format!("Not found: {}", src.display()),
));
bail!("Not found: {}", src.display());
}
if !dest.exists() {
fs::create_dir(&dest)?;
Expand All @@ -57,10 +51,10 @@ impl Manager for Module {
}
fstools::cp_folder(src.clone(), dest.clone()).await?;
std::fs::rename(
dest.join(src.file_name().ok_or(Error::new(
ErrorKind::NotFound,
"Fail to parse client artifacts path",
))?),
dest.join(
src.file_name()
.context("Fail to parse client artifacts path")?,
),
dest.join("client"),
)?;
Ok(None)
Expand Down
3 changes: 2 additions & 1 deletion cli/src/modules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ use crate::{
spawner::{spawn, SpawnOptions, SpawnResult},
Target,
};
use anyhow::Error;
use async_trait::async_trait;
use futures::future::join_all;
use std::{io::Error, path::PathBuf};
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub enum Kind {
Expand Down
12 changes: 3 additions & 9 deletions cli/src/modules/wrapper.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use super::{Kind, Manager};
use crate::{fstools, location::get_root, spawner::SpawnResult, Target};
use anyhow::{bail, Error};
use async_trait::async_trait;
use std::{
fs,
io::{Error, ErrorKind},
path::PathBuf,
};
use std::{fs, path::PathBuf};

const PATH: &str = "application/apps/rustcore/ts-bindings";

Expand Down Expand Up @@ -36,10 +33,7 @@ impl Manager for Module {
let src = Target::Binding.get().cwd().join("dist/index.node");
let dest = self.cwd().join("dist/native");
if !src.exists() {
return Err(Error::new(
ErrorKind::NotFound,
format!("Not found: {}", src.to_string_lossy()),
));
bail!("Not found: {}", src.to_string_lossy());
}
if !dest.exists() {
fs::create_dir(&dest)?;
Expand Down
11 changes: 4 additions & 7 deletions cli/src/spawner.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// cmd.envs(vec![("PATH", "/bin"), ("TERM", "xterm-256color")]);
use crate::{ location::{to_relative_path, get_root}, tracker::get_tracker};
use anyhow::bail;
use futures_lite::{future, FutureExt};
use std::{
env::vars,
io,
path::PathBuf,
process::{ExitStatus, Stdio},
};
Expand Down Expand Up @@ -78,7 +78,7 @@ pub async fn spawn(
cwd: Option<PathBuf>,
caption: String,
opts: Option<SpawnOptions>,
) -> Result<SpawnResult, io::Error> {
) -> Result<SpawnResult, anyhow::Error> {
let opts = opts.unwrap_or_default();
let cwd = cwd.unwrap_or_else(|| get_root().clone());
let mut parts = command.split(' ').collect::<Vec<&str>>();
Expand Down Expand Up @@ -146,7 +146,7 @@ pub async fn spawn(
}

future::pending::<()>().await;
Ok::<Option<ExitStatus>, io::Error>(None)
Ok::<Option<ExitStatus>, anyhow::Error>(None)
}
};

Expand Down Expand Up @@ -176,9 +176,6 @@ pub async fn spawn(
tracker
.fail(sequence, "Fail to get exist status of spawned command")
.await;
Err(io::Error::new(
io::ErrorKind::Other,
"Fail to get exist status of spawned command",
))
bail!( "Fail to get exist status of spawned command")
}
}
27 changes: 10 additions & 17 deletions cli/src/tracker.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use anyhow::{anyhow, Context, Error};
use console::style;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::{
collections::HashMap,
io::{Error, ErrorKind},
time::Instant,
};
use std::{collections::HashMap, time::Instant};
use tokio::sync::{
mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
oneshot, OnceCell,
Expand Down Expand Up @@ -81,9 +78,9 @@ impl Tracker {
}

pub async fn run(mut rx: UnboundedReceiver<Tick>) -> Result<(), Error> {
let spinner_style = ProgressStyle::with_template("{spinner} {prefix:.bold.dim} {wide_msg}")
.map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?
.tick_chars("▂▃▅▆▇▆▅▃▂ ");
let spinner_style =
ProgressStyle::with_template("{spinner} {prefix:.bold.dim} {wide_msg}")?
.tick_chars("▂▃▅▆▇▆▅▃▂ ");
async move {
let mut sequence: usize = 0;
let mut max_time_len = 0;
Expand Down Expand Up @@ -223,10 +220,8 @@ impl Tracker {
let (tx_response, rx_response) = oneshot::channel();
self.tx
.send(Tick::Started(job.to_string(), max, tx_response))
.map_err(|e| Error::new(ErrorKind::Other, format!("Fail to send tick: {e}")))?;
rx_response
.await
.map_err(|err| Error::new(ErrorKind::NotConnected, err.to_string()))
.context("Fail to send tick")?;
rx_response.await.context("Fail to receive tick")
}

pub async fn progress(&self, sequence: usize, pos: Option<u64>) {
Expand Down Expand Up @@ -265,17 +260,15 @@ impl Tracker {
let (tx_response, rx_response) = oneshot::channel();
self.tx
.send(Tick::Shutdown(tx_response))
.map_err(|e| Error::new(ErrorKind::Other, format!("Fail to send tick: {e}")))?;
rx_response
.await
.map_err(|err| Error::new(ErrorKind::NotConnected, err.to_string()))
.context("Fail to send tick")?;
rx_response.await.context("Fail to receive tick")
}

pub async fn _print(&self, msg: String) {
if let Err(e) = self
.tx
.send(Tick::Print(msg))
.map_err(|e| Error::new(ErrorKind::Other, format!("Fail to send tick: {e}")))
.map_err(|e| anyhow!("Fail to send tick: {e}"))
{
eprintln!("Fail to communicate with tracker: {e}");
}
Expand Down

0 comments on commit 5f2c3a7

Please sign in to comment.