use std::ops::RangeInclusive;
use crate::{
Finding, RepoPath, Source,
markdown::{Block, BlockDetail, BlockKind, Body},
model::{Document, ParseMode, parse_source},
};
pub const MARKER: &str = "<<<<<<< ";
fn marker_lines(text: &str, skip: &[RangeInclusive<usize>]) -> Vec<usize> {
text.lines()
.enumerate()
.map(|(i, l)| (i + 1, l))
.filter(|(n, l)| l.starts_with(MARKER) && !skip.iter().any(|r| r.contains(n)))
.map(|(n, _)| n)
.collect()
}
fn fences(body: &Body) -> Vec<RangeInclusive<usize>> {
fn walk(blocks: &[Block], out: &mut Vec<RangeInclusive<usize>>) {
for b in blocks {
if b.kind == BlockKind::Code
&& matches!(b.detail, BlockDetail::Code { fence, .. } if fence > 0)
{
out.push(b.line..=b.end_line);
}
for u in &b.units {
walk(&u.nested, out);
}
}
}
let mut out = Vec::new();
walk(&body.blocks, &mut out);
out
}
pub fn document_conflicts(doc: &Document) -> Vec<usize> {
let skip = if doc.type_name() == Some("Schema") {
Vec::new()
} else {
fences(&doc.body)
};
marker_lines(&doc.source.text, &skip)
}
pub fn conflict_lines(path: &RepoPath, text: &str) -> Vec<usize> {
if !path.as_str().ends_with(".md") {
return marker_lines(text, &[]);
}
let source = Source::from_text(path.clone(), text);
let parsed = parse_source(&source, ParseMode::Document);
document_conflicts(&Document::new(source, parsed))
}
pub fn check(doc: &Document) -> Vec<Finding> {
document_conflicts(doc)
.into_iter()
.map(|line| {
Finding::error(
doc.path.clone(),
Some(line),
"CLI-4_AC-37",
"the line begins a conflict that a merge left; keep the lines that the file needs, and delete the markers `<<<<<<<`, `=======`, and `>>>>>>>`",
)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn lines(path: &str, text: &str) -> Vec<usize> {
conflict_lines(&RepoPath::parse(path).unwrap(), text)
}
#[test]
fn each_line_that_begins_a_conflict_is_an_error() {
let text = "a\n<<<<<<< ours\nb\n=======\nc\n>>>>>>> theirs\n <<<<<<< x\n<<<<<<<\n";
assert_eq!(lines("/knowledge/a.md", text), vec![2]);
assert_eq!(lines("/.sokf/packs/m/formats.yaml", text), vec![2]);
assert!(lines("/knowledge/a.md", "no conflict\n").is_empty());
}
#[test]
fn a_marker_in_a_fence_of_a_document_is_an_example() {
let example = "```text\n<<<<<<< /knowledge/a.md\nmine\n=======\ntheirs\n>>>>>>> /knowledge/a.md\n```\n";
let doc = format!("---\ntype: Note\nid: a\n---\n\n# A\n\n{example}\n<<<<<<< ours\n");
assert_eq!(lines("/knowledge/a.md", &doc), vec![16]);
let nested = format!("# A\n\n- An item.\n\n ```text\n x\n ```\n\n{example}");
assert!(lines("/knowledge/a.md", &nested).is_empty());
let schema = "---\ntype: Schema\nid: schema-a\n---\n\n````yaml\n<<<<<<< x\n````\n";
assert_eq!(lines("/knowledge/schemas/a.md", schema), vec![7]);
assert_eq!(lines("/.sokf/packs/m/formats.yaml", example), vec![2]);
}
}