Skip to content

Commit

Permalink
chore: use anyhow + resolve lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nokazn committed Apr 16, 2024
1 parent 2bfa80a commit c535caa
Show file tree
Hide file tree
Showing 13 changed files with 82 additions and 74 deletions.
7 changes: 7 additions & 0 deletions 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 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.82"
clap = "4.5.1"
data-encoding = "2.5.0"
dirs = "5.0.1"
Expand Down
9 changes: 5 additions & 4 deletions src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::core::{Result, APP_NAME};
use crate::core::APP_NAME;
use crate::errors::{to_error, Error, Paths};
use crate::utils::path::{to_dir_key, DirKey};
use crate::utils::{fs, hash::Hash};
Expand Down Expand Up @@ -37,7 +38,7 @@ impl Metadata {
contents,
file_path: file_path.clone(),
})
.map_err(|error| Error::Parse(Paths::One(file_path), error.to_string())),
.map_err(|error| Error::Parse(Paths::One(file_path), error.to_string()).into()),
Err(_) => {
let v = Self {
file_path: file_path.clone(),
Expand Down Expand Up @@ -161,13 +162,13 @@ impl Cache {
}
// escape the current cache is exists
fs::rename(&self.target_dir, self.to_cache_path(&current_hash_key))
.map_err(|error| error.log_warn(Some("Failed to save the old cache")))
.map_err(|error| error.context("Failed to save the old cache"))
.unwrap_or(());
}
// restore the cache
fs::rename(cache, &self.target_dir).and(Ok(self.clone()))
} else {
Err(Error::NotDir(cache))
Err(Error::NotDir(cache).into())
}
}
}
Expand Down
20 changes: 6 additions & 14 deletions src/core.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::{
path::{Path, PathBuf},
result,
};
use std::path::{Path, PathBuf};

use anyhow::Result;

use crate::{
cache::Cache,
errors::Error,
lockfile::Lockfile,
package_manager::PackageManager,
project::ProjectRoot,
Expand All @@ -15,8 +13,6 @@ use crate::{
},
};

pub type Result<T> = result::Result<T, Error>;

pub const APP_NAME: &str = "syncnm";

pub fn run(base_dir: impl AsRef<Path>, cache_dir: Option<impl AsRef<Path>>) -> Result<()> {
Expand All @@ -30,14 +26,10 @@ pub fn run(base_dir: impl AsRef<Path>, cache_dir: Option<impl AsRef<Path>>) -> R
if let Ok(lockfile) = &lockfile {
let cache = Cache::new(&base_dir, &node_modules_dir, cache_dir.as_ref());
let cache_hash_key = generate_cache_key(&base_dir, lockfile, &project_root);
match (cache.as_ref(), cache_hash_key) {
(Ok(cache), Ok(cache_hash_key)) => {
match cache.restore(&base_dir, &cache_hash_key) {
Ok(_) => return Ok(()),
_ => {}
};
if let (Ok(cache), Ok(cache_hash_key)) = (cache.as_ref(), cache_hash_key) {
if cache.restore(&base_dir, &cache_hash_key).is_ok() {
return Ok(());
}
_ => {}
}
if let Ok(cache) = &cache {
// save the current cache before update node_modules and a lockfile
Expand Down
4 changes: 2 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,6 @@ fn stringify_install_command(package_manager: &PackageManager) -> String {
)
}

pub fn to_error<E: Debug>(error: E) -> Error {
Error::Any(format!("{:?}", error))
pub fn to_error<E: Debug>(error: E) -> anyhow::Error {
Error::Any(format!("{:?}", error)).into()
}
25 changes: 12 additions & 13 deletions src/lockfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::Result;
use itertools::Itertools;
use strum::IntoEnumIterator;

use crate::{
core::Result,
errors::{to_error, Error},
package_manager::PackageManagerKind,
utils::{hash::Hashable, option::both_and_then},
Expand Down Expand Up @@ -47,7 +47,7 @@ impl Lockfile {
.iter()
.next()
.map(|(kind, path)| (*kind, path.clone()))
.ok_or(Error::NoLockfile(base_dir)),
.ok_or(Error::NoLockfile(base_dir).into()),
2 =>
// priority to Bun if lockfiles for Bun and Yarn coexist
// Bun has a option to generate yarn.lock (v1) as said in https://bun.sh/docs/install/lockfile
Expand All @@ -57,15 +57,13 @@ impl Lockfile {
kinds.contains_key(&PackageManagerKind::Yarn).then_some(()),
)
.map(|((kind, path), _)| (*kind, path.clone()))
.ok_or(Error::MultipleLockfiles(
base_dir,
kinds.into_values().sorted().collect_vec(),
))
.ok_or(
Error::MultipleLockfiles(base_dir, kinds.into_values().sorted().collect_vec()).into(),
)
}
_ => {
Err(Error::MultipleLockfiles(base_dir, kinds.into_values().sorted().collect_vec()).into())
}
_ => Err(Error::MultipleLockfiles(
base_dir,
kinds.into_values().sorted().collect_vec(),
)),
}
}
}
Expand Down Expand Up @@ -127,19 +125,20 @@ mod tests {
);

#[test]
fn test_new_nope() {
fn test_new_nope() -> Result<()> {
let lockfile = Lockfile::new("tests/fixtures/lockfile/nope");
assert_eq!(
lockfile.unwrap_err(),
lockfile.unwrap_err().downcast::<Error>()?,
Error::NoLockfile(PathBuf::from("tests/fixtures/lockfile/nope"))
);
Ok(())
}

#[test]
fn test_new_multiple() {
let lockfile = Lockfile::new("tests/fixtures/lockfile/multiple");
assert_eq!(
lockfile.unwrap_err(),
lockfile.unwrap_err().downcast::<Error>().unwrap(),
Error::MultipleLockfiles(
PathBuf::from("tests/fixtures/lockfile/multiple"),
[
Expand Down
8 changes: 5 additions & 3 deletions src/package_manager.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::{path::Path, process::Command, vec};

use anyhow::Result;
use serde::{Deserialize, Serialize};
use strum_macros::EnumIter;

use crate::{core::Result, errors::Error};
use crate::errors::Error;

#[derive(Debug, PartialEq, Clone)]
pub struct PackageManager {
Expand Down Expand Up @@ -49,8 +50,9 @@ impl PackageManager {

pub fn execute_install(self, base_dir: impl AsRef<Path>) -> Result<()> {
let base_dir = base_dir.as_ref().to_path_buf();
let to_error =
|message: String| Error::FailedToInstallDependencies(self.clone(), base_dir.clone(), message);
let to_error = |message: String| {
Error::FailedToInstallDependencies(self.clone(), base_dir.clone(), message).into()
};
let output = Command::new(&self.executable_name)
.arg(&self.install_sub_command)
.current_dir(&base_dir)
Expand Down
25 changes: 15 additions & 10 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;

use crate::{
core::Result,
errors::{to_error, Error, Paths},
package_manager::PackageManagerKind,
utils::hash::Hashable,
Expand Down Expand Up @@ -59,8 +59,8 @@ impl PackageJson {
let contents = fs::read_to_string(&file_path);
match contents {
Ok(contents) => serde_json::from_str::<Self>(&contents)
.map_err(|error| Error::Parse(Paths::One(file_path), error.to_string())),
Err(_) => Err(Error::NoEntry(Paths::One(file_path))),
.map_err(|error| Error::Parse(Paths::One(file_path), error.to_string()).into()),
Err(_) => Err(Error::NoEntry(Paths::One(file_path)).into()),
}
}
}
Expand Down Expand Up @@ -104,7 +104,7 @@ impl WorkspacePackage {
fn new(base_dir: impl AsRef<Path>, kind: PackageManagerKind) -> Result<Self> {
let base_dir = base_dir.as_ref().to_path_buf();
if !is_valid_base_dir(&base_dir) {
return Err(Error::InvalidWorkspace(base_dir));
return Err(Error::InvalidWorkspace(base_dir).into());
}
let original = PackageJson::new(&base_dir)?;
Ok(Self {
Expand All @@ -121,10 +121,10 @@ impl WorkspacePackage {
PackageManagerKind::Yarn
if self.original.name.is_none() || self.original.version.is_none() =>
{
Err(Error::InvalidPackageJsonFieldsForYarn(package_json_path))
Err(Error::InvalidPackageJsonFieldsForYarn(package_json_path).into())
}
PackageManagerKind::Bun if self.original.name.is_none() => {
Err(Error::InvalidPackageJsonFieldsForBun(package_json_path))
Err(Error::InvalidPackageJsonFieldsForBun(package_json_path).into())
}
_ => Ok(self),
}
Expand Down Expand Up @@ -197,7 +197,7 @@ impl ProjectRoot {
}
.validate_package_json_fields(&base_dir)
} else {
Err(Error::NoLockfile(base_dir.as_ref().to_path_buf()))
Err(Error::NoLockfile(base_dir.as_ref().to_path_buf()).into())
}
}

Expand Down Expand Up @@ -272,7 +272,9 @@ impl ProjectRoot {
&& !self.original.private.unwrap_or_default() =>
{
Err(
Error::InvalidPackageJsonPrivateForYarn(to_package_json_path(&base_dir)).log_error(None),
Error::InvalidPackageJsonPrivateForYarn(to_package_json_path(&base_dir))
.log_error(None)
.into(),
)
}
_ => Ok(self),
Expand Down Expand Up @@ -434,7 +436,10 @@ mod tests {
assert_eq!(project_root.root, expected.root);
assert_eq!(project_root.workspaces, expected.workspaces);
} else {
assert_eq!(project_root.unwrap_err(), case.expected.unwrap_err());
assert_eq!(
project_root.unwrap_err().downcast::<Error>().unwrap(),
case.expected.unwrap_err().downcast::<Error>().unwrap()
);
}
}

Expand Down Expand Up @@ -524,7 +529,7 @@ mod tests {
PathBuf::from("tests/fixtures/workspaces/yarn_private_false"),
Some(PackageManagerKind::Yarn),
),
expected:Err(Error::InvalidPackageJsonPrivateForYarn(PathBuf::from("tests/fixtures/workspaces/yarn_private_false/package.json")))
expected:Err(Error::InvalidPackageJsonPrivateForYarn(PathBuf::from("tests/fixtures/workspaces/yarn_private_false/package.json")).into())
},
"pnpm" => NewTestCase {
input: (
Expand Down
23 changes: 13 additions & 10 deletions src/utils/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::Result;

use crate::{
core::Result,
errors::{to_error, Error, Paths},
utils::path::to_absolute_path,
};
Expand All @@ -16,14 +17,16 @@ pub fn exists_dir(dir: impl AsRef<Path>) -> Result<PathBuf> {
match &original {
Ok(original) if original.is_dir() => original
.canonicalize()
.map_err(|_| Error::NotAccessible(dir)),
Ok(_) => Err(Error::NotDir(dir)),
Err(_) => Err(Error::NotAccessible(dir)),
.map_err(|_| Error::NotAccessible(dir).into()),
Ok(_) => Err(Error::NotDir(dir).into()),
Err(_) => Err(Error::NotAccessible(dir).into()),
}
} else if dir.is_dir() {
dir.canonicalize().map_err(|_| Error::NotAccessible(dir))
dir
.canonicalize()
.map_err(|_| Error::NotAccessible(dir).into())
} else {
Err(Error::NotDir(dir))
Err(Error::NotDir(dir).into())
}
}

Expand Down Expand Up @@ -79,7 +82,7 @@ mod tests {

struct ExistsDirTestCase {
dir: &'static str,
expected: Result<PathBuf>,
expected: Result<PathBuf, Error>,
}

test_each_serial!(
Expand All @@ -99,7 +102,7 @@ mod tests {
expected_original.canonicalize().unwrap()
)
},
Err(error) => assert_eq!(&result.unwrap_err(), error)
Err(error) => assert_eq!(result.unwrap_err().downcast_ref::<Error>().unwrap(), error)
}

}),
Expand Down Expand Up @@ -194,7 +197,7 @@ mod tests {
});

fs::remove_dir_all(&base_dir).unwrap();
assert_eq!(result, Ok(()));
assert!(result.is_ok());
}

// TODO* fix this test for windows
Expand Down Expand Up @@ -264,6 +267,6 @@ mod tests {
});

fs::remove_dir_all(&base_dir).unwrap();
assert_eq!(result, Ok(()));
assert!(result.is_ok());
}
}
9 changes: 2 additions & 7 deletions src/utils/hash.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::fmt::{Debug, Display};

use anyhow::Result;
use data_encoding::BASE32_NOPAD;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::{core::Result, errors::to_error};
use crate::errors::to_error;

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub struct Hash(pub String);
Expand All @@ -15,12 +16,6 @@ impl Display for Hash {
}
}

impl Hash {
pub fn to_string(&self) -> String {
self.0.to_string()
}
}

pub trait Hashable {
fn to_hash_target(&self) -> Result<impl AsRef<[u8]>>;

Expand Down
Loading

0 comments on commit c535caa

Please sign in to comment.