aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorTeddy Wing2020-07-25 13:22:04 +0200
committerTeddy Wing2020-07-25 16:56:12 +0200
commitd27d99084b58d19dc76443a03a0db445cbd9bcc7 (patch)
tree2048113386296bbd676ca05f3fe324e213c384d6 /src
parent4b3016a512f6353c2766576d2b8bce2f472ccdf3 (diff)
downloadgit-suggestion-d27d99084b58d19dc76443a03a0db445cbd9bcc7.tar.bz2
Suggestion: Try applying a change to the file (WIP)
Not working yet, but the idea is to get the file referenced by the suggestion and apply the suggested change directly to it. Here, we read the original file, and write its contents to the new file, replacing the lines modified by the suggestion with the suggested change. Currently doesn't work because you can't pass file instances to `fs::rename`, only paths. I'd like to try a slightly different system so I can keep the original file's creation date. With the current system, it would be overwritten by the new temporary file created to store the change.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs
index e4c45c2..b368747 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,11 +1,17 @@
#![warn(rust_2018_idioms)]
+use std::fs;
+use std::fs::File;
+use std::io::{BufRead, BufReader, Write};
+
+use git2::Repository;
use github_rs::client::{Executor, Github};
use regex::Regex;
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
+use tempfile::tempfile;
#[derive(Debug, Error)]
@@ -61,6 +67,11 @@ pub struct Suggestion {
#[serde(rename = "body")]
suggestion: String,
+
+ path: String,
+
+ original_start_line: usize,
+ original_end_line: usize,
}
impl Suggestion {
@@ -90,6 +101,36 @@ impl Suggestion {
let s = re.replace(&self.suggestion, "+");
s.replace("```", "")
}
+
+ fn apply(&self) -> Result<(), Error> {
+ 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 mut new = tempfile().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();
+ } else if i == self.original_end_line {
+ write!(new, "{}", self.suggestion()).unwrap();
+ }
+ },
+ Err(e) => panic!(e),
+ }
+ }
+
+ fs::rename(new, original).unwrap();
+
+ Ok(())
+ }
}
#[cfg(test)]