Pour tout problème contactez-nous par mail : support@froggit.fr | La FAQ :grey_question: | Rejoignez-nous sur le Chat :speech_balloon:

Skip to content
Snippets Groups Projects
Commit c551cf94 authored by Dorian Turba's avatar Dorian Turba
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
Pipeline #33841 passed
Showing
with 1135 additions and 0 deletions
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
include:
# https://r2devops.io/marketplace/gitlab/swepy/cicd-templates/ruff/ruff
- remote: 'https://gitlab.com/swepy/cicd-templates/ruff/-/raw/ruff@1.0.2/ruff.yml'
# https://r2devops.io/marketplace/gitlab/dorianturba-templates/r2devops_catalog/r2_metadata/pytest
- remote: 'https://gitlab.com/dorianturba-templates/r2devops_catalog/-/raw/main/templates/python/testing/pytest/pytest.yml'
variables:
PACKAGE_NAME: "release_by_changelog"
pytest:
variables:
PYTHON_SETUP: "pip install .[test]"
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.1
hooks:
- id: ruff
=======
Credits
=======
Development Lead
----------------
* Dorian Turba <releasebychangelog.rjsts@simplelogin.com>
Contributors
------------
None yet. Why not be the first?
# Changelog
All notable changes to this job will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] - 2024-04-28
[![Pipeline](https://lab.frogg.it/swepy/release-by-changelog/badges/0.1.0/pipeline.svg)](https://lab.frogg.it/swepy/release-by-changelog/-/pipelines?ref=0.1.0)
* Initial version
# Who is concerned by this file
[//]: # (For a guide to create CONTRIBUTING.md, see http://mozillascience.github.io/working-open-workshop/contributing/)
This file is for:
- Project owners - creators and maintainers of the project
- Project contributors - users of the project who want to know items they're welcome to tackle, and
tact they need in navigating the project/respecting those involved with the project
- Project consumers - users who want to build off the project to create their own project
## Testing
### Installation
```bash
pip install --upgrade pip
pip install -e .[ALL]
pre-commit install
```
Run pre-commit hooks on all files:
```bash
pre-commit autoupdate
pre-commit run --all-files
```
This will run the following hooks:
- `ruff`
### Running tests
```bash
pytest
```
## Generating distribution archives
```bash
pip install --upgrade pip
pip install --upgrade build
python -m build
```
## Pypi share
```bash
pip install --upgrade pip
pip install --upgrade twine
python -m twine upload --repository pypi dist/*
```
You will be prompted for a username and password. For the username, use __token__. For the password, use the token value, including the pypi- prefix.
LICENCE 0 → 100644
MIT License
Copyright (c) 2023 Dorian Turba
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Release by Changelog
Release a new version of a software based on CHANGELOG.md file.
## Installation
```bash
pip install --upgrade pip
pip install release-by-changelog
```
## Usage
In a Gitlab CI pipeline, you can use the following command to release a new version of
your software based on the CHANGELOG.md file.
```bash
release-by-changelog
```
It's recommended to use the `only` directive to run this command only on the default
branch.
Here is an example of a `.gitlab-ci.yml` file using `release-by-changelog`:
```yaml
release:
stage: deploy
script:
- pip install release-by-changelog
- release-by-changelog
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
```
`release-by-changelog` will read the CHANGELOG.md file and create a new tag based on the
latest version found in the file. The release will be pushed to the repository.
`release-by-changelog` rely on the following predefined CI/CD variables to authenticate
with the GitLab API:
- `CI_PROJECT_ID`: Used to identify the project,
- `CI_COMMIT_SHA`: Used to identify the reference,
- `CI_JOB_TOKEN`: Used to authenticate with the GitLab API.
- `CI_SERVER_HOST`: Used to identify the GitLab host.
### Local usage
You can also use this command locally to release a new version of your software.
```bash
release-by-changelog --token <token> <project> <ref>
```
* project: Path or id on host. [required]
* ref: Can be a branch, tag, or commit SHA. [required]
The token is required to authenticate with the GitLab API.
You can authenticate with the GitLab API in several ways:
- [OAuth 2.0 tokens](https://docs.gitlab.com/ee/api/rest/#oauth-20-tokens)
- [Personal access tokens](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html)
- [Project access tokens](https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html)
- [Group access tokens](https://docs.gitlab.com/ee/user/group/settings/group_access_tokens.html)
### Using environment variables
You can also use environment variables to avoid passing the token each time. A token
passed as an argument will always take precedence over the environment variable.
```bash
export PRIVATE_TOKEN=<token>
release-by-changelog <project> <ref>
```
[build-system]
build-backend = "hatchling.build"
requires = ["hatchling"]
[project]
name = "release_by_changelog"
version = "0.1.0"
authors = [
{email = "releasebychangelog.rjsts@simplelogin.com", name = "Dorian Turba"},
]
description = "Release a new version of a software based on CHANGELOG.md file."
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Typing :: Typed",
]
dependencies = [
"python-gitlab",
"typer[all]",
]
[project.scripts]
release_by_changelog = "release_by_changelog:app"
[project.urls]
"Bug Tracker" = "https://lab.frogg.it/swepy/release-by-changelog/-/issues"
"Homepage" = "https://lab.frogg.it/swepy/release-by-changelog"
[project.optional-dependencies]
ALL = ["release_by_changelog[DEV,QUALITY,TEST]"]
DEV = [
"bump-my-version",
"pip-tools",
]
QUALITY = [
"pre-commit",
"ruff>=0.3.3",
"toml-sort",
"pyright",
]
TEST = [
"pytest",
"coverage",
"pytest-mock",
]
[tool.pytest.ini_options]
addopts = "-rA -q"
minversion = "6.0"
testpaths = [
"tests",
"integration",
]
[tool.bumpversion]
allow-dirty = true
commit = false
config-file = "pyproject.toml"
current_version = "0.1.0"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
replace = "{new_version}"
search = "{current_version}"
serialize = [
"{major}.{minor}.{patch}",
]
tag = false
[[tool.bumpversion.files]]
allow-dirty = true
filename = "pyproject.toml"
replace = "version = \"{new_version}\""
search = "version = \"{current_version}\""
[tool.mypy]
disallow_untyped_defs = true
packages = "release_by_changelog"
python_version = ">=3.8"
[tool.hatch.envs.default.scripts]
all-requirements = [
"requirements",
"dev-requirements",
"quality-requirements",
"test-requirements",
]
bump-major = "bump-my-version bump major --allow-dirty"
bump-minor = "bump-my-version bump minor --allow-dirty"
bump-patch = "bump-my-version bump patch --allow-dirty"
dev-requirements = "pip-compile --extra=dev --allow-unsafe --output-file=requirements/dev.txt --strip-extras pyproject.toml"
format = "ruff format ."
format-check = "ruff format . --check"
format-diff = "ruff format . --diff"
install = [
"pip-upgrade",
"pip install -e . --upgrade",
]
lint = "ruff check ."
lint-fix = "ruff check . --fix"
lint-ufix = "ruff check . --fix --unsafe-fixes"
pip-upgrade = "pip install --upgrade pip"
pre-commit-install = "pre-commit install"
pre-commit-run = "pre-commit run --all-files"
pre-commit-update = "pre-commit autoupdate"
pre-push-run = "pre-commit run --all-files --hook-stage pre-push"
quality-requirements = "pip-compile --extra=quality --allow-unsafe --output-file=requirements/quality.txt --strip-extras pyproject.toml"
requirements = "pip-compile --allow-unsafe --output-file=requirements/prod.txt --strip-extras pyproject.toml"
test-requirements = "pip-compile --extra=test --allow-unsafe --output-file=requirements/test.txt --strip-extras pyproject.toml"
toml = "toml-sort --in-place pyproject.toml"
[tool.hatch.metadata]
allow-direct-references = false
[tool.pip-tools]
allow-unsafe = true
annotate = true
generate_hashes = false
quiet = true
strip-extras = true
upgrade = true
[tool.ruff]
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".mypy_cache",
".nox",
".pants.d",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"pypackages",
"venv",
]
indent-width = 4
line-length = 88
target-version = "py38"
[tool.ruff.format]
docstring-code-format = true
docstring-code-line-length = "dynamic"
[tool.ruff.lint]
select = ["ANN", "C90", "D2", "D3", "D4", "E", "F", "I", "N", "RUF", "UP", "W"]
[tool.ruff.lint.flake8-annotations]
suppress-dummy-args = true
[tool.ruff.lint.pydocstyle]
convention = "pep257"
ignore-decorators = ["typing.overload"]
[tool.tomlsort]
check = false
ignore_case = true
in_place = true
no_block_comments = true
no_comments = true
no_footer_comments = true
no_header_comments = true
no_inline_comments = true
no_sort_tables = true
sort_inline_arrays = false
sort_inline_tables = true
sort_table_keys = true
spaces_before_inline_comment = 2
spaces_indent_inline_array = 4
trailing_comma_inline_array = true
[tool.tomlsort.overrides."project"]
table_keys = false
[tool.tox]
legacy_tox_ini = """
[tox]
min_version = 4.0
env_list =
py{38,39,310,311,312}
isolated_build = true
[testenv]
deps = pytest
commands = pytest
"""
#
# This file is autogenerated by pip-compile with Python 3.12
# by the following command:
#
# pip-compile --allow-unsafe --extra=dev --output-file=requirements/dev.txt --strip-extras pyproject.toml
#
annotated-types==0.6.0
# via pydantic
build==1.2.1
# via pip-tools
bump-my-version==0.20.3
# via release_by_changelog (pyproject.toml)
certifi==2024.2.2
# via requests
charset-normalizer==3.3.2
# via requests
click==8.1.7
# via
# bump-my-version
# pip-tools
# rich-click
# typer
idna==3.7
# via requests
markdown-it-py==3.0.0
# via rich
mdurl==0.1.2
# via markdown-it-py
packaging==24.0
# via build
pip-tools==7.4.1
# via release_by_changelog (pyproject.toml)
prompt-toolkit==3.0.36
# via questionary
pydantic==2.7.1
# via
# bump-my-version
# pydantic-settings
pydantic-core==2.18.2
# via pydantic
pydantic-settings==2.2.1
# via bump-my-version
pygments==2.17.2
# via rich
pyproject-hooks==1.0.0
# via
# build
# pip-tools
python-dotenv==1.0.1
# via pydantic-settings
python-gitlab==4.4.0
# via release_by_changelog (pyproject.toml)
questionary==2.0.1
# via bump-my-version
requests==2.31.0
# via
# python-gitlab
# requests-toolbelt
requests-toolbelt==1.0.0
# via python-gitlab
rich==13.7.1
# via
# bump-my-version
# rich-click
# typer
rich-click==1.7.4
# via bump-my-version
shellingham==1.5.4
# via typer
tomlkit==0.12.4
# via bump-my-version
typer==0.12.3
# via release_by_changelog (pyproject.toml)
typing-extensions==4.11.0
# via
# pydantic
# pydantic-core
# rich-click
# typer
urllib3==2.2.1
# via requests
wcwidth==0.2.13
# via prompt-toolkit
wheel==0.43.0
# via pip-tools
# The following packages are considered to be unsafe in a requirements file:
pip==24.0
# via pip-tools
setuptools==69.5.1
# via pip-tools
#
# This file is autogenerated by pip-compile with Python 3.12
# by the following command:
#
# pip-compile --allow-unsafe --output-file=requirements/prod.txt --strip-extras pyproject.toml
#
certifi==2024.2.2
# via requests
charset-normalizer==3.3.2
# via requests
click==8.1.7
# via typer
idna==3.7
# via requests
markdown-it-py==3.0.0
# via rich
mdurl==0.1.2
# via markdown-it-py
pygments==2.17.2
# via rich
python-gitlab==4.4.0
# via release_by_changelog (pyproject.toml)
requests==2.31.0
# via
# python-gitlab
# requests-toolbelt
requests-toolbelt==1.0.0
# via python-gitlab
rich==13.7.1
# via typer
shellingham==1.5.4
# via typer
typer==0.12.3
# via release_by_changelog (pyproject.toml)
typing-extensions==4.11.0
# via typer
urllib3==2.2.1
# via requests
#
# This file is autogenerated by pip-compile with Python 3.12
# by the following command:
#
# pip-compile --allow-unsafe --extra=quality --output-file=requirements/quality.txt --strip-extras pyproject.toml
#
certifi==2024.2.2
# via requests
cfgv==3.4.0
# via pre-commit
charset-normalizer==3.3.2
# via requests
click==8.1.7
# via typer
distlib==0.3.8
# via virtualenv
filelock==3.13.4
# via virtualenv
identify==2.5.36
# via pre-commit
idna==3.7
# via requests
markdown-it-py==3.0.0
# via rich
mdurl==0.1.2
# via markdown-it-py
nodeenv==1.8.0
# via
# pre-commit
# pyright
platformdirs==4.2.1
# via virtualenv
pre-commit==3.7.0
# via release_by_changelog (pyproject.toml)
pygments==2.17.2
# via rich
pyright==1.1.360
# via release_by_changelog (pyproject.toml)
python-gitlab==4.4.0
# via release_by_changelog (pyproject.toml)
pyyaml==6.0.1
# via pre-commit
requests==2.31.0
# via
# python-gitlab
# requests-toolbelt
requests-toolbelt==1.0.0
# via python-gitlab
rich==13.7.1
# via typer
ruff==0.4.2
# via release_by_changelog (pyproject.toml)
shellingham==1.5.4
# via typer
toml-sort==0.23.1
# via release_by_changelog (pyproject.toml)
tomlkit==0.12.4
# via toml-sort
typer==0.12.3
# via release_by_changelog (pyproject.toml)
typing-extensions==4.11.0
# via typer
urllib3==2.2.1
# via requests
virtualenv==20.26.0
# via pre-commit
# The following packages are considered to be unsafe in a requirements file:
setuptools==69.5.1
# via nodeenv
#
# This file is autogenerated by pip-compile with Python 3.12
# by the following command:
#
# pip-compile --allow-unsafe --extra=test --output-file=requirements/test.txt --strip-extras pyproject.toml
#
certifi==2024.2.2
# via requests
charset-normalizer==3.3.2
# via requests
click==8.1.7
# via typer
coverage==7.5.0
# via release_by_changelog (pyproject.toml)
idna==3.7
# via requests
iniconfig==2.0.0
# via pytest
markdown-it-py==3.0.0
# via rich
mdurl==0.1.2
# via markdown-it-py
packaging==24.0
# via pytest
pluggy==1.5.0
# via pytest
pygments==2.17.2
# via rich
pytest==8.2.0
# via
# pytest-mock
# release_by_changelog (pyproject.toml)
pytest-mock==3.14.0
# via release_by_changelog (pyproject.toml)
python-gitlab==4.4.0
# via release_by_changelog (pyproject.toml)
requests==2.31.0
# via
# python-gitlab
# requests-toolbelt
requests-toolbelt==1.0.0
# via python-gitlab
rich==13.7.1
# via typer
shellingham==1.5.4
# via typer
typer==0.12.3
# via release_by_changelog (pyproject.toml)
typing-extensions==4.11.0
# via typer
urllib3==2.2.1
# via requests
from release_by_changelog.main import app
__all__ = ["app"]
import typer
app = typer.Typer(rich_markup_mode="rich")
from __future__ import annotations
import contextlib
import functools
import http
import os
import pathlib
import re
import typing
import typer
if typing.TYPE_CHECKING:
import rich.console
import gitlab.v4.objects
import release_by_changelog.exc
regex: typing.Final = re.compile(
r"^## \[(?P<version>(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]"
r"\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*"
r"|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA"
r"-Z-]+)*))?)\]"
)
def _extract_last_version(f: typing.TextIO) -> str:
for lines in f:
matches = regex.finditer(lines)
try:
match = next(matches)
except StopIteration:
continue
return match.group("version")
raise ValueError("No changelog entry found")
def _extract_body(f: typing.TextIO) -> str:
body = []
for lines in f:
matches = regex.finditer(lines)
with contextlib.suppress(StopIteration):
next(matches)
break
body.append(lines)
return "".join(body)
class ChangelogEntry(typing.NamedTuple):
version: str
body: str
def _last_changelog(changelog_path: pathlib.Path) -> ChangelogEntry:
"""Extract the last changelog entry from the changelog file."""
with changelog_path.open() as f:
version = _extract_last_version(f)
body = _extract_body(f)
return ChangelogEntry(version=version, body=body)
@functools.cache
def _project(
token: str,
host: str,
project: str,
console: rich.console.Console,
) -> tuple[gitlab.v4.objects.Project, str]:
console.print(
f"Retrieving project [bold cyan]{project}[/bold cyan] from "
f"[bold cyan]{host}[/bold cyan]"
)
url = f"https://{host}"
gl = gitlab.Gitlab(url=url, oauth_token=token)
try:
project_ = gl.projects.get(project)
except gitlab.GitlabAuthenticationError as e:
if e.response_code == http.HTTPStatus.UNAUTHORIZED:
raise release_by_changelog.exc.UnauthorizedError from e
raise e
project_name = f"{project_.namespace.get('full_path')}/{project_.name}"
console.print(
f"[bold green]Project found:[/bold green] [bold cyan]{project_name}[bold cyan]"
)
return project_, project_name
def _release(
project: gitlab.v4.objects.Project,
changelog_entry: ChangelogEntry,
ref: str,
) -> str:
data = {
"ref": ref,
"name": changelog_entry.version,
"tag_name": changelog_entry.version,
"description": changelog_entry.body,
}
try:
project.releases.create(data)
except gitlab.GitlabAuthenticationError as e:
if e.response_code == http.HTTPStatus.UNAUTHORIZED:
raise release_by_changelog.exc.UnauthorizedError from e
raise e
except gitlab.GitlabCreateError as e:
if e.response_code == http.HTTPStatus.CONFLICT:
raise release_by_changelog.exc.ReleaseAlreadyExistError from e
raise e
return changelog_entry.version
def _get_remote_changelog_file(
changelog_path: pathlib.Path,
console: rich.console.Console,
project_: gitlab.v4.objects.Project,
ref: str,
) -> gitlab.v4.objects.ProjectFile:
try:
changelog_file: gitlab.v4.objects.ProjectFile = project_.files.get(
file_path=str(changelog_path), ref=ref
)
except gitlab.GitlabGetError as e:
if e.response_code == http.HTTPStatus.NOT_FOUND:
console.print(
f"[bold red]Changelog file {changelog_path} not found in the remote "
f"project files[/bold red]"
)
raise typer.Exit(code=1)
raise e
console.print(
f"[bold cyan]{changelog_path}[/bold cyan] [bold green]found in the remote "
f"project files[/bold green]"
)
return changelog_file
def _save_remote_changelog_file(
changelog_file: gitlab.v4.objects.ProjectFile, changelog_path: pathlib.Path
) -> pathlib.Path:
"""
Save the remote changelog file to a temporary file.
:raises NotImplementedError: If the OS is not supported.
"""
if os.name == "posix":
tmp_file = pathlib.Path(f"/tmp/{changelog_path.name}")
elif os.name == "nt":
temp_path = pathlib.Path(os.environ["Temp"])
tmp_file = temp_path / changelog_path.name
else:
raise NotImplementedError(f"OS {os.name} not supported")
tmp_file.write_bytes(changelog_file.decode())
return tmp_file
def _changelog_file(
changelog_path: pathlib.Path,
token: str,
host: str,
project: str,
ref: str,
console: rich.console.Console,
) -> pathlib.Path:
"""
Find usable changelog file path.
If the changelog file is not found locally, it will look for it in the remote
project files.
:raises NotImplementedError: If the OS is not supported.
"""
console.print(f"Look for local [bold cyan]{changelog_path}[/bold cyan]")
if changelog_path.exists():
console.print(
f"[bold green]Found local[/bold green] "
f"[bold cyan]{changelog_path}[/bold cyan]"
)
return changelog_path
console.print(
f"[yellow]Local [bold cyan]{changelog_path}[/bold cyan] file not found, looking"
" for file in the remote project files[/yellow]"
)
project_, _ = _project(
token,
host,
project,
console,
)
changelog_file = _get_remote_changelog_file(changelog_path, console, project_, ref)
tmp_file = _save_remote_changelog_file(changelog_file, changelog_path)
return tmp_file
import pathlib
import typing
import rich.panel
import rich.table
import typer
import release_by_changelog.exc
from release_by_changelog.app import app
from release_by_changelog.cmds._release import (
_changelog_file,
_last_changelog,
_project,
_release,
)
err_console = rich.console.Console(stderr=True)
@app.command()
def release(
project: str = typer.Argument(help="Path or id on host.", envvar="CI_PROJECT_ID"),
ref: str = typer.Argument(
help="Can be a branch, tag, or commit SHA.",
envvar="CI_COMMIT_SHA",
),
changelog_path: typing.Annotated[
pathlib.Path,
typer.Option(help="Path to the changelog file."),
] = pathlib.Path("CHANGELOG.md"),
host: typing.Annotated[
str,
typer.Option(
help="URL of the GitLab instance.",
envvar="CI_SERVER_HOST",
),
] = "gitlab.com",
interact: bool = typer.Option(
True,
help="CLI ask for confirmation before creating the release. "
"No interaction means automatic confirmation.",
),
token: str = typer.Option(
None,
help="[red]Required[/red] for [yellow]user-based[/yellow] authentication.",
envvar="PRIVATE_TOKEN",
),
ci_job_token: str = typer.Option(
None,
help="[red]Required[/red] for [yellow]CI-based[/yellow] authentication.",
envvar="CI_JOB_TOKEN",
),
) -> None:
console = rich.console.Console()
if not token and not ci_job_token:
err_console.print(
rich.panel.Panel(
"You need to provide a PRIVATE_TOKEN or a CI_JOB_TOKEN",
title="Error: Missing token",
title_align="left",
subtitle="release_by_changelog --help",
subtitle_align="left",
expand=False,
border_style="red",
)
)
raise typer.Exit(code=1)
token = token or ci_job_token
try:
changelog_path = _changelog_file(
changelog_path, token, host, project, ref, console
)
except release_by_changelog.exc.UnauthorizedError:
err_console.print("Error: Unauthorized", style="bold red")
raise typer.Exit(code=1)
console.print(f"Processing [bold cyan]{changelog_path}[/bold cyan]")
changelog_entry = _last_changelog(changelog_path)
console.print(
"[bold green]Found changelog entry:[/bold green] "
f"[bold cyan]{changelog_entry.version}[/bold cyan]"
)
project_, project_name = _project(token, host, project, console)
if interact:
typer.confirm("Do you confirm release?", default=True, abort=True)
console.print(
f"Creating release [bold cyan]{changelog_entry.version}[/bold cyan] for "
f"project [bold cyan]{project_name}[/bold cyan]"
)
try:
result = _release(project_, changelog_entry, ref)
except release_by_changelog.exc.UnauthorizedError:
err_console.print("Error: Unauthorized", style="bold red")
raise typer.Exit(code=1)
except release_by_changelog.exc.ReleaseAlreadyExistError:
err_console.print("Error: Release already exists", style="bold red")
raise typer.Exit(code=1)
console.print(f"Release created: {result}", style="bold green")
if __name__ == "__main__":
release(
project="1484",
ref="main",
changelog_path=pathlib.Path("test_dir/TEST_CHANGELOG.md"),
host="lab.frogg.it",
interact=True,
token="glpat-nxkztk41T6-WDxfaifxs",
)
class UnauthorizedError(Exception):
pass
class ReleaseAlreadyExistError(Exception):
pass
import importlib
from release_by_changelog.app import app
__all__ = ["app"]
importlib.import_module("release_by_changelog.cmds.release")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment