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
108#[derive(Debug, thiserror::Error, miette::Diagnostic, Clone, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum WriteError {
111 #[error("cannot write changeset: no entries and an empty summary")]
113 #[diagnostic(code(E049))]
114 EmptyChangeset,
115
116 #[error("entry {index} has an empty package name")]
118 #[diagnostic(code(E049))]
119 EmptyName { index: usize },
120
121 #[error("entry {index} name {name:?} contains a literal `\"`, which cannot be written (no escaping convention is defined for this grammar)")]
124 NameContainsQuote { index: usize, name: String },
125}
126
127pub fn parse_changeset(source: &str) -> Result<Changeset, ParseError> {
134 let trimmed_bom = source.strip_prefix('\u{FEFF}').unwrap_or(source);
135 let normalized = trimmed_bom.replace("\r\n", "\n").replace('\r', "\n");
136 let lines: Vec<&str> = normalized.split('\n').collect();
137
138 if lines.first().map(|l| l.trim_end()) != Some("---") {
139 return Err(ParseError::MissingFrontmatterStart);
140 }
141
142 let closing_index = lines[1..]
149 .iter()
150 .position(|&l| l.trim_end() == "---")
151 .map(|i| i + 1);
152 let Some(closing_index) = closing_index else {
153 return Err(ParseError::UnclosedFrontmatter);
154 };
155
156 let mut entries: Vec<Entry> = Vec::new();
157 let mut first_seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
158
159 for (offset, &line) in lines[1..closing_index].iter().enumerate() {
160 let line_no = offset + 2; if line.trim().is_empty() || line.trim_start().starts_with('#') {
162 continue;
163 }
164 let entry = parse_entry_line(line).map_err(|e| promote_line_error(e, line_no))?;
165 if let Some(&first_line) = first_seen.get(&entry.name) {
166 return Err(ParseError::DuplicateEntry {
167 line: line_no,
168 first_line,
169 name: entry.name,
170 });
171 }
172 first_seen.insert(entry.name.clone(), line_no);
173 entries.push(entry);
174 }
175
176 let summary = lines[closing_index + 1..].join("\n").trim().to_string();
177
178 if entries.is_empty() && summary.is_empty() {
179 return Err(ParseError::EmptyChangeset);
180 }
181
182 Ok(Changeset { entries, summary })
183}
184
185fn promote_line_error(err: LineError, line: usize) -> ParseError {
186 match err {
187 LineError::UnclosedQuotedName => ParseError::UnclosedQuotedName { line },
188 LineError::AmbiguousNameQuoting { raw } => ParseError::AmbiguousNameQuoting { line, raw },
189 LineError::MissingSeparator { raw } => ParseError::MissingSeparator { line, raw },
190 LineError::EmptyName => ParseError::EmptyName { line },
191 LineError::InvalidSeverity { name, source } => {
192 ParseError::InvalidSeverity { line, name, source }
193 }
194 }
195}
196
197pub fn write_changeset(changeset: &Changeset) -> Result<String, WriteError> {
202 if changeset.entries.is_empty() && changeset.summary.trim().is_empty() {
203 return Err(WriteError::EmptyChangeset);
204 }
205 for (index, entry) in changeset.entries.iter().enumerate() {
206 if entry.name.is_empty() {
207 return Err(WriteError::EmptyName { index });
208 }
209 if entry.name.contains('"') {
210 return Err(WriteError::NameContainsQuote {
211 index,
212 name: entry.name.clone(),
213 });
214 }
215 }
216
217 let mut out = String::from("---\n");
218 for entry in &changeset.entries {
219 if needs_quoting(&entry.name) {
220 out.push_str(&format!("\"{}\": {}\n", entry.name, entry.severity));
221 } else {
222 out.push_str(&format!("{}: {}\n", entry.name, entry.severity));
223 }
224 }
225 out.push_str("---\n\n");
226 out.push_str(changeset.summary.trim());
227 out.push('\n');
228 Ok(out)
229}