Skip to content

Commit a762c9e

Browse files
authored
Merge pull request #156 from commitizen-tools/fix-mypy-check
Fix mypy check
2 parents 7d4e3b9 + 906d1fb commit a762c9e

File tree

17 files changed

+118
-48
lines changed

17 files changed

+118
-48
lines changed

.flake8

Lines changed: 0 additions & 4 deletions
This file was deleted.

commitizen/bump.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,12 @@ def prerelease_generator(current_version: str, prerelease: Optional[str] = None)
6666
return ""
6767

6868
version = Version(current_version)
69-
new_prerelease_number: int = 0
70-
if version.is_prerelease and prerelease.startswith(version.pre[0]):
71-
prev_prerelease: int = list(version.pre)[1]
69+
# version.pre is needed for mypy check
70+
if version.is_prerelease and version.pre and prerelease.startswith(version.pre[0]):
71+
prev_prerelease: int = version.pre[1]
7272
new_prerelease_number = prev_prerelease + 1
73+
else:
74+
new_prerelease_number = 0
7375
pre_version = f"{prerelease}{new_prerelease_number}"
7476
return pre_version
7577

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

177179
major, minor, patch = version.release
178180
prerelease = ""
179-
if version.is_prerelease:
181+
# version.pre is needed for mypy check
182+
if version.is_prerelease and version.pre:
180183
prerelease = f"{version.pre[0]}{version.pre[1]}"
181184

182185
t = Template(tag_format)

commitizen/commands/check.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
22
import re
3-
from typing import Dict
3+
from typing import Dict, Optional
44

55
from commitizen import factory, git, out
66
from commitizen.config import BaseConfig
@@ -22,8 +22,8 @@ def __init__(self, config: BaseConfig, arguments: Dict[str, str], cwd=os.getcwd(
2222
the flags provided by the user
2323
2424
"""
25-
self.commit_msg_file: str = arguments.get("commit_msg_file")
26-
self.rev_range: str = arguments.get("rev_range")
25+
self.commit_msg_file: Optional[str] = arguments.get("commit_msg_file")
26+
self.rev_range: Optional[str] = arguments.get("rev_range")
2727

2828
self._valid_command_argument()
2929

@@ -76,4 +76,4 @@ def _get_commit_messages(self):
7676
def validate_commit_message(commit_msg: str, pattern: str) -> bool:
7777
if commit_msg.startswith("Merge") or commit_msg.startswith("Revert"):
7878
return True
79-
return re.match(pattern, commit_msg)
79+
return bool(re.match(pattern, commit_msg))

commitizen/config/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import warnings
22
from pathlib import Path
3-
from typing import Optional
3+
from typing import Optional, Union
44

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

32-
conf = IniConfig(data)
32+
conf = IniConfig(data=data, path=global_cfg)
3333
return conf
3434

3535

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

59+
_conf: Union[TomlConfig, IniConfig]
5960
if "toml" in filename.suffix:
6061
_conf = TomlConfig(data=data, path=filename)
6162
else:

commitizen/config/base_config.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
import warnings
2-
from typing import Optional
2+
from pathlib import Path
3+
from typing import Any, Dict, Optional, Union
34

45
from commitizen.defaults import DEFAULT_SETTINGS
56

67

78
class BaseConfig:
89
def __init__(self):
9-
self._settings: dict = DEFAULT_SETTINGS.copy()
10-
self._path: Optional[str] = None
10+
self._settings: Dict[str, Any] = DEFAULT_SETTINGS.copy()
11+
self._path: Optional[Path] = None
1112

1213
@property
13-
def settings(self) -> dict:
14+
def settings(self) -> Dict[str, Any]:
1415
return self._settings
1516

1617
@property
17-
def path(self) -> str:
18+
def path(self) -> Optional[Path]:
1819
return self._path
1920

2021
def set_key(self, key, value):
@@ -28,8 +29,8 @@ def set_key(self, key, value):
2829
def update(self, data: dict):
2930
self._settings.update(data)
3031

31-
def add_path(self, path: str):
32-
self._path = path
32+
def add_path(self, path: Union[str, Path]):
33+
self._path = Path(path)
3334

3435
def _parse_setting(self, data: str) -> dict:
3536
raise NotImplementedError()

commitizen/config/ini_config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import configparser
22
import json
33
import warnings
4+
from pathlib import Path
5+
from typing import Union
46

57
from .base_config import BaseConfig
68

79

810
class IniConfig(BaseConfig):
9-
def __init__(self, *, data: str, path: str):
11+
def __init__(self, *, data: str, path: Union[Path, str]):
1012
warnings.simplefilter("always", DeprecationWarning)
1113
warnings.warn(
1214
(

commitizen/config/toml_config.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
from pathlib import Path
2+
from typing import Union
3+
14
from tomlkit import exceptions, parse
25

36
from .base_config import BaseConfig
47

58

69
class TomlConfig(BaseConfig):
7-
def __init__(self, *, data: str, path: str):
10+
def __init__(self, *, data: str, path: Union[Path, str]):
811
super(TomlConfig, self).__init__()
912
self.is_empty_config = False
1013
self._parse_setting(data)

commitizen/cz/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
import importlib
22
import pkgutil
3+
from typing import Dict, Type
34

5+
from commitizen.cz.base import BaseCommitizen
46
from commitizen.cz.conventional_commits import ConventionalCommitsCz
57
from commitizen.cz.customize import CustomizeCommitsCz
68
from commitizen.cz.jira import JiraSmartCz
79

8-
registry = {
10+
registry: Dict[str, Type[BaseCommitizen]] = {
911
"cz_conventional_commits": ConventionalCommitsCz,
1012
"cz_jira": JiraSmartCz,
1113
"cz_customize": CustomizeCommitsCz,
1214
}
1315
plugins = {
14-
name: importlib.import_module(name).discover_this
16+
name: importlib.import_module(name).discover_this # type: ignore
1517
for finder, name, ispkg in pkgutil.iter_modules()
1618
if name.startswith("cz_")
1719
}

commitizen/cz/base.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
from prompt_toolkit.styles import Style, merge_styles
55

6+
from commitizen.config.base_config import BaseConfig
7+
68

79
class BaseCommitizen(metaclass=ABCMeta):
810
bump_pattern: Optional[str] = None
@@ -20,7 +22,7 @@ class BaseCommitizen(metaclass=ABCMeta):
2022
("disabled", "fg:#858585 italic"),
2123
]
2224

23-
def __init__(self, config: dict):
25+
def __init__(self, config: BaseConfig):
2426
self.config = config
2527
if not self.config.settings.get("style"):
2628
self.config.settings.update({"style": BaseCommitizen.default_style_config})
@@ -42,18 +44,18 @@ def style(self):
4244
]
4345
)
4446

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

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

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

57-
def info(self) -> str:
59+
def info(self) -> Optional[str]:
5860
"""Information about the standardized commit message."""
5961
raise NotImplementedError("Not Implemented yet")

commitizen/cz/conventional_commits/conventional_commits.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
from typing import Any, Dict, List
23

34
from commitizen import defaults
45
from commitizen.cz.base import BaseCommitizen
@@ -29,8 +30,8 @@ class ConventionalCommitsCz(BaseCommitizen):
2930
bump_pattern = defaults.bump_pattern
3031
bump_map = defaults.bump_map
3132

32-
def questions(self) -> list:
33-
questions = [
33+
def questions(self) -> List[Dict[str, Any]]:
34+
questions: List[Dict[str, Any]] = [
3435
{
3536
"type": "list",
3637
"name": "prefix",

commitizen/cz/customize/customize.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
try:
22
from jinja2 import Template
33
except ImportError:
4-
from string import Template
4+
from string import Template # type: ignore
55

6-
from commitizen import defaults
6+
from typing import Any, Dict, List, Optional
7+
8+
from commitizen import defaults, out
79
from commitizen.config import BaseConfig
810
from commitizen.cz.base import BaseCommitizen
11+
from commitizen.error_codes import MISSING_CONFIG
912

1013
__all__ = ["CustomizeCommitsCz"]
1114

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

1720
def __init__(self, config: BaseConfig):
1821
super(CustomizeCommitsCz, self).__init__(config)
19-
self.custom_settings = self.config.settings.get("customize")
22+
23+
if "customize" not in self.config.settings:
24+
out.error("fatal: customize is not set in configuration file.")
25+
raise SystemExit(MISSING_CONFIG)
26+
self.custom_settings = self.config.settings["customize"]
2027

2128
custom_bump_pattern = self.custom_settings.get("bump_pattern")
2229
if custom_bump_pattern:
@@ -26,23 +33,23 @@ def __init__(self, config: BaseConfig):
2633
if custom_bump_map:
2734
self.bump_map = custom_bump_map
2835

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

3239
def message(self, answers: dict) -> str:
3340
message_template = Template(self.custom_settings.get("message_template"))
3441
if getattr(Template, "substitute", None):
35-
return message_template.substitute(**answers)
42+
return message_template.substitute(**answers) # type: ignore
3643
else:
3744
return message_template.render(**answers)
3845

39-
def example(self) -> str:
46+
def example(self) -> Optional[str]:
4047
return self.custom_settings.get("example")
4148

42-
def schema(self) -> str:
49+
def schema(self) -> Optional[str]:
4350
return self.custom_settings.get("schema")
4451

45-
def info(self) -> str:
52+
def info(self) -> Optional[str]:
4653
info_path = self.custom_settings.get("info_path")
4754
info = self.custom_settings.get("info")
4855
if info_path:
@@ -51,3 +58,4 @@ def info(self) -> str:
5158
return content
5259
elif info:
5360
return info
61+
return None

commitizen/cz/jira/jira.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import os
2+
from typing import Any, Dict, List
23

34
from commitizen.cz.base import BaseCommitizen
45

56
__all__ = ["JiraSmartCz"]
67

78

89
class JiraSmartCz(BaseCommitizen):
9-
def questions(self):
10+
def questions(self) -> List[Dict[str, Any]]:
1011
questions = [
1112
{
1213
"type": "input",
@@ -43,7 +44,7 @@ def questions(self):
4344
]
4445
return questions
4546

46-
def message(self, answers):
47+
def message(self, answers) -> str:
4748
return " ".join(
4849
filter(
4950
bool,
@@ -57,7 +58,7 @@ def message(self, answers):
5758
)
5859
)
5960

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

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

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

75-
def info(self):
76+
def info(self) -> str:
7677
dir_path = os.path.dirname(os.path.realpath(__file__))
7778
filepath = os.path.join(dir_path, "jira_info.txt")
7879
with open(filepath, "r") as f:

commitizen/defaults.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
from collections import OrderedDict
2+
from typing import Any, Dict
23

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

9-
DEFAULT_SETTINGS: dict = {
10+
DEFAULT_SETTINGS: Dict[str, Any] = {
1011
"name": "cz_conventional_commits",
1112
"version": None,
1213
"version_files": [],

commitizen/error_codes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
# Config
55
NOT_A_GIT_PROJECT = 2
6+
MISSING_CONFIG = 15
67

78
# Bump
89
NO_COMMITS_FOUND = 3

scripts/test

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ fi
88
${PREFIX}pytest --cov-report term-missing --cov-report=xml:coverage.xml --cov=commitizen tests/
99
${PREFIX}black commitizen tests --check
1010
${PREFIX}isort --recursive --check-only commitizen tests
11-
${PREFIX}flake8 --max-line-length=88 commitizen/ tests/
11+
${PREFIX}flake8 commitizen/ tests/
12+
${PREFIX}mypy commitizen/ tests/

0 commit comments

Comments
 (0)