Skip to content

Commit

Permalink
refactor(python-3.9): refactor syntax and typing for python 3.9
Browse files Browse the repository at this point in the history
- ci: remove 'pylint', replaced by ruff module PL
- ci: add ruff module for complexity checks (C901)
- ci: add ruff module for comprehension checks (C4)
- ci: add ruff module naming conventions checks (N)
  • Loading branch information
tomassebestik committed Sep 29, 2024
1 parent fe771f8 commit 8de6c1d
Show file tree
Hide file tree
Showing 10 changed files with 125 additions and 141 deletions.
53 changes: 26 additions & 27 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
# Run `pre-commit autoupdate` to update to the latest pre-commit hooks version.
minimum_pre_commit_version: 3.3.0 # Specifies the minimum version of pre-commit required for this configuration
default_install_hook_types: [pre-commit, commit-msg] # Default hook types to install if not specified in individual hooks
minimum_pre_commit_version: 3.3.0
default_install_hook_types: [pre-commit, commit-msg]
default_stages: [commit]

repos:
Expand All @@ -13,59 +12,60 @@ repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace # Removes trailing whitespaces from lines
- id: end-of-file-fixer # Ensures files end with a newline
- id: check-shebang-scripts-are-executable # Checks that scripts with shebangs are executable.
- id: check-case-conflict # Check conflict on a case-insensitive filesystem (MacOS HFS+/Windows FAT).
- id: mixed-line-ending # Detects mixed line endings (CRLF/LF)
args: ['-f=lf'] # Forces files to use LF line endings

- repo: https://github.com/pylint-dev/pylint
rev: v3.2.6
hooks:
- id: pylint # Runs pylint on Python code
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-shebang-scripts-are-executable
- id: check-case-conflict
- id: mixed-line-ending
args: ['-f=lf']

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.3
hooks:
- id: ruff # Linter
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format # Formatter (replaces Black)
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.2
hooks:
- id: mypy # Runs mypy for Python type checking
- id: mypy

- repo: https://github.com/asottile/pyupgrade
rev: v3.17.0
hooks:
- id: pyupgrade
args: [--py39-plus]

- repo: https://github.com/espressif/conventional-precommit-linter
rev: v1.10.0
hooks:
- id: conventional-precommit-linter # Lints commit messages for conventional format
- id: conventional-precommit-linter

- repo: https://github.com/codespell-project/codespell
rev: v2.3.0
hooks:
- id: codespell # Code spell checker
- id: codespell
args: ['--write-changes']
additional_dependencies: [tomli]

- repo: https://github.com/executablebooks/mdformat
rev: 0.7.17
hooks:
- id: mdformat
args: [--number] # Keep numbering for ordered lists
args: [--number]
additional_dependencies:
- mdformat-gfm # Support for GitHub Flavored Markdown (GFM), including tables, task lists, strikethroughs, and autolinks.
- mdformat-ruff # Formats Python code blocks in Markdown files according to the `ruff` linter's style.
- mdformat-simple-breaks # Ensures that single line breaks in Markdown are converted to `<br>`
- mdformat-gfm
- mdformat-ruff
- mdformat-simple-breaks

- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets
args:
- --base64-limit=4 # Level of entropy for base64 type strings
- --hex-limit=3 # Level of entropy for hex strings
- --base64-limit=4
- --hex-limit=3

- repo: https://github.com/lyz-code/yamlfix/
rev: 1.17.0
Expand All @@ -78,10 +78,9 @@ repos:
- id: update-changelog
files: ^pyproject\.toml$

# Local hooks
- repo: local
hooks:
- id: pip-compile # Generate locked requirements.txt for production (Dockerfile)
- id: pip-compile
name: compile requirements.txt
entry: bash -c 'pip-compile --strip-extras --output-file=requirements.txt pyproject.toml > /dev/null'
language: system
Expand Down
8 changes: 0 additions & 8 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,6 @@

---

## v0.1.0 (2024-09-07)

### ✨ New features

- init commit, project basic structure (from template commitizen) *(Tomas Sebestik - 61c03ec)*

---

**[Espressif Systems CO LTD. (2024)](https://www.espressif.com/)**

- [Commitizen tools plugin with Espressif code style](https://www.github.com/espressif/cz-plugin-espressif)
Expand Down
72 changes: 37 additions & 35 deletions czespressif/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
from dataclasses import fields
from functools import cached_property
from functools import total_ordering
from typing import Dict
from typing import List
from typing import Union
from typing import cast

from commitizen.config import read_cfg
from commitizen.defaults import Settings
Expand All @@ -26,26 +24,30 @@
class CommitType:
type: str # Key used as type in the commit header.
description: str # A human-readable description of the type.
heading: Union[str, None] = None # The resulting heading in the changelog for this type.
emoji: Union[str, None] = None # An optional emoji representing the type.
heading: str | None = None # The resulting heading in the changelog for this type.
emoji: str | None = None # An optional emoji representing the type.
changelog: bool = True # Whether this type should appear in the changelog or not.
question: bool = True # Whether this type should appear in the question choices.
bump: Union[INCREMENT, None] = None # Specifies the version bump category (e.g., 'MAJOR', 'MINOR', 'PATCH').
regex: Union[str, None] = None # An optional regular expression matching this type.
bump: INCREMENT | None = None # Specifies the version bump category (e.g., 'MAJOR', 'MINOR', 'PATCH').
regex: str | None = None # An optional regular expression matching this type.

def __str__(self) -> str:
return self.type

def __hash__(self):
def __hash__(self) -> int:
return hash(self.type)

def __eq__(self, other) -> bool:
return self._compare_key(other) == 0
def __eq__(self, other: object) -> bool:
if isinstance(other, CommitType):
return self._compare_key(other) == 0
return NotImplemented

def __lt__(self, other) -> bool:
return self._compare_key(other) < 0
def __lt__(self, other: object) -> bool:
if isinstance(other, CommitType):
return self._compare_key(other) < 0
return NotImplemented

def _compare_key(self, other) -> int:
def _compare_key(self, other: object) -> int:
"""Helper method for comparing with either CommitType or str."""
if isinstance(other, CommitType):
other_type = other.type.lower()
Expand All @@ -56,30 +58,30 @@ def _compare_key(self, other) -> int:
return (self.type.lower() > other_type) - (self.type.lower() < other_type)

@classmethod
def from_dict(cls, data: Dict) -> CommitType:
def from_dict(cls, data: dict) -> CommitType:
"""Creates a CommitType instance from a dictionary."""
valid_fields = {f.name for f in fields(cls)}
filtered_data = {k: v for k, v in data.items() if k in valid_fields}
return cls(**filtered_data)

@classmethod
def from_list(cls, lst: List[Dict]) -> List[CommitType]:
def from_list(cls, lst: list[dict]) -> list[CommitType]:
"""Creates a list of CommitType instances from a list of dictionaries."""
return [cls.from_dict(d) for d in lst]


class CzEspressifSettings(Settings):
types: Union[list[dict], None]
extra_types: Union[list[dict], None]
changelog_unreleased: Union[bool, None]
use_emoji: Union[bool, None]
changelog_title: Union[str, None]
changelog_header: Union[str, None]
changelog_footer: Union[str, None]
changelog_section_line: Union[bool, None]
changelog_show_commits: Union[bool, None]
changelog_show_authors: Union[bool, None]
release_notes_footer: Union[str, None]
types: list[dict] | None
extra_types: list[dict] | None
changelog_unreleased: bool | None
use_emoji: bool | None
changelog_title: str | None
changelog_header: str | None
changelog_footer: str | None
changelog_section_line: bool | None
changelog_show_commits: bool | None
changelog_show_authors: bool | None
release_notes_footer: str | None


@dataclass
Expand All @@ -104,36 +106,36 @@ def incremental(self) -> bool:

@property
def changelog_unreleased(self) -> bool:
return self.settings.get('changelog_unreleased', True)
return cast(bool, self.settings.get('changelog_unreleased', True))

@property
def use_emoji(self) -> bool:
return self.settings.get('use_emoji', True)
return cast(bool, self.settings.get('use_emoji', True))

@property
def changelog_title(self) -> str:
return self.settings.get('changelog_title', CHANGELOG_TITLE)
return cast(str, self.settings.get('changelog_title', CHANGELOG_TITLE))

@property
def changelog_header(self) -> str:
return self.settings.get('changelog_header', CHANGELOG_HEADER)
return cast(str, self.settings.get('changelog_header', CHANGELOG_HEADER))

@property
def changelog_footer(self) -> str:
return self.settings.get('changelog_footer', CHANGELOG_FOOTER)
return cast(str, self.settings.get('changelog_footer', CHANGELOG_FOOTER))

@property
def changelog_section_line(self) -> bool:
return self.settings.get('changelog_section_line', True)
return cast(bool, self.settings.get('changelog_section_line', True))

@property
def changelog_show_commits(self) -> bool:
return self.settings.get('changelog_show_commits', True)
return cast(bool, self.settings.get('changelog_show_commits', True))

@property
def changelog_show_authors(self) -> bool:
return self.settings.get('changelog_show_authors', True)
return cast(bool, self.settings.get('changelog_show_authors', True))

@property
def release_notes_footer(self) -> str:
return self.settings.get('release_notes_footer', None)
return cast(str, self.settings.get('release_notes_footer', ''))
27 changes: 13 additions & 14 deletions czespressif/czespressif.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from __future__ import annotations

import itertools
import re

from collections import OrderedDict
from collections.abc import Iterable
from typing import Any
from typing import Dict
from typing import Iterable
from typing import List
from typing import Union

from commitizen.cz.base import BaseCommitizen
from commitizen.cz.base import BaseConfig
Expand All @@ -30,8 +29,8 @@ def __init__(self, config: BaseConfig):
self.cze_config = CzEspressifConfig(config.settings)

@property
def known_types(self) -> Dict[str, CommitType]:
return dict(itertools.chain(((t.type, t) for t in self.cze_config.known_types)))
def known_types(self) -> dict[str, CommitType]:
return dict(itertools.chain((t.type, t) for t in self.cze_config.known_types))

@property
def re_known_types(self) -> str:
Expand All @@ -43,15 +42,15 @@ def changelog_pattern(self) -> str:
return rf'\A({re_known_types})(\(.+\))?(!)?'

@property
def change_type_map(self) -> Dict[str, str]:
def change_type_map(self) -> dict[str, str]:
return dict(
itertools.chain(
((t.type, f'{t.emoji + " " if self.cze_config.use_emoji and t.emoji else ""}{t.heading}') for t in self.cze_config.known_types if t.heading),
)
)

@property
def change_type_order(self) -> List[str]:
def change_type_order(self) -> list[str]:
return [
f'{commit_type.emoji} {commit_type.heading}' if self.cze_config.use_emoji and commit_type.emoji else commit_type.heading
for commit_type in self.cze_config.known_types
Expand All @@ -65,7 +64,7 @@ def bump_pattern(self) -> str:
return rf'^((({re_types})(\(.+\))?(!)?)|\w+!):'

@property
def bump_map(self) -> Dict[str, INCREMENT]:
def bump_map(self) -> dict[str, INCREMENT]:
"""
Mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
"""
Expand All @@ -77,7 +76,7 @@ def bump_map(self) -> Dict[str, INCREMENT]:
)

@property
def bump_map_major_version_zero(self) -> Dict[str, INCREMENT]:
def bump_map_major_version_zero(self) -> dict[str, INCREMENT]:
return OrderedDict((pattern, increment.replace('MAJOR', 'MINOR')) for pattern, increment in self.bump_map.items()) # type: ignore

@property
Expand All @@ -92,13 +91,13 @@ def commit_parser(self) -> str:
)

@property
def template_extras(self) -> Dict[str, Any]:
def template_extras(self) -> dict[str, Any]:
return {'config': self.cze_config, 'settings': self.cze_config.settings}

def questions(self) -> Questions:
return get_questions(self.cze_config)

def message(self, answers: Dict[str, Any]) -> str:
def message(self, answers: dict[str, Any]) -> str:
prefix = answers['type']
scope = answers['scope']
subject = answers['subject']
Expand Down Expand Up @@ -135,7 +134,7 @@ def wrap_problematic_parts(self, message: str) -> str:
message = re.sub(issue, lambda match: match.group(0).replace('_', r'\_'), message)
return message

def changelog_message_builder_hook(self, parsed_message: Dict[str, Any], commit: Any) -> Union[Dict[str, Any], Iterable[Dict[str, Any]], None]: # pylint: disable=unused-argument
def changelog_message_builder_hook(self, parsed_message: dict[str, Any], commit: Any) -> dict[str, Any] | Iterable[dict[str, Any]] | None: # pylint: disable=unused-argument
# Remap breaking changes type
if parsed_message.get('breaking'):
parsed_message['change_type'] = 'BREAKING CHANGE'
Expand All @@ -161,7 +160,7 @@ def changelog_message_builder_hook(self, parsed_message: Dict[str, Any], commit:

return parsed_message

def changelog_hook(self, full: str, partial: Union[str, None]) -> str:
def changelog_hook(self, full: str, partial: str | None) -> str:
"""Process resulting changelog to keep 1 empty line at the end of the file."""
changelog = partial or full
return changelog.rstrip() + '\n'
Expand Down
6 changes: 2 additions & 4 deletions czespressif/defaults.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from __future__ import annotations

from datetime import datetime
from typing import Dict
from typing import List
from typing import Literal

TYPES: List[Dict] = [ # this is order in changelog
TYPES: list[dict] = [ # this is order in changelog
{
'type': 'BREAKING CHANGE',
'description': 'Changes that are not backward-compatibles',
Expand Down Expand Up @@ -129,4 +127,4 @@
# Currently BUMP_MESSAGE not possible to define default here - if not provided from pyproject.toml, it will be commitizen default, not ours :(
BUMP_MESSAGE: str = 'change(bump): release $current_version → $new_version [skip-ci]'

ESCAPE_MARKDOWN_SEQ: List[str] = [r'_{', r'}_']
ESCAPE_MARKDOWN_SEQ: list[str] = [r'_{', r'}_']
4 changes: 2 additions & 2 deletions czespressif/example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List
from __future__ import annotations

from czespressif.config import CommitType

Expand All @@ -13,7 +13,7 @@
RESET = '\033[0m'


def build_example(types: List[CommitType], extra_types: List[CommitType]) -> str:
def build_example(types: list[CommitType], extra_types: list[CommitType]) -> str:
"""
'cz example' command output.
Generate an example guide for commit message schema and conventions.
Expand Down
Loading

0 comments on commit 8de6c1d

Please sign in to comment.