ferrflow 5.11.1

Universal semantic versioning for monorepos and classic repos
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#[cfg(feature = "cli")]
use crate::conventional_commits::determine_bump;
use crate::conventional_commits::{BumpType, CommitCategory, classify_commit, parse_subject};
use anyhow::Result;
use chrono::Local;
use std::path::Path;

pub struct GitLog {
    pub hash: String,
    pub message: String,
}

#[cfg(feature = "cli")]
pub fn generate_only(config_path: Option<&Path>, dry_run: bool) -> Result<()> {
    use crate::config::Config;
    use crate::formats::read_version;
    use crate::git::{
        find_highest_semver_tag_with_cache, get_commits_since_last_tag, get_repo_root, open_repo,
    };
    use crate::versioning::bump_version;
    use colored::Colorize;
    let repo = open_repo(&std::env::current_dir()?)?;
    let root = get_repo_root(&repo)?;
    let config = Config::load(&root, config_path)?;

    if config.packages.is_empty() {
        println!(
            "{}",
            "No packages configured. Run `ferrflow init` to create a ferrflow config.".yellow()
        );
        return Ok(());
    }

    for pkg in &config.packages {
        let tag_prefix = format!("{}@v", pkg.name);
        let skip_markers = config.workspace.effective_commit_skip_markers();
        let commits = get_commits_since_last_tag(
            &repo,
            &tag_prefix,
            config.workspace.orphaned_tag_strategy,
            &skip_markers,
        )?;

        if commits.is_empty() {
            continue;
        }

        let bump = commits
            .iter()
            .map(|c| determine_bump(&c.message))
            .max()
            .unwrap_or(BumpType::None);

        if bump == BumpType::None {
            continue;
        }

        // `versionedFiles` is optional — see #531. If no file is
        // configured, fall back to the highest existing tag, then to
        // 0.0.0 if there are no tags yet.
        let current_version = match pkg.versioned_files.first() {
            Some(vf) => read_version(vf, &root)?,
            None => find_highest_semver_tag_with_cache(
                &repo,
                &tag_prefix,
                config.workspace.orphaned_tag_strategy,
                None,
            )?
            .map(|(_tag, version)| version)
            .unwrap_or_else(|| "0.0.0".to_string()),
        };
        let new_version = bump_version(&current_version, bump)?;

        let changelog_path = match &pkg.changelog {
            Some(rel) => crate::formats::join_within_repo(&root, rel)?,
            None => {
                println!(
                    "{}",
                    format!(
                        "  No changelog configured for '{}', defaulting to CHANGELOG.md.",
                        pkg.name
                    )
                    .yellow()
                );
                root.join("CHANGELOG.md")
            }
        };

        update_changelog(
            &changelog_path,
            &pkg.name,
            &new_version,
            &commits,
            bump,
            dry_run,
        )?;
    }

    Ok(())
}

pub fn build_section(new_version: &str, commits: &[GitLog]) -> String {
    let date = Local::now().format("%Y-%m-%d").to_string();
    let mut breaking = Vec::new();
    let mut features = Vec::new();
    let mut fixes = Vec::new();
    let mut refactors = Vec::new();

    // Reuse the same classifier that drives `determine_bump` so the
    // changelog can never label a release "Breaking Changes" while the
    // bump engine computed a minor — and so `refactor:` commits, which
    // are Patch in the bump engine, no longer disappear from the
    // rendered section. See #525.
    for commit in commits {
        let subject = parse_subject(&commit.message);
        match classify_commit(&commit.message) {
            CommitCategory::Breaking => breaking.push(format!("- {subject}")),
            CommitCategory::Feature => features.push(format!("- {subject}")),
            CommitCategory::Fix => fixes.push(format!("- {subject}")),
            CommitCategory::Refactor => refactors.push(format!("- {subject}")),
            CommitCategory::Other => {}
        }
    }

    let mut section = format!("\n## [{new_version}] - {date}\n");

    if !breaking.is_empty() {
        section.push_str("\n### Breaking Changes\n\n");
        section.push_str(&breaking.join("\n"));
        section.push('\n');
    }
    if !features.is_empty() {
        section.push_str("\n### Features\n\n");
        section.push_str(&features.join("\n"));
        section.push('\n');
    }
    if !fixes.is_empty() {
        section.push_str("\n### Bug Fixes\n\n");
        section.push_str(&fixes.join("\n"));
        section.push('\n');
    }
    if !refactors.is_empty() {
        section.push_str("\n### Refactoring\n\n");
        section.push_str(&refactors.join("\n"));
        section.push('\n');
    }

    section
}

pub fn update_changelog(
    changelog_path: &Path,
    package_name: &str,
    new_version: &str,
    commits: &[GitLog],
    bump: BumpType,
    dry_run: bool,
) -> Result<()> {
    if bump == BumpType::None {
        return Ok(());
    }

    let section = build_section(new_version, commits);

    if dry_run {
        println!(
            "  [dry-run] Would update {}: {}",
            changelog_path.display(),
            section.trim()
        );
        return Ok(());
    }

    let existing = if changelog_path.exists() {
        std::fs::read_to_string(changelog_path)?
    } else {
        format!(
            "# Changelog\n\nAll notable changes to `{package_name}` will be documented here.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/).\n"
        )
    };

    let new_content = if let Some(pos) = existing.find("\n## ") {
        format!("{}{}{}", &existing[..pos], section, &existing[pos..])
    } else {
        format!("{}\n{}", existing.trim_end(), section)
    };

    std::fs::write(changelog_path, new_content)?;
    println!("  ✓ Updated {}", changelog_path.display());
    Ok(())
}

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

    fn make_commits(messages: &[&str]) -> Vec<GitLog> {
        messages
            .iter()
            .map(|m| GitLog {
                hash: "abc1234".to_string(),
                message: m.to_string(),
            })
            .collect()
    }

    #[test]
    fn build_section_features_only() {
        let commits = make_commits(&["feat: add login", "feat(ui): new dashboard"]);
        let section = build_section("1.1.0", &commits);
        assert!(section.contains("## [1.1.0]"));
        assert!(section.contains("### Features"));
        assert!(section.contains("- feat: add login"));
        assert!(section.contains("- feat(ui): new dashboard"));
        assert!(!section.contains("### Bug Fixes"));
        assert!(!section.contains("### Breaking Changes"));
    }

    #[test]
    fn build_section_fixes_only() {
        let commits = make_commits(&["fix: null pointer", "perf: faster query"]);
        let section = build_section("1.0.1", &commits);
        assert!(section.contains("### Bug Fixes"));
        assert!(section.contains("- fix: null pointer"));
        assert!(section.contains("- perf: faster query"));
        assert!(!section.contains("### Features"));
    }

    #[test]
    fn build_section_breaking_changes() {
        let commits = make_commits(&["feat!: remove old API"]);
        let section = build_section("2.0.0", &commits);
        assert!(section.contains("### Breaking Changes"));
        assert!(section.contains("- feat!: remove old API"));
    }

    #[test]
    fn build_section_mixed_commits() {
        let commits = make_commits(&[
            "feat: new feature",
            "fix: bug fix",
            "feat!: breaking",
            "chore: update deps",
        ]);
        let section = build_section("2.0.0", &commits);
        assert!(section.contains("### Breaking Changes"));
        assert!(section.contains("### Features"));
        assert!(section.contains("### Bug Fixes"));
        assert!(!section.contains("chore: update deps"));
    }

    #[test]
    fn build_section_does_not_misclassify_prose() {
        let commits = make_commits(&[
            "fix: handle the !: token in the parser",
            "features added without a conventional prefix",
        ]);
        let section = build_section("1.0.1", &commits);
        assert!(section.contains("### Bug Fixes"));
        assert!(section.contains("- fix: handle the !: token in the parser"));
        assert!(!section.contains("### Breaking Changes"));
        assert!(!section.contains("### Features"));
    }

    #[test]
    fn build_section_empty_commits() {
        let section = build_section("1.0.0", &[]);
        assert!(section.contains("## [1.0.0]"));
        assert!(!section.contains("### "));
    }

    #[test]
    fn update_changelog_creates_new_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        let commits = make_commits(&["feat: initial"]);
        update_changelog(&path, "myapp", "0.1.0", &commits, BumpType::Minor, false).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("# Changelog"));
        assert!(content.contains("## [0.1.0]"));
        assert!(content.contains("- feat: initial"));
    }

    #[test]
    fn update_changelog_inserts_before_existing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        std::fs::write(
            &path,
            "# Changelog\n\n## [1.0.0] - 2025-01-01\n\n- old stuff\n",
        )
        .unwrap();
        let commits = make_commits(&["feat: new stuff"]);
        update_changelog(&path, "myapp", "1.1.0", &commits, BumpType::Minor, false).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        let pos_new = content.find("## [1.1.0]").unwrap();
        let pos_old = content.find("## [1.0.0]").unwrap();
        assert!(pos_new < pos_old, "new version should come before old");
    }

    #[test]
    fn update_changelog_skips_none_bump() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        update_changelog(&path, "myapp", "1.0.0", &[], BumpType::None, false).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn update_changelog_dry_run_no_write() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        let commits = make_commits(&["feat: something"]);
        update_changelog(&path, "myapp", "1.0.0", &commits, BumpType::Minor, true).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn build_section_breaking_change_in_body() {
        let commits = vec![GitLog {
            hash: "abc".to_string(),
            message: "feat: add endpoint\n\nBREAKING CHANGE: removed old endpoint".to_string(),
        }];
        let section = build_section("2.0.0", &commits);
        assert!(section.contains("### Breaking Changes"));
    }

    #[test]
    fn build_section_chore_docs_excluded_refactor_kept() {
        // chore/docs/ci/style/test/build don't bump and don't appear in
        // the user-facing changelog. refactor: DOES bump (patch) and
        // must appear, otherwise a release shows up with an empty
        // changelog section. See #525.
        let commits = make_commits(&[
            "refactor: clean up",
            "chore: update deps",
            "docs: update readme",
            "ci: fix pipeline",
            "style: format code",
            "test: add tests",
            "build: update config",
        ]);
        let section = build_section("1.0.1", &commits);
        assert!(!section.contains("### Features"));
        assert!(!section.contains("### Bug Fixes"));
        assert!(!section.contains("### Breaking Changes"));
        assert!(
            section.contains("### Refactoring"),
            "refactor: must render its own section, not be silently dropped"
        );
        assert!(section.contains("- refactor: clean up"));
        assert!(!section.contains("chore: update deps"));
        assert!(!section.contains("docs: update readme"));
        assert!(!section.contains("ci: fix pipeline"));
        assert!(!section.contains("style: format code"));
        assert!(!section.contains("test: add tests"));
        assert!(!section.contains("build: update config"));
    }

    #[test]
    fn build_section_does_not_misclassify_feature_word() {
        // `feature:` (no colon-delimited type) and `feat add` (no colon)
        // are not the conventional `feat:` type and must not appear as
        // features.
        let commits = make_commits(&["feature: misnamed type", "feat add no colon"]);
        let section = build_section("1.0.1", &commits);
        assert!(!section.contains("### Features"));
        assert!(!section.contains("misnamed type"));
        assert!(!section.contains("no colon"));
    }

    #[test]
    fn build_section_scoped_commits() {
        let commits = make_commits(&["feat(api): add endpoint", "fix(db): connection leak"]);
        let section = build_section("1.1.0", &commits);
        assert!(section.contains("- feat(api): add endpoint"));
        assert!(section.contains("- fix(db): connection leak"));
    }

    #[test]
    fn build_section_perf_in_fixes() {
        let commits = make_commits(&["perf: optimize query"]);
        let section = build_section("1.0.1", &commits);
        assert!(section.contains("### Bug Fixes"));
        assert!(section.contains("- perf: optimize query"));
    }

    #[test]
    fn update_changelog_preserves_existing_content() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        std::fs::write(
            &path,
            "# Changelog\n\n## [1.0.0] - 2025-01-01\n\n- feat: initial release\n",
        )
        .unwrap();
        let commits = make_commits(&["feat: new feature"]);
        update_changelog(&path, "myapp", "1.1.0", &commits, BumpType::Minor, false).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("## [1.1.0]"));
        assert!(content.contains("## [1.0.0]"));
        assert!(content.contains("- feat: initial release"));
    }

    #[test]
    fn update_changelog_empty_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");
        std::fs::write(&path, "").unwrap();
        let commits = make_commits(&["feat: first"]);
        update_changelog(&path, "myapp", "0.1.0", &commits, BumpType::Minor, false).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("## [0.1.0]"));
    }

    #[test]
    fn build_section_contains_date() {
        let commits = make_commits(&["feat: something"]);
        let section = build_section("1.0.0", &commits);
        let today = chrono::Local::now().format("%Y-%m-%d").to_string();
        assert!(section.contains(&today));
    }

    #[test]
    fn update_changelog_multiple_versions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("CHANGELOG.md");

        let commits1 = make_commits(&["feat: first"]);
        update_changelog(&path, "myapp", "0.1.0", &commits1, BumpType::Minor, false).unwrap();

        let commits2 = make_commits(&["feat: second"]);
        update_changelog(&path, "myapp", "0.2.0", &commits2, BumpType::Minor, false).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        let pos1 = content.find("## [0.2.0]").unwrap();
        let pos2 = content.find("## [0.1.0]").unwrap();
        assert!(pos1 < pos2, "newer version should come first");
    }
}