sr-core 8.0.8

Core library for sr — a release-state reconciler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use serde::Serialize;

use crate::commit::ConventionalCommit;
use crate::config::ChangelogGroup;
use crate::error::ReleaseError;

/// A single changelog entry representing a release.
#[derive(Debug, Clone, Serialize)]
pub struct ChangelogEntry {
    pub version: String,
    pub date: String,
    /// All commits in this release, flat. Used when rendering a single-package
    /// repo or when `package_sections` is empty (flat layout).
    pub commits: Vec<ConventionalCommit>,
    pub compare_url: Option<String>,
    pub repo_url: Option<String>,
    /// Optional per-package sections (path + its commits). When `len() > 1`,
    /// the default formatter renders per-package subsections under the
    /// version header instead of a flat list. Ignored for single-package
    /// repos or when only one package had commits.
    #[serde(default)]
    pub package_sections: Vec<PackageSection>,
}

/// One package's commits under a release entry. Used for per-package
/// sectioning in monorepos.
#[derive(Debug, Clone, Serialize)]
pub struct PackageSection {
    /// Package path (matches `Config.packages[].path`).
    pub path: String,
    pub commits: Vec<ConventionalCommit>,
}

/// A rendered group of commits for template context.
#[derive(Debug, Clone, Serialize)]
pub struct RenderedGroup {
    pub name: String,
    pub commits: Vec<ConventionalCommit>,
}

/// Formats changelog entries into a string representation.
pub trait ChangelogFormatter: Send + Sync {
    fn format(&self, entries: &[ChangelogEntry]) -> Result<String, ReleaseError>;
}

/// Default formatter using changelog groups.
/// When a custom template is provided, renders using minijinja.
pub struct DefaultChangelogFormatter {
    template: Option<String>,
    groups: Vec<ChangelogGroup>,
}

impl DefaultChangelogFormatter {
    pub fn new(template: Option<String>, groups: Vec<ChangelogGroup>) -> Self {
        Self { template, groups }
    }

    /// Resolve template: if it's a file path that exists, read it.
    /// Otherwise treat as inline template string.
    fn resolve_template(&self) -> Option<String> {
        let tmpl = self.template.as_ref()?;
        if std::path::Path::new(tmpl).exists() {
            std::fs::read_to_string(tmpl).ok()
        } else {
            Some(tmpl.clone())
        }
    }

    /// Build rendered groups from commits using configured groups.
    fn build_groups(&self, commits: &[ConventionalCommit]) -> Vec<RenderedGroup> {
        self.groups
            .iter()
            .map(|group| {
                let group_commits: Vec<_> = commits
                    .iter()
                    .filter(|c| {
                        if group.content.contains(&"breaking".to_string()) {
                            c.breaking
                        } else {
                            !c.breaking && group.content.contains(&c.r#type)
                        }
                    })
                    .cloned()
                    .collect();
                RenderedGroup {
                    name: group.name.clone(),
                    commits: group_commits,
                }
            })
            .collect()
    }
}

impl ChangelogFormatter for DefaultChangelogFormatter {
    fn format(&self, entries: &[ChangelogEntry]) -> Result<String, ReleaseError> {
        if let Some(template_str) = self.resolve_template() {
            // Build groups for each entry and pass to template.
            #[derive(Serialize)]
            struct TemplateEntry {
                version: String,
                date: String,
                groups: Vec<RenderedGroup>,
                compare_url: Option<String>,
                repo_url: Option<String>,
            }

            let template_entries: Vec<_> = entries
                .iter()
                .map(|e| TemplateEntry {
                    version: e.version.clone(),
                    date: e.date.clone(),
                    groups: self.build_groups(&e.commits),
                    compare_url: e.compare_url.clone(),
                    repo_url: e.repo_url.clone(),
                })
                .collect();

            let mut env = minijinja::Environment::new();
            env.add_template("changelog", &template_str)
                .map_err(|e| ReleaseError::Changelog(format!("invalid template: {e}")))?;
            let tmpl = env
                .get_template("changelog")
                .map_err(|e| ReleaseError::Changelog(format!("template error: {e}")))?;
            let output = tmpl
                .render(minijinja::context! { entries => template_entries })
                .map_err(|e| ReleaseError::Changelog(format!("template render error: {e}")))?;
            return Ok(output.trim_end().to_string());
        }

        // Built-in default format using groups.
        let mut output = String::new();

        for entry in entries {
            output.push_str(&format!("## {} ({})\n", entry.version, entry.date));

            // Decide: per-package sections vs. flat.
            //
            // Use per-package sections when more than one package has commits
            // in this release. Single-package repos (or releases where only
            // one package changed) render flat for readability.
            let non_empty_sections: Vec<&PackageSection> = entry
                .package_sections
                .iter()
                .filter(|s| !s.commits.is_empty())
                .collect();
            let multi_package = non_empty_sections.len() > 1;

            if multi_package {
                for section in &non_empty_sections {
                    output.push_str(&format!("\n### {}\n", section.path));
                    render_groups(
                        &mut output,
                        &self.build_groups(&section.commits),
                        entry.repo_url.as_deref(),
                        /*heading_level=*/ 4,
                    );
                }
            } else {
                render_groups(
                    &mut output,
                    &self.build_groups(&entry.commits),
                    entry.repo_url.as_deref(),
                    /*heading_level=*/ 3,
                );
            }

            if let Some(url) = &entry.compare_url {
                output.push_str(&format!("\n[Full Changelog]({url})\n"));
            }

            output.push('\n');
        }

        Ok(output.trim_end().to_string())
    }
}

fn render_groups(
    output: &mut String,
    groups: &[RenderedGroup],
    repo_url: Option<&str>,
    heading_level: usize,
) {
    let heading_marker = "#".repeat(heading_level);
    for group in groups {
        if group.commits.is_empty() {
            continue;
        }
        let title = group
            .name
            .split('-')
            .map(|w| {
                let mut c = w.chars();
                match c.next() {
                    None => String::new(),
                    Some(f) => f.to_uppercase().to_string() + c.as_str(),
                }
            })
            .collect::<Vec<_>>()
            .join(" ");
        output.push_str(&format!("\n{heading_marker} {title}\n\n"));
        for commit in &group.commits {
            format_commit_line(output, commit, repo_url);
        }
    }
}

fn format_commit_line(output: &mut String, commit: &ConventionalCommit, repo_url: Option<&str>) {
    let short_sha = &commit.sha[..7.min(commit.sha.len())];
    let sha_display = match repo_url {
        Some(url) => format!("[{short_sha}]({url}/commit/{})", commit.sha),
        None => short_sha.to_string(),
    };
    if let Some(scope) = &commit.scope {
        output.push_str(&format!(
            "- **{scope}**: {} ({sha_display})\n",
            commit.description
        ));
    } else {
        output.push_str(&format!("- {} ({sha_display})\n", commit.description));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::default_changelog_groups;

    fn make_commit(
        type_: &str,
        desc: &str,
        scope: Option<&str>,
        breaking: bool,
    ) -> ConventionalCommit {
        ConventionalCommit {
            sha: "abc1234def5678".into(),
            r#type: type_.into(),
            scope: scope.map(Into::into),
            description: desc.into(),
            body: None,
            breaking,
        }
    }

    fn entry(commits: Vec<ConventionalCommit>, compare_url: Option<&str>) -> ChangelogEntry {
        ChangelogEntry {
            version: "1.0.0".into(),
            date: "2025-01-01".into(),
            commits,
            compare_url: compare_url.map(Into::into),
            repo_url: None,
            package_sections: Vec::new(),
        }
    }

    fn format(entries: &[ChangelogEntry]) -> String {
        DefaultChangelogFormatter::new(None, default_changelog_groups())
            .format(entries)
            .unwrap()
    }

    #[test]
    fn format_features_only() {
        let out = format(&[entry(
            vec![make_commit("feat", "add button", None, false)],
            None,
        )]);
        assert!(out.contains("## 1.0.0"));
        assert!(out.contains("### Features"));
        assert!(out.contains("add button"));
    }

    #[test]
    fn format_fixes_only() {
        let out = format(&[entry(
            vec![make_commit("fix", "null check", None, false)],
            None,
        )]);
        assert!(out.contains("### Bug Fixes"));
        assert!(out.contains("null check"));
    }

    #[test]
    fn format_breaking_changes() {
        let out = format(&[entry(
            vec![make_commit("feat", "new API", None, true)],
            None,
        )]);
        assert!(out.contains("### Breaking"));
    }

    #[test]
    fn format_mixed_commits() {
        let commits = vec![
            make_commit("feat", "add button", None, false),
            make_commit("fix", "null check", None, false),
            make_commit("feat", "breaking thing", None, true),
        ];
        let out = format(&[entry(commits, None)]);
        assert!(out.contains("### Features"));
        assert!(out.contains("### Bug Fixes"));
        assert!(out.contains("### Breaking"));
    }

    #[test]
    fn format_with_scope() {
        let out = format(&[entry(
            vec![make_commit("feat", "add flag", Some("cli"), false)],
            None,
        )]);
        assert!(out.contains("**cli**:"));
    }

    #[test]
    fn format_with_compare_url() {
        let out = format(&[entry(
            vec![make_commit("feat", "add button", None, false)],
            Some("https://github.com/o/r/compare/v0.1.0...v1.0.0"),
        )]);
        assert!(out.contains("[Full Changelog]"));
    }

    #[test]
    fn format_empty_entries() {
        let out = format(&[entry(vec![], None)]);
        assert!(!out.contains("### Features"));
        assert!(!out.contains("### Bug Fixes"));
    }

    #[test]
    fn format_with_commit_links() {
        let mut e = entry(vec![make_commit("feat", "add button", None, false)], None);
        e.repo_url = Some("https://github.com/o/r".into());
        let out = format(&[e]);
        assert!(out.contains("[abc1234](https://github.com/o/r/commit/abc1234def5678)"));
    }

    #[test]
    fn format_breaking_at_top() {
        let commits = vec![
            make_commit("feat", "add button", None, false),
            make_commit("feat", "breaking thing", None, true),
        ];
        let out = format(&[entry(commits, None)]);
        let breaking_pos = out.find("### Breaking").unwrap();
        let features_pos = out.find("### Features").unwrap();
        assert!(breaking_pos < features_pos);
    }

    #[test]
    fn format_misc_catch_all() {
        let commits = vec![
            make_commit("feat", "add button", None, false),
            make_commit("chore", "tidy up", None, false),
            make_commit("ci", "fix pipeline", None, false),
        ];
        let out = format(&[entry(commits, None)]);
        assert!(out.contains("### Misc"));
        assert!(out.contains("tidy up"));
        assert!(out.contains("fix pipeline"));
    }

    #[test]
    fn format_breaking_excluded_from_type_sections() {
        let commits = vec![
            make_commit("feat", "normal feature", None, false),
            make_commit("feat", "breaking feature", None, true),
        ];
        let out = format(&[entry(commits, None)]);
        let features_section_start = out.find("### Features").unwrap();
        let features_section_end = out[features_section_start..]
            .find("\n### ")
            .map(|p| features_section_start + p)
            .unwrap_or(out.len());
        let features_section = &out[features_section_start..features_section_end];
        assert!(features_section.contains("normal feature"));
        assert!(!features_section.contains("breaking feature"));
    }

    #[test]
    fn custom_template_renders() {
        let template = r#"{% for entry in entries %}Release {{ entry.version }}
{% for group in entry.groups %}{% if group.commits %}{{ group.name }}:
{% for c in group.commits %}- {{ c.description }}
{% endfor %}{% endif %}{% endfor %}{% endfor %}"#;
        let formatter =
            DefaultChangelogFormatter::new(Some(template.into()), default_changelog_groups());
        let out = formatter
            .format(&[entry(
                vec![
                    make_commit("feat", "add button", None, false),
                    make_commit("fix", "null check", None, false),
                ],
                None,
            )])
            .unwrap();
        assert!(out.contains("Release 1.0.0"));
        assert!(out.contains("- add button"));
        assert!(out.contains("- null check"));
        assert!(!out.contains("### Features"));
    }

    #[test]
    fn invalid_template_returns_error() {
        let template = "{% invalid %}";
        let formatter =
            DefaultChangelogFormatter::new(Some(template.into()), default_changelog_groups());
        let result = formatter.format(&[entry(vec![], None)]);
        assert!(result.is_err());
    }
}