step six: add types to objects

This commit is contained in:
Gonçalo Valério 2020-10-05 12:58:48 +01:00
parent 98ef42e0d3
commit f8d970ccdf
2 changed files with 25 additions and 11 deletions

View File

@ -10,22 +10,33 @@ pub fn init() -> std::io::Result<()> {
Ok(()) Ok(())
} }
pub fn hash_object(content: &Vec<u8>) -> String { pub fn hash_object(content: &Vec<u8>, _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(); let mut hasher = Sha1::new();
hasher.update(content); hasher.update(&raw);
let digest = &hasher.finalize(); let digest = &hasher.finalize();
let s = format!("{:x}", digest); let s = format!("{:x}", digest);
fs::write( fs::write(format!("{}/{}/{}", RGIT_DIR, "objects", s), raw.as_slice())
format!("{}/{}/{}", RGIT_DIR, "objects", s), .expect("Failed to write object");
content.as_slice(),
)
.expect("Failed to write object");
return s; return s;
} }
pub fn get_object(hash: String) -> String { pub fn get_object(hash: String, expected: String) -> String {
return fs::read_to_string(format!("{}/{}/{}", RGIT_DIR, "objects", hash)) let mut content = fs::read_to_string(format!("{}/{}/{}", RGIT_DIR, "objects", hash))
.expect("Could not find a matching object"); .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;
} }

View File

@ -39,14 +39,17 @@ fn hash_object(matches: ArgMatches) {
if let Some(cmd_matches) = matches.subcommand_matches("hash-object") { if let Some(cmd_matches) = matches.subcommand_matches("hash-object") {
let content = fs::read(cmd_matches.value_of("file").unwrap()) let content = fs::read(cmd_matches.value_of("file").unwrap())
.expect("Something went wrong reading the provided file"); .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); println!("{}", hash);
} }
} }
fn cat_file(matches: ArgMatches) { fn cat_file(matches: ArgMatches) {
if let Some(cmd_matches) = matches.subcommand_matches("cat-file") { 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) println!("{}", file_contents)
} }
} }