knope-versioning 0.8.0

A library for handling all the versioned files supported by Knope
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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use std::{borrow::Cow, fmt::Write, iter::Peekable};

pub use changelog::Changelog;
pub use config::{CommitFooter, CustomChangeType, SectionName, SectionSource, Sections};
use itertools::Itertools;
pub use release::Release;
use serde::Deserialize;
use time::{OffsetDateTime, macros::format_description};

use crate::{Action, changes::Change, package, semver::Version};

mod changelog;
mod config;
mod release;

/// Defines how release notes are handled for a package.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ReleaseNotes {
    pub sections: Sections,
    pub changelog: Option<Changelog>,
    pub change_templates: Vec<ChangeTemplate>,
}

impl ReleaseNotes {
    /// Returns the first if any forge-specific variable in `Self::change_templates`
    /// (for example, `$pr_number`, `$pr_author_login`).
    #[must_use]
    pub fn first_variable_needing_forge_data(&self) -> Option<&'static str> {
        self.change_templates
            .iter()
            .find_map(ChangeTemplate::first_variable_needing_forge_data)
    }

    /// Create new release notes for use in changelogs / forges.
    ///
    /// # Errors
    ///
    /// If the current date can't be formatted
    pub(crate) fn create_release(
        &mut self,
        version: Version,
        changes: &[Change],
        package_name: &package::Name,
    ) -> Result<Vec<Action>, TimeError> {
        let mut notes = String::new();
        for (section_name, sources) in self.sections.iter() {
            let mut changes = changes
                .iter()
                .filter(|change| sources.contains(&change.change_type))
                .sorted()
                .peekable();
            if changes.peek().is_some() {
                if !notes.is_empty() {
                    notes.push_str("\n\n");
                }
                notes.push_str("## ");
                notes.push_str(section_name.as_ref());
                notes.push_str("\n\n");
                write_body(&mut notes, changes, &self.change_templates);
            }
        }

        let release = Release {
            title: release_title(&version)?,
            version,
            notes,
            package_name: package_name.clone(),
        };

        let mut pending_actions = Vec::with_capacity(2);
        if let Some(changelog) = self.changelog.as_mut() {
            let new_changes = changelog.with_release(&release);
            pending_actions.push(Action::WriteToFile {
                path: changelog.path.clone(),
                content: changelog.content.clone(),
                diff: format!("\n{new_changes}\n"),
            });
        }
        pending_actions.push(Action::CreateRelease(release));
        Ok(pending_actions)
    }
}

#[derive(Debug, thiserror::Error)]
#[cfg_attr(feature = "miette", derive(miette::Diagnostic))]
#[error("Failed to format current time")]
#[cfg_attr(
    feature = "miette",
    diagnostic(
        code(release_notes::time_format),
        help(
            "This is probably a bug with knope, please file an issue at https://github.com/knope-dev/knope"
        )
    )
)]
pub struct TimeError(#[from] time::error::Format);

fn write_body<'change>(
    out: &mut String,
    changes: Peekable<impl Iterator<Item = &'change Change>>,
    templates: &[ChangeTemplate],
) {
    let mut changes = changes.peekable();
    while let Some(change) = changes.next() {
        write_change(out, change, templates);

        match changes.peek().map(|change| change.details.is_some()) {
            Some(false) => out.push('\n'),
            Some(true) => out.push_str("\n\n"),
            None => (),
        }
    }
}

fn write_change(out: &mut String, change: &Change, templates: &[ChangeTemplate]) {
    for template in templates {
        if template.write(change, out) {
            return;
        }
    }
    if let Some(details) = &change.details {
        write!(out, "### {summary}\n\n{details}", summary = change.summary).ok();
    } else {
        write!(out, "- {summary}", summary = change.summary).ok();
    }
}

/// Create the title of a new release with no Markdown header level.
///
/// # Errors
///
/// If the current date can't be formatted
fn release_title(version: &Version) -> Result<String, TimeError> {
    let format = format_description!("[year]-[month]-[day]");
    let date_str = OffsetDateTime::now_utc().date().format(&format)?;
    Ok(format!("{version} ({date_str})"))
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct ChangeTemplate(Cow<'static, str>);

impl ChangeTemplate {
    const PR_AUTHOR_LOGIN: &'static str = "$pr_author_login";
    const COMMIT_AUTHOR_NAME: &'static str = "$commit_author_name";
    const COMMIT_HASH: &'static str = "$commit_hash";
    const DETAILS: &'static str = "$details";
    const PR_NUMBER: &'static str = "$pr_number";
    const SUMMARY: &'static str = "$summary";

    fn write(&self, change: &Change, out: &mut String) -> bool {
        let mut result = self.0.to_string();
        if result.contains(Self::COMMIT_AUTHOR_NAME) || result.contains(Self::COMMIT_HASH) {
            if let Some(git) = change.git.as_ref() {
                result = result.replace(Self::COMMIT_AUTHOR_NAME, &git.author_name);
                result = result.replace(Self::COMMIT_HASH, &git.hash);
            } else {
                return false;
            }
        }

        if result.contains(Self::PR_AUTHOR_LOGIN) {
            if let Some(login) = change
                .git
                .as_ref()
                .and_then(|g| g.pr_author_login.as_deref())
            {
                result = result.replace(Self::PR_AUTHOR_LOGIN, login);
            } else {
                return false;
            }
        }

        if result.contains(Self::PR_NUMBER) {
            if let Some(pr) = change.git.as_ref().and_then(|g| g.pr_number) {
                result = result.replace(Self::PR_NUMBER, &pr.to_string());
            } else {
                return false;
            }
        }

        if result.contains(Self::DETAILS) {
            if let Some(details) = change.details.as_deref() {
                result = result.replace(Self::DETAILS, details);
            } else {
                return false;
            }
        }

        result = result.replace(Self::SUMMARY, &change.summary);
        out.push_str(&result);

        true
    }

    /// Returns any forge-specific variables int this template that require API calls to populate
    /// (for example, `$pr_number`, `$pr_author_login`).
    #[must_use]
    pub fn first_variable_needing_forge_data(&self) -> Option<&'static str> {
        [Self::PR_AUTHOR_LOGIN, Self::PR_NUMBER]
            .into_iter()
            .find(|&variable| self.0.contains(variable))
    }
}

impl From<String> for ChangeTemplate {
    fn from(template: String) -> Self {
        Self(Cow::Owned(template))
    }
}

impl From<&'static str> for ChangeTemplate {
    fn from(template: &'static str) -> Self {
        Self(Cow::Borrowed(template))
    }
}

#[cfg(test)]
mod test_release_notes {
    use std::sync::Arc;

    use changesets::UniqueId;
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::changes::{ChangeSource, ChangeType, GitInfo};

    #[test]
    fn simple_changes_before_complex() {
        let changes = vec![
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a complex feature".into(),
                details: Some("some details".into()),
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a simple feature".into(),
                details: None,
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "a super simple feature".into(),
                details: None,
                git: None,
            },
        ];

        let mut actions = ReleaseNotes::create_release(
            &mut ReleaseNotes::default(),
            Version::new(1, 0, 0, None),
            &changes,
            &package::Name::Default,
        )
        .expect("can create release notes");
        assert_eq!(actions.len(), 1);

        let action = actions.pop().unwrap();

        let Action::CreateRelease(release) = action else {
            panic!("expected release action");
        };

        assert_eq!(
            release.notes,
            "## Features\n\n- a simple feature\n- a super simple feature\n\n### a complex feature\n\nsome details"
        );
    }

    #[test]
    fn custom_templates() {
        let change_templates = [
            "* $summary by $commit_author_name ($commit_hash)", // commit-only
            "###### $summary!!! $notAVariable\n\n$details", // Complex change files, should skip #s
            "* $summary",                                   // A fallback that's always applicable
        ]
        .into_iter()
        .map(ChangeTemplate::from)
        .collect_vec();

        let mut release_notes = ReleaseNotes {
            change_templates,
            changelog: Some(Changelog::new(
                "CHANGELOG.md".into(),
                "# My Changelog\n\n## 1.2.3 (previous version)".to_string(),
            )),
            ..ReleaseNotes::default()
        };

        let changes = &[
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a complex feature".to_string(),
                details: Some("some details".into()),
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a simple feature".into(),
                details: None,
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "a super simple feature".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Sushi".into(),
                    hash: "1234".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
        ];

        let mut actions = release_notes
            .create_release(
                Version::new(1, 3, 0, None),
                changes,
                &package::Name::Default,
            )
            .expect("can create release notes");
        let Some(Action::CreateRelease(release)) = actions.pop() else {
            panic!("expected release action");
        };

        assert_eq!(
            release.notes,
            "## Features\n\n* a simple feature\n* a super simple feature by Sushi (1234)\n\n###### a complex feature!!! $notAVariable\n\nsome details"
        );

        let Some(Action::WriteToFile { diff, .. }) = actions.pop() else {
            panic!("expected write changelog action");
        };

        assert!(
            diff.ends_with(
            "\n\n### Features\n\n* a simple feature\n* a super simple feature by Sushi (1234)\n\n####### a complex feature!!! $notAVariable\n\nsome details\n"
            ) // Can't check the date
        );
    }

    #[test]
    fn fall_back_to_built_in_templates() {
        let change_templates = ["* $summary by $commit_author_name"]
            .into_iter()
            .map(ChangeTemplate::from)
            .collect_vec(); // Only applies to commits
        let mut release_notes = ReleaseNotes {
            change_templates,
            ..ReleaseNotes::default()
        };

        let changes = &[
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a complex feature".to_string(),
                details: Some("some details".into()),
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "a simple feature".into(),
                details: None,
                git: None,
            },
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "a super simple feature".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Sushi".into(),
                    hash: "1234".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
        ];

        let mut actions = release_notes
            .create_release(
                Version::new(1, 3, 0, None),
                changes,
                &package::Name::Default,
            )
            .expect("can create release notes");
        let Some(Action::CreateRelease(release)) = actions.pop() else {
            panic!("expected release action");
        };
        assert_eq!(
            release.notes,
            "## Features\n\n- a simple feature\n* a super simple feature by Sushi\n\n### a complex feature\n\nsome details"
        );
    }

    #[test]
    fn change_files_with_commit_info_use_commit_templates() {
        let change_templates = [
            "* $summary by $commit_author_name ($commit_hash)\n\n$details", // commit + details
            "* $summary by $commit_author_name ($commit_hash)",             // commit only
            "### $summary\n\n$details",                                     // details only
            "* $summary",                                                   // fallback
        ]
        .into_iter()
        .map(ChangeTemplate::from)
        .collect_vec();

        let mut release_notes = ReleaseNotes {
            change_templates,
            ..ReleaseNotes::default()
        };

        let changes = &[
            // Committed change file with details - should use first template (commit + details)
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("committed-with-details")),
                },
                summary: "a committed feature with details".to_string(),
                details: Some("some implementation details".into()),
                git: Some(GitInfo {
                    author_name: "Alice".into(),
                    hash: "abc123".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
            // Committed change file without details - should use second template (commit only)
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("committed-simple")),
                },
                summary: "a committed simple feature".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Bob".into(),
                    hash: "def456".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
            // Uncommitted change file with details - should use third template (details only)
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("uncommitted-with-details")),
                },
                summary: "an uncommitted feature with details".to_string(),
                details: Some("some more details".into()),
                git: None,
            },
            // Uncommitted change file without details - should use fallback template
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("uncommitted-simple")),
                },
                summary: "an uncommitted simple feature".into(),
                details: None,
                git: None,
            },
            // Conventional commit - should use second template (commit only)
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: "feat: conventional commit feature".into(),
                },
                summary: "conventional commit feature".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Charlie".into(),
                    hash: "ghi789".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
        ];

        let mut actions = release_notes
            .create_release(
                Version::new(2, 0, 0, None),
                changes,
                &package::Name::Default,
            )
            .expect("can create release notes");

        let Some(Action::CreateRelease(release)) = actions.pop() else {
            panic!("expected release action");
        };

        assert_eq!(
            release.notes,
            "## Features\n\n* a committed simple feature by Bob (def456)\n* an uncommitted simple feature\n* conventional commit feature by Charlie (ghi789)\n\n* a committed feature with details by Alice (abc123)\n\nsome implementation details\n\n### an uncommitted feature with details\n\nsome more details"
        );
    }

    #[test]
    fn github_style_templates_with_pr_and_login() {
        let change_templates = [
            "* $summary by @$pr_author_login in #$pr_number",
            "* $summary by @$pr_author_login",
            "* $summary",
        ]
        .into_iter()
        .map(ChangeTemplate::from)
        .collect_vec();

        let mut release_notes = ReleaseNotes {
            change_templates,
            ..ReleaseNotes::default()
        };

        let changes = &[
            // Has PR info and login -> first template
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "add dark mode".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Dale Seo".into(),
                    hash: "abc1234".into(),
                    pr_number: Some(42),
                    pr_author_login: Some("DaleSeo".into()),
                }),
            },
            // Has login but no PR -> second template
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "improve logging".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Alice".into(),
                    hash: "def5678".into(),
                    pr_number: None,
                    pr_author_login: Some("alice".into()),
                }),
            },
            // No git info at all -> third template
            Change {
                change_type: ChangeType::Feature,
                original_source: ChangeSource::ChangeFile {
                    id: Arc::new(UniqueId::exact("")),
                },
                summary: "uncommitted feature".into(),
                details: None,
                git: None,
            },
            // Has git info but no login/PR -> third template
            Change {
                change_type: ChangeType::Fix,
                original_source: ChangeSource::ConventionalCommit {
                    description: String::new(),
                },
                summary: "fix crash".into(),
                details: None,
                git: Some(GitInfo {
                    author_name: "Bob".into(),
                    hash: "ghi9012".into(),
                    pr_number: None,
                    pr_author_login: None,
                }),
            },
        ];

        let mut actions = release_notes
            .create_release(
                Version::new(1, 1, 0, None),
                changes,
                &package::Name::Default,
            )
            .expect("can create release notes");

        let Some(Action::CreateRelease(release)) = actions.pop() else {
            panic!("expected release action");
        };

        assert_eq!(
            release.notes,
            "## Features\n\n* add dark mode by @DaleSeo in #42\n* improve logging by @alice\n* uncommitted feature\n\n## Fixes\n\n* fix crash"
        );
    }

    #[test]
    fn needs_forge_data_false_for_local_only_template() {
        let notes = ReleaseNotes {
            change_templates: vec![ChangeTemplate::from("* $summary by $commit_author_name")],
            ..ReleaseNotes::default()
        };
        assert!(notes.first_variable_needing_forge_data().is_none());
    }

    #[test]
    fn needs_forge_data_true_for_pr_number() {
        let notes = ReleaseNotes {
            change_templates: vec![ChangeTemplate::from("* $summary in #$pr_number")],
            ..ReleaseNotes::default()
        };
        assert!(notes.first_variable_needing_forge_data().is_some());
    }

    #[test]
    fn needs_forge_data_true_for_author_login() {
        let notes = ReleaseNotes {
            change_templates: vec![ChangeTemplate::from("* $summary by @$pr_author_login")],
            ..ReleaseNotes::default()
        };
        assert!(notes.first_variable_needing_forge_data().is_some());
    }

    #[test]
    fn needs_forge_data_false_for_default() {
        let notes = ReleaseNotes::default();
        assert!(notes.first_variable_needing_forge_data().is_none());
    }
}