step six: add types to objects
This commit is contained in:
parent
98ef42e0d3
commit
f8d970ccdf
29
src/data.rs
29
src/data.rs
|
@ -10,22 +10,33 @@ pub fn init() -> std::io::Result<()> {
|
|||
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();
|
||||
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;
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue