mirror of
https://github.com/MrBeanCpp/MIT.git
synced 2026-02-03 02:04:09 +08:00
clippy: disable bool comparison
This commit is contained in:
5
clippy.toml
Normal file
5
clippy.toml
Normal file
@@ -0,0 +1,5 @@
|
||||
avoid-breaking-exported-api = false
|
||||
|
||||
# use the various `span_lint_*` methods instead, which also add a link to the docs
|
||||
disallowed-methods = [
|
||||
]
|
||||
@@ -22,8 +22,7 @@ fn search_hash(commit_hash: Hash) -> Option<Hash> {
|
||||
}
|
||||
// commit hash
|
||||
let store = store::Store::new();
|
||||
let commit = store.search(&commit_hash);
|
||||
commit
|
||||
store.search(&commit_hash)
|
||||
}
|
||||
|
||||
fn create_branch(branch_name: String, _base_commit: Hash) -> Result<(), BranchErr> {
|
||||
@@ -70,9 +69,8 @@ fn delete_branch(branch_name: String) -> Result<(), BranchErr> {
|
||||
fn show_current_branch() {
|
||||
println!("show_current_branch");
|
||||
let head = head::current_head();
|
||||
match head {
|
||||
head::Head::Branch(branch_name) => println!("{}", branch_name),
|
||||
_ => (), // do nothing
|
||||
if let head::Head::Branch(branch_name) = head {
|
||||
println!("{}", branch_name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,11 +103,7 @@ pub fn branch(
|
||||
show_current: bool,
|
||||
) {
|
||||
if new_branch.is_some() {
|
||||
let basic_commit = if commit_hash.is_some() {
|
||||
commit_hash.unwrap()
|
||||
} else {
|
||||
head::current_head_commit() // 默认使用当前commit
|
||||
};
|
||||
let basic_commit = commit_hash.unwrap_or_else(head::current_head_commit); // 默认使用当前commit
|
||||
let _ = create_branch(new_branch.unwrap(), basic_commit);
|
||||
} else if delete.is_some() {
|
||||
let _ = delete_branch(delete.unwrap());
|
||||
@@ -134,10 +128,7 @@ mod test {
|
||||
// no commit: invalid object
|
||||
let result = create_branch("test_branch".to_string(), head::current_head_commit());
|
||||
assert!(result.is_err());
|
||||
assert!(match result.unwrap_err() {
|
||||
BranchErr::InvalidObject => true,
|
||||
_ => false,
|
||||
});
|
||||
assert!(matches!(result.unwrap_err(), BranchErr::InvalidObject));
|
||||
assert!(head::list_local_branches().is_empty());
|
||||
|
||||
commands::commit::commit("test commit 1".to_string(), true);
|
||||
@@ -155,10 +146,7 @@ mod test {
|
||||
// branch exist
|
||||
let result = create_branch(new_branch_one.clone(), commit_hash_two.clone());
|
||||
assert!(result.is_err());
|
||||
assert!(match result.unwrap_err() {
|
||||
BranchErr::BranchExist => true,
|
||||
_ => false,
|
||||
});
|
||||
assert!(matches!(result.unwrap_err(), BranchErr::BranchExist));
|
||||
|
||||
// use branch name as commit hash, success
|
||||
let new_branch_two = "test_branch".to_string() + &rand::random::<u32>().to_string();
|
||||
@@ -175,10 +163,7 @@ mod test {
|
||||
// no commit: invalid object
|
||||
let result = delete_branch("test_branch".to_string());
|
||||
assert!(result.is_err());
|
||||
assert!(match result.unwrap_err() {
|
||||
BranchErr::BranchNoExist => true,
|
||||
_ => false,
|
||||
});
|
||||
assert!(matches!(result.unwrap_err(), BranchErr::BranchNoExist));
|
||||
assert!(head::list_local_branches().is_empty());
|
||||
|
||||
commands::commit::commit("test commit 1".to_string(), true);
|
||||
|
||||
@@ -55,14 +55,14 @@ mod test {
|
||||
let head_one = head::current_head_commit();
|
||||
assert!(head_one.is_empty());
|
||||
|
||||
test::ensure_file(&Path::new(test_file), "test content".into());
|
||||
test::ensure_file(Path::new(test_file), "test content".into());
|
||||
cmd::add(vec![], true, false);
|
||||
cmd::commit("test commit 1".to_string(), true);
|
||||
let head_two = head::current_head_commit();
|
||||
assert!(head_two.len() > 0);
|
||||
assert_eq!(head_two.is_empty(), false);
|
||||
|
||||
let commit = models::commit::Commit::load(&head_two);
|
||||
assert_eq!(commit.get_parent_hash().len(), 0);
|
||||
assert_eq!(commit.get_message(), "test commit 1");
|
||||
assert!(commit.get_parent_hash().is_empty());
|
||||
assert!(commit.get_message() == "test commit 1");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn init() -> io::Result<()> {
|
||||
}
|
||||
fs::write(mit_dir.join("HEAD"), "ref: refs/heads/master\n")?;
|
||||
|
||||
set_dir_hidden(&mit_dir.to_str().unwrap())?; // 设置目录隐藏 (跨平台)
|
||||
set_dir_hidden(mit_dir.to_str().unwrap())?; // 设置目录隐藏 (跨平台)
|
||||
println!("Initialized empty mit repository in {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn __log(all: bool, number: Option<usize>) -> usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if commit.get_parent_hash().len() == 0 {
|
||||
if commit.get_parent_hash().is_empty() {
|
||||
break;
|
||||
}
|
||||
head_commit = commit.get_parent_hash().first().unwrap().clone();
|
||||
|
||||
@@ -21,7 +21,7 @@ fn check_ff(current: &Hash, target: Hash) -> Result<bool, MergeErr> {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return Err(MergeErr::NoFastForward);
|
||||
Err(MergeErr::NoFastForward)
|
||||
}
|
||||
|
||||
/** commit 以fast forward到形式合并到当前分支 */
|
||||
@@ -38,9 +38,7 @@ fn merge_ff(commit_hash: String) -> Result<(), MergeErr> {
|
||||
// 检查当前分支是否可以fast forward到commit
|
||||
let current_commit = head::current_head_commit();
|
||||
let check = check_ff(¤t_commit, commit_hash.clone());
|
||||
if check.is_err() {
|
||||
return Err(check.unwrap_err());
|
||||
}
|
||||
check?;
|
||||
|
||||
// 执行fast forward
|
||||
let head = head::current_head();
|
||||
|
||||
@@ -56,7 +56,7 @@ fn preprocess_filters(filters: Option<&Vec<PathBuf>>) -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
/// 转化为绝对路径(to workdir)的HashMap
|
||||
fn preprocess_blobs(blobs: &Vec<(PathBuf, Hash)>) -> HashMap<PathBuf, Hash> {
|
||||
fn preprocess_blobs(blobs: &[(PathBuf, Hash)]) -> HashMap<PathBuf, Hash> {
|
||||
blobs // 转为绝对路径 //TODO tree改变路径表示方式后,这里需要修改
|
||||
.iter()
|
||||
.map(|(path, hash)| (path.to_absolute_workdir(), hash.clone()))
|
||||
@@ -64,7 +64,7 @@ fn preprocess_blobs(blobs: &Vec<(PathBuf, Hash)>) -> HashMap<PathBuf, Hash> {
|
||||
}
|
||||
|
||||
/** 根据filter restore workdir */
|
||||
pub fn restore_worktree(filter: Option<&Vec<PathBuf>>, target_blobs: &Vec<(PathBuf, Hash)>) {
|
||||
pub fn restore_worktree(filter: Option<&Vec<PathBuf>>, target_blobs: &[(PathBuf, Hash)]) {
|
||||
let input_paths = preprocess_filters(filter); //预处理filter 将None转化为workdir
|
||||
let target_blobs = preprocess_blobs(target_blobs); //预处理target_blobs 转化为绝对路径HashMap
|
||||
|
||||
@@ -81,7 +81,7 @@ pub fn restore_worktree(filter: Option<&Vec<PathBuf>>, target_blobs: &Vec<(PathB
|
||||
//文件不存在于workdir
|
||||
if target_blobs.contains_key(path) {
|
||||
//文件存在于target_commit (deleted),需要恢复
|
||||
restore_to_file(&target_blobs[path], &path);
|
||||
restore_to_file(&target_blobs[path], path);
|
||||
} else {
|
||||
//在target_commit和workdir中都不存在(非法路径), 用户输入
|
||||
println!("fatal: pathspec '{}' did not match any files", path.display());
|
||||
@@ -90,16 +90,16 @@ pub fn restore_worktree(filter: Option<&Vec<PathBuf>>, target_blobs: &Vec<(PathB
|
||||
//文件存在,有两种情况:1.修改 2.新文件
|
||||
if target_blobs.contains_key(path) {
|
||||
//文件已修改(modified)
|
||||
let dry_blob = Blob::dry_new(util::read_workfile(&path)); //TODO tree没有存修改时间,所以这里只能用hash判断
|
||||
let dry_blob = Blob::dry_new(util::read_workfile(path)); //TODO tree没有存修改时间,所以这里只能用hash判断
|
||||
if dry_blob.get_hash() != target_blobs[path] {
|
||||
restore_to_file(&target_blobs[path], &path);
|
||||
restore_to_file(&target_blobs[path], path);
|
||||
}
|
||||
} else {
|
||||
//新文件,也分两种情况:1.已跟踪,需要删除 2.未跟踪,保留
|
||||
if index.tracked(path) {
|
||||
//文件已跟踪
|
||||
fs::remove_file(&path).unwrap();
|
||||
util::clear_empty_dir(&path); // 级联删除 清理空目录
|
||||
fs::remove_file(path).unwrap();
|
||||
util::clear_empty_dir(path); // 级联删除 清理空目录
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,12 +107,12 @@ pub fn restore_worktree(filter: Option<&Vec<PathBuf>>, target_blobs: &Vec<(PathB
|
||||
}
|
||||
|
||||
/** 根据filter restore staged */
|
||||
pub fn restore_index(filter: Option<&Vec<PathBuf>>, target_blobs: &Vec<(PathBuf, Hash)>) {
|
||||
pub fn restore_index(filter: Option<&Vec<PathBuf>>, target_blobs: &[(PathBuf, Hash)]) {
|
||||
let input_paths = preprocess_filters(filter); //预处理filter 将None转化为workdir
|
||||
let target_blobs = preprocess_blobs(target_blobs); //预处理target_blobs 转化为绝对路径HashMap
|
||||
|
||||
let index = Index::get_instance();
|
||||
let deleted_files_index = get_index_deleted_files_in_filters(&index, &input_paths, &target_blobs); //统计已删除的文件
|
||||
let deleted_files_index = get_index_deleted_files_in_filters(index, &input_paths, &target_blobs); //统计已删除的文件
|
||||
|
||||
//1.获取index中包含于input_path的文件(使用paths进行过滤)
|
||||
let mut file_paths: HashSet<PathBuf> = util::filter_to_fit_paths(&index.get_tracked_files(), &input_paths);
|
||||
@@ -168,13 +168,13 @@ pub fn restore(paths: Vec<String>, source: Option<String>, worktree: bool, stage
|
||||
if src == "HEAD" {
|
||||
//Default Source
|
||||
head::current_head_commit() // "" if not exist
|
||||
} else if head::list_local_branches().contains(&src) {
|
||||
} else if head::list_local_branches().contains(src) {
|
||||
// Branch Name, e.g. master
|
||||
head::get_branch_head(&src) // "" if not exist
|
||||
head::get_branch_head(src) // "" if not exist
|
||||
} else {
|
||||
// [Commit Hash, e.g. a1b2c3d4] || [Wrong Branch Name]
|
||||
let store = store::Store::new();
|
||||
let commit = store.search(&src);
|
||||
let commit = store.search(src);
|
||||
if commit.is_none() || !util::is_typeof_commit(commit.clone().unwrap()) {
|
||||
println!("fatal: 非法的 commit hash: '{}'", src);
|
||||
return;
|
||||
@@ -243,19 +243,19 @@ mod test {
|
||||
test::ensure_files(&files);
|
||||
|
||||
cmd::add(vec![], true, false);
|
||||
assert_eq!(status::changes_to_be_committed().new.iter().count(), 4);
|
||||
assert_eq!(status::changes_to_be_committed().new.len(), 4);
|
||||
|
||||
cmd::restore(vec!["c.txt".to_string()], None, false, true); //restore c.txt --staged
|
||||
assert_eq!(status::changes_to_be_committed().new.iter().count(), 3);
|
||||
assert_eq!(status::changes_to_be_staged().new.iter().count(), 1);
|
||||
assert_eq!(status::changes_to_be_committed().new.len(), 3);
|
||||
assert_eq!(status::changes_to_be_staged().new.len(), 1);
|
||||
|
||||
fs::remove_file("a.txt").unwrap(); //删除a.txt
|
||||
fs::remove_dir_all("test").unwrap(); //删除test文件夹
|
||||
assert_eq!(status::changes_to_be_staged().deleted.iter().count(), 2);
|
||||
assert_eq!(status::changes_to_be_staged().deleted.len(), 2);
|
||||
|
||||
cmd::restore(vec![".".to_string()], None, true, false); //restore . //from index
|
||||
assert_eq!(status::changes_to_be_committed().new.iter().count(), 3);
|
||||
assert_eq!(status::changes_to_be_staged().new.iter().count(), 1);
|
||||
assert_eq!(status::changes_to_be_staged().deleted.iter().count(), 0);
|
||||
assert_eq!(status::changes_to_be_committed().new.len(), 3);
|
||||
assert_eq!(status::changes_to_be_staged().new.len(), 1);
|
||||
assert_eq!(status::changes_to_be_staged().deleted.len(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn changes_to_be_committed() -> Changes {
|
||||
.iter()
|
||||
.map(|f| f.to_relative_workdir())
|
||||
.collect::<Vec<PathBuf>>();
|
||||
if head_hash == "" {
|
||||
if head_hash.is_empty() {
|
||||
// 初始提交
|
||||
change.new = tracked_files;
|
||||
return change;
|
||||
@@ -147,7 +147,7 @@ pub fn status() {
|
||||
util::check_repo_exist();
|
||||
match head::current_head() {
|
||||
head::Head::Detached(commit) => {
|
||||
println!("HEAD detached at {}", commit[0..7].to_string());
|
||||
println!("HEAD detached at {}", &commit[0..7]);
|
||||
}
|
||||
head::Head::Branch(branch) => {
|
||||
println!("On branch {}", branch);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![allow(clippy::bool_assert_comparison)] // see tree&false directly
|
||||
#![allow(clippy::bool_comparison)] // see tree&false directly
|
||||
mod cli;
|
||||
mod commands;
|
||||
mod models;
|
||||
|
||||
@@ -34,10 +34,10 @@ impl Blob {
|
||||
let mut cmopress_encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
cmopress_encoder.write_all(data.as_bytes()).unwrap();
|
||||
let compressed_data = cmopress_encoder.finish().unwrap();
|
||||
base64::engine::general_purpose::STANDARD_NO_PAD.encode(&compressed_data)
|
||||
base64::engine::general_purpose::STANDARD_NO_PAD.encode(compressed_data)
|
||||
}
|
||||
fn decode(encoded: String) -> String {
|
||||
let compressed_data = base64::engine::general_purpose::STANDARD_NO_PAD.decode(&encoded).unwrap();
|
||||
let compressed_data = base64::engine::general_purpose::STANDARD_NO_PAD.decode(encoded).unwrap();
|
||||
let mut decompress_decoder = GzDecoder::new(&compressed_data[..]);
|
||||
let mut data = String::new();
|
||||
decompress_decoder.read_to_string(&mut data).unwrap();
|
||||
|
||||
@@ -90,7 +90,7 @@ mod test {
|
||||
test::setup_with_clean_mit();
|
||||
|
||||
let index = super::Index::get_instance();
|
||||
let mut commit = super::Commit::new(&index, vec!["123".to_string(), "456".to_string()], "test".to_string());
|
||||
let mut commit = super::Commit::new(index, vec!["123".to_string(), "456".to_string()], "test".to_string());
|
||||
assert_eq!(commit.hash.len(), 0);
|
||||
|
||||
let hash = commit.save();
|
||||
|
||||
@@ -22,7 +22,8 @@ pub fn update_branch(branch_name: &String, commit_hash: &String) {
|
||||
branch.push("refs");
|
||||
branch.push("heads");
|
||||
branch.push(branch_name);
|
||||
std::fs::write(&branch, commit_hash).expect(&format!("无法写入branch in {:?} with {}", branch, commit_hash));
|
||||
std::fs::write(&branch, commit_hash)
|
||||
.unwrap_or_else(|_| panic!("无法写入branch in {:?} with {}", branch, commit_hash));
|
||||
}
|
||||
|
||||
pub fn get_branch_head(branch_name: &String) -> String {
|
||||
@@ -32,8 +33,7 @@ pub fn get_branch_head(branch_name: &String) -> String {
|
||||
branch.push("heads");
|
||||
branch.push(branch_name);
|
||||
if branch.exists() {
|
||||
let commit_hash = std::fs::read_to_string(branch).expect("无法读取branch");
|
||||
commit_hash
|
||||
std::fs::read_to_string(branch).expect("无法读取branch")
|
||||
} else {
|
||||
"".to_string() // 分支不存在或者没有commit
|
||||
}
|
||||
@@ -56,8 +56,7 @@ pub fn current_head_commit() -> String {
|
||||
let head = current_head();
|
||||
match head {
|
||||
Head::Branch(branch_name) => {
|
||||
let commit_hash = get_branch_head(&branch_name);
|
||||
commit_hash
|
||||
get_branch_head(&branch_name)
|
||||
}
|
||||
Head::Detached(commit_hash) => commit_hash,
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ impl Index {
|
||||
fn new() -> Index {
|
||||
let mut index = Index::default();
|
||||
index.load();
|
||||
return index;
|
||||
index
|
||||
}
|
||||
|
||||
/// 单例模式,线程不安全,但是本程序默认单线程
|
||||
@@ -88,7 +88,7 @@ impl Index {
|
||||
|
||||
// 删除文件
|
||||
pub fn remove(&mut self, path: &Path) {
|
||||
let path = Index::preprocess(&path);
|
||||
let path = Index::preprocess(path);
|
||||
self.entries.remove(&path);
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ impl Index {
|
||||
|
||||
/** 获取跟踪的文件列表 */
|
||||
pub fn get_tracked_files(&self) -> Vec<PathBuf> {
|
||||
self.entries.keys().map(|f| f.clone()).collect()
|
||||
self.entries.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn get_tracked_entries(&self) -> HashMap<PathBuf, FileMetaData> {
|
||||
|
||||
@@ -30,12 +30,12 @@ fn store_path_to_tree(index: &Index, current_root: PathBuf) -> Tree {
|
||||
let get_blob_entry = |path: &PathBuf| {
|
||||
let mete = index.get(path).unwrap().clone();
|
||||
let filename = path.file_name().unwrap().to_str().unwrap().to_string();
|
||||
let entry = TreeEntry {
|
||||
|
||||
TreeEntry {
|
||||
filemode: (String::from("blob"), mete.mode),
|
||||
object_hash: mete.hash,
|
||||
name: filename,
|
||||
};
|
||||
entry
|
||||
}
|
||||
};
|
||||
let mut tree = Tree { hash: "".to_string(), entries: Vec::new() };
|
||||
let mut processed_path: HashSet<String> = HashSet::new();
|
||||
@@ -145,15 +145,15 @@ mod test {
|
||||
fn test_new() {
|
||||
test::setup_with_clean_mit();
|
||||
let index = Index::get_instance();
|
||||
for test_file in vec!["b.txt", "mit_src/a.txt", "test/test.txt"] {
|
||||
for test_file in ["b.txt", "mit_src/a.txt", "test/test.txt"] {
|
||||
let test_file = PathBuf::from(test_file);
|
||||
test::ensure_file(&test_file, None);
|
||||
index.add(test_file.clone(), FileMetaData::new(&Blob::new(util::read_workfile(&test_file)), &test_file));
|
||||
}
|
||||
|
||||
let tree = Tree::new(&index);
|
||||
let tree = Tree::new(index);
|
||||
assert!(tree.entries.len() == 3);
|
||||
assert!(tree.hash.len() != 0);
|
||||
assert_eq!(tree.hash.is_empty(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -167,7 +167,7 @@ mod test {
|
||||
index.add(test_file.clone(), FileMetaData::new(&Blob::new(util::read_workfile(&test_file)), &test_file));
|
||||
}
|
||||
|
||||
let tree = Tree::new(&index);
|
||||
let tree = Tree::new(index);
|
||||
let tree_hash = tree.get_hash();
|
||||
|
||||
let loaded_tree = Tree::load(&tree_hash);
|
||||
@@ -190,7 +190,7 @@ mod test {
|
||||
index.add(test_file.clone(), FileMetaData::new(&Blob::new(util::read_workfile(&test_file)), &test_file));
|
||||
}
|
||||
|
||||
let tree = Tree::new(&index);
|
||||
let tree = Tree::new(index);
|
||||
let tree_hash = tree.get_hash();
|
||||
|
||||
let loaded_tree = Tree::load(&tree_hash);
|
||||
|
||||
@@ -9,7 +9,7 @@ pub trait PathExt {
|
||||
fn to_absolute_workdir(&self) -> PathBuf;
|
||||
fn to_relative(&self) -> PathBuf;
|
||||
fn to_relative_workdir(&self) -> PathBuf;
|
||||
fn is_sub_to(&self, parent: &PathBuf) -> bool;
|
||||
fn is_sub_to(&self, parent: &Path) -> bool;
|
||||
fn include_in<T, U>(&self, paths: U) -> bool
|
||||
where
|
||||
T: AsRef<Path>,
|
||||
@@ -22,27 +22,27 @@ pub trait PathExt {
|
||||
impl PathExt for Path {
|
||||
/// 转换为绝对路径
|
||||
fn to_absolute(&self) -> PathBuf {
|
||||
util::get_absolute_path(&self)
|
||||
util::get_absolute_path(self)
|
||||
}
|
||||
|
||||
/// 转换为绝对路径(from workdir相对路径)
|
||||
fn to_absolute_workdir(&self) -> PathBuf {
|
||||
util::to_workdir_absolute_path(&self)
|
||||
util::to_workdir_absolute_path(self)
|
||||
}
|
||||
|
||||
/// 转换为相对路径(to cur_dir)
|
||||
fn to_relative(&self) -> PathBuf {
|
||||
util::get_relative_path(&self)
|
||||
util::get_relative_path(self)
|
||||
}
|
||||
|
||||
/// 转换为相对路径(to workdir)
|
||||
fn to_relative_workdir(&self) -> PathBuf {
|
||||
util::to_workdir_relative_path(&self)
|
||||
util::to_workdir_relative_path(self)
|
||||
}
|
||||
|
||||
/// 从字符串角度判断path是否是parent的子路径(不检测存在性)
|
||||
fn is_sub_to(&self, parent: &PathBuf) -> bool {
|
||||
util::is_sub_path(&self, parent)
|
||||
fn is_sub_to(&self, parent: &Path) -> bool {
|
||||
util::is_sub_path(self, parent)
|
||||
}
|
||||
|
||||
/// 判断是否在paths中(包括子目录),不检查存在
|
||||
@@ -51,6 +51,6 @@ impl PathExt for Path {
|
||||
T: AsRef<Path>,
|
||||
U: IntoIterator<Item = T>,
|
||||
{
|
||||
util::include_in_paths(&self, paths)
|
||||
util::include_in_paths(self, paths)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +58,7 @@ impl Store {
|
||||
result = Some(object);
|
||||
}
|
||||
}
|
||||
match result {
|
||||
None => None,
|
||||
Some(result) => Some(result),
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn save(&self, content: &String) -> Hash {
|
||||
@@ -83,6 +80,7 @@ impl Store {
|
||||
|
||||
pub fn dry_save(&self, content: &String) -> Hash {
|
||||
/* 不实际保存文件,返回Hash */
|
||||
#[warn(clippy::let_and_return)]
|
||||
let hash = Self::calc_hash(content);
|
||||
// TODO more such as check
|
||||
hash
|
||||
@@ -110,7 +108,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_save_and_load() {
|
||||
let _ = test::setup_with_clean_mit();
|
||||
test::setup_with_clean_mit();
|
||||
let store = Store::new();
|
||||
let content = "hello world".to_string();
|
||||
let hash = store.save(&content);
|
||||
|
||||
@@ -15,22 +15,23 @@ use super::util;
|
||||
/* tools for test */
|
||||
fn find_cargo_dir() -> PathBuf {
|
||||
let cargo_path = std::env::var("CARGO_MANIFEST_DIR");
|
||||
if cargo_path.is_err() {
|
||||
// vscode DEBUG test没有CARGO_MANIFEST_DIR宏,手动尝试查找cargo.toml
|
||||
let mut path = util::cur_dir();
|
||||
loop {
|
||||
path.push("Cargo.toml");
|
||||
if path.exists() {
|
||||
break;
|
||||
}
|
||||
if !path.pop() {
|
||||
panic!("找不到CARGO_MANIFEST_DIR");
|
||||
match cargo_path {
|
||||
Ok(path) => PathBuf::from(path),
|
||||
Err(_) => {
|
||||
// vscode DEBUG test没有CARGO_MANIFEST_DIR宏,手动尝试查找cargo.toml
|
||||
let mut path = util::cur_dir();
|
||||
loop {
|
||||
path.push("Cargo.toml");
|
||||
if path.exists() {
|
||||
break;
|
||||
}
|
||||
if !path.pop() {
|
||||
panic!("找不到CARGO_MANIFEST_DIR");
|
||||
}
|
||||
}
|
||||
path.pop();
|
||||
path
|
||||
}
|
||||
path.pop();
|
||||
path
|
||||
} else {
|
||||
PathBuf::from(cargo_path.unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +89,7 @@ pub fn ensure_empty_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
|
||||
|
||||
pub fn setup_with_empty_workdir() {
|
||||
let test_dir = find_cargo_dir().join(TEST_DIR);
|
||||
ensure_empty_dir(&test_dir).unwrap();
|
||||
ensure_empty_dir(test_dir).unwrap();
|
||||
setup_with_clean_mit();
|
||||
}
|
||||
|
||||
@@ -96,12 +97,12 @@ pub fn ensure_file(path: &Path, content: Option<&str>) {
|
||||
// 以测试目录为根目录,创建文件
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap(); // ensure父目录
|
||||
let mut file = fs::File::create(util::get_working_dir().unwrap().join(path))
|
||||
.expect(format!("无法创建文件:{:?}", path).as_str());
|
||||
.unwrap_or_else(|_| panic!("无法创建文件:{:?}", path));
|
||||
if let Some(content) = content {
|
||||
file.write(content.as_bytes()).unwrap();
|
||||
file.write_all(content.as_bytes()).unwrap();
|
||||
} else {
|
||||
// 写入文件名
|
||||
file.write(path.file_name().unwrap().to_str().unwrap().as_bytes()).unwrap();
|
||||
file.write_all(path.file_name().unwrap().to_str().unwrap().as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,7 @@ pub const ROOT_DIR: &str = ".mit";
|
||||
pub fn storage_exist() -> bool {
|
||||
/*检查是否存在储存库 */
|
||||
let rt = get_storage_path();
|
||||
match rt {
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
rt.is_ok()
|
||||
}
|
||||
|
||||
pub fn check_repo_exist() {
|
||||
@@ -47,11 +44,7 @@ pub fn get_storage_path() -> Result<PathBuf, io::Error> {
|
||||
|
||||
/// 获取项目工作区目录, 也就是.mit的父目录
|
||||
pub fn get_working_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = get_storage_path().unwrap().parent() {
|
||||
Some(path.to_path_buf())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
get_storage_path().unwrap().parent().map(|path| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// 检查文件是否在dir内(包括子文件夹), 若不存在则false
|
||||
@@ -112,7 +105,7 @@ where
|
||||
F: Fn(&T) -> T,
|
||||
{
|
||||
//items可以是一个引用
|
||||
items.into_iter().map(|item| func(item)).collect::<O>()
|
||||
items.into_iter().map(func).collect::<O>()
|
||||
}
|
||||
|
||||
/// 过滤列表中的元素,使其在paths中(包括子目录),不检查存在性
|
||||
@@ -132,7 +125,7 @@ pub fn is_inside_repo(file: &Path) -> bool {
|
||||
}
|
||||
|
||||
pub fn format_time(time: &std::time::SystemTime) -> String {
|
||||
let datetime: chrono::DateTime<chrono::Utc> = time.clone().into();
|
||||
let datetime: chrono::DateTime<chrono::Utc> = (*time).into();
|
||||
datetime.format("%Y-%m-%d %H:%M:%S.%3f").to_string()
|
||||
}
|
||||
|
||||
@@ -172,7 +165,7 @@ pub fn include_root_dir(dir: &Path) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
false
|
||||
}
|
||||
|
||||
/// 级联删除空目录,直到遇到 [工作区根目录 | 当前目录]
|
||||
@@ -333,7 +326,7 @@ pub fn get_absolute_path_to_dir(path: &Path, dir: &Path) -> PathBuf {
|
||||
pub fn integrate_paths(paths: &Vec<PathBuf>) -> HashSet<PathBuf> {
|
||||
let mut abs_paths = HashSet::new();
|
||||
for path in paths {
|
||||
let path = get_absolute_path(&path); // 统一转换为绝对路径
|
||||
let path = get_absolute_path(path); // 统一转换为绝对路径
|
||||
if path.is_dir() {
|
||||
// 包括目录下的所有文件(子文件夹)
|
||||
let files = list_files(&path).unwrap();
|
||||
@@ -404,17 +397,17 @@ mod tests {
|
||||
Ok(path) => println!("{:?}", path),
|
||||
Err(err) => match err.kind() {
|
||||
std::io::ErrorKind::NotFound => println!("Not a git repository"),
|
||||
_ => assert!(false, "Unexpected error"),
|
||||
_ => unreachable!("Unexpected error"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_integrate_paths() {
|
||||
let mut paths = Vec::new();
|
||||
paths.push(PathBuf::from("src/utils"));
|
||||
paths.push(PathBuf::from("../test_del.txt"));
|
||||
paths.push(PathBuf::from("src/utils/util.rs"));
|
||||
let paths = ["src/utils", "../test_del.txt", "src/utils/util.rs"]
|
||||
.iter()
|
||||
.map(PathBuf::from)
|
||||
.collect::<Vec<PathBuf>>();
|
||||
// paths.push(PathBuf::from("."));
|
||||
let abs_paths = integrate_paths(&paths);
|
||||
for path in abs_paths {
|
||||
@@ -439,7 +432,7 @@ mod tests {
|
||||
fn test_get_relative_path() {
|
||||
test::setup_with_clean_mit();
|
||||
let path = Path::new("../../src\\main.rs");
|
||||
let rel_path = get_relative_path_to_dir(&path, &cur_dir());
|
||||
let rel_path = get_relative_path_to_dir(path, &cur_dir());
|
||||
println!("{:?}", rel_path);
|
||||
|
||||
assert_eq!(rel_path, path);
|
||||
@@ -492,7 +485,7 @@ mod tests {
|
||||
let content = util::read_workfile(get_working_dir().unwrap().join("test.txt").as_path());
|
||||
let hash = Blob::new(content).get_hash();
|
||||
assert_eq!(check_object_type(hash), ObjectType::Blob);
|
||||
let mut commit = Commit::new(&Index::get_instance(), vec![], "test".to_string());
|
||||
let mut commit = Commit::new(Index::get_instance(), vec![], "test".to_string());
|
||||
assert_eq!(check_object_type(commit.get_tree_hash()), ObjectType::Tree);
|
||||
commit.save();
|
||||
assert_eq!(check_object_type(commit.get_hash()), ObjectType::Commit);
|
||||
@@ -509,10 +502,10 @@ mod tests {
|
||||
fs::remove_dir_all(f).unwrap();
|
||||
}
|
||||
});
|
||||
assert_eq!(include_root_dir(Path::new("./")), true);
|
||||
assert!(include_root_dir(Path::new("./")));
|
||||
fs::create_dir("./src").unwrap_or_default();
|
||||
assert_eq!(include_root_dir(Path::new("./src")), false);
|
||||
fs::create_dir("./src/.mit").unwrap_or_default();
|
||||
assert_eq!(include_root_dir(Path::new("./src")), true);
|
||||
assert!(include_root_dir(Path::new("./src")));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user