diff --git a/src/cli.rs b/src/cli.rs index e03ffd3..5985c70 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -2,6 +2,7 @@ use clap::{Parser, Subcommand}; use mit::commands::add::add; use mit::commands::commit::commit; use mit::commands::init::init; +use mit::commands::remove::remove; /// Rust实现的简易版本的Git,用于学习Rust语言 #[derive(Parser)] @@ -37,6 +38,9 @@ enum Command { /// flag 删除暂存区的文件 #[clap(long, action)] cached: bool, + /// flag 递归删除目录 + #[clap(short, long)] + recursive: bool, }, /// 提交暂存区的文件 Commit { @@ -51,13 +55,13 @@ pub fn handle_command() { let cli = Cli::parse(); match cli.command { Command::Init => { - let _ = init(); + init().expect("初始化失败"); } Command::Add { files, all, update } => { add(files, all, update); } - Command::Rm { files, cached } => { - println!("rm: {:?}, cached= {}", files, cached); + Command::Rm { files, cached, recursive} => { + remove(files, cached, recursive).expect("删除失败"); } Command::Commit { message, allow_empty, } => { commit(message, allow_empty); diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 0ea1d0c..852962e 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,4 +1,5 @@ pub mod init; pub mod add; pub mod commit; -pub mod status; \ No newline at end of file +pub mod status; +pub mod remove; \ No newline at end of file diff --git a/src/commands/remove.rs b/src/commands/remove.rs new file mode 100644 index 0000000..765d9df --- /dev/null +++ b/src/commands/remove.rs @@ -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, 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(()) +} \ No newline at end of file