Skip to content

Safely ignore modules named cz_ that are not plugins #480

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 6 commits into from
Feb 7, 2022
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
32 changes: 25 additions & 7 deletions commitizen/cz/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
import importlib
import pkgutil
from typing import Dict, Type
import warnings
from typing import Dict, Iterable, 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


def discover_plugins(path: Iterable[str] = None) -> Dict[str, Type[BaseCommitizen]]:
"""Discover commitizen plugins on the path

Args:
path (Path, optional): If provided, 'path' should be either None or a list of paths to look for
modules in. If path is None, all top-level modules on sys.path.. Defaults to None.

Returns:
Dict[str, Type[BaseCommitizen]]: Registry with found plugins
"""
plugins = {}
for finder, name, ispkg in pkgutil.iter_modules(path):
try:
if name.startswith("cz_"):
plugins[name] = importlib.import_module(name).discover_this # type: ignore
except AttributeError as e:
Copy link
Member

@Lee-W Lee-W Feb 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, I like the idea. Most of the part looks good to me

@woile do you think we should go with the exit code method in this case as well?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean? like a code to easily identify where this warning is coming from?
I'm not sure it's needed, the warning should point to the line in the code AFAIK 🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

like what we define here so that user can decide whether to suppress the warning. but I'm ok with this PR now. we could create another one if we think that's necessary. it won't break anything if we do that in the future

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just approved it. If you agree with not handling this at this moment, I think we're good to merge it

warnings.warn(UserWarning(e.args[0]))
continue
return plugins


registry: Dict[str, Type[BaseCommitizen]] = {
"cz_conventional_commits": ConventionalCommitsCz,
"cz_jira": JiraSmartCz,
"cz_customize": CustomizeCommitsCz,
}
plugins = {
name: importlib.import_module(name).discover_this # type: ignore
for finder, name, ispkg in pkgutil.iter_modules()
if name.startswith("cz_")
}

registry.update(plugins)
registry.update(discover_plugins())
27 changes: 27 additions & 0 deletions tests/test_factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import sys

import pytest

from commitizen import BaseCommitizen, defaults, factory
from commitizen.config import BaseConfig
from commitizen.cz import discover_plugins
from commitizen.exceptions import NoCommitizenFoundException


Expand All @@ -19,3 +22,27 @@ def test_factory_fails():
factory.commiter_factory(config)

assert "The committer has not been found in the system." in str(excinfo)


@pytest.mark.parametrize(
"module_content, plugin_name, expected_plugins",
[
("", "cz_no_plugin", {}),
],
)
def test_discover_plugins(module_content, plugin_name, expected_plugins, tmp_path):
no_plugin_folder = tmp_path / plugin_name
no_plugin_folder.mkdir()
init_file = no_plugin_folder / "__init__.py"
init_file.write_text(module_content)

sys.path.append(tmp_path.as_posix())
with pytest.warns(UserWarning) as record:
discovered_plugins = discover_plugins([tmp_path.as_posix()])
sys.path.pop()

assert (
record[0].message.args[0]
== f"module '{plugin_name}' has no attribute 'discover_this'"
)
assert expected_plugins == discovered_plugins