Skip to content

Commit

Permalink
feat: hash file
Browse files Browse the repository at this point in the history
  • Loading branch information
mrchantey committed Jan 12, 2025
1 parent e0fa610 commit bcc9b6a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
30 changes: 1 addition & 29 deletions crates/forky_fs/src/fs/fs_ext.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
use crate::prelude::*;
use forky_core::prelude::PathExt;
use std::collections::hash_map::DefaultHasher;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::hash::Hash;
use std::hash::Hasher;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;

Expand Down Expand Up @@ -38,6 +32,7 @@ impl FsExt {
Ok(())
}


// pub fn dir_contains(path: PathBuf, pattern: &str) -> bool {
// let pattern = Pattern::new(pattern).unwrap();
// glob::glob_with(
Expand All @@ -53,29 +48,6 @@ impl FsExt {
// .any(|p| pattern. p.to_str().unwrap().contains(pattern))
// }

pub fn hash_file(path: impl AsRef<Path>) -> io::Result<u64> {
let mut hasher = DefaultHasher::new();
let mut file = fs::File::open(path)?;

let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
buffer.hash(&mut hasher);

let hash = hasher.finish();
Ok(hash)
}



pub fn write<P>(filename: P, data: &str) -> io::Result<()>
where
P: AsRef<Path>,
{
let mut file = File::create(filename)?;
file.write_all(data.as_bytes())?;
Ok(())
}

/// Return the closest ancestor (inclusive) that contains a `Cargo.lock` file
/// # Panics
/// - The current directory is not found
Expand Down
33 changes: 33 additions & 0 deletions crates/forky_fs/src/fs/read_file.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use super::FsError;
use super::FsResult;
use std::fs;
use std::hash::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::path::Path;


Expand All @@ -14,6 +18,24 @@ impl ReadFile {
pub fn to_bytes(path: impl AsRef<Path>) -> FsResult<Vec<u8>> {
std::fs::read(&path).map_err(|e| FsError::from_io_with_file(e, path))
}


pub fn hash_file(path: impl AsRef<Path>) -> FsResult<u64> {
let mut hasher = DefaultHasher::new();
let file = Self::to_bytes(path)?;
file.hash(&mut hasher);
let hash = hasher.finish();
Ok(hash)
}

/// Write a file, ensuring the path exists
pub fn write(path: impl AsRef<Path>, data: &str) -> FsResult<()> {
if let Some(parent) = path.as_ref().parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, data)?;
Ok(())
}
}


Expand Down Expand Up @@ -43,4 +65,15 @@ mod test {
expect(ReadFile::to_bytes(FsExt::test_dir().join("foo.rs")))
.to_be_err();
}


#[test]
fn hash() {
let hash1 =
ReadFile::hash_file(FsExt::test_dir().join("mod.rs")).unwrap();
let hash2 =
ReadFile::hash_file(FsExt::test_dir().join("included_file.rs"))
.unwrap();
expect(hash1).not().to_be(hash2);
}
}

0 comments on commit bcc9b6a

Please sign in to comment.