Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
basnijholt committed Nov 16, 2023
0 parents commit 07ff4f6
Show file tree
Hide file tree
Showing 16 changed files with 850 additions and 0 deletions.
110 changes: 110 additions & 0 deletions .github/release.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""Create a new release tag with CalVer format."""
import datetime
import operator
import os
from pathlib import Path

import git
from packaging import version


def get_repo() -> git.Repo:
"""Get the git repo for the current project."""
return git.Repo(Path(__file__).parent.parent)


def is_already_tagged(repo: git.Repo) -> bool:
"""Check if the current commit is already tagged."""
return repo.git.tag(points_at="HEAD")


def should_skip_release(repo: git.Repo) -> bool:
"""Check if the commit message contains [skip release]."""
commit_message = repo.head.commit.message.split("\n")[0]
return "[skip release]" in commit_message


def get_new_version(repo: git.Repo) -> str:
"""Get the new version number."""
latest_tag = max(repo.tags, key=operator.attrgetter("commit.committed_datetime"))
last_version = version.parse(latest_tag.name)
now = datetime.datetime.now(tz=datetime.timezone.utc)
patch = (
last_version.micro + 1
if last_version.major == now.year and last_version.minor == now.month
else 0
)
return f"{now.year}.{now.month}.{patch}"


def set_author(repo: git.Repo) -> None:
"""Set author information."""
author_name = repo.head.commit.author.name
author_email = repo.head.commit.author.email
os.environ["GIT_AUTHOR_NAME"] = author_name
os.environ["GIT_AUTHOR_EMAIL"] = author_email
os.environ["GIT_COMMITTER_NAME"] = author_name
os.environ["GIT_COMMITTER_EMAIL"] = author_email


def create_tag(repo: git.Repo, new_version: str, release_notes: str) -> None:
"""Create a new tag."""
set_author(repo)
repo.create_tag(new_version, message=f"Release {new_version}\n\n{release_notes}")


def push_tag(repo: git.Repo, new_version: str) -> None:
"""Push the new tag to the remote repository."""
origin = repo.remote("origin")
origin.push(new_version)


def get_commit_messages_since_last_release(repo: git.Repo) -> str:
"""Get the commit messages since the last release."""
latest_tag = max(repo.tags, key=operator.attrgetter("commit.committed_datetime"))
return repo.git.log(f"{latest_tag}..HEAD", "--pretty=format:%s")


def format_release_notes(commit_messages: str, new_version: str) -> str:
"""Format the release notes."""
header = f"🚀 Release {new_version}\n\n"
intro = "📝 This release includes the following changes:\n\n"

commit_list = commit_messages.split("\n")
formatted_commit_list = [f"- {commit}" for commit in commit_list]
commit_section = "\n".join(formatted_commit_list)

footer = (
"\n\n🙏 Thank you for using this project! Please report any issues "
"or feedback on the GitHub repository"
" on https://github.com/basnijholt/home-assistant-streamdeck-yaml."
)

return f"{header}{intro}{commit_section}{footer}"


def main() -> None:
"""Main entry point."""
repo = get_repo()
if is_already_tagged(repo):
print("Current commit is already tagged!")
return

if should_skip_release(repo):
print("Commit message is [skip release]!")
return

new_version = get_new_version(repo)
commit_messages = get_commit_messages_since_last_release(repo)
release_notes = format_release_notes(commit_messages, new_version)
print(release_notes)
create_tag(repo, new_version, release_notes)
push_tag(repo, new_version)
# Write the output version to the GITHUB_OUTPUT environment file
with open(os.environ["GITHUB_OUTPUT"], "a") as output_file: # noqa: PTH123
output_file.write(f"version={new_version}\n")
print(f"Created new tag: {new_version}")


if __name__ == "__main__":
main()
30 changes: 30 additions & 0 deletions .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: pytest

on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]

steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e ".[test]"
- name: Run pytest
run: pytest
- name: Upload coverage to Codecov
if: matrix.python-version == '3.11'
uses: codecov/codecov-action@v3
28 changes: 28 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Upload Python Package

on:
release:
types: [published]

jobs:
deploy:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine build
- name: Build and publish
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
run: |
python -m build
twine upload dist/*
10 changes: 10 additions & 0 deletions .github/workflows/toc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
on: push
name: TOC Generator
jobs:
generateTOC:
name: TOC Generator
runs-on: ubuntu-latest
steps:
- uses: technote-space/toc-generator@v4
with:
TOC_TITLE: ""
52 changes: 52 additions & 0 deletions .github/workflows/update-readme.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: Update README.md

on:
push:
branches:
- main
pull_request:

jobs:
update_readme:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
with:
persist-credentials: false
fetch-depth: 0

- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.x'

- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install markdown-code-runner
pip install -e .
- name: Run markdown-code-runner
run: markdown-code-runner README.md

- name: Commit updated README.md
id: commit
run: |
git add README.md
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
if git diff --quiet && git diff --staged --quiet; then
echo "No changes in README.md, skipping commit."
echo "commit_status=skipped" >> $GITHUB_ENV
else
git commit -m "Update README.md"
echo "commit_status=committed" >> $GITHUB_ENV
fi
- name: Push changes
if: env.commit_status == 'committed'
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.head_ref }}
89 changes: 89 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# 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/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# IPython Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# dotenv
.env

# virtualenv
venv/
ENV/

# Spyder project settings
.spyderproject

# Rope project settings
.ropeproject
23 changes: 23 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-added-large-files
- id: trailing-whitespace
- id: end-of-file-fixer
- id: mixed-line-ending
- repo: "https://github.com/ambv/black"
rev: 23.3.0
hooks:
- id: black-jupyter
language_version: python3
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.0.270"
hooks:
- id: ruff
args: ["--fix"]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.3.0"
hooks:
- id: mypy
additional_dependencies: ["types-PyYAML"]
29 changes: 29 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2017, Bas Nijholt
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Loading

0 comments on commit 07ff4f6

Please sign in to comment.