chore: refator in repository module
Some checks failed
CI checks / Clippy (push) Failing after 26s
CI checks / Format (push) Successful in 25s

This commit is contained in:
Patrick MARIE 2025-02-05 20:17:21 +01:00
parent d1f83c18f3
commit 49ed740014
Signed by: mycroft
GPG Key ID: BB519E5CD8E7BFA7
4 changed files with 191 additions and 141 deletions

View File

@ -1,6 +1,6 @@
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use std::env; use repository::default_init_path;
use std::{fs, path::PathBuf}; use std::path::PathBuf;
use clap::Parser; use clap::Parser;
use clap::Subcommand; use clap::Subcommand;
@ -8,10 +8,10 @@ use clap::Subcommand;
mod error; mod error;
mod kind; mod kind;
mod object; mod object;
mod repository;
mod tree; mod tree;
use crate::object::{read_object, write_blob}; use crate::repository::Repository;
use crate::tree::write_tree;
#[derive(Parser)] #[derive(Parser)]
#[command(name = "mg", about = "A simple git clone")] #[command(name = "mg", about = "A simple git clone")]
@ -45,42 +45,25 @@ enum Command {
}, },
} }
fn default_init_path() -> PathBuf {
env::var("REPO_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
}
fn init_repository(path: PathBuf) -> Result<PathBuf> {
let git_dir = path.join(".git");
fs::create_dir(&git_dir)?;
fs::create_dir(git_dir.join("objects"))?;
fs::create_dir(git_dir.join("refs"))?;
fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n")?;
Ok(path)
}
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let cli = Cli::parse(); let cli = Cli::parse();
let repo_path = default_init_path();
let mut repo = Repository::new()?;
match cli.command { match cli.command {
Command::Init { path } => match init_repository(path) { Command::Init { path } => match repo.init_repository(&path) {
Ok(path) => println!("Initialized empty Git repository in {:?}", path), Ok(path) => println!("Initialized empty Git repository in {:?}", path),
Err(e) => eprintln!("Failed to initialize repository: {}", e), Err(e) => eprintln!("Failed to initialize repository: {}", e),
}, },
Command::CatFile { hash } => match read_object(&repo_path, &hash) { Command::CatFile { hash } => match repo.read_object(&hash) {
Ok(mut obj) => print!("{}", obj.string()?), Ok(mut obj) => print!("{}", obj.string()?),
Err(e) => eprintln!("Failed to read object: {}", e), Err(e) => eprintln!("Failed to read object: {}", e),
}, },
Command::WriteBlob { file } => match write_blob(&repo_path, &file) { Command::WriteBlob { file } => match repo.write_blob(&file) {
Ok(hash) => println!("{}", hex::encode(hash)), Ok(hash) => println!("{}", hex::encode(hash)),
Err(e) => eprintln!("Failed to write object: {}", e), Err(e) => eprintln!("Failed to write object: {}", e),
}, },
Command::WriteTree { path } => match write_tree(&repo_path, &path) { Command::WriteTree { path } => match repo.write_tree(&path) {
Ok(hash) => println!("{}", hex::encode(hash)), Ok(hash) => println!("{}", hex::encode(hash)),
Err(e) => eprintln!("Failed to write tree: {}", e), Err(e) => eprintln!("Failed to write tree: {}", e),
}, },

View File

@ -1,3 +1,4 @@
use crate::repository::Repository;
use crate::{error::RuntimeError, kind::Kind}; use crate::{error::RuntimeError, kind::Kind};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use flate2::{write::ZlibEncoder, Compression}; use flate2::{write::ZlibEncoder, Compression};
@ -24,8 +25,10 @@ pub struct TreeObject {
pub hash: [u8; 20], pub hash: [u8; 20],
} }
pub fn read_object(path: &Path, object: &str) -> Result<Object<impl BufRead>> { impl Repository {
let object_path = path pub fn read_object(&self, object: &str) -> Result<Object<impl BufRead>> {
let object_path = self
.path
.join(".git") .join(".git")
.join("objects") .join("objects")
.join(&object[..2]) .join(&object[..2])
@ -67,36 +70,24 @@ pub fn read_object(path: &Path, object: &str) -> Result<Object<impl BufRead>> {
}) })
} }
fn is_path_in_repo(repo_path: &Path, file_path: &Path) -> Result<bool> { pub fn write_blob(&self, file: &Path) -> Result<[u8; 20]> {
// Convert both paths to absolute paths if !file.exists() || !is_path_in_repo(&self.path, file)? {
let repo_canonical = repo_path.canonicalize()?;
let file_canonical = match file_path.canonicalize() {
Ok(path) => path,
Err(_) => return Ok(false),
};
// Check if file_path starts with repo_path
Ok(file_canonical.starts_with(repo_canonical))
}
pub fn write_blob(repo_path: &Path, file: &Path) -> Result<[u8; 20]> {
if !file.exists() || !is_path_in_repo(repo_path, file)? {
return Err(anyhow!("path does not exist")); return Err(anyhow!("path does not exist"));
} }
let content = std::fs::read(file)?; let content = std::fs::read(file)?;
Ok(write_object(repo_path, Kind::Blob(false), &content)?) Ok(self.write_object(Kind::Blob(false), &content)?)
} }
pub fn write_object(repo_path: &Path, kind: Kind, content: &[u8]) -> Result<[u8; 20]> { pub fn write_object(&self, kind: Kind, content: &[u8]) -> Result<[u8; 20]> {
let mut hasher = Sha1::new(); let mut hasher = Sha1::new();
hasher.update(format!("{} {}\0", kind.string(), content.len()).as_bytes()); hasher.update(format!("{} {}\0", kind.string(), content.len()).as_bytes());
hasher.update(content); hasher.update(content);
let hash = hasher.finalize().into(); let hash = hasher.finalize().into();
let hash_str = hex::encode(hash); let hash_str = hex::encode(hash);
let target_dir = repo_path.join(".git").join("objects").join(&hash_str[..2]); let target_dir = self.path.join(".git").join("objects").join(&hash_str[..2]);
if !target_dir.exists() { if !target_dir.exists() {
create_dir(&target_dir).context("could not create directory in .git/objects")?; create_dir(&target_dir).context("could not create directory in .git/objects")?;
} }
@ -109,7 +100,8 @@ pub fn write_object(repo_path: &Path, kind: Kind, content: &[u8]) -> Result<[u8;
let file_out_fd = File::create(target_file).context("could not open target file")?; let file_out_fd = File::create(target_file).context("could not open target file")?;
let mut zlib_out = ZlibEncoder::new(file_out_fd, Compression::default()); let mut zlib_out = ZlibEncoder::new(file_out_fd, Compression::default());
write!(zlib_out, "{} {}\0", kind.string(), content.len()).context("could not write header")?; write!(zlib_out, "{} {}\0", kind.string(), content.len())
.context("could not write header")?;
zlib_out.write(content)?; zlib_out.write(content)?;
zlib_out zlib_out
.finish() .finish()
@ -117,6 +109,19 @@ pub fn write_object(repo_path: &Path, kind: Kind, content: &[u8]) -> Result<[u8;
Ok(hash) Ok(hash)
} }
}
fn is_path_in_repo(repo_path: &Path, file_path: &Path) -> Result<bool> {
// Convert both paths to absolute paths
let repo_canonical = repo_path.canonicalize()?;
let file_canonical = match file_path.canonicalize() {
Ok(path) => path,
Err(_) => return Ok(false),
};
// Check if file_path starts with repo_path
Ok(file_canonical.starts_with(repo_canonical))
}
impl<R: BufRead> Object<R> { impl<R: BufRead> Object<R> {
pub fn string(&mut self) -> Result<String> { pub fn string(&mut self) -> Result<String> {

57
src/repository.rs Normal file
View File

@ -0,0 +1,57 @@
use anyhow::Result;
use std::{
env,
fs::{create_dir, read_to_string},
path::PathBuf,
};
pub struct Repository {
pub path: PathBuf,
pub ignore: Vec<String>,
}
pub fn default_init_path() -> PathBuf {
env::var("REPO_PATH")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
}
impl Repository {
pub fn new() -> Result<Repository> {
let path = default_init_path();
let mut repo = Repository {
path,
ignore: Vec::new(),
};
repo.load_ignore()?;
Ok(repo)
}
fn load_ignore(&mut self) -> Result<bool> {
let ignore_path = self.path.join(".gitignore");
if !ignore_path.exists() {
return Ok(false);
}
let ignore_content = read_to_string(ignore_path)?;
self.ignore = ignore_content.lines().map(String::from).collect();
Ok(true)
}
pub fn init_repository(&mut self, path: &PathBuf) -> Result<PathBuf> {
self.path = path.clone();
let git_dir = self.path.join(".git");
create_dir(&git_dir)?;
create_dir(git_dir.join("objects"))?;
create_dir(git_dir.join("refs"))?;
std::fs::write(git_dir.join("HEAD"), "ref: refs/heads/main\n")?;
Ok(self.path.clone())
}
}

View File

@ -3,9 +3,11 @@ use std::os::unix::fs::MetadataExt;
use std::path::PathBuf; use std::path::PathBuf;
use crate::kind::Kind; use crate::kind::Kind;
use crate::object::{write_blob, write_object, TreeObject}; use crate::object::TreeObject;
use crate::repository::Repository;
pub fn write_tree(repo_path: &PathBuf, path: &PathBuf) -> Result<[u8; 20]> { impl Repository {
pub fn write_tree(&self, path: &PathBuf) -> Result<[u8; 20]> {
let mut entries = Vec::new(); let mut entries = Vec::new();
let files = std::fs::read_dir(path)?; let files = std::fs::read_dir(path)?;
@ -24,10 +26,12 @@ pub fn write_tree(repo_path: &PathBuf, path: &PathBuf) -> Result<[u8; 20]> {
let kind; let kind;
if file_type.is_dir() { if file_type.is_dir() {
hash = write_tree(repo_path, &file_path).context("could not write_tree of subtree")?; hash = self
.write_tree(&file_path)
.context("could not write_tree of subtree")?;
kind = Kind::Tree; kind = Kind::Tree;
} else { } else {
hash = write_blob(repo_path, &file_path).context(format!( hash = self.write_blob(&file_path).context(format!(
"could not write object {:?}", "could not write object {:?}",
file_path.file_name() file_path.file_name()
))?; ))?;
@ -53,5 +57,6 @@ pub fn write_tree(repo_path: &PathBuf, path: &PathBuf) -> Result<[u8; 20]> {
out.extend_from_slice(&entry.hash); out.extend_from_slice(&entry.hash);
} }
write_object(repo_path, Kind::Tree, &out).context("Write") self.write_object(Kind::Tree, &out).context("Write")
}
} }