Skip to main content

callisto_format/changeset/
mod.rs

1mod frontmatter;
2#[cfg(test)]
3mod tests;
4
5use callisto_model::{Severity, SeverityParseError};
6use frontmatter::{needs_quoting, parse_entry_line, LineError};
7
8/// One parsed `.changeset/*.md` file (§6.1's shape): a frontmatter block of
9/// `name: severity` entries, followed by a free-text summary.
10///
11/// Deliberately does not carry a filename or path — this crate is filesystem-free; a caller
12/// that reads files off disk attaches the filename itself for sort ordering and error
13/// context.
14use schemars::JsonSchema;
15
16/// One parsed `.changeset/*.md` file (§6.1's shape): a frontmatter block of
17/// `name: severity` entries, followed by a free-text summary.
18///
19/// Deliberately does not carry a filename or path — this crate is filesystem-free; a caller
20/// that reads files off disk attaches the filename itself for sort ordering and error
21/// context.
22#[derive(Clone, Debug, PartialEq, Eq, JsonSchema)]
23pub struct Changeset {
24    pub entries: Vec<Entry>,
25    pub summary: String,
26}
27
28/// One `"name": severity` frontmatter line, after quote resolution.
29///
30/// `name` is the raw string as written in the changeset — resolving it to a `PackageId`
31/// (bare vs. `ecosystem/name`-prefixed) is a workspace-aware operation this crate cannot
32/// perform and does not attempt.
33#[derive(Clone, Debug, PartialEq, Eq, JsonSchema)]
34pub struct Entry {
35    pub name: String,
36    pub severity: Severity,
37}
38
39impl Changeset {
40    /// Convenience wrapper around [`write_changeset`].
41    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    /// The file does not open with a `---` delimiter on line 1 at all.
50    #[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    /// A `---` opened on line 1 but no matching closing `---` line was ever found.
58    #[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    /// A quoted name's opening `"` has no matching closing `"` on the same line.
63    #[error("line {line}: quoted name is never closed with a matching `\"`")]
64    #[diagnostic(code(E042))]
65    UnclosedQuotedName { line: usize },
66
67    /// The closing `"` of a quoted name is not immediately followed by the separator `:`.
68    #[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    /// A bare (unquoted) line contains no `:` at all.
73    #[error("line {line}: no `:` separator found in {raw:?}")]
74    #[diagnostic(code(E044))]
75    MissingSeparator { line: usize, raw: String },
76
77    /// The name resolved to the empty string.
78    #[error("line {line}: package name is empty")]
79    #[diagnostic(code(E045))]
80    EmptyName { line: usize },
81
82    /// The severity token is not one of `major | minor | patch | none` (case-insensitive).
83    #[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    /// The same (raw, pre-`PackageId`-resolution) name appears twice in one changeset's
93    /// frontmatter.
94    #[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    /// §6.1: "Empty frontmatter valid iff summary is non-empty."
103    #[error("changeset has no frontmatter entries and an empty summary")]
104    #[diagnostic(code(E048))]
105    EmptyChangeset,
106
107    /// A changeset with one or more entries must have a non-empty summary.
108    #[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    /// Mirrors `ParseError::EmptyChangeset`.
117    #[error("cannot write changeset: no entries and an empty summary")]
118    #[diagnostic(code(E049))]
119    EmptyChangeset,
120
121    /// A changeset with one or more entries must have a non-empty summary.
122    #[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    /// `entries[index]`'s name is the empty string.
127    #[error("entry {index} has an empty package name")]
128    #[diagnostic(code(E057))]
129    EmptyName { index: usize },
130
131    /// `entries[index]`'s name contains a literal `"`, which cannot be written — no escaping
132    /// convention is defined for this grammar.
133    #[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
137/// Parses one `.changeset/*.md` file's contents.
138///
139/// Grammar (§6.1): a `---`-delimited frontmatter block starting on line 1, each non-blank,
140/// non-comment line inside it shaped `<name>: <severity>`, followed by the file's remaining
141/// content as `summary` (trimmed). `#`-comment lines and blank lines inside the frontmatter
142/// block are skipped. CRLF line endings are normalized to LF before parsing.
143pub 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    // Two-pass, deliberately: find the frontmatter's boundaries FIRST, then parse content
153    // within them. A single pass that tries to parse every line as an entry until it
154    // happens to hit a literal "---" cannot tell "this entry is malformed" apart from "the
155    // frontmatter was never closed at all" — the first non-entry-shaped line after a missing
156    // closing delimiter would otherwise surface as a misleading parse error on that line
157    // instead of `UnclosedFrontmatter`.
158    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; // absolute, 1-indexed; line 1 was "---"
168        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
205/// Serializes a [`Changeset`] back to `.changeset/*.md` bytes.
206///
207/// Names are quoted only when necessary. Severities are always written lowercase. Output
208/// always uses `\n` line endings and ends with a single trailing newline after the summary.
209pub 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}