cargo-changeset 0.1.7

A cargo subcommand for managing changesets
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
mod add;
mod additional_packages;
mod init;
mod manage;
mod release;
mod status;
mod verify;

use std::path::Path;

use clap::{Args, Subcommand, ValueEnum};

use changeset_core::{BumpType, ChangeCategory};
use changeset_manifest::{
    ChangelogLocation, ComparisonLinks, NoneBumpBehavior, TagFormat, ZeroVersionBehavior,
};
use changeset_operations::OperationError;

use crate::error::Result;
use crate::output::StdoutCliWriter;

#[derive(Args)]
pub(crate) struct AddArgs {
    /// Package(s) to include in the changeset (skips interactive selection)
    #[arg(long = "package", short = 'p', value_name = "NAME")]
    pub packages: Vec<String>,

    /// Bump type for all packages (major, minor, patch, none)
    #[arg(long, short = 'b', value_enum)]
    pub bump: Option<BumpType>,

    /// Per-package bump type: "package-name:bump-type"
    #[arg(long = "package-bump", value_name = "NAME:TYPE")]
    pub package_bumps: Vec<String>,

    /// Change category (defaults to "changed")
    #[arg(long, short = 'c', value_enum, default_value = "changed")]
    pub category: ChangeCategory,

    /// Description (use "-" to read from stdin)
    #[arg(long, short = 'm')]
    pub message: Option<String>,

    /// Open external editor ($EDITOR) for description input
    #[arg(long)]
    pub editor: bool,

    /// Skip dependency tracking (do not compute transitive dependents)
    #[arg(long)]
    pub exclude_dependents: bool,
}

#[derive(Args)]
pub(crate) struct VerifyArgs {
    /// Base branch to compare against (overrides config value)
    #[arg(long)]
    pub base: Option<String>,

    /// Head ref to compare (defaults to HEAD)
    #[arg(long)]
    pub head: Option<String>,

    /// Suppress all output (exit code only, for CI)
    #[arg(long, short = 'q')]
    pub quiet: bool,

    /// Allow deleted changeset files (not recommended)
    #[arg(long, short = 'd')]
    pub allow_deleted_changesets: bool,

    /// Skip dependency tracking (do not require coverage for transitive dependents)
    #[arg(long)]
    pub exclude_dependents: bool,

    /// Skip dirty working directory detection; always compare against base branch
    #[arg(long)]
    pub ignore_dirty: bool,
}

#[derive(Args)]
pub(crate) struct ReleaseArgs {
    /// Preview changes without modifying any files
    #[arg(long)]
    pub dry_run: bool,

    /// Convert inherited versions (version.workspace = true) to explicit versions
    #[arg(long)]
    pub convert: bool,

    /// Skip all git operations (commit and tags); allows dirty working tree
    #[arg(long)]
    pub no_commit: bool,

    /// Skip creating git tags
    #[arg(long)]
    pub no_tags: bool,

    /// Keep changeset files after release (do not delete them)
    #[arg(long)]
    pub keep_changesets: bool,

    /// Create pre-release for specific crate(s). Format: "crate:tag" or just "tag".
    /// Can be specified multiple times. If no crate specified, applies to all.
    /// Built-in tags: alpha, beta, rc. Custom tags are also supported.
    /// If tag is omitted on a pre-release version, reuses the current tag.
    /// To graduate a pre-release to stable, run without this flag.
    #[arg(long, value_name = "CRATE:TAG", num_args = 0..=1, default_missing_value = "")]
    pub prerelease: Vec<String>,

    /// Force release without changesets (only valid for pre-release increment)
    #[arg(long, short = 'f')]
    pub force: bool,

    /// Graduate specific 0.x crate(s) to 1.0.0.
    /// In workspace: specify which crates to graduate.
    /// For single package: graduates the package (no value needed).
    /// Can be specified multiple times.
    #[arg(long, value_name = "CRATE", num_args = 0..=1, default_missing_value = "")]
    pub graduate: Vec<String>,
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum TagFormatArg {
    VersionOnly,
    CratePrefixed,
}

impl From<TagFormatArg> for TagFormat {
    fn from(arg: TagFormatArg) -> Self {
        match arg {
            TagFormatArg::VersionOnly => Self::VersionOnly,
            TagFormatArg::CratePrefixed => Self::CratePrefixed,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum ChangelogLocationArg {
    Root,
    PerPackage,
}

impl From<ChangelogLocationArg> for ChangelogLocation {
    fn from(arg: ChangelogLocationArg) -> Self {
        match arg {
            ChangelogLocationArg::Root => Self::Root,
            ChangelogLocationArg::PerPackage => Self::PerPackage,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum ComparisonLinksArg {
    Auto,
    Enabled,
    Disabled,
}

impl From<ComparisonLinksArg> for ComparisonLinks {
    fn from(arg: ComparisonLinksArg) -> Self {
        match arg {
            ComparisonLinksArg::Auto => Self::Auto,
            ComparisonLinksArg::Enabled => Self::Enabled,
            ComparisonLinksArg::Disabled => Self::Disabled,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum ZeroVersionBehaviorArg {
    EffectiveMinor,
    AutoPromoteOnMajor,
}

impl From<ZeroVersionBehaviorArg> for ZeroVersionBehavior {
    fn from(arg: ZeroVersionBehaviorArg) -> Self {
        match arg {
            ZeroVersionBehaviorArg::EffectiveMinor => Self::EffectiveMinor,
            ZeroVersionBehaviorArg::AutoPromoteOnMajor => Self::AutoPromoteOnMajor,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
pub(crate) enum NoneBumpBehaviorArg {
    PromoteToPatch,
    Allow,
    Disallow,
}

impl From<NoneBumpBehaviorArg> for NoneBumpBehavior {
    fn from(value: NoneBumpBehaviorArg) -> Self {
        match value {
            NoneBumpBehaviorArg::PromoteToPatch => Self::PromoteToPatch,
            NoneBumpBehaviorArg::Allow => Self::Allow,
            NoneBumpBehaviorArg::Disallow => Self::Disallow,
        }
    }
}

#[derive(Args)]
pub(crate) struct InitArgs {
    /// Use default configuration values without prompts
    #[arg(long)]
    pub defaults: bool,

    /// Disable interactive prompts (use only CLI-provided values)
    #[arg(long)]
    pub no_interactive: bool,

    /// Create git commits on release (default: true)
    #[arg(long)]
    pub commit: Option<bool>,

    /// Create git tags on release (default: true)
    #[arg(long)]
    pub tags: Option<bool>,

    /// Keep changeset files after release (default: false)
    #[arg(long)]
    pub keep_changesets: Option<bool>,

    /// Tag format: "version-only" or "crate-prefixed" (default: version-only)
    #[arg(long, value_name = "FORMAT")]
    pub tag_format: Option<TagFormatArg>,

    /// Changelog location: "root" or "per-package" (default: root)
    #[arg(long, value_name = "LOCATION")]
    pub changelog: Option<ChangelogLocationArg>,

    /// Comparison links: "auto", "enabled", or "disabled" (default: auto)
    #[arg(long, value_name = "MODE")]
    pub comparison_links: Option<ComparisonLinksArg>,

    /// Zero version behavior: "effective-minor" or "auto-promote-on-major" (default: effective-minor)
    #[arg(long, value_name = "BEHAVIOR")]
    pub zero_version_behavior: Option<ZeroVersionBehaviorArg>,

    /// Default base branch for git comparisons (default: main)
    #[arg(long, value_name = "BRANCH")]
    pub base_branch: Option<String>,

    /// None bump behavior: "promote-to-patch", "allow", or "disallow" (default: promote-to-patch)
    #[arg(long, value_name = "BEHAVIOR")]
    pub none_bump_behavior: Option<NoneBumpBehaviorArg>,

    /// Custom changelog message template when none bumps are promoted to patch
    #[arg(long, value_name = "MESSAGE")]
    pub none_bump_promote_message_template: Option<String>,

    /// Commit title template (default: "{new-version}")
    #[arg(long, value_name = "TEMPLATE")]
    pub commit_title_template: Option<String>,

    /// Include version transition details in commit body (default: true)
    #[arg(long)]
    pub changes_in_body: Option<bool>,

    /// Custom comparison links template for changelogs
    #[arg(long, value_name = "TEMPLATE")]
    pub comparison_links_template: Option<String>,

    /// Custom dependency bump changelog template
    #[arg(long, value_name = "TEMPLATE")]
    pub dependency_bump_changelog_template: Option<String>,

    /// Glob patterns for files to ignore in change detection (can be repeated)
    #[arg(long = "ignored-file", value_name = "PATTERN")]
    pub ignored_files: Vec<String>,
}

#[derive(Args)]
pub(crate) struct ManagePrereleaseArgs {
    /// Add crate to pre-release (format: crate:tag)
    #[arg(long, value_name = "CRATE:TAG")]
    pub add: Vec<String>,

    /// Remove crate from pre-release
    #[arg(long, value_name = "CRATE")]
    pub remove: Vec<String>,

    /// Move crate from pre-release to graduation queue
    /// (only valid if crate is NOT currently in prerelease version)
    #[arg(long, value_name = "CRATE")]
    pub graduate: Vec<String>,

    /// List current pre-release configuration
    #[arg(long, short)]
    pub list: bool,
}

#[derive(Args)]
pub(crate) struct ManageGraduationArgs {
    /// Add crate to graduation queue (must be 0.x version)
    #[arg(long, value_name = "CRATE")]
    pub add: Vec<String>,

    /// Remove crate from graduation queue
    #[arg(long, value_name = "CRATE")]
    pub remove: Vec<String>,

    /// List crates marked for graduation
    #[arg(long, short)]
    pub list: bool,
}

#[derive(Subcommand)]
pub(crate) enum ManageCommand {
    /// Manage active pre-releases (.changeset/pre-release.toml)
    #[command(name = "pre-release")]
    Prerelease(ManagePrereleaseArgs),

    /// Manage graduation queue (.changeset/graduation.toml)
    Graduation(ManageGraduationArgs),
}

#[derive(Args)]
pub(crate) struct ManageArgs {
    #[command(subcommand)]
    pub command: ManageCommand,
}

pub(crate) struct ExecuteResult {
    pub(crate) quiet: bool,
}

#[derive(Subcommand)]
pub(crate) enum Commands {
    /// Add a new changeset
    Add(AddArgs),
    /// Verify changeset coverage for changed packages
    Verify(VerifyArgs),
    /// Show pending changesets and projected version bumps
    Status,
    /// Calculate version bumps and prepare releases based on pending changesets
    #[command(
        verbatim_doc_comment,
        after_long_help = "\
Pre-release workflow:
  1. cargo changeset release --prerelease alpha      → All packages get alpha tag
  2. cargo changeset release --prerelease foo:alpha  → Only foo gets alpha tag
  3. cargo changeset release                         → Graduates prereleases to stable

Graduation (0.x to 1.0.0):
  - cargo changeset release --graduate foo --graduate bar
  - Or configure in .changeset/graduation.toml

Per-package configuration can also be set via:
  - .changeset/pre-release.toml
  - .changeset/graduation.toml
Use 'cargo changeset manage' to configure these files."
    )]
    Release(ReleaseArgs),
    /// Initialize changeset directory in the project
    Init(InitArgs),
    /// Manage release configuration files
    Manage(ManageArgs),
    /// Manage non-Rust package declarations in Cargo.toml metadata
    #[command(name = "additional-packages")]
    AdditionalPackages(additional_packages::AdditionalPackagesArgs),
}

impl Commands {
    pub(crate) fn execute(self, start_path: &Path) -> (Result<()>, ExecuteResult) {
        let writer = StdoutCliWriter;
        match self {
            Self::Add(args) => (
                add::run(args, start_path, &writer),
                ExecuteResult { quiet: false },
            ),
            Self::Verify(args) => {
                let quiet = args.quiet;
                (
                    verify::run(args, start_path, &writer),
                    ExecuteResult { quiet },
                )
            }
            Self::Status => (
                status::run(start_path, &writer),
                ExecuteResult { quiet: false },
            ),
            Self::Release(args) => (
                release::run(args, start_path, &writer),
                ExecuteResult { quiet: false },
            ),
            Self::Init(args) => (
                init::run(args, start_path, &writer),
                ExecuteResult { quiet: false },
            ),
            Self::Manage(args) => (
                manage::run(args, start_path, &writer),
                ExecuteResult { quiet: false },
            ),
            Self::AdditionalPackages(args) => (
                additional_packages::run(args, start_path, &writer),
                ExecuteResult { quiet: false },
            ),
        }
    }
}

pub(super) fn dialoguer_to_operation_error(e: dialoguer::Error) -> OperationError {
    match e {
        dialoguer::Error::IO(io_err) => OperationError::Io(io_err),
    }
}

pub(super) fn cli_error_to_operation_error(e: crate::error::CliError) -> OperationError {
    use crate::error::CliError;
    match e {
        CliError::Io(io) => OperationError::Io(io),
        CliError::NotATty => OperationError::InteractionRequired,
        CliError::EditorFailed { source } => OperationError::Io(source),
        CliError::Core(e) => OperationError::Core(e),
        CliError::Git(e) => OperationError::Git(e),
        CliError::Project(e) => OperationError::Project(e),
        CliError::Operation(e) => e,
        CliError::CurrentDir(io) => OperationError::Io(io),
        CliError::ManifestFormatRequired | CliError::IncompleteArgs => {
            OperationError::InteractionRequired
        }
        CliError::InvalidPackageBumpFormat { .. }
        | CliError::InvalidBumpType { .. }
        | CliError::VerificationFailed { .. }
        | CliError::ChangesetDeleted { .. } => OperationError::Cancelled,
    }
}

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

    use changeset_operations::OperationError;

    use super::dialoguer_to_operation_error;

    #[test]
    fn converts_io_error_to_operation_io_variant() {
        let io_err = io::Error::new(io::ErrorKind::BrokenPipe, "pipe closed");
        let dialoguer_err = dialoguer::Error::IO(io_err);

        let result = dialoguer_to_operation_error(dialoguer_err);

        assert!(matches!(result, OperationError::Io(_)));
    }

    #[test]
    fn preserves_io_error_kind() {
        let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");
        let dialoguer_err = dialoguer::Error::IO(io_err);

        let result = dialoguer_to_operation_error(dialoguer_err);

        match result {
            OperationError::Io(inner) => {
                assert_eq!(inner.kind(), io::ErrorKind::PermissionDenied);
            }
            other => panic!("expected OperationError::Io, got {other:?}"),
        }
    }

    #[test]
    fn preserves_error_chain() {
        let io_err = io::Error::other("chain test");
        let dialoguer_err = dialoguer::Error::IO(io_err);

        let result = dialoguer_to_operation_error(dialoguer_err);

        let source = std::error::Error::source(&result);
        assert!(
            source.is_some(),
            "error chain should be preserved through conversion"
        );
    }

    #[test]
    fn preserves_io_error_message() {
        let io_err = io::Error::other("terminal unavailable");
        let dialoguer_err = dialoguer::Error::IO(io_err);

        let result = dialoguer_to_operation_error(dialoguer_err);

        assert!(
            result.to_string().contains("IO error"),
            "expected display to contain 'IO error', got: {}",
            result
        );
        match result {
            OperationError::Io(inner) => {
                assert_eq!(inner.to_string(), "terminal unavailable");
            }
            other => panic!("expected OperationError::Io, got {other:?}"),
        }
    }
}

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

    use changeset_operations::OperationError;

    use crate::error::CliError;

    use super::cli_error_to_operation_error;

    #[test]
    fn io_error_maps_to_operation_io() {
        let err = CliError::Io(io::Error::new(io::ErrorKind::NotFound, "not found"));

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::Io(_)));
    }

    #[test]
    fn not_a_tty_maps_to_interaction_required() {
        let err = CliError::NotATty;

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::InteractionRequired));
    }

    #[test]
    fn incomplete_args_maps_to_interaction_required() {
        let err = CliError::IncompleteArgs;

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::InteractionRequired));
    }

    #[test]
    fn operation_error_passes_through() {
        let inner = OperationError::Cancelled;
        let err = CliError::Operation(inner);

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::Cancelled));
    }

    #[test]
    fn project_error_maps_to_operation_project() {
        use std::path::PathBuf;
        let err = CliError::Project(changeset_project::ProjectError::NotFound {
            start_dir: PathBuf::from("/test"),
        });

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::Project(_)));
    }

    #[test]
    fn editor_failed_maps_to_operation_io() {
        let err = CliError::EditorFailed {
            source: io::Error::new(io::ErrorKind::NotFound, "editor not found"),
        };

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::Io(_)));
    }

    #[test]
    fn invalid_package_bump_format_maps_to_cancelled() {
        let err = CliError::InvalidPackageBumpFormat {
            input: "bad".to_string(),
        };

        let result = cli_error_to_operation_error(err);

        assert!(matches!(result, OperationError::Cancelled));
    }
}