rgit/src/data.rs

53 lines
1.5 KiB
Rust
Raw Normal View History

2020-09-29 01:04:28 +02:00
use sha1::{Digest, Sha1};
2020-09-27 14:52:54 +02:00
use std::fs;
2020-09-29 01:04:28 +02:00
use std::str;
2020-09-27 14:52:54 +02:00
static RGIT_DIR: &'static str = ".rgit";
pub fn init() -> std::io::Result<()> {
fs::create_dir(RGIT_DIR)?;
2020-09-29 01:04:28 +02:00
fs::create_dir(format!("{}/{}", RGIT_DIR, "objects"))?;
2020-09-27 14:52:54 +02:00
Ok(())
}
2020-09-29 01:04:28 +02:00
2020-10-05 13:58:48 +02:00
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);
2020-09-29 01:04:28 +02:00
let mut hasher = Sha1::new();
2020-10-05 13:58:48 +02:00
hasher.update(&raw);
2020-09-29 01:04:28 +02:00
let digest = &hasher.finalize();
let s = format!("{:x}", digest);
2020-10-05 13:58:48 +02:00
fs::write(format!("{}/{}/{}", RGIT_DIR, "objects", s), raw.as_slice())
.expect("Failed to write object");
2020-09-29 01:04:28 +02:00
return s;
}
2020-09-29 12:08:12 +02:00
2020-10-05 13:58:48 +02:00
pub fn get_object(hash: String, expected: String) -> String {
let mut content = fs::read_to_string(format!("{}/{}/{}", RGIT_DIR, "objects", hash))
2020-09-29 12:08:12 +02:00
.expect("Could not find a matching object");
2020-10-05 13:58:48 +02:00
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
2020-10-25 19:35:47 +01:00
content.pop();
2020-10-05 13:58:48 +02:00
assert_eq!(expected, content);
}
return data;
2020-09-29 12:08:12 +02:00
}
pub fn update_ref(reference: String, oid: String) {
fs::write(format!("{}/{}", RGIT_DIR, reference), oid).expect("Failed to updated HEAD");
}
2020-11-02 00:01:24 +01:00
pub fn get_ref(reference: String) -> Result<String, Box<dyn std::error::Error + 'static>> {
let oid = fs::read_to_string(format!("{}/{}", RGIT_DIR, reference))?;
2020-11-02 00:01:24 +01:00
return Ok(oid);
}