Skip to content

Fix mypy check #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Apr 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions .flake8

This file was deleted.

11 changes: 7 additions & 4 deletions commitizen/bump.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,12 @@ def prerelease_generator(current_version: str, prerelease: Optional[str] = None)
return ""

version = Version(current_version)
new_prerelease_number: int = 0
if version.is_prerelease and prerelease.startswith(version.pre[0]):
prev_prerelease: int = list(version.pre)[1]
# version.pre is needed for mypy check
if version.is_prerelease and version.pre and prerelease.startswith(version.pre[0]):
prev_prerelease: int = version.pre[1]
new_prerelease_number = prev_prerelease + 1
else:
new_prerelease_number = 0
pre_version = f"{prerelease}{new_prerelease_number}"
return pre_version

Expand Down Expand Up @@ -176,7 +178,8 @@ def create_tag(version: Union[Version, str], tag_format: Optional[str] = None):

major, minor, patch = version.release
prerelease = ""
if version.is_prerelease:
# version.pre is needed for mypy check
if version.is_prerelease and version.pre:
prerelease = f"{version.pre[0]}{version.pre[1]}"

t = Template(tag_format)
Expand Down
8 changes: 4 additions & 4 deletions commitizen/commands/check.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
import re
from typing import Dict
from typing import Dict, Optional

from commitizen import factory, git, out
from commitizen.config import BaseConfig
Expand All @@ -22,8 +22,8 @@ def __init__(self, config: BaseConfig, arguments: Dict[str, str], cwd=os.getcwd(
the flags provided by the user

"""
self.commit_msg_file: str = arguments.get("commit_msg_file")
self.rev_range: str = arguments.get("rev_range")
self.commit_msg_file: Optional[str] = arguments.get("commit_msg_file")
self.rev_range: Optional[str] = arguments.get("rev_range")

self._valid_command_argument()

Expand Down Expand Up @@ -76,4 +76,4 @@ def _get_commit_messages(self):
def validate_commit_message(commit_msg: str, pattern: str) -> bool:
if commit_msg.startswith("Merge") or commit_msg.startswith("Revert"):
return True
return re.match(pattern, commit_msg)
return bool(re.match(pattern, commit_msg))
5 changes: 3 additions & 2 deletions commitizen/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import warnings
from pathlib import Path
from typing import Optional
from typing import Optional, Union

from commitizen import defaults, git, out
from commitizen.error_codes import NOT_A_GIT_PROJECT
Expand Down Expand Up @@ -29,7 +29,7 @@ def load_global_conf() -> Optional[IniConfig]:
with open(global_cfg, "r") as f:
data = f.read()

conf = IniConfig(data)
conf = IniConfig(data=data, path=global_cfg)
return conf


Expand All @@ -56,6 +56,7 @@ def read_cfg() -> BaseConfig:
with open(filename, "r") as f:
data: str = f.read()

_conf: Union[TomlConfig, IniConfig]
if "toml" in filename.suffix:
_conf = TomlConfig(data=data, path=filename)
else:
Expand Down
15 changes: 8 additions & 7 deletions commitizen/config/base_config.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import warnings
from typing import Optional
from pathlib import Path
from typing import Any, Dict, Optional, Union

from commitizen.defaults import DEFAULT_SETTINGS


class BaseConfig:
def __init__(self):
self._settings: dict = DEFAULT_SETTINGS.copy()
self._path: Optional[str] = None
self._settings: Dict[str, Any] = DEFAULT_SETTINGS.copy()
self._path: Optional[Path] = None

@property
def settings(self) -> dict:
def settings(self) -> Dict[str, Any]:
return self._settings

@property
def path(self) -> str:
def path(self) -> Optional[Path]:
return self._path

def set_key(self, key, value):
Expand All @@ -28,8 +29,8 @@ def set_key(self, key, value):
def update(self, data: dict):
self._settings.update(data)

def add_path(self, path: str):
self._path = path
def add_path(self, path: Union[str, Path]):
self._path = Path(path)

def _parse_setting(self, data: str) -> dict:
raise NotImplementedError()
Expand Down
4 changes: 3 additions & 1 deletion commitizen/config/ini_config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import configparser
import json
import warnings
from pathlib import Path
from typing import Union

from .base_config import BaseConfig


class IniConfig(BaseConfig):
def __init__(self, *, data: str, path: str):
def __init__(self, *, data: str, path: Union[Path, str]):
warnings.simplefilter("always", DeprecationWarning)
warnings.warn(
(
Expand Down
5 changes: 4 additions & 1 deletion commitizen/config/toml_config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from pathlib import Path
from typing import Union

from tomlkit import exceptions, parse

from .base_config import BaseConfig


class TomlConfig(BaseConfig):
def __init__(self, *, data: str, path: str):
def __init__(self, *, data: str, path: Union[Path, str]):
super(TomlConfig, self).__init__()
self.is_empty_config = False
self._parse_setting(data)
Expand Down
6 changes: 4 additions & 2 deletions commitizen/cz/__init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import importlib
import pkgutil
from typing import Dict, Type

from commitizen.cz.base import BaseCommitizen
from commitizen.cz.conventional_commits import ConventionalCommitsCz
from commitizen.cz.customize import CustomizeCommitsCz
from commitizen.cz.jira import JiraSmartCz

registry = {
registry: Dict[str, Type[BaseCommitizen]] = {
"cz_conventional_commits": ConventionalCommitsCz,
"cz_jira": JiraSmartCz,
"cz_customize": CustomizeCommitsCz,
}
plugins = {
name: importlib.import_module(name).discover_this
name: importlib.import_module(name).discover_this # type: ignore
for finder, name, ispkg in pkgutil.iter_modules()
if name.startswith("cz_")
}
Expand Down
12 changes: 7 additions & 5 deletions commitizen/cz/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from prompt_toolkit.styles import Style, merge_styles

from commitizen.config.base_config import BaseConfig


class BaseCommitizen(metaclass=ABCMeta):
bump_pattern: Optional[str] = None
Expand All @@ -20,7 +22,7 @@ class BaseCommitizen(metaclass=ABCMeta):
("disabled", "fg:#858585 italic"),
]

def __init__(self, config: dict):
def __init__(self, config: BaseConfig):
self.config = config
if not self.config.settings.get("style"):
self.config.settings.update({"style": BaseCommitizen.default_style_config})
Expand All @@ -42,18 +44,18 @@ def style(self):
]
)

def example(self) -> str:
def example(self) -> Optional[str]:
"""Example of the commit message."""
raise NotImplementedError("Not Implemented yet")

def schema(self) -> str:
def schema(self) -> Optional[str]:
"""Schema definition of the commit message."""
raise NotImplementedError("Not Implemented yet")

def schema_pattern(self) -> str:
def schema_pattern(self) -> Optional[str]:
"""Regex matching the schema used for message validation"""
raise NotImplementedError("Not Implemented yet")

def info(self) -> str:
def info(self) -> Optional[str]:
"""Information about the standardized commit message."""
raise NotImplementedError("Not Implemented yet")
5 changes: 3 additions & 2 deletions commitizen/cz/conventional_commits/conventional_commits.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from typing import Any, Dict, List

from commitizen import defaults
from commitizen.cz.base import BaseCommitizen
Expand Down Expand Up @@ -29,8 +30,8 @@ class ConventionalCommitsCz(BaseCommitizen):
bump_pattern = defaults.bump_pattern
bump_map = defaults.bump_map

def questions(self) -> list:
questions = [
def questions(self) -> List[Dict[str, Any]]:
questions: List[Dict[str, Any]] = [
{
"type": "list",
"name": "prefix",
Expand Down
24 changes: 16 additions & 8 deletions commitizen/cz/customize/customize.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
try:
from jinja2 import Template
except ImportError:
from string import Template
from string import Template # type: ignore

from commitizen import defaults
from typing import Any, Dict, List, Optional

from commitizen import defaults, out
from commitizen.config import BaseConfig
from commitizen.cz.base import BaseCommitizen
from commitizen.error_codes import MISSING_CONFIG

__all__ = ["CustomizeCommitsCz"]

Expand All @@ -16,7 +19,11 @@ class CustomizeCommitsCz(BaseCommitizen):

def __init__(self, config: BaseConfig):
super(CustomizeCommitsCz, self).__init__(config)
self.custom_settings = self.config.settings.get("customize")

if "customize" not in self.config.settings:
out.error("fatal: customize is not set in configuration file.")
raise SystemExit(MISSING_CONFIG)
self.custom_settings = self.config.settings["customize"]

custom_bump_pattern = self.custom_settings.get("bump_pattern")
if custom_bump_pattern:
Expand All @@ -26,23 +33,23 @@ def __init__(self, config: BaseConfig):
if custom_bump_map:
self.bump_map = custom_bump_map

def questions(self) -> list:
def questions(self) -> List[Dict[str, Any]]:
return self.custom_settings.get("questions")

def message(self, answers: dict) -> str:
message_template = Template(self.custom_settings.get("message_template"))
if getattr(Template, "substitute", None):
return message_template.substitute(**answers)
return message_template.substitute(**answers) # type: ignore
else:
return message_template.render(**answers)

def example(self) -> str:
def example(self) -> Optional[str]:
return self.custom_settings.get("example")

def schema(self) -> str:
def schema(self) -> Optional[str]:
return self.custom_settings.get("schema")

def info(self) -> str:
def info(self) -> Optional[str]:
info_path = self.custom_settings.get("info_path")
info = self.custom_settings.get("info")
if info_path:
Expand All @@ -51,3 +58,4 @@ def info(self) -> str:
return content
elif info:
return info
return None
11 changes: 6 additions & 5 deletions commitizen/cz/jira/jira.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import os
from typing import Any, Dict, List

from commitizen.cz.base import BaseCommitizen

__all__ = ["JiraSmartCz"]


class JiraSmartCz(BaseCommitizen):
def questions(self):
def questions(self) -> List[Dict[str, Any]]:
questions = [
{
"type": "input",
Expand Down Expand Up @@ -43,7 +44,7 @@ def questions(self):
]
return questions

def message(self, answers):
def message(self, answers) -> str:
return " ".join(
filter(
bool,
Expand All @@ -57,7 +58,7 @@ def message(self, answers):
)
)

def example(self):
def example(self) -> str:
return (
"JRA-34 #comment corrected indent issue\n"
"JRA-35 #time 1w 2d 4h 30m Total work logged\n"
Expand All @@ -66,13 +67,13 @@ def example(self):
"ahead of schedule"
)

def schema(self):
def schema(self) -> str:
return "<ignored text> <ISSUE_KEY> <ignored text> #<COMMAND> <optional COMMAND_ARGUMENTS>" # noqa

def schema_pattern(self) -> str:
return r".*[A-Z]{2,}\-[0-9]+( #| .* #).+( #.+)*"

def info(self):
def info(self) -> str:
dir_path = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(dir_path, "jira_info.txt")
with open(filepath, "r") as f:
Expand Down
3 changes: 2 additions & 1 deletion commitizen/defaults.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from collections import OrderedDict
from typing import Any, Dict

name: str = "cz_conventional_commits"
# TODO: .cz, setup.cfg, .cz.cfg should be removed in 2.0
long_term_support_config_files: list = ["pyproject.toml", ".cz.toml"]
deprcated_config_files: list = [".cz", "setup.cfg", ".cz.cfg"]
config_files: list = long_term_support_config_files + deprcated_config_files

DEFAULT_SETTINGS: dict = {
DEFAULT_SETTINGS: Dict[str, Any] = {
"name": "cz_conventional_commits",
"version": None,
"version_files": [],
Expand Down
1 change: 1 addition & 0 deletions commitizen/error_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# Config
NOT_A_GIT_PROJECT = 2
MISSING_CONFIG = 15

# Bump
NO_COMMITS_FOUND = 3
Expand Down
3 changes: 2 additions & 1 deletion scripts/test
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ fi
${PREFIX}pytest --cov-report term-missing --cov-report=xml:coverage.xml --cov=commitizen tests/
${PREFIX}black commitizen tests --check
${PREFIX}isort --recursive --check-only commitizen tests
${PREFIX}flake8 --max-line-length=88 commitizen/ tests/
${PREFIX}flake8 commitizen/ tests/
${PREFIX}mypy commitizen/ tests/
Loading