#[derive(Debug, Clone, PartialEq, Eq)] pub enum Part { Text(String), Suggestion(Vec), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ApplyError { OutOfRange, Changed, } pub fn split_body(body: &str) -> Vec { let lines: Vec<&str> = body.split('\n').collect(); let mut parts = Vec::new(); let mut text: Vec<&str> = Vec::new(); let mut i = 0; while i < lines.len() { if let Some(ticks) = open_fence(lines[i]) { let close = (i + 1..lines.len()).find(|&j| closes_fence(lines[j], ticks)); if let Some(close) = close { if !text.is_empty() { parts.push(Part::Text(text.join("\n"))); text.clear(); } let block = lines[i + 1..close] .iter() .map(|line| line.trim_end_matches('\r').to_owned()) .collect(); parts.push(Part::Suggestion(block)); i = close + 1; continue; } } text.push(lines[i]); i += 1; } if !text.is_empty() { parts.push(Part::Text(text.join("\n"))); } parts } fn open_fence(line: &str) -> Option { let ticks = line.bytes().take_while(|&b| b == b'`').count(); (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks) } fn closes_fence(line: &str, ticks: usize) -> bool { let trimmed = line.trim(); trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`') } pub fn hunk_line(diff_hunk: &str) -> Option<&str> { let last = diff_hunk.lines().last()?; match last.as_bytes().first()? { b'+' | b' ' => Some(&last[1..]), _ => None, } } pub fn replace_line( text: &str, line: u32, expected: &str, replacement: &[String], ) -> Result { if text.is_empty() { return Err(ApplyError::OutOfRange); } let index = (line as usize) .checked_sub(1) .ok_or(ApplyError::OutOfRange)?; let ends_with_newline = text.ends_with('\n'); let body = text.strip_suffix('\n').unwrap_or(text); let mut lines: Vec<&str> = body.split('\n').collect(); let current = lines.get(index).ok_or(ApplyError::OutOfRange)?; if current.trim_end_matches('\r') != expected.trim_end_matches('\r') { return Err(ApplyError::Changed); } let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect(); lines.splice(index..=index, replacement); let mut out = lines.join("\n"); if ends_with_newline && !lines.is_empty() { out.push('\n'); } Ok(out) } #[cfg(test)] mod tests { use super::*; fn lines(items: &[&str]) -> Vec { items.iter().map(|s| s.to_string()).collect() } #[test] fn split_body_cases() { let cases: Vec<(&str, Vec)> = vec![ ( "looks fine\n\n```rust\nlet x = 1;\n```", vec![Part::Text("looks fine\n\n```rust\nlet x = 1;\n```".into())], ), ( "Try this:\n```suggestion\nlet y = 2;\n```\nThanks", vec![ Part::Text("Try this:".into()), Part::Suggestion(lines(&["let y = 2;"])), Part::Text("Thanks".into()), ], ), ( "```suggestion\n```\n\n````suggestion\na\n```\nb\n````", vec![ Part::Suggestion(vec![]), Part::Text("".into()), Part::Suggestion(lines(&["a", "```", "b"])), ], ), ( "```suggestion\nlet y = 2;", vec![Part::Text("```suggestion\nlet y = 2;".into())], ), ]; for (body, want) in cases { assert_eq!(split_body(body), want, "case {body:?}"); } } #[test] fn hunk_last_line_gives_the_commented_text() { assert_eq!(hunk_line("-old\n+let x = 1;"), Some("let x = 1;")); assert_eq!(hunk_line(" ctx\n more"), Some("more")); assert_eq!(hunk_line("+a\n-gone"), None); assert_eq!(hunk_line(""), None); } #[test] fn replace_line_cases() { type Case<'a> = ( &'a str, u32, &'a str, &'a [&'a str], Result<&'a str, ApplyError>, ); let cases: Vec> = vec![ ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")), ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")), ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")), ("a\n", 1, "a", &[], Ok("")), ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)), ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)), ("a\n", 0, "a", &["x"], Err(ApplyError::OutOfRange)), ("", 1, "", &["x"], Err(ApplyError::OutOfRange)), ("a\r\nb\r\n", 1, "a", &["A"], Ok("A\nb\r\n")), ]; for (text, line, expect, new, want) in cases { let got = replace_line(text, line, expect, &lines(new)); assert_eq!(got, want.map(str::to_string), "case {text:?} line {line}"); } } }