aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorTeddy Wing2020-07-25 16:54:09 +0200
committerTeddy Wing2020-07-25 16:56:12 +0200
commitfe0290e043cdaa533c071aa62eb922b4cf105625 (patch)
tree1912688218ac5b017942590cd8938aa4aacf5602 /src
parentd27d99084b58d19dc76443a03a0db445cbd9bcc7 (diff)
downloadgit-suggestion-fe0290e043cdaa533c071aa62eb922b4cf105625.tar.bz2
Suggestion.apply: Try writing to the original file
Haven't tested this yet. To keep the original file's metadata, try writing the changes to the original instead of the temporary file. First copy the original to a new file that we can reference after truncating the original, then write the change onto the original.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs27
1 files changed, 16 insertions, 11 deletions
diff --git a/src/lib.rs b/src/lib.rs
index b368747..ce0a2ff 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,7 +2,7 @@
use std::fs;
-use std::fs::File;
+use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use git2::Repository;
@@ -11,7 +11,7 @@ use regex::Regex;
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
-use tempfile::tempfile;
+use tempfile::NamedTempFile;
#[derive(Debug, Error)]
@@ -106,29 +106,34 @@ impl Suggestion {
let repo = Repository::open(".").unwrap();
let repo_root = repo.workdir().unwrap();
- let original = File::open(repo_root.join(&self.path)).unwrap();
- let metadata = original.metadata().unwrap();
- let created_at = metadata.created().unwrap();
- let mut reader = BufReader::new(original);
+ // let original = File::open(repo_root.join(&self.path)).unwrap();
+ // let metadata = original.metadata().unwrap();
+ // let created_at = metadata.created().unwrap();
- let mut new = tempfile().unwrap();
+ let new = NamedTempFile::new().unwrap();
+
+ fs::copy(repo_root.join(&self.path), new.path()).unwrap();
+
+ let reader = BufReader::new(new);
+ let mut original = OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .open(repo_root.join(&self.path)).unwrap();
for (i, line) in reader.lines().enumerate() {
match line {
Ok(l) => {
if i < self.original_start_line
|| i > self.original_end_line {
- writeln!(new, "{}", l).unwrap();
+ writeln!(original, "{}", l).unwrap();
} else if i == self.original_end_line {
- write!(new, "{}", self.suggestion()).unwrap();
+ write!(original, "{}", self.suggestion()).unwrap();
}
},
Err(e) => panic!(e),
}
}
- fs::rename(new, original).unwrap();
-
Ok(())
}
}