callisto_format/changeset/
mod.rs1mod frontmatter;
2#[cfg(test)]
3mod tests;
4
5use callisto_model::{Severity, SeverityParseError};
6use frontmatter::{needs_quoting, parse_entry_line, LineError};
7
8use schemars::JsonSchema;
15
16#[derive(Clone, Debug, PartialEq, Eq, JsonSchema)]
23pub struct Changeset {
24 pub entries: Vec<Entry>,
25 pub summary: String,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq, JsonSchema)]
34pub struct Entry {
35 pub name: String,
36 pub severity: Severity,
37}
38
39impl Changeset {
40 pub fn to_markdown(&self) -> Result<String, WriteError> {
42 write_changeset(self)
43 }
44}
45
46#[derive(Debug, thiserror::Error, miette::Diagnostic, Clone, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum ParseError {
49 #[error("changeset does not start with a `---` frontmatter delimiter on line 1")]
51 #[diagnostic(
52 code(E040),
53 help("Add a `---` frontmatter delimiter on line 1 of the changeset file.")
54 )]
55 MissingFrontmatterStart,
56
57 #[error("frontmatter opened with `---` on line 1 but was never closed with a matching `---`")]
59 #[diagnostic(code(E041), help("Ensure frontmatter block closes with `---`."))]
60 UnclosedFrontmatter,
61
62 #[error("line {line}: quoted name is never closed with a matching `\"`")]
64 #[diagnostic(code(E042))]
65 UnclosedQuotedName { line: usize },
66
67 #[error("line {line}: quoted name `{raw}` is followed by unexpected content before the `:` separator")]
69 #[diagnostic(code(E043))]
70 AmbiguousNameQuoting { line: usize, raw: String },
71
72 #[error("line {line}: no `:` separator found in {raw:?}")]
74 #[diagnostic(code(E044))]
75 MissingSeparator { line: usize, raw: String },
76
77 #[error("line {line}: package name is empty")]
79 #[diagnostic(code(E045))]
80 EmptyName { line: usize },
81
82 #[error("line {line}: invalid severity for package {name:?}: {source}")]
84 #[diagnostic(code(E046))]
85 InvalidSeverity {
86 line: usize,
87 name: String,
88 #[source]
89 source: SeverityParseError,
90 },
91
92 #[error("line {line}: package {name:?} is named more than once in this changeset's frontmatter (first on line {first_line})")]
95 #[diagnostic(code(E047))]
96 DuplicateEntry {
97 line: usize,
98 first_line: usize,
99 name: String,
100 },
101
102 #[error("changeset has no frontmatter entries and an empty summary")]
104 #[diagnostic(code(E048))]
105 EmptyChangeset,
106
107 #[error("changeset has entries but an empty or whitespace-only summary")]
109 #[diagnostic(code(E055), help("Add a non-empty summary after the closing `---` delimiter."))]
110 EmptySummary,
111}
112
113#[derive(Debug, thiserror::Error, miette::Diagnostic, Clone, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum WriteError {
116 #[error("cannot write changeset: no entries and an empty summary")]
118 #[diagnostic(code(E049))]
119 EmptyChangeset,
120
121 #[error("cannot write changeset: entries present but summary is empty or whitespace-only")]
123 #[diagnostic(code(E056), help("Provide a non-empty summary describing the change."))]
124 EmptySummary,
125
126 #[error("entry {index} has an empty package name")]
128 #[diagnostic(code(E057))]
129 EmptyName { index: usize },
130
131 #[error("entry {index} name {name:?} contains a literal `\"`, which cannot be written (no escaping convention is defined for this grammar)")]
134 NameContainsQuote { index: usize, name: String },
135}
136
137pub fn parse_changeset(source: &str) -> Result<Changeset, ParseError> {
144 let trimmed_bom = source.strip_prefix('\u{FEFF}').unwrap_or(source);
145 let normalized = trimmed_bom.replace("\r\n", "\n").replace('\r', "\n");
146 let lines: Vec<&str> = normalized.split('\n').collect();
147
148 if lines.first().map(|l| l.trim_end()) != Some("---") {
149 return Err(ParseError::MissingFrontmatterStart);
150 }
151
152 let closing_index = lines[1..].iter().position(|&l| l.trim_end() == "---").map(|i| i + 1);
159 let Some(closing_index) = closing_index else {
160 return Err(ParseError::UnclosedFrontmatter);
161 };
162
163 let mut entries: Vec<Entry> = Vec::new();
164 let mut first_seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
165
166 for (offset, &line) in lines[1..closing_index].iter().enumerate() {
167 let line_no = offset + 2; if line.trim().is_empty() || line.trim_start().starts_with('#') {
169 continue;
170 }
171 let entry = parse_entry_line(line).map_err(|e| promote_line_error(e, line_no))?;
172 if let Some(&first_line) = first_seen.get(&entry.name) {
173 return Err(ParseError::DuplicateEntry {
174 line: line_no,
175 first_line,
176 name: entry.name,
177 });
178 }
179 first_seen.insert(entry.name.clone(), line_no);
180 entries.push(entry);
181 }
182
183 let summary = lines[closing_index + 1..].join("\n").trim().to_string();
184
185 if entries.is_empty() && summary.is_empty() {
186 return Err(ParseError::EmptyChangeset);
187 }
188 if !entries.is_empty() && summary.is_empty() {
189 return Err(ParseError::EmptySummary);
190 }
191
192 Ok(Changeset { entries, summary })
193}
194
195fn promote_line_error(err: LineError, line: usize) -> ParseError {
196 match err {
197 LineError::UnclosedQuotedName => ParseError::UnclosedQuotedName { line },
198 LineError::AmbiguousNameQuoting { raw } => ParseError::AmbiguousNameQuoting { line, raw },
199 LineError::MissingSeparator { raw } => ParseError::MissingSeparator { line, raw },
200 LineError::EmptyName => ParseError::EmptyName { line },
201 LineError::InvalidSeverity { name, source } => ParseError::InvalidSeverity { line, name, source },
202 }
203}
204
205pub fn write_changeset(changeset: &Changeset) -> Result<String, WriteError> {
210 if changeset.summary.trim().is_empty() {
211 if changeset.entries.is_empty() {
212 return Err(WriteError::EmptyChangeset);
213 }
214 return Err(WriteError::EmptySummary);
215 }
216 for (index, entry) in changeset.entries.iter().enumerate() {
217 if entry.name.is_empty() {
218 return Err(WriteError::EmptyName { index });
219 }
220 if entry.name.contains('"') {
221 return Err(WriteError::NameContainsQuote {
222 index,
223 name: entry.name.clone(),
224 });
225 }
226 }
227
228 let mut out = String::from("---\n");
229 for entry in &changeset.entries {
230 if needs_quoting(&entry.name) {
231 out.push_str(&format!("\"{}\": {}\n", entry.name, entry.severity));
232 } else {
233 out.push_str(&format!("{}: {}\n", entry.name, entry.severity));
234 }
235 }
236 out.push_str("---\n\n");
237 out.push_str(changeset.summary.trim());
238 out.push('\n');
239 Ok(out)
240}