aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.rs
diff options
context:
space:
mode:
authorTeddy Wing2020-07-21 01:27:37 +0200
committerTeddy Wing2020-07-21 01:32:41 +0200
commit1e883be33f61818e941dd2a147ce1bba85d178ce (patch)
treee002fea57732f01644a9e9a662d2dfbd94b84c91 /src/lib.rs
parentd65b1ab87e4d3dbd7bf7ade653dd64dc5b715368 (diff)
downloadgit-suggestion-1e883be33f61818e941dd2a147ce1bba85d178ce.tar.bz2
Suggesstion: Implement `patch` to generate a patch for the suggestion
Still working on it, but have an initial draft working. There's no file name in the diff hunk, so I'm assuming I'm going to have to add one later. Build a patch from the diff hunk and suggestion comment. 1. Remove `-` lines 2. Change `+` lines to ` ` 3. Change last line to `-` 4. Append suggestion to the diff with a `+` prefix
Diffstat (limited to 'src/lib.rs')
-rw-r--r--src/lib.rs62
1 files changed, 61 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 9343b1f..839ad0b 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2,6 +2,7 @@
use github_rs::client::{Executor, Github};
+use regex::Regex;
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
@@ -63,7 +64,31 @@ pub struct Suggestion {
}
impl Suggestion {
- pub fn patch(&self) {
+ pub fn patch(&self) -> String {
+ let mut diff: Vec<_> = self.diff.lines()
+ .filter(|l| !l.starts_with("-"))
+ .map(|l| {
+ if l.starts_with("+") {
+ return l.replacen("+", " ", 1);
+ }
+
+ l.to_owned()
+ })
+ .collect();
+
+ let last = diff.len() - 1;
+ diff[last] = diff.last().unwrap()
+ .replacen(" ", "-", 1);
+
+ diff.push(self.suggestion());
+
+ diff.join("\n")
+ }
+
+ fn suggestion(&self) -> String {
+ let re = Regex::new(r"(?s).*```\s*suggestion\n").unwrap();
+ let s = re.replace(&self.suggestion, "+");
+ s.replace("```", "")
}
}
@@ -83,4 +108,39 @@ mod tests {
println!("{:?}", suggestion);
}
+
+ #[test]
+ fn suggestion_patch_generates_patch() {
+ let suggestion = Suggestion {
+ diff: r#"@@ -1, 9 +1, 11 @@
+ package command
+
+ import (
++ "bufio" // used to input comment
+ "errors"
+ "fmt"
+ "io"
++ "os" // used to input comment"#.to_owned(),
+ suggestion: r#"It's ok to leave these uncommented
+
+```suggestion
+ "os"
+```"#.to_owned(),
+ };
+
+ assert_eq!(
+ suggestion.patch(),
+ r#"@@ -1, 9 +1, 11 @@
+ package command
+
+ import (
+ "bufio" // used to input comment
+ "errors"
+ "fmt"
+ "io"
+- "os" // used to input comment
++ "os"
+"#,
+ );
+ }
}