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
108#[derive(Debug, thiserror::Error, miette::Diagnostic, Clone, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum WriteError {
111    /// Mirrors `ParseError::EmptyChangeset`.
112    #[error("cannot write changeset: no entries and an empty summary")]
113    #[diagnostic(code(E049))]
114    EmptyChangeset,
115
116    /// `entries[index]`'s name is the empty string.
117    #[error("entry {index} has an empty package name")]
118    #[diagnostic(code(E049))]
119    EmptyName { index: usize },
120
121    /// `entries[index]`'s name contains a literal `"`, which cannot be written — no escaping
122    /// convention is defined for this grammar.
123    #[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
127/// Parses one `.changeset/*.md` file's contents.
128///
129/// Grammar (§6.1): a `---`-delimited frontmatter block starting on line 1, each non-blank,
130/// non-comment line inside it shaped `<name>: <severity>`, followed by the file's remaining
131/// content as `summary` (trimmed). `#`-comment lines and blank lines inside the frontmatter
132/// block are skipped. CRLF line endings are normalized to LF before parsing.
133pub 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    // Two-pass, deliberately: find the frontmatter's boundaries FIRST, then parse content
143    // within them. A single pass that tries to parse every line as an entry until it
144    // happens to hit a literal "---" cannot tell "this entry is malformed" apart from "the
145    // frontmatter was never closed at all" — the first non-entry-shaped line after a missing
146    // closing delimiter would otherwise surface as a misleading parse error on that line
147    // instead of `UnclosedFrontmatter`.
148    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; // absolute, 1-indexed; line 1 was "---"
161        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
197/// Serializes a [`Changeset`] back to `.changeset/*.md` bytes.
198///
199/// Names are quoted only when necessary. Severities are always written lowercase. Output
200/// always uses `\n` line endings and ends with a single trailing newline after the summary.
201pub 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}