Skip to content

Commit 59b2e41

Browse files
authored
Merge pull request #29 from callowayproject/28-add-short_branch_name-to-version-rendering-context
Adds `short_branch_name` to version rendering context
2 parents 9a6bbe2 + bfe5306 commit 59b2e41

File tree

5 files changed

+145
-15
lines changed

5 files changed

+145
-15
lines changed

.pre-commit-config.yaml

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
repos:
22
- repo: https://github.com/charliermarsh/ruff-pre-commit
33
# Ruff version.
4-
rev: 'v0.0.272'
4+
rev: 'v0.0.275'
55
hooks:
66
- id: ruff
77
args: [--fix, --exit-non-zero-on-fix]
@@ -39,7 +39,7 @@ repos:
3939
args: ['--baseline', '.secrets.baseline']
4040
additional_dependencies: ["gibberish-detector"]
4141
- repo: https://github.com/pre-commit/mirrors-mypy
42-
rev: v1.3.0
42+
rev: v1.4.1
4343
hooks:
4444
- id: mypy
4545
args: [--no-strict-optional, --ignore-missing-imports]
@@ -59,6 +59,6 @@ repos:
5959
- id: interrogate
6060
exclude: test.*
6161
- repo: https://github.com/python-jsonschema/check-jsonschema
62-
rev: 0.23.1
62+
rev: 0.23.2
6363
hooks:
6464
- id: check-azure-pipelines

bumpversion/scm.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
import logging
44
import os
5+
import re
56
import subprocess
67
from dataclasses import dataclass
78
from pathlib import Path
89
from tempfile import NamedTemporaryFile
9-
from typing import TYPE_CHECKING, List, MutableMapping, Optional, Type, Union
10+
from typing import TYPE_CHECKING, ClassVar, List, MutableMapping, Optional, Type, Union
1011

1112
if TYPE_CHECKING: # pragma: no-coverage
1213
from bumpversion.config import Config
@@ -25,6 +26,7 @@ class SCMInfo:
2526
distance_to_latest_tag: Optional[int] = None
2627
current_version: Optional[str] = None
2728
branch_name: Optional[str] = None
29+
short_branch_name: Optional[str] = None
2830
dirty: Optional[bool] = None
2931

3032
def __str__(self):
@@ -42,9 +44,9 @@ def __repr__(self):
4244
class SourceCodeManager:
4345
"""Base class for version control systems."""
4446

45-
_TEST_USABLE_COMMAND: List[str] = []
46-
_COMMIT_COMMAND: List[str] = []
47-
_ALL_TAGS_COMMAND: List[str] = []
47+
_TEST_USABLE_COMMAND: ClassVar[List[str]] = []
48+
_COMMIT_COMMAND: ClassVar[List[str]] = []
49+
_ALL_TAGS_COMMAND: ClassVar[List[str]] = []
4850

4951
@classmethod
5052
def commit(cls, message: str, current_version: str, new_version: str, extra_args: Optional[list] = None) -> None:
@@ -199,9 +201,9 @@ def __repr__(self):
199201
class Git(SourceCodeManager):
200202
"""Git implementation."""
201203

202-
_TEST_USABLE_COMMAND = ["git", "rev-parse", "--git-dir"]
203-
_COMMIT_COMMAND = ["git", "commit", "-F"]
204-
_ALL_TAGS_COMMAND = ["git", "tag", "--list"]
204+
_TEST_USABLE_COMMAND: ClassVar[List[str]] = ["git", "rev-parse", "--git-dir"]
205+
_COMMIT_COMMAND: ClassVar[List[str]] = ["git", "commit", "-F"]
206+
_ALL_TAGS_COMMAND: ClassVar[List[str]] = ["git", "tag", "--list"]
205207

206208
@classmethod
207209
def assert_nondirty(cls) -> None:
@@ -245,11 +247,12 @@ def latest_tag_info(cls, tag_pattern: str) -> SCMInfo:
245247
git_cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"]
246248
result = subprocess.run(git_cmd, text=True, check=True, capture_output=True) # noqa: S603
247249
branch_name = result.stdout.strip()
250+
short_branch_name = re.sub(r"([^a-zA-Z0-9]*)", "", branch_name).lower()[:20]
248251
except subprocess.CalledProcessError as e:
249252
logger.debug("Error when running git describe: %s", e.stderr)
250253
return SCMInfo(tool=cls)
251254

252-
info = SCMInfo(tool=cls, branch_name=branch_name)
255+
info = SCMInfo(tool=cls, branch_name=branch_name, short_branch_name=short_branch_name)
253256

254257
if describe_out[-1].strip() == "dirty":
255258
info.dirty = True
@@ -292,9 +295,9 @@ def tag(cls, name: str, sign: bool = False, message: Optional[str] = None) -> No
292295
class Mercurial(SourceCodeManager):
293296
"""Mercurial implementation."""
294297

295-
_TEST_USABLE_COMMAND = ["hg", "root"]
296-
_COMMIT_COMMAND = ["hg", "commit", "--logfile"]
297-
_ALL_TAGS_COMMAND = ["hg", "log", '--rev="tag()"', '--template="{tags}\n"']
298+
_TEST_USABLE_COMMAND: ClassVar[List[str]] = ["hg", "root"]
299+
_COMMIT_COMMAND: ClassVar[List[str]] = ["hg", "commit", "--logfile"]
300+
_ALL_TAGS_COMMAND: ClassVar[List[str]] = ["hg", "log", '--rev="tag()"', '--template="{tags}\n"']
298301

299302
@classmethod
300303
def latest_tag_info(cls, tag_pattern: str) -> SCMInfo:

bumpversion/version_part.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def __init__(
134134
serialize: List[str],
135135
search: str,
136136
replace: str,
137-
part_configs: Dict[str, VersionPartConfig] = None,
137+
part_configs: Optional[Dict[str, VersionPartConfig]] = None,
138138
):
139139
try:
140140
self.parse_regex = re.compile(parse, re.VERBOSE)

tests/fixtures/pep440.toml

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
[tool.bumpversion]
2+
allow_dirty = false
3+
commit = false
4+
message = "Bump version: {current_version} → {new_version}"
5+
commit_args = ""
6+
tag = false
7+
sign_tags = false
8+
tag_name = "v{new_version}"
9+
tag_message = "Bump version: {current_version} → {new_version}"
10+
current_version = "1.0.0"
11+
parse = """(?x)
12+
(?:
13+
(?P<release>
14+
(?P<major>[0-9]+)
15+
(?:
16+
\\.(?P<minor>[0-9]+)
17+
(?:
18+
\\.(?P<patch>[0-9]+)
19+
)?
20+
)?
21+
)
22+
(?P<prerelease>
23+
[-_\\.]?
24+
(?P<pre_label>a|b|rc)
25+
[-_\\.]?
26+
(?P<pre_n>[0-9]+)?
27+
)?
28+
(?P<postrelease>
29+
(?:
30+
[-_\\.]?
31+
(?P<post_label>post|rev|r)
32+
[-_\\.]?
33+
(?P<post_n>[0-9]+)?
34+
)
35+
)?
36+
(?P<dev>
37+
[-_\\.]?
38+
(?P<dev_label>dev)
39+
[-_\\.]?
40+
(?P<dev_n>[0-9]+)?
41+
)?
42+
)
43+
(?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?
44+
"""
45+
serialize = [
46+
"{major}.{minor}.{patch}.{dev_label}{distance_to_latest_tag}+{short_branch_name}",
47+
# "{major}.{minor}.{patch}{pre_label}{pre_n}",
48+
# "{major}.{minor}.{patch}+{branch_name}",
49+
"{major}.{minor}.{patch}",
50+
]
51+
search = "{current_version}"
52+
replace = "{new_version}"
53+
54+
[tool.bumpversion.parts.pre_label]
55+
values = ["final", "a", "b", "rc"]
56+
57+
[tool.bumpversion.parts.pre_n]
58+
first_value = 1
59+
60+
[tool.bumpversion.parts.post_label]
61+
values = ["final", "post"]
62+
63+
[tool.bumpversion.parts.post_n]
64+
first_value = 1
65+
66+
67+
[tool.bumpversion.parts.dev_label]
68+
values = ["final", "dev"]
69+
independent = true
70+
71+
[tool.bumpversion.parts.dev_n]
72+
first_value = 1
73+
74+
[tool.bumpversion.parts.local]
75+
independent = true

tests/test_config.py

+52
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from textwrap import dedent
66

77
import pytest
8+
from click.testing import CliRunner, Result
89
from pytest import param
910

1011
from bumpversion import config
@@ -194,3 +195,54 @@ def test_update_config_file(tmp_path: Path, cfg_file_name: str, expected_diff: s
194195
new_content = cfg_path.read_text().splitlines(keepends=True)
195196
difference = difflib.context_diff(original_content, new_content, n=0)
196197
assert "".join(difference) == expected_diff
198+
199+
200+
def test_pep440_config(git_repo: Path, fixtures_path: Path):
201+
"""
202+
Check the PEP440 config file.
203+
"""
204+
from bumpversion.utils import get_context
205+
from bumpversion.bump import get_next_version
206+
from bumpversion import cli
207+
import subprocess
208+
209+
# Arrange
210+
211+
cfg_path = git_repo / "pyproject.toml"
212+
orig_path = fixtures_path / "pep440.toml"
213+
cfg_path.write_text(orig_path.read_text())
214+
version_path = git_repo / "VERSION"
215+
version_path.write_text("1.0.0")
216+
readme_path = git_repo / "README.md"
217+
runner: CliRunner = CliRunner()
218+
219+
with inside_dir(git_repo):
220+
subprocess.run(["git", "add", "VERSION"], check=True, capture_output=True)
221+
subprocess.run(["git", "commit", "-m", "initial commit"], check=True, capture_output=True)
222+
subprocess.run(["git", "tag", "v1.0.0"], check=True, capture_output=True)
223+
224+
cfg = config.get_configuration(cfg_path)
225+
ctx = get_context(cfg)
226+
version = cfg.version_config.parse(cfg.current_version)
227+
next_version = get_next_version(version, cfg, "patch", None)
228+
next_version_str = cfg.version_config.serialize(next_version, ctx)
229+
assert next_version_str == "1.0.1"
230+
231+
subprocess.run(["git", "checkout", "-b", "my-really-LONG-branch_name"], check=True, capture_output=True)
232+
readme_path.write_text("This is my branch!")
233+
result: Result = runner.invoke(cli.cli, ["bump", "dev_label", "--no-tag"])
234+
assert result.exit_code == 0
235+
cfg = config.get_configuration(cfg_path)
236+
assert cfg.current_version == "1.0.0.dev0+myreallylongbranchna"
237+
238+
# try:
239+
# subprocess.run(["git", "add", "README.md"], check=True, capture_output=True)
240+
# subprocess.run(["git", "commit", "-am", "my branch commit"], check=True, capture_output=True)
241+
# except subprocess.CalledProcessError as e:
242+
# print(e.stdout)
243+
# print(e.stderr)
244+
# raise
245+
# result: Result = runner.invoke(cli.cli, ["bump", "dev_label", "--no-tag"])
246+
# assert result.exit_code == 0
247+
# cfg = config.get_configuration(cfg_path)
248+
# assert cfg.current_version == "1.0.0.dev1+myreallylongbranchna"

0 commit comments

Comments
 (0)