use crate::objects::blob;
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::Path;
pub fn add(file_path_str: &str) -> io::Result<()> {
let git_dir = ".xit";
let file_path = Path::new(file_path_str);
if !Path::new(git_dir).is_dir() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"Not a xit repository (or any of the parent directories): .git",
));
}
if !file_path.is_file() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("pathspec '{}' did not match any files", file_path_str),
));
}
let file_content = fs::read(file_path)?;
let blob_hash = blob::create_blob(&file_content)?;
update_index(file_path_str, &blob_hash)?;
Ok(())
}
fn update_index(file_path: &str, blob_hash: &str) -> io::Result<()> {
let git_dir = ".xit";
let index_path = Path::new(git_dir).join("index");
let mut index_entries: HashMap<String, String> = HashMap::new();
if index_path.exists() {
let file = fs::File::open(&index_path)?;
for line in io::BufReader::new(file).lines() {
let line = line?;
let parts: Vec<&str> = line.splitn(2, ' ').collect();
if parts.len() == 2 {
index_entries.insert(parts[1].to_string(), parts[0].to_string());
}
}
}
index_entries.insert(file_path.to_string(), blob_hash.to_string());
let mut file = fs::File::create(&index_path)?;
for (path, hash) in &index_entries {
writeln!(file, "{} {}", hash, path)?;
}
Ok(())
}