Skip to content

Commit b5b0709

Browse files
committed
refactor: use custom exception for error handling
the error code used is embedded into these exceptions
1 parent a108872 commit b5b0709

16 files changed

+171
-85
lines changed

commitizen/bump.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
bump_message,
1616
bump_pattern,
1717
)
18-
from commitizen.error_codes import CURRENT_VERSION_NOT_FOUND
18+
from commitizen.exceptions import CurrentVersionNotFoundError
1919
from commitizen.git import GitCommit
2020

2121

@@ -167,7 +167,7 @@ def update_version_in_files(
167167
"The version defined in commitizen configuration and the ones in "
168168
"version_files are possibly inconsistent."
169169
)
170-
raise SystemExit(CURRENT_VERSION_NOT_FOUND)
170+
raise CurrentVersionNotFoundError()
171171

172172
# Write the file out again
173173
with open(filepath, "w") as file:

commitizen/cli.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from decli import cli
77

88
from commitizen import commands, config, out
9+
from commitizen.exceptions import CommitizenError
910

1011
logger = logging.getLogger(__name__)
1112
data = {
@@ -237,6 +238,17 @@
237238
},
238239
}
239240

241+
original_excepthook = sys.excepthook
242+
243+
244+
def commitizen_excepthook(type, value, tracekback):
245+
original_excepthook(type, value, tracekback)
246+
if isinstance(value, CommitizenError):
247+
sys.exit(value.exit_code)
248+
249+
250+
sys.excepthook = commitizen_excepthook
251+
240252

241253
def main():
242254
conf = config.read_cfg()

commitizen/commands/bump.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
from commitizen import bump, factory, git, out
77
from commitizen.commands.changelog import Changelog
88
from commitizen.config import BaseConfig
9-
from commitizen.error_codes import (
10-
COMMIT_FAILED,
11-
NO_COMMITS_FOUND,
12-
NO_PATTERN_MAP,
13-
NO_VERSION_SPECIFIED,
14-
TAG_FAILED,
9+
from commitizen.exceptions import (
10+
CommitFailedError,
11+
NoCommitsFoundError,
12+
NoPatternMapError,
13+
NoVersionSpecifiedError,
14+
TagFailedError,
1515
)
1616

1717

@@ -57,7 +57,7 @@ def find_increment(self, commits: List[git.GitCommit]) -> Optional[str]:
5757
bump_map = self.cz.bump_map
5858
if not bump_map or not bump_pattern:
5959
out.error(f"'{self.config.settings['name']}' rule does not support bump")
60-
raise SystemExit(NO_PATTERN_MAP)
60+
raise NoPatternMapError()
6161
increment = bump.find_increment(
6262
commits, regex=bump_pattern, increments_map=bump_map
6363
)
@@ -73,7 +73,7 @@ def __call__(self): # noqa: C901
7373
"Check if current version is specified in config file, like:\n"
7474
"version = 0.4.3\n"
7575
)
76-
raise SystemExit(NO_VERSION_SPECIFIED)
76+
raise NoVersionSpecifiedError()
7777

7878
# Initialize values from sources (conf)
7979
current_version: str = self.config.settings["version"]
@@ -102,7 +102,7 @@ def __call__(self): # noqa: C901
102102
# Unless we previously had a prerelease.
103103
if not commits and not current_version_instance.is_prerelease:
104104
out.error("[NO_COMMITS_FOUND]\n" "No new commits found.")
105-
raise SystemExit(NO_COMMITS_FOUND)
105+
raise NoCommitsFoundError()
106106

107107
if increment is None:
108108
increment = self.find_increment(commits)
@@ -155,11 +155,11 @@ def __call__(self): # noqa: C901
155155
c = git.commit(message, args=self._get_commit_args())
156156
if c.err:
157157
out.error('git.commit error: "{}"'.format(c.err.strip()))
158-
raise SystemExit(COMMIT_FAILED)
158+
raise CommitFailedError()
159159
c = git.tag(new_tag_version)
160160
if c.err:
161161
out.error(c.err)
162-
raise SystemExit(TAG_FAILED)
162+
raise TagFailedError()
163163
out.success("Done!")
164164

165165
def _get_commit_args(self):

commitizen/commands/changelog.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55

66
from commitizen import changelog, factory, git, out
77
from commitizen.config import BaseConfig
8-
from commitizen.error_codes import NO_COMMITS_FOUND, NO_PATTERN_MAP, NO_REVISION
8+
from commitizen.exceptions import (
9+
NoCommitsFoundError,
10+
NoPatternMapError,
11+
NoRevisionError,
12+
)
913
from commitizen.git import GitTag
1014

1115

@@ -51,9 +55,9 @@ def _find_incremental_rev(self, latest_version: str, tags: List[GitTag]) -> str:
5155
try:
5256
score, tag = max(tag_ratio, key=itemgetter(0))
5357
except ValueError:
54-
raise SystemExit(NO_REVISION)
58+
raise NoRevisionError()
5559
if score < SIMILARITY_THRESHOLD:
56-
raise SystemExit(NO_REVISION)
60+
raise NoRevisionError()
5761
start_rev = tag.name
5862
return start_rev
5963

@@ -73,7 +77,7 @@ def __call__(self):
7377
out.error(
7478
f"'{self.config.settings['name']}' rule does not support changelog"
7579
)
76-
raise SystemExit(NO_PATTERN_MAP)
80+
raise NoPatternMapError()
7781

7882
tags = git.get_tags()
7983
if not tags:
@@ -88,7 +92,7 @@ def __call__(self):
8892
commits = git.get_commits(start=start_rev, args="--author-date-order")
8993
if not commits:
9094
out.error("No commits found")
91-
raise SystemExit(NO_COMMITS_FOUND)
95+
raise NoCommitsFoundError()
9296

9397
tree = changelog.generate_tree_from_commits(
9498
commits,

commitizen/commands/check.py

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

66
from commitizen import factory, git, out
77
from commitizen.config import BaseConfig
8-
from commitizen.error_codes import INVALID_COMMIT_MSG, NO_COMMITS_FOUND
8+
from commitizen.exceptions import InvalidCommitMessageError, NoCommitsFoundError
99

1010

1111
class Check:
@@ -46,7 +46,7 @@ def __call__(self):
4646
commit_msgs = self._get_commit_messages()
4747
if not commit_msgs:
4848
warnings.warn(f"No commit found with range: '{self.rev_range}'")
49-
raise SystemExit(NO_COMMITS_FOUND)
49+
raise NoCommitsFoundError()
5050

5151
pattern = self.cz.schema_pattern()
5252
for commit_msg in commit_msgs:
@@ -57,7 +57,7 @@ def __call__(self):
5757
f"commit: {commit_msg}\n"
5858
f"pattern: {pattern}"
5959
)
60-
raise SystemExit(INVALID_COMMIT_MSG)
60+
raise InvalidCommitMessageError()
6161
out.success("Commit validation: successful!")
6262

6363
def _get_commit_messages(self):

commitizen/commands/commit.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
from commitizen import factory, git, out
88
from commitizen.config import BaseConfig
99
from commitizen.cz.exceptions import CzException
10-
from commitizen.error_codes import (
11-
COMMIT_ERROR,
12-
CUSTOM_ERROR,
13-
NO_ANSWERS,
14-
NO_COMMIT_BACKUP,
15-
NOTHING_TO_COMMIT,
10+
from commitizen.exceptions import (
11+
CommitError,
12+
CustomError,
13+
NoAnswersError,
14+
NoCommitBackupError,
15+
NothingToCommitError,
1616
)
1717

1818

@@ -29,7 +29,7 @@ def read_backup_message(self) -> str:
2929
# Check the commit backup file exists
3030
if not os.path.isfile(self.temp_file):
3131
out.error("No commit backup found")
32-
raise SystemExit(NO_COMMIT_BACKUP)
32+
raise NoCommitBackupError()
3333

3434
# Read commit message from backup
3535
with open(self.temp_file, "r") as f:
@@ -45,19 +45,19 @@ def prompt_commit_questions(self) -> str:
4545
root_err = err.__context__
4646
if isinstance(root_err, CzException):
4747
out.error(root_err.__str__())
48-
raise SystemExit(CUSTOM_ERROR)
48+
raise CustomError()
4949
raise err
5050

5151
if not answers:
52-
raise SystemExit(NO_ANSWERS)
52+
raise NoAnswersError()
5353
return cz.message(answers)
5454

5555
def __call__(self):
5656
dry_run: bool = self.arguments.get("dry_run")
5757

5858
if git.is_staging_clean() and not dry_run:
5959
out.write("No files added to staging!")
60-
raise SystemExit(NOTHING_TO_COMMIT)
60+
raise NothingToCommitError()
6161

6262
retry: bool = self.arguments.get("retry")
6363

@@ -69,7 +69,7 @@ def __call__(self):
6969
out.info(f"\n{m}\n")
7070

7171
if dry_run:
72-
raise SystemExit(NOTHING_TO_COMMIT)
72+
raise NothingToCommitError()
7373

7474
c = git.commit(m)
7575

@@ -80,7 +80,7 @@ def __call__(self):
8080
with open(self.temp_file, "w") as f:
8181
f.write(m)
8282

83-
raise SystemExit(COMMIT_ERROR)
83+
raise CommitError()
8484

8585
if "nothing added" in c.out or "no changes added to commit" in c.out:
8686
out.error(c.out)

commitizen/config/__init__.py

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

5-
from commitizen import defaults, git, out
6-
from commitizen.error_codes import NOT_A_GIT_PROJECT
5+
from commitizen import defaults, git
6+
from commitizen.exceptions import NotAGitProjectError
77

88
from .base_config import BaseConfig
99
from .ini_config import IniConfig
@@ -38,10 +38,7 @@ def read_cfg() -> BaseConfig:
3838

3939
git_project_root = git.find_git_project_root()
4040
if not git_project_root:
41-
out.error(
42-
"fatal: not a git repository (or any of the parent directories): .git"
43-
)
44-
raise SystemExit(NOT_A_GIT_PROJECT)
41+
raise NotAGitProjectError()
4542

4643
cfg_paths = (
4744
path / Path(filename)

commitizen/cz/customize/customize.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55

66
from typing import Any, Dict, List, Optional
77

8-
from commitizen import defaults, out
8+
from commitizen import defaults
99
from commitizen.config import BaseConfig
1010
from commitizen.cz.base import BaseCommitizen
11-
from commitizen.error_codes import MISSING_CONFIG
11+
from commitizen.exceptions import MissingConfigError
1212

1313
__all__ = ["CustomizeCommitsCz"]
1414

@@ -21,8 +21,7 @@ def __init__(self, config: BaseConfig):
2121
super(CustomizeCommitsCz, self).__init__(config)
2222

2323
if "customize" not in self.config.settings:
24-
out.error("fatal: customize is not set in configuration file.")
25-
raise SystemExit(MISSING_CONFIG)
24+
raise MissingConfigError()
2625
self.custom_settings = self.config.settings["customize"]
2726

2827
custom_bump_pattern = self.custom_settings.get("bump_pattern")

commitizen/error_codes.py

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

0 commit comments

Comments
 (0)