diff --git a/Cargo.lock b/Cargo.lock index a7ed220..05d758b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -559,7 +559,7 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "vault" -version = "1.0.1" +version = "1.2.1" dependencies = [ "chrono", "clap", diff --git a/Cargo.toml b/Cargo.toml index 6be5770..4af3b55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vault" -version = "1.0.1" +version = "1.2.1" edition = "2021" authors = [ "Shubham singh ", diff --git a/src/commands/delete.rs b/src/commands/delete.rs index 940cbae..02d70c2 100644 --- a/src/commands/delete.rs +++ b/src/commands/delete.rs @@ -1,26 +1,58 @@ -use std::fs; -use std::io; - use crate::utils::get_current_branch::get_current_branch; +use crate::utils::yaml_layouts::InitLayout; +use std::fs; +use std::fs::File; +use std::io::{self, BufReader}; +use std::path::{Path,PathBuf}; pub fn delete(branch_to_delete: &str) -> io::Result<()> { if branch_to_delete == "." { let _ = fs::remove_dir_all(".vault"); let _ = fs::remove_file(".vaultignore"); + Ok(()) } else { - let current_branch: Result = get_current_branch(); - match current_branch { - Ok(current_branch) => { - if current_branch == branch_to_delete { - panic!("You can not delete an Active Branch!") - } else { - //@TODO - Get add branches and check if the branch actually exists + let init_file: &Path = Path::new(".vault/init.yaml"); + let file: Result = File::open(&init_file); + match file { + Ok(file) => { + let reader: BufReader = BufReader::new(file); + let mut parsed: InitLayout = + serde_yaml::from_reader(reader).expect("Failed to read YAML"); + let current_branch: Result = get_current_branch(); + match current_branch { + Ok(current_branch) => { + if current_branch == branch_to_delete { + panic!("You can not delete an Active Branch!Kindly switch to another branch first.") + } else { + let exists: bool = does_branch_exists(&branch_to_delete, &parsed); + if exists { + let vault_path: &Path = Path::new(".vault"); + let branch_to_delete_path: PathBuf = vault_path.join(branch_to_delete); + let _ = fs::remove_dir_all(branch_to_delete_path); + parsed.branches.retain(|x| x != branch_to_delete); + let yaml_string: String = serde_yaml::to_string(&parsed).unwrap(); + fs::write(init_file,yaml_string).unwrap(); + Ok(()) + } else { + panic!("Branch not found") + } + } + } + Err(e) => { + panic!("Some Error Occurred: {e}") + } } } - Err(e) => { - panic!("Some Error Occurred: {e}") + Err(_e) => { + panic!( + "Couldn't detect directory as a vault. Kindly Run `vault init` to make a vault" + ) } } } - panic!("Some unknown error occurred!") +} + +fn does_branch_exists(branch_to_check: &str, parsed: &InitLayout) -> bool { + let branch_array: &Vec = &parsed.branches; + branch_array.contains(&branch_to_check.to_string()) }