rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Reads a pull request description (Markdown): its checklist, its test plan, the issues it
//! closes, and whether it shows the change. PR templates are full of HTML comments and
//! fenced examples, which are not the author's words and are skipped.

#[derive(Clone, Debug)]
pub struct CheckItem {
    pub text: String,
    pub done: bool,
    /// 1-based line in the description, and the column of the text after `[ ]`.
    pub line: u32,
    pub col: u32,
}

#[derive(Clone, Debug)]
pub struct Section {
    pub heading: String,
    /// The list items and sentences under it, without markup.
    pub body: Vec<String>,
}

#[derive(Clone, Debug)]
pub struct IssueRef {
    /// `#12`, `owner/repo#12` or a URL.
    pub target: String,
    /// Whether it says the PR closes it (`Fixes #12`) rather than only mentions it.
    pub closes: bool,
}

#[derive(Clone, Debug, Default)]
pub struct Description {
    /// Where it came from, for messages: `PR description`, `commit messages`, a file name.
    pub source: String,
    /// The lines, with comments and fenced code blanked out but line numbers kept.
    pub lines: Vec<String>,
    pub checklist: Vec<CheckItem>,
    pub sections: Vec<Section>,
    pub issues: Vec<IssueRef>,
    pub has_image: bool,
}

pub fn parse(text: &str, source: &str) -> Description {
    let mut d = Description { source: source.to_string(), ..Default::default() };
    let mut in_comment = false;
    let mut fence: Option<String> = None;
    for raw in text.lines() {
        // Blank out HTML comments (they can span lines) and fenced code, keeping line numbers.
        let mut line = String::new();
        let mut rest = raw;
        loop {
            if in_comment {
                match rest.find("-->") {
                    Some(i) => {
                        rest = &rest[i + 3..];
                        in_comment = false;
                    }
                    None => break,
                }
            } else {
                match rest.find("<!--") {
                    Some(i) => {
                        line.push_str(&rest[..i]);
                        rest = &rest[i + 4..];
                        in_comment = true;
                    }
                    None => {
                        line.push_str(rest);
                        break;
                    }
                }
            }
        }
        let trimmed = line.trim_start();
        if let Some(f) = &fence {
            if trimmed.starts_with(f.as_str()) {
                fence = None;
            }
            d.lines.push(String::new());
            continue;
        }
        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
            fence = Some(trimmed.chars().take(3).collect());
            d.lines.push(String::new());
            continue;
        }
        d.lines.push(line);
    }

    for (i, line) in d.lines.iter().enumerate() {
        let no = i as u32 + 1;
        let trimmed = line.trim_start();
        let indent = line.len() - trimmed.len();
        if let Some(h) = heading(trimmed) {
            d.sections.push(Section { heading: h.to_string(), body: Vec::new() });
            continue;
        }
        if let Some((done, text, off)) = checkbox(trimmed) {
            d.checklist.push(CheckItem { text: text.to_string(), done, line: no, col: (indent + off) as u32 + 1 });
        }
        if let Some(sec) = d.sections.last_mut() {
            let item = strip_marker(trimmed);
            if !item.is_empty() {
                sec.body.push(item.to_string());
            }
        }
        let lower = line.to_lowercase();
        if lower.contains("![") || lower.contains("<img") || lower.contains("<video") || has_media_link(&lower) {
            d.has_image = true;
        }
        issue_refs(line, &mut d.issues);
    }
    d
}

fn heading(line: &str) -> Option<&str> {
    let hashes = line.bytes().take_while(|&b| b == b'#').count();
    if (1..=6).contains(&hashes) && line[hashes..].starts_with(' ') {
        return Some(line[hashes..].trim().trim_end_matches('#').trim());
    }
    // `**Test plan**` or `**Test plan:**` on a line of its own works as a heading too.
    let t = line.trim();
    if let Some(inner) = t.strip_prefix("**").and_then(|s| s.strip_suffix("**"))
        && !inner.contains("**")
        && !inner.is_empty()
    {
        return Some(inner.trim_end_matches(':').trim());
    }
    None
}

/// `- [ ] text`, `* [x] text`, `1. [X] text`: (done, text, byte offset of the text).
fn checkbox(line: &str) -> Option<(bool, &str, usize)> {
    let after_marker = strip_list_marker(line)?;
    let skipped = line.len() - after_marker.len();
    let rest = after_marker.strip_prefix('[')?;
    let mark = rest.chars().next()?;
    let done = match mark {
        ' ' => false,
        'x' | 'X' => true,
        _ => return None,
    };
    let rest = rest[mark.len_utf8()..].strip_prefix(']')?;
    if !rest.is_empty() && !rest.starts_with(' ') {
        return None;
    }
    let text = rest.trim_start();
    let off = skipped + 3 + (rest.len() - text.len());
    (!text.is_empty()).then_some((done, text.trim_end(), off))
}

fn strip_list_marker(line: &str) -> Option<&str> {
    for m in ["- ", "* ", "+ "] {
        if let Some(r) = line.strip_prefix(m) {
            return Some(r.trim_start());
        }
    }
    let digits = line.bytes().take_while(u8::is_ascii_digit).count();
    if digits > 0 && digits < 4 {
        let rest = &line[digits..];
        if let Some(r) = rest.strip_prefix(". ").or_else(|| rest.strip_prefix(") ")) {
            return Some(r.trim_start());
        }
    }
    None
}

fn strip_marker(line: &str) -> &str {
    let l = strip_list_marker(line).unwrap_or(line);
    let l = l.strip_prefix("[ ] ").or_else(|| l.strip_prefix("[x] ")).or_else(|| l.strip_prefix("[X] ")).unwrap_or(l);
    l.trim()
}

fn has_media_link(lower: &str) -> bool {
    [".png", ".jpg", ".jpeg", ".gif", ".webp", ".mp4", ".webm", ".mov", "user-attachments", "user-images"]
        .iter()
        .any(|e| lower.contains(e))
}

/// `Fixes #12`, `closes owner/repo#3`, `Resolves https://.../issues/7`, or a bare `#12`.
fn issue_refs(line: &str, out: &mut Vec<IssueRef>) {
    let lower = line.to_lowercase();
    let bytes = line.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let is_hash = bytes[i] == b'#';
        let is_url = line[i..].starts_with("https://") || line[i..].starts_with("http://");
        if !is_hash && !is_url {
            i += 1;
            continue;
        }
        // The token: for `#12` with an optional `owner/repo` before it, for a URL up to a space.
        let (start, end) = if is_url {
            let end = line[i..].find(char::is_whitespace).map_or(line.len(), |n| i + n);
            (i, end)
        } else {
            let digits = line[i + 1..].bytes().take_while(u8::is_ascii_digit).count();
            if digits == 0 {
                i += 1;
                continue;
            }
            let mut s = i;
            while s > 0 && (bytes[s - 1].is_ascii_alphanumeric() || matches!(bytes[s - 1], b'/' | b'-' | b'_' | b'.')) {
                s -= 1;
            }
            (s, i + 1 + digits)
        };
        let token = line[start..end].trim_end_matches(['.', ',', ')', ';']);
        let is_issue_url = ["/issues/", "/pull/", "/merge_requests/", "/-/issues/", "/pull-requests/"]
            .iter()
            .any(|p| token.contains(p));
        if (is_hash || is_issue_url) && !token.is_empty() {
            let before = lower[..start].trim_end();
            let closes = ["close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"]
                .iter()
                .any(|k| {
                    before.ends_with(k) && !before[..before.len() - k.len()].ends_with(|c: char| c.is_alphanumeric())
                })
                || before.strip_suffix(':').is_some_and(|b| {
                    ["close", "closes", "fix", "fixes", "resolve", "resolves"].iter().any(|k| b.trim_end().ends_with(k))
                });
            if !out.iter().any(|r| r.target == token) {
                out.push(IssueRef { target: token.to_string(), closes });
            }
        }
        i = end.max(i + 1);
    }
}

impl Description {
    /// Whether there is a section that describes how the change was or should be tested.
    pub fn test_section(&self) -> Option<&Section> {
        self.sections.iter().find(|s| {
            let h = s.heading.to_lowercase();
            ["test", "verif", "how to", "qa", "steps to", "reproduc", "validation", "try it"]
                .iter()
                .any(|k| h.contains(k))
        })
    }

    /// Whether the text says anything about `words` (lowercase fragments), outside headings
    /// of an empty template: any non-empty line mentioning one counts.
    pub fn mentions(&self, words: &[&str]) -> bool {
        self.lines.iter().any(|l| {
            let l = l.to_lowercase();
            words.iter().any(|w| l.contains(w))
        })
    }

    /// The first line mentioning one of `words`: (1-based line, byte column, matched word).
    pub fn find(&self, words: &[&str]) -> Option<(u32, usize, String)> {
        self.lines.iter().enumerate().find_map(|(i, l)| {
            let lower = l.to_lowercase();
            words.iter().find_map(|w| lower.find(w).map(|c| (i as u32 + 1, c, (*w).to_string())))
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEMPLATE: &str = "\
<!-- Thanks for the PR! Describe it here. -->
## Summary
Adds invoices. Fixes #12 and closes acme/app#7.

## Test plan
<!--
- [ ] this is just the template hint
-->
1. Open /invoices
2. Click **New**

```
- [ ] not a real item
```

## Checklist
- [x] Tests added
- [ ] Docs updated
* [ ]  Changelog
- [ ]
![shot](https://github.com/user-attachments/assets/1)
See also #99.
";

    #[test]
    fn skips_comments_and_code_and_finds_the_checklist() {
        let d = parse(TEMPLATE, "PR description");
        let items: Vec<_> = d.checklist.iter().map(|c| (c.text.as_str(), c.done)).collect();
        assert_eq!(items, vec![("Tests added", true), ("Docs updated", false), ("Changelog", false)]);
        let docs = &d.checklist[1];
        assert_eq!(
            d.lines[docs.line as usize - 1].chars().skip(docs.col as usize - 1).collect::<String>(),
            "Docs updated"
        );
        assert_eq!(d.lines.len(), TEMPLATE.lines().count());
    }

    #[test]
    fn finds_the_test_plan_steps() {
        let d = parse(TEMPLATE, "PR description");
        let s = d.test_section().unwrap();
        assert_eq!(s.heading, "Test plan");
        assert_eq!(s.body, vec!["Open /invoices", "Click **New**"]);
    }

    #[test]
    fn finds_issues_and_images() {
        let d = parse(TEMPLATE, "PR description");
        let issues: Vec<_> = d.issues.iter().map(|i| (i.target.as_str(), i.closes)).collect();
        assert_eq!(issues, vec![("#12", true), ("acme/app#7", true), ("#99", false)]);
        assert!(d.has_image);
        assert!(!parse("just words", "x").has_image);
    }

    #[test]
    fn bold_lines_count_as_headings_and_mentions_work() {
        let d = parse("**How to test**\n- run it\n\n## Deploy\nMigration needed: yes\n", "x");
        assert_eq!(d.test_section().unwrap().body, vec!["run it"]);
        assert!(d.mentions(&["migrat"]));
        assert_eq!(d.find(&["migrat"]).map(|(l, c, _)| (l, c)), Some((5, 0)));
        assert!(!d.mentions(&["env"]));
    }

    #[test]
    fn empty_and_odd_input() {
        let d = parse("", "x");
        assert!(d.checklist.is_empty() && d.test_section().is_none());
        let d = parse("<!-- never closed\n- [ ] hidden\n", "x");
        assert!(d.checklist.is_empty());
    }
}