Skip to main content

verctl_core/
changelog.rs

1use anyhow::{Context, Result};
2use minijinja::{Environment, context};
3use serde::Serialize;
4
5// ast-grep-ignore: include-parent-path (TODO(`VER-171`))
6const RELEASE_TEMPLATE: &str = include_str!("../templates/changelog.jinja");
7// ast-grep-ignore: include-parent-path (TODO(`VER-171`))
8const DEPENDENCY_TEMPLATE: &str = include_str!("../templates/dependency-changelog.jinja");
9
10/// A pull request an entry links to.
11#[derive(Debug, Clone, Serialize)]
12pub struct PullRequest {
13    /// The pull request number.
14    pub number: u64,
15    /// Link to the pull request.
16    pub url: String,
17    /// The author's login.
18    pub user: Option<String>,
19    /// Link to the author's profile.
20    pub user_url: Option<String>,
21    /// The author is outside `internal_authors`, so the entry credits them by
22    /// name.
23    pub external_author: bool,
24}
25
26/// A commit an entry links to when no pull request is known.
27#[derive(Debug, Clone, Serialize)]
28pub struct Commit {
29    /// Abbreviated commit SHA.
30    pub short: String,
31    /// Link to the commit.
32    pub url: String,
33}
34
35/// A dependency whose version changed.
36#[derive(Debug, Clone, Serialize)]
37pub struct Dependency {
38    /// The package name.
39    pub name: String,
40    /// The version the dependency was bumped to.
41    pub new_version: String,
42}
43
44/// The data one fragment contributes to a release entry.
45#[derive(Debug, Clone)]
46pub struct ReleaseInput {
47    /// The fragment's first paragraph: every line before the first blank one.
48    pub summary: String,
49    /// Fragment body lines after the first paragraph, starting with the blank
50    /// line that ends it, indented under the entry.
51    pub continuations: Vec<String>,
52    /// The pull request that added the fragment.
53    pub pull_request: Option<PullRequest>,
54    /// The commit that added the fragment, linked when no pull request is
55    /// known.
56    pub commit: Option<Commit>,
57}
58
59impl ReleaseInput {
60    /// Marks the pull request as externally authored unless its author is in
61    /// `internal_authors`.
62    #[must_use]
63    pub fn with_author_filter(mut self, internal_authors: &[String]) -> Self {
64        if let Some(pr) = &mut self.pull_request {
65            let login = pr.user.as_deref().unwrap_or("");
66            pr.external_author =
67                !login.is_empty() && !internal_authors.iter().any(|name| name == login);
68        }
69        self
70    }
71}
72
73/// Whether the summary already ends in `.`, `!`, or `?`.
74#[must_use]
75pub fn summary_has_terminal(summary: &str) -> bool {
76    summary
77        .trim_end()
78        .chars()
79        .next_back()
80        .is_some_and(|ch| matches!(ch, '.' | '!' | '?'))
81}
82
83/// The summary a reference follows, with one trailing period removed.
84///
85/// The entry then ends `… ([#12](url)).` with a single period, never
86/// `…. ([#12](url)).`. An ellipsis (`...`) stays whole, since dropping one dot
87/// would leave `..`.
88#[must_use]
89pub fn summary_body(summary: &str) -> &str {
90    let summary = summary.trim_end();
91    if summary.ends_with("..") {
92        return summary;
93    }
94    summary.strip_suffix('.').unwrap_or(summary)
95}
96
97/// Renders `input` with the stock release template.
98///
99/// # Errors
100///
101/// Returns an error when the stock template fails to render, which a test
102/// guards against.
103pub fn render_release(input: &ReleaseInput) -> Result<String> {
104    render_release_template(RELEASE_TEMPLATE, input)
105}
106
107/// Renders `input` with `template` instead of the stock release template.
108///
109/// # Errors
110///
111/// Returns an error when `template` is not valid minijinja syntax, or when
112/// rendering it fails, for example on an unknown filter or a failed call.
113pub fn render_release_template(template: &str, input: &ReleaseInput) -> Result<String> {
114    let mut env = Environment::new();
115    env.add_template("changelog", template)
116        .context("parse changelog template")?;
117    let tmpl = env.get_template("changelog")?;
118    let rendered = tmpl
119        .render(context! {
120            summary => input.summary,
121            continuations => input.continuations,
122            pull_request => input.pull_request,
123            commit => input.commit,
124            summary_body => summary_body(&input.summary),
125            summary_has_terminal => summary_has_terminal(&input.summary),
126        })
127        .context("render changelog")?;
128    Ok(rendered)
129}
130
131/// Renders the `Updated dependencies:` entry for `dependencies`.
132///
133/// # Errors
134///
135/// Returns an error when the built-in dependency template fails to parse or
136/// render, which a test guards against.
137pub fn render_dependencies(dependencies: &[Dependency]) -> Result<String> {
138    let mut env = Environment::new();
139    env.add_template("deps", DEPENDENCY_TEMPLATE)
140        .context("parse dependency template")?;
141    let tmpl = env.get_template("deps")?;
142    tmpl.render(context! { dependencies => dependencies })
143        .context("render dependency changelog")
144}