use crate::{
RepoPath, Source,
grammar::{Only, States},
markdown::{is_guidance_marker, is_only_marker, is_optional_mark, only_marker},
model::{ParseMode, parse_source},
source::split,
};
fn is_marker(line: &str) -> bool {
is_only_marker(line) || is_optional_mark(line) || is_guidance_marker(line)
}
fn drop_guidance_above(lines: &[&str], out: &mut [Option<String>], i: usize, floor: usize) {
let mut k = i;
while k > floor && is_guidance_marker(lines[k - 1]) {
out[k - 1] = None;
k -= 1;
}
}
pub fn gate(document: &str, states: &States) -> String {
let lines: Vec<&str> = document.lines().collect();
let source = Source::from_text(RepoPath::root(), document);
let parsed = parse_source(&source, ParseMode::Document);
let mut out: Vec<Option<String>> = lines.iter().map(|l| Some((*l).to_string())).collect();
let close = split(&source)
.frontmatter
.map(|_| parsed.body_line - 2)
.filter(|&c| c < lines.len());
if let Some(close) = close {
let mut i = 1;
while i < close {
let line = lines[i];
if !is_only_marker(line) {
i += 1;
continue;
}
if admitted(line, states) {
let cut = line.rfind('#').unwrap_or(line.len());
out[i] = Some(line[..cut].trim_end().to_string());
i += 1;
continue;
}
let end = continuation_end(&lines, i, close);
out[i..end].fill(None);
drop_guidance_above(&lines, &mut out, i, 1);
i = end;
}
}
let body_start = close.map_or(0, |c| c + 1);
for i in body_start..lines.len() {
let line = lines[i];
if !line.trim_start().starts_with("<!--")
|| !is_only_marker(line)
|| parsed.body.in_code(i + 1)
{
continue;
}
out[i] = None;
if admitted(line, states) {
continue;
}
drop_guidance_above(&lines, &mut out, i, body_start);
let Some(marked) =
(i + 1..lines.len()).find(|&j| !lines[j].trim().is_empty() && !is_marker(lines[j]))
else {
continue;
};
let end = extent(&parsed.body, &lines, marked);
for slot in out.iter_mut().take(end + 1).skip(marked) {
*slot = None;
}
if end + 1 < lines.len() && lines[end + 1].trim().is_empty() {
out[end + 1] = None;
}
}
let mut text: String = out.into_iter().flatten().collect::<Vec<_>>().join("\n");
if document.ends_with('\n') {
text.push('\n');
}
text
}
fn admitted(line: &str, states: &States) -> bool {
only_marker(line).is_none_or(|map| Only(map).admits(states))
}
pub(super) fn continuation_end(lines: &[&str], i: usize, close: usize) -> usize {
let own = indent(lines[i]);
let mut j = i + 1;
while j < close && (lines[j].trim().is_empty() || indent(lines[j]) > own) {
if lines[j].trim().is_empty() && !next_deeper(lines, j, close, own) {
break;
}
j += 1;
}
j
}
fn indent(line: &str) -> usize {
line.len() - line.trim_start().len()
}
fn next_deeper(lines: &[&str], from: usize, close: usize, own: usize) -> bool {
(from..close)
.find(|&j| !lines[j].trim().is_empty())
.is_some_and(|j| indent(lines[j]) > own)
}
fn extent(body: &crate::Body, lines: &[&str], marked: usize) -> usize {
let line_no = marked + 1;
if let Some(h) = body.headings.iter().find(|h| h.line == line_no) {
let stop = body
.headings
.iter()
.find(|n| n.line > h.line && n.level <= h.level)
.map_or(lines.len(), |n| n.line - 1);
let mut end = stop;
while end > marked + 1
&& (lines[end - 1].trim().is_empty()
|| is_only_marker(lines[end - 1])
|| is_guidance_marker(lines[end - 1]))
{
end -= 1;
}
return end - 1;
}
if let Some(b) = body.blocks.iter().find(|b| b.line == line_no) {
return b.end_line - 1;
}
marked
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scaffold::fixtures::states;
const TEMPLATE: &str = "---\ntype: Issue\nid: x\nstate: open\nresolution: none # sokf:only state=closed\nreviewers: # sokf:only kind=feature\n - a\n - b\ntags: [t]\n---\n\n# Title\n\nIntro.\n\n<!-- sokf:only kind=bug -->\n## Reproduction\n\nSteps.\n\n### Detail\n\nMore.\n\n<!-- sokf:only state=closed -->\n## Conclusion\n\nDone.\n\n## Notes\n\n<!-- sokf:only kind=bug -->\n- one\n- two\n\nAfter.\n\n```\n<!-- sokf:only state=closed -->\nkept as text\n```\n";
#[test]
fn an_open_bug_keeps_the_bug_parts_and_drops_the_closed_ones() {
let out = gate(TEMPLATE, &states(&[("state", "open"), ("kind", "bug")]));
assert_eq!(
out,
"---\ntype: Issue\nid: x\nstate: open\ntags: [t]\n---\n\n# Title\n\nIntro.\n\n## Reproduction\n\nSteps.\n\n### Detail\n\nMore.\n\n## Notes\n\n- one\n- two\n\nAfter.\n\n```\n<!-- sokf:only state=closed -->\nkept as text\n```\n"
);
}
#[test]
fn a_closed_feature_keeps_the_other_parts() {
let out = gate(
TEMPLATE,
&states(&[("state", "closed"), ("kind", "feature")]),
);
assert_eq!(
out,
"---\ntype: Issue\nid: x\nstate: open\nresolution: none\nreviewers:\n - a\n - b\ntags: [t]\n---\n\n# Title\n\nIntro.\n\n## Conclusion\n\nDone.\n\n## Notes\n\nAfter.\n\n```\n<!-- sokf:only state=closed -->\nkept as text\n```\n"
);
}
#[test]
fn edge_cases_two_markers_a_top_heading_and_the_last_line() {
let two =
"---\ntype: T\n---\n\n<!-- sokf:only a=x -->\n<!-- sokf:only b=y -->\n# H\n\nBody.\n";
assert_eq!(
gate(two, &states(&[("a", "x"), ("b", "y")])),
"---\ntype: T\n---\n\n# H\n\nBody.\n"
);
assert_eq!(
gate(two, &states(&[("a", "x"), ("b", "z")])),
"---\ntype: T\n---\n\n"
);
let top = "# A\n\n<!-- sokf:only a=x -->\n# B\n\nb\n\n## B1\n\nb1\n";
assert_eq!(gate(top, &states(&[("a", "y")])), "# A\n\n");
assert_eq!(
gate(top, &states(&[("a", "x")])),
"# A\n\n# B\n\nb\n\n## B1\n\nb1\n"
);
assert_eq!(
gate("# A\n\n<!-- sokf:only a=x -->\n", &states(&[("a", "y")])),
"# A\n\n"
);
assert_eq!(
gate("# A\n\n<!-- sokf:only nonsense -->\nkept\n", &states(&[])),
"# A\n\nkept\n"
);
assert_eq!(
gate("# A\n<!-- sokf:only a=x -->\ngone", &states(&[("a", "y")])),
"# A"
);
}
}