mirror of
https://github.com/drewcassidy/yaclog.git
synced 2024-09-01 14:58:58 +00:00
Compare commits
12 Commits
Author | SHA1 | Date | |
---|---|---|---|
ebcb70c130 | |||
c614363b5f | |||
9ab1f74936 | |||
74b6448ee1 | |||
a82e455267 | |||
41974dc953 | |||
5205e27fc8 | |||
157f49839f | |||
6e75e15526 | |||
e9a8e63c27 | |||
983fff1471 | |||
39f6ede5f2 |
18
CHANGELOG.md
18
CHANGELOG.md
@ -1,7 +1,20 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
All notable changes to this project will be documented in this file
|
All notable changes to this project will be documented in this file
|
||||||
|
|
||||||
## 0.2.0
|
## 0.3.1 - 2021-04-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `yaclog` tool for manipulating changelogs from the command line
|
||||||
|
- `init` command to make a new changelog
|
||||||
|
- `format` command to reformat the changelog
|
||||||
|
- `show` command to show changes from the changelog
|
||||||
|
- `entry` command for manipulating entries in the changelog
|
||||||
|
- `tag` command for manipulating tags in the changelog
|
||||||
|
- `release` command for creating releases
|
||||||
|
|
||||||
|
## 0.2.0 - 2021-04-19
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
@ -12,8 +25,7 @@ All notable changes to this project will be documented in this file
|
|||||||
- Updated package metadata
|
- Updated package metadata
|
||||||
- Rewrote parser to use a 2-step method that is more flexible.
|
- Rewrote parser to use a 2-step method that is more flexible.
|
||||||
- Parser can now handle code blocks.
|
- Parser can now handle code blocks.
|
||||||
- Parser can now handle setext-style headers and H2s not conforming to the
|
- Parser can now handle setext-style headers and H2s not conforming to the schema.
|
||||||
schema.
|
|
||||||
|
|
||||||
## 0.1.0 - 2021-04-16
|
## 0.1.0 - 2021-04-16
|
||||||
|
|
||||||
|
@ -27,6 +27,9 @@ project_urls =
|
|||||||
Changelog = https://github.com/drewcassidy/yaclog/blob/main/CHANGELOG.md
|
Changelog = https://github.com/drewcassidy/yaclog/blob/main/CHANGELOG.md
|
||||||
|
|
||||||
[options]
|
[options]
|
||||||
install_requires = Click; GitPython
|
install_requires =
|
||||||
|
Click ~= 7.0
|
||||||
|
GitPython >= 3
|
||||||
|
packaging >= 20
|
||||||
python_requires = >= 3.8
|
python_requires = >= 3.8
|
||||||
packages = find:
|
packages = find:
|
||||||
|
@ -17,7 +17,6 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import string
|
|
||||||
from typing import List, Tuple, Optional
|
from typing import List, Tuple, Optional
|
||||||
|
|
||||||
bullets = '+-*'
|
bullets = '+-*'
|
||||||
@ -30,6 +29,8 @@ under2_regex = re.compile(r'^-+\s*$')
|
|||||||
bullet_regex = re.compile(r'^[-+*]')
|
bullet_regex = re.compile(r'^[-+*]')
|
||||||
linkid_regex = re.compile(r'^\[(?P<link_id>\S*)]:\s*(?P<link>.*)')
|
linkid_regex = re.compile(r'^\[(?P<link_id>\S*)]:\s*(?P<link>.*)')
|
||||||
|
|
||||||
|
default_header = '# Changelog\n\nAll notable changes to this project will be documented in this file'
|
||||||
|
|
||||||
|
|
||||||
def _strip_link(token):
|
def _strip_link(token):
|
||||||
if link_literal := re.fullmatch(r'\[(.*?)]\((.*?)\)', token):
|
if link_literal := re.fullmatch(r'\[(.*?)]\((.*?)\)', token):
|
||||||
@ -47,7 +48,7 @@ def _join_markdown(segments: List[str]) -> str:
|
|||||||
text: List[str] = []
|
text: List[str] = []
|
||||||
last_bullet = False
|
last_bullet = False
|
||||||
for segment in segments:
|
for segment in segments:
|
||||||
is_bullet = bullet_regex.match(segment) and '\n' not in segment
|
is_bullet = bullet_regex.match(segment)
|
||||||
|
|
||||||
if not is_bullet or not last_bullet:
|
if not is_bullet or not last_bullet:
|
||||||
text.append('')
|
text.append('')
|
||||||
@ -62,18 +63,38 @@ def _join_markdown(segments: List[str]) -> str:
|
|||||||
class VersionEntry:
|
class VersionEntry:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.sections = {'': []}
|
self.sections = {'': []}
|
||||||
self.name: str = ''
|
self.name: str = 'Unreleased'
|
||||||
self.date: Optional[datetime.date] = None
|
self.date: Optional[datetime.date] = None
|
||||||
self.tags: List[str] = []
|
self.tags: List[str] = []
|
||||||
self.link: str = ''
|
self.link: str = ''
|
||||||
self.link_id: str = None
|
self.link_id: str = ''
|
||||||
self.line_no: int = -1
|
self.line_no: int = -1
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def body(self, md: bool = True) -> str:
|
||||||
if self.link:
|
segments = []
|
||||||
segments = [f'[{self.name}]']
|
|
||||||
|
for section, entries in self.sections.items():
|
||||||
|
if section:
|
||||||
|
if md:
|
||||||
|
segments.append(f'### {section.title()}')
|
||||||
else:
|
else:
|
||||||
segments = [self.name]
|
segments.append(f'{section.upper()}:')
|
||||||
|
|
||||||
|
if len(entries) > 0:
|
||||||
|
segments.append(_join_markdown(entries))
|
||||||
|
|
||||||
|
return _join_markdown(segments)
|
||||||
|
|
||||||
|
def header(self, md: bool = True) -> str:
|
||||||
|
segments = []
|
||||||
|
|
||||||
|
if md:
|
||||||
|
segments.append('##')
|
||||||
|
|
||||||
|
if self.link and md:
|
||||||
|
segments.append(f'[{self.name}]')
|
||||||
|
else:
|
||||||
|
segments.append(self.name)
|
||||||
|
|
||||||
if self.date or len(self.tags) > 0:
|
if self.date or len(self.tags) > 0:
|
||||||
segments.append('-')
|
segments.append('-')
|
||||||
@ -85,28 +106,36 @@ class VersionEntry:
|
|||||||
|
|
||||||
return ' '.join(segments)
|
return ' '.join(segments)
|
||||||
|
|
||||||
|
def text(self, md: bool = True) -> str:
|
||||||
|
return self.header(md) + '\n\n' + self.body(md)
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.header(False)
|
||||||
|
|
||||||
|
|
||||||
class Changelog:
|
class Changelog:
|
||||||
def __init__(self, path: os.PathLike):
|
def __init__(self, path: os.PathLike = None):
|
||||||
self.path = path
|
self.path: os.PathLike = path
|
||||||
self.header = ''
|
self.header: str = ''
|
||||||
self.versions = []
|
self.versions: List[VersionEntry] = []
|
||||||
|
self.links = {}
|
||||||
|
|
||||||
|
if not os.path.exists(path):
|
||||||
|
self.header = default_header
|
||||||
|
return
|
||||||
|
|
||||||
# Read file
|
# Read file
|
||||||
with open(path, 'r') as fp:
|
with open(path, 'r') as fp:
|
||||||
self.lines = fp.readlines()
|
lines = fp.readlines()
|
||||||
|
|
||||||
section = ''
|
section = ''
|
||||||
in_block = False
|
in_block = False
|
||||||
in_code = False
|
in_code = False
|
||||||
|
|
||||||
self.links = {}
|
|
||||||
|
|
||||||
links = {}
|
|
||||||
segments: List[Tuple[int, List[str], str]] = []
|
segments: List[Tuple[int, List[str], str]] = []
|
||||||
header_segments = []
|
header_segments = []
|
||||||
|
|
||||||
for line_no, line in enumerate(self.lines):
|
for line_no, line in enumerate(lines):
|
||||||
if in_code:
|
if in_code:
|
||||||
# this is the contents of a code block
|
# this is the contents of a code block
|
||||||
segments[-1][1].append(line)
|
segments[-1][1].append(line)
|
||||||
@ -143,7 +172,7 @@ class Changelog:
|
|||||||
|
|
||||||
elif match := linkid_regex.match(line):
|
elif match := linkid_regex.match(line):
|
||||||
# this is a link definition in the form '[id]: link', so add it to the link table
|
# this is a link definition in the form '[id]: link', so add it to the link table
|
||||||
links[match['link_id'].lower()] = match['link']
|
self.links[match['link_id'].lower()] = match['link']
|
||||||
|
|
||||||
elif line.isspace():
|
elif line.isspace():
|
||||||
# skip empty lines
|
# skip empty lines
|
||||||
@ -216,18 +245,17 @@ class Changelog:
|
|||||||
if match := re.fullmatch(r'\[(.*)]', version.name):
|
if match := re.fullmatch(r'\[(.*)]', version.name):
|
||||||
# ref-matched link
|
# ref-matched link
|
||||||
link_id = match[1].lower()
|
link_id = match[1].lower()
|
||||||
if link_id in links:
|
if link_id in self.links:
|
||||||
version.link = links.pop(link_id)
|
version.link = self.links.pop(link_id)
|
||||||
version.link_id = None
|
version.link_id = None
|
||||||
version.name = match[1]
|
version.name = match[1]
|
||||||
|
|
||||||
elif version.link_id in links:
|
elif version.link_id in self.links:
|
||||||
# id-matched link
|
# id-matched link
|
||||||
version.link = links.pop(version.link_id)
|
version.link = self.links.pop(version.link_id)
|
||||||
|
|
||||||
# strip whitespace from header
|
# strip whitespace from header
|
||||||
self.header = _join_markdown(header_segments)
|
self.header = _join_markdown(header_segments)
|
||||||
self.links = links
|
|
||||||
|
|
||||||
def write(self, path: os.PathLike = None):
|
def write(self, path: os.PathLike = None):
|
||||||
if path is None:
|
if path is None:
|
||||||
@ -236,23 +264,18 @@ class Changelog:
|
|||||||
v_links = {}
|
v_links = {}
|
||||||
v_links.update(self.links)
|
v_links.update(self.links)
|
||||||
|
|
||||||
with open(path, 'w') as fp:
|
segments = [self.header]
|
||||||
fp.write(self.header)
|
|
||||||
fp.write('\n\n')
|
|
||||||
|
|
||||||
for version in self.versions:
|
for version in self.versions:
|
||||||
fp.write(f'## {version}\n\n')
|
|
||||||
|
|
||||||
if version.link:
|
if version.link:
|
||||||
v_links[version.name] = version.link
|
v_links[version.name] = version.link
|
||||||
|
|
||||||
for section in version.sections:
|
segments.append(version.text())
|
||||||
if section:
|
|
||||||
fp.write(f'### {section}\n\n')
|
|
||||||
|
|
||||||
if len(version.sections[section]) > 0:
|
|
||||||
fp.write(_join_markdown(version.sections[section]))
|
|
||||||
fp.write('\n\n')
|
|
||||||
|
|
||||||
for link_id, link in v_links.items():
|
for link_id, link in v_links.items():
|
||||||
fp.write(f'[{link_id.lower()}]: {link}\n')
|
segments.append(f'[{link_id.lower()}]: {link}')
|
||||||
|
|
||||||
|
text = _join_markdown(segments)
|
||||||
|
|
||||||
|
with open(path, 'w') as fp:
|
||||||
|
fp.write(text)
|
||||||
|
0
yaclog/cli/__init__.py
Normal file
0
yaclog/cli/__init__.py
Normal file
228
yaclog/cli/__main__.py
Normal file
228
yaclog/cli/__main__.py
Normal file
@ -0,0 +1,228 @@
|
|||||||
|
# yaclog: yet another changelog tool
|
||||||
|
# Copyright (c) 2021. Andrew Cassidy
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU Affero General Public License as
|
||||||
|
# published by the Free Software Foundation, either version 3 of the
|
||||||
|
# License, or (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU Affero General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import click
|
||||||
|
import os.path
|
||||||
|
import datetime
|
||||||
|
import git
|
||||||
|
import yaclog.cli.version_util
|
||||||
|
from yaclog import Changelog
|
||||||
|
|
||||||
|
|
||||||
|
@click.group()
|
||||||
|
@click.option('--path', envvar='YACLOG_PATH', default='CHANGELOG.md', show_default=True,
|
||||||
|
type=click.Path(dir_okay=False, writable=True, readable=True),
|
||||||
|
help='Location of the changelog file.')
|
||||||
|
@click.version_option()
|
||||||
|
@click.pass_context
|
||||||
|
def cli(ctx, path):
|
||||||
|
"""Manipulate markdown changelog files."""
|
||||||
|
if not (ctx.invoked_subcommand == 'init') and not os.path.exists(path):
|
||||||
|
# file does not exist and this isn't the init command
|
||||||
|
raise click.FileError(f'Changelog file {path} does not exist. Create it by running `yaclog init`.')
|
||||||
|
|
||||||
|
ctx.obj = yaclog.read(path)
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.pass_obj
|
||||||
|
def init(obj: Changelog):
|
||||||
|
"""Create a new changelog file."""
|
||||||
|
if os.path.exists(obj.path):
|
||||||
|
click.confirm(f'Changelog file {obj.path} already exists. Would you like to overwrite it?', abort=True)
|
||||||
|
os.remove(obj.path)
|
||||||
|
|
||||||
|
yaclog.Changelog(obj.path).write()
|
||||||
|
print(f'Created new changelog file at {obj.path}')
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command('format') # dont accidentally hide the `format` python builtin
|
||||||
|
@click.pass_obj
|
||||||
|
def reformat(obj: Changelog):
|
||||||
|
"""Reformat the changelog file."""
|
||||||
|
obj.write()
|
||||||
|
print(f'Reformatted changelog file at {obj.path}')
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(short_help='Show changes from the changelog file')
|
||||||
|
@click.option('--all', '-a', 'all_versions', is_flag=True, help='Show the entire changelog.')
|
||||||
|
@click.argument('versions', type=str, nargs=-1)
|
||||||
|
@click.pass_obj
|
||||||
|
def show(obj: Changelog, all_versions, versions):
|
||||||
|
"""Show the changes for VERSIONS.
|
||||||
|
|
||||||
|
VERSIONS is a list of versions to print. If not given, the most recent version is used.
|
||||||
|
"""
|
||||||
|
if all_versions:
|
||||||
|
with open(obj.path, 'r') as fp:
|
||||||
|
click.echo_via_pager(fp.read())
|
||||||
|
else:
|
||||||
|
if len(versions):
|
||||||
|
v_list = []
|
||||||
|
for v_name in versions:
|
||||||
|
matches = [v for v in obj.versions if v.name == v_name]
|
||||||
|
if len(matches) == 0:
|
||||||
|
raise click.BadArgumentUsage(f'Version "{v_name}" not found in changelog.')
|
||||||
|
v_list += matches
|
||||||
|
else:
|
||||||
|
v_list = [obj.versions[0]]
|
||||||
|
|
||||||
|
for v in v_list:
|
||||||
|
click.echo(v.text(False))
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(short_help='Modify version tags')
|
||||||
|
@click.option('--add/--delete', '-a/-d', default=True, is_flag=True, help='Add or delete tags')
|
||||||
|
@click.argument('tag_name', metavar='tag', type=str)
|
||||||
|
@click.argument('version_name', metavar='version', type=str, required=False)
|
||||||
|
@click.pass_obj
|
||||||
|
def tag(obj: Changelog, add, tag_name: str, version_name: str):
|
||||||
|
"""Modify TAG on VERSION.
|
||||||
|
|
||||||
|
VERSION is the name of a version to add tags to. If not given, the most recent version is used.
|
||||||
|
"""
|
||||||
|
tag_name = tag_name.upper()
|
||||||
|
if version_name:
|
||||||
|
matches = [v for v in obj.versions if v.name == version_name]
|
||||||
|
if len(matches) == 0:
|
||||||
|
raise click.BadArgumentUsage(f'Version "{version_name}" not found in changelog.')
|
||||||
|
version = matches[0]
|
||||||
|
else:
|
||||||
|
version = obj.versions[0]
|
||||||
|
|
||||||
|
if add:
|
||||||
|
version.tags.append(tag_name)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
version.tags.remove(tag_name)
|
||||||
|
except ValueError:
|
||||||
|
raise click.BadArgumentUsage(f'Tag "{tag_name}" not found in version "{version.name}".')
|
||||||
|
|
||||||
|
obj.write()
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command(short_help='Add entries to the changelog.')
|
||||||
|
@click.option('--bullet', '-b', 'bullets', multiple=True, type=str,
|
||||||
|
help='Bullet points to add. '
|
||||||
|
'When multiple bullet points are provided, additional points are added as sub-points.')
|
||||||
|
@click.option('--paragraph', '-p', 'paragraphs', multiple=True, type=str,
|
||||||
|
help='Paragraphs to add')
|
||||||
|
@click.argument('section_name', metavar='SECTION', type=str, default='', required=False)
|
||||||
|
@click.argument('version_name', metavar='VERSION', type=str, default=None, required=False)
|
||||||
|
@click.pass_obj
|
||||||
|
def entry(obj: Changelog, bullets, paragraphs, section_name, version_name):
|
||||||
|
"""Add entries to SECTION in VERSION
|
||||||
|
|
||||||
|
SECTION is the name of the section to append to. If not given, entries will be uncategorized.
|
||||||
|
|
||||||
|
VERSION is the name of the version to append to. If not given, the most recent version will be used,
|
||||||
|
or a new 'Unreleased' version will be added if the most recent version has been released.
|
||||||
|
"""
|
||||||
|
|
||||||
|
section_name = section_name.title()
|
||||||
|
if version_name:
|
||||||
|
matches = [v for v in obj.versions if v.name == version_name]
|
||||||
|
if len(matches) == 0:
|
||||||
|
raise click.BadArgumentUsage(f'Version "{version_name}" not found in changelog.')
|
||||||
|
version = matches[0]
|
||||||
|
else:
|
||||||
|
version = obj.versions[0]
|
||||||
|
if version.name.lower() != 'unreleased':
|
||||||
|
version = yaclog.changelog.VersionEntry()
|
||||||
|
obj.versions.insert(0, version)
|
||||||
|
|
||||||
|
if section_name not in version.sections.keys():
|
||||||
|
version.sections[section_name] = []
|
||||||
|
|
||||||
|
section = version.sections[section_name]
|
||||||
|
section += paragraphs
|
||||||
|
|
||||||
|
sub_bullet = False
|
||||||
|
bullet_str = ''
|
||||||
|
for bullet in bullets:
|
||||||
|
bullet = bullet.strip()
|
||||||
|
if bullet[0] not in ['-+*']:
|
||||||
|
bullet = '- ' + bullet
|
||||||
|
|
||||||
|
if sub_bullet:
|
||||||
|
bullet = '\n ' + bullet
|
||||||
|
|
||||||
|
bullet_str += bullet
|
||||||
|
sub_bullet = True
|
||||||
|
section.append(bullet_str)
|
||||||
|
|
||||||
|
obj.write()
|
||||||
|
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('-v', '--version', 'v_flag', type=str, default=None, help='The new version number to use.')
|
||||||
|
@click.option('-M', '--major', 'v_flag', flag_value='+M', help='Increment major version number.')
|
||||||
|
@click.option('-m', '--minor', 'v_flag', flag_value='+m', help='Increment minor version number.')
|
||||||
|
@click.option('-p', '--patch', 'v_flag', flag_value='+p', help='Increment patch number.')
|
||||||
|
@click.option('-a', '--alpha', 'v_flag', flag_value='+a', help='Increment alpha version number.')
|
||||||
|
@click.option('-b', '--beta', 'v_flag', flag_value='+b', help='Increment beta version number.')
|
||||||
|
@click.option('-r', '--rc', 'v_flag', flag_value='+rc', help='Increment release candidate version number.')
|
||||||
|
@click.option('-c', '--commit', is_flag=True, help='Create a git commit tagged with the new version number.')
|
||||||
|
@click.pass_obj
|
||||||
|
def release(obj: Changelog, v_flag, commit):
|
||||||
|
"""Release versions in the changelog and increment their version numbers"""
|
||||||
|
version = [v for v in obj.versions if v.name.lower() != 'unreleased'][0]
|
||||||
|
cur_version = obj.versions[0]
|
||||||
|
old_name = cur_version.name
|
||||||
|
|
||||||
|
if v_flag:
|
||||||
|
if v_flag[0] == '+':
|
||||||
|
new_name = yaclog.cli.version_util.increment_version(version.name, v_flag)
|
||||||
|
else:
|
||||||
|
new_name = v_flag
|
||||||
|
|
||||||
|
if yaclog.cli.version_util.is_release(cur_version.name):
|
||||||
|
click.confirm(f'Rename release version "{cur_version.name}" to "{new_name}"?', abort=True)
|
||||||
|
|
||||||
|
cur_version.name = new_name
|
||||||
|
cur_version.date = datetime.datetime.utcnow().date()
|
||||||
|
|
||||||
|
obj.write()
|
||||||
|
print(f'Renamed version "{old_name}" to "{cur_version.name}".')
|
||||||
|
|
||||||
|
if commit:
|
||||||
|
repo = git.Repo(os.curdir)
|
||||||
|
|
||||||
|
if repo.bare:
|
||||||
|
raise click.BadOptionUsage('commit', f'Directory {os.path.abspath(os.curdir)} is not a git repo.')
|
||||||
|
|
||||||
|
repo.index.add(obj.path)
|
||||||
|
|
||||||
|
version_type = '' if yaclog.cli.version_util.is_release(cur_version.name) else 'non-release '
|
||||||
|
untracked = len(repo.index.diff(None))
|
||||||
|
untracked_warning = ''
|
||||||
|
untracked_plural = 's' if untracked > 1 else ''
|
||||||
|
if untracked > 0:
|
||||||
|
untracked_warning = click.style(
|
||||||
|
f' You have {untracked} untracked file{untracked_plural} that will not be committed.',
|
||||||
|
fg='red', bold=True)
|
||||||
|
|
||||||
|
click.confirm(f'Commit and create tag for {version_type}version {cur_version.name}?{untracked_warning}',
|
||||||
|
abort=True)
|
||||||
|
|
||||||
|
repo.index.commit(f'Version {cur_version.name}\n\n{cur_version.body()}')
|
||||||
|
repo.create_tag(cur_version.name, message=cur_version.body(False))
|
||||||
|
|
||||||
|
print(f'Created tag "{cur_version.name}".')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
cli()
|
80
yaclog/cli/version_util.py
Normal file
80
yaclog/cli/version_util.py
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
# yaclog: yet another changelog tool
|
||||||
|
# Copyright (c) 2021. Andrew Cassidy
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU Affero General Public License as
|
||||||
|
# published by the Free Software Foundation, either version 3 of the
|
||||||
|
# License, or (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU Affero General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Affero General Public License
|
||||||
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
from packaging.version import Version, InvalidVersion
|
||||||
|
|
||||||
|
|
||||||
|
def is_release(version: str) -> bool:
|
||||||
|
try:
|
||||||
|
v = Version(version)
|
||||||
|
return not (v.is_devrelease or v.is_prerelease)
|
||||||
|
except InvalidVersion:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def increment_version(version: str, mode: str) -> str:
|
||||||
|
v = Version(version)
|
||||||
|
epoch = v.epoch
|
||||||
|
release = v.release
|
||||||
|
pre = v.pre
|
||||||
|
post = v.post
|
||||||
|
dev = v.dev
|
||||||
|
local = v.local
|
||||||
|
|
||||||
|
if mode == '+M':
|
||||||
|
release = (release[0] + 1,) + release[1:]
|
||||||
|
elif mode == '+m':
|
||||||
|
release = (release[0], release[1] + 1) + release[2:]
|
||||||
|
elif mode == '+p':
|
||||||
|
release = (release[0], release[1], release[2] + 1) + release[3:]
|
||||||
|
elif mode in ['+a', '+b', '+rc']:
|
||||||
|
if pre[0] == mode[1:]:
|
||||||
|
pre = (mode[1:], pre[1] + 1)
|
||||||
|
else:
|
||||||
|
pre = (mode[1:], 0)
|
||||||
|
else:
|
||||||
|
raise IndexError(f'Unknown mode {mode}')
|
||||||
|
|
||||||
|
return join_version(epoch, release, pre, post, dev, local)
|
||||||
|
|
||||||
|
|
||||||
|
def join_version(epoch, release, pre, post, dev, local) -> str:
|
||||||
|
parts = []
|
||||||
|
|
||||||
|
# Epoch
|
||||||
|
if epoch != 0:
|
||||||
|
parts.append(f"{epoch}!")
|
||||||
|
|
||||||
|
# Release segment
|
||||||
|
parts.append(".".join(str(x) for x in release))
|
||||||
|
|
||||||
|
# Pre-release
|
||||||
|
if pre is not None:
|
||||||
|
parts.append("".join(str(x) for x in pre))
|
||||||
|
|
||||||
|
# Post-release
|
||||||
|
if post is not None:
|
||||||
|
parts.append(f".post{post}")
|
||||||
|
|
||||||
|
# Development release
|
||||||
|
if dev is not None:
|
||||||
|
parts.append(f".dev{dev}")
|
||||||
|
|
||||||
|
# Local version segment
|
||||||
|
if local is not None:
|
||||||
|
parts.append(f"+{local}")
|
||||||
|
|
||||||
|
return "".join(parts)
|
Reference in New Issue
Block a user