mirror of
https://github.com/MrBeanCpp/MIT.git
synced 2026-02-13 07:05:15 +08:00
实现rm(--cached &| -r)
This commit is contained in:
10
src/cli.rs
10
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);
|
||||
|
||||
@@ -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
44
src/commands/remove.rs
Normal 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(())
|
||||
}
|
||||
Reference in New Issue
Block a user