实现rm(--cached &| -r)

This commit is contained in:
mrbeanc
2023-12-21 17:18:41 +08:00
parent ffefd7f981
commit c812957a80
3 changed files with 53 additions and 4 deletions

View File

@@ -1,4 +1,5 @@
pub mod init;
pub mod add;
pub mod commit;
pub mod status;
pub mod status;
pub mod remove;

44
src/commands/remove.rs Normal file
View File

@@ -0,0 +1,44 @@
use std::{fs, io};
use std::path::PathBuf;
use colored::Colorize;
use crate::models::index::Index;
use crate::utils::util;
use crate::utils::util::check_repo_exist;
/// 从暂存区&|工作区删除文件
pub fn remove(files: Vec<String>, cached: bool, recursive: bool) -> io::Result<()> {
check_repo_exist();
let mut index = Index::new();
for file in files.iter() {
let path = PathBuf::from(file);
if !path.exists() {
println!("Warning: {} not exist", file.red());
continue;
}
if !index.contains(&path) { //不能删除未跟踪的文件
println!("Warning: {} not tracked", file.red());
continue;
}
if path.is_dir() && !recursive {
println!("fatal: not removing '{}' recursively without -r", file.bright_blue());
continue;
}
if path.is_dir() {
let dir_files = util::list_files(&path)?;
for file in dir_files.iter() {
index.remove(file);
}
if !cached {
fs::remove_dir_all(&path)?;
}
} else {
index.remove(&path);
if !cached {
fs::remove_file(&path)?;
}
}
println!("removed [{}]", file.bright_green());
}
Ok(())
}