bumpversion 0.0.9

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
//! Git backend for version control operations.
//!
//! Implements the `VersionControlSystem` trait using git commands.
use crate::{
    command::run_command,
    f_string::{PythonFormatString, Value},
    vcs::{RevisionInfo, TagAndRevision, TagInfo, VersionControlSystem},
};
use async_process::Command;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

/// Git VCS error type.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// I/O error while running git commands.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// UTF-8 decoding error.
    #[error("UTF-8 decode error: {0}")]
    Utf8(#[from] std::str::Utf8Error),

    /// Git command execution failed.
    #[error("command failed: {0}")]
    CommandFailed(#[from] crate::command::Error),

    /// Regex compilation error.
    #[error("regex error: {0}")]
    Regex(#[from] regex::Error),

    /// Failed to parse tag output.
    #[error("invalid tag: {0}")]
    InvalidTag(#[from] InvalidTagError),

    /// Missing argument while formatting a template.
    #[error("failed to template {format_string}")]
    MissingArgument {
        /// Underlying missing-argument error.
        #[source]
        source: crate::f_string::MissingArgumentError,
        /// Template that failed to format.
        format_string: PythonFormatString,
    },
}

/// Errors parsing git tag strings into version metadata.
#[derive(thiserror::Error, Debug)]
pub enum InvalidTagError {
    /// Tag output did not include a commit SHA.
    #[error("tag {0:?} is missing commit SHA")]
    MissingCommitSha(String),

    /// Tag output did not include the distance to the latest tag.
    #[error("tag {0:?} is missing distance to latest tag")]
    MissingDistanceToLatestTag(String),

    /// Distance to latest tag could not be parsed.
    #[error("invalid distance to latest tag for {tag:?}")]
    InvalidDistanceToLatestTag {
        /// Underlying parse error.
        #[source]
        source: std::num::ParseIntError,
        /// The tag string that contained the invalid distance.
        tag: String,
    },

    /// Tag output did not include the tag name.
    #[error("tag {0:?} is missing current tag")]
    MissingCurrentTag(String),

    /// Tag output did not include the version string.
    #[error("tag {0:?} is missing version")]
    MissingVersion(String),
}

/// Represents a git repository at a given filesystem path.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[allow(clippy::module_name_repetitions)]
pub struct GitRepository {
    path: PathBuf,
}

static FLAG_PATTERN: LazyLock<regex::Regex> = LazyLock::new(|| {
    #[expect(
        clippy::unwrap_used,
        reason = "static regex pattern is a hard-coded literal and is guaranteed to be valid"
    )]
    regex::RegexBuilder::new(r"^(\(\?[aiLmsux]+\))")
        .build()
        .unwrap()
});

/// Extract the regex flags from the regex pattern.
///
/// # Returns
/// The tuple `(pattern_without flags, flags)`.
fn extract_regex_flags(pattern: &str) -> (&str, &str) {
    let bits: Vec<_> = FLAG_PATTERN.split(pattern).collect();
    let Some(pattern_without_flags) = bits.get(1).copied() else {
        return (pattern, "");
    };
    let flags = bits.first().copied().unwrap_or("");
    (pattern_without_flags, flags)
}

/// Return the version from a tag
///
/// # Errors
/// - When the given `parse_version_regex` cannot be transformed to extract the
///   current version from the git tag
fn get_version_from_tag<'a>(
    tag: &'a str,
    tag_name: &PythonFormatString,
    parse_version_regex: &regex::Regex,
) -> Result<Option<&'a str>, regex::Error> {
    let parse_pattern = parse_version_regex.as_str();
    let version_pattern = parse_pattern.replace("\\\\", "\\");
    let (version_pattern, regex_flags) = extract_regex_flags(&version_pattern);
    let PythonFormatString(values) = tag_name;

    let mut prefix = String::new();
    let mut suffix = String::new();
    if let Some(idx) = values
        .iter()
        .position(|value| value == &Value::Argument("new_version".to_string()))
    {
        for value in values.iter().take(idx) {
            prefix.push_str(&value.to_string());
        }
        for value in values.iter().skip(idx + 1) {
            suffix.push_str(&value.to_string());
        }
    }

    let pattern = format!(
        "{regex_flags}{}(?P<current_version>{version_pattern}){}",
        regex::escape(&prefix),
        regex::escape(&suffix),
    );
    let tag_regex = regex::RegexBuilder::new(&pattern).build()?;
    let version = tag_regex
        .captures_iter(tag)
        .filter_map(|m| m.name("current_version"))
        .map(|m| m.as_str())
        .next();
    Ok(version)
}

/// Regex used to remove non-alphanumeric characters from branch names.
pub static BRANCH_NAME_REGEX: LazyLock<regex::Regex> = LazyLock::new(|| {
    #[expect(
        clippy::unwrap_used,
        reason = "static regex pattern is a hard-coded literal and is guaranteed to be valid"
    )]
    regex::RegexBuilder::new(r"([^a-zA-Z0-9]*)")
        .build()
        .unwrap()
});

impl GitRepository {
    /// Returns a dictionary containing revision information.
    async fn revision_info(&self) -> Result<Option<RevisionInfo>, Error> {
        let mut cmd = Command::new("git");
        cmd.args(["rev-parse", "--show-toplevel", "--abbrev-ref", "HEAD"])
            .current_dir(&self.path);

        let res = run_command(&mut cmd).await?;
        let mut lines = res.stdout.lines().map(str::trim);
        let Some(repository_root) = lines.next().map(PathBuf::from) else {
            return Ok(None);
        };
        let Some(branch_name) = lines.next() else {
            return Ok(None);
        };
        let short_branch_name: String = BRANCH_NAME_REGEX
            .replace_all(branch_name, "")
            .to_lowercase()
            .chars()
            .take(20)
            .collect();

        Ok(Some(RevisionInfo {
            branch_name: branch_name.to_string(),
            short_branch_name,
            repository_root,
        }))
    }

    /// Get the commit info for the repo.
    ///
    /// The `tag_name` is the tag name format used to locate the latest tag.
    /// The `parse_pattern` is a regular expression pattern used to parse the version from the tag.
    async fn latest_tag_info(
        &self,
        tag_name: &PythonFormatString,
        parse_version_regex: &regex::Regex,
    ) -> Result<Option<TagInfo>, Error> {
        let tag_pattern = tag_name
            .format(&[("new_version", "*")].into_iter().collect(), true)
            .map_err(|source| Error::MissingArgument {
                source,
                format_string: tag_name.clone(),
            })?;
        // let tag_pattern = tag_name.replace("{new_version}", "*");

        // get info about the latest tag in git
        let match_tag_pattern_flag = format!("--match={tag_pattern}");
        let mut cmd = Command::new("git");
        cmd.args([
            "describe",
            "--dirty",
            "--tags",
            "--long",
            "--abbrev=40",
            &match_tag_pattern_flag,
        ])
        .current_dir(&self.path);

        match run_command(&mut cmd).await {
            Ok(tag_info) => {
                let raw_tag = tag_info.stdout;
                let mut tag_parts: Vec<&str> = raw_tag.split('-').collect();

                let dirty = tag_parts
                    .last()
                    .is_some_and(|t| t.trim().eq_ignore_ascii_case("dirty"));
                if dirty {
                    let _ = tag_parts.pop();
                }

                let commit_sha = tag_parts
                    .pop()
                    .ok_or_else(|| InvalidTagError::MissingCommitSha(raw_tag.clone()))?
                    .trim_start_matches('g')
                    .to_string();

                let distance_to_latest_tag = tag_parts
                    .pop()
                    .ok_or_else(|| InvalidTagError::MissingDistanceToLatestTag(raw_tag.clone()))?
                    .parse::<usize>()
                    .map_err(|source| InvalidTagError::InvalidDistanceToLatestTag {
                        source,
                        tag: raw_tag.clone(),
                    })?;
                let current_tag = tag_parts.join("-");
                let version = get_version_from_tag(&current_tag, tag_name, parse_version_regex)?;
                let current_numeric_version = current_tag.trim_start_matches('v').to_string();
                let current_version = version
                    .unwrap_or(current_numeric_version.as_str())
                    .to_string();

                tracing::debug!(
                    dirty,
                    commit_sha,
                    distance_to_latest_tag,
                    current_tag,
                    version,
                    current_numeric_version,
                    current_version
                );

                Ok(Some(TagInfo {
                    dirty,
                    commit_sha,
                    distance_to_latest_tag,
                    current_tag,
                    current_version,
                }))
            }
            Err(err) => {
                if let crate::command::Error::Failed { ref output, .. } = err
                    && output
                        .stderr
                        .contains("No names found, cannot describe anything")
                    {
                        return Ok(None);
                    }
                Err(err.into())
            }
        }
    }
}

// #[async_trait::async_trait]
impl VersionControlSystem for GitRepository {
    type Error = Error;

    fn open(path: impl Into<PathBuf>) -> Result<Self, Error> {
        Ok(Self { path: path.into() })
    }

    fn path(&self) -> &Path {
        &self.path
    }

    async fn commit<A, E, AS, EK, EV>(
        &self,
        message: &str,
        extra_args: A,
        env: E,
    ) -> Result<(), Error>
    where
        A: IntoIterator<Item = AS>,
        E: IntoIterator<Item = (EK, EV)>,
        AS: AsRef<std::ffi::OsStr>,
        EK: AsRef<std::ffi::OsStr>,
        EV: AsRef<std::ffi::OsStr>,
    {
        use tokio::io::AsyncWriteExt;

        let tmp = tempfile::TempDir::new()?;
        let tmp_file_path = tmp.path().join("commit-message.txt");
        let tmp_file = tokio::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&tmp_file_path)
            .await?;
        let mut writer = tokio::io::BufWriter::new(tmp_file);
        writer.write_all(message.as_bytes()).await?;
        writer.flush().await?;

        let mut cmd = Command::new("git");
        cmd.arg("commit");
        cmd.arg("-F");
        cmd.arg(tmp_file_path.to_string_lossy().to_string());
        cmd.args(extra_args);
        cmd.envs(env);
        cmd.current_dir(&self.path);
        let _commit_output = run_command(&mut cmd).await?;
        Ok(())
    }

    async fn add<P>(&self, files: impl IntoIterator<Item = P>) -> Result<(), Error>
    where
        P: AsRef<std::ffi::OsStr>,
    {
        let mut cmd = Command::new("git");
        cmd.arg("add")
            .arg("--update")
            .args(files)
            .current_dir(&self.path);
        let _add_output = run_command(&mut cmd).await?;
        Ok(())
    }

    async fn dirty_files(&self) -> Result<Vec<PathBuf>, Error> {
        let mut cmd = Command::new("git");
        cmd.args(["status", "-u", "--porcelain"])
            .current_dir(&self.path);

        let status_output = run_command(&mut cmd).await?;
        let dirty = status_output
            .stdout
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .filter(|line| !line.starts_with("??"))
            .filter_map(|line| line.split_once(' '))
            .map(|(_, file)| self.path().join(file))
            .collect();
        Ok(dirty)
    }

    async fn tag(&self, name: &str, message: Option<&str>, sign: bool) -> Result<(), Error> {
        let mut cmd = Command::new("git");
        cmd.current_dir(&self.path);
        cmd.args(["tag", name]);
        if sign {
            cmd.arg("--sign");
        }
        if let Some(message) = message {
            cmd.args(["--message", message]);
        }
        let _tag_output = run_command(&mut cmd).await?;
        Ok(())
    }

    async fn tags(&self) -> Result<Vec<String>, Error> {
        let mut cmd = Command::new("git");
        cmd.current_dir(&self.path);
        cmd.args(["tag", "--list"]);
        let output = run_command(&mut cmd).await?;
        Ok(output
            .stdout
            .lines()
            .map(|line| line.trim().to_string())
            .collect())
    }

    async fn latest_tag_and_revision(
        &self,
        tag_name: &PythonFormatString,
        parse_version_regex: &regex::Regex,
    ) -> Result<TagAndRevision, Error> {
        let mut cmd = Command::new("git");
        cmd.args(["update-index", "--refresh", "-q"])
            .current_dir(&self.path);
        if let Err(err) = run_command(&mut cmd).await {
            tracing::debug!("failed to update git index: {err}");
        }

        let tag = self.latest_tag_info(tag_name, parse_version_regex).await?;
        let revision = self.revision_info().await.ok().flatten();

        Ok(TagAndRevision { tag, revision })
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        command::run_command,
        f_string::PythonFormatString,
        tests::sim_assert_eq_sorted,
        vcs::{VersionControlSystem, git, temp::EphemeralRepository},
    };
    use async_process::Command;
    use color_eyre::eyre;

    use similar_asserts::assert_eq as sim_assert_eq;

    use std::io::Write;
    use std::path::PathBuf;

    #[test]
    fn test_get_version_from_tag() -> eyre::Result<()> {
        crate::tests::init();
        let regex_pattern =
            regex::RegexBuilder::new(r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)").build()?;
        let tag_name = PythonFormatString::parse("v{new_version}")?;
        let version = super::get_version_from_tag("v2.1.4", &tag_name, &regex_pattern)?;
        sim_assert_eq!(version, Some("2.1.4"));
        Ok(())
    }

    #[ignore = "wip"]
    #[tokio::test]
    async fn test_create_empty_git_repo() -> eyre::Result<()> {
        crate::tests::init();
        let repo: EphemeralRepository<git::GitRepository> = EphemeralRepository::new().await?;
        let status = run_command(
            Command::new("git")
                .args(["status"])
                .current_dir(repo.path()),
        )
        .await?;
        assert!(status.stdout.contains("No commits yet"));
        Ok(())
    }

    #[ignore = "wip"]
    #[tokio::test]
    async fn test_tag() -> eyre::Result<()> {
        crate::tests::init();
        let repo: EphemeralRepository<git::GitRepository> = EphemeralRepository::new().await?;
        let tags = vec![
            None,
            Some(("tag1", Some("tag1 message"))),
            Some(("tag2", Some("tag2 message"))),
        ];
        // add a single file so we can commit and get a HEAD
        let initial_file = repo.path().join("README.md");
        std::fs::File::create(&initial_file)?.write_all(b"Hello, world!")?;

        repo.add(&[initial_file]).await?;
        repo.commit::<_, _, &str, &str, &str>("initial commit", [], [])
            .await?;
        similar_asserts::assert_eq!(repo.dirty_files().await?.len(), 0);

        for (_tag, _previous) in tags.iter().skip(1).zip(&tags) {
            // let latest = repo.latest_tag_info(None)?.map(|t| t.current_version);
            // let previous = previous.map(|t| t.0.to_string());
            // similar_asserts::assert_eq!(&previous, &latest);
            // if let Some((tag_name, tag_message)) = *tag {
            //     repo.tag(tag_name, tag_message, false)?;
            // }
        }
        Ok(())
    }

    #[ignore = "wip"]
    #[tokio::test]
    async fn test_dirty_tree() -> eyre::Result<()> {
        crate::tests::init();
        let repo: EphemeralRepository<git::GitRepository> = EphemeralRepository::new().await?;
        similar_asserts::assert_eq!(repo.dirty_files().await?.len(), 0);

        // add some dirty files
        let mut dirty_files: Vec<PathBuf> = ["foo.txt", "dir/bar.txt"]
            .iter()
            .map(|f| repo.path().join(f))
            .collect();

        for dirty_file in &dirty_files {
            use tokio::io::AsyncWriteExt;
            if let Some(parent) = dirty_file.parent() {
                tokio::fs::create_dir_all(parent).await?;
            }
            let file = tokio::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(dirty_file)
                .await?;
            let mut writer = tokio::io::BufWriter::new(file);
            writer.write_all(b"Hello, world!").await?;
        }
        similar_asserts::assert_eq!(repo.dirty_files().await?.len(), 0);

        // track first file
        let first_dirty_file = dirty_files
            .first()
            .ok_or_else(|| eyre::eyre!("expected at least one dirty file"))?
            .clone();
        let mut expected_first_dirty_files = vec![first_dirty_file];
        repo.add(expected_first_dirty_files.as_slice()).await?;
        let mut actual_dirty_files = repo.dirty_files().await?;
        sim_assert_eq_sorted!(actual_dirty_files, expected_first_dirty_files);

        // track all files
        repo.add(&dirty_files).await?;
        let mut actual_dirty_files = repo.dirty_files().await?;
        sim_assert_eq_sorted!(actual_dirty_files, dirty_files);
        Ok(())
    }
}