| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8 | pub enum Part { |
| 9 | Text(String), |
| 10 | Suggestion(Vec<String>), |
| 11 | } |
| 12 | |
| 13 | |
| 14 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 15 | pub enum ApplyError { |
| 16 | |
| 17 | OutOfRange, |
| 18 | |
| 19 | Changed, |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | pub fn split_body(body: &str) -> Vec<Part> { |
| 26 | let lines: Vec<&str> = body.split('\n').collect(); |
| 27 | let mut parts = Vec::new(); |
| 28 | let mut text: Vec<&str> = Vec::new(); |
| 29 | let mut i = 0; |
| 30 | while i < lines.len() { |
| 31 | if let Some(ticks) = open_fence(lines[i]) { |
| 32 | let close = (i + 1..lines.len()).find(|&j| closes_fence(lines[j], ticks)); |
| 33 | if let Some(close) = close { |
| 34 | if !text.is_empty() { |
| 35 | parts.push(Part::Text(text.join("\n"))); |
| 36 | text.clear(); |
| 37 | } |
| 38 | let block = lines[i + 1..close] |
| 39 | .iter() |
| 40 | .map(|line| line.trim_end_matches('\r').to_owned()) |
| 41 | .collect(); |
| 42 | parts.push(Part::Suggestion(block)); |
| 43 | i = close + 1; |
| 44 | continue; |
| 45 | } |
| 46 | } |
| 47 | text.push(lines[i]); |
| 48 | i += 1; |
| 49 | } |
| 50 | if !text.is_empty() { |
| 51 | parts.push(Part::Text(text.join("\n"))); |
| 52 | } |
| 53 | parts |
| 54 | } |
| 55 | |
| 56 | |
| 57 | fn open_fence(line: &str) -> Option<usize> { |
| 58 | let ticks = line.bytes().take_while(|&b| b == b'`').count(); |
| 59 | (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks) |
| 60 | } |
| 61 | |
| 62 | |
| 63 | fn closes_fence(line: &str, ticks: usize) -> bool { |
| 64 | let trimmed = line.trim(); |
| 65 | trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`') |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | pub fn hunk_line(diff_hunk: &str) -> Option<&str> { |
| 71 | let last = diff_hunk.lines().last()?; |
| 72 | match last.as_bytes().first()? { |
| 73 | b'+' | b' ' => Some(&last[1..]), |
| 74 | _ => None, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | pub fn replace_line( |
| 81 | text: &str, |
| 82 | line: u32, |
| 83 | expected: &str, |
| 84 | replacement: &[String], |
| 85 | ) -> Result<String, ApplyError> { |
| 86 | if text.is_empty() { |
| 87 | return Err(ApplyError::OutOfRange); |
| 88 | } |
| 89 | let index = (line as usize) |
| 90 | .checked_sub(1) |
| 91 | .ok_or(ApplyError::OutOfRange)?; |
| 92 | let ends_with_newline = text.ends_with('\n'); |
| 93 | let body = text.strip_suffix('\n').unwrap_or(text); |
| 94 | let mut lines: Vec<&str> = body.split('\n').collect(); |
| 95 | let current = lines.get(index).ok_or(ApplyError::OutOfRange)?; |
| 96 | if current.trim_end_matches('\r') != expected.trim_end_matches('\r') { |
| 97 | return Err(ApplyError::Changed); |
| 98 | } |
| 99 | let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect(); |
| 100 | lines.splice(index..=index, replacement); |
| 101 | let mut out = lines.join("\n"); |
| 102 | if ends_with_newline { |
| 103 | out.push('\n'); |
| 104 | } |
| 105 | Ok(out) |
| 106 | } |
| 107 | |
| 108 | #[cfg(test)] |
| 109 | mod tests { |
| 110 | use super::*; |
| 111 | |
| 112 | fn lines(items: &[&str]) -> Vec<String> { |
| 113 | items.iter().map(|s| s.to_string()).collect() |
| 114 | } |
| 115 | |
| 116 | #[test] |
| 117 | fn split_body_cases() { |
| 118 | let cases: Vec<(&str, Vec<Part>)> = vec![ |
| 119 | ( |
| 120 | "looks fine\n\n```rust\nlet x = 1;\n```", |
| 121 | vec![Part::Text("looks fine\n\n```rust\nlet x = 1;\n```".into())], |
| 122 | ), |
| 123 | ( |
| 124 | "Try this:\n```suggestion\nlet y = 2;\n```\nThanks", |
| 125 | vec![ |
| 126 | Part::Text("Try this:".into()), |
| 127 | Part::Suggestion(lines(&["let y = 2;"])), |
| 128 | Part::Text("Thanks".into()), |
| 129 | ], |
| 130 | ), |
| 131 | ( |
| 132 | "```suggestion\n```\n\n````suggestion\na\n```\nb\n````", |
| 133 | vec![ |
| 134 | Part::Suggestion(vec![]), |
| 135 | Part::Text("".into()), |
| 136 | Part::Suggestion(lines(&["a", "```", "b"])), |
| 137 | ], |
| 138 | ), |
| 139 | ( |
| 140 | "```suggestion\nlet y = 2;", |
| 141 | vec![Part::Text("```suggestion\nlet y = 2;".into())], |
| 142 | ), |
| 143 | ]; |
| 144 | for (body, want) in cases { |
| 145 | assert_eq!(split_body(body), want, "case {body:?}"); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | #[test] |
| 150 | fn hunk_last_line_gives_the_commented_text() { |
| 151 | assert_eq!(hunk_line("-old\n+let x = 1;"), Some("let x = 1;")); |
| 152 | assert_eq!(hunk_line(" ctx\n more"), Some("more")); |
| 153 | assert_eq!(hunk_line("+a\n-gone"), None); |
| 154 | assert_eq!(hunk_line(""), None); |
| 155 | } |
| 156 | |
| 157 | #[test] |
| 158 | fn replace_line_cases() { |
| 159 | |
| 160 | type Case<'a> = ( |
| 161 | &'a str, |
| 162 | u32, |
| 163 | &'a str, |
| 164 | &'a [&'a str], |
| 165 | Result<&'a str, ApplyError>, |
| 166 | ); |
| 167 | let cases: Vec<Case<'_>> = vec![ |
| 168 | ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")), |
| 169 | ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")), |
| 170 | ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")), |
| 171 | ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)), |
| 172 | ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)), |
| 173 | ("a\n", 0, "a", &["x"], Err(ApplyError::OutOfRange)), |
| 174 | ("", 1, "", &["x"], Err(ApplyError::OutOfRange)), |
| 175 | ("a\r\nb\r\n", 1, "a", &["A"], Ok("A\nb\r\n")), |
| 176 | ]; |
| 177 | for (text, line, expect, new, want) in cases { |
| 178 | let got = replace_line(text, line, expect, &lines(new)); |
| 179 | assert_eq!(got, want.map(str::to_string), "case {text:?} line {line}"); |
| 180 | } |
| 181 | } |
| 182 | } |