Skip to content

Commit

Permalink
refactor: update Hashable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
nokazn committed Mar 30, 2024
1 parent f2e7020 commit 1b97c15
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 28 deletions.
21 changes: 8 additions & 13 deletions src/lockfile.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
use std::{
fs, io,
fs,
path::{Path, PathBuf},
};

use data_encoding::BASE32;
use sha2::{Digest, Sha256};
use strum::IntoEnumIterator;

use crate::{
core::Result,
errors::{to_error, Error},
package_manager::PackageManagerKind,
utils::hash::Hash,
utils::hash::{Hash, Hashable},
};

#[derive(Debug, PartialEq)]
Expand All @@ -20,6 +18,12 @@ pub struct Lockfile {
path: PathBuf,
}

impl Hashable for Lockfile {
fn to_hash_target(&self) -> Result<Vec<u8>> {
fs::read(&self.path).map_err(to_error)
}
}

impl Lockfile {
pub fn new(base_dir: impl AsRef<Path>) -> Result<Self> {
let base_dir = base_dir.as_ref().to_path_buf();
Expand All @@ -40,15 +44,6 @@ impl Lockfile {
}
None
}

pub fn generate_hash(&self) -> Result<Hash> {
let mut file = fs::File::open(&self.path).map_err(to_error)?;
let mut hasher = Sha256::new();
io::copy(&mut file, &mut hasher).map_err(to_error)?;
let raw_hash = hasher.finalize();
let hash = BASE32.encode(&raw_hash);
Ok(Hash(hash))
}
}

#[cfg(test)]
Expand Down
6 changes: 3 additions & 3 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use strum::IntoEnumIterator;

use crate::{
core::Result,
errors::{Error, Paths},
errors::{to_error, Error, Paths},
package_manager::PackageManagerKind,
utils::hash::Hashable,
workspaces::Workspaces,
Expand Down Expand Up @@ -163,7 +163,7 @@ struct ProjectDependencies {
}

impl Hashable for ProjectRoot {
fn to_bytes(&self) -> serde_json::Result<Vec<u8>> {
fn to_hash_target(&self) -> Result<impl AsRef<[u8]>> {
let base = &ProjectDependencies {
root: self.root.clone(),
workspaces: self
Expand All @@ -181,7 +181,7 @@ impl Hashable for ProjectRoot {
})
.collect::<BTreeMap<_, _>>(),
};
serde_json::to_string(base).map(|json| json.into_bytes())
serde_json::to_string(base).map_err(to_error)
}
}

Expand Down
15 changes: 3 additions & 12 deletions src/utils/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,10 @@ impl Hash {
}

pub trait Hashable {
fn to_bytes(&self) -> serde_json::Result<Vec<u8>>
where
Self: serde::Serialize,
{
let json = serde_json::to_string(self)?;
Ok(json.into_bytes())
}
fn to_hash_target(&self) -> Result<impl AsRef<[u8]>>;

fn generate_hash(&self) -> Result<Hash>
where
Self: serde::Serialize + Debug,
{
let bytes = self.to_bytes();
fn generate_hash(&self) -> Result<Hash> {
let bytes = self.to_hash_target();
match bytes {
Ok(bytes) => {
let mut generator = Sha256::new();
Expand Down

0 comments on commit 1b97c15

Please sign in to comment.