优化add命令输出

This commit is contained in:
mrbeanc
2023-12-20 22:18:30 +08:00
parent 162313b7bc
commit a573ede3a6
2 changed files with 11 additions and 5 deletions

View File

@@ -29,7 +29,7 @@ pub fn add(files: Vec<String>, all: bool, mut update: bool) {
env::current_dir().unwrap()
};
println!("Working on [{}]\n", path.to_str().unwrap().bright_blue());
files = list_files(&*path).unwrap();
files = list_files(&path).unwrap();
if update {
files.retain(|file|{
index.contains(file)
@@ -47,18 +47,22 @@ pub fn add(files: Vec<String>, all: bool, mut update: bool) {
}
fn add_a_file(file: &Path, index: &mut Index) {
println!("add a file: {}", get_relative_path(file, &*get_working_dir().unwrap()).display());
let relative_path = get_relative_path(file, &get_working_dir().unwrap());
if !file.exists() { //文件被删除
index.remove(file);
println!("removed: {}", relative_path.display());
} else { //文件存在
if !index.contains(file) { //文件未被跟踪
let blob = Blob::new(file);
index.add(file.to_path_buf(), FileMetaData::new(&blob, file));
println!("add(stage): {}", relative_path.display());
} else { //文件已被跟踪,可能被修改
if index.is_modified(file) { //文件被修改,但不一定内容更改
let blob = Blob::new(file); //到这一步才创建blob是为了优化
if !index.verify_hash(file, &blob.get_hash()) { //比较hash 确认内容更改
index.update(file.to_path_buf(), FileMetaData::new(&blob, file));
println!("add(modified): {}", relative_path.display());
}
}
}

View File

@@ -42,7 +42,7 @@ pub struct Index {
}
impl Index {
// 创建索引
/// 从index文件加载
pub(crate) fn new() -> Index {
let mut index = Index {
entries: HashMap::new(),
@@ -78,6 +78,7 @@ impl Index {
Option::from(self.get(file)?.hash.clone())
}
/// 验证文件的hash是否与index中的一致
pub fn verify_hash(&self, file: &Path, hash: &Hash) -> bool {
&self.get_hash(file).unwrap_or_default() == hash
}
@@ -92,7 +93,7 @@ impl Index {
self.entries.contains_key(&path)
}
/// 获取所有已删除的文件
/// 与暂存区比较,获取工作区中被删除的文件
pub fn get_deleted_files(&self) -> Vec<PathBuf> {
let mut files = Vec::new();
self.entries.keys().for_each(|file| {
@@ -125,6 +126,7 @@ impl Index {
self.entries.insert(path, data);
}
/// 从index文件加载数据
fn load(&mut self) {
let path = Index::get_path();
if path.exists() {
@@ -133,13 +135,13 @@ impl Index {
self.entries = relative_index.into_iter()
.map(|(path, value)| {
let abs_path = self.working_dir.join(path);
println!("{}", abs_path.display());
(abs_path, value)
})
.collect();
}
}
/// 获取.mit/index文件绝对路径
pub fn get_path() -> PathBuf {
let mut path = util::get_storage_path().unwrap();
path.push("index");