use std::path::{Path, PathBuf}; use forge_git::browse::{self, EntryKind, TreeEntry}; pub const MAX_TEMPLATES: usize = 20; pub const MAX_TEMPLATE_BYTES: usize = 64 * 1024; const ROOTS: [&str; 3] = [".forge", ".github", ".gitea"]; const ISSUE_DIR: &str = "ISSUE_TEMPLATE"; const ISSUE_FILE: &str = "ISSUE_TEMPLATE.md"; const PULL_FILE: &str = "PULL_REQUEST_TEMPLATE.md"; #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Template { pub stem: String, pub name: String, pub about: String, pub title: String, pub labels: Vec, pub body: String, } pub fn parse_template(stem: &str, text: &str) -> Template { let (front, body) = split_front_matter(text); let mut template = Template { stem: stem.to_owned(), body: body.to_owned(), ..Template::default() }; if let Some(front) = front { for line in front.lines() { let Some((key, value)) = line.split_once(':') else { continue; }; let value = unquote(value); match key.trim() { "name" => template.name = value.to_owned(), "about" => template.about = value.to_owned(), "title" => template.title = value.to_owned(), "labels" => { template.labels = value .split(',') .map(|label| unquote(label).to_owned()) .filter(|label| !label.is_empty()) .collect(); } _ => {} } } } if template.name.trim().is_empty() { template.name = stem.to_owned(); } template } fn split_front_matter(text: &str) -> (Option<&str>, &str) { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let Some(first_end) = text.find('\n') else { return (None, text); }; if text[..first_end].trim_end_matches('\r') != "---" { return (None, text); } let rest = &text[first_end + 1..]; let mut offset = 0; for line in rest.split_inclusive('\n') { if line.trim_end_matches(['\r', '\n']) == "---" { let front = &rest[..offset]; let body = rest[offset + line.len()..].trim_start_matches(['\r', '\n']); return (Some(front), body); } offset += line.len(); } (None, text) } fn unquote(value: &str) -> &str { let value = value.trim(); for quote in ['"', '\''] { if let Some(inner) = value .strip_prefix(quote) .and_then(|rest| rest.strip_suffix(quote)) { return inner.trim(); } } value } fn read_templates( repo: &Path, commit: &str, dir: Option<&str>, file: &str, ) -> forge_git::Result> { for root in ROOTS { if let Some(dir) = dir { let found = read_dir_templates(repo, commit, &format!("{root}/{dir}"))?; if !found.is_empty() { return Ok(found); } } let path = format!("{root}/{file}"); if let Some(text) = browse::read_text_blob(repo, commit, &path, MAX_TEMPLATE_BYTES)? { let stem = file.strip_suffix(".md").unwrap_or(file); return Ok(vec![parse_template(stem, &text)]); } } Ok(Vec::new()) } fn read_dir_templates(repo: &Path, commit: &str, path: &str) -> forge_git::Result> { let Some(entries) = browse::read_tree(repo, commit, path)? else { return Ok(Vec::new()); }; let mut files: Vec<&TreeEntry> = entries .iter() .filter(|e| matches!(e.kind, EntryKind::Blob | EntryKind::Executable)) .filter(|e| e.name.ends_with(".md") && e.name.len() > ".md".len()) .collect(); files.sort_by(|a, b| a.name.cmp(&b.name)); let mut templates = Vec::new(); for entry in files.into_iter().take(MAX_TEMPLATES) { let full = format!("{path}/{}", entry.name); if let Some(text) = browse::read_text_blob(repo, commit, &full, MAX_TEMPLATE_BYTES)? { let stem = entry.name.strip_suffix(".md").unwrap_or(&entry.name); templates.push(parse_template(stem, &text)); } } Ok(templates) } pub fn issue_templates(repo: &Path, branch: &str) -> forge_git::Result> { let Some(commit) = browse::default_branch_commit(repo, branch)? else { return Ok(Vec::new()); }; read_templates(repo, &commit, Some(ISSUE_DIR), ISSUE_FILE) } pub fn pull_template(repo: &Path, branch: &str) -> forge_git::Result> { let Some(commit) = browse::default_branch_commit(repo, branch)? else { return Ok(None); }; Ok(read_templates(repo, &commit, None, PULL_FILE)? .into_iter() .next()) } pub async fn load_issue_templates(repo: PathBuf, branch: String) -> topcoat::Result> { let result = tokio::task::spawn_blocking(move || issue_templates(&repo, &branch)).await?; Ok(result.unwrap_or_else(|e| { tracing::warn!(error = %e, "issue templates: read failed"); Vec::new() })) } pub async fn load_pull_template( repo: PathBuf, branch: String, ) -> topcoat::Result> { let result = tokio::task::spawn_blocking(move || pull_template(&repo, &branch)).await?; Ok(result.unwrap_or_else(|e| { tracing::warn!(error = %e, "pull request template: read failed"); None })) } #[cfg(test)] mod tests { use super::*; #[test] fn no_front_matter_is_all_body_and_name_is_stem() { let t = parse_template("bug", "Steps:\n1. click\n"); assert_eq!(t.stem, "bug"); assert_eq!(t.name, "bug"); assert_eq!(t.about, ""); assert_eq!(t.title, ""); assert!(t.labels.is_empty()); assert_eq!(t.body, "Steps:\n1. click\n"); } #[test] fn front_matter_fields_are_parsed_and_removed_from_body() { let text = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, 'needs triage',, \n---\n\n## Steps\n"; let t = parse_template("bug", text); assert_eq!(t.name, "Bug report"); assert_eq!(t.about, "Something broke"); assert_eq!(t.title, "[Bug]:"); assert_eq!(t.labels, vec!["bug", "needs triage"]); assert_eq!(t.body, "## Steps\n"); } #[test] fn unknown_and_malformed_lines_are_ignored() { let text = "---\nassignees: someone\nno colon here\nname: Feature\n---\nbody"; let t = parse_template("feat", text); assert_eq!(t.name, "Feature"); assert_eq!(t.body, "body"); } #[test] fn blank_or_unclosed_front_matter_and_late_dashes_fall_back() { let cases = [ ("docs", "---\nname: \n---\nx", "docs", "x"), ( "oops", "---\nname: Oops\nno closing marker\n", "oops", "---\nname: Oops\nno closing marker\n", ), ( "x", "Intro\n---\nname: no\n---\n", "x", "Intro\n---\nname: no\n---\n", ), ]; for (stem, text, name, body) in cases { let t = parse_template(stem, text); assert_eq!(t.name, name, "case {stem}"); assert_eq!(t.body, body, "case {stem}"); } } #[test] fn crlf_line_endings_are_handled() { let text = "---\r\nname: Crlf\r\nlabels: a,b\r\n---\r\n\r\nBody\r\n"; let t = parse_template("crlf", text); assert_eq!(t.name, "Crlf"); assert_eq!(t.labels, vec!["a", "b"]); assert_eq!(t.body, "Body\r\n"); } }