Repository: callowayproject/bump-my-version (python)

Issue:
Derive current version from git tags.
### Discussed in https://github.com/callowayproject/bump-my-version/discussions/211

<div type='discussions-op-text'>

<sup>Originally posted by **jpavlav** July 12, 2024</sup>
Hello!

First off, just want to say, thanks for forking the project and keeping it going. I've used the previous incarnations and 👍. Previously, I've used this tool only for `python` projects. Right now, I'm trying to use this tool to create a github action that is somewhat generic for bumping versions.

I thought this would be a cinch, since there is support for detecting the version from a git tag. It would prevent us from having our users include a configuration file in their repo with the version in it. However, I find that it, in the absence of the `current_version` in a config file, the tool bottoms out despite being able to detect the tagged version. Am I just missing some option here? Or is this intentional? 

Examples:

```sh
bump-my-version bump --current-version 0.4.0 --dry-run minor
KeyError: "Key 'current_version' not found at 'tool.bumpversion'"
```

Does `current_version` really need to be present in the config file if the user is specifying the version? Further, does it really need to be present if there is a tagged version available? I see that it detects that:

```sh
bump-my-version bump --current-version 1.0.0 --dry-run
  Specified version (1.0.0) does not match last tagged version (0.4.0)
```

I just wanted to ask about this before I raised an issue. I'd be unopposed to making a contribution to make this possible, but I want to make sure that I'm not stepping outside of the bounds of what is intended. Thanks!</div>

Pull request description:
Fix KeyError in TOML file handling
The code has been updated to handle KeyErrors when updating TOML files. If a KeyError is raised, it's now caught and managed depending on the file_change attributes 'ignore_missing_file' or 'ignore_missing_version'. This aims to provide more robust handling of edge cases in TOML files. In addition, a new test case has been added to ensure current version is not required in the configuration.

Fixes #212

Patch:
diff --git a/bumpversion/files.py b/bumpversion/files.py
index 92c44e40..2c1c3a7b 100644
--- a/bumpversion/files.py
+++ b/bumpversion/files.py
@@ -337,7 +337,13 @@ class DataFileUpdater:
         search_for, raw_search_pattern = self.file_change.get_search_pattern(new_context)
         replace_with = self.file_change.replace.format(**new_context)
         if self.path.suffix == ".toml":
-            self._update_toml_file(search_for, raw_search_pattern, replace_with, dry_run)
+            try:
+                self._update_toml_file(search_for, raw_search_pattern, replace_with, dry_run)
+            except KeyError as e:
+                if self.file_change.ignore_missing_file or self.file_change.ignore_missing_version:
+                    pass
+                else:
+                    raise e
 
     def _update_toml_file(
         self, search_for: re.Pattern, raw_search_pattern: str, replace_with: str, dry_run: bool = False
@@ -348,9 +354,7 @@ class DataFileUpdater:
         toml_data = tomlkit.parse(self.path.read_text(encoding="utf-8"))
         value_before = get_nested_value(toml_data, self.file_change.key_path)
 
-        if value_before is None:
-            raise KeyError(f"Key path '{self.file_change.key_path}' does not exist in {self.path}")
-        elif not contains_pattern(search_for, value_before) and not self.file_change.ignore_missing_version:
+        if not contains_pattern(search_for, value_before) and not self.file_change.ignore_missing_version:
             raise ValueError(
                 f"Key '{self.file_change.key_path}' in {self.path} does not contain the correct contents: "
                 f"{raw_search_pattern}"


Test patch:
diff --git a/tests/test_cli/test_bump.py b/tests/test_cli/test_bump.py
index 9406a39e..9d97fb0b 100644
--- a/tests/test_cli/test_bump.py
+++ b/tests/test_cli/test_bump.py
@@ -312,3 +312,37 @@ def test_dash_in_tag_matches_current_version(git_repo, runner, caplog):
         print(traceback.print_exception(result.exc_info[1]))
 
     assert result.exit_code == 0
+
+
+def test_current_version_not_required_in_config(tmp_path, fixtures_path, runner):
+    """The current version is not required in the configuration."""
+
+    config_file = tmp_path / ".bumpversion.toml"
+    config_contents = "[tool.bumpversion]\nallow_dirty = true\n\n"
+    config_file.write_text(
+        config_contents,
+        encoding="utf-8",
+    )
+
+    # Act
+    with inside_dir(tmp_path):
+        result: Result = runner.invoke(
+            cli.cli,
+            [
+                "bump",
+                "-vv",
+                "--current-version",
+                "1.0.0",
+                "--dry-run",
+                "minor",
+            ],
+        )
+
+    # Assert
+    if result.exit_code != 0:
+        print("Here is the output:")
+        print(result.output)
+        print(traceback.print_exception(result.exc_info[1]))
+
+    assert result.exit_code == 0
+    assert config_file.read_text() == config_contents