forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

templates.rs264 lines, 9.5 KiBHistoryRawDownload
1//! Issue and pull request templates, read from the repository's default branch.
2//!
3//! Issue templates live in `ISSUE_TEMPLATE/*.md` or `ISSUE_TEMPLATE.md`; the pull request
4//! template is `PULL_REQUEST_TEMPLATE.md`. Each is looked up under `.forge/`, then `.github/`,
5//! then `.gitea/`, and the first location that yields a template wins. A file may start with
6//! front matter between two `---` lines holding simple `key: value` lines (`name`, `about`,
7//! `title`, `labels`); everything after it is the body.
8
9use std::path::{Path, PathBuf};
10
11use forge_git::browse::{self, EntryKind, TreeEntry};
12
13/// Most issue templates offered per repository.
14pub const MAX_TEMPLATES: usize = 20;
15/// Largest template file read. Bigger files are skipped.
16pub const MAX_TEMPLATE_BYTES: usize = 64 * 1024;
17
18/// Directories searched for templates, in priority order.
19const ROOTS: [&str; 3] = [".forge", ".github", ".gitea"];
20const ISSUE_DIR: &str = "ISSUE_TEMPLATE";
21const ISSUE_FILE: &str = "ISSUE_TEMPLATE.md";
22const PULL_FILE: &str = "PULL_REQUEST_TEMPLATE.md";
23
24/// One parsed template file.
25#[derive(Debug, Clone, PartialEq, Eq, Default)]
26pub struct Template {
27 /// File name without `.md`. This is the `template` query value that selects it.
28 pub stem: String,
29 /// Display name: the `name` front matter, or the stem.
30 pub name: String,
31 pub about: String,
32 /// Suggested title. Empty when the template sets none.
33 pub title: String,
34 /// Suggested label names, in file order.
35 pub labels: Vec<String>,
36 pub body: String,
37}
38
39/// Parses one template file. `stem` is the file name without `.md`.
40pub fn parse_template(stem: &str, text: &str) -> Template {
41 let (front, body) = split_front_matter(text);
42 let mut template = Template {
43 stem: stem.to_owned(),
44 body: body.to_owned(),
45 ..Template::default()
46 };
47 if let Some(front) = front {
48 for line in front.lines() {
49 let Some((key, value)) = line.split_once(':') else {
50 continue;
51 };
52 let value = unquote(value);
53 match key.trim() {
54 "name" => template.name = value.to_owned(),
55 "about" => template.about = value.to_owned(),
56 "title" => template.title = value.to_owned(),
57 "labels" => {
58 template.labels = value
59 .split(',')
60 .map(|label| unquote(label).to_owned())
61 .filter(|label| !label.is_empty())
62 .collect();
63 }
64 _ => {}
65 }
66 }
67 }
68 if template.name.trim().is_empty() {
69 template.name = stem.to_owned();
70 }
71 template
72}
73
74/// Splits front matter from the body. Text without a closed front matter block is all body.
75fn split_front_matter(text: &str) -> (Option<&str>, &str) {
76 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
77 let Some(first_end) = text.find('\n') else {
78 return (None, text);
79 };
80 if text[..first_end].trim_end_matches('\r') != "---" {
81 return (None, text);
82 }
83 let rest = &text[first_end + 1..];
84 let mut offset = 0;
85 for line in rest.split_inclusive('\n') {
86 if line.trim_end_matches(['\r', '\n']) == "---" {
87 let front = &rest[..offset];
88 let body = rest[offset + line.len()..].trim_start_matches(['\r', '\n']);
89 return (Some(front), body);
90 }
91 offset += line.len();
92 }
93 (None, text)
94}
95
96/// A value with one pair of matching surrounding quotes removed, and whitespace trimmed.
97fn unquote(value: &str) -> &str {
98 let value = value.trim();
99 for quote in ['"', '\''] {
100 if let Some(inner) = value
101 .strip_prefix(quote)
102 .and_then(|rest| rest.strip_suffix(quote))
103 {
104 return inner.trim();
105 }
106 }
107 value
108}
109
110/// Templates from the first root in `ROOTS` that has any. `dir` names a directory of `.md` files
111/// (tried first under each root); `file` is the single-file form.
112fn read_templates(
113 repo: &Path,
114 commit: &str,
115 dir: Option<&str>,
116 file: &str,
117) -> forge_git::Result<Vec<Template>> {
118 for root in ROOTS {
119 if let Some(dir) = dir {
120 let found = read_dir_templates(repo, commit, &format!("{root}/{dir}"))?;
121 if !found.is_empty() {
122 return Ok(found);
123 }
124 }
125 let path = format!("{root}/{file}");
126 if let Some(text) = browse::read_text_blob(repo, commit, &path, MAX_TEMPLATE_BYTES)? {
127 let stem = file.strip_suffix(".md").unwrap_or(file);
128 return Ok(vec![parse_template(stem, &text)]);
129 }
130 }
131 Ok(Vec::new())
132}
133
134/// The `.md` files directly in `path`, read in name order, at most `MAX_TEMPLATES`.
135fn read_dir_templates(repo: &Path, commit: &str, path: &str) -> forge_git::Result<Vec<Template>> {
136 let Some(entries) = browse::read_tree(repo, commit, path)? else {
137 return Ok(Vec::new());
138 };
139 let mut files: Vec<&TreeEntry> = entries
140 .iter()
141 .filter(|e| matches!(e.kind, EntryKind::Blob | EntryKind::Executable))
142 .filter(|e| e.name.ends_with(".md") && e.name.len() > ".md".len())
143 .collect();
144 files.sort_by(|a, b| a.name.cmp(&b.name));
145 let mut templates = Vec::new();
146 for entry in files.into_iter().take(MAX_TEMPLATES) {
147 let full = format!("{path}/{}", entry.name);
148 if let Some(text) = browse::read_text_blob(repo, commit, &full, MAX_TEMPLATE_BYTES)? {
149 let stem = entry.name.strip_suffix(".md").unwrap_or(&entry.name);
150 templates.push(parse_template(stem, &text));
151 }
152 }
153 Ok(templates)
154}
155
156/// The issue templates on `branch`. Empty when the branch does not exist or has none.
157pub fn issue_templates(repo: &Path, branch: &str) -> forge_git::Result<Vec<Template>> {
158 let Some(commit) = browse::default_branch_commit(repo, branch)? else {
159 return Ok(Vec::new());
160 };
161 read_templates(repo, &commit, Some(ISSUE_DIR), ISSUE_FILE)
162}
163
164/// The pull request template on `branch`, if any.
165pub fn pull_template(repo: &Path, branch: &str) -> forge_git::Result<Option<Template>> {
166 let Some(commit) = browse::default_branch_commit(repo, branch)? else {
167 return Ok(None);
168 };
169 Ok(read_templates(repo, &commit, None, PULL_FILE)?
170 .into_iter()
171 .next())
172}
173
174/// `issue_templates` on a blocking thread. A read failure is logged and gives no templates, so
175/// the page still renders.
176pub async fn load_issue_templates(repo: PathBuf, branch: String) -> topcoat::Result<Vec<Template>> {
177 let result = tokio::task::spawn_blocking(move || issue_templates(&repo, &branch)).await?;
178 Ok(result.unwrap_or_else(|e| {
179 tracing::warn!(error = %e, "issue templates: read failed");
180 Vec::new()
181 }))
182}
183
184/// `pull_template` on a blocking thread. A read failure is logged and gives no template.
185pub async fn load_pull_template(
186 repo: PathBuf,
187 branch: String,
188) -> topcoat::Result<Option<Template>> {
189 let result = tokio::task::spawn_blocking(move || pull_template(&repo, &branch)).await?;
190 Ok(result.unwrap_or_else(|e| {
191 tracing::warn!(error = %e, "pull request template: read failed");
192 None
193 }))
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn no_front_matter_is_all_body_and_name_is_stem() {
202 let t = parse_template("bug", "Steps:\n1. click\n");
203 assert_eq!(t.stem, "bug");
204 assert_eq!(t.name, "bug");
205 assert_eq!(t.about, "");
206 assert_eq!(t.title, "");
207 assert!(t.labels.is_empty());
208 assert_eq!(t.body, "Steps:\n1. click\n");
209 }
210
211 #[test]
212 fn front_matter_fields_are_parsed_and_removed_from_body() {
213 let text = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, 'needs triage',, \n---\n\n## Steps\n";
214 let t = parse_template("bug", text);
215 assert_eq!(t.name, "Bug report");
216 assert_eq!(t.about, "Something broke");
217 assert_eq!(t.title, "[Bug]:");
218 assert_eq!(t.labels, vec!["bug", "needs triage"]);
219 assert_eq!(t.body, "## Steps\n");
220 }
221
222 #[test]
223 fn unknown_and_malformed_lines_are_ignored() {
224 let text = "---\nassignees: someone\nno colon here\nname: Feature\n---\nbody";
225 let t = parse_template("feat", text);
226 assert_eq!(t.name, "Feature");
227 assert_eq!(t.body, "body");
228 }
229
230 #[test]
231 fn blank_or_unclosed_front_matter_and_late_dashes_fall_back() {
232 // (stem, text, want name, want body): a blank name uses the stem; an unclosed block and a
233 // dash line later in the body are not front matter, so the whole text is body.
234 let cases = [
235 ("docs", "---\nname: \n---\nx", "docs", "x"),
236 (
237 "oops",
238 "---\nname: Oops\nno closing marker\n",
239 "oops",
240 "---\nname: Oops\nno closing marker\n",
241 ),
242 (
243 "x",
244 "Intro\n---\nname: no\n---\n",
245 "x",
246 "Intro\n---\nname: no\n---\n",
247 ),
248 ];
249 for (stem, text, name, body) in cases {
250 let t = parse_template(stem, text);
251 assert_eq!(t.name, name, "case {stem}");
252 assert_eq!(t.body, body, "case {stem}");
253 }
254 }
255
256 #[test]
257 fn crlf_line_endings_are_handled() {
258 let text = "---\r\nname: Crlf\r\nlabels: a,b\r\n---\r\n\r\nBody\r\n";
259 let t = parse_template("crlf", text);
260 assert_eq!(t.name, "Crlf");
261 assert_eq!(t.labels, vec!["a", "b"]);
262 assert_eq!(t.body, "Body\r\n");
263 }
264}