Skip to content

Commit

Permalink
chore: resolve some clippy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nokazn committed Feb 20, 2024
1 parent 6706d29 commit 92e7926
Show file tree
Hide file tree
Showing 14 changed files with 102 additions and 113 deletions.
12 changes: 6 additions & 6 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct Metadata {

impl Metadata {
pub fn new(cache_dir: impl AsRef<Path>) -> Result<Self> {
const FILE_NAME: &'static str = "metadata.json";
const FILE_NAME: &str = "metadata.json";
let file_path = cache_dir.as_ref().join(FILE_NAME);
let contents = fs::read_to_string(&file_path);
match contents {
Expand All @@ -36,14 +36,14 @@ impl Metadata {
contents,
file_path: file_path.clone(),
})
.map_err(|_| Error::ParseError(Paths::One(file_path))),
.map_err(|_| Error::Parse(Paths::One(file_path))),
Err(_) => {
let v = Self {
file_path: file_path.clone(),
..Self::default()
};
let contents = serde_json::to_string(&v.contents).map_err(to_error)?;
fs::write(&file_path, &contents)?;
fs::write(&file_path, contents)?;
Ok(v)
}
}
Expand All @@ -63,7 +63,7 @@ impl Metadata {
},
};
let json = serde_json::to_string(&contents)
.map_err(|_| Error::ParseError(Paths::One(self.file_path.clone())))?;
.map_err(|_| Error::Parse(Paths::One(self.file_path.clone())))?;
fs::write(&self.file_path, json)?;
Ok(Self {
contents,
Expand All @@ -88,7 +88,7 @@ impl Cache {
target_dir: impl AsRef<Path>,
cache_dir: Option<impl AsRef<Path>>,
) -> Result<Self> {
const DEFAULT_CACHE_DIR: &'static str = ".cache/syncnm";
const DEFAULT_CACHE_DIR: &str = ".cache/syncnm";

let base_dir = fs::exists_dir(base_dir)?;
let target_dir = fs::exists_dir(target_dir)?;
Expand Down Expand Up @@ -130,7 +130,7 @@ impl Cache {
}
fs::rename_dir(cache, &self.target_dir)
} else {
Err(Error::NotDirError(cache))
Err(Error::NotDir(cache))
}
}
}
23 changes: 12 additions & 11 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use crate::{
lockfile::Lockfile,
package_manager::PackageManager,
project::ProjectRoot,
utils::hash::{Hash, Hashable},
utils::{
hash::{Hash, Hashable},
result::both_and_then,
},
};

pub type Result<T> = result::Result<T, Error>;
Expand All @@ -18,25 +21,23 @@ pub fn run(base_dir: impl AsRef<Path>, cache_dir: Option<impl AsRef<Path>>) -> R

let base_dir = base_dir.as_ref().to_path_buf();
let node_modules_dir = &base_dir.join("node_modules");
let cache = Cache::new(&base_dir, &node_modules_dir, cache_dir.as_ref());
let cache = Cache::new(&base_dir, node_modules_dir, cache_dir.as_ref());

if let Ok(lockfile) = &lockfile {
let _ = generate_cache_key(&lockfile, &project_root).map(|cache_key| {
#[allow(unused_must_use)]
let _ = cache
.and_then(|cache| cache.restore(cache_key.to_string()))
.map(|result| {
return result;
});
});
if both_and_then(cache, generate_cache_key(lockfile, &project_root))
.and_then(|(cache, cache_key)| cache.restore(cache_key.to_string()))
.is_ok()
{
return Ok(());
}
}

let package_manager: PackageManager = project_root.kind.into();
package_manager.install(&base_dir)?;

let lockfile = lockfile.or(Lockfile::new(&base_dir))?;
let cache_key = generate_cache_key(&lockfile, &project_root)?;
let cache = Cache::new(&base_dir, &node_modules_dir, cache_dir.as_ref());
let cache = Cache::new(&base_dir, node_modules_dir, cache_dir.as_ref());
cache.and_then(|cache| cache.save(cache_key.to_string()))?;

Ok(())
Expand Down
22 changes: 11 additions & 11 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,37 @@ use crate::{package_manager::PackageManager, utils::path::to_absolute_path};
#[derive(Debug, Error, PartialEq)]
pub enum Error {
#[error("Cannot access to a file or a directory: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
NotAccessibleError(PathBuf),
NotAccessible(PathBuf),

#[error("No such a file or a directory: `{}`", stringify_path(.0))]
NoEntryError(Paths),
NoEntry(Paths),

#[error("Not a directory: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
NotDirError(PathBuf),
NotDir(PathBuf),

#[error("No lockfile at: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
NoLockfileError(PathBuf),
NoLockfile(PathBuf),

#[error("Invalid workspace: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
InvalidWorkspaceError(PathBuf),
InvalidWorkspace(PathBuf),

#[error("\"name\" or \"version\" are missing in: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
InvalidPackageJsonFieldsForYarnError(PathBuf),
InvalidPackageJsonFieldsForYarn(PathBuf),

#[error("\"private\" should be set to `true`: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
InvalidPackageJsonPrivateForYarnError(PathBuf),
InvalidPackageJsonPrivateForYarn(PathBuf),

#[error("\"name\" is missing in: `{}`", stringify_path(&Paths::One(.0.to_path_buf())))]
InvalidPackageJsonFieldsForBunError(PathBuf),
InvalidPackageJsonFieldsForBun(PathBuf),

#[error("Failed to parse: `{}`", stringify_path(.0))]
ParseError(Paths),
Parse(Paths),

#[error("Invalid glob pattern: {:?}", .0)]
InvalidGlobPatternError(&'static str),
InvalidGlobPattern(&'static str),

#[error("Failed to install dependencies by `{}` at: `{:?}`", stringify_install_command(.0), .1)]
FailedToInstallDependenciesError(PackageManager, PathBuf),
FailedToInstallDependencies(PackageManager, PathBuf),

#[error("Error: {:?}", .0)]
Any(String),
Expand Down
2 changes: 1 addition & 1 deletion src/lockfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl Lockfile {
pub fn new(dir_path: impl AsRef<Path>) -> Result<Self> {
match Lockfile::try_to_read_lockfile(&dir_path) {
Some((kind, path)) => Ok(Self { kind, path }),
None => Err(Error::NoLockfileError(dir_path.as_ref().to_path_buf())),
None => Err(Error::NoLockfile(dir_path.as_ref().to_path_buf())),
}
}

Expand Down
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ mod project;
mod utils;
mod workspaces;

use env_logger;

use crate::{core::run, lockfile::Lockfile, project::ProjectRoot, utils::hash::Hashable};

fn main() {
Expand Down
15 changes: 5 additions & 10 deletions src/package_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,27 +49,22 @@ impl PackageManager {
if output.status.success() {
Ok(())
} else {
Err(Error::FailedToInstallDependenciesError(self, base_dir))
Err(Error::FailedToInstallDependencies(self, base_dir))
}
}
}

#[derive(EnumIter, Serialize, Deserialize, Hash, Clone, Copy, Debug, PartialEq)]
#[derive(EnumIter, Serialize, Deserialize, Hash, Clone, Copy, Debug, PartialEq, Default)]
pub enum PackageManagerKind {
#[default]
Npm,
Yarn,
Pnpm,
Bun,
}

impl Default for PackageManagerKind {
fn default() -> Self {
PackageManagerKind::Npm
}
}

impl PackageManagerKind {
pub fn to_lockfile_names(&self) -> Vec<&str> {
pub fn to_lockfile_names(self) -> Vec<&'static str> {
match self {
PackageManagerKind::Npm => vec!["package-lock.json"],
PackageManagerKind::Yarn => vec!["yarn.lock"],
Expand All @@ -78,7 +73,7 @@ impl PackageManagerKind {
}
}

pub fn to_corepack_name(&self) -> Option<&'static str> {
pub fn to_corepack_name(self) -> Option<&'static str> {
match self {
PackageManagerKind::Npm => Some("npm"),
PackageManagerKind::Yarn => Some("yarn"),
Expand Down
37 changes: 20 additions & 17 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ impl PackageJson {
let file_path = to_package_json_path(base_dir);
let contents = fs::read_to_string(&file_path);
match contents {
Ok(contents) => serde_json::from_str::<Self>(&contents)
.map_err(|_| Error::ParseError(Paths::One(file_path))),
Err(_) => Err(Error::NoEntryError(Paths::One(file_path))),
Ok(contents) => {
serde_json::from_str::<Self>(&contents).map_err(|_| Error::Parse(Paths::One(file_path)))
}
Err(_) => Err(Error::NoEntry(Paths::One(file_path))),
}
}
}
Expand Down Expand Up @@ -104,7 +105,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::InvalidWorkspaceError(base_dir));
return Err(Error::InvalidWorkspace(base_dir));
}
let original = PackageJson::new(&base_dir)?;
Ok(Self {
Expand All @@ -121,13 +122,11 @@ impl WorkspacePackage {
PackageManagerKind::Yarn
if self.original.name.is_none() || self.original.version.is_none() =>
{
Err(Error::InvalidPackageJsonFieldsForYarnError(
package_json_path,
))
Err(Error::InvalidPackageJsonFieldsForYarn(package_json_path))
}
PackageManagerKind::Bun if self.original.name.is_none() => {
Err(Error::InvalidPackageJsonFieldsForBun(package_json_path))
}
PackageManagerKind::Bun if self.original.name.is_none() => Err(
Error::InvalidPackageJsonFieldsForBunError(package_json_path),
),
_ => Ok(self),
}
}
Expand Down Expand Up @@ -199,7 +198,7 @@ impl ProjectRoot {
}
.validate_package_json_fields(&base_dir)
} else {
Err(Error::NoLockfileError(base_dir.as_ref().to_path_buf()))
Err(Error::NoLockfile(base_dir.as_ref().to_path_buf()))
}
}

Expand All @@ -212,7 +211,7 @@ impl ProjectRoot {
let mut workspace_map = BTreeMap::<String, WorkspacePackage>::new();
for path in workspaces.packages.iter() {
if let Ok(w) =
WorkspacePackage::new(&path, kind).and_then(|w| w.validate_package_json_fields(path))
WorkspacePackage::new(path, kind).and_then(|w| w.validate_package_json_fields(path))
{
let (name, fallback) = w.get_package_name();
if workspace_map.get(&name).is_none() {
Expand Down Expand Up @@ -245,7 +244,7 @@ impl ProjectRoot {
}
};
match regex
.captures(&package_manager)
.captures(package_manager)
.and_then(|c| c.get(1))
.map(|m| m.as_str())
{
Expand All @@ -265,12 +264,16 @@ impl ProjectRoot {
fn validate_package_json_fields(self, base_dir: impl AsRef<Path>) -> Result<Self> {
match self.kind {
PackageManagerKind::Yarn
if self.original.workspaces.clone().unwrap_or_default().len() > 0
if !self
.original
.workspaces
.clone()
.unwrap_or_default()
.is_empty()
&& !self.original.private.unwrap_or_default() =>
{
Err(
Error::InvalidPackageJsonPrivateForYarnError(to_package_json_path(&base_dir))
.log_error(None),
Error::InvalidPackageJsonPrivateForYarn(to_package_json_path(&base_dir)).log_error(None),
)
}
_ => Ok(self),
Expand Down Expand Up @@ -522,7 +525,7 @@ mod tests {
PathBuf::from("tests/fixtures/workspaces/yarn_private_false"),
Some(PackageManagerKind::Yarn),
),
expected:Err(Error::InvalidPackageJsonPrivateForYarnError(PathBuf::from("tests/fixtures/workspaces/yarn_private_false/package.json")))
expected:Err(Error::InvalidPackageJsonPrivateForYarn(PathBuf::from("tests/fixtures/workspaces/yarn_private_false/package.json")))
},
"pnpm" => NewTestCase {
input: (
Expand Down
16 changes: 5 additions & 11 deletions src/utils/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ pub fn exists_dir(dir: impl AsRef<Path>) -> Result<PathBuf> {
.as_ref()
.to_path_buf()
.canonicalize()
.map_err(|_| Error::NoEntryError(Paths::One(dir.as_ref().to_path_buf())))?;
.map_err(|_| Error::NoEntry(Paths::One(dir.as_ref().to_path_buf())))?;
if dir.is_dir() {
Ok(dir)
} else {
Err(Error::NotDirError(dir))
Err(Error::NotDir(dir))
}
}

Expand All @@ -30,29 +30,23 @@ pub fn make_dir_if_not_exists(dir: impl AsRef<Path>) -> Result<()> {

pub fn rename_dir(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let to = to.as_ref().to_path_buf();
let parent = &to
.parent()
.ok_or(Error::NoEntryError(Paths::One(to.clone())))?;
let parent = &to.parent().ok_or(Error::NoEntry(Paths::One(to.clone())))?;
make_dir_if_not_exists(parent)?;
fs::rename(&from, &to).map_err(to_error)
}

#[cfg(unix)]
pub fn create_symlink_dir(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let to = to.as_ref().to_path_buf();
let parent = &to
.parent()
.ok_or(Error::NoEntryError(Paths::One(to.clone())))?;
let parent = &to.parent().ok_or(Error::NoEntry(Paths::One(to.clone())))?;
make_dir_if_not_exists(parent)?;
std::os::unix::fs::symlink(&from, &to).map_err(to_error)
}

#[cfg(windows)]
pub fn create_symlink_dir(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let to = to.as_ref().to_path_buf();
let parent = &to
.parent()
.ok_or(Error::NoEntryError(Paths::One(to.clone())))?;
let parent = &to.parent().ok_or(Error::NoEntry(Paths::One(to.clone())))?;
make_dir_if_not_exists(parent)?;
std::os::windows::fs::symlink_dir(&from, &to).unwrap();
}
Expand Down
14 changes: 4 additions & 10 deletions src/utils/glob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,7 @@ pub fn collect(
if negate {
entries = entries
.iter()
.filter_map(|entry| {
if matched.iter().any(|p| entry.starts_with(p)) {
None
} else {
Some(entry)
}
})
.filter(|entry| !matched.iter().any(|p| entry.starts_with(p)))
.cloned()
.collect::<Vec<_>>();
} else {
Expand All @@ -42,7 +36,7 @@ pub fn collect(
result
};

run_in_base_dir(&base_dir, collect, None)
run_in_base_dir(base_dir, collect, None)
}

fn resolve_glob(pattern: String, enable_negate: bool) -> (Option<Vec<PathBuf>>, bool) {
Expand All @@ -52,7 +46,7 @@ fn resolve_glob(pattern: String, enable_negate: bool) -> (Option<Vec<PathBuf>>,
let entries = entries
.filter_map(|entry| {
if let Err(error) = &entry {
Error::NotAccessibleError(error.path().to_path_buf())
Error::NotAccessible(error.path().to_path_buf())
.log_debug(error)
.log_warn(None);
}
Expand All @@ -62,7 +56,7 @@ fn resolve_glob(pattern: String, enable_negate: bool) -> (Option<Vec<PathBuf>>,
(Some(entries), negate)
}
Err(error) => {
Error::InvalidGlobPatternError(error.msg).log_warn(None);
Error::InvalidGlobPattern(error.msg).log_warn(None);
(None, negate)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ pub mod glob;
pub mod hash;
pub mod map;
pub mod path;
pub mod result;
pub mod tests;
Loading

0 comments on commit 92e7926

Please sign in to comment.