step forty eight: merge in working directory

This commit is contained in:
Gonçalo Valério 2020-11-27 00:11:30 +00:00
parent 89287d3f00
commit 8a8b028150
2 changed files with 62 additions and 1 deletions

View File

@ -6,6 +6,9 @@ use walkdir::WalkDir;
#[path = "data.rs"]
mod data;
#[path = "diff.rs"]
mod diff;
pub struct Commit {
pub tree: String,
pub parent: String,
@ -259,7 +262,16 @@ pub fn reset(oid: String) {
)
}
pub fn merge(_oid: String) {}
pub fn merge(oid: String) {
let head = data::get_ref("HEAD".to_owned(), true);
assert!(head.value != "");
let c_head = get_commit(head.value);
let c_other = get_commit(oid);
read_tree_merged(c_head.tree, c_other.tree);
println!("Merged in working tree");
}
fn is_ignored(path: &String) -> bool {
if path.contains(".rgit") {
@ -351,3 +363,18 @@ fn empty_current_directory(dir: &str) -> io::Result<()> {
fn is_branch(name: String) -> bool {
return data::get_ref(name, true).value != "";
}
fn read_tree_merged(head_tree: String, commit_tree: String) {
empty_current_directory(".").unwrap();
let head_tree = get_tree(head_tree, "".to_owned());
let commit_tree = get_tree(commit_tree, "".to_owned());
for (path, blob) in diff::merge_trees(head_tree, commit_tree) {
let mut dirs = Path::new(&path).ancestors();
dirs.next();
let dir = dirs.next().unwrap().to_str().unwrap();
fs::create_dir_all(dir).expect("Cannot create required dirs");
fs::write(path, blob).expect("Cannot write required object");
}
}

View File

@ -90,3 +90,37 @@ pub fn changed_files(
}
return result;
}
pub fn merge_trees(t_head: HashMap<String, String>, t_other: HashMap<String, String>) -> HashMap<String, String> {
let mut tree = HashMap::new();
let trees = vec![t_head, t_other];
for (path, oids) in compare_trees(trees).iter() {
tree.insert(path.clone(), merge_blobs(oids[0].clone(), oids[1].clone()));
}
return tree;
}
fn merge_blobs(o_head: String, o_other: String) -> String {
let f_head = NamedTempFile::new().unwrap();
let f_other = NamedTempFile::new().unwrap();
if o_head != "" {
let content = data::get_object(o_head, "blob".to_owned());
fs::write(f_head.path(), content).unwrap();
}
if o_other != "" {
let content = data::get_object(o_other, "blob".to_owned());
fs::write(f_other.path(), content).unwrap();
}
let output = Command::new("diff")
.arg("-DHEAD")
.arg(f_head.path())
.arg(f_other.path())
.stdout(Stdio::piped())
.output()
.expect("Failed to merge file");
return String::from_utf8_lossy(&output.stdout).to_string();
}