bumpversion-cli 0.0.9

Update all version strings in your project and optionally commit and tag the changes
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
//! Command-line options and parsing for bumpversion CLI.
//!
//! Defines flags, positional arguments, and configuration overrides via environment.
use bumpversion::config;
use color_eyre::eyre;
use std::path::PathBuf;

/// Trait to invert an `Option<bool>`, used for negatable flags (e.g., --flag/--no-flag).
pub trait Invert {
    /// Flip the contained boolean if present.
    fn invert(self) -> Self;
}

impl Invert for Option<bool> {
    fn invert(self) -> Self {
        self.map(|value| !value)
    }
}

/// Subcommands for the CLI.
#[derive(clap::Parser, Debug, Clone)]
pub enum SubCommand {
    #[clap(name = "major")]
    Major,
    #[clap(name = "minor")]
    Minor,
    #[clap(name = "patch")]
    Patch,
    #[clap(name = "show")]
    Show(ShowOptions),
    #[clap(name = "show-bump")]
    ShowBump(ShowBumpOptions),
    #[clap(name = "bump")]
    Bump(BumpOptions),
}

#[derive(clap::Args, Debug, Clone)]
pub struct ShowOptions {
    #[arg(help = "The variables or configuration settings to show")]
    pub variables: Vec<String>,
}

#[derive(clap::Args, Debug, Clone)]
pub struct ShowBumpOptions {
    #[arg(help = "The version component to bump")]
    pub component: Option<String>,

    #[arg()]
    pub args: Vec<String>,
}

#[derive(clap::Args, Debug, Clone)]
pub struct BumpOptions {
    #[arg(help = "The version component to bump")]
    pub component: String,

    #[arg()]
    pub args: Vec<String>,
}

/// Logging flags to `#[command(flatten)]` into your CLI
#[derive(clap::Args, Debug, Clone, Copy, Default)]
pub struct Verbosity {
    #[arg(
        long,
        short = 'v',
        action = clap::ArgAction::Count,
        global = true,
        help = "Increase logging verbosity",
        long_help = None,
    )]
    pub verbose: u8,

    #[arg(
        long,
        short = 'q',
        action = clap::ArgAction::Count,
        global = true,
        help = "Decrease logging verbosity",
        long_help = None,
        conflicts_with = "verbose",
    )]
    pub quiet: u8,
}

/// CLI options for the `bumpversion` command.
#[derive(clap::Parser, Debug, Clone)]
#[clap(
    name = "bumpversion",
    version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
    about = "bump git version",
    author = "romnn <contact@romnn.com>",
)]
pub struct Options {
    #[clap(
        long = "dir",
        help = "repository directory to run bumpversion in",
        env = "BUMPVERSION_DIR",
        global = true,
    )]
    pub dir: Option<PathBuf>,

    #[clap(
        long = "config-file",
        help = "config file to read most of the variables from",
        env = "BUMPVERSION_CONFIG_FILE",
        global = true,
    )]
    pub config_file: Option<PathBuf>,

    #[arg(
        long = "color",
        env = "BUMPVERSION_COLOR",
        help = "enable or disable color",
        global = true,
    )]
    pub color_choice: Option<termcolor::ColorChoice>,

    #[command(flatten)]
    pub verbosity: Verbosity,

    #[arg(
        long = "log",
        env = "BUMPVERSION_LOG_LEVEL",
        aliases = ["log-level"],
        help = "Log level. When using a more sophisticated logging setup using RUST_LOG environment variable, this option is overwritten.",
        global = true,
    )]
    pub log_level: Option<tracing::metadata::Level>,

    #[clap(
        long = "allow-dirty",
        help = "don't abort if working directory is dirty",
        env = "BUMPVERSION_ALLOW_DIRTY",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub allow_dirty: Option<bool>,

    #[clap(
        long = "no-allow-dirty",
        help = "explicitly abort if dirty",
        env = "BUMPVERSION_NO_ALLOW_DIRTY",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_allow_dirty: Option<bool>,

    #[clap(
        long = "current-version",
        help = "version that needs to be updated",
        env = "BUMPVERSION_CURRENT_VERSION",
        global = true,
    )]
    pub current_version: Option<String>,

    #[clap(
        long = "new-version",
        help = "new version that should be in the files",
        env = "BUMPVERSION_NEW_VERSION",
        global = true,
    )]
    pub new_version: Option<String>,

    #[clap(
        long = "parse",
        help = "regex parsing the version string",
        env = "BUMPVERSION_PARSE",
        global = true,
    )]
    pub parse_version_pattern: Option<String>,

    #[clap(
        long = "serialize",
        help = "how to format what is parsed back to a version",
        env = "BUMPVERSION_SERIALIZE",
        global = true,
    )]
    pub serialize_version_patterns: Option<Vec<String>>,

    #[clap(
        long = "search",
        help = "template for complete string to search",
        env = "BUMPVERSION_SEARCH",
        global = true,
    )]
    pub search: Option<String>,

    #[clap(
        long = "replace",
        help = "template for complete string to replace",
        env = "BUMPVERSION_REPLACE",
        global = true,
    )]
    pub replace: Option<String>,

    #[clap(
        long = "regex",
        help = "treat the search parameter as a regular expression",
        env = "BUMPVERSION_REGEX",
        global = true,
    )]
    pub regex: Option<bool>,

    #[clap(
        long = "no-regex",
        help = "explicitly do not treat the search parameter as a regular expression",
        env = "BUMPVERSION_NO_REGEX",
        global = true,
    )]
    pub no_regex: Option<bool>,

    #[clap(
        long = "no-configured-files", 
        help = "only replace the version in files specified on the command line, ignoring the files from the configuration file",
        env = "BUMPVERSION_NO_CONFIGURED_FILES",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_configured_files: Option<bool>,

    #[clap(
        long = "ignore-missing-files", 
        help = "ignore any missing files when searching and replacing in files",
        env = "BUMPVERSION_IGNORE_MISSING_FILES",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub ignore_missing_files: Option<bool>,

    #[clap(
        long = "no-ignore-missing-files", 
        help = "do not allow missing files when searching and replacing in files",
        env = "BUMPVERSION_NO_IGNORE_MISSING_FILES",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_ignore_missing_files: Option<bool>,

    #[clap(
        long = "ignore-missing-version", 
        help = "ignore any missing versions when searching and replacing in files",
        env = "BUMPVERSION_IGNORE_MISSING_VERSION",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub ignore_missing_version: Option<bool>,

    #[clap(
        long = "no-ignore-missing-version", 
        help = "do not allow missing versions when searching and replacing in files",
        env = "BUMPVERSION_NO_IGNORE_MISSING_VERSION",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_ignore_missing_version: Option<bool>,

    #[clap(
        short = 'n',
        long = "dry-run",
        help = "don't write any files, just pretend.",
        env = "BUMPVERSION_DRY_RUN",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub dry_run: Option<bool>,

    #[clap(
        long = "commit",
        help = "commit to version control",
        env = "BUMPVERSION_COMMIT",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub commit: Option<bool>,

    #[clap(
        long = "no-commit",
        help = "do not commit to version control",
        env = "BUMPVERSION_NO_COMMIT",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_commit: Option<bool>,

    #[clap(
        long = "tag",
        help = "create a tag in version control",
        env = "BUMPVERSION_TAG",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub tag: Option<bool>,

    #[clap(
        long = "no-tag",
        help = "do not create a tag in version control",
        env = "BUMPVERSION_NO_TAG",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_tag: Option<bool>,

    #[clap(
        long = "sign-tags",
        help = "sign tags if created",
        env = "BUMPVERSION_SIGN_TAGS",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub sign_tags: Option<bool>,

    #[clap(
        long = "no-sign-tags",
        help = "do not sign tags if created",
        env = "BUMPVERSION_NO_SIGN_TAGS",
        action = clap::ArgAction::SetTrue,
        global = true,
    )]
    pub no_sign_tag: Option<bool>,

    #[clap(
        long = "tag-name",
        help = "tag name (only works with --tag)",
        env = "BUMPVERSION_TAG_NAME",
        global = true,
    )]
    pub tag_name: Option<String>,

    #[clap(
        long = "tag-message",
        help = "tag message",
        env = "BUMPVERSION_TAG_MESSAGE",
        global = true,
    )]
    pub tag_message: Option<String>,

    #[clap(
        short = 'm',
        long = "message",
        help = "commit message",
        env = "BUMPVERSION_MESSAGE",
        global = true,
    )]
    pub commit_message: Option<String>,

    #[clap(
        long = "commit-args",
        help = "extra arguments to commit command",
        env = "BUMPVERSION_COMMIT_ARGS",
        global = true,
    )]
    pub commit_args: Option<String>,

    #[clap(subcommand)]
    pub command: Option<SubCommand>,

    #[arg()]
    pub args: Vec<String>,
}

pub fn fix(options: &mut Options) {
    // HACK(roman):
    //
    // For some reason, clap v4 may set `options.allow_dirty = Some(false)` when using
    // `clap::ArgAction::SetTrue` and the flag is not specified.
    //
    // It's fine to check for these cases, since `clap::ArgAction::SetTrue` does not allow
    // users to set `--allow-dirty=false`.
    for boolean_option in [
        &mut options.allow_dirty,
        &mut options.no_allow_dirty,
        &mut options.regex,
        &mut options.no_regex,
        &mut options.no_configured_files,
        &mut options.ignore_missing_files,
        &mut options.no_ignore_missing_files,
        &mut options.ignore_missing_version,
        &mut options.no_ignore_missing_version,
        &mut options.dry_run,
        &mut options.commit,
        &mut options.no_commit,
        &mut options.tag,
        &mut options.no_tag,
        &mut options.sign_tags,
        &mut options.no_sign_tag,
    ] {
        if *boolean_option != Some(true) {
            *boolean_option = None;
        }
    }
}

pub fn parse_positional_arguments(
    options: &mut Options,
    components: &config::VersionComponentConfigs,
) -> eyre::Result<(Option<String>, Vec<PathBuf>)> {
    let mut cli_files = vec![];
    let mut bump: Option<String> = None;

    if let Some(command) = &options.command {
        match command {
            SubCommand::Major => bump = Some("major".to_string()),
            SubCommand::Minor => bump = Some("minor".to_string()),
            SubCommand::Patch => bump = Some("patch".to_string()),
            SubCommand::Bump(opts) => {
                bump = Some(opts.component.clone());
                cli_files.extend(opts.args.iter().map(PathBuf::from));
            }
            SubCommand::Show(_) | SubCommand::ShowBump(_) => {
                // These commands don't produce a 'bump' action or files in the same way
                // They are handled separately in common.rs
            }
        }
    } else if !options.args.is_empty() {
        // No subcommand, check legacy args
        // first, check for invalid flags in the args
        for arg in &options.args {
            if arg.starts_with("--") {
                eyre::bail!("unknown flag {arg:?}");
            }
        }

        // first argument must be version component to bump
        let component = options.args.remove(0);
        if components.contains_key(&component) {
            bump = Some(component);

            // remaining arguments are files
            cli_files.extend(options.args.drain(..).map(PathBuf::from));
        } else {
            eyre::bail!(
                "first argument must be one of the version components {:?}",
                components.keys().collect::<Vec<_>>()
            )
        }
    }

    Ok((bump, cli_files))
}

pub fn global_cli_config(options: &Options) -> eyre::Result<bumpversion::config::GlobalConfig> {
    let search_as_regex = options
        .allow_dirty
        .or(options.no_allow_dirty.invert())
        .unwrap_or(false);

    let search = options
        .search
        .as_ref()
        .map(|search| {
            let format_string = bumpversion::f_string::PythonFormatString::parse(search)?;
            let search = if search_as_regex {
                bumpversion::config::RegexTemplate::Regex(format_string)
            } else {
                bumpversion::config::RegexTemplate::Escaped(format_string)
            };
            Ok::<_, eyre::Report>(search)
        })
        .transpose()?;

    let parse_version_pattern = options
        .parse_version_pattern
        .as_deref()
        .map(bumpversion::config::Regex::try_from)
        .transpose()?;

    let serialize_version_patterns = options
        .serialize_version_patterns
        .as_ref()
        .map(|patterns| {
            patterns
                .iter()
                .map(String::as_str)
                .map(bumpversion::f_string::PythonFormatString::parse)
                .collect::<Result<Vec<_>, _>>()
        })
        .transpose()?;

    let tag_name = options
        .tag_name
        .as_deref()
        .map(bumpversion::f_string::PythonFormatString::parse)
        .transpose()?;

    let tag_message = options
        .tag_name
        .as_deref()
        .map(bumpversion::f_string::PythonFormatString::parse)
        .transpose()?;

    let commit_message = options
        .commit_message
        .as_deref()
        .map(bumpversion::f_string::PythonFormatString::parse)
        .transpose()?;

    let cli_overrides = bumpversion::config::GlobalConfig {
        allow_dirty: options.allow_dirty.or(options.no_allow_dirty.invert()),
        current_version: options.current_version.clone(),
        parse_version_pattern,
        serialize_version_patterns,
        search,
        replace: options.replace.clone(),
        no_configured_files: options.no_configured_files,
        ignore_missing_files: options
            .ignore_missing_files
            .or(options.no_ignore_missing_files.invert()),
        ignore_missing_version: options
            .ignore_missing_version
            .or(options.no_ignore_missing_version.invert()),
        dry_run: options.dry_run,
        commit: options.commit.or(options.no_commit.invert()),
        tag: options.tag.or(options.no_tag.invert()),
        sign_tags: options.sign_tags.or(options.no_sign_tag.invert()),
        tag_name,
        tag_message,
        commit_message,
        commit_args: options.commit_args.clone(),
        ..bumpversion::config::GlobalConfig::empty()
    };
    Ok(cli_overrides)
}