Skip to main content

xtask/
release_notes.rs

1//! The cumulative migration note (#3178).
2//!
3//! `design/bynk-release-discipline.md` promises each release an upgrade note:
4//! what breaks, and how to move. It is assembled, not remembered. An increment
5//! declares `breaking:` in its pending file; the stamp ([`crate::stamp`]) writes
6//! it under the increment's version into the Book page [`UPGRADING_PAGE`]; and
7//! [`release_section`] — behind `cargo xtask release-notes` — reads that page to
8//! build the "Upgrading from vPREV" section of a release body, covering every
9//! version after the previous release up to and including this one.
10//!
11//! The page is the canonical record; the release body is derived from it, so
12//! the two cannot drift.
13
14use crate::stamp::Version;
15
16/// The Book's upgrading page, relative to the repo root.
17pub const UPGRADING_PAGE: &str = "site/src/content/docs/reference/upgrading.md";
18
19/// The marker the stamp inserts new entries after (newest first). It is an HTML
20/// comment so it is invisible in the rendered page.
21pub const ENTRIES_MARKER: &str = "<!-- stamp:breaking-entries -->";
22
23/// One page entry: a `## vX.Y.Z` heading and the note.
24pub fn upgrading_entry(version: Version, note: &str) -> String {
25    format!("## v{version}\n\n{note}\n\n")
26}
27
28/// Insert `entries` (already newest-first) straight after [`ENTRIES_MARKER`].
29pub fn insert_upgrading_entries(page: &str, entries: &[String]) -> Result<String, String> {
30    let Some(at) = page.find(ENTRIES_MARKER) else {
31        return Err(format!(
32            "{UPGRADING_PAGE} has no `{ENTRIES_MARKER}` line to insert breaking-change \
33             entries after"
34        ));
35    };
36    let split = at + ENTRIES_MARKER.len();
37    let (head, tail) = page.split_at(split);
38    let tail = tail.trim_start_matches('\n');
39    Ok(format!("{head}\n\n{}{tail}", entries.concat()))
40}
41
42/// Every `(version, note)` entry on the page, in page order (newest first).
43pub fn parse_entries(page: &str) -> Vec<(Version, String)> {
44    let Some(at) = page.find(ENTRIES_MARKER) else {
45        return Vec::new();
46    };
47    let mut out: Vec<(Version, String)> = Vec::new();
48    for line in page[at + ENTRIES_MARKER.len()..].lines() {
49        if let Some(v) = line
50            .strip_prefix("## v")
51            .and_then(|rest| Version::parse(rest.trim()))
52        {
53            out.push((v, String::new()));
54        } else if let Some((_, note)) = out.last_mut() {
55            note.push_str(line);
56            note.push('\n');
57        }
58    }
59    for (_, note) in &mut out {
60        *note = note.trim().to_string();
61    }
62    out
63}
64
65/// The version a release tag names: `vX.Y.Z`, with any pre-release suffix
66/// (`v0.16.0-rc1`) dropped, as `release.yml`'s verify job does, so a pre-release
67/// tag still gets a release body.
68pub fn parse_release_tag(tag: &str) -> Option<Version> {
69    let rest = tag.strip_prefix('v')?;
70    Version::parse(rest.split('-').next()?)
71}
72
73fn ordering_key(v: Version) -> (u64, u64, u64) {
74    (v.major, v.minor, v.patch)
75}
76
77/// The release before `current` among `tags`: the greatest plain `vX.Y.Z` tag
78/// strictly below it. Pre-release tags (`v0.16.0-rc1`) and anything unparseable
79/// are ignored.
80pub fn previous_tag(tags: &[String], current: Version) -> Option<Version> {
81    tags.iter()
82        .filter_map(|t| Version::parse(t.trim().strip_prefix('v')?))
83        .filter(|v| ordering_key(*v) < ordering_key(current))
84        .max_by_key(|v| ordering_key(*v))
85}
86
87/// The release-body section: breaking changes in `(prev, tag]`, oldest first.
88/// Always a section, even when empty, so a reader can tell "nothing breaks" from
89/// "nobody wrote the note".
90pub fn release_section(page: &str, prev: Option<Version>, tag: Version) -> String {
91    let mut entries: Vec<(Version, String)> = parse_entries(page)
92        .into_iter()
93        .filter(|(v, _)| {
94            ordering_key(*v) <= ordering_key(tag)
95                && prev.is_none_or(|p| ordering_key(*v) > ordering_key(p))
96        })
97        .collect();
98    entries.sort_by_key(|(v, _)| ordering_key(*v));
99
100    let heading = match prev {
101        Some(p) => format!("## Upgrading from v{p}"),
102        None => "## Upgrading".to_string(),
103    };
104    if entries.is_empty() {
105        return format!("{heading}\n\nNo breaking changes.\n");
106    }
107    let mut out = format!("{heading}\n\n");
108    for (v, note) in entries {
109        out.push_str(&format!("- **v{v}** — {note}\n"));
110    }
111    out.push_str(
112        "\nThe full history is in the \
113         [upgrading page](https://bynk-lang.org/reference/upgrading/).\n",
114    );
115    out
116}
117
118/// Consistency problems on the upgrading page (empty means consistent).
119///
120/// The stamp writes the page, so these only fire on a hand edit or a stamp bug:
121/// the marker is missing, a `## v…` heading does not parse, versions are not
122/// strictly newest-first, an entry has no note, or a version has no row in the
123/// changelog (`changelog`, the changelog page's text) — an entry for an
124/// increment that never shipped.
125pub fn check_page(page: &str, changelog: &str) -> Vec<String> {
126    let mut problems = Vec::new();
127    let Some(at) = page.find(ENTRIES_MARKER) else {
128        return vec![format!("{UPGRADING_PAGE}: missing `{ENTRIES_MARKER}`")];
129    };
130    let headings = page[at..]
131        .lines()
132        .filter(|l| l.starts_with("## "))
133        .collect::<Vec<_>>();
134    let entries = parse_entries(page);
135    if headings.len() != entries.len() {
136        problems.push(format!(
137            "{UPGRADING_PAGE}: {} heading(s) but {} parse as `## vX.Y.Z`",
138            headings.len(),
139            entries.len()
140        ));
141    }
142    for pair in entries.windows(2) {
143        if ordering_key(pair[0].0) <= ordering_key(pair[1].0) {
144            problems.push(format!(
145                "{UPGRADING_PAGE}: v{} must come before v{} (newest first, no duplicates)",
146                pair[1].0, pair[0].0
147            ));
148        }
149    }
150    for (version, note) in &entries {
151        if note.is_empty() {
152            problems.push(format!("{UPGRADING_PAGE}: v{version} has no note"));
153        }
154        if !changelog.contains(&format!("**v{version}**")) {
155            problems.push(format!(
156                "{UPGRADING_PAGE}: v{version} has no row in the changelog"
157            ));
158        }
159    }
160    problems
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn v(s: &str) -> Version {
168        Version::parse(s).unwrap()
169    }
170
171    const PAGE: &str = "# Upgrading\n\nIntro.\n\n<!-- stamp:breaking-entries -->\n\n## v0.3.0\n\nThree breaks `a`.\n\n## v0.2.1\n\nTwo-one breaks `b`.\n\n## v0.1.0\n\nOne breaks `c`.\n\n";
172
173    #[test]
174    fn entries_round_trip_newest_first() {
175        let es = parse_entries(PAGE);
176        let got: Vec<String> = es.iter().map(|(v, _)| v.to_string()).collect();
177        assert_eq!(got, ["0.3.0", "0.2.1", "0.1.0"]);
178        assert_eq!(es[1].1, "Two-one breaks `b`.");
179    }
180
181    #[test]
182    fn insertion_puts_new_entries_above_old_ones() {
183        let new = vec![upgrading_entry(v("0.4.0"), "Four breaks `d`.")];
184        let out = insert_upgrading_entries(PAGE, &new).unwrap();
185        let es = parse_entries(&out);
186        assert_eq!(es.len(), 4);
187        assert_eq!(es[0].0, v("0.4.0"));
188        assert!(out.starts_with("# Upgrading\n\nIntro."));
189    }
190
191    #[test]
192    fn insertion_needs_the_marker() {
193        assert!(insert_upgrading_entries("# no marker\n", &[]).is_err());
194    }
195
196    #[test]
197    fn a_release_tag_may_carry_a_prerelease_suffix() {
198        assert_eq!(parse_release_tag("v0.16.0"), Some(v("0.16.0")));
199        assert_eq!(parse_release_tag("v0.16.0-rc1"), Some(v("0.16.0")));
200        assert_eq!(parse_release_tag("0.16.0"), None);
201        assert_eq!(parse_release_tag("vjunk"), None);
202    }
203
204    #[test]
205    fn previous_tag_skips_prereleases_and_later_tags() {
206        let tags: Vec<String> = ["v0.1.0", "v0.2.1", "v0.3.0-rc1", "v0.3.0", "v0.4.0", "junk"]
207            .map(String::from)
208            .to_vec();
209        assert_eq!(previous_tag(&tags, v("0.3.0")), Some(v("0.2.1")));
210        assert_eq!(previous_tag(&tags, v("0.1.0")), None);
211        // Numeric, not lexical, ordering.
212        let tags = vec!["v0.9.0".to_string(), "v0.10.0".to_string()];
213        assert_eq!(previous_tag(&tags, v("0.11.0")), Some(v("0.10.0")));
214    }
215
216    #[test]
217    fn section_covers_exactly_the_versions_after_prev_up_to_tag() {
218        let s = release_section(PAGE, Some(v("0.1.0")), v("0.3.0"));
219        assert!(s.starts_with("## Upgrading from v0.1.0\n"));
220        assert!(s.contains("**v0.2.1** — Two-one breaks `b`."));
221        assert!(s.contains("**v0.3.0** — Three breaks `a`."));
222        assert!(!s.contains("One breaks"));
223        // Oldest first.
224        assert!(s.find("v0.2.1").unwrap() < s.find("v0.3.0").unwrap());
225        // A version beyond the tag is not in this release.
226        let s = release_section(PAGE, Some(v("0.1.0")), v("0.2.1"));
227        assert!(!s.contains("Three breaks"));
228    }
229
230    #[test]
231    fn section_says_so_when_nothing_breaks() {
232        let s = release_section(PAGE, Some(v("0.3.0")), v("0.3.0"));
233        assert!(s.contains("No breaking changes."));
234        let s = release_section("# no entries\n", None, v("0.3.0"));
235        assert!(s.starts_with("## Upgrading\n"));
236    }
237
238    const LOG: &str = "| **v0.3.0** | x |\n| **v0.2.1** | x |\n| **v0.1.0** | x |\n";
239
240    #[test]
241    fn the_sample_page_is_consistent() {
242        assert_eq!(check_page(PAGE, LOG), Vec::<String>::new());
243    }
244
245    #[test]
246    fn the_gate_flags_each_kind_of_drift() {
247        assert!(check_page("# none\n", LOG)[0].contains("missing"));
248        let swapped = PAGE.replace("## v0.3.0", "## v0.0.9");
249        assert!(
250            check_page(&swapped, LOG)
251                .iter()
252                .any(|p| p.contains("newest first"))
253        );
254        let dup = PAGE.replace("## v0.2.1", "## v0.3.0");
255        assert!(
256            check_page(&dup, LOG)
257                .iter()
258                .any(|p| p.contains("newest first"))
259        );
260        let junk = PAGE.replace("## v0.2.1", "## v0.2");
261        assert!(check_page(&junk, LOG).iter().any(|p| p.contains("parse")));
262        let empty = format!("{PAGE}## v0.0.1\n");
263        assert!(
264            check_page(&empty, LOG)
265                .iter()
266                .any(|p| p.contains("no note"))
267        );
268        assert!(check_page(PAGE, "").iter().any(|p| p.contains("no row")));
269    }
270}