grubble 5.0.1

Automatic semantic versioning based on conventional commits, optimized for AI-generated commit messages
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use crate::analyser::BumpType;
use crate::error::BumperResult;
use crate::versioner::Version;
use chrono::Local;
use regex::Regex;
use std::fs;
use std::path::Path;

const CHANGELOG_FILE: &str = "CHANGELOG.md";

/// Represents a parsed changelog entry
#[derive(Debug)]
#[allow(dead_code)]
struct ChangelogEntry {
    version: String,
    date: String,
    changes: Vec<Change>,
}

#[derive(Debug)]
struct Change {
    category: ChangeCategory,
    description: String,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
#[allow(dead_code)]
enum ChangeCategory {
    Added,
    Changed,
    Deprecated,
    Removed,
    Fixed,
    Security,
}

impl ChangeCategory {
    fn as_str(&self) -> &'static str {
        match self {
            ChangeCategory::Added => "### Added",
            ChangeCategory::Changed => "### Changed",
            ChangeCategory::Deprecated => "### Deprecated",
            ChangeCategory::Removed => "### Removed",
            ChangeCategory::Fixed => "### Fixed",
            ChangeCategory::Security => "### Security",
        }
    }

    fn from_commit_type(commit_type: &str) -> Self {
        match commit_type {
            "feat" => ChangeCategory::Added,
            "fix" => ChangeCategory::Fixed,
            "perf" => ChangeCategory::Changed,
            "refactor" => ChangeCategory::Changed,
            "revert" => ChangeCategory::Removed,
            "security" => ChangeCategory::Security,
            _ => ChangeCategory::Changed,
        }
    }
}

/// Categorize commits and generate changelog entry
pub fn generate_changelog_entry(
    version: &Version,
    commits: &[String],
    _bump_type: BumpType,
) -> BumperResult<()> {
    generate_changelog_entry_at_path(version, commits, Path::new(CHANGELOG_FILE))
}

/// Internal function that accepts a custom path for testing
fn generate_changelog_entry_at_path(
    version: &Version,
    commits: &[String],
    changelog_path: &Path,
) -> BumperResult<()> {
    let date = Local::now().format("%Y-%m-%d").to_string();

    // Parse commits into categorized changes
    let mut changes: Vec<Change> = Vec::new();
    let commit_regex = Regex::new(r"^([a-z]+)(?:\([^)]+\))?(!?): (.+)$").unwrap();

    for commit in commits {
        if commit.starts_with("chore: bump version") || commit.starts_with("chore: sync package") {
            continue;
        }

        if let Some(captures) = commit_regex.captures(commit) {
            let commit_type = captures.get(1).map(|m| m.as_str()).unwrap_or("");
            let has_breaking = captures.get(2).map(|m| m.as_str()).unwrap_or("") == "!";
            let description = captures.get(3).map(|m| m.as_str()).unwrap_or(commit);

            // Breaking changes go under Changed (or Removed if it's a removal)
            let category = if has_breaking {
                ChangeCategory::Changed
            } else {
                ChangeCategory::from_commit_type(commit_type)
            };

            let mut desc = description.to_string();
            if has_breaking {
                desc = format!("**BREAKING:** {}", desc);
            }

            changes.push(Change {
                category,
                description: desc,
            });
        } else {
            // Fallback for commits that don't match conventional format
            changes.push(Change {
                category: ChangeCategory::Changed,
                description: commit.clone(),
            });
        }
    }

    // Sort changes by category
    changes.sort_by(|a, b| a.category.cmp(&b.category));

    // Generate changelog content
    let mut entry = format!("## [{}] - {}\n\n", version, date);

    let mut current_category: Option<ChangeCategory> = None;
    for change in changes {
        if current_category.as_ref() != Some(&change.category) {
            // Add blank line after previous list (if exists)
            if current_category.is_some() {
                entry.push('\n');
            }
            entry.push_str(&format!("{}\n\n", change.category.as_str()));
            current_category = Some(change.category);
        }
        entry.push_str(&format!("- {}\n", change.description));
    }

    // Read existing changelog or create header
    let mut content = if changelog_path.exists() {
        fs::read_to_string(changelog_path)?
    } else {
        String::from("# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n")
    };

    // Find where to insert the new entry (after the header, before existing entries)
    let insertion_point = if let Some(pos) = content.find("\n## [") {
        // Add blank line after the new entry if there are existing entries
        entry.push('\n');
        pos + 1
    } else {
        content.len()
    };

    content.insert_str(insertion_point, &entry);

    // Write updated changelog
    fs::write(changelog_path, content)?;

    Ok(())
}

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

    #[test]
    fn test_change_category_from_commit_type() {
        assert_eq!(
            ChangeCategory::from_commit_type("feat"),
            ChangeCategory::Added
        );
        assert_eq!(
            ChangeCategory::from_commit_type("fix"),
            ChangeCategory::Fixed
        );
        assert_eq!(
            ChangeCategory::from_commit_type("refactor"),
            ChangeCategory::Changed
        );
        assert_eq!(
            ChangeCategory::from_commit_type("perf"),
            ChangeCategory::Changed
        );
        assert_eq!(
            ChangeCategory::from_commit_type("revert"),
            ChangeCategory::Removed
        );
        assert_eq!(
            ChangeCategory::from_commit_type("security"),
            ChangeCategory::Security
        );
    }

    #[test]
    fn test_change_category_ordering() {
        assert!(ChangeCategory::Added < ChangeCategory::Changed);
        assert!(ChangeCategory::Fixed < ChangeCategory::Security);
        assert!(ChangeCategory::Added < ChangeCategory::Fixed);
    }

    #[test]
    fn test_generate_changelog_entry_creates_new_file() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: add new feature".to_string(),
            "fix: resolve bug".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        assert!(changelog_path.exists());

        let content = fs::read_to_string(&changelog_path).unwrap();
        assert!(content.contains("# Changelog"));
        assert!(content.contains("## [1.0.0]"));
        assert!(content.contains("### Added"));
        assert!(content.contains("- add new feature"));
        assert!(content.contains("### Fixed"));
        assert!(content.contains("- resolve bug"));

        // Verify no double blank lines (triple newlines) in the file
        assert!(
            !content.contains("\n\n\n"),
            "New changelog should not have double blank lines"
        );

        // The file should end with a single newline, not multiple blank lines
        assert!(
            !content.ends_with("\n\n\n"),
            "New changelog should not end with double blank lines"
        );
        assert!(
            !content.ends_with("\n\n"),
            "New changelog should not end with a blank line (should end with single newline after last list item)"
        );
    }

    #[test]
    fn test_new_changelog_file_has_no_double_blank_lines_at_end() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec!["feat: first feature".to_string()];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // For a new file with just one entry, the structure should be:
        // - Header (ending with \n\n)
        // - Version header: "## [1.0.0] - date\n\n"
        // - Category header: "### Added\n\n"
        // - List item: "- first feature\n"
        // - End of file (no extra newlines)

        // Verify the ending structure
        assert!(
            content.ends_with("- first feature\n"),
            "New changelog should end with list item + single newline, but got: {:?}",
            &content[content.len().saturating_sub(30)..]
        );

        // Verify no triple newlines anywhere (which would be double blank lines)
        assert!(
            !content.contains("\n\n\n"),
            "New changelog should not contain double blank lines"
        );

        // Count the total newlines at the end - should be exactly 1
        let trailing_newlines = content.chars().rev().take_while(|&c| c == '\n').count();
        assert_eq!(
            trailing_newlines, 1,
            "New changelog should end with exactly 1 newline, found {}",
            trailing_newlines
        );
    }

    #[test]
    fn test_generate_changelog_entry_updates_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        // Create initial changelog
        let version1 = Version::parse("1.0.0").unwrap();
        let commits1 = vec!["feat: initial feature".to_string()];
        generate_changelog_entry_at_path(&version1, &commits1, &changelog_path).unwrap();

        // Add second version
        let version2 = Version::parse("1.1.0").unwrap();
        let commits2 = vec!["feat: another feature".to_string()];
        generate_changelog_entry_at_path(&version2, &commits2, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Check both versions exist and in correct order
        let v1_pos = content.find("## [1.0.0]").unwrap();
        let v2_pos = content.find("## [1.1.0]").unwrap();
        assert!(v2_pos < v1_pos, "Newer version should appear first");

        assert!(content.contains("- initial feature"));
        assert!(content.contains("- another feature"));
    }

    #[test]
    fn test_generate_changelog_entry_with_breaking_changes() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("2.0.0").unwrap();
        let commits = vec![
            "feat!: breaking change".to_string(),
            "fix: normal fix".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        assert!(content.contains("### Changed"));
        assert!(content.contains("**BREAKING:** breaking change"));
        assert!(content.contains("### Fixed"));
        assert!(content.contains("- normal fix"));
    }

    #[test]
    fn test_generate_changelog_entry_with_scopes() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat(api): add new endpoint".to_string(),
            "fix(ui): correct button alignment".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        assert!(content.contains("- add new endpoint"));
        assert!(content.contains("- correct button alignment"));
    }

    #[test]
    fn test_generate_changelog_entry_skips_version_bump_commits() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: add feature".to_string(),
            "chore: bump version to 0.9.0".to_string(),
            "chore: sync package version".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        assert!(content.contains("- add feature"));
        assert!(!content.contains("bump version"));
        assert!(!content.contains("sync package"));
    }

    #[test]
    fn test_generate_changelog_entry_groups_by_category() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "fix: bug 1".to_string(),
            "feat: feature 1".to_string(),
            "fix: bug 2".to_string(),
            "feat: feature 2".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Check that features are grouped together
        let added_pos = content.find("### Added").unwrap();
        let feature1_pos = content.find("- feature 1").unwrap();
        let feature2_pos = content.find("- feature 2").unwrap();

        assert!(added_pos < feature1_pos);
        assert!(added_pos < feature2_pos);

        // Check that fixes are grouped together
        let fixed_pos = content.find("### Fixed").unwrap();
        let bug1_pos = content.find("- bug 1").unwrap();
        let bug2_pos = content.find("- bug 2").unwrap();

        assert!(fixed_pos < bug1_pos);
        assert!(fixed_pos < bug2_pos);
    }

    #[test]
    fn test_generate_changelog_entry_with_non_conventional_commits() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: proper feature".to_string(),
            "Some random commit message".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Non-conventional commits should still be included under Changed
        assert!(content.contains("### Added"));
        assert!(content.contains("- proper feature"));
        assert!(content.contains("### Changed"));
        assert!(content.contains("Some random commit message"));
    }

    #[test]
    fn test_generate_changelog_entry_multiple_categories() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: new feature".to_string(),
            "fix: bug fix".to_string(),
            "perf: performance improvement".to_string(),
            "refactor: code refactor".to_string(),
            "revert: revert change".to_string(),
            "security: security fix".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Verify all categories appear in the correct order
        assert!(content.contains("### Added"));
        assert!(content.contains("### Changed"));
        assert!(content.contains("### Removed"));
        assert!(content.contains("### Fixed"));
        assert!(content.contains("### Security"));

        // Verify category ordering (Added should come before Changed, etc.)
        let added_pos = content.find("### Added").unwrap();
        let changed_pos = content.find("### Changed").unwrap();
        let removed_pos = content.find("### Removed").unwrap();
        let fixed_pos = content.find("### Fixed").unwrap();
        let security_pos = content.find("### Security").unwrap();

        assert!(added_pos < changed_pos);
        assert!(changed_pos < removed_pos);
        assert!(removed_pos < fixed_pos);
        assert!(fixed_pos < security_pos);
    }

    #[test]
    fn test_generate_changelog_entry_markdown_lint_compliance() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: add new feature".to_string(),
            "fix: resolve bug".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Test MD032: Lists should be surrounded by blank lines
        // Check that there's a blank line after "### Added" before the list
        assert!(content.contains("### Added\n\n- add new feature\n\n"));

        // Test MD022: Headings should be surrounded by blank lines
        // Check that there's a blank line before "### Fixed" heading
        assert!(content.contains("\n\n### Fixed\n\n"));

        // Verify the list ends with a blank line
        assert!(content.contains("- resolve bug\n"));

        // Test: No triple newlines (double blank lines) should exist
        assert!(
            !content.contains("\n\n\n"),
            "Found triple newlines (double blank lines)"
        );

        // Test: No trailing whitespace after newlines
        for line in content.lines() {
            assert!(
                !line.ends_with(' '),
                "Found trailing whitespace on line: {}",
                line
            );
        }
    }

    #[test]
    fn test_generate_changelog_entry_proper_spacing_between_releases() {
        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        // Create first release
        let version1 = Version::parse("1.0.0").unwrap();
        let commits1 = vec!["feat: initial feature".to_string()];
        generate_changelog_entry_at_path(&version1, &commits1, &changelog_path).unwrap();

        // Create second release
        let version2 = Version::parse("1.1.0").unwrap();
        let commits2 = vec!["fix: bug fix".to_string()];
        generate_changelog_entry_at_path(&version2, &commits2, &changelog_path).unwrap();

        // Create third release
        let version3 = Version::parse("1.2.0").unwrap();
        let commits3 = vec!["feat: another feature".to_string()];
        generate_changelog_entry_at_path(&version3, &commits3, &changelog_path).unwrap();

        let content = fs::read_to_string(&changelog_path).unwrap();

        // Verify proper spacing: should have exactly one blank line between release entries
        // Pattern should be: "- item\n\n## [version]" (list item, blank line, next header)
        assert!(
            content.contains("- another feature\n\n## [1.1.0]"),
            "Missing blank line between [1.2.0] and [1.1.0]"
        );
        assert!(
            content.contains("- bug fix\n\n## [1.0.0]"),
            "Missing blank line between [1.1.0] and [1.0.0]"
        );

        // Should NOT have double blank lines (triple newlines)
        assert!(
            !content.contains("\n\n\n"),
            "Found double blank line (triple newlines) in changelog"
        );

        // Verify all versions are present and in correct order
        let v3_pos = content.find("## [1.2.0]").unwrap();
        let v2_pos = content.find("## [1.1.0]").unwrap();
        let v1_pos = content.find("## [1.0.0]").unwrap();
        assert!(
            v3_pos < v2_pos && v2_pos < v1_pos,
            "Versions not in descending order"
        );
    }

    #[test]
    fn test_markdown_linter_if_available() {
        use std::process::Command;

        // Only run this test in CI or when explicitly requested
        if std::env::var("CI").is_err() && std::env::var("RUN_MARKDOWN_LINT").is_err() {
            println!("⚠ Skipping markdown linter test (run with RUN_MARKDOWN_LINT=1 to enable)");
            return;
        }

        let temp_dir = TempDir::new().unwrap();
        let changelog_path = temp_dir.path().join("CHANGELOG.md");

        let version = Version::parse("1.0.0").unwrap();
        let commits = vec![
            "feat: add new feature".to_string(),
            "fix: resolve bug".to_string(),
            "refactor: improve code".to_string(),
        ];

        generate_changelog_entry_at_path(&version, &commits, &changelog_path).unwrap();

        // Try to run markdownlint-cli if available
        let result = Command::new("npx")
            .args(["markdownlint-cli", changelog_path.to_str().unwrap()])
            .output();

        match result {
            Ok(output) => {
                if output.status.success() {
                    println!("✓ Markdown linter passed!");
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    let stdout = String::from_utf8_lossy(&output.stdout);
                    panic!(
                        "Markdown linter failed!\nstdout: {}\nstderr: {}",
                        stdout, stderr
                    );
                }
            }
            Err(e) => {
                panic!("markdownlint-cli not available but required in CI: {}", e);
            }
        }
    }
}