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.
Files changed (44) hide show
  1. conventional_git/__init__.py +0 -0
  2. conventional_git/adapters/__init__.py +0 -0
  3. conventional_git/adapters/commitizen_config.py +49 -0
  4. conventional_git/adapters/gitlint_rules.py +93 -0
  5. conventional_git/branch/__init__.py +7 -0
  6. conventional_git/branch/grammar.py +21 -0
  7. conventional_git/branch/rules.py +119 -0
  8. conventional_git/branch/vocabulary.py +89 -0
  9. conventional_git/cli/__init__.py +0 -0
  10. conventional_git/cli/app.py +41 -0
  11. conventional_git/cli/auth.py +107 -0
  12. conventional_git/cli/capabilities.py +111 -0
  13. conventional_git/cli/check.py +132 -0
  14. conventional_git/cli/create.py +172 -0
  15. conventional_git/cli/hook.py +132 -0
  16. conventional_git/cli/mcp.py +13 -0
  17. conventional_git/commit/__init__.py +8 -0
  18. conventional_git/commit/compose.py +39 -0
  19. conventional_git/commit/grammar.py +41 -0
  20. conventional_git/commit/rules.py +237 -0
  21. conventional_git/commit/vocabulary.py +94 -0
  22. conventional_git/config.py +51 -0
  23. conventional_git/csv_columns.py +28 -0
  24. conventional_git/data/__init__.py +0 -0
  25. conventional_git/data/branch-trunks.csv +4 -0
  26. conventional_git/data/branch-types.csv +8 -0
  27. conventional_git/data/commit-attribution.csv +4 -0
  28. conventional_git/data/commit-types.csv +12 -0
  29. conventional_git/generation/__init__.py +27 -0
  30. conventional_git/generation/credentials.py +112 -0
  31. conventional_git/generation/diff.py +131 -0
  32. conventional_git/generation/heuristic.py +119 -0
  33. conventional_git/generation/protocol.py +94 -0
  34. conventional_git/generation/typesafe.py +140 -0
  35. conventional_git/helpers.py +39 -0
  36. conventional_git/mcp/__init__.py +0 -0
  37. conventional_git/mcp/server.py +75 -0
  38. conventional_git/py.typed +0 -0
  39. conventional_git/violations.py +75 -0
  40. conventional_git-1.0.0.dist-info/METADATA +365 -0
  41. conventional_git-1.0.0.dist-info/RECORD +44 -0
  42. conventional_git-1.0.0.dist-info/WHEEL +4 -0
  43. conventional_git-1.0.0.dist-info/entry_points.txt +3 -0
  44. conventional_git-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,237 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING
6
+ from typing import NamedTuple
7
+
8
+ from conventional_git.commit import grammar
9
+ from conventional_git.commit 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 collections.abc import Callable
17
+ from collections.abc import Iterable
18
+ from typing import Final
19
+
20
+ _BODY_LINE_MAX: Final[int] = 140
21
+ _MESSAGE_MAX_BYTES: Final[int] = 2048
22
+ _BULLET_PREFIXES: Final[tuple[str, ...]] = ("- ", "* ")
23
+
24
+
25
+ class Header(NamedTuple):
26
+ type: str
27
+ scope: str | None
28
+ breaking: bool
29
+ description: str
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class ParsedMessage:
34
+ message: str
35
+ header: Header | None
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class _RulePolicy:
40
+ types: frozenset[str]
41
+ attribution_patterns: tuple[str, ...]
42
+
43
+
44
+ def _violation(
45
+ code: ViolationCode,
46
+ field: str,
47
+ message: str,
48
+ fix_hint: str,
49
+ *,
50
+ severity: Severity = Severity.ERROR,
51
+ ) -> Violation:
52
+ return Violation(code=code, field=field, message=message, fix_hint=fix_hint, severity=severity)
53
+
54
+
55
+ def _parse_header(message: str) -> Header | None:
56
+ header = message.split("\n", 1)[0].strip()
57
+ parsed = grammar.split_title(header)
58
+ if parsed is None:
59
+ return None
60
+ return Header(
61
+ type=parsed["type"],
62
+ scope=parsed.get("scope"),
63
+ breaking=bool(parsed.get("breaking")),
64
+ description=parsed["description"],
65
+ )
66
+
67
+
68
+ _BODY_SPLIT_PARTS: Final[int] = 2
69
+
70
+
71
+ def _body_lines(message: str) -> list[str]:
72
+ parts = message.split("\n", 1)
73
+ if len(parts) < _BODY_SPLIT_PARTS:
74
+ return []
75
+ body = parts[1].split("\n\n", 1)[0]
76
+ return [line for line in body.splitlines() if line.strip()]
77
+
78
+
79
+ def _is_bullet(line: str) -> bool:
80
+ return line.lstrip().startswith(_BULLET_PREFIXES)
81
+
82
+
83
+ def _check_header(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
84
+ header = parsed.header
85
+ if header is None:
86
+ yield _violation(
87
+ ViolationCode.COMMIT_HEADER_FORMAT,
88
+ "header",
89
+ "Header does not match <type>[(<scope>)][!]: <description>",
90
+ "Use the form 'type(scope)!: description' (scope and ! optional)",
91
+ )
92
+ return
93
+ if header.type not in policy.types:
94
+ yield _violation(
95
+ ViolationCode.COMMIT_TYPE,
96
+ "type",
97
+ f"Commit type {header.type!r} is not allowed",
98
+ f"Use one of: {', '.join(sorted(policy.types))}",
99
+ )
100
+ if not grammar.is_valid_description(header.description):
101
+ yield _violation(
102
+ ViolationCode.COMMIT_DESCRIPTION_FORMAT,
103
+ "description",
104
+ "Description must start with a lowercase letter or digit and use only lowercase characters",
105
+ "Rewrite the description in lowercase, imperative, present tense",
106
+ )
107
+ if grammar.TRAILING_DOT.search(header.description):
108
+ yield _violation(
109
+ ViolationCode.COMMIT_DESCRIPTION_TRAILING_PERIOD,
110
+ "description",
111
+ "Description must not end with a period",
112
+ "Remove the trailing period",
113
+ severity=Severity.WARNING,
114
+ )
115
+
116
+
117
+ def _check_title_length(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
118
+ del policy
119
+ title = parsed.message.split("\n", 1)[0]
120
+ if len(title) > grammar.MAX_TITLE_LENGTH:
121
+ yield _violation(
122
+ ViolationCode.COMMIT_TITLE_LENGTH,
123
+ "title",
124
+ f"Title exceeds {grammar.MAX_TITLE_LENGTH} characters",
125
+ f"Shorten the title to at most {grammar.MAX_TITLE_LENGTH} characters",
126
+ )
127
+
128
+
129
+ def _check_body_lines(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
130
+ del policy
131
+ for index, line in enumerate(_body_lines(parsed.message)):
132
+ if len(line) > _BODY_LINE_MAX:
133
+ yield _violation(
134
+ ViolationCode.COMMIT_BODY_LINE_LENGTH,
135
+ f"body[{index}]",
136
+ f"Body line {index + 1} exceeds {_BODY_LINE_MAX} characters ({len(line)})",
137
+ f"Wrap or shorten the line to at most {_BODY_LINE_MAX} characters",
138
+ )
139
+ if not _is_bullet(line):
140
+ yield _violation(
141
+ ViolationCode.COMMIT_BODY_BULLET,
142
+ f"body[{index}]",
143
+ f"Body line {index + 1} is not a bullet",
144
+ "Prefix the line with '- ' or '* '",
145
+ severity=Severity.WARNING,
146
+ )
147
+
148
+
149
+ def _check_message_bytes(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
150
+ del policy
151
+ byte_length = len(parsed.message.encode("utf-8"))
152
+ if byte_length > _MESSAGE_MAX_BYTES:
153
+ yield _violation(
154
+ ViolationCode.COMMIT_MESSAGE_BYTES,
155
+ "message",
156
+ f"Message exceeds {_MESSAGE_MAX_BYTES} bytes ({byte_length})",
157
+ "Shorten the message so its UTF-8 encoding fits within the byte limit",
158
+ )
159
+
160
+
161
+ def _check_breaking_footer(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
162
+ del policy
163
+ header = parsed.header
164
+ if header is not None and header.breaking and not grammar.has_breaking_footer(parsed.message):
165
+ yield _violation(
166
+ ViolationCode.COMMIT_BREAKING_FOOTER,
167
+ "footer",
168
+ "Header marks a breaking change but no 'BREAKING CHANGE:' footer was found",
169
+ "Append 'BREAKING CHANGE: <description>' after the body",
170
+ )
171
+
172
+
173
+ def _check_attribution(parsed: ParsedMessage, policy: _RulePolicy) -> Iterable[Violation]:
174
+ if not policy.attribution_patterns:
175
+ return
176
+ combined = re.compile("|".join(policy.attribution_patterns), re.IGNORECASE)
177
+ message = parsed.message
178
+ body_lines = message.split("\n", 1)[1].splitlines() if "\n" in message else []
179
+ for index, line in enumerate(body_lines):
180
+ stripped = line.strip()
181
+ if stripped and combined.search(stripped):
182
+ yield _violation(
183
+ ViolationCode.COMMIT_ATTRIBUTION,
184
+ f"footer[{index}]",
185
+ f"Attribution line is not allowed: {stripped}",
186
+ "Remove the attribution trailer",
187
+ )
188
+
189
+
190
+ _CHECKS: Final[tuple[Callable[[ParsedMessage, _RulePolicy], Iterable[Violation]], ...]] = (
191
+ _check_header,
192
+ _check_title_length,
193
+ _check_body_lines,
194
+ _check_message_bytes,
195
+ _check_breaking_footer,
196
+ _check_attribution,
197
+ )
198
+
199
+
200
+ def validate_message(
201
+ message: str,
202
+ *,
203
+ allowed_types: frozenset[str] | None = None,
204
+ attribution_patterns: tuple[str, ...] | None = None,
205
+ ) -> Report:
206
+ if not message or not message.strip():
207
+ return Report.from_violations(
208
+ _violation(
209
+ ViolationCode.COMMIT_EMPTY,
210
+ "message",
211
+ "Commit message is empty",
212
+ "Provide a non-empty commit message",
213
+ )
214
+ )
215
+
216
+ policy = _RulePolicy(
217
+ types=allowed_types if allowed_types is not None else vocabulary.default_types(),
218
+ attribution_patterns=vocabulary.default_attribution_patterns() + (attribution_patterns or ()),
219
+ )
220
+ parsed = ParsedMessage(message=message, header=_parse_header(message))
221
+ violations = [violation for check in _CHECKS for violation in check(parsed, policy)]
222
+ return Report.from_violations(*violations)
223
+
224
+
225
+ @dataclass(frozen=True, slots=True)
226
+ class Limits:
227
+ title_max_length: int
228
+ body_line_max: int
229
+ message_max_bytes: int
230
+
231
+
232
+ def limits() -> Limits:
233
+ return Limits(
234
+ title_max_length=grammar.MAX_TITLE_LENGTH,
235
+ body_line_max=_BODY_LINE_MAX,
236
+ message_max_bytes=_MESSAGE_MAX_BYTES,
237
+ )
@@ -0,0 +1,94 @@
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
+ from conventional_git.csv_columns import read_mapping
10
+
11
+ if TYPE_CHECKING:
12
+ from typing import Final
13
+
14
+ from conventional_git.config import Config
15
+
16
+ PACKAGE_ROOT: Final[Path] = Path(__file__).resolve().parents[1]
17
+
18
+
19
+ @lru_cache(maxsize=1)
20
+ def _load_default() -> frozenset[str]:
21
+ default_path = PACKAGE_ROOT / "data" / "commit-types.csv"
22
+ return frozenset(load_from_csv(default_path))
23
+
24
+
25
+ @lru_cache(maxsize=1)
26
+ def _load_default_attribution_patterns() -> tuple[str, ...]:
27
+ default_path = PACKAGE_ROOT / "data" / "commit-attribution.csv"
28
+ return load_attribution_csv(default_path)
29
+
30
+
31
+ @lru_cache(maxsize=1)
32
+ def _load_default_criteria() -> dict[str, str]:
33
+ default_path = PACKAGE_ROOT / "data" / "commit-types.csv"
34
+ return load_criteria_from_csv(default_path)
35
+
36
+
37
+ def load_from_csv(path: Path) -> frozenset[str]:
38
+ return frozenset(read_column(path, "type"))
39
+
40
+
41
+ def load_criteria_from_csv(path: Path) -> dict[str, str]:
42
+ return read_mapping(path, "type", "when_to_use")
43
+
44
+
45
+ def load_attribution_csv(path: Path) -> tuple[str, ...]:
46
+ return read_column(path, "pattern")
47
+
48
+
49
+ def default_types() -> frozenset[str]:
50
+ return _load_default()
51
+
52
+
53
+ def default_attribution_patterns() -> tuple[str, ...]:
54
+ return _load_default_attribution_patterns()
55
+
56
+
57
+ def default_criteria() -> dict[str, str]:
58
+ return dict(_load_default_criteria())
59
+
60
+
61
+ def merge_vocabularies(overrides: tuple[Path, ...]) -> frozenset[str]:
62
+ types: set[str] = set(default_types())
63
+ for path in overrides:
64
+ if not path.exists():
65
+ continue
66
+ types |= load_from_csv(path)
67
+ return frozenset(types)
68
+
69
+
70
+ def merge_criteria(overrides: tuple[Path, ...]) -> dict[str, str]:
71
+ criteria: dict[str, str] = dict(_load_default_criteria())
72
+ for path in overrides:
73
+ if not path.exists():
74
+ continue
75
+ criteria |= load_criteria_from_csv(path)
76
+ return criteria
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class CommitPolicy:
81
+ types: frozenset[str]
82
+ extra_attribution_patterns: tuple[str, ...]
83
+
84
+
85
+ def resolve_policy(config: Config, *, extra_types_csv: Path | None = None) -> CommitPolicy:
86
+ overrides = (
87
+ (extra_types_csv, *config.commit_type_overrides)
88
+ if extra_types_csv is not None
89
+ else config.commit_type_overrides
90
+ )
91
+ return CommitPolicy(
92
+ types=merge_vocabularies(overrides),
93
+ extra_attribution_patterns=config.extra_attribution_patterns,
94
+ )
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Iterable
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class Config:
14
+ extra_attribution_patterns: tuple[str, ...]
15
+ commit_type_overrides: tuple[Path, ...]
16
+ branch_type_overrides: tuple[Path, ...]
17
+ branch_trunk_overrides: tuple[Path, ...]
18
+
19
+ @classmethod
20
+ def load(cls, path: Path | None = None) -> Config:
21
+ if path is None:
22
+ path = Path.cwd() / ".conventional-git.toml"
23
+ if not path.exists():
24
+ return cls(
25
+ extra_attribution_patterns=(),
26
+ commit_type_overrides=(),
27
+ branch_type_overrides=(),
28
+ branch_trunk_overrides=(),
29
+ )
30
+ with path.open("rb") as handle:
31
+ data = tomllib.load(handle)
32
+ commit = data.get("commit", {}) or {}
33
+ branch = data.get("branch", {}) or {}
34
+ # Relative override paths are resolved against the config file's own
35
+ # directory, not the process cwd, so every consumer (CLI, MCP, the
36
+ # gitlint adapter) that loads the same file gets the same paths.
37
+ base = path.parent
38
+ return cls(
39
+ extra_attribution_patterns=tuple(commit.get("attribution_patterns", ()) or ()),
40
+ commit_type_overrides=_resolve_paths(base, commit.get("type_overrides", ()) or ()),
41
+ branch_type_overrides=_resolve_paths(base, branch.get("type_overrides", ()) or ()),
42
+ branch_trunk_overrides=_resolve_paths(base, branch.get("trunk_overrides", ()) or ()),
43
+ )
44
+
45
+
46
+ def _resolve_paths(base: Path, raw: Iterable[str]) -> tuple[Path, ...]:
47
+ resolved: list[Path] = []
48
+ for entry in raw:
49
+ candidate = Path(entry)
50
+ resolved.append(candidate if candidate.is_absolute() else base / candidate)
51
+ return tuple(resolved)
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from pathlib import Path
8
+
9
+
10
+ def read_column(path: Path, column: str) -> tuple[str, ...]:
11
+ values: list[str] = []
12
+ with path.open(encoding="utf-8", newline="") as handle:
13
+ for row in csv.DictReader(handle):
14
+ value = (row.get(column) or "").strip()
15
+ if value:
16
+ values.append(value)
17
+ return tuple(values)
18
+
19
+
20
+ def read_mapping(path: Path, key_column: str, value_column: str) -> dict[str, str]:
21
+ mapping: dict[str, str] = {}
22
+ with path.open(encoding="utf-8", newline="") as handle:
23
+ for row in csv.DictReader(handle):
24
+ key = (row.get(key_column) or "").strip()
25
+ value = (row.get(value_column) or "").strip()
26
+ if key:
27
+ mapping[key] = value
28
+ return mapping
File without changes
@@ -0,0 +1,4 @@
1
+ name,when_to_use
2
+ main,Primary trunk branch
3
+ master,Legacy primary trunk branch
4
+ develop,Integration trunk branch
@@ -0,0 +1,8 @@
1
+ type,when_to_use
2
+ feature,New feature or capability under development
3
+ feat,Short alias for feature
4
+ bugfix,Fix for a non-urgent, already-reported bug
5
+ fix,Short alias for bugfix
6
+ hotfix,Urgent fix applied directly against a release or production branch
7
+ release,Preparation for a release (version bump, changelog, freeze)
8
+ chore,Non-code maintenance (dependency bumps, tooling, docs)
@@ -0,0 +1,4 @@
1
+ pattern,why
2
+ ^co-authored-by:,Attribution trailer naming a co-author (human or AI)
3
+ ^generated (with|by)\b,Marketing/attribution line inserted by a generation tool
4
+ 🤖,Robot emoji marker used by AI-generated attribution lines
@@ -0,0 +1,12 @@
1
+ type,when_to_use
2
+ feat,New feature or capability visible to the user
3
+ fix,Bug fix that corrects incorrect behavior
4
+ docs,Documentation-only changes (README, comments, wikis)
5
+ style,Formatting changes that do not affect meaning (whitespace, semicolons, etc.)
6
+ refactor,Code restructuring that neither fixes a bug nor adds a feature
7
+ perf,Performance improvement without behavior change
8
+ test,Adding or correcting tests
9
+ build,Changes to build system, tooling, or external dependencies (e.g. pyproject.toml, Makefile)
10
+ ci,Changes to CI/CD configuration files and scripts
11
+ chore,Routine maintenance that does not modify src or test files (e.g. bump version, update lockfile)
12
+ revert,Reverts a previous commit
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from conventional_git.generation.heuristic import HeuristicProvider
4
+ from conventional_git.generation.protocol import CommitSuggestion
5
+ from conventional_git.generation.protocol import MissingCredentialsError
6
+ from conventional_git.generation.protocol import ProviderError
7
+ from conventional_git.generation.protocol import SuggestionProvider
8
+ from conventional_git.generation.protocol import SuggestionResult
9
+ from conventional_git.generation.protocol import available_providers
10
+ from conventional_git.generation.protocol import enable_optional_providers
11
+ from conventional_git.generation.protocol import get_provider
12
+ from conventional_git.generation.protocol import register_provider
13
+ from conventional_git.generation.protocol import suggest
14
+
15
+ __all__ = [
16
+ "CommitSuggestion",
17
+ "HeuristicProvider",
18
+ "MissingCredentialsError",
19
+ "ProviderError",
20
+ "SuggestionProvider",
21
+ "SuggestionResult",
22
+ "available_providers",
23
+ "enable_optional_providers",
24
+ "get_provider",
25
+ "register_provider",
26
+ "suggest",
27
+ ]
@@ -0,0 +1,112 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import os
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ from typing import TYPE_CHECKING
8
+
9
+ import keyring
10
+ from keyring.errors import KeyringError
11
+
12
+ from conventional_git.generation.protocol import MissingCredentialsError
13
+
14
+ if TYPE_CHECKING:
15
+ from typing import Final
16
+
17
+ _SERVICE: Final[str] = "conventional-git"
18
+
19
+
20
+ class CredentialProvider(StrEnum):
21
+ # Definition order doubles as resolution priority: env vars are checked
22
+ # in this order, then the keyring entries are checked in this same order.
23
+ TYPESAFE = "typesafe"
24
+ OPENROUTER = "openrouter"
25
+
26
+ @property
27
+ def display_name(self) -> str:
28
+ return _DISPLAY_NAMES[self]
29
+
30
+
31
+ class CredentialSource(StrEnum):
32
+ ENV = "env"
33
+ KEYRING = "keyring"
34
+
35
+
36
+ _ENV_VARS: Final[dict[str, str]] = {
37
+ CredentialProvider.TYPESAFE: "TYPESAFE_API_KEY",
38
+ CredentialProvider.OPENROUTER: "OPENROUTER_API_KEY",
39
+ }
40
+ _DISPLAY_NAMES: Final[dict[str, str]] = {
41
+ CredentialProvider.TYPESAFE: "TypeSafe",
42
+ CredentialProvider.OPENROUTER: "OpenRouter",
43
+ }
44
+
45
+ PROVIDERS: Final[tuple[CredentialProvider, ...]] = tuple(CredentialProvider)
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Credential:
50
+ provider: str
51
+ key: str
52
+ source: CredentialSource
53
+
54
+
55
+ def env_var_name(provider: str) -> str:
56
+ return _ENV_VARS[provider]
57
+
58
+
59
+ def env_key(provider: str) -> str | None:
60
+ key = os.environ.get(env_var_name(provider), "").strip()
61
+ return key or None
62
+
63
+
64
+ def stored_key(provider: str) -> str | None:
65
+ with contextlib.suppress(KeyringError):
66
+ key = keyring.get_password(_SERVICE, provider)
67
+ return key.strip() if key and key.strip() else None
68
+ return None
69
+
70
+
71
+ def resolve_credential(provider: str) -> Credential | None:
72
+ key = env_key(provider)
73
+ if key:
74
+ return Credential(provider=provider, key=key, source=CredentialSource.ENV)
75
+ key = stored_key(provider)
76
+ if key:
77
+ return Credential(provider=provider, key=key, source=CredentialSource.KEYRING)
78
+ return None
79
+
80
+
81
+ def resolve_active_credential() -> Credential | None:
82
+ for provider in PROVIDERS:
83
+ key = env_key(provider)
84
+ if key:
85
+ return Credential(provider=provider, key=key, source=CredentialSource.ENV)
86
+ for provider in PROVIDERS:
87
+ key = stored_key(provider)
88
+ if key:
89
+ return Credential(provider=provider, key=key, source=CredentialSource.KEYRING)
90
+ return None
91
+
92
+
93
+ def store_key(provider: str, key: str) -> None:
94
+ if provider not in PROVIDERS:
95
+ message = f"Unknown provider {provider!r}"
96
+ raise ValueError(message)
97
+ try:
98
+ keyring.set_password(_SERVICE, provider, key)
99
+ except KeyringError as error:
100
+ message = (
101
+ f"No usable OS keyring backend is available: {error}. "
102
+ f"Set {env_var_name(provider)} in the environment instead."
103
+ )
104
+ raise MissingCredentialsError(message) from error
105
+
106
+
107
+ def clear_key(provider: str) -> None:
108
+ if provider not in PROVIDERS:
109
+ message = f"Unknown provider {provider!r}"
110
+ raise ValueError(message)
111
+ with contextlib.suppress(KeyringError):
112
+ keyring.delete_password(_SERVICE, provider)