bumpversion 0.0.13

Update all version strings in your project and optionally commit and tag the changes
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
//! File operations for searching and replacing version strings in project files.
//!
//! Handles reading, modifying, and writing files based on configuration.
use crate::{
    config::{self, FileChange, InputFile, VersionComponentConfigs},
    f_string::{self, PythonFormatString},
    version::{self, Version},
};
use indexmap::IndexMap;
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};

// /// Does the search pattern match any part of the contents?
// fn contains_pattern(contents: &str, search_pattern: &regex::Regex) -> bool {
//     let matches = search_pattern.captures_iter(contents);
//     let Some(m) = matches.into_iter().next() else {
//         return false;
//     };
//     let Some(m) = m.iter().next().flatten() else {
//         return false;
//     };
//     let line_num = contents[..m.start()].chars().filter(|c| *c == '\n').count() + 1;
//     tracing::info!(
//         "found {:?} at line {}: {:?}",
//         search_pattern.as_str(),
//         line_num,
//         m.as_str(),
//     );
//     true
// }

/// Errors that can occur when replacing version strings in files.
#[derive(thiserror::Error, Debug)]
pub enum ReplaceVersionError {
    #[error(transparent)]
    /// I/O error while reading or writing a file.
    Io(#[from] IoError),
    #[error(transparent)]
    /// Failed to serialize a version according to the configured patterns.
    Serialize(#[from] version::SerializeError),
    #[error(transparent)]
    /// Required template argument is missing.
    MissingArgument(#[from] f_string::MissingArgumentError),
    #[error(transparent)]
    /// Invalid Python-style format string.
    InvalidFormatString(#[from] f_string::ParseError),

    #[error(transparent)]
    /// Failed to format a regex template.
    RegexTemplate(#[from] config::regex::RegexTemplateError),
    #[error(transparent)]
    /// TOML editing error.
    Toml(#[from] toml_edit::TomlError),
}

/// Apply a list of `changes` to the input `before` content,
/// producing the modified text and a record of replacements.
///
/// # Errors
/// Returns `ReplaceVersionError` if serialization, I/O, or formatting fails.
pub fn replace_version<'a, K, V, S>(
    before: String,
    changes: &'a [FileChange],
    current_version: &'a Version,
    new_version: &'a Version,
    ctx: &'a HashMap<K, V, S>,
) -> Result<Modification, ReplaceVersionError>
where
    K: std::borrow::Borrow<str> + std::hash::Hash + Eq + std::fmt::Debug,
    V: AsRef<str> + std::fmt::Debug,
    S: std::hash::BuildHasher,
{
    let mut after = before.clone();
    let mut replacements = vec![];
    for change in changes {
        tracing::debug!(
            search = ?change.search,
            replace = ?change.replace,
            "update",
        );

        // we need to update the version because each file may serialize versions differently
        let current_version_serialized =
            current_version.serialize(&change.serialize_version_patterns, ctx)?;
        let new_version_serialized =
            new_version.serialize(&change.serialize_version_patterns, ctx)?;

        let ctx: HashMap<&str, &str> = ctx
            .iter()
            .map(|(k, v)| (k.borrow(), v.as_ref()))
            .chain([
                ("current_version", current_version_serialized.as_str()),
                ("new_version", new_version_serialized.as_str()),
            ])
            .collect();

        let search_pattern = &change.search;
        let search_regex = search_pattern.format(&ctx, true)?;

        let replace_pattern = &change.replace;
        let replacement = PythonFormatString::parse(replace_pattern)?;
        let replacement = replacement.format(&ctx, true)?;

        // TODO(roman): i don't think we need to check if the change pattern is present?
        // // does the file contain the change pattern?
        // let contains_change_pattern: bool = {
        //     if contains_pattern(&before, &search_regex) {
        //         return Ok(true);
        //     }
        //
        //     // The `search` pattern did not match, but the original supplied
        //     // version number (representing the same version component values) might
        //     // match instead. This is probably the case if environment variables are used.
        //     let file_uses_global_search_pattern = file_change.search == version_config.search;
        //
        //     let pattern = regex::RegexBuilder::new(regex::escape(version.original)).build()?;
        //
        //     if file_uses_global_search_pattern && contains_pattern(&before, &pattern) {
        //         // The original version is present, and we're not looking for something
        //         // more specific -> this is accepted as a match
        //         return Ok(true);
        //     }
        //
        //     Ok(false)
        // }?;
        //
        // if !contains_change_pattern {
        //     if file_change.ignore_missing_version {
        //         tracing::warn!("did not find {:?} in file {path:?}", search_regex.as_str());
        //     } else {
        //         eyre::bail!("did not find {:?} in file {path:?}", search_regex.as_str());
        //     }
        //     return Ok(());
        // }

        after = search_regex.replace_all(&after, &replacement).to_string();

        replacements.push(Replacement {
            search_pattern: search_pattern.to_string(),
            search: search_regex.as_str().to_string(),
            replace_pattern: replace_pattern.clone(),
            replace: replacement,
        });
    }

    let modification = Modification {
        before,
        after,
        replacements,
    };
    Ok(modification)
}

/// A single substitution made during version replacement.
#[derive(Debug)]
pub struct Replacement {
    /// The regex string used to search for the existing version.
    pub search: String,
    /// Original search template from configuration before formatting.
    pub search_pattern: String,
    /// Replacement string generated with the new version.
    pub replace: String,
    /// Template used for replacement before formatting.
    pub replace_pattern: String,
}

/// Represents the overall result of modifying a file.
#[derive(Debug)]
pub struct Modification {
    /// Original file content before any replacements.
    pub before: String,
    /// File content after applying all replacements.
    pub after: String,
    /// Detailed list of individual replacements performed.
    pub replacements: Vec<Replacement>,
}

impl Modification {
    /// Generate a unified diff between original and modified content.
    ///
    /// If `path` is provided, include labels in the diff header.
    #[must_use]
    pub fn diff(&self, path: Option<&Path>) -> Option<String> {
        if self.before == self.after {
            None
        } else {
            let (label_before, label_after) = if let Some(path) = path {
                (
                    format!("{} (before)", path.display()),
                    format!("{} (after)", path.display()),
                )
            } else {
                ("before".to_string(), "after".to_string())
            };
            let diff = similar_asserts::SimpleDiff::from_str(
                &self.before,
                &self.after,
                &label_before,
                &label_after,
            );
            Some(diff.to_string())
        }
    }
}

/// Read a file at `path`, apply version replacement, and write back if changed.
///
/// Honors `dry_run` to skip writing. Returns `None` if file unchanged or missing (when allowed).
///
/// # Errors
///
/// Returns [`ReplaceVersionError`] if the file cannot be read or written, or a configured version
/// replacement cannot be rendered.
pub async fn replace_version_in_file<K, V, S>(
    path: &Path,
    changes: &[FileChange],
    current_version: &Version,
    new_version: &Version,
    ctx: &HashMap<K, V, S>,
    dry_run: bool,
) -> Result<Option<Modification>, ReplaceVersionError>
where
    K: std::borrow::Borrow<str> + std::hash::Hash + Eq + std::fmt::Debug,
    V: AsRef<str> + std::fmt::Debug,
    S: std::hash::BuildHasher,
{
    let as_io_error = |source: std::io::Error| -> IoError { IoError::new(source, path) };
    if !path.is_file() {
        if changes.iter().all(|change| change.ignore_missing_file) {
            tracing::info!(?path, "file not found");
            return Ok(None);
        }
        let not_found = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
        return Err(ReplaceVersionError::from(as_io_error(not_found)));
    }

    let before = tokio::fs::read_to_string(path).await.map_err(as_io_error)?;
    let modification = replace_version(before, changes, current_version, new_version, ctx)?;

    if modification.before == modification.after {
        // tracing::warn!(?path, "no change after version replacement");
        // TODO(roman): can we also not do this?
        // && current_version.original {
        // og_context = deepcopy(context)
        // og_context["current_version"] = current_version.original
        // search_for_og, _ = self.file_change.get_search_pattern(og_context)
        // file_content_after = search_for_og.sub(replace_with, file_content_before)
        // return Ok(());
    }

    if !dry_run {
        use tokio::io::AsyncWriteExt;
        let file = tokio::fs::OpenOptions::new()
            .write(true)
            .create(false)
            .truncate(true)
            .open(path)
            .await
            .map_err(as_io_error)?;
        let mut writer = tokio::io::BufWriter::new(file);
        writer
            .write_all(modification.after.as_bytes())
            .await
            .map_err(as_io_error)?;
        writer.flush().await.map_err(as_io_error)?;
    }
    Ok(Some(modification))
}

/// Errors encountered when resolving glob patterns to file paths.
#[derive(thiserror::Error, Debug)]
pub enum GlobError {
    #[error(transparent)]
    /// Invalid glob pattern.
    Pattern(#[from] glob::PatternError),
    #[error(transparent)]
    /// Error while iterating glob matches.
    Glob(#[from] glob::GlobError),
}

/// I/O error with optional path context.
#[derive(thiserror::Error, Debug)]
pub struct IoError {
    /// Underlying I/O error.
    #[source]
    pub source: std::io::Error,
    /// Path of the file that caused the error, if available.
    pub path: Option<PathBuf>,
}

impl IoError {
    /// Create a new [`IoError`] with a source error and a path.
    pub fn new(source: impl Into<std::io::Error>, path_or_stream: impl Into<PathBuf>) -> Self {
        Self {
            source: source.into(),
            path: Some(path_or_stream.into()),
        }
    }
}

impl std::fmt::Display for IoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.path {
            Some(path) => write!(f, "io error for {}", path.display()),
            None => write!(f, "io error"),
        }
    }
}

/// Combined error type for file resolution operations.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    /// Error while resolving file globs.
    Glob(#[from] GlobError),
    #[error(transparent)]
    /// I/O error while resolving files.
    Io(#[from] IoError),
}

/// Match options shared by every glob pattern bumpversion expands.
const GLOB_OPTIONS: glob::MatchOptions = glob::MatchOptions {
    case_sensitive: false,
    require_literal_separator: false,
    require_literal_leading_dot: false,
};

/// Whether `component` is the prefix or root of a path rather than a directory or file name.
fn is_path_root(component: Component<'_>) -> bool {
    matches!(component, Component::Prefix(_) | Component::RootDir)
}

/// Whether `path` contains a character that [`glob`] interprets.
///
/// The prefix and root are skipped: a canonical Windows path starts with the verbatim prefix
/// `\\?\`, whose `?` is not a wildcard.
fn is_glob_pattern(path: &Path) -> bool {
    path.components()
        .filter(|component| !is_path_root(*component))
        .any(|component| {
            component
                .as_os_str()
                .to_string_lossy()
                .contains(['*', '?', '['])
        })
}

/// Render `base_dir` as the literal start of a glob pattern.
///
/// Every directory name is escaped so a `*`, `?`, or `[` in it matches itself.
/// The prefix and root are kept as they are, because [`glob`] takes them as the directory to
/// search from rather than as a pattern, and escaping the `?` of a Windows verbatim prefix
/// `\\?\` turns a canonical path into one that matches nothing.
fn literal_glob_prefix(base_dir: &Path) -> PathBuf {
    let mut prefix = PathBuf::new();
    for component in base_dir.components() {
        match component {
            Component::Normal(name) => {
                prefix.push(glob::Pattern::escape(&name.to_string_lossy()));
            }
            _ => prefix.push(component.as_os_str()),
        }
    }
    prefix
}

/// Resolve the `additional_files` entries to the paths staged with the release commit.
///
/// An entry with glob characters is expanded relative to `base_dir`.
/// A match may be a directory, which the VCS stages recursively, so `docs/*/generated` covers
/// every tracked file below each `generated` directory.
/// A pattern that matches nothing is skipped with a warning.
///
/// A plain path is returned as it is, joined to `base_dir` when relative, so the VCS reports a
/// file that does not exist.
///
/// # Errors
///
/// Returns [`GlobError`] if a pattern is invalid or a matched directory cannot be read.
pub fn resolve_additional_files(
    entries: &[PathBuf],
    base_dir: &Path,
) -> Result<Vec<PathBuf>, GlobError> {
    let mut resolved = Vec::new();
    for entry in entries {
        if !is_glob_pattern(entry) {
            resolved.push(if entry.is_absolute() {
                entry.clone()
            } else {
                base_dir.join(entry)
            });
            continue;
        }
        let pattern = if entry.is_absolute() {
            entry.clone()
        } else {
            literal_glob_prefix(base_dir).join(entry)
        };
        let mut matches: Vec<PathBuf> =
            glob::glob_with(&pattern.to_string_lossy(), GLOB_OPTIONS)?.collect::<Result<_, _>>()?;
        if matches.is_empty() {
            tracing::warn!(
                "additional_files pattern {} did not match any files",
                entry.display()
            );
        }
        // Sorted: `glob` yields matches in an unspecified order, and the staged
        // files are logged in the order they are resolved.
        matches.sort();
        resolved.extend(matches);
    }
    Ok(resolved)
}

/// Return a list of file configurations that match the glob pattern
fn resolve_glob_files(
    pattern: &str,
    exclude_patterns: &[String],
) -> Result<Vec<PathBuf>, GlobError> {
    let included: HashSet<PathBuf> =
        glob::glob_with(pattern, GLOB_OPTIONS)?.collect::<Result<_, _>>()?;

    let excluded: HashSet<PathBuf> = exclude_patterns
        .iter()
        .map(|pattern| glob::glob_with(pattern, GLOB_OPTIONS))
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .flat_map(std::iter::IntoIterator::into_iter)
        .collect::<Result<_, _>>()?;

    // Sorted: `glob` yields matches in an unspecified order and the set difference
    // discards it entirely, so without this the files of one glob entry would be
    // rewritten — and logged — in a different order on every run.
    let mut matched: Vec<PathBuf> = included.difference(&excluded).cloned().collect();
    matched.sort();
    Ok(matched)
}

/// Mapping from file paths to the list of version `FileChange`s to apply.
pub type FileMap = IndexMap<PathBuf, Vec<FileChange>>;

/// Build the file map from `config`, expanding glob patterns and relative paths.
///
/// Applies `parts` (version component configs) and resolves paths under `base_dir`.
///
/// # Errors
///
/// Returns [`Error`] if a glob is invalid, a glob match cannot be read, or a relative path cannot
/// be canonicalized.
pub fn resolve_files_from_config(
    config: &mut config::FinalizedConfig,
    parts: &VersionComponentConfigs,
    base_dir: Option<&Path>,
) -> Result<FileMap, Error> {
    let files = config.files.drain(..);
    let new_files: Vec<_> = files
        .into_iter()
        .map(|(file, file_config)| {
            let new_files = match file {
                InputFile::GlobPattern {
                    pattern,
                    exclude_patterns,
                } => resolve_glob_files(&pattern, exclude_patterns.as_deref().unwrap_or_default()),
                InputFile::Path(path) => Ok(vec![path.clone()]),
            }?;

            let file_change = FileChange::new(file_config, parts);
            Ok(new_files
                .into_iter()
                .map(|file| {
                    if file.is_absolute() {
                        Ok(file)
                    } else if let Some(base_dir) = base_dir {
                        let file = base_dir.join(&file);
                        file.canonicalize()
                            .map_err(|source| IoError::new(source, file))
                    } else {
                        Ok(file)
                    }
                })
                .map(move |file| file.map(|file| (file, file_change.clone()))))
        })
        .collect::<Result<_, Error>>()?;

    let new_files = new_files.into_iter().flatten().try_fold(
        IndexMap::<PathBuf, Vec<FileChange>>::new(),
        |mut acc, res| {
            let (file, config) = res?;
            acc.entry(file).or_default().push(config);
            Ok::<_, Error>(acc)
        },
    )?;
    Ok(new_files)
}

/// Filter the `file_map` based on `config` include/exclude settings.
pub fn files_to_modify(
    config: &config::FinalizedConfig,
    file_map: FileMap,
) -> impl Iterator<Item = (PathBuf, Vec<FileChange>)> + use<'_> {
    let excluded_paths_from_config: HashSet<&PathBuf> = config
        .global
        .excluded_paths
        .as_deref()
        .unwrap_or_default()
        .iter()
        .collect();

    let included_paths_from_config: HashSet<&PathBuf> = config
        .global
        .included_paths
        .as_deref()
        .unwrap_or_default()
        .iter()
        .collect();

    let included_files: HashSet<&PathBuf> = file_map
        .keys()
        .collect::<HashSet<&PathBuf>>()
        .difference(&excluded_paths_from_config)
        .copied()
        .collect();

    let included_files: HashSet<PathBuf> = included_paths_from_config
        .union(&included_files)
        .copied()
        .cloned()
        .collect();

    file_map
        .into_iter()
        .filter(move |(file, _)| included_files.contains(file))
}

#[cfg(test)]
mod tests {
    use super::resolve_additional_files;
    use color_eyre::eyre;
    use similar_asserts::assert_eq as sim_assert_eq;
    use std::fs;
    use std::path::PathBuf;

    /// A repository with two generated directories and a lockfile, and its canonical root.
    ///
    /// The root is canonical because the CLI canonicalizes the repository path.
    /// On Windows that adds the verbatim prefix `\\?\`, whose `?` must not be read as a
    /// wildcard.
    fn repo() -> eyre::Result<(tempfile::TempDir, PathBuf)> {
        let temp = tempfile::tempdir()?;
        let root = temp.path().canonicalize()?;
        for example in ["a", "b"] {
            let generated = root.join("docs/examples").join(example).join("generated");
            fs::create_dir_all(&generated)?;
            fs::write(generated.join("out.txt"), "generated")?;
        }
        fs::write(root.join("Cargo.lock"), "lock")?;
        Ok((temp, root))
    }

    /// `git add` does not descend into a directory matched by a wildcard, so the
    /// pattern must be expanded to the directories themselves.
    #[test]
    fn glob_expands_to_matched_directories() -> eyre::Result<()> {
        crate::tests::init();
        let (_temp, root) = repo()?;
        let entries = [PathBuf::from("docs/examples/*/generated")];
        let resolved = resolve_additional_files(&entries, &root)?;
        sim_assert_eq!(
            resolved,
            vec![
                root.join("docs/examples/a/generated"),
                root.join("docs/examples/b/generated"),
            ]
        );
        Ok(())
    }

    /// A plain path is not looked up, so a missing lockfile still reaches the
    /// VCS, which reports it.
    #[test]
    fn plain_paths_pass_through() -> eyre::Result<()> {
        crate::tests::init();
        let (_temp, root) = repo()?;
        let entries = [PathBuf::from("Cargo.lock"), PathBuf::from("missing.lock")];
        let resolved = resolve_additional_files(&entries, &root)?;
        sim_assert_eq!(
            resolved,
            vec![root.join("Cargo.lock"), root.join("missing.lock")]
        );
        Ok(())
    }

    /// A pattern without matches contributes nothing rather than an invalid
    /// pathspec.
    #[test]
    fn unmatched_glob_is_skipped() -> eyre::Result<()> {
        crate::tests::init();
        let (_temp, root) = repo()?;
        let entries = [PathBuf::from("nothing/*/here"), PathBuf::from("Cargo.lock")];
        let resolved = resolve_additional_files(&entries, &root)?;
        sim_assert_eq!(resolved, vec![root.join("Cargo.lock")]);
        Ok(())
    }

    #[test]
    fn invalid_glob_is_an_error() -> eyre::Result<()> {
        crate::tests::init();
        let (_temp, root) = repo()?;
        let entries = [PathBuf::from("docs/[unclosed")];
        assert!(resolve_additional_files(&entries, &root).is_err());
        Ok(())
    }

    /// The `?` in the verbatim prefix of a canonical Windows path is not a wildcard,
    /// so a plain absolute path stays a plain path.
    #[cfg(windows)]
    #[test]
    fn verbatim_prefix_is_not_a_glob() {
        assert!(!super::is_glob_pattern(std::path::Path::new(
            r"\\?\C:\repo\Cargo.lock"
        )));
        assert!(super::is_glob_pattern(std::path::Path::new(
            r"\\?\C:\repo\docs\*\generated"
        )));
    }
}