use anyhow::Result; use anyhow::bail; use clap::Parser; use std::{fs, path::Path}; use crate::GIT_DIR; use crate::git_fs::head::Head; use crate::subcommands::Subcommand; #[derive(Parser, Debug)] pub struct InitSubcommand { directory: Option, } impl Subcommand for InitSubcommand { fn run(&self) -> Result { let path = match &self.directory { None => Path::new("."), Some(path) => Path::new(path), } .join(GIT_DIR); let new_repo = path.exists(); if fs::create_dir_all(&path).is_err() { bail!("Error while creating dir") }; let folders = ["objects/info", "objects/pack", "refs/heads", "refs/tags"]; for folder in folders { fs::create_dir_all(path.join(folder))?; } let head = Head { ref_to: String::from("refs/heads/master"), }; head.save()?; let canonical_path = path.canonicalize(); if new_repo { Ok(format!( "Reinitialized exisiting Git repo in {}", canonical_path?.display() )) } else { Ok(format!( "Initialized empty Git repo in {}", canonical_path?.display() )) } } }