Skip to content

API Reference

This page is generated directly from the library's docstrings via mkdocstrings, so it always reflects the installed version's actual signatures and behavior rather than a hand-maintained copy that can drift out of sync with the code.

For the command-line options, see CLI Reference instead — that page is generated from the CLI's live --help output.

CLI Entry Point

bumpcalver.cli.main(beta, rc, build, release, custom, timezone, git_tag, auto_commit, undo, undo_id, list_history, bump, dry_run, config_file, json_output)

Bump this project's version and write it to every configured file.

Reads [tool.bumpcalver] from pyproject.toml (or bumpcalver.toml) for the file list and defaults; CLI flags override config values where both exist. At most one of --beta/--rc/--release/--custom may be set. Optionally creates a git tag and/or commit — or preview with --dry-run instead of writing anything. Undo a previous run with --undo, --undo-id, or --list-history (mutually exclusive with every version-bump option, including --dry-run). Pass --json for a single machine-readable JSON result on stdout instead of the log lines below.

Versioning Utilities

bumpcalver.utils.get_current_date(timezone=default_timezone, date_format='%Y.%m.%d')

Returns the current date in the specified timezone.

Falls back to default_timezone (printing a warning) if timezone isn't a recognized IANA name, rather than raising.

Parameters:

Name Type Description Default
timezone str

The IANA timezone name to use (e.g. "Europe/London").

default_timezone
date_format str

The strftime format string for the returned date.

'%Y.%m.%d'

Returns:

Name Type Description
str str

The current date formatted according to date_format.

Example

current_date = get_current_date(timezone="UTC")

bumpcalver.utils.get_current_datetime_version(timezone=default_timezone, date_format='%Y.%m.%d')

Returns the current date/time formatted as a version string.

Falls back to default_timezone (printing a warning) if timezone isn't a recognized IANA name, rather than raising. Supports the %q quarter placeholder (1-4) in date_format in addition to standard strftime codes.

Parameters:

Name Type Description Default
timezone str

The IANA timezone name to use (e.g. "Europe/London").

default_timezone
date_format str

The strftime format string; may include %q.

'%Y.%m.%d'

Returns:

Name Type Description
str str

The current date/time formatted according to date_format.

Example

version = get_current_datetime_version(timezone="UTC", date_format="%y.Q%q")

bumpcalver.utils.get_build_version(file_config, version_format, timezone, date_format, major=0, minor=0, patch=0)

Returns the build version string based on the provided file configuration.

This function reads the current version from the specified file, increments the build count if the date matches the current date, and returns the formatted build version string.

Parameters:

Name Type Description Default
file_config Dict[str, Any]

A dictionary containing file configuration details. - "path" (str): The path to the file. - "file_type" (str): The type of the file (e.g., "python", "toml", "yaml", "json", "xml", "dockerfile", "makefile"). - "variable" (str, optional): The variable name that holds the version string. - "directive" (str, optional): The directive for Dockerfile (e.g., "ARG" or "ENV").

required
version_format str

The format string for the version.

required
timezone str

The timezone to use for date calculations.

required
date_format str

The format string for the date.

required

Returns:

Name Type Description
str str

The formatted build version string.

Example

file_config = { "path": "version.py", "file_type": "python", "variable": "version" } build_version = get_build_version(file_config, "{current_date}-{build_count:03}", "America/New_York", "%Y.%m.%d")

bumpcalver.utils.parse_version(version, version_format=None, date_format=None)

Parses a version string and returns a tuple of date and count.

This function can parse version strings in various formats. If version_format and date_format are provided, it will use them to dynamically parse the version. Otherwise, it falls back to the legacy 'YYYY-MM-DD-XXX' format for backwards compatibility.

Parameters:

Name Type Description Default
version str

The version string to parse.

required
version_format str

The format string used to create the version (e.g., "{current_date}.{build_count:03}")

None
date_format str

The date format string (e.g., "%y.Q%q")

None

Returns:

Type Description
Optional[tuple]

Optional[tuple]: A tuple containing the date string and count, or None if the version string is invalid.

Examples:

version_info = parse_version("2023-10-05-001") # Legacy format version_info = parse_version("25.Q4.001", "{current_date}.{build_count:03}", "%y.Q%q") # Custom format

bumpcalver.utils.apply_prerelease_suffix(base_version, suffix_format, current_raw_version='')

Apply a pre-release suffix to base_version, honouring {xxx_count} placeholders.

If suffix_format contains no placeholder the literal string is appended. When a placeholder is present the count is derived from current_raw_version: if it starts with base_version + the suffix prefix the existing count is incremented; otherwise the count starts at 1.

bumpcalver.utils.update_semantic_in_config(key, value)

Update major/minor/patch integer in pyproject.toml or bumpcalver.toml.

bumpcalver.utils.parse_dot_path(dot_path, file_type)

Parses a dot-separated path and converts it to a file path.

This function converts a dot-separated path to a file path. If the input path is already a valid file path (contains '/' or '\' or is an absolute path), it returns the input path as is. For Python files, it ensures the path ends with '.py'.

Parameters:

Name Type Description Default
dot_path str

The dot-separated path to parse.

required
file_type str

The type of the file (e.g., "python").

required

Returns:

Name Type Description
str str

The converted file path.

Example

file_path = parse_dot_path("src.module", "python")

Configuration

bumpcalver.config.load_config(config_path=None)

Load BumpCalver's configuration.

Parameters:

Name Type Description Default
config_path Optional[str]

Explicit path to a config file (from --config-file / BUMPCALVER_CONFIG). If given, it's used as-is instead of the usual pyproject.toml/bumpcalver.toml auto-discovery in the current directory — useful for monorepo tooling or wrapper scripts invoking bumpcalver from a different directory than the target project root.

None

Git Integration

bumpcalver.git_utils.create_git_tag(version, files_to_commit, auto_commit)

Creates a Git tag and optionally commits changes.

This function checks if the specified Git tag already exists. If it does not, it creates the tag. If auto-commit is enabled, it stages the specified files and commits them before creating the tag.

Parameters:

Name Type Description Default
version str

The version string to use as the Git tag.

required
files_to_commit List[str]

A list of file paths to commit if auto-commit is enabled.

required
auto_commit bool

Whether to automatically commit changes before creating the tag.

required

Raises:

Type Description
CalledProcessError

If there is an error during Git operations.

Example

To create a Git tag and commit changes: create_git_tag("v1.0.0", ["file1.py", "file2.py"], auto_commit=True)

File Handlers

Every supported file_type (see Configuration) is backed by a VersionHandler subclass. All of them share the same read_version/update_version contract defined on the abstract base class — see the handler extension guide if you're adding support for a new file format, or distributing your handler as a plugin if you'd rather ship it as a separate installable package via the bumpcalver.handlers entry-point group.

bumpcalver.handlers.VersionHandler

Bases: ABC

Abstract base class for version handlers.

Subclasses implement read_version/update_version for one file format; see the handler extension guide for the shared helpers (_read_key_value_file, _update_key_value_file, _handle_regex_update, etc.) available for reuse.

Source code in src/bumpcalver/handlers.py
 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
class VersionHandler(ABC):
    """Abstract base class for version handlers.

    Subclasses implement `read_version`/`update_version` for one file format;
    see the [handler extension guide](development-guide.md#file-format-support)
    for the shared helpers (`_read_key_value_file`, `_update_key_value_file`,
    `_handle_regex_update`, etc.) available for reuse.
    """

    @abstractmethod
    def read_version(
        self, file_path: str, variable: str, **kwargs: Any
    ) -> Optional[str]:  # pragma: no cover
        """Reads the version string from the specified file.

        Args:
            file_path (str): The path to the file.
            variable (str): The variable name that holds the version string.
            **kwargs: Additional keyword arguments.

        Returns:
            Optional[str]: The version string if found, otherwise None.
        """

    @abstractmethod
    def update_version(
        self, file_path: str, variable: str, new_version: str, **kwargs: Any
    ) -> bool:  # pragma: no cover
        """Updates the version string in the specified file.

        Args:
            file_path (str): The path to the file.
            variable (str): The variable name that holds the version string.
            new_version (str): The new version string.
            **kwargs: Additional keyword arguments.

        Returns:
            bool: True if the version was successfully updated, otherwise False.
        """

    def format_version(self, version: str, standard: str) -> str:
        """Formats the version string according to the specified standard.

        Args:
            version (str): The version string to format.
            standard (str): The versioning standard to use (e.g., "python" for PEP 440).

        Returns:
            str: The formatted version string.
        """
        if standard == "python":
            return self.format_pep440_version(version)
        return version

    def format_pep440_version(self, version: str) -> str:
        """Formats the version string according to PEP 440.

        This method replaces hyphens and underscores with dots and ensures no leading
        zeros in numeric segments.

        Args:
            version (str): The version string to format.

        Returns:
            str: The formatted version string.
        """
        # Replace hyphens and underscores with dots
        version = version.replace("-", ".").replace("_", ".")
        # Ensure no leading zeros in numeric segments
        version = re.sub(r"\b0+(\d)", r"\1", version)
        return version

    def _read_file_safe(self, file_path: str, encoding: str = "utf-8") -> Optional[str]:
        """Safely read file content with error handling.

        Args:
            file_path (str): Path to the file to read.
            encoding (str): File encoding, defaults to utf-8.

        Returns:
            Optional[str]: File content if successful, None if error.
        """
        try:
            with open(file_path, "r", encoding=encoding) as file:
                return file.read()
        except Exception as e:
            print(f"Error reading version from {file_path}: {e}")
            return None

    def _write_file_safe(self, file_path: str, content: str, encoding: str = "utf-8") -> bool:
        """Safely write file content with error handling.

        Args:
            file_path (str): Path to the file to write.
            content (str): Content to write.
            encoding (str): File encoding, defaults to utf-8.

        Returns:
            bool: True if successful, False if error.
        """
        try:
            with open(file_path, "w", encoding=encoding) as file:
                file.write(content)
            print(f"Updated {file_path}")
            return True
        except Exception as e:
            print(f"Error updating {file_path}: {e}")
            return False

    def _format_version_with_standard(self, new_version: str, **kwargs: Any) -> str:
        """Apply version formatting based on version_standard kwarg.

        Args:
            new_version (str): The version to format.
            **kwargs: Keyword arguments containing version_standard.

        Returns:
            str: Formatted version string.
        """
        version_standard = kwargs.get("version_standard", "default")
        return self.format_version(new_version, version_standard)

    def _find_key_value_in_lines(self, lines: List[str], variable: str) -> Optional[int]:
        """Find the line index containing a key=value pair.

        Args:
            lines (List[str]): List of file lines.
            variable (str): Variable name to search for.

        Returns:
            Optional[int]: Line index if found, None otherwise.
        """
        for i, line in enumerate(lines):
            stripped_line = line.strip()
            if stripped_line and not stripped_line.startswith("#") and "=" in stripped_line:
                key, _ = stripped_line.split("=", 1)
                if key.strip() == variable:
                    return i
        return None

    def _log_variable_not_found(self, variable: str, file_path: str, prefix: str = "") -> None:
        """Log a standardized 'variable not found' message.

        Args:
            variable (str): The variable name that was not found.
            file_path (str): The file path being searched.
            prefix (str): Optional prefix for the variable description.
        """
        prefix_text = f"{prefix} " if prefix else ""
        print(f"{prefix_text}Variable '{variable}' not found in {file_path}")

    def _log_success_update(self, file_path: str, extra_info: str = "") -> None:
        """Log a standardized success message for file updates.

        Args:
            file_path (str): The file path that was updated.
            extra_info (str): Optional extra information to include.
        """
        if extra_info:
            print(f"Updated {extra_info} in {file_path}")
        else:
            print(f"Updated {file_path}")

    def _handle_regex_update(
        self,
        file_path: str,
        pattern: re.Pattern,
        replacement_func,
        new_version: str,
        variable: str,
        not_found_message: Optional[str] = None,
    ) -> bool:
        """Handle regex-based file updates with standardized error handling.

        Args:
            file_path (str): Path to the file to update.
            pattern (re.Pattern): Compiled regex pattern for matching.
            replacement_func: Function to generate replacement text.
            new_version (str): The new version string.
            variable (str): The variable name being updated.
            not_found_message (str): Custom message when variable not found.

        Returns:
            bool: True if update successful, False otherwise.
        """
        try:
            with open(file_path, "r", encoding="utf-8") as file:
                content = file.read()
        except Exception as e:
            print(f"Error updating {file_path}: {e}")
            return False

        new_content, num_subs = pattern.subn(replacement_func, content)

        if num_subs > 0:
            return self._write_file_safe(file_path, new_content)
        else:
            if not_found_message:
                print(not_found_message)
            else:
                self._log_variable_not_found(variable, file_path)
            return False

    def _update_key_value_file(
        self, file_path: str, variable: str, new_version: str, not_found_label: str = "Variable"
    ) -> bool:
        """Shared update logic for key=value line-based files (Properties, .env)."""
        try:
            with open(file_path, "r", encoding="utf-8") as file:
                lines = file.readlines()

            line_index = self._find_key_value_in_lines(lines, variable)
            if line_index is None:
                print(f"{not_found_label} '{variable}' not found in {file_path}")
                return False

            key, _ = lines[line_index].strip().split("=", 1)
            lines[line_index] = f"{key}={new_version}\n"
            with open(file_path, "w", encoding="utf-8") as file:
                file.writelines(lines)
            print(f"Updated {file_path}")
            return True
        except Exception as e:
            print(f"Error updating {file_path}: {e}")
            return False

    def _read_key_value_file(
        self, file_path: str, variable: str, strip_quotes: bool = False
    ) -> Optional[str]:
        """Shared read logic for key=value line-based files (Properties, .env).

        Args:
            file_path (str): Path to the file to read.
            variable (str): The key whose value should be returned.
            strip_quotes (bool): Strip surrounding single/double quotes from the
                value, as .env files conventionally allow (e.g. VERSION="1.0").

        Returns:
            Optional[str]: The value if the key is found, otherwise None.
        """
        try:
            with open(file_path, "r", encoding="utf-8") as file:
                for line in file:
                    line = line.strip()
                    if line and not line.startswith("#") and "=" in line:
                        key, value = line.split("=", 1)
                        if key.strip() == variable:
                            value = value.strip()
                            if strip_quotes:
                                value = value.strip("\"'")
                            return value
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
        return None

    def _handle_read_operation(
        self, file_path: str, operation_func: Callable[[], Optional[str]]
    ) -> Optional[str]:
        """Handle read operations with standardized error handling."""
        try:
            return operation_func()
        except Exception as e:
            print(f"Error reading version from {file_path}: {e}")
            return None

format_pep440_version(version)

Formats the version string according to PEP 440.

This method replaces hyphens and underscores with dots and ensures no leading zeros in numeric segments.

Parameters:

Name Type Description Default
version str

The version string to format.

required

Returns:

Name Type Description
str str

The formatted version string.

Source code in src/bumpcalver/handlers.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def format_pep440_version(self, version: str) -> str:
    """Formats the version string according to PEP 440.

    This method replaces hyphens and underscores with dots and ensures no leading
    zeros in numeric segments.

    Args:
        version (str): The version string to format.

    Returns:
        str: The formatted version string.
    """
    # Replace hyphens and underscores with dots
    version = version.replace("-", ".").replace("_", ".")
    # Ensure no leading zeros in numeric segments
    version = re.sub(r"\b0+(\d)", r"\1", version)
    return version

format_version(version, standard)

Formats the version string according to the specified standard.

Parameters:

Name Type Description Default
version str

The version string to format.

required
standard str

The versioning standard to use (e.g., "python" for PEP 440).

required

Returns:

Name Type Description
str str

The formatted version string.

Source code in src/bumpcalver/handlers.py
71
72
73
74
75
76
77
78
79
80
81
82
83
def format_version(self, version: str, standard: str) -> str:
    """Formats the version string according to the specified standard.

    Args:
        version (str): The version string to format.
        standard (str): The versioning standard to use (e.g., "python" for PEP 440).

    Returns:
        str: The formatted version string.
    """
    if standard == "python":
        return self.format_pep440_version(version)
    return version

read_version(file_path, variable, **kwargs) abstractmethod

Reads the version string from the specified file.

Parameters:

Name Type Description Default
file_path str

The path to the file.

required
variable str

The variable name that holds the version string.

required
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
Optional[str]

Optional[str]: The version string if found, otherwise None.

Source code in src/bumpcalver/handlers.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@abstractmethod
def read_version(
    self, file_path: str, variable: str, **kwargs: Any
) -> Optional[str]:  # pragma: no cover
    """Reads the version string from the specified file.

    Args:
        file_path (str): The path to the file.
        variable (str): The variable name that holds the version string.
        **kwargs: Additional keyword arguments.

    Returns:
        Optional[str]: The version string if found, otherwise None.
    """

update_version(file_path, variable, new_version, **kwargs) abstractmethod

Updates the version string in the specified file.

Parameters:

Name Type Description Default
file_path str

The path to the file.

required
variable str

The variable name that holds the version string.

required
new_version str

The new version string.

required
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
bool bool

True if the version was successfully updated, otherwise False.

Source code in src/bumpcalver/handlers.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@abstractmethod
def update_version(
    self, file_path: str, variable: str, new_version: str, **kwargs: Any
) -> bool:  # pragma: no cover
    """Updates the version string in the specified file.

    Args:
        file_path (str): The path to the file.
        variable (str): The variable name that holds the version string.
        new_version (str): The new version string.
        **kwargs: Additional keyword arguments.

    Returns:
        bool: True if the version was successfully updated, otherwise False.
    """

bumpcalver.handlers.get_version_handler(file_type)

Return a handler instance for the given file type.

Checks built-in handlers first, then third-party plugins registered via the bumpcalver.handlers entry-point group (see docs/development-guide.md) — a plugin can never override a built-in file_type.

Raises ValueError for unsupported types.

bumpcalver.handlers.available_file_types()

Return every file_type usable with get_version_handler().

Includes both built-in handlers and any discovered via the bumpcalver.handlers plugin entry-point group.

bumpcalver.handlers.update_version_in_files(new_version, file_configs)

Updates the version string in multiple files based on the provided configurations.

This function iterates over the provided file configurations, updates the version string in each file using the appropriate version handler, and returns a list of files that were successfully updated.

Parameters:

Name Type Description Default
new_version str

The new version string to set in the files.

required
file_configs List[Dict[str, Any]]

A list of dictionaries containing file configuration details. Each dictionary should have the following keys: - "path" (str): The path to the file. - "file_type" (str): The type of the file (e.g., "python", "toml", "yaml", "json", "xml", "dockerfile", "makefile", "properties", "env", "setup.cfg", "text", "regex"). - "variable" (str, optional): The variable name that holds the version string. - "directive" (str, optional): The directive for Dockerfile (e.g., "ARG" or "ENV"). - "pattern" (str, optional): Regex with one capture group, required for file_type="regex". - "version_standard" (str, optional): The versioning standard to follow (default is "default").

required

Returns:

Type Description
List[str]

List[str]: A list of file paths that were successfully updated.

Example

file_configs = [ {"path": "version.py", "file_type": "python", "variable": "version"}, {"path": "pyproject.toml", "file_type": "toml", "variable": "tool.bumpcalver.version"}, ] updated_files = update_version_in_files("2023.10.05", file_configs)

Format-specific handlers

bumpcalver.handlers.PythonVersionHandler

Bases: VersionHandler

Handler for variable = "..."-style assignments in Python files, e.g. __version__.

read_version(file_path, variable, **kwargs)

Reads variable's value from a variable = "..." (or '...') assignment.

update_version(file_path, variable, new_version, **kwargs)

Updates variable's assignment in place, preserving its quote style and surrounding whitespace.

bumpcalver.handlers.TomlVersionHandler

Bases: VersionHandler

Handler for TOML files (e.g. pyproject.toml), using tomlkit.

Uses tomlkit rather than the plain toml package so comments and formatting elsewhere in the file survive an update — toml.load/toml.dump round-trip through a plain dict and silently drop every comment, which matters since this handler's primary target commonly carries them.

read_version(file_path, variable, **kwargs)

Reads the value at variable, a dot-separated key path (e.g. "tool.project.version").

update_version(file_path, variable, new_version, **kwargs)

Updates the value at variable (a dot-separated key path) in place.

bumpcalver.handlers.YamlVersionHandler

Bases: VersionHandler

Handler for YAML files, using ruamel.yaml's round-trip mode.

Uses ruamel.yaml rather than the plain PyYAML package so comments, key order, and quote style elsewhere in the file survive an update — yaml.safe_load/yaml.safe_dump round-trip through plain dicts and silently drop every comment (and, unless sort_keys=False is passed, alphabetize every key too). Mirrors why TomlVersionHandler uses tomlkit instead of the plain toml package.

read_version(file_path, variable, **kwargs)

Reads the value at variable, a dot-separated key path (e.g. "configuration.version").

update_version(file_path, variable, new_version, **kwargs)

Updates the value at variable (a dot-separated key path) in place.

bumpcalver.handlers.JsonVersionHandler

Bases: VersionHandler

Handler for JSON files (e.g. package.json); variable is a top-level key only.

read_version(file_path, variable, **kwargs)

Reads the top-level key variable (unlike Toml/Yaml, this is a plain key, not a dot-separated path).

update_version(file_path, variable, new_version, **kwargs)

Updates the top-level key variable in place.

bumpcalver.handlers.XmlVersionHandler

Bases: VersionHandler

Handler for XML files, using xml.etree.ElementTree.

update_version preserves the <?xml ?> declaration and any comments nested inside the root element. Comments in the prolog (before the root element's opening tag) are not preserved — an ElementTree limitation (Element/ TreeBuilder model the tree from the root element down, so anything outside it is dropped on write regardless of parser options); lxml would be needed for full prolog fidelity.

read_version(file_path, variable, **kwargs)

Reads the text of the element at variable, an ElementTree find() path (e.g. "version" or "metadata/version").

update_version(file_path, variable, new_version, **kwargs)

Updates the text of the element at variable in place (see class docstring for formatting fidelity).

bumpcalver.handlers.DockerfileVersionHandler

Bases: VersionHandler

Handler for ARG/ENV directives in Dockerfiles; requires a directive kwarg.

read_version(file_path, variable, **kwargs)

Reads variable's value from an ARG/ENV line; requires directive="ARG" or "ENV" in kwargs.

update_version(file_path, variable, new_version, **kwargs)

Updates variable's ARG/ENV line in place; requires directive="ARG" or "ENV" in kwargs.

bumpcalver.handlers.MakefileVersionHandler

Bases: VersionHandler

Handler for VAR = value / VAR := value lines in Makefiles.

read_version(file_path, variable, **kwargs)

Reads the value from the first line starting with variable (e.g. VERSION = 1.0).

update_version(file_path, variable, new_version, **kwargs)

Updates variable's value in place (accepts both VAR = value and VAR := value).

bumpcalver.handlers.PropertiesVersionHandler

Bases: VersionHandler

Handler for key=value properties files (e.g. sonar-project.properties).

read_version(file_path, variable, **kwargs)

Reads the value of the variable key from a key=value line.

bumpcalver.handlers.EnvVersionHandler

Bases: VersionHandler

Handler for KEY=VALUE .env files; strips surrounding quotes on read.

read_version(file_path, variable, **kwargs)

Reads the value of the variable key from a KEY=value line, stripping surrounding quotes if present.

bumpcalver.handlers.SetupCfgVersionHandler

Bases: VersionHandler

Handler for setup.cfg's INI-style sections and key=value pairs.

read_version(file_path, variable, **kwargs)

Reads variable's value: "section.key" reads that section directly, a bare key searches all sections.

update_version(file_path, variable, new_version, **kwargs)

Updates variable's value in place; a bare key not found in any section is created under [metadata].

Generic handlers

For formats with no dedicated handler above.

bumpcalver.handlers.TextVersionHandler

Bases: VersionHandler

Handler for bare version files whose entire content is the version (e.g. a VERSION file containing just 1.2.3, as used by many shell-based release pipelines). variable is ignored — there is no key, the whole file is the value.

read_version(file_path, variable, **kwargs)

Reads the entire file, stripped of surrounding whitespace, as the version.

update_version(file_path, variable, new_version, **kwargs)

Overwrites the entire file with new_version plus a trailing newline.

bumpcalver.handlers.RegexVersionHandler

Bases: VersionHandler

Generic handler for formats with no dedicated handler (Ruby VERSION = "...", Rust const VERSION: &str = "...";, Go var Version = "...", etc.).

Driven entirely by a pattern kwarg: a regex string with exactly one capture group around the version. Set file_type = "regex" and pass pattern in the file's config, e.g. pattern = 'VERSION = "(.+?)"' for a Ruby file. variable is not used for matching — it only appears in log messages — since the pattern itself locates the version.

read_version(file_path, variable, **kwargs)

Reads the text captured by pattern's first group.

update_version(file_path, variable, new_version, **kwargs)

Replaces the text captured by pattern's first group with new_version, leaving everything else on the line untouched.

AI Assistant Instructions

See AI Assistant Instructions for the full narrative guide (what's covered, what isn't, the security contract). API reference:

bumpcalver.ai_instructions.get_app_instructions(profile='generic')

Return packaged app-side integration instructions for an AI assistant profile.

Aliases are accepted (for example: github-copilot, anthropic-claude).

bumpcalver.ai_instructions.available_instruction_profiles()

Return canonical app-integration instruction profiles bundled with the package.

bumpcalver.ai_instructions.suggested_instruction_filename(profile='generic')

Return a suggested filename for app repositories.

This is only a recommendation and is not written automatically unless the caller opts into --write / --output via the CLI.

Undo / Backup

bumpcalver.backup_utils.BackupManager

Manages file backups and operation history for undo functionality.

__init__(backup_dir=None, history_file=None)

Initialize the backup manager.

Parameters:

Name Type Description Default
backup_dir Optional[str]

Directory to store backups. If None, uses .bumpcalver/backups

None
history_file Optional[str]

Path to history file. If None, uses bumpcalver-history.json in current directory

None

cleanup_old_backups(days_to_keep=30)

Remove backup files older than specified days.

Parameters:

Name Type Description Default
days_to_keep int

Number of days of backups to retain

30

create_backup(file_path)

Create a backup of a file before modification.

Parameters:

Name Type Description Default
file_path str

Path to the file to backup

required

Returns:

Type Description
Optional[str]

Path to the backup file, or None if backup failed

get_latest_operation()

Get the most recent operation.

Returns:

Type Description
Optional[Dict[str, Any]]

The latest operation record, or None if no history exists

get_operation_history(limit=None)

Retrieve the history of version operations.

Parameters:

Name Type Description Default
limit Optional[int]

Maximum number of operations to return

None

Returns:

Type Description
List[Dict[str, Any]]

List of operation records, newest first

store_operation_history(operation_id, version, files_updated, backups, git_tag=False, git_commit=False, git_commit_hash=None, git_tag_name=None)

Store metadata about a version bump operation.

Parameters:

Name Type Description Default
operation_id str

Unique identifier for this operation

required
version str

The version that was set

required
files_updated List[str]

List of files that were updated

required
backups Dict[str, str]

Mapping of original file paths to backup file paths

required
git_tag bool

Whether a git tag was created

False
git_commit bool

Whether files were committed to git

False
git_commit_hash Optional[str]

Hash of the git commit (if created)

None
git_tag_name Optional[str]

Name of the git tag (if created)

None

bumpcalver.undo_utils.undo_last_operation(backup_manager=None)

Undo the most recent version bump operation.

Parameters:

Name Type Description Default
backup_manager Optional[BackupManager]

Optional backup manager instance

None

Returns:

Type Description
bool

True if undo was successful, False otherwise

bumpcalver.undo_utils.undo_operation_by_id(operation_id, backup_manager=None)

Undo a specific operation by its ID.

Parameters:

Name Type Description Default
operation_id str

The ID of the operation to undo

required
backup_manager Optional[BackupManager]

Optional backup manager instance

None

Returns:

Type Description
bool

True if undo was successful, False otherwise

bumpcalver.undo_utils.list_undo_history(backup_manager=None, limit=10)

List recent operations that can be undone.

Parameters:

Name Type Description Default
backup_manager Optional[BackupManager]

Optional backup manager instance

None
limit int

Maximum number of operations to display

10