cargo-ark 0.2.0

Cargo release utilities
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::collections::BTreeMap;
use std::fmt::{self, Display};
use std::path::Path;
use std::process::Command;

use clap::Args as ClapArgs;
use git_conventional::{Commit, Type};
use ohno::{AppError, app_err, bail};
use semver::Version;

/// Declaration order determines release-note category order.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Category {
    Breaking,
    Features,
    BugFixes,
    Performance,
    Documentation,
    Tasks,
    Refactoring,
    Build,
    Ci,
    Style,
    Miscellaneous,
    Custom(String),
}

impl From<Type<'_>> for Category {
    fn from(kind: Type<'_>) -> Self {
        match kind.as_str().to_ascii_lowercase().as_str() {
            "breaking" => Self::Breaking,
            "feat" => Self::Features,
            "fix" => Self::BugFixes,
            "perf" => Self::Performance,
            "doc" | "docs" => Self::Documentation,
            "chore" | "task" => Self::Tasks,
            "refactor" => Self::Refactoring,
            "build" => Self::Build,
            "ci" => Self::Ci,
            "style" => Self::Style,
            "misc" | "miscellaneous" => Self::Miscellaneous,
            other => Self::Custom(other.to_owned()),
        }
    }
}

impl Display for Category {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Breaking => f.write_str("\u{26a0}\u{fe0f} Breaking"),
            Self::Features => f.write_str("\u{2728} Features"),
            Self::BugFixes => f.write_str("\u{1f41b} Bug Fixes"),
            Self::Performance => f.write_str("\u{26a1} Performance"),
            Self::Documentation => f.write_str("\u{1f4da} Documentation"),
            Self::Tasks => f.write_str("\u{2714}\u{fe0f} Tasks"),
            Self::Refactoring => f.write_str("\u{267b}\u{fe0f} Code Refactoring"),
            Self::Build => f.write_str("\u{1f3d7}\u{fe0f} Build System"),
            Self::Ci => f.write_str("\u{1f504} Continuous Integration"),
            Self::Style => f.write_str("\u{1f3a8} Styling"),
            Self::Miscellaneous => f.write_str("\u{1f9e9} Miscellaneous"),
            Self::Custom(kind) => {
                let mut chars = kind.chars();
                let first = chars.next().expect("custom categories come from nonempty parsed commit types");
                write!(f, "{}{}", first.to_uppercase(), chars.as_str())
            }
        }
    }
}

#[derive(ClapArgs)]
pub(super) struct Args {
    /// Git tag in <crate>-v<major>.<minor>.<patch> form.
    pub(super) tag: String,

    /// Target GitHub repository (required unless --dry-run is set).
    #[arg(long, value_name = "OWNER/NAME")]
    pub(super) repo: Option<String>,

    /// Print the release notes without creating a GitHub release.
    #[arg(long)]
    pub(super) dry_run: bool,
}

// #[gamma::skip(fn_value.ok, tag = "native-boundary", reason = "This wrapper only supplies real filesystem and process operations. Publishing is tested through the injected operations.")]
#[cfg_attr(coverage_nightly, coverage(off))]
pub(super) fn run(args: &Args) -> Result<(), AppError> {
    publish(args, Path::is_dir, git_output, run_gh)
}

fn publish(
    args: &Args,
    is_dir: impl FnOnce(&Path) -> bool,
    mut git: impl FnMut(&[&str]) -> Result<String, AppError>,
    gh: impl FnOnce(&[&str]) -> Result<(), AppError>,
) -> Result<(), AppError> {
    let (crate_name, version, range) = determine_range(&args.tag, &mut git)?;
    let commits = read_git_log(&range, crate_name, is_dir, git)?;
    let categories = categorize_commits(&commits);
    let body = format_release_notes(categories)?;
    create_release(args, crate_name, &version.to_string(), &body, gh)
}

/// Splits a tag like `foo-v1.2.3` into a crate name and release version.
fn parse_tag(tag: &str) -> Result<(&str, Version), AppError> {
    let idx = tag
        .rfind("-v")
        .ok_or_else(|| app_err!("Tag '{tag}' does not match <crate>-v<version>"))?;

    let crate_name = &tag[..idx];
    let version = &tag[idx + 2..]; // skip "-v"

    if crate_name.is_empty() {
        bail!("Tag '{tag}' has an empty crate name");
    }

    let version = Version::parse(version).map_err(|error| app_err!("Tag '{tag}' must contain a major.minor.patch version: {error}"))?;
    if !version.pre.is_empty() || !version.build.is_empty() {
        bail!("Tag '{tag}' must contain a major.minor.patch version without a prerelease or build suffix");
    }

    Ok((crate_name, version))
}

/// Selects the greatest release version below the requested version for this crate.
fn previous_tag<'a>(tags: &'a str, crate_name: &str, version: &Version) -> Option<&'a str> {
    tags.lines()
        .filter_map(|tag| {
            let (name, candidate) = parse_tag(tag).ok()?;
            (name == crate_name && candidate < *version).then_some((candidate, tag))
        })
        .max_by(|(left, _), (right, _)| left.cmp(right))
        .map(|(_, tag)| tag)
}

#[ohno::enrich_err("failed to determine tag range for {tag}")]
fn determine_range(tag: &str, mut git: impl FnMut(&[&str]) -> Result<String, AppError>) -> Result<(&str, Version, String), AppError> {
    let (crate_name, version) = parse_tag(tag)?;
    let tags = git(&["tag", "--list", &format!("{crate_name}-v*")])?;
    let range = match previous_tag(&tags, crate_name, &version) {
        Some(previous) => format!("{previous}..{tag}"),
        None => tag.to_owned(),
    };
    Ok((crate_name, version, range))
}

#[ohno::enrich_err("failed to read Git log for {range}")]
fn read_git_log(
    range: &str,
    crate_name: &str,
    is_dir: impl FnOnce(&Path) -> bool,
    mut git: impl FnMut(&[&str]) -> Result<String, AppError>,
) -> Result<Vec<String>, AppError> {
    if crate_name.contains("..") || crate_name.contains('/') || crate_name.contains('\\') {
        bail!("Invalid crate name: '{crate_name}'");
    }

    let crate_path = format!("crates/{crate_name}");
    if !is_dir(Path::new(&crate_path)) {
        bail!("Crate directory not found: '{crate_path}'");
    }

    let log = git(&["log", "--format=%B", "--encoding=UTF-8", "-z", range, "--", &crate_path])?;
    Ok(log
        .split_terminator('\0')
        .map(str::trim)
        .filter(|message| !message.is_empty())
        .map(str::to_owned)
        .collect())
}

/// Groups raw commit messages by category, excluding conventional test commits.
fn categorize_commits(commits: &[String]) -> BTreeMap<Category, Vec<String>> {
    let mut categories: BTreeMap<Category, Vec<String>> = BTreeMap::new();

    for message in commits {
        let (category, description) = match Commit::parse(message) {
            Ok(commit) => {
                if commit.type_() == Type::TEST {
                    continue;
                }

                (
                    if commit.breaking() {
                        Category::Breaking
                    } else {
                        Category::from(commit.type_())
                    },
                    commit.description(),
                )
            }
            Err(_) => (
                Category::Miscellaneous,
                message.lines().next().expect("read_git_log filters out empty commit messages"),
            ),
        };
        categories.entry(category).or_default().push(description.to_owned());
    }

    categories
}

/// Formats categorized commits as grouped Markdown.
///
/// # Errors
///
/// Returns an error if no categories are supplied.
fn format_release_notes(categories: BTreeMap<Category, Vec<String>>) -> Result<String, AppError> {
    if categories.is_empty() {
        bail!("No relevant commits found; check the release tag and crate history");
    }

    Ok(categories
        .into_iter()
        .map(|(category, descriptions)| format!("- {category}\n\n  - {}", descriptions.join("\n  - ")))
        .collect::<Vec<_>>()
        .join("\n\n"))
}

// #[gamma::skip(all, tag = "native-boundary", reason = "Only launches Git and converts native process output. Tests script Git commands, output, and failures without spawning processes.")]
#[ohno::enrich_err("failed to run Git with arguments {args:?}")]
#[cfg_attr(coverage_nightly, coverage(off))]
fn git_output(args: &[&str]) -> Result<String, AppError> {
    let output = Command::new("git").args(args).output()?;
    if !output.status.success() {
        bail!(
            "Git exited with {}: {}. Ensure the release tag and full history have been fetched",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8(output.stdout)?)
}

/// Previews release notes or invokes `gh release create` to publish them.
///
/// # Errors
///
/// Returns an error if publishing without `--repo`, or if `gh` fails.
fn create_release(
    args: &Args,
    crate_name: &str,
    version: &str,
    body: &str,
    gh: impl FnOnce(&[&str]) -> Result<(), AppError>,
) -> Result<(), AppError> {
    let title = format!("{crate_name} v{version}");
    println!("Release {title} with body:\n{body}");

    if args.dry_run {
        println!("\nDry run: GitHub release creation skipped.");
        return Ok(());
    }

    let repo = args
        .repo
        .as_deref()
        .ok_or_else(|| app_err!("--repo is required to create a release; pass --repo <owner/name> or use --dry-run to preview notes"))?;
    gh(&["release", "create", &args.tag, "--repo", repo, "--title", &title, "--notes", body])
}

// #[gamma::skip(all, tag = "native-boundary", reason = "Only launches gh and checks its exit status. Tests exercise release command construction and error propagation without spawning processes.")]
#[ohno::enrich_err("failed to run `gh`")]
#[cfg_attr(coverage_nightly, coverage(off))]
fn run_gh(args: &[&str]) -> Result<(), AppError> {
    let status = Command::new("gh").args(args).status()?;
    if !status.success() {
        bail!("`gh` exited with {status}");
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io;

    use super::*;

    #[test]
    fn rejects_invalid_tags_before_reading_history_or_publishing() {
        for (tag, expected) in [
            ("sample-1.0.0", "Tag 'sample-1.0.0' does not match <crate>-v<version>"),
            ("-v1.0.0", "Tag '-v1.0.0' has an empty crate name"),
        ] {
            let args = Args {
                tag: tag.to_owned(),
                repo: Some("microsoft/ox-tools".to_owned()),
                dry_run: false,
            };
            let error = publish(
                &args,
                |_| panic!("invalid tags must fail before checking the filesystem"),
                |_| panic!("invalid tags must fail before invoking Git"),
                |_| panic!("invalid tags must fail before publishing"),
            )
            .expect_err("release tags require a crate name and a -v separator");
            let message = error.to_string();
            assert_eq!(message.lines().next(), Some(expected));
        }
    }

    #[test]
    fn does_not_publish_without_relevant_history() {
        let args = Args {
            tag: "sample-v1.0.0".to_owned(),
            repo: Some("microsoft/ox-tools".to_owned()),
            dry_run: false,
        };
        let error = publish(
            &args,
            |path| path == Path::new("crates/sample"),
            |args| match args {
                ["tag", "--list", "sample-v*"] => Ok("sample-v1.0.0\n".to_owned()),
                [
                    "log",
                    "--format=%B",
                    "--encoding=UTF-8",
                    "-z",
                    "sample-v1.0.0",
                    "--",
                    "crates/sample",
                ] => Ok("test: check output\0".to_owned()),
                _ => panic!("unexpected Git call: {args:?}"),
            },
            |_| panic!("history containing only tests must not be published"),
        )
        .expect_err("a release needs at least one relevant commit");
        assert_eq!(
            error.to_string(),
            "No relevant commits found; check the release tag and crate history"
        );
    }

    #[test]
    fn selects_preceding_version_numerically_for_the_same_crate() -> Result<(), AppError> {
        let (_, version) = parse_tag("sample-v1.11.0")?;
        let tags = "sample-v1.9.9\nsample-v1.10.0\nsample-v1.11.0\nsample-v2.0.0\n\
                    other-v1.10.9\nsample-v1.10.5-rc.1\nsample-v1.10.6+build\nsample-vpreview";
        assert_eq!(previous_tag(tags, "sample", &version), Some("sample-v1.10.0"));
        Ok(())
    }

    #[test]
    fn determines_range_from_the_preceding_tag() -> Result<(), AppError> {
        let release = determine_range("sample-v1.1.0", |args| {
            assert_eq!(args, ["tag", "--list", "sample-v*"]);
            Ok("sample-v1.0.0\nsample-v1.1.0\nsample-v2.0.0".to_owned())
        })?;
        assert_eq!(
            release,
            ("sample", Version::new(1, 1, 0), "sample-v1.0.0..sample-v1.1.0".to_owned())
        );
        Ok(())
    }

    #[test]
    fn uses_requested_tag_alone_when_no_preceding_tag_exists() -> Result<(), AppError> {
        let release = determine_range("sample-v1.1.0", |args| {
            assert_eq!(args, ["tag", "--list", "sample-v*"]);
            Ok("sample-vpreview\nsample-v1.1.0\nsample-v2.0.0".to_owned())
        })?;
        assert_eq!(release, ("sample", Version::new(1, 1, 0), "sample-v1.1.0".to_owned()));
        Ok(())
    }

    #[test]
    fn propagates_tag_range_git_failures() {
        let tag = "sample-v1.0.0";
        let error = determine_range(tag, |args| {
            assert_eq!(args, ["tag", "--list", "sample-v*"]);
            Err(io::Error::from(io::ErrorKind::PermissionDenied).into())
        })
        .expect_err("a failed Git command must abort tag-range selection");
        assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::PermissionDenied);
    }

    #[test]
    fn reads_normalized_full_commit_messages() -> Result<(), AppError> {
        let range = "sample-v1.0.0..sample-v1.1.0";
        let path = "crates/sample";
        let commits = read_git_log(
            range,
            "sample",
            |path| {
                assert_eq!(path, Path::new("crates/sample"));
                true
            },
            |args| {
                assert_eq!(args, ["log", "--format=%B", "--encoding=UTF-8", "-z", range, "--", path]);
                Ok("  feat(sample): first change\n\nBREAKING CHANGE: new contract\n\0test(sample): more coverage  \0".to_owned())
            },
        )?;
        assert_eq!(
            commits,
            [
                "feat(sample): first change\n\nBREAKING CHANGE: new contract",
                "test(sample): more coverage"
            ]
        );
        Ok(())
    }

    #[test]
    fn reads_empty_or_blank_history_as_no_commits() -> Result<(), AppError> {
        let tag = "sample-v1.0.0";
        let path = "crates/sample";
        for log in ["", "\0 \n\t\0"] {
            let commits = read_git_log(
                tag,
                "sample",
                |path| {
                    assert_eq!(path, Path::new("crates/sample"));
                    true
                },
                |args| {
                    assert_eq!(args, ["log", "--format=%B", "--encoding=UTF-8", "-z", tag, "--", path]);
                    Ok(log.to_owned())
                },
            )?;
            assert_eq!(commits, [] as [String; 0]);
        }
        Ok(())
    }

    #[test]
    fn rejects_invalid_crate_names_before_checking_paths_or_reading_git() {
        for crate_name in ["..", "sample/other", "sample\\other"] {
            let error = read_git_log(
                "sample-v1.0.0",
                crate_name,
                |_| panic!("invalid crate names must fail before checking the filesystem"),
                |_| panic!("invalid crate names must fail before reading Git history"),
            )
            .expect_err("crate names must not escape the crates directory");
            let message = error.to_string();
            assert_eq!(
                message.lines().next().expect("AppError should include an error message"),
                format!("Invalid crate name: '{crate_name}'")
            );
        }
    }

    #[test]
    fn rejects_missing_crate_directory_before_reading_git() {
        let mut directory_checked = false;
        let error = read_git_log(
            "sample-v1.0.0",
            "sample",
            |path| {
                assert_eq!(path, Path::new("crates/sample"));
                directory_checked = true;
                false
            },
            |_| panic!("a missing crate directory must fail before reading Git history"),
        )
        .expect_err("the crate directory must exist");
        assert!(directory_checked);
        let message = error.to_string();
        assert_eq!(
            message.lines().next().expect("AppError should include an error message"),
            "Crate directory not found: 'crates/sample'"
        );
    }

    #[test]
    fn does_not_publish_when_git_log_fails() {
        let args = Args {
            tag: "sample-v1.0.0".to_owned(),
            repo: Some("microsoft/ox-tools".to_owned()),
            dry_run: false,
        };
        let error = publish(
            &args,
            |path| path == Path::new("crates/sample"),
            |args| match args {
                ["tag", "--list", "sample-v*"] => Ok("sample-v1.0.0\n".to_owned()),
                [
                    "log",
                    "--format=%B",
                    "--encoding=UTF-8",
                    "-z",
                    "sample-v1.0.0",
                    "--",
                    "crates/sample",
                ] => Err(io::Error::from(io::ErrorKind::PermissionDenied).into()),
                _ => panic!("unexpected Git call: {args:?}"),
            },
            |_| panic!("a failed Git log must not be published"),
        )
        .expect_err("a failed Git command must abort publishing");
        assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::PermissionDenied);
    }

    #[test]
    fn categorizes_and_groups_commits() {
        let commits = [
            "chore: update tooling",
            "docs(api): explain usage  (#9)",
            "Feat(parser): accept new syntax (#12)",
            "fix(config)!: reject invalid input",
            "feat(api): change the contract\n\nBREAKING CHANGE: new contract",
            "plain subject (#13)\n\nBody must not become a bullet.",
            "doc: document migration",
            "misc: update examples",
            "UNKNOWN: title",
        ]
        .map(str::to_owned);
        assert_eq!(
            categorize_commits(&commits),
            BTreeMap::from([
                (
                    Category::Breaking,
                    vec!["reject invalid input".to_owned(), "change the contract".to_owned()]
                ),
                (Category::Features, vec!["accept new syntax (#12)".to_owned()]),
                (
                    Category::Documentation,
                    vec!["explain usage  (#9)".to_owned(), "document migration".to_owned()]
                ),
                (Category::Tasks, vec!["update tooling".to_owned()]),
                (
                    Category::Miscellaneous,
                    vec!["plain subject (#13)".to_owned(), "update examples".to_owned()]
                ),
                (Category::Custom("unknown".to_owned()), vec!["title".to_owned()]),
            ])
        );
    }

    #[test]
    fn excludes_test_commits_during_categorization() {
        let commits = [
            "test: add coverage",
            "test(api): add scoped coverage",
            "test!: change test infrastructure",
            "TEST: add more coverage",
            "Test!: change shared test infrastructure",
            "feat: preview release notes",
        ]
        .map(str::to_owned);
        assert_eq!(
            categorize_commits(&commits),
            BTreeMap::from([(Category::Features, vec!["preview release notes".to_owned()])])
        );
    }

    #[test]
    fn formats_categorized_commits() -> Result<(), AppError> {
        let categories = BTreeMap::from([
            (Category::Custom("zeta".to_owned()), vec!["last category".to_owned()]),
            (Category::Tasks, vec!["update tooling".to_owned()]),
            (Category::Documentation, vec!["explain usage  (#9)".to_owned()]),
            (Category::Features, vec!["accept new syntax (#12)".to_owned()]),
            (
                Category::Custom("alpha".to_owned()),
                vec!["first custom change".to_owned(), "second custom change".to_owned()],
            ),
            (Category::Breaking, vec!["reject invalid input".to_owned()]),
            (Category::Miscellaneous, vec!["plain subject (#13)".to_owned()]),
        ]);
        assert_eq!(
            format_release_notes(categories)?,
            "- \u{26a0}\u{fe0f} Breaking\n\n  - reject invalid input\n\n\
             - \u{2728} Features\n\n  - accept new syntax (#12)\n\n\
             - \u{1f4da} Documentation\n\n  - explain usage  (#9)\n\n\
             - \u{2714}\u{fe0f} Tasks\n\n  - update tooling\n\n\
             - \u{1f9e9} Miscellaneous\n\n  - plain subject (#13)\n\n\
             - Alpha\n\n  - first custom change\n  - second custom change\n\n\
             - Zeta\n\n  - last category"
        );
        Ok(())
    }

    #[test]
    fn includes_maintenance_and_performance_changes_in_release_notes() -> Result<(), AppError> {
        let commits = [
            "style: format examples",
            "ci: cache build outputs",
            "build: update linker flags",
            "refactor: simplify tag handling",
            "perf: reduce allocation",
            "fix: handle an empty tag",
            "breaking: drop legacy tags",
        ]
        .map(str::to_owned);
        assert_eq!(
            format_release_notes(categorize_commits(&commits))?,
            "- \u{26a0}\u{fe0f} Breaking\n\n  - drop legacy tags\n\n\
             - \u{1f41b} Bug Fixes\n\n  - handle an empty tag\n\n\
             - \u{26a1} Performance\n\n  - reduce allocation\n\n\
             - \u{267b}\u{fe0f} Code Refactoring\n\n  - simplify tag handling\n\n\
             - \u{1f3d7}\u{fe0f} Build System\n\n  - update linker flags\n\n\
             - \u{1f504} Continuous Integration\n\n  - cache build outputs\n\n\
             - \u{1f3a8} Styling\n\n  - format examples"
        );
        Ok(())
    }

    #[test]
    fn dry_run_does_not_invoke_gh() -> Result<(), AppError> {
        for repo in [None, Some("microsoft/ox-tools".to_owned())] {
            let args = Args {
                tag: "sample-v1.0.0".to_owned(),
                repo,
                dry_run: true,
            };
            create_release(&args, "sample", "1.0.0", "release notes", |_| panic!("dry runs must not invoke gh"))?;
        }
        Ok(())
    }

    #[test]
    fn publishes_with_the_requested_repository_tag_title_and_notes() -> Result<(), AppError> {
        let args = Args {
            tag: "sample-v1.1.0".to_owned(),
            repo: Some("microsoft/ox-tools".to_owned()),
            dry_run: false,
        };
        let mut called = false;
        let log_args = [
            "log",
            "--format=%B",
            "--encoding=UTF-8",
            "-z",
            "sample-v1.0.0..sample-v1.1.0",
            "--",
            "crates/sample",
        ];
        let mut git_calls = [
            (&["tag", "--list", "sample-v*"][..], "sample-v1.0.0\nsample-v1.1.0\n"),
            (&log_args[..], "fix: correct the output (#42)\n\0test: check output\n\0"),
        ]
        .into_iter();
        publish(
            &args,
            |path| {
                assert_eq!(path, Path::new("crates/sample"));
                true
            },
            |args| {
                let (expected, output) = git_calls.next().expect("unexpected Git call");
                assert_eq!(args, expected);
                Ok(output.to_owned())
            },
            |args| {
                assert_eq!(
                    args,
                    [
                        "release",
                        "create",
                        "sample-v1.1.0",
                        "--repo",
                        "microsoft/ox-tools",
                        "--title",
                        "sample v1.1.0",
                        "--notes",
                        "- \u{1f41b} Bug Fixes\n\n  - correct the output (#42)"
                    ]
                );
                called = true;
                Ok(())
            },
        )?;
        assert!(git_calls.next().is_none());
        assert!(called);
        Ok(())
    }

    #[test]
    fn publishing_requires_a_repository() {
        let args = Args {
            tag: "sample-v1.0.0".to_owned(),
            repo: None,
            dry_run: false,
        };
        let error = create_release(&args, "sample", "1.0.0", "release notes", |_| {
            panic!("a missing repository must fail before invoking gh")
        })
        .expect_err("publishing without --repo must fail");
        assert_eq!(
            error.to_string(),
            "--repo is required to create a release; pass --repo <owner/name> or use --dry-run to preview notes"
        );
    }

    #[test]
    fn reports_a_failed_release_creation() {
        let args = Args {
            tag: "sample-v1.0.0".to_owned(),
            repo: Some("microsoft/ox-tools".to_owned()),
            dry_run: false,
        };
        let error = create_release(&args, "sample", "1.0.0", "release notes", |_| {
            Err(io::Error::from(io::ErrorKind::NotFound).into())
        })
        .expect_err("a missing gh executable must not be reported as a successful release");
        assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), io::ErrorKind::NotFound);
    }
}