From 456cfd543f0ab78b47b8a331a5de4bb2ec8753f8 Mon Sep 17 00:00:00 2001 From: danieleades <33452915+danieleades@users.noreply.github.com> Date: Mon, 22 Jan 2024 05:09:25 +0000 Subject: [PATCH] refactor rust code (#672) * refactor rust code * enforce clippy::all lints * use modern directory layout * put test utils behind a conditional compilation flag * use 'Self' keyword to refer to own type (clippy::use_self) * remove dead code * more tidying --------- Co-authored-by: daniel.eades --- server/Cargo.lock | 89 ++++++----- server/Cargo.toml | 10 ++ server/src/gitignore.rs | 87 +++++------ server/src/lib.rs | 9 +- server/src/{sync/mod.rs => sync.rs} | 151 +++++++++---------- server/src/sync/merkle.rs | 204 +++++++++++++------------- server/src/{utils/mod.rs => utils.rs} | 13 +- 7 files changed, 282 insertions(+), 281 deletions(-) rename server/src/{sync/mod.rs => sync.rs} (80%) rename server/src/{utils/mod.rs => utils.rs} (70%) diff --git a/server/Cargo.lock b/server/Cargo.lock index 9ef0cf647..c662983c8 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -55,9 +55,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "542f33a8835a0884b006a0c3df3dadd99c0c3f296ed26c2fdc8028e01ad6230c" +checksum = "c48f0051a4b4c5e0b6d365cd04af53aeaa209e3cc15ec2cdb69e73cc87fbd0dc" dependencies = [ "memchr", "serde", @@ -139,21 +139,20 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.16" +version = "0.9.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2fe95351b870527a5d09bf563ed3c97c0cffb87cf1c78a591bf48bb218d9aa" +checksum = "0e3681d554572a651dda4186cd47240627c3d0114d45a95f6ad27f2f22e7548d" dependencies = [ "autocfg", "cfg-if", "crossbeam-utils", - "memoffset 0.9.0", ] [[package]] name = "crossbeam-utils" -version = "0.8.17" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f" +checksum = "c3a430a770ebd84726f584a90ee7f020d28db52c6d02138900f22341f866d39c" dependencies = [ "cfg-if", ] @@ -196,9 +195,9 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "futures" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" dependencies = [ "futures-channel", "futures-core", @@ -211,9 +210,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -221,15 +220,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", @@ -238,38 +237,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-macro" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", ] [[package]] name = "futures-sink" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -422,9 +421,9 @@ checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "memchr" -version = "2.6.4" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" [[package]] name = "memoffset" @@ -509,9 +508,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" dependencies = [ "unicode-ident", ] @@ -562,7 +561,7 @@ dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", - "syn 2.0.41", + "syn 2.0.43", ] [[package]] @@ -574,7 +573,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", ] [[package]] @@ -663,7 +662,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", ] [[package]] @@ -716,9 +715,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.41" +version = "2.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269" +checksum = "ee659fb5f3d355364e1f3e5bc10fb82068efbf824a1e9d1c9504244a6469ad53" dependencies = [ "proc-macro2", "quote", @@ -733,35 +732,35 @@ checksum = "14c39fd04924ca3a864207c66fc2cd7d22d7c016007f9ce846cbb9326331930a" [[package]] name = "tempfile" -version = "3.8.1" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" dependencies = [ "cfg-if", "fastrand", "redox_syscall", "rustix", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "thiserror" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" +checksum = "83a48fd946b02c0a526b2e9481c8e2a17755e47039164a86c4070446e3a4614d" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" +checksum = "e7fbe9b594d6568a6a1443250a7e67d80b74e1e96f6d1715e1e21cc1888291d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", ] [[package]] @@ -819,7 +818,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", "wasm-bindgen-shared", ] @@ -841,7 +840,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" dependencies = [ "proc-macro2", "quote", - "syn 2.0.41", + "syn 2.0.43", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/server/Cargo.toml b/server/Cargo.toml index 171bc2914..bd2d84dc8 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -29,3 +29,13 @@ tempfile = "3.8.1" [dev-dependencies] tempfile = "3.8.1" + +[lints.clippy] +all = "deny" +type_complexity = { level = "allow", priority = 1 } # remove me +use_self = "warn" + +[lints.rust] +dead_code = "deny" +missing_copy_implementations = "warn" +missing_debug_implementations = "warn" diff --git a/server/src/gitignore.rs b/server/src/gitignore.rs index 730caa089..f14aeb50e 100644 --- a/server/src/gitignore.rs +++ b/server/src/gitignore.rs @@ -1,51 +1,52 @@ -use std::collections::HashMap; -use std::fs; -use std::io::{self, Read}; -use std::path::{Path, PathBuf}; +// use std::collections::HashMap; +// use std::fs; +// use std::io::{self, Read}; +// use std::path::{Path, PathBuf}; -pub fn local_find_gitignores(workspace_dir: &Path) -> io::Result> { - let mut gitignores = HashMap::new(); - for entry in fs::read_dir(workspace_dir)? { - let entry = entry?; - let path = entry.path(); - if path.is_dir() { - gitignores.extend(local_find_gitignores(&path)?); - } else { - match path.file_name().and_then(|name| name.to_str()) { - Some(file_name) - if file_name.ends_with(".gitignore") - || file_name.ends_with(".continueignore") => - { - let mut contents = String::new(); - fs::File::open(&path)?.read_to_string(&mut contents)?; - gitignores.insert(path, contents); - } - _ => {} - } - } - } - Ok(gitignores) -} +// fn main() -> io::Result<()> { +// let workspace_dir = Path::new("path/to/workspace"); +// let gitignore_map = local_find_gitignores(workspace_dir)?; -fn main() -> io::Result<()> { - let workspace_dir = Path::new("path/to/workspace"); - let gitignore_map = local_find_gitignores(workspace_dir)?; +// // Print out the result (optional) +// for (path, contents) in gitignore_map { +// println!("{}:\n{}", path.display(), contents); +// } - // Print out the result (optional) - for (path, contents) in gitignore_map { - println!("{}:\n{}", path.display(), contents); - } - - Ok(()) -} +// Ok(()) +// } #[cfg(test)] mod tests { - use super::*; + use std::collections::HashMap; use std::fs::{self, File}; - use std::io::Write; + use std::io::{self, Read, Write}; + use std::path::{Path, PathBuf}; use tempfile::tempdir; + pub fn local_find_gitignores(workspace_dir: &Path) -> io::Result> { + let mut gitignores = HashMap::new(); + for entry in fs::read_dir(workspace_dir)? { + let entry = entry?; + let path = entry.path(); + if path.is_dir() { + gitignores.extend(local_find_gitignores(&path)?); + } else { + match path.file_name().and_then(|name| name.to_str()) { + Some(file_name) + if file_name.ends_with(".gitignore") + || file_name.ends_with(".continueignore") => + { + let mut contents = String::new(); + fs::File::open(&path)?.read_to_string(&mut contents)?; + gitignores.insert(path, contents); + } + _ => {} + } + } + } + Ok(gitignores) + } + #[test] fn test_local_find_gitignores() -> io::Result<()> { // Create a temporary directory for the test @@ -59,14 +60,14 @@ mod tests { ("dir3", None, ""), ]; - for (dir, file, contents) in dir_structure.iter() { + for (dir, file, contents) in &dir_structure { let dir_path = temp_path.join(dir); fs::create_dir(&dir_path)?; if let Some(file_name) = file { let file_path = dir_path.join(file_name); let mut file = File::create(file_path)?; - writeln!(file, "{}", contents)?; + writeln!(file, "{contents}")?; } } @@ -74,7 +75,7 @@ mod tests { let gitignores = local_find_gitignores(temp_path)?; // Verify that the returned HashMap contains the correct paths and contents - for (dir, file, contents) in dir_structure.iter() { + for (dir, file, contents) in &dir_structure { if let Some(file_name) = file { let file_path = temp_path.join(dir).join(file_name); assert!(gitignores.contains_key(&file_path)); @@ -93,7 +94,7 @@ mod tests { // Get the current directory let current_dir = std::env::current_dir()?; let parent_dir = current_dir.parent().unwrap(); - let gitignores = local_find_gitignores(&parent_dir)?; + let gitignores = local_find_gitignores(parent_dir)?; // Verify that the returned HashMap contains the correct paths and contents let top_level_gitignore = parent_dir.join(".gitignore"); diff --git a/server/src/lib.rs b/server/src/lib.rs index 041364f77..5975cfbc2 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -2,20 +2,21 @@ use pyo3::{exceptions, prelude::*}; use std::path::Path; mod gitignore; mod sync; +#[cfg(test)] mod utils; #[pyfunction] fn sync_results( - dir: String, - branch: String, + dir: &str, + branch: &str, ) -> PyResult<( Vec<(String, String)>, Vec<(String, String)>, Vec<(String, String)>, Vec<(String, String)>, )> { - return sync::sync(Path::new(&dir), Some(&branch)) - .map_err(|err| PyErr::new::(format!("{}", err))); + return sync::sync(Path::new(dir), Some(branch)) + .map_err(|err| PyErr::new::(format!("{err}"))); } #[pymodule] diff --git a/server/src/sync/mod.rs b/server/src/sync.rs similarity index 80% rename from server/src/sync/mod.rs rename to server/src/sync.rs index ea8697904..e57cee8e0 100644 --- a/server/src/sync/mod.rs +++ b/server/src/sync.rs @@ -1,6 +1,6 @@ mod merkle; use homedir::get_my_home; -use merkle::{build_walk, compute_tree_for_dir, diff, hash_string, ObjectHash}; +use merkle::{compute_tree_for_dir, diff, hash_string}; use std::{ collections::HashMap, fs::{self, File, OpenOptions}, @@ -18,10 +18,10 @@ fn remove_seps_from_path(dir: &Path) -> String { } // Remove leading slash - if path.starts_with("/") || path.starts_with("\\") { + if path.starts_with('/') || path.starts_with('\\') { path.remove(0); } - return path; + path } fn path_for_tag(dir: &Path, branch: Option<&str>) -> PathBuf { @@ -33,21 +33,20 @@ fn path_for_tag(dir: &Path, branch: Option<&str>) -> PathBuf { } else { path.push("main"); } - return path; + path } -/// Stored in ~/.continue/index/.last_sync -fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 { - // TODO: Error handle here - let path = path_for_tag(dir, branch).join(".last_sync"); +// /// Stored in ~/.continue/index/.last_sync +// fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 { +// // TODO: Error handle here +// let path = path_for_tag(dir, branch).join(".last_sync"); - let mut file = File::open(path).unwrap(); - let mut contents = String::new(); - file.read_to_string(&mut contents).unwrap(); +// let mut file = File::open(path).unwrap(); +// let mut contents = String::new(); +// file.read_to_string(&mut contents).unwrap(); - let last_sync_time = contents.parse::().unwrap(); - return last_sync_time; -} +// contents.parse::().unwrap() +// } fn write_sync_time(dir: &Path, branch: Option<&str>) { let path = path_for_tag(dir, branch).join(".last_sync"); @@ -60,23 +59,25 @@ fn write_sync_time(dir: &Path, branch: Option<&str>) { file.write_all(now.to_string().as_bytes()).unwrap(); } -/// Use stat to find files since last sync time -pub fn get_modified_files(dir: &Path, branch: Option<&str>) -> Vec { - let last_sync_time = get_last_sync_time(dir, branch); - let mut modified_files = Vec::new(); - for entry in build_walk(dir) { - let entry = entry.unwrap(); - let path = entry.path(); - let metadata = path.metadata().unwrap(); - let modified = metadata.modified().unwrap(); +// /// Use stat to find files since last sync time +// pub fn get_modified_files(dir: &Path, branch: Option<&str>) -> Vec { +// let last_sync_time = get_last_sync_time(dir, branch); - if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time { - modified_files.push(path.to_path_buf().clone()); - } - } +// build_walk(dir) +// .filter_map(|entry| { +// let entry = entry.unwrap(); +// let path = entry.path(); +// let metadata = path.metadata().unwrap(); +// let modified = metadata.modified().unwrap(); - return modified_files; -} +// if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time { +// Some(path.to_path_buf()) +// } else { +// None +// } +// }) +// .collect() +// } // Merkle trees are unique to directories, even if nested, but .index_cache is shared between all @@ -87,13 +88,13 @@ struct DiskSet { const ITEM_SIZE: usize = 20; impl DiskSet { - pub fn new(path: &str) -> DiskSet { + pub fn new(path: &str) -> Self { let path = Path::new(path); if !path.exists() { File::create(path).unwrap(); } - DiskSet { + Self { file: OpenOptions::new() .read(true) .write(true) @@ -165,7 +166,7 @@ impl IndexCache { fn index_cache_path_for_tag(dir: &Path, branch: &str) -> PathBuf { let mut path = path_for_tag(dir, Some(branch)); path.push(".index_cache"); - return path; + path } fn rev_tags_path(hash: [u8; ITEM_SIZE]) -> PathBuf { @@ -174,20 +175,17 @@ impl IndexCache { path.push(".continue/index/rev_tags"); // Branch by 1) first two chars of hash path.push(&hash_str[0..2]); - return path; + path } fn tag_str(&self) -> String { - return format!("{}::{}", self.dir.to_str().unwrap(), self.branch); + format!("{}::{}", self.dir.to_str().unwrap(), self.branch) } - fn new(dir: &Path, branch: Option<&str>) -> IndexCache { - return IndexCache { + fn new(dir: &Path, branch: Option<&str>) -> Self { + Self { dir: Box::from(dir), - branch: match branch { - Some(branch) => Box::from(branch), - None => Box::from("main"), - }, + branch: Box::from(branch.unwrap_or("main")), global_cache: DiskSet::new( get_my_home() .unwrap() @@ -197,11 +195,11 @@ impl IndexCache { .unwrap(), ), tag_cache: DiskSet::new( - IndexCache::index_cache_path_for_tag(dir, branch.unwrap_or("main")) + Self::index_cache_path_for_tag(dir, branch.unwrap_or("main")) .to_str() .unwrap(), ), - }; + } } // rev_tags files are just json files with the following format: @@ -209,29 +207,27 @@ impl IndexCache { // TODO: You could add_bulk, remove_bulk if this gets slow - fn read_rev_tags(&self, hash: [u8; ITEM_SIZE]) -> HashMap> { - let rev_tags_path = IndexCache::rev_tags_path(hash); + fn read_rev_tags(hash: [u8; ITEM_SIZE]) -> HashMap> { + let rev_tags_path = Self::rev_tags_path(hash); let mut rev_tags_file = OpenOptions::new() .read(true) .write(true) .create(true) - .open(&rev_tags_path) + .open(rev_tags_path) .unwrap(); let mut contents = String::new(); rev_tags_file.read_to_string(&mut contents).unwrap(); - let rev_tags: HashMap> = - serde_json::from_str(&contents).unwrap_or(HashMap::new()); - return rev_tags; + serde_json::from_str(&contents).unwrap_or_default() } - fn write_rev_tags(&self, hash: [u8; ITEM_SIZE], rev_tags: HashMap>) { - let rev_tags_path = IndexCache::rev_tags_path(hash); + fn write_rev_tags(hash: [u8; ITEM_SIZE], rev_tags: &HashMap>) { + let rev_tags_path = Self::rev_tags_path(hash); let mut rev_tags_file = OpenOptions::new() .read(true) .write(true) .create(true) - .open(&rev_tags_path) + .open(rev_tags_path) .unwrap(); let json = serde_json::to_string(&rev_tags).unwrap(); @@ -247,14 +243,14 @@ impl IndexCache { self.tag_cache.add(&item.hash); // Add to rev_tags - let mut rev_tags = self.read_rev_tags(item.hash); + let mut rev_tags = Self::read_rev_tags(item.hash); let tag_str = self.tag_str(); let hash_str = hash_string(item.hash); if !rev_tags.contains_key(hash_str.as_str()) { rev_tags.insert(hash_str.clone(), Vec::new()); } rev_tags.get_mut(hash_str.as_str()).unwrap().push(tag_str); - self.write_rev_tags(item.hash, rev_tags); + Self::write_rev_tags(item.hash, &rev_tags); } fn global_remove(&mut self, item: &ObjDescription) { @@ -262,48 +258,47 @@ impl IndexCache { self.tag_cache.remove(&item.hash); // Remove from rev_tags - let mut rev_tags = self.read_rev_tags(item.hash); - let tag_str = self.tag_str(); + let mut rev_tags = Self::read_rev_tags(item.hash); let hash_str = hash_string(item.hash); if rev_tags.contains_key(hash_str.as_str()) { rev_tags.remove(hash_str.as_str()); } - self.write_rev_tags(item.hash, rev_tags); + Self::write_rev_tags(item.hash, &rev_tags); } fn local_remove(&mut self, item: &ObjDescription) { self.tag_cache.remove(&item.hash); // Remove from rev_tags - let mut rev_tags = self.read_rev_tags(item.hash); + let mut rev_tags = Self::read_rev_tags(item.hash); let tag_str = self.tag_str(); let hash_str = hash_string(item.hash); if rev_tags.contains_key(hash_str.as_str()) { let tags = rev_tags.get_mut(hash_str.as_str()).unwrap(); let index = tags.iter().position(|x| *x == tag_str).unwrap(); tags.remove(index); - if tags.len() == 0 { + if tags.is_empty() { rev_tags.remove(hash_str.as_str()); } } - self.write_rev_tags(item.hash, rev_tags); + Self::write_rev_tags(item.hash, &rev_tags); } fn global_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool { self.global_cache.contains(hash) } - fn tag_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool { - self.tag_cache.contains(&hash) - } + // fn tag_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool { + // self.tag_cache.contains(hash) + // } - fn get_rev_tags(&self, hash: &[u8; ITEM_SIZE]) -> Vec { - let mut rev_tags = self.read_rev_tags(*hash); + fn get_rev_tags(hash: &[u8; ITEM_SIZE]) -> Vec { + let mut rev_tags = Self::read_rev_tags(*hash); let hash_str = hash_string(*hash); if rev_tags.contains_key(hash_str.as_str()) { - return rev_tags.remove(hash_str.as_str()).unwrap(); + rev_tags.remove(hash_str.as_str()).unwrap() } else { - return Vec::new(); + Vec::new() } } } @@ -329,10 +324,8 @@ pub fn sync( let mut tree_path = path_for_tag(dir, branch); tree_path.push("merkle_tree"); - let old_tree: Tree = match Tree::load(&tree_path) { - Ok(tree) => tree, - Err(_) => Tree::empty(), - }; + + let old_tree = Tree::load(&tree_path).unwrap_or_default(); // Calculate and save new tree // TODO: Use modified files to speed up calculation @@ -384,7 +377,7 @@ pub fn sync( continue; } if index_cache.global_contains(&item.hash) { - if index_cache.get_rev_tags(&item.hash).len() <= 1 { + if IndexCache::get_rev_tags(&item.hash).len() <= 1 { // If it's cached only for this tag, remove it from the global cache as well index_cache.global_remove(&item); let hash = hash_string(item.hash); @@ -402,13 +395,13 @@ pub fn sync( } } - return Ok((compute, delete, add_label, remove_label)); + Ok((compute, delete, add_label, remove_label)) } #[cfg(test)] mod tests { use super::*; - use crate::utils::TempDirBuilder; + use crate::{sync::merkle::ObjectHash, utils::TempDirBuilder}; use std::fs::remove_file; #[test] @@ -459,7 +452,7 @@ mod tests { #[test] fn test_sync() { let ti = std::time::Instant::now(); - let results = sync( + let _results = sync( Path::new("/Users/natesesti/Desktop/continue"), Some("nate/pyO3"), ); @@ -469,7 +462,7 @@ mod tests { #[test] fn test_on_vscode_extension() { - let results = sync( + let _results = sync( Path::new("/Users/natesesti/Desktop/continue/extensions/vscode"), Some("nate/pyO3"), ); @@ -484,8 +477,8 @@ mod tests { ) .expect("Sync failed."); println!("First sync took {:?}", ti.elapsed()); - assert!(results.0.len() > 0); - assert!(results.1.len() > 0); + assert!(!results.0.is_empty()); + assert!(!results.1.is_empty()); let ti = std::time::Instant::now(); let results = sync( @@ -514,9 +507,9 @@ mod tests { // Make changes let mut file = File::create(temp_dir.path().join("dir1/file1.txt")).unwrap(); - file.write_all("File 1 changed".as_bytes()).unwrap(); + file.write_all(b"File 1 changed").unwrap(); let mut file = File::create(temp_dir.path().join("dir2/file3.txt")).unwrap(); - file.write_all("File 3 changed".as_bytes()).unwrap(); + file.write_all(b"File 3 changed").unwrap(); // Sync again let results = sync(temp_dir.path(), Some("BRANCH")).expect("Sync failed."); diff --git a/server/src/sync/merkle.rs b/server/src/sync/merkle.rs index 961b174ce..866a56543 100644 --- a/server/src/sync/merkle.rs +++ b/server/src/sync/merkle.rs @@ -3,21 +3,20 @@ use ignore::{Walk, WalkBuilder}; use serde::{Deserialize, Serialize}; use sha1::{Digest, Sha1}; use std::{ - io::{self, Read, Result, Write}, + io::{Read, Result, Write}, path::{Path, PathBuf}, }; pub type ObjectHash = [u8; 20]; pub fn hash_string(hash: ObjectHash) -> String { - let mut result = String::new(); - for byte in hash { - result.push_str(&format!("{:02x}", byte)); - } - return result; + hash.iter().fold(String::new(), |mut output, byte| { + output.push_str(&format!("{byte:02x}")); + output + }) } -#[derive(Clone)] +#[derive(Clone, Default)] pub struct Tree { parent: Option, children: Vec, @@ -48,6 +47,18 @@ enum Object { Blob(Blob), } +impl From for Object { + fn from(tree: Tree) -> Self { + Self::Tree(tree) + } +} + +impl From for Object { + fn from(blob: Blob) -> Self { + Self::Blob(blob) + } +} + pub struct ObjDescription { pub hash: ObjectHash, pub path: String, @@ -57,22 +68,22 @@ pub struct ObjDescription { impl Object { fn hash(&self) -> ObjectHash { match self { - Object::Tree(tree) => tree.hash, - Object::Blob(blob) => blob.hash, + Self::Tree(tree) => tree.hash, + Self::Blob(blob) => blob.hash, } } fn path(&self) -> &String { match self { - Object::Tree(tree) => &tree.path, - Object::Blob(blob) => &blob.path, + Self::Tree(tree) => &tree.path, + Self::Blob(blob) => &blob.path, } } fn json_for_obj(&self) -> String { match self { - Object::Tree(tree) => tree.json_for_obj(), - Object::Blob(blob) => blob.json_for_obj(), + Self::Tree(tree) => tree.json_for_obj(), + Self::Blob(blob) => blob.json_for_obj(), } } @@ -80,15 +91,12 @@ impl Object { return ObjDescription { hash: self.hash(), path: self.path().clone(), - is_blob: match self { - Object::Tree(_) => false, - Object::Blob(_) => true, - }, + is_blob: matches!(self, Self::Blob(_)), }; } /// Return a tuple of (paths to add, paths to remove) - fn diff(&self, new_obj: &Object) -> (Vec, Vec) { + fn diff(&self, new_obj: &Self) -> (Vec, Vec) { let mut add: Vec = Vec::new(); let mut remove: Vec = Vec::new(); @@ -97,7 +105,7 @@ impl Object { } match (self, new_obj) { - (Object::Tree(old_tree), Object::Tree(new_tree)) => { + (Self::Tree(old_tree), Self::Tree(new_tree)) => { // This is where you recurse like below let (child_add, child_remove) = old_tree.diff_children(new_tree); add.push(new_tree.descr()); @@ -105,23 +113,23 @@ impl Object { add.extend(child_add); remove.extend(child_remove); } - (Object::Blob(old_blob), Object::Blob(new_blob)) => { + (Self::Blob(old_blob), Self::Blob(new_blob)) => { add.push(new_blob.descr()); remove.push(old_blob.descr()); } - (Object::Blob(old_blob), Object::Tree(new_tree)) => { + (Self::Blob(old_blob), Self::Tree(new_tree)) => { // Remove blob, add entire new tree remove.push(old_blob.descr()); add.extend(new_tree.all_obj_descriptions()); } - (Object::Tree(old_tree), Object::Blob(new_blob)) => { + (Self::Tree(old_tree), Self::Blob(new_blob)) => { // Remove entire old tree, add blob remove.extend(old_tree.all_obj_descriptions()); add.push(new_blob.descr()); } } - return (add, remove); + (add, remove) } } @@ -140,7 +148,7 @@ pub fn diff(old_tree: &Tree, new_tree: &Tree) -> (Vec, Vec ObjDescription { - return ObjDescription { + ObjDescription { hash: self.hash, path: self.path.clone(), is_blob: true, - }; + } } } -enum DiffType { - Add, - Update, - Remove, -} +// enum DiffType { +// Add, +// Update, +// Remove, +// } + impl Tree { fn descr(&self) -> ObjDescription { - return ObjDescription { + ObjDescription { hash: self.hash, path: self.path.clone(), is_blob: false, - }; + } } fn json_for_node(&self) -> String { let node = SerializeableNode { parent: self.parent, - children: Some(self.children.iter().map(|child| child.hash()).collect()), + children: Some(self.children.iter().map(Object::hash).collect()), hash: self.hash, path: self.path.clone(), }; let mut json = serde_json::to_string(&node).unwrap(); - json.push_str("\n"); - return json; + json.push('\n'); + json } fn json_for_obj(&self) -> String { @@ -201,70 +210,63 @@ impl Tree { result.push_str(&child.json_for_obj()); } - return result; + result } - fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option) -> Tree { - let root_node = match first_line { - Some(line) => line, - None => serde_json::from_str(lines.next().unwrap()).unwrap(), - }; + fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option) -> Self { + let root_node = + first_line.unwrap_or_else(|| serde_json::from_str(lines.next().unwrap()).unwrap()); - let mut children: Vec = Vec::new(); - for child_hash in root_node.children.unwrap() { - let child_jsonl = lines.next().unwrap(); - let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap(); - match child_node.children { - Some(_) => { - let child = Tree::obj_from_jsonl(lines, Some(child_node)); - children.push(Object::Tree(child)); - } - None => { - let child = Blob { + let children = root_node + .children + .unwrap() + .into_iter() + .map(|_child_hash| { + let child_jsonl = lines.next().unwrap(); + let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap(); + if child_node.children.is_some() { + Self::obj_from_jsonl(lines, Some(child_node)).into() + } else { + Blob { parent: child_node.parent, hash: child_node.hash, path: child_node.path, - }; - children.push(Object::Blob(child)); + } + .into() } - } - } + }) + .collect(); - return Tree { + Self { parent: root_node.parent, children, hash: root_node.hash, path: root_node.path, - }; + } } /// Persist the tree to disk as JSONL pub fn persist(&self, filepath: &Path) { if let Some(dir) = filepath.parent() { std::fs::create_dir_all(dir) - .expect(format!("Failed to create dir {}", dir.display()).as_str()); + .unwrap_or_else(|_| panic!("Failed to create dir {}", dir.display())); } let mut file = std::fs::File::create(filepath).unwrap(); file.write_all(self.json_for_obj().as_bytes()).unwrap(); } /// Load the tree from JSONL file - pub fn load(filepath: &Path) -> Result { + pub fn load(filepath: &Path) -> Result { let mut file = std::fs::File::open(filepath)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let mut lines = contents.lines(); - return Ok(Tree::obj_from_jsonl(&mut lines, None)); + Ok(Self::obj_from_jsonl(&mut lines, None)) } - pub fn empty() -> Tree { - return Tree { - parent: None, - children: Vec::new(), - hash: tree_hash(Vec::new()), - path: String::new(), - }; - } + // pub fn empty() -> Self { + // Self::default() + // } fn set_childrens_parent(&mut self) { for child in &mut self.children { @@ -293,12 +295,12 @@ impl Tree { fn all_obj_descriptions(&self) -> Vec { let mut result = Vec::new(); self.walk(&mut |obj| result.push(obj.descr())); - return result; + result } /// Return a list of paths that have changed and the type of change (0 = add, 1 = update, 2 = remove) /// other is considered the "new" tree - fn diff_children(&self, new_tree: &Tree) -> (Vec, Vec) { + fn diff_children(&self, new_tree: &Self) -> (Vec, Vec) { let mut add = Vec::new(); let mut remove = Vec::new(); @@ -331,16 +333,16 @@ impl Tree { } // Remove - along with all children - for (path, obj) in old_path_to_object { + for obj in old_path_to_object.values() { match obj { - Object::Tree(tree) => tree.walk(&mut |obj| { + Object::Tree(tree) => tree.walk(&mut |_obj| { remove.extend(tree.all_obj_descriptions()); }), Object::Blob(_) => remove.push(obj.descr()), } } - return (add, remove); + (add, remove) } } @@ -395,7 +397,7 @@ fn global_ignore_path() -> PathBuf { path.push(".continue"); path.push("index"); path.push(".globalcontinueignore"); - return path; + path } fn create_global_ignore_file() -> PathBuf { @@ -406,11 +408,11 @@ fn create_global_ignore_file() -> PathBuf { let mut file = std::fs::File::create(path).unwrap(); for pattern in GLOBAL_IGNORE_PATTERNS { file.write_all(pattern.as_bytes()).unwrap(); - file.write_all("\n".as_bytes()).unwrap(); + file.write_all(b"\n").unwrap(); } } - return global_ignore_path(); + global_ignore_path() } pub fn build_walk(dir: &Path) -> Walk { @@ -420,48 +422,43 @@ pub fn build_walk(dir: &Path) -> Walk { let builder = binding.add_custom_ignore_filename(".continueignore"); builder.add_ignore(path); - return builder.build(); + builder.build() } fn sha1_hash(content: &str) -> ObjectHash { let mut hasher = Sha1::new(); hasher.update(content); - let result = hasher.finalize(); - let hash_bytes: [u8; 20] = result.into(); - return hash_bytes; + hasher.finalize().into() } fn blob_hash(content: &str, file_ext: &str) -> ObjectHash { - return sha1_hash(&format!("blob {} {}", file_ext, content)); + sha1_hash(&format!("blob {file_ext} {content}")) } fn create_blob(filepath: &Path, parent: Option) -> Result { let content = std::fs::read_to_string(filepath)?; let hash = blob_hash( &content, - match filepath.extension() { - Some(ext) => ext.to_str().unwrap(), - None => "", - }, + filepath.extension().map_or("", |ext| ext.to_str().unwrap()), ); - return Ok(Blob { - parent: parent, - hash: hash, + Ok(Blob { + parent, + hash, path: filepath.to_str().unwrap().to_string(), - }); + }) } -fn tree_hash(children: Vec) -> ObjectHash { +fn tree_hash(children: impl IntoIterator) -> ObjectHash { let mut hasher = Sha1::new(); - hasher.update("tree".as_bytes()); + hasher.update(b"tree"); // Note you're not just concatenating - for child in &children { + for child in children { hasher.update(child); } let result = hasher.finalize(); let hash_bytes: [u8; 20] = result.into(); - return hash_bytes; + hash_bytes } struct PreTree { @@ -474,7 +471,7 @@ impl PreTree { return Tree { parent: None, children: self.children.clone(), - hash: tree_hash(self.children.iter().map(|child| child.hash()).collect()), + hash: tree_hash(self.children.iter().map(Object::hash)), path: self.path.clone(), }; } @@ -482,7 +479,7 @@ impl PreTree { /// Compute merkle tree and all sub-objects /// The last element in the vector is the root of the tree -pub fn compute_tree_for_dir(dir: &Path, parent: Option) -> Result { +pub fn compute_tree_for_dir(dir: &Path, _parent: Option) -> Result { let mut walk = build_walk(dir); let root_entry = walk .next() // This is just "." @@ -535,7 +532,7 @@ pub fn compute_tree_for_dir(dir: &Path, parent: Option) -> Result { + Err(_err) => { // Not UTF-8 formatted. Binary file. Ignore. } } @@ -563,7 +560,7 @@ pub fn compute_tree_for_dir(dir: &Path, parent: Option) -> Result, } impl TempDirBuilder { - pub fn new() -> TempDirBuilder { - return TempDirBuilder { files: Vec::new() }; + pub fn new() -> Self { + Self::default() } - pub fn add(&mut self, path: &str, content: &str) -> &mut TempDirBuilder { + pub fn add(&mut self, path: &str, content: &str) -> &mut Self { self.files.push((path.to_string(), content.to_string())); - return self; + self } pub fn create(&self) -> tempfile::TempDir { @@ -25,9 +26,9 @@ impl TempDirBuilder { fs::create_dir_all(dir).expect("Failed to create directory"); } let mut file = File::create(&file_path).expect("Failed to create test file"); - writeln!(file, "{}", content).expect("Failed to write to test file"); + writeln!(file, "{content}").expect("Failed to write to test file"); } - return temp_dir; + temp_dir } }