forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

suggestions.rs182 lines, 6.5 KiBHistoryRawDownload
1//! Suggested changes in review comments. A comment whose body holds a fenced block opened with
2//! ```suggestion proposes replacing the commented line with the lines of that block. This module
3//! splits a body into text and suggestion parts, and computes the replacement of one line of a
4//! file. The web layer checks the replacement against the head and the git layer commits it.
5
6/// One part of a comment body: markdown text, or the lines of a suggestion block.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum Part {
9 Text(String),
10 Suggestion(Vec<String>),
11}
12
13/// Why a suggestion cannot replace a line.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ApplyError {
16 /// The file has no such line.
17 OutOfRange,
18 /// The line no longer reads what the comment was written against.
19 Changed,
20}
21
22/// Splits a comment body into text and suggestion parts, in order. A suggestion opens with three
23/// or more backticks and the word `suggestion`, and closes with a line of at least as many
24/// backticks. A fence that never closes is text, as is any other code fence.
25pub 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/// The number of backticks of a line that opens a suggestion block, if it does.
57fn 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/// Whether `line` closes a fence opened with `ticks` backticks.
63fn 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/// The text of the commented line, read from the last line of a stored diff hunk. The hunk ends
69/// at the commented line, and that line is an added or a context line. `None` for a deleted line.
70pub 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/// `text` with line `line` (1-based) replaced by `replacement`, when that line still reads
79/// `expected`. An empty replacement deletes the line. The trailing newline of `text` is kept.
80pub 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)]
109mod 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 // (text, 1-based line, expected line text, replacement, want)
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}