diff options
author | Rosyid Haryadi <rosyid_haryadi@protonmail.com> | 2025-03-13 16:14:02 +0700 |
---|---|---|
committer | Rosyid Haryadi <rosyid_haryadi@protonmail.com> | 2025-03-13 16:14:02 +0700 |
commit | 85cf6bc2d8d32fb8a75723d4724ddb0f7631b002 (patch) | |
tree | f75faaef431129d0d4d242c1a84dd12c1ae8970f /src/core.rs | |
parent | 79c761f4fc61fbe05bd17ad473d324e052b5db62 (diff) |
upd: init subcommand
Diffstat (limited to 'src/core.rs')
-rw-r--r-- | src/core.rs | 65 |
1 files changed, 55 insertions, 10 deletions
diff --git a/src/core.rs b/src/core.rs index be1edfb..4f9302e 100644 --- a/src/core.rs +++ b/src/core.rs @@ -1,10 +1,10 @@ +use crate::utilities::{die, ConfigHashMap}; +use ini::ini; use std::collections::HashMap; +use std::fs::{create_dir, File}; +use std::io::Write; use std::path::PathBuf; -use std::process; -use ini::ini; - -type ConfigHashMap = HashMap<String, HashMap<String, Option<String>>>; - +use configparser::ini::Ini; pub struct GitRepository { pub worktree: PathBuf, @@ -12,11 +12,6 @@ pub struct GitRepository { conf: HashMap<String, HashMap<String, Option<String>>> } -fn die(msg: &str) { - println!("{}", msg); - process::exit(1); -} - impl GitRepository { pub fn new(worktree: PathBuf) -> Self { let gitdir = worktree.join(".git"); @@ -52,4 +47,54 @@ impl GitRepository { conf } } + + pub fn create_new_repo(worktree: PathBuf) { + let repo = GitRepository::new(worktree); + if repo.worktree.exists() { + if repo.gitdir.exists() { + die("Repo already exists"); + } + } + + let create_gitdir = create_dir(repo.gitdir.clone()); + if let Err(_) = create_gitdir { + die("Failed to initialize repository"); + } + + if let Err(_) = create_dir(repo.gitdir.clone().join("objects")) { + die("Failed to create objects directory"); + } + + if let Err(_) = create_dir(repo.gitdir.clone().join("refs").join("heads")) { + die("Failed to create git refs/head directory"); + } + + if let Err(_) = create_dir(repo.gitdir.clone().join("refs").join("tags")) { + die("Failed to create git refs/tags directory"); + } + + if let Ok(mut head_file) = File::create(repo.gitdir.clone().join("HEAD")) { + if let Err(_) = head_file.write_all(&"ref: refs/heads/master\n".as_ref()) { + die("Failed to write HEAD file"); + } + } else { + die("Failed to create HEAD file"); + } + + let mut config = Ini::new(); + config.set("core", "repositoryformatversion", Some("0".to_owned())); + config.set("core", "filemode", Some("false".to_owned())); + config.set("core", "bare", Some("false".to_owned())); + + if let Err(_) = config.write(repo.gitdir.join("config")) { + die("Failed to write config file"); + } + + + if let Ok(mut description_file) = File::create(repo.gitdir.clone().join("config")) { + if let Err(_) = description_file.write("Unnamed repository; edit this file 'description' to name the repository.\n".as_ref()) { + die("Failed to write description file"); + } + } + } }
\ No newline at end of file |