Skip to content

Commit 80105fb

Browse files
committed
refactor: removed delegator, added decli and many tests
1 parent a960084 commit 80105fb

File tree

13 files changed

+327
-186
lines changed

13 files changed

+327
-186
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ venv.bak/
105105
.mypy_cache/
106106

107107
.vscode/
108+
*.bak
108109

109110
# build
110-
poetry.lock
111+
poetry.lock

commitizen/__init__.py

Lines changed: 13 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,23 @@
1-
import sys
21
import logging
32
import logging.config
4-
from commitizen.cz import registry
5-
from commitizen.cz.base import BaseCommitizen # noqa
6-
from commitizen.__version__ import __version__
7-
3+
from commitizen.cz.base import BaseCommitizen
84

95
LOGGING = {
10-
'version': 1,
11-
'disable_existing_loggers': False,
12-
'formatters': {
13-
'standard': {
14-
'format': '%(message)s'
15-
},
16-
},
17-
'handlers': {
18-
'default': {
19-
'level': 'DEBUG',
20-
'formatter': 'standard',
21-
'class': 'logging.StreamHandler',
6+
"version": 1,
7+
"disable_existing_loggers": True,
8+
"formatters": {"standard": {"format": "%(message)s"}},
9+
"handlers": {
10+
"default": {
11+
"level": "DEBUG",
12+
"formatter": "standard",
13+
"class": "logging.StreamHandler",
2214
}
2315
},
24-
'loggers': {
25-
'commitizen': {
26-
'handlers': ['default'],
27-
'level': 'INFO',
28-
'propagate': True
29-
}
30-
}
16+
"loggers": {
17+
"commitizen": {"handlers": ["default"], "level": "INFO", "propagate": True}
18+
},
3119
}
3220

3321
logging.config.dictConfig(LOGGING)
34-
logger = logging.getLogger(__name__)
35-
36-
37-
def registered(*args, **kwargs):
38-
_r = '\n'.join(registry.keys())
39-
logger.info(_r)
40-
41-
42-
name = None
43-
44-
45-
def commiter():
46-
"""Loaded commitizen.
47-
48-
:rtype: instance of implemented BaseCommitizen
49-
"""
50-
global name
51-
try:
52-
_cz = registry[name]()
53-
except KeyError:
54-
msg_error = ('The commiter has not been found in the system.\n\n'
55-
'Try running \'pip install {name}\'\n')
56-
logger.info(msg_error.format(name=name))
57-
sys.exit(1)
58-
else:
59-
return _cz
60-
61-
62-
def set_commiter(new_name):
63-
global name
64-
logger.debug('Updating commiter name')
65-
name = new_name
66-
67-
68-
def show_example(args):
69-
_commiter = commiter()
70-
_commiter.show_example()
71-
72-
73-
def show_info(args):
74-
_commiter = commiter()
75-
_commiter.show_info()
76-
77-
78-
def show_schema(args):
79-
_commiter = commiter()
80-
_commiter.show_schema()
81-
82-
83-
def run(args):
84-
_commiter = commiter()
85-
_commiter.run()
86-
8722

88-
def version():
89-
logger.info(__version__)
23+
__all__ = ["BaseCommitizen"]

commitizen/application.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import logging
2+
from typing import Optional
3+
from commitizen.cz import registry
4+
from commitizen.__version__ import __version__
5+
6+
logger = logging.getLogger(__name__)
7+
8+
9+
class Application:
10+
name: Optional[str] = None
11+
12+
def __init__(self, name: str):
13+
self.name = name
14+
15+
@property
16+
def cz(self):
17+
try:
18+
_cz = registry[self.name]()
19+
except KeyError:
20+
msg_error = (
21+
"The commiter has not been found in the system.\n\n"
22+
"Try running 'pip install {name}'\n"
23+
)
24+
logger.info(msg_error.format(name=self.name))
25+
raise SystemExit(1)
26+
else:
27+
return _cz
28+
29+
@property
30+
def version(self):
31+
return __version__
32+
33+
def detected_cz(*args, **kwargs):
34+
print("\n".join(registry.keys()))

commitizen/cli.py

Lines changed: 68 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -3,69 +3,70 @@
33
import sys
44
import logging
55
import argparse
6+
from decli import cli
67
from pathlib import Path
78
from configparser import RawConfigParser, NoSectionError
8-
from commitizen import (
9-
registered,
10-
run,
11-
set_commiter,
12-
show_example,
13-
show_info,
14-
show_schema,
15-
version,
16-
)
9+
from commitizen.application import Application
10+
from commitizen import deafults
1711

1812

1913
logger = logging.getLogger(__name__)
20-
21-
22-
def get_parser(config):
23-
description = (
14+
data = {
15+
"prog": "cz",
16+
"description": (
2417
"Commitizen is a cli tool to generate conventional commits.\n"
2518
"For more information about the topic go to "
2619
"https://conventionalcommits.org/"
27-
)
28-
29-
formater = argparse.RawDescriptionHelpFormatter
30-
parser = argparse.ArgumentParser(
31-
prog="cz", description=description, formatter_class=formater
32-
)
33-
parser.set_defaults(func=run)
34-
parser.add_argument(
35-
"--debug", action="store_true", default=False, help="use debug mode"
36-
)
37-
parser.add_argument(
38-
"-n", "--name", default=config.get("name"), help="use the given commitizen"
39-
)
40-
parser.add_argument(
41-
"--version",
42-
action="store_true",
43-
default=False,
44-
help="get the version of the installed commitizen",
45-
)
46-
47-
subparser = parser.add_subparsers(title="commands")
48-
49-
lscz = subparser.add_parser("ls", help="show available commitizens")
50-
lscz.set_defaults(func=registered)
51-
52-
commit = subparser.add_parser("commit", aliases=["c"], help="create new commit")
53-
commit.set_defaults(func=run)
54-
55-
example = subparser.add_parser("example", help="show commit example")
56-
example.set_defaults(func=show_example)
57-
58-
info = subparser.add_parser("info", help="show information about the cz")
59-
info.set_defaults(func=show_info)
60-
61-
schema = subparser.add_parser("schema", help="show commit schema")
62-
schema.set_defaults(func=show_schema)
63-
64-
return parser
20+
),
21+
"formatter_class": argparse.RawDescriptionHelpFormatter,
22+
"arguments": [
23+
{"name": "--debug", "action": "store_true", "help": "use debug mode"},
24+
{
25+
"name": ["-n", "--name"],
26+
"default": deafults.NAME,
27+
"help": "use the given commitizen",
28+
},
29+
{
30+
"name": ["--version"],
31+
"action": "store_true",
32+
"help": "get the version of the installed commitizen",
33+
},
34+
],
35+
"subcommands": {
36+
"title": "commands",
37+
"commands": [
38+
{
39+
"name": "ls",
40+
"help": "show available commitizens",
41+
"func": lambda app: app.detected_cz,
42+
},
43+
{
44+
"name": ["commit", "c"],
45+
"help": "create new commit",
46+
"func": lambda app: app.cz.run,
47+
},
48+
{
49+
"name": "example",
50+
"help": "show commit example",
51+
"func": lambda app: app.cz.show_example,
52+
},
53+
{
54+
"name": "info",
55+
"help": "show information about the cz",
56+
"func": lambda app: app.cz.show_info,
57+
},
58+
{
59+
"name": "schema",
60+
"help": "show commit schema",
61+
"func": lambda app: app.cz.show_schema,
62+
},
63+
],
64+
},
65+
}
6566

6667

6768
def load_cfg():
68-
defaults = {"name": "cz_conventional_commits"}
69+
settings = {"name": deafults.NAME}
6970
config = RawConfigParser("")
7071
home = str(Path.home())
7172

@@ -86,26 +87,35 @@ def load_cfg():
8687
log_config = io.StringIO()
8788
config.write(log_config)
8889
try:
89-
defaults.update(dict(config.items("commitizen")))
90+
settings.update(dict(config.items("commitizen")))
9091
break
9192
except NoSectionError:
9293
# The file does not have commitizen section
9394
continue
9495

95-
return defaults
96+
return settings
9697

9798

9899
def main():
99100
config = load_cfg()
100-
parser = get_parser(config)
101+
parser = cli(data)
102+
103+
# Show help if no arg provided
104+
if len(sys.argv) == 1:
105+
parser.print_help(sys.stderr)
106+
raise SystemExit(1)
107+
101108
args = parser.parse_args()
109+
app = Application(**config)
110+
111+
if args.name:
112+
app.name = args.name
102113

103114
if args.debug:
104115
logging.getLogger("commitizen").setLevel(logging.DEBUG)
105116

106117
if args.version:
107-
logger.info(version())
118+
logger.info(app.version)
108119
sys.exit(0)
109120

110-
set_commiter(args.name)
111-
args.func(args)
121+
args.func(app)(args)

commitizen/cmd.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import subprocess
2+
from typing import NamedTuple
3+
4+
5+
class Command(NamedTuple):
6+
out: str
7+
err: str
8+
stdout: bytes
9+
stderr: bytes
10+
11+
12+
def run(cmd: str) -> Command:
13+
cmd.split()
14+
process = subprocess.Popen(
15+
cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE
16+
)
17+
stdout, stderr = process.communicate()
18+
return Command(stdout.decode(), stderr.decode(), stdout, stderr)

commitizen/cz/base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
22
import sys
33
import logging
4-
import delegator
4+
from commitizen import cmd
55
from abc import ABCMeta, abstractmethod
66
from tempfile import NamedTemporaryFile
77
from questionary import prompt
@@ -31,12 +31,12 @@ def message(self, answers):
3131
:rtype: string
3232
"""
3333

34-
def commit(self, message):
34+
def commit(self, message: str):
3535
f = NamedTemporaryFile('wb', delete=False)
3636
f.write(message.encode('utf-8'))
3737
f.close()
3838

39-
c = delegator.run('git commit -a -F {0}'.format(f.name), block=True)
39+
c = cmd.run(f'git commit -a -F {f.name}')
4040
print(c.out or c.err)
4141

4242
os.unlink(f.name)

0 commit comments

Comments
 (0)