Init commit

This commit is contained in:
Antonin Ruan
2026-02-19 14:46:58 +01:00
commit f600a89f5b
12 changed files with 993 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
use clap::Parser;
use std::{
fs,
path::Path
};
use crate::git_fs::head::Head;
use crate::subcommands::Subcommand;
use crate::GIT_DIR;
use super::CmdResult;
#[derive(Parser, Debug)]
pub struct InitSubcommand {
directory: Option<String>,
}
impl Subcommand for InitSubcommand {
fn run(&self) -> CmdResult {
let path = match &self.directory {
None => Path::new("."),
Some(path) => Path::new(path),
}.join(GIT_DIR);
let new_repo = path.exists();
match fs::create_dir_all(&path) {
Err(_) => return Err("Error while creating dir".to_owned()),
Ok(()) => (),
};
let folders = [
"objects/info",
"objects/pack",
"refs/heads",
"refs/tags",
];
for folder in folders {
match fs::create_dir_all(&path.join(folder)) {
Err(_) => return Err("".to_owned()),
Ok(()) => (),
};
}
let head = Head { ref_to: String::from("refs/heads/master") };
match head.save() {
Err(_) => return Err("".to_owned()),
Ok(()) => (),
};
let canonical_path = path.canonicalize();
if new_repo {
Ok(format!("Reinitialized exisiting Git repo in {}", canonical_path.unwrap().display()))
} else {
Ok(format!("Initialized empty Git repo in {}", canonical_path.unwrap().display()))
}
}
}