diff --git a/src/data.rs b/src/data.rs index 297dc13..cdc48ce 100644 --- a/src/data.rs +++ b/src/data.rs @@ -10,22 +10,33 @@ pub fn init() -> std::io::Result<()> { Ok(()) } -pub fn hash_object(content: &Vec) -> String { +pub fn hash_object(content: &Vec, _type: String) -> String { + let mut raw = format!("{}\u{0}", _type).into_bytes(); + let mut data = content.clone(); + raw.append(&mut data); + let mut hasher = Sha1::new(); - hasher.update(content); + hasher.update(&raw); let digest = &hasher.finalize(); let s = format!("{:x}", digest); - fs::write( - format!("{}/{}/{}", RGIT_DIR, "objects", s), - content.as_slice(), - ) - .expect("Failed to write object"); + fs::write(format!("{}/{}/{}", RGIT_DIR, "objects", s), raw.as_slice()) + .expect("Failed to write object"); return s; } -pub fn get_object(hash: String) -> String { - return fs::read_to_string(format!("{}/{}/{}", RGIT_DIR, "objects", hash)) +pub fn get_object(hash: String, expected: String) -> String { + let mut content = fs::read_to_string(format!("{}/{}/{}", RGIT_DIR, "objects", hash)) .expect("Could not find a matching object"); + + let index = content.find(char::from(0)).expect("object type missing"); + let data = content.split_off(index + 1); + + if expected != "".to_owned() { + // Compare the type + assert_eq!(expected, content); + } + + return data; } diff --git a/src/main.rs b/src/main.rs index 39f1a2d..c85cf33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -39,14 +39,17 @@ fn hash_object(matches: ArgMatches) { if let Some(cmd_matches) = matches.subcommand_matches("hash-object") { let content = fs::read(cmd_matches.value_of("file").unwrap()) .expect("Something went wrong reading the provided file"); - let hash = data::hash_object(&content); + let hash = data::hash_object(&content, "blob".to_owned()); println!("{}", hash); } } fn cat_file(matches: ArgMatches) { if let Some(cmd_matches) = matches.subcommand_matches("cat-file") { - let file_contents = data::get_object(cmd_matches.value_of("hash").unwrap().to_owned()); + let file_contents = data::get_object( + cmd_matches.value_of("hash").unwrap().to_owned(), + "".to_owned(), + ); println!("{}", file_contents) } }