conventional-git 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- conventional_git/__init__.py +0 -0
- conventional_git/adapters/__init__.py +0 -0
- conventional_git/adapters/commitizen_config.py +49 -0
- conventional_git/adapters/gitlint_rules.py +93 -0
- conventional_git/branch/__init__.py +7 -0
- conventional_git/branch/grammar.py +21 -0
- conventional_git/branch/rules.py +119 -0
- conventional_git/branch/vocabulary.py +89 -0
- conventional_git/cli/__init__.py +0 -0
- conventional_git/cli/app.py +41 -0
- conventional_git/cli/auth.py +107 -0
- conventional_git/cli/capabilities.py +111 -0
- conventional_git/cli/check.py +132 -0
- conventional_git/cli/create.py +172 -0
- conventional_git/cli/hook.py +132 -0
- conventional_git/cli/mcp.py +13 -0
- conventional_git/commit/__init__.py +8 -0
- conventional_git/commit/compose.py +39 -0
- conventional_git/commit/grammar.py +41 -0
- conventional_git/commit/rules.py +237 -0
- conventional_git/commit/vocabulary.py +94 -0
- conventional_git/config.py +51 -0
- conventional_git/csv_columns.py +28 -0
- conventional_git/data/__init__.py +0 -0
- conventional_git/data/branch-trunks.csv +4 -0
- conventional_git/data/branch-types.csv +8 -0
- conventional_git/data/commit-attribution.csv +4 -0
- conventional_git/data/commit-types.csv +12 -0
- conventional_git/generation/__init__.py +27 -0
- conventional_git/generation/credentials.py +112 -0
- conventional_git/generation/diff.py +131 -0
- conventional_git/generation/heuristic.py +119 -0
- conventional_git/generation/protocol.py +94 -0
- conventional_git/generation/typesafe.py +140 -0
- conventional_git/helpers.py +39 -0
- conventional_git/mcp/__init__.py +0 -0
- conventional_git/mcp/server.py +75 -0
- conventional_git/py.typed +0 -0
- conventional_git/violations.py +75 -0
- conventional_git-1.0.0.dist-info/METADATA +365 -0
- conventional_git-1.0.0.dist-info/RECORD +44 -0
- conventional_git-1.0.0.dist-info/WHEEL +4 -0
- conventional_git-1.0.0.dist-info/entry_points.txt +3 -0
- conventional_git-1.0.0.dist-info/licenses/LICENSE +21 -0
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import tomllib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from conventional_git.commit import vocabulary
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def schema_pattern() -> str:
|
|
12
|
+
types = vocabulary.default_types()
|
|
13
|
+
return r"(?i)" + "|".join(sorted(types)) + r"(?:\(.+\))?(!)?: .+"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _schemes() -> dict[str, Any]:
|
|
17
|
+
return {
|
|
18
|
+
"cz_customize": {
|
|
19
|
+
"schema_pattern": schema_pattern(),
|
|
20
|
+
"commit_parser": "",
|
|
21
|
+
"changelog_pattern": "",
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _commitizen_block() -> dict[str, Any]:
|
|
27
|
+
return {
|
|
28
|
+
"name": "cz_customize",
|
|
29
|
+
"tag_format": "$version",
|
|
30
|
+
"version_scheme": "semver",
|
|
31
|
+
"version_provider": "commitizen",
|
|
32
|
+
"update_changelog_on_bump": True,
|
|
33
|
+
"schemes": _schemes(),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def commitizen_config(path: Path | None = None) -> dict[str, Any]:
|
|
38
|
+
if path is None:
|
|
39
|
+
path = Path.cwd() / ".cz.toml"
|
|
40
|
+
if path.exists():
|
|
41
|
+
with path.open("rb") as handle:
|
|
42
|
+
loaded = tomllib.load(handle)
|
|
43
|
+
loaded.setdefault("tool", {})["commitizen"] = _commitizen_block()
|
|
44
|
+
return loaded
|
|
45
|
+
return {"tool": {"commitizen": _commitizen_block()}}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def emit_json(path: Path | None = None) -> str:
|
|
49
|
+
return json.dumps(commitizen_config(path), indent=2)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from gitlint.options import BoolOption
|
|
8
|
+
from gitlint.rules import CommitRule
|
|
9
|
+
from gitlint.rules import RuleViolation
|
|
10
|
+
|
|
11
|
+
from conventional_git.commit import rules as commit_rules
|
|
12
|
+
from conventional_git.commit import vocabulary as commit_vocab
|
|
13
|
+
from conventional_git.config import Config
|
|
14
|
+
from conventional_git.violations import Severity
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from typing import ClassVar
|
|
18
|
+
from typing import Final
|
|
19
|
+
|
|
20
|
+
from gitlint.git import GitCommit
|
|
21
|
+
from gitlint.options import RuleOption
|
|
22
|
+
|
|
23
|
+
# gitlint built-ins that duplicate or contradict the core checks; `.gitlint`
|
|
24
|
+
# should carry `ignore=<these>` so the adapter holds the only verdict.
|
|
25
|
+
RECOMMENDED_IGNORE: Final[tuple[str, ...]] = ("B1", "B5", "B6", "T1", "T3", "T5")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _repo_root(commit: GitCommit) -> Path:
|
|
29
|
+
repository_path = commit.context.repository_path
|
|
30
|
+
return Path(repository_path) if repository_path else Path.cwd()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _config(commit: GitCommit) -> tuple[frozenset[str], tuple[str, ...]]:
|
|
34
|
+
root = _repo_root(commit)
|
|
35
|
+
config = Config.load(root / ".conventional-git.toml")
|
|
36
|
+
policy = commit_vocab.resolve_policy(config)
|
|
37
|
+
return policy.types, policy.extra_attribution_patterns
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _to_gitlint(
|
|
41
|
+
message: str,
|
|
42
|
+
*,
|
|
43
|
+
allowed_types: frozenset[str] | None = None,
|
|
44
|
+
attribution_patterns: tuple[str, ...] = (),
|
|
45
|
+
include_warnings: bool = False,
|
|
46
|
+
) -> list[RuleViolation]:
|
|
47
|
+
report = commit_rules.validate_message(
|
|
48
|
+
message,
|
|
49
|
+
allowed_types=allowed_types,
|
|
50
|
+
attribution_patterns=attribution_patterns,
|
|
51
|
+
)
|
|
52
|
+
violations: list[RuleViolation] = []
|
|
53
|
+
for violation in report.violations:
|
|
54
|
+
is_warning = violation.severity is Severity.WARNING
|
|
55
|
+
if is_warning and not include_warnings:
|
|
56
|
+
continue
|
|
57
|
+
label = "WARNING" if is_warning else "ERROR"
|
|
58
|
+
violations.append(
|
|
59
|
+
RuleViolation(
|
|
60
|
+
rule_id=f"conventional-git/{violation.code}",
|
|
61
|
+
message=f"{label}: {violation.field}: {violation.message}",
|
|
62
|
+
content=violation.fix_hint,
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
return violations
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ConventionalCommitHeaderRule(CommitRule): # type: ignore[misc]
|
|
69
|
+
name = "conventional-git-header"
|
|
70
|
+
id = "CG1"
|
|
71
|
+
options_spec: ClassVar[list[RuleOption]] = [
|
|
72
|
+
BoolOption(name="warnings", value=False, description="Report core warnings as gitlint violations")
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
def validate(self, commit: GitCommit) -> list[RuleViolation]:
|
|
76
|
+
allowed_types, attribution_patterns = _config(commit)
|
|
77
|
+
return _to_gitlint(
|
|
78
|
+
commit.message.original,
|
|
79
|
+
allowed_types=allowed_types,
|
|
80
|
+
attribution_patterns=attribution_patterns,
|
|
81
|
+
include_warnings=bool(self.options["warnings"].value),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def rule_classes() -> list[type[Any]]:
|
|
86
|
+
return [ConventionalCommitHeaderRule]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"RECOMMENDED_IGNORE",
|
|
91
|
+
"ConventionalCommitHeaderRule",
|
|
92
|
+
"rule_classes",
|
|
93
|
+
]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from typing import Final
|
|
8
|
+
|
|
9
|
+
MAX_DESCRIPTION_LENGTH: Final[int] = 75
|
|
10
|
+
|
|
11
|
+
_SEGMENT: Final[str] = r"[a-z0-9]+(?:\.[a-z0-9]+)*"
|
|
12
|
+
_BRANCH_NAME_PATTERN: Final[re.Pattern[str]] = re.compile(
|
|
13
|
+
rf"^(?P<type>[a-z]+)/(?P<description>{_SEGMENT}(?:-{_SEGMENT})*)$"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse(name: str) -> dict[str, str] | None:
|
|
18
|
+
match = _BRANCH_NAME_PATTERN.match(name)
|
|
19
|
+
if not match:
|
|
20
|
+
return None
|
|
21
|
+
return match.groupdict()
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from conventional_git.branch import grammar
|
|
9
|
+
from conventional_git.branch import vocabulary
|
|
10
|
+
from conventional_git.violations import Report
|
|
11
|
+
from conventional_git.violations import Severity
|
|
12
|
+
from conventional_git.violations import Violation
|
|
13
|
+
from conventional_git.violations import ViolationCode
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from typing import Final
|
|
17
|
+
|
|
18
|
+
DEFAULT_DESCRIPTION: Final[str] = "work-in-progress"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _violation(
|
|
22
|
+
code: ViolationCode,
|
|
23
|
+
field: str,
|
|
24
|
+
message: str,
|
|
25
|
+
fix_hint: str,
|
|
26
|
+
*,
|
|
27
|
+
severity: Severity = Severity.ERROR,
|
|
28
|
+
) -> Violation:
|
|
29
|
+
return Violation(code=code, field=field, message=message, fix_hint=fix_hint, severity=severity)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def normalize_description(raw: str | None) -> str:
|
|
33
|
+
text = unicodedata.normalize("NFKD", raw or DEFAULT_DESCRIPTION)
|
|
34
|
+
text = text.encode("ascii", "ignore").decode("ascii")
|
|
35
|
+
text = text.replace("_", "-").replace(" ", "-").lower()
|
|
36
|
+
text = re.sub(r"[^a-z0-9.\-]", "", text)
|
|
37
|
+
text = re.sub(r"\.{2,}", ".", text)
|
|
38
|
+
text = re.sub(r"-{2,}", "-", text)
|
|
39
|
+
text = re.sub(r"[.\-]?-[.\-]?", "-", text)
|
|
40
|
+
text = text.strip("-.")
|
|
41
|
+
if len(text) > grammar.MAX_DESCRIPTION_LENGTH:
|
|
42
|
+
text = text[: grammar.MAX_DESCRIPTION_LENGTH].rsplit("-", 1)[0].strip("-.")
|
|
43
|
+
if not text:
|
|
44
|
+
text = DEFAULT_DESCRIPTION
|
|
45
|
+
return text
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_branch_name(branch_type: str, description: str) -> str:
|
|
49
|
+
return f"{branch_type}/{description}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def validate_name(
|
|
53
|
+
name: str,
|
|
54
|
+
*,
|
|
55
|
+
allowed_types: frozenset[str] | None = None,
|
|
56
|
+
trunk_branches: frozenset[str] | None = None,
|
|
57
|
+
) -> Report:
|
|
58
|
+
trunks = trunk_branches if trunk_branches is not None else vocabulary.default_trunks()
|
|
59
|
+
if name in trunks:
|
|
60
|
+
return Report.from_violations()
|
|
61
|
+
|
|
62
|
+
types = allowed_types if allowed_types is not None else vocabulary.default_types()
|
|
63
|
+
parsed = grammar.parse(name)
|
|
64
|
+
if parsed is None:
|
|
65
|
+
return Report.from_violations(
|
|
66
|
+
_violation(
|
|
67
|
+
ViolationCode.BRANCH_FORMAT,
|
|
68
|
+
"name",
|
|
69
|
+
f"Branch name {name!r} does not match <type>/<description>",
|
|
70
|
+
"Use the form 'type/description' (lowercase letters, digits, hyphens, dots)",
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
violations: list[Violation] = []
|
|
75
|
+
branch_type = parsed["type"]
|
|
76
|
+
description = parsed["description"]
|
|
77
|
+
|
|
78
|
+
if branch_type not in types:
|
|
79
|
+
violations.append(
|
|
80
|
+
_violation(
|
|
81
|
+
ViolationCode.BRANCH_TYPE,
|
|
82
|
+
"type",
|
|
83
|
+
f"Branch type {branch_type!r} is not allowed",
|
|
84
|
+
f"Use one of: {', '.join(sorted(types))}",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
if not description:
|
|
88
|
+
violations.append(
|
|
89
|
+
_violation(
|
|
90
|
+
ViolationCode.BRANCH_DESCRIPTION_EMPTY,
|
|
91
|
+
"description",
|
|
92
|
+
"Description segment is empty",
|
|
93
|
+
"Provide a non-empty hyphenated description",
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
if len(description) > grammar.MAX_DESCRIPTION_LENGTH:
|
|
97
|
+
violations.append(
|
|
98
|
+
_violation(
|
|
99
|
+
ViolationCode.BRANCH_DESCRIPTION_LENGTH,
|
|
100
|
+
"description",
|
|
101
|
+
f"Description exceeds {grammar.MAX_DESCRIPTION_LENGTH} characters ({len(description)})",
|
|
102
|
+
f"Shorten the description to at most {grammar.MAX_DESCRIPTION_LENGTH} characters",
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
return Report.from_violations(*violations)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def default_description() -> str:
|
|
110
|
+
return DEFAULT_DESCRIPTION
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, slots=True)
|
|
114
|
+
class Limits:
|
|
115
|
+
description_max_length: int
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def limits() -> Limits:
|
|
119
|
+
return Limits(description_max_length=grammar.MAX_DESCRIPTION_LENGTH)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from conventional_git.csv_columns import read_column
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
from conventional_git.config import Config
|
|
14
|
+
|
|
15
|
+
PACKAGE_ROOT: Final[Path] = Path(__file__).resolve().parents[1]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@lru_cache(maxsize=1)
|
|
19
|
+
def _load_default() -> frozenset[str]:
|
|
20
|
+
default_path = PACKAGE_ROOT / "data" / "branch-types.csv"
|
|
21
|
+
return frozenset(load_from_csv(default_path))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@lru_cache(maxsize=1)
|
|
25
|
+
def _load_default_trunks() -> frozenset[str]:
|
|
26
|
+
default_path = PACKAGE_ROOT / "data" / "branch-trunks.csv"
|
|
27
|
+
return frozenset(load_trunks_from_csv(default_path))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_from_csv(path: Path) -> frozenset[str]:
|
|
31
|
+
return frozenset(read_column(path, "type"))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def load_trunks_from_csv(path: Path) -> frozenset[str]:
|
|
35
|
+
return frozenset(read_column(path, "name"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def default_types() -> frozenset[str]:
|
|
39
|
+
return _load_default()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def default_trunks() -> frozenset[str]:
|
|
43
|
+
return _load_default_trunks()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def merge_vocabularies(overrides: tuple[Path, ...]) -> frozenset[str]:
|
|
47
|
+
types: set[str] = set(default_types())
|
|
48
|
+
for path in overrides:
|
|
49
|
+
if not path.exists():
|
|
50
|
+
continue
|
|
51
|
+
types |= load_from_csv(path)
|
|
52
|
+
return frozenset(types)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def merge_trunks(overrides: tuple[Path, ...]) -> frozenset[str]:
|
|
56
|
+
trunks: set[str] = set(default_trunks())
|
|
57
|
+
for path in overrides:
|
|
58
|
+
if not path.exists():
|
|
59
|
+
continue
|
|
60
|
+
trunks |= load_trunks_from_csv(path)
|
|
61
|
+
return frozenset(trunks)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True, slots=True)
|
|
65
|
+
class BranchPolicy:
|
|
66
|
+
types: frozenset[str]
|
|
67
|
+
trunks: frozenset[str]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def resolve_policy(
|
|
71
|
+
config: Config,
|
|
72
|
+
*,
|
|
73
|
+
extra_types_csv: Path | None = None,
|
|
74
|
+
extra_trunks_csv: Path | None = None,
|
|
75
|
+
) -> BranchPolicy:
|
|
76
|
+
type_overrides = (
|
|
77
|
+
(extra_types_csv, *config.branch_type_overrides)
|
|
78
|
+
if extra_types_csv is not None
|
|
79
|
+
else config.branch_type_overrides
|
|
80
|
+
)
|
|
81
|
+
trunk_overrides = (
|
|
82
|
+
(extra_trunks_csv, *config.branch_trunk_overrides)
|
|
83
|
+
if extra_trunks_csv is not None
|
|
84
|
+
else config.branch_trunk_overrides
|
|
85
|
+
)
|
|
86
|
+
return BranchPolicy(
|
|
87
|
+
types=merge_vocabularies(type_overrides),
|
|
88
|
+
trunks=merge_trunks(trunk_overrides),
|
|
89
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
from importlib import import_module
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from conventional_git.cli import auth as auth_module
|
|
9
|
+
from conventional_git.cli import capabilities as capabilities_module
|
|
10
|
+
from conventional_git.cli import check as check_module
|
|
11
|
+
from conventional_git.cli import create as create_module
|
|
12
|
+
from conventional_git.cli import hook as hook_module
|
|
13
|
+
|
|
14
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
15
|
+
app = typer.Typer(
|
|
16
|
+
name="conventional-git",
|
|
17
|
+
help="Validate, enforce, and generate Conventional Commits / Conventional Branch names.",
|
|
18
|
+
no_args_is_help=True,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
app.add_typer(auth_module.app, name="auth")
|
|
22
|
+
app.add_typer(capabilities_module.app, name="capabilities")
|
|
23
|
+
app.add_typer(check_module.app, name="check")
|
|
24
|
+
app.add_typer(create_module.app, name="create")
|
|
25
|
+
app.add_typer(hook_module.app, name="hook")
|
|
26
|
+
|
|
27
|
+
# The `mcp` extra pulls in a heavy dependency tree (pydantic, httpx,
|
|
28
|
+
# starlette, ...) that most CLI/hook-only installs don't need, so the
|
|
29
|
+
# subcommand only appears when `conventional-git[mcp]` is installed.
|
|
30
|
+
with contextlib.suppress(ImportError):
|
|
31
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
32
|
+
mcp_module = import_module("conventional_git.cli.mcp")
|
|
33
|
+
app.add_typer(mcp_module.app, name="mcp")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main() -> None:
|
|
37
|
+
app()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
if __name__ == "__main__":
|
|
41
|
+
main()
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from conventional_git.generation.protocol import MissingCredentialsError
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from conventional_git.generation import credentials
|
|
12
|
+
except ImportError:
|
|
13
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
14
|
+
credentials = None # type: ignore[assignment]
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from types import ModuleType
|
|
18
|
+
from typing import Final
|
|
19
|
+
|
|
20
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
21
|
+
app = typer.Typer(help="Manage credentials for LLM-backed suggestion providers (requires the 'llm' extra).")
|
|
22
|
+
|
|
23
|
+
_INSTALL_HINT: Final[str] = "Install the LLM extra first: pip install 'conventional-git[llm]'"
|
|
24
|
+
_MASK_MIN_VISIBLE_LENGTH: Final[int] = 4
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _display_name(creds: ModuleType, provider: str) -> str:
|
|
28
|
+
return str(creds.CredentialProvider(provider).display_name)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _require_credentials() -> ModuleType:
|
|
32
|
+
if credentials is None:
|
|
33
|
+
typer.echo(_INSTALL_HINT, err=True)
|
|
34
|
+
raise typer.Exit(1)
|
|
35
|
+
return credentials
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _require_provider(creds: ModuleType, provider: str) -> None:
|
|
39
|
+
if provider not in creds.PROVIDERS:
|
|
40
|
+
available = ", ".join(creds.PROVIDERS)
|
|
41
|
+
typer.echo(f"Unknown provider {provider!r}. Available: {available}", err=True)
|
|
42
|
+
raise typer.Exit(2)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@app.command("login")
|
|
46
|
+
def login(
|
|
47
|
+
provider: Annotated[
|
|
48
|
+
str,
|
|
49
|
+
typer.Option("--provider", help="Which provider to store a key for (typesafe or openrouter)"),
|
|
50
|
+
] = "openrouter",
|
|
51
|
+
) -> None:
|
|
52
|
+
creds = _require_credentials()
|
|
53
|
+
_require_provider(creds, provider)
|
|
54
|
+
key = typer.prompt(f"{_display_name(creds, provider)} API key", hide_input=True)
|
|
55
|
+
if not key.strip():
|
|
56
|
+
typer.echo("Refusing to store an empty key.", err=True)
|
|
57
|
+
raise typer.Exit(1)
|
|
58
|
+
try:
|
|
59
|
+
creds.store_key(provider, key.strip())
|
|
60
|
+
except MissingCredentialsError as error:
|
|
61
|
+
typer.echo(str(error), err=True)
|
|
62
|
+
raise typer.Exit(1) from error
|
|
63
|
+
typer.echo(f"Stored the {_display_name(creds, provider)} API key in the OS keyring.")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@app.command("status")
|
|
67
|
+
def status() -> None:
|
|
68
|
+
creds = _require_credentials()
|
|
69
|
+
active = creds.resolve_active_credential()
|
|
70
|
+
found_any = False
|
|
71
|
+
for provider in creds.PROVIDERS:
|
|
72
|
+
credential = creds.resolve_credential(provider)
|
|
73
|
+
name = _display_name(creds, provider)
|
|
74
|
+
if credential is None:
|
|
75
|
+
typer.echo(f"{name}: not set")
|
|
76
|
+
continue
|
|
77
|
+
found_any = True
|
|
78
|
+
env_var = creds.env_var_name(provider)
|
|
79
|
+
source = f"env ({env_var})" if credential.source == "env" else "keyring"
|
|
80
|
+
marker = " (active)" if active is not None and active.provider == provider else ""
|
|
81
|
+
typer.echo(f"{name}: {source}, {_mask(credential.key)}{marker}")
|
|
82
|
+
if not found_any:
|
|
83
|
+
typer.echo("No credentials found. Run 'conventional-git auth login'.")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@app.command("logout")
|
|
87
|
+
def logout(
|
|
88
|
+
provider: Annotated[
|
|
89
|
+
str | None,
|
|
90
|
+
typer.Option("--provider", help="Which provider's stored key to remove (default: all)"),
|
|
91
|
+
] = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
creds = _require_credentials()
|
|
94
|
+
if provider is None:
|
|
95
|
+
for name in creds.PROVIDERS:
|
|
96
|
+
creds.clear_key(name)
|
|
97
|
+
typer.echo("Removed all stored API keys.")
|
|
98
|
+
return
|
|
99
|
+
_require_provider(creds, provider)
|
|
100
|
+
creds.clear_key(provider)
|
|
101
|
+
typer.echo(f"Removed the stored {_display_name(creds, provider)} API key.")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _mask(key: str) -> str:
|
|
105
|
+
if len(key) <= _MASK_MIN_VISIBLE_LENGTH:
|
|
106
|
+
return "*" * len(key)
|
|
107
|
+
return f"{'*' * (len(key) - _MASK_MIN_VISIBLE_LENGTH)}{key[-_MASK_MIN_VISIBLE_LENGTH:]}"
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from importlib.metadata import PackageNotFoundError
|
|
7
|
+
from importlib.metadata import version as package_version
|
|
8
|
+
from importlib.util import find_spec
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
from typing import Annotated
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
|
|
14
|
+
from conventional_git import generation
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from conventional_git.generation import credentials
|
|
18
|
+
except ImportError:
|
|
19
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
20
|
+
credentials = None # type: ignore[assignment]
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
from conventional_git.mcp import server as mcp_server
|
|
24
|
+
except ImportError:
|
|
25
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
26
|
+
mcp_server = None # type: ignore[assignment]
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from typing import Final
|
|
30
|
+
|
|
31
|
+
# pylint: disable-next=app-require-final,app-module-const-naming
|
|
32
|
+
app = typer.Typer(help="Report what this installed conventional-git supports.")
|
|
33
|
+
|
|
34
|
+
_PACKAGE_NAME: Final[str] = "conventional-git"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class Capabilities:
|
|
39
|
+
version: str
|
|
40
|
+
extras: dict[str, bool]
|
|
41
|
+
providers: tuple[str, ...]
|
|
42
|
+
credentials: dict[str, str | None]
|
|
43
|
+
mcp_tools: tuple[str, ...]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _resolve_version() -> str:
|
|
47
|
+
try:
|
|
48
|
+
return package_version(_PACKAGE_NAME)
|
|
49
|
+
except PackageNotFoundError:
|
|
50
|
+
return "unknown"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _resolve_extras() -> dict[str, bool]:
|
|
54
|
+
return {
|
|
55
|
+
"llm": find_spec("keyring") is not None and find_spec("typesafe_sdk") is not None,
|
|
56
|
+
"mcp": mcp_server is not None,
|
|
57
|
+
"gitlint": find_spec("gitlint") is not None,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _resolve_credentials(*, has_llm: bool) -> dict[str, str | None]:
|
|
62
|
+
if not has_llm or credentials is None:
|
|
63
|
+
return {}
|
|
64
|
+
result: dict[str, str | None] = {}
|
|
65
|
+
for provider in credentials.PROVIDERS:
|
|
66
|
+
credential = credentials.resolve_credential(provider)
|
|
67
|
+
result[provider] = credential.source if credential is not None else None
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _resolve_mcp_tools(*, has_mcp: bool) -> tuple[str, ...]:
|
|
72
|
+
if not has_mcp or mcp_server is None:
|
|
73
|
+
return ()
|
|
74
|
+
tools = asyncio.run(mcp_server.mcp.list_tools())
|
|
75
|
+
return tuple(tool.name for tool in tools)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def collect() -> Capabilities:
|
|
79
|
+
extras = _resolve_extras()
|
|
80
|
+
generation.enable_optional_providers()
|
|
81
|
+
return Capabilities(
|
|
82
|
+
version=_resolve_version(),
|
|
83
|
+
extras=extras,
|
|
84
|
+
providers=generation.available_providers(),
|
|
85
|
+
credentials=_resolve_credentials(has_llm=extras["llm"]),
|
|
86
|
+
mcp_tools=_resolve_mcp_tools(has_mcp=extras["mcp"]),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.callback(invoke_without_command=True)
|
|
91
|
+
def capabilities(
|
|
92
|
+
as_json: Annotated[bool, typer.Option("--json", help="Print machine-readable JSON")] = False,
|
|
93
|
+
) -> None:
|
|
94
|
+
report = collect()
|
|
95
|
+
if as_json:
|
|
96
|
+
payload = {
|
|
97
|
+
"version": report.version,
|
|
98
|
+
"extras": report.extras,
|
|
99
|
+
"providers": list(report.providers),
|
|
100
|
+
"credentials": report.credentials,
|
|
101
|
+
"mcp_tools": list(report.mcp_tools),
|
|
102
|
+
}
|
|
103
|
+
typer.echo(json.dumps(payload))
|
|
104
|
+
return
|
|
105
|
+
typer.echo(f"version: {report.version}")
|
|
106
|
+
typer.echo(f"extras: {', '.join(f'{name}={value}' for name, value in report.extras.items())}")
|
|
107
|
+
typer.echo(f"providers: {', '.join(report.providers) or '(none)'}")
|
|
108
|
+
for provider, source in report.credentials.items():
|
|
109
|
+
typer.echo(f"credential[{provider}]: {source or 'not set'}")
|
|
110
|
+
if report.mcp_tools:
|
|
111
|
+
typer.echo(f"mcp_tools: {', '.join(report.mcp_tools)}")
|