Skip to content
Merged

Next #237

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
26 changes: 2 additions & 24 deletions commitizen/cli.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import argparse
import logging
import sys
import warnings
from functools import partial

from decli import cli
Expand All @@ -24,16 +23,10 @@
"name": ["-n", "--name"],
"help": "use the given commitizen (default: cz_conventional_commits)",
},
{
"name": ["--version"],
"action": "store_true",
"help": "get the version of the installed commitizen",
},
],
"subcommands": {
"title": "commands",
# TODO: Add this constraint back in 2.0
# "required": True,
"required": True,
"commands": [
{
"name": ["init"],
Expand Down Expand Up @@ -278,26 +271,11 @@ def main():
elif not args.name and not conf.path:
conf.update({"name": "cz_conventional_commits"})

if args.version:
warnings.warn(
(
"'cz --version' will be deprecated in next major version. "
"Please use 'cz version' command from your scripts"
),
category=DeprecationWarning,
)
args.func = commands.Version

if args.debug:
logging.getLogger("commitizen").setLevel(logging.DEBUG)
sys.excepthook = commitizen_debug_excepthook

# TODO: This try block can be removed after command is required in 2.0
# Handle the case that argument is given, but no command is provided
try:
args.func(conf, vars(args))()
except AttributeError:
raise NoCommandFoundError()
args.func(conf, vars(args))()


if __name__ == "__main__":
Expand Down
64 changes: 56 additions & 8 deletions commitizen/commands/init.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import os

import questionary
import yaml
from packaging.version import Version

from commitizen import factory, out
from commitizen.config import BaseConfig, IniConfig, TomlConfig
from commitizen import cmd, factory, out
from commitizen.__version__ import __version__
from commitizen.config import BaseConfig, TomlConfig
from commitizen.cz import registry
from commitizen.defaults import long_term_support_config_files
from commitizen.defaults import config_files
from commitizen.exceptions import NoAnswersError
from commitizen.git import get_latest_tag_name, get_tag_names

Expand All @@ -20,11 +24,8 @@ def __call__(self):
# No config for commitizen exist
if not self.config.path:
config_path = self._ask_config_path()

if "toml" in config_path:
self.config = TomlConfig(data="", path=config_path)
else:
self.config = IniConfig(data="", path=config_path)

self.config.init_empty_config_content()

Expand All @@ -33,17 +34,20 @@ def __call__(self):
values_to_add["version"] = Version(tag).public
values_to_add["tag_format"] = self._ask_tag_format(tag)
self._update_config_file(values_to_add)

if questionary.confirm("Do you want to install pre-commit hook?").ask():
self._install_pre_commit_hook()

out.write("You can bump the version and create changelog running:\n")
out.info("cz bump --changelog")
out.success("The configuration are all set.")
else:
# TODO: handle the case that config file exist but no value
out.line(f"Config file {self.config.path} already exists")

def _ask_config_path(self) -> str:
name = questionary.select(
"Please choose a supported config file: (default: pyproject.toml)",
choices=long_term_support_config_files,
choices=config_files,
default="pyproject.toml",
style=self.cz.style,
).ask()
Expand Down Expand Up @@ -101,6 +105,50 @@ def _ask_tag_format(self, latest_tag) -> str:
tag_format = "$version"
return tag_format

def _install_pre_commit_hook(self):
pre_commit_config_filename = ".pre-commit-config.yaml"
cz_hook_config = {
"repo": "https://github.com/commitizen-tools/commitizen",
"rev": f"v{__version__}",
"hooks": [{"id": "commitizen", "stages": ["commit-msg"]}],
}

config_data = {}
if not os.path.isfile(pre_commit_config_filename):
# .pre-commit-config does not exist
config_data["repos"] = [cz_hook_config]
else:
# breakpoint()
with open(pre_commit_config_filename) as config_file:
yaml_data = yaml.safe_load(config_file)
if yaml_data:
config_data = yaml_data

if "repos" in config_data:
for pre_commit_hook in config_data["repos"]:
if "commitizen" in pre_commit_hook["repo"]:
out.write("commitizen already in pre-commit config")
break
else:
config_data["repos"].append(cz_hook_config)
else:
# .pre-commit-config exists but there's no "repos" key
config_data["repos"] = [cz_hook_config]

with open(pre_commit_config_filename, "w") as config_file:
yaml.safe_dump(config_data, stream=config_file)

c = cmd.run("pre-commit install --hook-type commit-msg")
if c.return_code == 127:
out.error(
"pre-commit is not installed in current environement.\n"
"Run 'pre-commit install --hook-type commit-msg' again after it's installed"
)
elif c.return_code != 0:
out.error(c.err)
else:
out.write("commitizen pre-commit hook is now installed in your '.git'\n")

def _update_config_file(self, values):
for key, value in values.items():
self.config.set_key(key, value)
35 changes: 1 addition & 34 deletions commitizen/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,11 @@
import warnings
from pathlib import Path
from typing import Optional, Union

from commitizen import defaults, git

from .base_config import BaseConfig
from .ini_config import IniConfig
from .toml_config import TomlConfig


def load_global_conf() -> Optional[IniConfig]:
home = Path.home()
global_cfg = home / Path(".cz")
if not global_cfg.exists():
return None

# global conf doesn't make sense with commitizen bump
# so I'm deprecating it and won't test it
message = (
"Global conf will be deprecated in next major version. "
"Use per project configuration. "
"Remove '~/.cz' file from your conf folder."
)
warnings.simplefilter("always", DeprecationWarning)
warnings.warn(message, category=DeprecationWarning)

with open(global_cfg, "r") as f:
data = f.read()

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


def read_cfg() -> BaseConfig:
conf = BaseConfig()

Expand All @@ -52,21 +26,14 @@ def read_cfg() -> BaseConfig:
with open(filename, "r") as f:
data: str = f.read()

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

if _conf.is_empty_config:
continue
else:
conf = _conf
break

if not conf.path:
global_conf = load_global_conf()
if global_conf:
conf = global_conf

return conf
14 changes: 0 additions & 14 deletions commitizen/config/base_config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import warnings
from pathlib import Path
from typing import Any, Dict, Optional, Union

Expand Down Expand Up @@ -34,16 +33,3 @@ def add_path(self, path: Union[str, Path]):

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

# TODO: remove "files" supported in 2.0
@classmethod
def _show_files_column_deprecated_warning(cls):
warnings.simplefilter("always", DeprecationWarning)
warnings.warn(
(
'"files" is renamed as "version_files" '
"and will be deprecated in next major version\n"
'Please repalce "files" with "version_files"'
),
category=DeprecationWarning,
)
76 changes: 0 additions & 76 deletions commitizen/config/ini_config.py

This file was deleted.

4 changes: 0 additions & 4 deletions commitizen/config/toml_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,3 @@ def _parse_setting(self, data: str):
self.settings.update(doc["tool"]["commitizen"])
except exceptions.NonExistentKey:
self.is_empty_config = True

if "files" in self.settings:
self.settings["version_files"] = self.settings["files"]
TomlConfig._show_files_column_deprecated_warning
7 changes: 2 additions & 5 deletions commitizen/defaults.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from collections import OrderedDict
from typing import Any, Dict
from typing import Any, Dict, List

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
config_files: List[str] = ["pyproject.toml", ".cz.toml"]

DEFAULT_SETTINGS: Dict[str, Any] = {
"name": "cz_conventional_commits",
Expand Down
25 changes: 0 additions & 25 deletions docs/bump.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ However, it will still update `pyproject.toml` and `src/__version__.py`.
To fix it, you'll first `git checkout .` to reset to the status before trying to bump and update
the version in `setup.py` to `1.21.0`


## Configuration

### `tag_format`
Expand All @@ -155,13 +154,6 @@ In your `pyproject.toml` or `.cz.toml`
tag_format = "v$minor.$major.$patch$prerelease"
```

Or in your `.cz` (TO BE DEPRECATED)

```ini
[commitizen]
tag_format = v$minor.$major.$patch$prerelease
```

The variables must be preceded by a `$` sign.

Supported variables:
Expand Down Expand Up @@ -198,16 +190,6 @@ version_files = [
]
```

`.cz` (TO BE DEPRECATED)

```ini
[commitizen]
version_files = [
"src/__version__.py",
"setup.py:version"
]
```

In the example above, we can see the reference `"setup.py:version"`.
This means that it will find a file `setup.py` and will only make a change
in a line containing the `version` substring.
Expand All @@ -234,13 +216,6 @@ Some examples
bump_message = "release $current_version → $new_version [skip-ci]"
```

`.cz` (TO BE DEPRECATED)

```ini
[commitizen]
bump_message = release $current_version → $new_version [skip-ci]
```

## Custom bump

Read the [customizing section](./customization.md).
Expand Down
Loading