update tests for new defaults

This commit is contained in:
Manuel Barkhau 2020-10-14 22:17:18 +00:00
parent 54ab1151f1
commit 145401de33
30 changed files with 495 additions and 417 deletions

View file

@ -13,7 +13,7 @@ PACKAGE_NAME="pycalver"
GIT_REPO_NAMESPACE="mbarkhau"
GIT_REPO_DOMAIN="github.com"
PACKAGE_VERSION="v202010.1041-beta"
PACKAGE_VERSION="v2020.1041-beta"
DEFAULT_PYTHON_VERSION="python=3.8"
SUPPORTED_PYTHON_VERSIONS="python=2.7 python=3.6 python=3.8 pypy2.7 pypy3.5"

View file

@ -13,3 +13,7 @@ click
toml
lexid
colorama>=0.4
# needed pkg_resources.parse_version
setuptools<46.0.0; python_version < "3.5"
setuptools>=46.0.0; python_version >= "3.5"

View file

@ -19,7 +19,7 @@ warn_redundant_casts = True
[tool:isort]
known_first_party = pycalver
known_first_party = pycalver2
known_third_party = click,pathlib2,lexid,pkg_resources
force_single_line = True
length_sort = True
@ -89,8 +89,8 @@ addopts = --doctest-modules
[pycalver]
current_version = "v202010.1041-beta"
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
current_version = "v2020.1041-beta"
version_pattern = "vYYYY.BUILD[-TAG]"
commit_message = "bump {old_version} -> {new_version}"
commit = True
tag = True
@ -103,11 +103,11 @@ setup.cfg =
current_version = "{version}"
setup.py =
version="{pep440_version}"
src/pycalver/__init__.py =
src/pycalver2/__init__.py =
__version__ = "{version}"
src/pycalver/cli.py =
src/pycalver2/cli.py =
@click.version_option(version="{version}")
src/pycalver*/*.py =
src/pycalver2*/*.py =
Copyright (c) 2018-YYYY
LICENSE =
Copyright (c) 2018-YYYY

View file

@ -58,12 +58,12 @@ if any(arg.startswith("bdist") for arg in sys.argv):
setuptools.setup(
name="pycalver",
name="pycalver2",
license="MIT",
author="Manuel Barkhau",
author_email="mbarkhau@gmail.com",
url="https://github.com/mbarkhau/pycalver",
version="202010.1041b0",
version="2020.1041b0",
keywords="version versioning calver semver bumpversion pep440",
description="CalVer for python libraries.",
long_description=long_description,
@ -73,7 +73,7 @@ setuptools.setup(
install_requires=install_requires,
entry_points="""
[console_scripts]
pycalver=pycalver.cli:cli
calver=pycalver2.cli:cli
""",
python_requires=">=2.7",
zip_safe=True,

View file

@ -5,4 +5,4 @@
# SPDX-License-Identifier: MIT
"""PyCalVer: CalVer for Python Packages."""
__version__ = "v202010.1041-beta"
__version__ = "v2020.1041-beta"

View file

@ -39,7 +39,7 @@ except ImportError:
click.disable_unicode_literals_warning = True
logger = logging.getLogger("pycalver.cli")
logger = logging.getLogger("pycalver2.cli")
_VERBOSE = 0
@ -95,7 +95,7 @@ def _validate_release_tag(tag: typ.Optional[str]) -> None:
if tag in VALID_RELEASE_TAG_VALUES:
return
logger.error(f"Invalid argument --release={tag}")
logger.error(f"Invalid argument --tag={tag}")
logger.error(f"Valid arguments are: {', '.join(VALID_RELEASE_TAG_VALUES)}")
sys.exit(1)
@ -126,24 +126,21 @@ def _validate_flags(
def _log_no_change(subcmd: str, version_pattern: str, old_version: str) -> None:
msg = (
f"Version did not change: '{old_version}'. "
f"Invalid version and/or pattern '{version_pattern}'."
)
msg = f"Invalid version '{old_version}' and/or pattern '{version_pattern}'."
logger.error(msg)
is_semver = "{semver}" in version_pattern or (
"MAJOR" in version_pattern and "MAJOR" in version_pattern and "PATCH" in version_pattern
)
if is_semver:
logger.warning(f"pycalver {subcmd} [--major/--minor/--patch] required for use with SemVer.")
logger.warning(f"calver {subcmd} [--major/--minor/--patch] required for use with SemVer.")
else:
available_flags = [
"--" + part.lower() for part in ['MAJOR', 'MINOR', 'PATCH'] if part in version_pattern
]
if available_flags:
available_flags_str = "/".join(available_flags)
logger.info(f"Perhaps try: pycalver {subcmd} {available_flags_str} ")
logger.info(f"Perhaps try: calver {subcmd} {available_flags_str} ")
def _get_normalized_pattern(raw_pattern: str, version_pattern: typ.Optional[str]) -> str:
@ -167,37 +164,36 @@ def _get_normalized_pattern(raw_pattern: str, version_pattern: typ.Optional[str]
@click.group()
@click.version_option(version="v202010.1041-beta")
@click.version_option(version="v2020.1041-beta")
@click.help_option()
@click.option('-v', '--verbose', count=True, help="Control log level. -vv for debug level.")
def cli(verbose: int = 0) -> None:
"""Automatically update PyCalVer version strings in all project files."""
"""Automatically update CalVer version strings in plaintext files."""
if verbose:
_configure_logging(verbose=max(_VERBOSE, verbose))
@cli.command()
@click.argument("old_version")
@click.argument("pattern", default="{pycalver}")
@click.argument("pattern", default="vYYYY.BUILD[-TAG]")
@click.option('-v' , '--verbose', count=True, help="Control log level. -vv for debug level.")
@click.option(
"--release",
default=None,
metavar="<NAME>",
help=(
f"Override release name of current_version. Valid options are: "
f"{', '.join(VALID_RELEASE_TAG_VALUES)}."
),
)
@click.option("--major", is_flag=True, default=False, help="Increment major component.")
@click.option("-m" , "--minor", is_flag=True, default=False, help="Increment minor component.")
@click.option("-p" , "--patch", is_flag=True, default=False, help="Increment patch component.")
@click.option(
"-r",
"--release-num",
"--tag",
default=None,
metavar="<NAME>",
help=(
f"Override release tag of current_version. Valid options are: "
f"{', '.join(VALID_RELEASE_TAG_VALUES)}."
),
)
@click.option(
"--tag-num",
is_flag=True,
default=False,
help="Increment release number (rc1, rc2, rc3..).",
help="Increment release tag number (rc1, rc2, rc3..).",
)
@click.option("--pin-date", is_flag=True, default=False, help="Leave date components unchanged.")
@click.option(
@ -208,19 +204,18 @@ def cli(verbose: int = 0) -> None:
)
def test(
old_version: str,
pattern : str = "{pycalver}",
pattern : str = "vYYYY.BUILD[-TAG]",
verbose : int = 0,
release : str = None,
tag : str = None,
major : bool = False,
minor : bool = False,
patch : bool = False,
release_num: bool = False,
tag_num : bool = False,
pin_date : bool = False,
date : typ.Optional[str] = None,
) -> None:
"""Increment a version number for demo purposes."""
_configure_logging(verbose=max(_VERBOSE, verbose))
tag = release # use internal naming convention
_validate_release_tag(tag)
raw_pattern = pattern # use internal naming convention
@ -231,11 +226,11 @@ def test(
new_version = incr_dispatch(
old_version,
raw_pattern=raw_pattern,
tag=tag,
major=major,
minor=minor,
patch=patch,
release_num=release_num,
tag=tag,
tag_num=tag_num,
pin_date=pin_date,
date=_date,
)
@ -370,7 +365,7 @@ def show(verbose: int = 0, fetch: bool = True) -> None:
_, cfg = config.init(project_path=".")
if cfg is None:
logger.error("Could not parse configuration. Perhaps try 'pycalver init'.")
logger.error("Could not parse configuration. Perhaps try 'calver init'.")
sys.exit(1)
cfg = _update_cfg_from_vcs(cfg, fetch)
@ -432,11 +427,11 @@ def incr_dispatch(
old_version: str,
raw_pattern: str,
*,
tag : str = None,
major : bool = False,
minor : bool = False,
patch : bool = False,
release_num: bool = False,
tag : str = None,
tag_num : bool = False,
pin_date: bool = False,
date : typ.Optional[dt.date] = None,
) -> typ.Optional[str]:
@ -456,11 +451,11 @@ def incr_dispatch(
new_version = v1version.incr(
old_version,
raw_pattern=raw_pattern,
tag=tag,
major=major,
minor=minor,
patch=patch,
release_num=release_num,
tag=tag,
tag_num=tag_num,
pin_date=pin_date,
date=date,
)
@ -468,11 +463,11 @@ def incr_dispatch(
new_version = v2version.incr(
old_version,
raw_pattern=raw_pattern,
tag=tag,
major=major,
minor=minor,
patch=patch,
release_num=release_num,
tag=tag,
tag_num=tag_num,
pin_date=pin_date,
date=date,
)
@ -481,7 +476,7 @@ def incr_dispatch(
return None
elif pkg_resources.parse_version(new_version) <= pkg_resources.parse_version(old_version):
logger.error("Invariant violated: New version must be greater than old version ")
logger.error(f" Result: '{new_version}' > '{old_version}' -> False")
logger.error(f" Failed Invariant: '{new_version}' > '{old_version}'")
return None
else:
return new_version
@ -619,15 +614,6 @@ def _update_cfg_from_vcs(cfg: config.Config, fetch: bool) -> config.Config:
is_flag=True,
help="Display diff of changes, don't rewrite files.",
)
@click.option(
"--release",
default=None,
metavar="<NAME>",
help=(
f"Override release name of current_version. Valid options are: "
f"{', '.join(VALID_RELEASE_TAG_VALUES)}."
),
)
@click.option(
"--allow-dirty",
default=False,
@ -642,11 +628,20 @@ def _update_cfg_from_vcs(cfg: config.Config, fetch: bool) -> config.Config:
@click.option("-m", "--minor", is_flag=True, default=False, help="Increment minor component.")
@click.option("-p", "--patch", is_flag=True, default=False, help="Increment patch component.")
@click.option(
"-r",
"--release-num",
"-t",
"--tag",
default=None,
metavar="<NAME>",
help=(
f"Override release tag of current_version. Valid options are: "
f"{', '.join(VALID_RELEASE_TAG_VALUES)}."
),
)
@click.option(
"--tag-num",
is_flag=True,
default=False,
help="Increment release number (rc1, rc2, rc3..).",
help="Increment release tag number (rc1, rc2, rc3..).",
)
@click.option("--pin-date", is_flag=True, default=False, help="Leave date components unchanged.")
@click.option(
@ -656,7 +651,6 @@ def _update_cfg_from_vcs(cfg: config.Config, fetch: bool) -> config.Config:
help=f"Set explicit date in format YYYY-0M-0D (e.g. {_current_date}).",
)
def bump(
release : typ.Optional[str] = None,
verbose : int = 0,
dry : bool = False,
allow_dirty: bool = False,
@ -664,15 +658,14 @@ def bump(
major : bool = False,
minor : bool = False,
patch : bool = False,
release_num: bool = False,
tag : typ.Optional[str] = None,
tag_num : bool = False,
pin_date : bool = False,
date : typ.Optional[str] = None,
) -> None:
"""Increment the current version string and update project files."""
verbose = max(_VERBOSE, verbose)
_configure_logging(verbose)
tag = release # use internal naming convention
_validate_release_tag(tag)
_date = _validate_date(date, pin_date)
@ -688,11 +681,11 @@ def bump(
new_version = incr_dispatch(
old_version,
raw_pattern=cfg.version_pattern,
tag=tag,
major=major,
minor=minor,
patch=patch,
release_num=release_num,
tag=tag,
tag_num=tag_num,
pin_date=pin_date,
date=_date,
)

View file

@ -22,7 +22,7 @@ from . import v1patterns
from . import v2patterns
from .patterns import Pattern
logger = logging.getLogger("pycalver.config")
logger = logging.getLogger("pycalver2.config")
RawPatterns = typ.List[str]
RawPatternsByFile = typ.Dict[str, RawPatterns]
@ -428,7 +428,7 @@ def init(
DEFAULT_CONFIGPARSER_BASE_TMPL = """
[pycalver]
current_version = "{initial_version}"
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
version_pattern = "vYYYY.BUILD[-TAG]"
commit_message = "bump version {{old_version}} -> {{new_version}}"
commit = True
tag = True
@ -468,7 +468,7 @@ README.md =
DEFAULT_TOML_BASE_TMPL = """
[pycalver]
current_version = "{initial_version}"
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
version_pattern = "vYYYY.BUILD[-TAG]"
commit_message = "bump version {{old_version}} -> {{new_version}}"
commit = true
tag = true
@ -517,11 +517,11 @@ DEFAULT_TOML_README_MD_STR = """
def _initial_version() -> str:
return dt.datetime.now().strftime("v%Y%m.1001-alpha")
return dt.datetime.utcnow().strftime("v%Y.1001-alpha")
def _initial_version_pep440() -> str:
return dt.datetime.now().strftime("%Y%m.1001a0")
return dt.datetime.utcnow().strftime("%Y.1001a0")
def default_config(ctx: ProjectContext) -> str:

View file

@ -9,7 +9,7 @@ import textwrap
from . import pysix
logger = logging.getLogger("pycalver.regexfmt")
logger = logging.getLogger("pycalver2.regexfmt")
def format_regex(regex: str) -> str:

View file

@ -38,7 +38,7 @@ from . import utils
from .patterns import RE_PATTERN_ESCAPES
from .patterns import Pattern
logger = logging.getLogger("pycalver.v1patterns")
logger = logging.getLogger("pycalver2.v1patterns")
# https://regex101.com/r/fnj60p/10
PYCALVER_PATTERN = r"""
@ -207,17 +207,30 @@ def _compile_pattern_re(normalized_pattern: str) -> typ.Pattern[str]:
return re.compile(pattern_str)
def _normalized_pattern(version_pattern: str, raw_pattern: str) -> str:
res = raw_pattern.replace(r"{version}", version_pattern)
if version_pattern == r"{pycalver}":
res = res.replace(r"{pep440_version}", r"{pep440_pycalver}")
elif version_pattern == r"{semver}":
res = res.replace(r"{pep440_version}", r"{semver}")
elif version_pattern == r"v{year}{month}{build}{release}":
res = res.replace(r"{pep440_version}", r"{year}{month}.{BID}{pep440_tag}")
elif version_pattern == r"{year}{month}{build}{release}":
res = res.replace(r"{pep440_version}", r"{year}{month}.{BID}{pep440_tag}")
elif version_pattern == r"v{year}{build}{release}":
res = res.replace(r"{pep440_version}", r"{year}.{BID}{pep440_tag}")
elif version_pattern == r"{year}{build}{release}":
res = res.replace(r"{pep440_version}", r"{year}.{BID}{pep440_tag}")
elif r"{pep440_version}" in raw_pattern:
logger.warning(f"No mapping of '{version_pattern}' to '{{pep440_version}}'")
return res
@utils.memo
def compile_pattern(version_pattern: str, raw_pattern: typ.Optional[str] = None) -> Pattern:
_raw_pattern = version_pattern if raw_pattern is None else raw_pattern
normalized_pattern = _raw_pattern.replace(r"{version}", version_pattern)
if version_pattern == r"{pycalver}":
normalized_pattern = normalized_pattern.replace(r"{pep440_version}", r"{pep440_pycalver}")
elif version_pattern == r"{semver}":
normalized_pattern = normalized_pattern.replace(r"{pep440_version}", r"{semver}")
elif r"{pep440_version}" in _raw_pattern:
logger.warning(f"No mapping of '{version_pattern}' to '{{pep440_version}}'")
normalized_pattern = _normalized_pattern(version_pattern, _raw_pattern)
regexp = _compile_pattern_re(normalized_pattern)
return Pattern(version_pattern, normalized_pattern, regexp)

View file

@ -17,7 +17,7 @@ from . import regexfmt
from . import v1version
from .patterns import Pattern
logger = logging.getLogger("pycalver.v1rewrite")
logger = logging.getLogger("pycalver2.v1rewrite")
def rewrite_lines(

View file

@ -14,7 +14,7 @@ import lexid
from . import version
from . import v1patterns
logger = logging.getLogger("pycalver.v1version")
logger = logging.getLogger("pycalver2.v1version")
CalInfo = typ.Union[version.V1CalendarInfo, version.V1VersionInfo]
@ -97,7 +97,7 @@ def _parse_field_values(field_values: FieldValues) -> version.V1VersionInfo:
tag = fvals.get('tag')
if tag is None:
tag = "final"
tag = version.RELEASE_BY_PEP440_TAG.get(tag, tag)
tag = version.TAG_BY_PEP440_TAG.get(tag, tag)
assert tag is not None
bid = fvals['bid'] if 'bid' in fvals else "0001"
@ -351,7 +351,7 @@ def format_version(vinfo: version.V1VersionInfo, raw_pattern: str) -> str:
kwargs['pep440_tag'] = ""
else:
kwargs['release' ] = "-" + release_tag
kwargs['pep440_tag'] = version.PEP440_TAG_BY_RELEASE[release_tag] + "0"
kwargs['pep440_tag'] = version.PEP440_TAG_BY_TAG[release_tag] + "0"
kwargs['release_tag'] = release_tag
@ -381,11 +381,11 @@ def incr(
old_version: str,
raw_pattern: str = "{pycalver}",
*,
tag : typ.Optional[str] = None,
major : bool = False,
minor : bool = False,
patch : bool = False,
release_num: bool = False,
tag : typ.Optional[str] = None,
tag_num : bool = False,
pin_date: bool = False,
date : typ.Optional[dt.date] = None,
) -> typ.Optional[str]:
@ -415,8 +415,8 @@ def incr(
cur_vinfo = cur_vinfo._replace(minor=cur_vinfo.minor + 1, patch=0)
if patch:
cur_vinfo = cur_vinfo._replace(patch=cur_vinfo.patch + 1)
if release_num:
raise NotImplementedError("--release-num not supported for old style patterns")
if tag_num:
raise NotImplementedError("--tag-num not supported for old style patterns")
if tag:
cur_vinfo = cur_vinfo._replace(tag=tag)

View file

@ -5,7 +5,7 @@
# SPDX-License-Identifier: MIT
"""Compose Regular Expressions from Patterns.
>>> pattern = compile_pattern("vYYYY0M.BUILD[-RELEASE]")
>>> pattern = compile_pattern("vYYYY0M.BUILD[-TAG]")
>>> version_info = pattern.regexp.match("v201712.0123-alpha")
>>> assert version_info.groupdict() == {
... "year_y" : "2017",
@ -37,7 +37,7 @@ from . import utils
from .patterns import RE_PATTERN_ESCAPES
from .patterns import Pattern
logger = logging.getLogger("pycalver.v2patterns")
logger = logging.getLogger("pycalver2.v2patterns")
# NOTE (mb 2020-09-17): For patterns with different options '(AAA|BB|C)', the
# patterns with more digits should be first/left of those with fewer digits:
@ -83,7 +83,7 @@ PART_PATTERNS = {
'PATCH': r"[0-9]+",
'BUILD': r"[0-9]+",
'BLD' : r"[1-9][0-9]*",
'RELEASE': r"preview|final|alpha|beta|post|rc",
'TAG' : r"preview|final|alpha|beta|post|rc",
'PYTAG': r"post|rc|a|b",
'NUM' : r"[0-9]+",
'INC0' : r"[0-9]+",
@ -110,7 +110,7 @@ PATTERN_PART_FIELDS = {
'PATCH': 'patch',
'BUILD': 'bid',
'BLD' : 'bid',
'RELEASE': 'tag',
'TAG' : 'tag',
'PYTAG': 'pytag',
'NUM' : 'num',
'INC0' : 'inc0',
@ -132,7 +132,7 @@ PEP440_PART_SUBSTITUTIONS = {
'0D' : "DD",
'00J' : "JJJ",
'BUILD': "BLD",
'RELEASE': "PYTAG",
'TAG' : "PYTAG",
}
@ -209,7 +209,7 @@ PART_FORMATS: typ.Dict[str, FormatterFunc] = {
'PATCH': _fmt_num,
'BUILD': _fmt_num,
'BLD' : _fmt_bld,
'RELEASE': _fmt_num,
'TAG' : _fmt_num,
'PYTAG': _fmt_num,
'NUM' : _fmt_num,
'INC0' : _fmt_num,
@ -249,7 +249,7 @@ def _convert_to_pep440(version_pattern: str) -> str:
substitution = PEP440_PART_SUBSTITUTIONS[part_name]
is_numerical_part = part_name not in ('RELEASE', 'PYTAG')
is_numerical_part = part_name not in ('TAG', 'PYTAG')
if is_numerical_part:
part_index = pep440_pattern.find(part_name)
is_zero_truncation_part = part_index == 0 or pep440_pattern[part_index - 1] == "."
@ -321,7 +321,7 @@ def _replace_pattern_parts(pattern: str) -> str:
def _compile_pattern_re(normalized_pattern: str) -> typ.Pattern[str]:
escaped_pattern = normalized_pattern
for char, escaped in RE_PATTERN_ESCAPES:
# [] braces are used for optional parts, such as [-RELEASE]/[-beta]
# [] braces are used for optional parts, such as [-TAG]/[-beta]
# and need to be escaped manually.
is_semantic_char = char in "[]\\"
if not is_semantic_char:

View file

@ -18,7 +18,7 @@ from . import v2version
from . import v2patterns
from .patterns import Pattern
logger = logging.getLogger("pycalver.v2rewrite")
logger = logging.getLogger("pycalver2.v2rewrite")
def rewrite_lines(
@ -65,9 +65,9 @@ def rfd_from_content(
r"""Rewrite pattern occurrences with version string.
>>> from .v2patterns import compile_pattern
>>> version_pattern = "vYYYY0M.BUILD[-RELEASE]"
>>> version_pattern = "vYYYY0M.BUILD[-TAG]"
>>> new_vinfo = v2version.parse_version_info("v201809.0123", version_pattern)
>>> patterns = [compile_pattern(version_pattern, '__version__ = "vYYYY0M.BUILD[-RELEASE]"')]
>>> patterns = [compile_pattern(version_pattern, '__version__ = "vYYYY0M.BUILD[-TAG]"')]
>>> content = '__version__ = "v201809.0001-alpha"'
>>> rfd = rfd_from_content(patterns, new_vinfo, content)
>>> rfd.new_lines

View file

@ -14,7 +14,7 @@ import lexid
from . import version
from . import v2patterns
logger = logging.getLogger("pycalver.v2version")
logger = logging.getLogger("pycalver2.v2version")
CalInfo = typ.Union[version.V2CalendarInfo, version.V2VersionInfo]
@ -218,9 +218,9 @@ def parse_field_values_to_vinfo(field_values: FieldValues) -> version.V2VersionI
pytag = fvals.get('pytag') or ""
if tag and not pytag:
pytag = version.PEP440_TAG_BY_RELEASE[tag]
pytag = version.PEP440_TAG_BY_TAG[tag]
elif pytag and not tag:
tag = version.RELEASE_BY_PEP440_TAG[pytag]
tag = version.TAG_BY_PEP440_TAG[pytag]
if not tag:
tag = "final"
@ -257,15 +257,15 @@ def parse_field_values_to_vinfo(field_values: FieldValues) -> version.V2VersionI
def parse_version_info(
version_str: str, raw_pattern: str = "vYYYY0M.BUILD[-RELEASE]"
version_str: str, raw_pattern: str = "vYYYY0M.BUILD[-TAG]"
) -> version.V2VersionInfo:
"""Parse normalized V2VersionInfo.
>>> vinfo = parse_version_info("v201712.0033-beta", raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> vinfo = parse_version_info("v201712.0033-beta", raw_pattern="vYYYY0M.BUILD[-TAG]")
>>> fvals = {'year_y': 2017, 'month': 12, 'bid': "0033", 'tag': "beta"}
>>> assert vinfo == parse_field_values_to_vinfo(fvals)
>>> vinfo = parse_version_info("v201712.0033", raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> vinfo = parse_version_info("v201712.0033", raw_pattern="vYYYY0M.BUILD[-TAG]")
>>> fvals = {'year_y': 2017, 'month': 12, 'bid': "0033"}
>>> assert vinfo == parse_field_values_to_vinfo(fvals)
@ -296,10 +296,10 @@ def parse_version_info(
return parse_field_values_to_vinfo(field_values)
def is_valid(version_str: str, raw_pattern: str = "vYYYY0M.BUILD[-RELEASE]") -> bool:
def is_valid(version_str: str, raw_pattern: str = "vYYYY.BUILD[-TAG]") -> bool:
"""Check if a version matches a pattern.
>>> is_valid("v201712.0033-beta", raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> is_valid("v201712.0033-beta", raw_pattern="vYYYY0M.BUILD[-TAG]")
True
>>> is_valid("v201712.0033-beta", raw_pattern="MAJOR.MINOR.PATCH")
False
@ -327,9 +327,9 @@ def _format_part_values(vinfo: version.V2VersionInfo) -> PartValues:
It may for example have month=9, but not the formatted
representation '09' for '0M'.
>>> vinfo = parse_version_info("v200709.1033-beta", raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> vinfo = parse_version_info("v200709.1033-beta", raw_pattern="vYYYY0M.BUILD[-TAG]")
>>> kwargs = dict(_format_part_values(vinfo))
>>> (kwargs['YYYY'], kwargs['0M'], kwargs['BUILD'], kwargs['RELEASE'])
>>> (kwargs['YYYY'], kwargs['0M'], kwargs['BUILD'], kwargs['TAG'])
('2007', '09', '1033', 'beta')
>>> (kwargs['YY'], kwargs['0Y'], kwargs['MM'], kwargs['PYTAG'])
('7', '07', '9', 'b')
@ -472,7 +472,7 @@ def format_version(vinfo: version.V2VersionInfo, raw_pattern: str) -> str:
"""Generate version string.
>>> import datetime as dt
>>> vinfo = parse_version_info("v200712.0033-beta", raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> vinfo = parse_version_info("v200712.0033-beta", raw_pattern="vYYYY0M.BUILD[-TAG]")
>>> vinfo_a = vinfo._replace(**cal_info(date=dt.date(2007, 1, 1))._asdict())
>>> vinfo_b = vinfo._replace(**cal_info(date=dt.date(2007, 12, 31))._asdict())
@ -483,63 +483,63 @@ def format_version(vinfo: version.V2VersionInfo, raw_pattern: str) -> str:
'v7.33-b0'
>>> format_version(vinfo_a, raw_pattern="YYYY0M.BUILD[PYTAG[NUM]]")
'200701.0033b'
>>> format_version(vinfo_a, raw_pattern="v0Y.BLD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="v0Y.BLD[-TAG]")
'v07.33-beta'
>>> format_version(vinfo_a, raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vYYYY0M.BUILD[-TAG]")
'v200701.0033-beta'
>>> format_version(vinfo_b, raw_pattern="vYYYY0M.BUILD[-RELEASE]")
>>> format_version(vinfo_b, raw_pattern="vYYYY0M.BUILD[-TAG]")
'v200712.0033-beta'
>>> format_version(vinfo_a, raw_pattern="vYYYYw0W.BUILD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vYYYYw0W.BUILD[-TAG]")
'v2007w01.0033-beta'
>>> format_version(vinfo_a, raw_pattern="vYYYYwWW.BLD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vYYYYwWW.BLD[-TAG]")
'v2007w1.33-beta'
>>> format_version(vinfo_b, raw_pattern="vYYYYw0W.BUILD[-RELEASE]")
>>> format_version(vinfo_b, raw_pattern="vYYYYw0W.BUILD[-TAG]")
'v2007w53.0033-beta'
>>> format_version(vinfo_a, raw_pattern="vYYYYd00J.BUILD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vYYYYd00J.BUILD[-TAG]")
'v2007d001.0033-beta'
>>> format_version(vinfo_a, raw_pattern="vYYYYdJJJ.BUILD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vYYYYdJJJ.BUILD[-TAG]")
'v2007d1.0033-beta'
>>> format_version(vinfo_b, raw_pattern="vYYYYd00J.BUILD[-RELEASE]")
>>> format_version(vinfo_b, raw_pattern="vYYYYd00J.BUILD[-TAG]")
'v2007d365.0033-beta'
>>> format_version(vinfo_a, raw_pattern="vGGGGwVV.BLD[PYTAGNUM]")
'v2007w1.33b0'
>>> format_version(vinfo_a, raw_pattern="vGGGGw0V.BUILD[-RELEASE]")
>>> format_version(vinfo_a, raw_pattern="vGGGGw0V.BUILD[-TAG]")
'v2007w01.0033-beta'
>>> format_version(vinfo_b, raw_pattern="vGGGGw0V.BUILD[-RELEASE]")
>>> format_version(vinfo_b, raw_pattern="vGGGGw0V.BUILD[-TAG]")
'v2008w01.0033-beta'
>>> vinfo_c = vinfo_b._replace(major=1, minor=2, patch=34, tag='final')
>>> format_version(vinfo_c, raw_pattern="vYYYYwWW.BUILD-RELEASE")
>>> format_version(vinfo_c, raw_pattern="vYYYYwWW.BUILD-TAG")
'v2007w53.0033-final'
>>> format_version(vinfo_c, raw_pattern="vYYYYwWW.BUILD[-RELEASE]")
>>> format_version(vinfo_c, raw_pattern="vYYYYwWW.BUILD[-TAG]")
'v2007w53.0033'
>>> format_version(vinfo_c, raw_pattern="vMAJOR.MINOR.PATCH")
'v1.2.34'
>>> vinfo_d = vinfo_b._replace(major=1, minor=0, patch=0, tag='final')
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-RELEASENUM")
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-TAGNUM")
'v1.0.0-final0'
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-RELEASE")
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-TAG")
'v1.0.0-final'
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-RELEASE")
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH-TAG")
'v1.0.0-final'
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH[-RELEASE]")
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR.PATCH[-TAG]")
'v1.0.0'
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR[.PATCH[-RELEASE]]")
>>> format_version(vinfo_d, raw_pattern="vMAJOR.MINOR[.PATCH[-TAG]]")
'v1.0'
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-RELEASE]]]")
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-TAG]]]")
'v1'
>>> vinfo_d = vinfo_b._replace(major=1, minor=0, patch=2, tag='rc', pytag='rc', num=0)
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH]]")
'v1.0.2'
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-RELEASE]]]")
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-TAG]]]")
'v1.0.2-rc'
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[PYTAGNUM]]]")
'v1.0.2rc0'
@ -547,11 +547,11 @@ def format_version(vinfo: version.V2VersionInfo, raw_pattern: str) -> str:
'v1.0.2'
>>> vinfo_d = vinfo_b._replace(major=1, minor=0, patch=0, tag='rc', num=2)
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-RELEASENUM]]]")
>>> format_version(vinfo_d, raw_pattern="vMAJOR[.MINOR[.PATCH[-TAGNUM]]]")
'v1.0.0-rc2'
>>> vinfo_d = vinfo_b._replace(major=1, minor=0, patch=0, tag='rc', num=2)
>>> format_version(vinfo_d, raw_pattern='__version__ = "vMAJOR[.MINOR[.PATCH[-RELEASENUM]]]"')
>>> format_version(vinfo_d, raw_pattern='__version__ = "vMAJOR[.MINOR[.PATCH[-TAGNUM]]]"')
'__version__ = "v1.0.0-rc2"'
"""
part_values = _format_part_values(vinfo)
@ -615,7 +615,7 @@ def _incr_numeric(
minor : bool,
patch : bool,
tag : typ.Optional[str],
release_num: bool,
tag_num : bool,
) -> version.V2VersionInfo:
# Reset major/minor/patch/num/inc to zero if any part to the left of it is incremented
fields = _parse_pattern_fields(raw_pattern)
@ -647,7 +647,7 @@ def _incr_numeric(
cur_vinfo = cur_vinfo._replace(minor=cur_vinfo.minor + 1, patch=0)
if patch and 'patch' not in reset_fields:
cur_vinfo = cur_vinfo._replace(patch=cur_vinfo.patch + 1)
if release_num and 'release_num' not in reset_fields:
if tag_num and 'tag_num' not in reset_fields:
cur_vinfo = cur_vinfo._replace(num=cur_vinfo.num + 1)
if tag and 'tag' not in reset_fields:
if tag != cur_vinfo.tag:
@ -677,13 +677,13 @@ def is_valid_week_pattern(raw_pattern: str) -> bool:
def incr(
old_version: str,
raw_pattern: str = "vYYYY0M.BUILD[-RELEASE]",
raw_pattern: str = "vYYYY0M.BUILD[-TAG]",
*,
tag : typ.Optional[str] = None,
major : bool = False,
minor : bool = False,
patch : bool = False,
release_num: bool = False,
tag : typ.Optional[str] = None,
tag_num : bool = False,
pin_date: bool = False,
date : typ.Optional[dt.date] = None,
) -> typ.Optional[str]:
@ -716,7 +716,7 @@ def incr(
minor=minor,
patch=patch,
tag=tag,
release_num=release_num,
tag_num=tag_num,
)
new_version = format_version(cur_vinfo, raw_pattern)

View file

@ -24,7 +24,7 @@ import subprocess as sp
from pycalver import config
logger = logging.getLogger("pycalver.vcs")
logger = logging.getLogger("pycalver2.vcs")
VCS_SUBCOMMANDS_BY_NAME = {

View file

@ -81,7 +81,7 @@ class V2VersionInfo(typ.NamedTuple):
TODAY = dt.datetime.utcnow().date()
RELEASE_BY_PEP440_TAG = {
TAG_BY_PEP440_TAG = {
'a' : 'alpha',
'b' : 'beta',
'' : 'final',
@ -91,7 +91,7 @@ RELEASE_BY_PEP440_TAG = {
}
PEP440_TAG_BY_RELEASE = {
PEP440_TAG_BY_TAG = {
'a' : 'a',
'b' : 'b',
'dev' : 'dev',
@ -107,15 +107,15 @@ PEP440_TAG_BY_RELEASE = {
'rev' : 'post',
}
assert set(RELEASE_BY_PEP440_TAG.keys()) == set(PEP440_TAG_BY_RELEASE.values())
assert set(RELEASE_BY_PEP440_TAG.values()) < set(PEP440_TAG_BY_RELEASE.keys())
assert set(TAG_BY_PEP440_TAG.keys()) == set(PEP440_TAG_BY_TAG.values())
assert set(TAG_BY_PEP440_TAG.values()) < set(PEP440_TAG_BY_TAG.keys())
PART_ZERO_VALUES = {
'MAJOR': "0",
'MINOR': "0",
'PATCH': "0",
'RELEASE': "final",
'TAG' : "final",
'PYTAG': "",
'NUM' : "0",
'INC0' : "0",

View file

@ -1,3 +1,3 @@
# PyCalVer README Fixture
Current Version: v201612.0123-alpha
Current Version: v2016.0123-alpha

View file

@ -1,5 +1,6 @@
[pycalver]
current_version = "v201710.0123-alpha"
current_version = "v2017.0123-alpha"
version_pattern = "vYYYY.BUILD[-TAG]"
commit = true
tag = true
push = true

View file

@ -17,17 +17,20 @@ import pytest
import pathlib2 as pl
from click.testing import CliRunner
from pycalver import cli
from pycalver import config
from pycalver import v1patterns
from pycalver2 import cli
from pycalver2 import config
from pycalver2 import v2patterns
# pylint:disable=redefined-outer-name ; pytest fixtures
# pylint:disable=protected-access ; allowed for test code
# pylint:disable=unused-argument ; allowed for test code
README_TEXT_FIXTURE = """
Hello World v201701.1002-alpha !
[aka. 201701.1002a0 !]
Hello World v2017.1002-alpha !
[aka. 2017.1002a0 !]
Hello World v201707.1002-alpha !
[aka. 201707.1002a0 !]
"""
@ -61,6 +64,16 @@ def shell(*cmd):
return sp.check_output(cmd, env=ENV)
DEBUG_LOG = 0
def _debug_records(caplog):
if DEBUG_LOG:
print()
for record in caplog.records:
print(record)
@pytest.fixture
def runner(tmpdir):
runner = CliRunner(env=ENV)
@ -87,7 +100,7 @@ def runner(tmpdir):
def test_help(runner):
result = runner.invoke(cli.cli, ['--help', "-vv"])
assert result.exit_code == 0
assert "PyCalVer" in result.output
assert "CalVer" in result.output
assert "bump " in result.output
assert "test " in result.output
assert "init " in result.output
@ -98,29 +111,37 @@ def test_version(runner):
result = runner.invoke(cli.cli, ['--version', "-vv"])
assert result.exit_code == 0
assert " version v20" in result.output
match = v1patterns.PYCALVER_RE.search(result.output)
pattern = v2patterns.compile_pattern("vYYYY.BUILD[-TAG]")
match = pattern.regexp.search(result.output)
assert match
def test_incr_default(runner):
old_version = "v201701.0004-alpha"
old_version = "v201709.1004-alpha"
cmd = ['test', "-vv", "--pin-date", "--release", "beta", old_version]
cmd = ['test', "-vv", "--pin-date", "--tag", "beta", old_version, "{pycalver}"]
result = runner.invoke(cli.cli, cmd)
assert result.exit_code == 0
assert "Version: v201701.0005-beta\n" in result.output
assert "Version: v201709.1005-beta\n" in result.output
cmd = ['test', "-vv", "--pin-date", "--release", "beta", old_version, "vYYYY0M.BUILD[-RELEASE]"]
old_version = "v2017.1004-alpha"
cmd = ['test', "-vv", "--pin-date", "--tag", "beta", old_version, "v{year}{build}{release}"]
result = runner.invoke(cli.cli, cmd)
assert result.exit_code == 0
assert "Version: v201701.1005-beta\n" in result.output
assert "Version: v2017.1005-beta\n" in result.output
cmd = ['test', "-vv", "--pin-date", "--tag", "beta", old_version, "vYYYY.BUILD[-TAG]"]
result = runner.invoke(cli.cli, cmd)
assert result.exit_code == 0
assert "Version: v2017.1005-beta\n" in result.output
def test_incr_pin_date(runner):
old_version = "v201701.0999-alpha"
old_version = "v2017.1999-alpha"
result = runner.invoke(cli.cli, ['test', "-vv", "--pin-date", old_version])
assert result.exit_code == 0
assert "Version: v201701.11000-alpha\n" in result.output
assert "Version: v2017.22000-alpha\n" in result.output
def test_incr_semver(runner):
@ -158,27 +179,28 @@ def test_incr_semver_invalid(runner, caplog):
assert result.exit_code == 1
assert len(caplog.records) > 0
log_record = caplog.records[0]
assert "Invalid version string" in log_record.message
assert "for pattern '{pycalver}'" in log_record.message
assert "--patch is not applicable to pattern" in log_record.message
assert "to pattern 'vYYYY.BUILD[-TAG]'" in log_record.message
def test_incr_to_beta(runner):
old_version = "v201701.0999-alpha"
old_version = "v2017.1999-alpha"
initial_version = config._initial_version()
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--release", "beta"])
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--tag", "beta"])
assert result.exit_code == 0
new_version = initial_version.replace(".1001-alpha", ".11000-beta")
new_version = initial_version.replace(".1001-alpha", ".22000-beta")
assert f"Version: {new_version}\n" in result.output
def test_incr_to_final(runner):
old_version = "v201701.0999-alpha"
def test_incr_to_final(runner, caplog):
old_version = "v2017.1999-alpha"
initial_version = config._initial_version()
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--release", "final"])
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--tag", "final"])
_debug_records(caplog)
assert result.exit_code == 0
new_version = initial_version.replace(".1001-alpha", ".11000")
new_version = initial_version.replace(".1001-alpha", ".22000")
assert f"Version: {new_version}\n" in result.output
@ -188,15 +210,15 @@ def test_incr_release_num(runner):
old_version = "0.1.0b0"
new_version = "0.1.0b1"
result = runner.invoke(cli.cli, ['test', "-vv", "--release-num", old_version, semver])
result = runner.invoke(cli.cli, ['test', "-vv", "--tag-num", old_version, semver])
assert result.exit_code == 0
assert f"Version: {new_version}\n" in result.output
def test_incr_invalid(runner):
old_version = "v201701.0999-alpha"
old_version = "v2017.1999-alpha"
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--release", "alfa"])
result = runner.invoke(cli.cli, ['test', old_version, "-vv", "--tag", "alfa"])
assert result.exit_code == 1
@ -238,7 +260,7 @@ def test_nocfg(runner, caplog):
_add_project_files("README.md")
result = runner.invoke(cli.cli, ['show', "-vv"])
assert result.exit_code == 1
expected_msg = "Could not parse configuration. Perhaps try 'pycalver init'."
expected_msg = "Could not parse configuration. Perhaps try 'calver init'."
assert any(expected_msg in r.message for r in caplog.records)
@ -326,46 +348,57 @@ def _vcs_init(vcs, files=("README.md",)):
shell(f"{vcs}", "commit", "-m", "initial commit")
_today = dt.datetime.utcnow().date()
DEFAULT_VERSION_PATTERNS = [
'"{pycalver}"',
'"vYYYY0M.BUILD[-RELEASE]"',
('"vYYYY0M.BUILD[-TAG]"' , _today.strftime("v%Y%m.1001-alpha"), _today.strftime("%Y%m.1001a0")),
('"vYYYY.BUILD[-TAG]"' , _today.strftime("v%Y.1001-alpha"), _today.strftime("%Y.1001a0")),
('"{pycalver}"' , _today.strftime("v%Y%m.1001-alpha"), _today.strftime("%Y%m.1001a0")),
('"v{year}{build}{release}"', _today.strftime("v%Y.1001-alpha"), _today.strftime("%Y.1001a0")),
]
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_git_init(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_git_init(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("git")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
result = runner.invoke(cli.cli, ['show'])
assert result.exit_code == 0
assert f"Current Version: {config._initial_version()}\n" in result.output
assert f"PEP440 : {config._initial_version_pep440()}\n" in result.output
assert f"Current Version: {cur_version}\n" in result.output
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_hg_init(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_hg_init(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("hg")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
result = runner.invoke(cli.cli, ['show'])
assert result.exit_code == 0
assert f"Current Version: {config._initial_version()}\n" in result.output
assert f"PEP440 : {config._initial_version_pep440()}\n" in result.output
assert f"Current Version: {cur_version}\n" in result.output
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_v1_git_tag_eval(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_v1_git_tag_eval(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("git")
@ -374,22 +407,24 @@ def test_v1_git_tag_eval(runner, version_pattern):
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
initial_version = config._initial_version()
tag_version = initial_version.replace(".1001-alpha", ".1123-beta")
tag_version_pep440 = tag_version[1:7] + ".1123b0"
tag_version = cur_version.replace(".1001-alpha", ".1123-beta")
assert tag_version != cur_version
shell("git", "tag", "--annotate", tag_version, "--message", f"bump version to {tag_version}")
result = runner.invoke(cli.cli, ['show', "-vv"])
assert result.exit_code == 0
assert f"Current Version: {tag_version}\n" in result.output
assert f"PEP440 : {tag_version_pep440}\n" in result.output
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_hg_tag_eval(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_hg_tag_eval(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("hg")
@ -398,11 +433,14 @@ def test_hg_tag_eval(runner, version_pattern):
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
initial_version = config._initial_version()
tag_version = initial_version.replace(".1001-alpha", ".1123-beta")
tag_version_pep440 = tag_version[1:7] + ".1123b0"
tag_version = cur_version.replace(".1001-alpha", ".1123-beta")
tag_version_pep440 = tag_version[1:].split(".")[0] + ".1123b0"
shell("hg", "tag", tag_version, "--message", f"bump version to {tag_version}")
@ -412,26 +450,33 @@ def test_hg_tag_eval(runner, version_pattern):
assert f"PEP440 : {tag_version_pep440}\n" in result.output
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_novcs_bump(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_novcs_bump(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
with pl.Path("README.md").open(mode="r") as fobj:
content = fobj.read()
result = runner.invoke(cli.cli, ['bump', "-vv"])
assert result.exit_code == 0
calver = config._initial_version().split(".")[0]
calver = cur_version.split(".")[0]
with pl.Path("README.md").open() as fobj:
content = fobj.read()
assert calver + ".1002-alpha !\n" in content
assert calver[1:] + ".1002a0 !]\n" in content
result = runner.invoke(cli.cli, ['bump', "-vv", "--release", "beta"])
result = runner.invoke(cli.cli, ['bump', "-vv", "--tag", "beta"])
assert result.exit_code == 0
with pl.Path("README.md").open() as fobj:
@ -440,38 +485,47 @@ def test_novcs_bump(runner, version_pattern):
assert calver[1:] + ".1003b0 !]\n" in content
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_git_bump(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_git_bump(runner, caplog, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("git")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
shell("git", "add", "pycalver.toml")
shell("git", "commit", "-m", "initial commit")
result = runner.invoke(cli.cli, ['bump', "-vv"])
_debug_records(caplog)
assert result.exit_code == 0
calver = config._initial_version()[:7]
calver = cur_version.split(".")[0]
with pl.Path("README.md").open() as fobj:
content = fobj.read()
assert calver + ".1002-alpha !\n" in content
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_hg_bump(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_hg_bump(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md")
_vcs_init("hg")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("pycalver.toml", version_pattern=version_pattern)
_update_config_val(
"pycalver.toml",
version_pattern=version_pattern,
current_version='"' + cur_version + '"',
)
shell("hg", "add", "pycalver.toml")
shell("hg", "commit", "-m", "initial commit")
@ -479,7 +533,7 @@ def test_hg_bump(runner, version_pattern):
result = runner.invoke(cli.cli, ['bump', "-vv"])
assert result.exit_code == 0
calver = config._initial_version()[:7]
calver = cur_version.split(".")[0]
with pl.Path("README.md").open() as fobj:
content = fobj.read()
@ -490,6 +544,7 @@ def test_empty_git_bump(runner, caplog):
shell("git", "init")
with pl.Path("setup.cfg").open(mode="w") as fobj:
fobj.write("")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
@ -511,6 +566,7 @@ def test_empty_hg_bump(runner, caplog):
shell("hg", "init")
with pl.Path("setup.cfg").open(mode="w") as fobj:
fobj.write("")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
@ -597,27 +653,38 @@ def test_v1_bump_semver_diff(runner, caplog, version_pattern):
assert f"+current_version = \"{expected}\"" in out_lines
@pytest.mark.parametrize("version_pattern", DEFAULT_VERSION_PATTERNS)
def test_get_diff(runner, version_pattern):
@pytest.mark.parametrize("version_pattern, cur_version, cur_pep440", DEFAULT_VERSION_PATTERNS)
def test_get_diff(runner, version_pattern, cur_version, cur_pep440):
_add_project_files("README.md", "setup.cfg")
result = runner.invoke(cli.cli, ['init', "-vv"])
assert result.exit_code == 0
_update_config_val("setup.cfg", version_pattern=version_pattern)
if len(cur_pep440) == 11:
old_version = "v2017.1002-alpha"
old_pep440 = "2017.1002a0"
elif len(cur_pep440) == 13:
old_version = "v201707.1002-alpha"
old_pep440 = "201707.1002a0"
else:
assert False, len(cur_pep440)
_update_config_val(
"setup.cfg",
version_pattern=version_pattern,
current_version='"' + old_version + '"',
)
_, cfg = config.init()
new_version = "v202010.1003-beta"
diff_str = cli.get_diff(cfg, new_version)
diff_str = cli.get_diff(cfg, cur_version)
diff_lines = set(diff_str.splitlines())
assert "- Hello World v201701.1002-alpha !" in diff_lines
assert "- [aka. 201701.1002a0 !]" in diff_lines
assert "+ Hello World v202010.1003-beta !" in diff_lines
assert "+ [aka. 202010.1003b0 !]" in diff_lines
assert f"- Hello World {old_version} !" in diff_lines
assert f"+ Hello World {cur_version} !" in diff_lines
assert '-current_version = "v202010.1001-alpha"' in diff_lines
assert '+current_version = "v202010.1003-beta"' in diff_lines
assert f"- [aka. {old_pep440} !]" in diff_lines
assert f"+ [aka. {cur_pep440} !]" in diff_lines
assert f'-current_version = "{old_version}"' in diff_lines
assert f'+current_version = "{cur_version}"' in diff_lines
WEEKNUM_TEST_CASES = [
@ -680,21 +747,21 @@ def test_hg_commit_message(runner, caplog):
commit_message = """
"bump from {old_version} ({old_version_pep440}) to {new_version} ({new_version_pep440})"
"""
_update_config_val("setup.cfg", current_version='"v201903.1001-alpha"')
_update_config_val("setup.cfg", current_version='"v2019.1001-alpha"')
_update_config_val("setup.cfg", commit_message=commit_message.strip())
_vcs_init("hg", ["README.md", "setup.cfg"])
assert len(caplog.records) > 0
result = runner.invoke(cli.cli, ['bump', "-vv", "--pin-date", "--release", "beta"])
result = runner.invoke(cli.cli, ['bump', "-vv", "--pin-date", "--tag", "beta"])
assert result.exit_code == 0
tags = shell("hg", "tags").decode("utf-8")
assert "v201903.1002-beta" in tags
assert "v2019.1002-beta" in tags
commits = shell(*shlex.split("hg log -l 2")).decode("utf-8").split("\n\n")
expected = "bump from v201903.1001-alpha (201903.1001a0) to v201903.1002-beta (201903.1002b0)"
expected = "bump from v2019.1001-alpha (2019.1001a0) to v2019.1002-beta (2019.1002b0)"
summary = commits[1].split("summary:")[-1]
assert expected in summary
@ -707,37 +774,36 @@ def test_git_commit_message(runner, caplog):
commit_message = """
"bump: {old_version} ({old_version_pep440}) -> {new_version} ({new_version_pep440})"
"""
_update_config_val("setup.cfg", current_version='"v201903.1001-alpha"')
_update_config_val("setup.cfg", current_version='"v2019.1001-alpha"')
_update_config_val("setup.cfg", commit_message=commit_message.strip())
_vcs_init("git", ["README.md", "setup.cfg"])
assert len(caplog.records) > 0
result = runner.invoke(cli.cli, ['bump', "-vv", "--pin-date", "--release", "beta"])
result = runner.invoke(cli.cli, ['bump', "-vv", "--pin-date", "--tag", "beta"])
assert result.exit_code == 0
tags = shell("git", "tag", "--list").decode("utf-8")
assert "v201903.1002-beta" in tags
assert "v2019.1002-beta" in tags
commits = shell(*shlex.split("git log -l 2")).decode("utf-8").split("\n\n")
expected = "bump: v201903.1001-alpha (201903.1001a0) -> v201903.1002-beta (201903.1002b0)"
expected = "bump: v2019.1001-alpha (2019.1001a0) -> v2019.1002-beta (2019.1002b0)"
assert expected in commits[1]
def test_grep(runner):
_add_project_files("README.md")
#
search_re = r"^\s+2:\s+Hello World v201701\.1002-alpha !"
search_re = r"^\s+2:\s+Hello World v2017\.1002-alpha !"
cmd1 = r'grep "vYYYY0M.BUILD[-RELEASE]" README.md'
cmd1 = r'grep "vYYYY.BUILD[-TAG]" README.md'
result1 = runner.invoke(cli.cli, shlex.split(cmd1))
assert result1.exit_code == 0
assert "README.md" in result1.output
assert re.search(search_re, result1.output, flags=re.MULTILINE)
cmd2 = r'grep --version-pattern "vYYYY0M.BUILD[-RELEASE]" "{version}" README.md'
cmd2 = r'grep --version-pattern "vYYYY.BUILD[-TAG]" "{version}" README.md'
result2 = runner.invoke(cli.cli, shlex.split(cmd2))
assert result2.exit_code == 0
assert "README.md" in result2.output
@ -745,17 +811,15 @@ def test_grep(runner):
assert result1.output == result2.output
search_re = r"^\s+3:\s+\[aka\. 201701\.1002a0 \!\]"
search_re = r"^\s+3:\s+\[aka\. 2017\.1002a0 \!\]"
cmd3 = r'grep "\[aka. YYYY0M.BLD[PYTAGNUM] \!\]" README.md'
cmd3 = r'grep "\[aka. YYYY.BLD[PYTAGNUM] \!\]" README.md'
result3 = runner.invoke(cli.cli, shlex.split(cmd3))
assert result3.exit_code == 0
assert "README.md" in result3.output
assert re.search(search_re, result3.output, flags=re.MULTILINE)
cmd4 = (
r'grep --version-pattern "vYYYY0M.BUILD[-RELEASE]" "\[aka. {pep440_version} \!\]" README.md'
)
cmd4 = r'grep --version-pattern "vYYYY.BUILD[-TAG]" "\[aka. {pep440_version} \!\]" README.md'
result4 = runner.invoke(cli.cli, shlex.split(cmd4))
assert result4.exit_code == 0
assert "README.md" in result4.output
@ -784,14 +848,14 @@ def test_multimatch_file_patterns(runner):
with pl.Path("setup.cfg").open(mode="w", encoding="utf-8") as fobj:
fobj.write(SETUP_CFG_MULTIMATCH_FILE_PATTERNS_FIXTURE)
result = runner.invoke(cli.cli, ['bump', '--release', 'beta'])
result = runner.invoke(cli.cli, ['bump', '--tag', 'beta', '--date', "2020-11-22"])
assert result.exit_code == 0
with pl.Path("README.md").open(mode="r", encoding="utf-8") as fobj:
readme_text = fobj.read()
content = fobj.read()
assert "Hello World v202010.1003-beta !" in readme_text
assert "[aka. 202010.1003b0 !]" in readme_text
assert "Hello World v202011.1003-beta !" in content
assert "[aka. 202011.1003b0 !]" in content
def _kwargs(year, month, minor=False):

View file

@ -7,7 +7,7 @@ from __future__ import unicode_literals
import io
from test import util
from pycalver import config
from pycalver2 import config
# pylint:disable=redefined-outer-name ; pytest fixtures
# pylint:disable=protected-access ; allowed for test code
@ -66,7 +66,7 @@ setup.cfg =
NEW_PATTERN_CFG_FIXTURE = """
[pycalver]
current_version = "v201808.1456-beta"
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
version_pattern = "vYYYY0M.BUILD[-TAG]"
commit_message = "bump version to {new_version}"
commit = True
tag = True
@ -169,10 +169,10 @@ def test_parse_v2_cfg():
raw_patterns_by_filepath = _parse_raw_patterns_by_filepath(cfg)
assert raw_patterns_by_filepath["setup.py"] == [
"vYYYY0M.BUILD[-RELEASE]",
"vYYYY0M.BUILD[-TAG]",
"YYYY0M.BLD[PYTAGNUM]",
]
assert raw_patterns_by_filepath["setup.cfg"] == ['current_version = "vYYYY0M.BUILD[-RELEASE]"']
assert raw_patterns_by_filepath["setup.cfg"] == ['current_version = "vYYYY0M.BUILD[-TAG]"']
assert raw_patterns_by_filepath["src/project/*.py"] == ["Copyright (c) 2018-YYYY"]
@ -210,7 +210,7 @@ def test_parse_project_toml():
with config_path.open() as fobj:
config_data = fobj.read()
assert "v201710.0123-alpha" in config_data
assert "v2017.0123-alpha" in config_data
ctx = config.init_project_ctx(project_path)
assert ctx == config.ProjectContext(project_path, config_path, config_rel_path, "toml", None)
@ -219,7 +219,7 @@ def test_parse_project_toml():
assert cfg
assert cfg.current_version == "v201710.0123-alpha"
assert cfg.current_version == "v2017.0123-alpha"
assert cfg.commit is True
assert cfg.tag is True
assert cfg.push is True

View file

@ -4,8 +4,8 @@ from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from pycalver import parse
from pycalver import v1patterns
from pycalver2 import parse
from pycalver2 import v1patterns
SETUP_PY_FIXTURE = """
# setup.py

View file

@ -8,8 +8,8 @@ import re
import pytest
from pycalver import v1patterns
from pycalver import v2patterns
from pycalver2 import v1patterns
from pycalver2 import v2patterns
V2_PART_PATTERN_CASES = [
(['YYYY', 'GGGG'], "2020" , "2020"),
@ -127,13 +127,13 @@ V2_PART_PATTERN_CASES = [
(['0V'], "53", "53"),
(['0V'], "54", None),
(['MAJOR', 'MINOR', 'PATCH'], "0", "0"),
(['RELEASE'], "alpha" , "alpha"),
(['RELEASE'], "alfa" , None),
(['RELEASE'], "beta" , "beta"),
(['RELEASE'], "rc" , "rc"),
(['RELEASE'], "post" , "post"),
(['RELEASE'], "final" , "final"),
(['RELEASE'], "latest", None),
(['TAG' ], "alpha" , "alpha"),
(['TAG' ], "alfa" , None),
(['TAG' ], "beta" , "beta"),
(['TAG' ], "rc" , "rc"),
(['TAG' ], "post" , "post"),
(['TAG' ], "final" , "final"),
(['TAG' ], "latest", None),
(['PYTAG'], "a" , "a"),
(['PYTAG'], "b" , "b"),
(['PYTAG'], "rc" , "rc"),

View file

@ -8,14 +8,14 @@ import re
import copy
from test import util
from pycalver import config
from pycalver import rewrite
from pycalver import v1rewrite
from pycalver import v1version
from pycalver import v2rewrite
from pycalver import v2version
from pycalver import v1patterns
from pycalver import v2patterns
from pycalver2 import config
from pycalver2 import rewrite
from pycalver2 import v1rewrite
from pycalver2 import v1version
from pycalver2 import v2rewrite
from pycalver2 import v2version
from pycalver2 import v1patterns
from pycalver2 import v2patterns
# pylint:disable=protected-access ; allowed for test code
@ -56,7 +56,7 @@ def test_v1_rewrite_lines():
def test_v2_rewrite_lines():
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
version_pattern = "vYYYY0M.BUILD[-TAG]"
new_vinfo = v2version.parse_version_info("v201811.0123-beta", version_pattern)
patterns = [v2patterns.compile_pattern(version_pattern, '__version__ = "{version}"')]
lines = v2rewrite.rewrite_lines(patterns, new_vinfo, ['__version__ = "v201809.0002-alpha" '])
@ -191,10 +191,10 @@ def test_v1_optional_release():
def test_v2_optional_release():
version_pattern = "YYYY.BUILD[-RELEASE]"
version_pattern = "YYYY.BUILD[-TAG]"
new_vinfo = v2version.parse_version_info("2019.0003", version_pattern)
raw_pattern = '__version__ = "YYYY.BUILD[-RELEASE]"'
raw_pattern = '__version__ = "YYYY.BUILD[-TAG]"'
pattern = v2patterns.compile_pattern(version_pattern, raw_pattern)
old_lines = OPTIONAL_RELEASE_FIXTURE.splitlines()
@ -216,14 +216,13 @@ def test_v2_optional_release():
def test_v1_iter_rewritten():
version_pattern = "{pycalver}"
new_vinfo = v1version.parse_version_info("v201809.0123")
version_pattern = "v{year}{build}{release}"
new_vinfo = v1version.parse_version_info("v2018.0123", version_pattern)
file_patterns = {
"src/pycalver/__init__.py": [
v1patterns.compile_pattern(version_pattern, '__version__ = "{pycalver}"'),
]
}
init_pattern = v1patterns.compile_pattern(
version_pattern, '__version__ = "v{year}{build}{release}"'
)
file_patterns = {"src/pycalver2/__init__.py": [init_pattern]}
rewritten_datas = v1rewrite.iter_rewritten(file_patterns, new_vinfo)
rfd = list(rewritten_datas)[0]
expected = [
@ -234,19 +233,19 @@ def test_v1_iter_rewritten():
"# SPDX-License-Identifier: MIT",
'"""PyCalVer: CalVer for Python Packages."""',
'',
'__version__ = "v201809.0123"',
'__version__ = "v2018.0123"',
'',
]
assert rfd.new_lines == expected
def test_v2_iter_rewritten():
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
new_vinfo = v2version.parse_version_info("v201809.0123", version_pattern)
version_pattern = "vYYYY.BUILD[-TAG]"
new_vinfo = v2version.parse_version_info("v2018.0123", version_pattern)
file_patterns = {
"src/pycalver/__init__.py": [
v2patterns.compile_pattern(version_pattern, '__version__ = "vYYYY0M.BUILD[-RELEASE]"'),
"src/pycalver2/__init__.py": [
v2patterns.compile_pattern(version_pattern, '__version__ = "vYYYY.BUILD[-TAG]"'),
]
}
@ -260,32 +259,36 @@ def test_v2_iter_rewritten():
"# SPDX-License-Identifier: MIT",
'"""PyCalVer: CalVer for Python Packages."""',
'',
'__version__ = "v201809.0123"',
'__version__ = "v2018.0123"',
'',
]
assert rfd.new_lines == expected
def test_v1_diff():
version_pattern = "{pycalver}"
raw_pattern = '__version__ = "{pycalver}"'
version_pattern = "v{year}{build}{release}"
raw_pattern = '__version__ = "v{year}{build}{release}"'
pattern = v1patterns.compile_pattern(version_pattern, raw_pattern)
file_patterns = {"src/pycalver/__init__.py": [pattern]}
file_patterns = {"src/pycalver2/__init__.py": [pattern]}
old_vinfo = v1version.parse_version_info("v201809.0123")
new_vinfo = v1version.parse_version_info("v201910.1124")
new_vinfo = v1version.parse_version_info("v201911.1124")
assert new_vinfo > old_vinfo
old_vinfo = v1version.parse_version_info("v2018.0123", version_pattern)
new_vinfo = v1version.parse_version_info("v2019.1124", version_pattern)
diff_str = v1rewrite.diff(old_vinfo, new_vinfo, file_patterns)
lines = diff_str.split("\n")
assert lines[:2] == ["--- src/pycalver/__init__.py", "+++ src/pycalver/__init__.py"]
assert lines[:2] == ["--- src/pycalver2/__init__.py", "+++ src/pycalver2/__init__.py"]
assert lines[6].startswith('-__version__ = "v20')
assert lines[7].startswith('+__version__ = "v20')
assert not lines[6].startswith('-__version__ = "v201809.0123"')
assert not lines[6].startswith('-__version__ = "v2018.0123"')
assert lines[7] == '+__version__ = "v201910.1124"'
assert lines[7] == '+__version__ = "v2019.1124"'
raw_pattern = "Copyright (c) 2018-{year}"
pattern = v1patterns.compile_pattern(version_pattern, raw_pattern)
@ -298,25 +301,25 @@ def test_v1_diff():
def test_v2_diff():
version_pattern = "vYYYY0M.BUILD[-RELEASE]"
raw_pattern = '__version__ = "vYYYY0M.BUILD[-RELEASE]"'
version_pattern = "vYYYY.BUILD[-TAG]"
raw_pattern = '__version__ = "vYYYY.BUILD[-TAG]"'
pattern = v2patterns.compile_pattern(version_pattern, raw_pattern)
file_patterns = {"src/pycalver/__init__.py": [pattern]}
file_patterns = {"src/pycalver2/__init__.py": [pattern]}
old_vinfo = v2version.parse_version_info("v201809.0123", version_pattern)
new_vinfo = v2version.parse_version_info("v201910.1124", version_pattern)
old_vinfo = v2version.parse_version_info("v2018.0123", version_pattern)
new_vinfo = v2version.parse_version_info("v2019.1124", version_pattern)
diff_str = v2rewrite.diff(old_vinfo, new_vinfo, file_patterns)
lines = diff_str.split("\n")
assert lines[:2] == ["--- src/pycalver/__init__.py", "+++ src/pycalver/__init__.py"]
assert lines[:2] == ["--- src/pycalver2/__init__.py", "+++ src/pycalver2/__init__.py"]
assert lines[6].startswith('-__version__ = "v20')
assert lines[7].startswith('+__version__ = "v20')
assert not lines[6].startswith('-__version__ = "v201809.0123"')
assert not lines[6].startswith('-__version__ = "v2018.0123"')
assert lines[7] == '+__version__ = "v201910.1124"'
assert lines[7] == '+__version__ = "v2019.1124"'
raw_pattern = "Copyright (c) 2018-YYYY"
pattern = v2patterns.compile_pattern(version_pattern, raw_pattern)

View file

@ -9,11 +9,11 @@ import datetime as dt
import pytest
from pycalver import version
from pycalver import v1version
from pycalver import v2version
from pycalver import v1patterns
from pycalver import v2patterns
from pycalver2 import version
from pycalver2 import v1version
from pycalver2 import v2version
from pycalver2 import v1patterns
from pycalver2 import v2patterns
# pylint:disable=protected-access ; allowed for test code
@ -212,29 +212,29 @@ def test_v1_parse_versions(pattern_str, line, expected_vinfo):
def test_v2_parse_versions():
_vnfo = v2version.parse_version_info("v201712.0033", raw_pattern="vYYYY0M.BUILD[-RELEASE[NUM]]")
_vnfo = v2version.parse_version_info("v201712.0033", raw_pattern="vYYYY0M.BUILD[-TAG[NUM]]")
fvals = {'year_y': 2017, 'month': 12, 'bid': "0033"}
assert _vnfo == v2version.parse_field_values_to_vinfo(fvals)
def test_v2_format_version():
version_pattern = "vYYYY0M.BUILD[-RELEASE[NUM]]"
version_pattern = "vYYYY0M.BUILD[-TAG[NUM]]"
in_version = "v200701.0033-beta"
vinfo = v2version.parse_version_info(in_version, raw_pattern=version_pattern)
out_version = v2version.format_version(vinfo, raw_pattern=version_pattern)
assert in_version == out_version
result = v2version.format_version(vinfo, raw_pattern="v0Y.BUILD[-RELEASE]")
result = v2version.format_version(vinfo, raw_pattern="v0Y.BUILD[-TAG]")
assert result == "v07.0033-beta"
result = v2version.format_version(vinfo, raw_pattern="vYY.BLD[-RELEASE]")
result = v2version.format_version(vinfo, raw_pattern="vYY.BLD[-TAG]")
assert result == "v7.33-beta"
result = v2version.format_version(vinfo, raw_pattern="vYY.BLD-RELEASE")
result = v2version.format_version(vinfo, raw_pattern="vYY.BLD-TAG")
assert result == "v7.33-beta"
result = v2version.format_version(vinfo, raw_pattern='__version__ = "YYYY.BUILD[-RELEASE]"')
result = v2version.format_version(vinfo, raw_pattern='__version__ = "YYYY.BUILD[-TAG]"')
assert result == '__version__ = "2007.0033-beta"'
result = v2version.format_version(vinfo, raw_pattern='__version__ = "YYYY.BLD"')