commit-roaster 0.1.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.
@@ -0,0 +1,10 @@
1
+ """commit-roaster: roast a git diff and suggest a proper commit message."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("commit-roaster")
7
+ except PackageNotFoundError: # running from a source checkout without installing
8
+ __version__ = "0.0.0+unknown"
9
+
10
+ __all__ = ["__version__"]
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m commit_roaster``."""
2
+
3
+ from commit_roaster.cli import main
4
+
5
+ raise SystemExit(main())
commit_roaster/cli.py ADDED
@@ -0,0 +1,240 @@
1
+ """Command-line entry point: ``roast``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import os
8
+ import sys
9
+ from collections.abc import Callable, Sequence
10
+ from typing import TextIO
11
+
12
+ from commit_roaster import __version__
13
+ from commit_roaster.config import EFFORT_LEVELS, Settings, parse_positive_int
14
+ from commit_roaster.diff import (
15
+ Diff,
16
+ DiffSource,
17
+ RevisionRangeDiffSource,
18
+ StagedDiffSource,
19
+ StdinDiffSource,
20
+ )
21
+ from commit_roaster.exceptions import CommitRoasterError, ConfigError, ExitCode
22
+ from commit_roaster.git import GitClient
23
+ from commit_roaster.models import SUBJECT_MAX_CHARS, RoastResult, SpiceLevel
24
+ from commit_roaster.render import JsonRenderer, Renderer, TextRenderer
25
+ from commit_roaster.roaster import Roaster, SupportsRoast
26
+
27
+ RoasterFactory = Callable[[Settings], SupportsRoast]
28
+ GitFactory = Callable[[], GitClient]
29
+
30
+ _EPILOG = """\
31
+ examples:
32
+ roast roast staged changes
33
+ roast --spice savage no mercy
34
+ roast --range HEAD~3..HEAD roast the last three commits
35
+ git show | roast --stdin roast any diff you can pipe in
36
+ roast --commit roast, then commit with the suggested message
37
+ """
38
+
39
+
40
+ def _positive_int(value: str) -> int:
41
+ """argparse adapter for :func:`parse_positive_int`, so the rule lives in one place."""
42
+ try:
43
+ return parse_positive_int(value)
44
+ except ConfigError as exc:
45
+ raise argparse.ArgumentTypeError(str(exc)) from None
46
+
47
+
48
+ class CommitRoasterCLI:
49
+ """Parses arguments, wires the pieces together and maps errors to exit codes.
50
+
51
+ Collaborators are injected so tests can run the full flow without git or the API.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ *,
57
+ stdin: TextIO | None = None,
58
+ stdout: TextIO | None = None,
59
+ stderr: TextIO | None = None,
60
+ git_factory: GitFactory = GitClient,
61
+ roaster_factory: RoasterFactory = Roaster.from_settings,
62
+ env: dict[str, str] | None = None,
63
+ ) -> None:
64
+ self._stdin = stdin if stdin is not None else sys.stdin
65
+ self._stdout = stdout if stdout is not None else sys.stdout
66
+ self._stderr = stderr if stderr is not None else sys.stderr
67
+ self._git_factory = git_factory
68
+ self._roaster_factory = roaster_factory
69
+ self._env = dict(os.environ) if env is None else env
70
+
71
+ # ------------------------------------------------------------------ public
72
+
73
+ def run(self, argv: Sequence[str] | None = None) -> int:
74
+ try:
75
+ args = self._parse_args(argv)
76
+ except SystemExit as exc: # argparse exits on --help, --version and bad usage
77
+ return exc.code if isinstance(exc.code, int) else ExitCode.USAGE
78
+
79
+ self._configure_logging(args.verbose)
80
+ try:
81
+ code = self._execute(args)
82
+ except CommitRoasterError as exc:
83
+ self._print_err(f"error: {exc}")
84
+ code = exc.exit_code
85
+ except KeyboardInterrupt:
86
+ self._print_err("Interrupted.")
87
+ return ExitCode.INTERRUPTED
88
+ # In a git hook, a failed roast (no key, API down, nothing left to roast after
89
+ # excluding lock files) must not block the commit.
90
+ return ExitCode.OK if args.exit_zero else code
91
+
92
+ def build_parser(self) -> argparse.ArgumentParser:
93
+ parser = argparse.ArgumentParser(
94
+ prog="roast",
95
+ description="A grumpy senior dev reviews your diff, then writes the commit message.",
96
+ epilog=_EPILOG,
97
+ formatter_class=argparse.RawDescriptionHelpFormatter,
98
+ )
99
+ source = parser.add_mutually_exclusive_group()
100
+ source.add_argument(
101
+ "-r",
102
+ "--range",
103
+ metavar="REVS",
104
+ help="roast a revision or range (e.g. HEAD~1, main..feature) instead of staged changes",
105
+ )
106
+ source.add_argument(
107
+ "--stdin", action="store_true", help="read the diff from standard input"
108
+ )
109
+ parser.add_argument(
110
+ "-s",
111
+ "--spice",
112
+ choices=[level.value for level in SpiceLevel],
113
+ default=SpiceLevel.MEDIUM.value,
114
+ help="how hard to roast (default: %(default)s)",
115
+ )
116
+ parser.add_argument("--json", action="store_true", help="print the result as JSON")
117
+ parser.add_argument(
118
+ "-c",
119
+ "--commit",
120
+ action="store_true",
121
+ help="commit the staged changes with the suggested message",
122
+ )
123
+ parser.add_argument(
124
+ "-y", "--yes", action="store_true", help="with --commit, skip the confirmation"
125
+ )
126
+ parser.add_argument("--model", help="Claude model ID (env: ROAST_MODEL)")
127
+ parser.add_argument(
128
+ "--effort", choices=EFFORT_LEVELS, help="thinking effort (env: ROAST_EFFORT)"
129
+ )
130
+ parser.add_argument(
131
+ "--max-diff-chars",
132
+ type=_positive_int,
133
+ metavar="N",
134
+ help="truncate larger diffs, with a warning (env: ROAST_MAX_DIFF_CHARS)",
135
+ )
136
+ parser.add_argument(
137
+ "--exit-zero",
138
+ action="store_true",
139
+ help="exit 0 even when the roast fails, so a git hook never blocks a commit",
140
+ )
141
+ parser.add_argument(
142
+ "-v", "--verbose", action="count", default=0, help="-v for info, -vv for debug logs"
143
+ )
144
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
145
+ return parser
146
+
147
+ # ----------------------------------------------------------------- private
148
+
149
+ def _parse_args(self, argv: Sequence[str] | None) -> argparse.Namespace:
150
+ parser = self.build_parser()
151
+ args = parser.parse_args(argv)
152
+ if args.commit and (args.stdin or args.range):
153
+ parser.error("--commit only works with staged changes (drop --range/--stdin)")
154
+ if args.yes and not args.commit:
155
+ parser.error("--yes only makes sense with --commit")
156
+ if args.commit and not args.yes and not self._is_tty(self._stdin):
157
+ # Checked before the paid API call, not after it.
158
+ parser.error("--commit asks for confirmation, which needs a terminal; add --yes")
159
+ return args
160
+
161
+ def _execute(self, args: argparse.Namespace) -> int:
162
+ settings = Settings.from_env(self._env).with_overrides(
163
+ model=args.model, effort=args.effort, max_diff_chars=args.max_diff_chars
164
+ )
165
+ git = self._git_factory()
166
+ diff = self._build_source(args, git, settings).load(settings.max_diff_chars)
167
+ if diff.truncated:
168
+ self._print_err(
169
+ f"warning: diff is {diff.original_chars:,} characters; only the first "
170
+ f"{len(diff.text):,} will be reviewed (raise with --max-diff-chars)."
171
+ )
172
+ if not args.json and self._is_tty(self._stderr):
173
+ self._print_err(f"Roasting {diff.description} with {settings.model}...")
174
+
175
+ result = self._roaster_factory(settings).roast(diff, SpiceLevel(args.spice))
176
+ self._print_out(self._renderer(args).render(result, diff))
177
+
178
+ if args.commit:
179
+ self._commit(git, result, diff, assume_yes=args.yes)
180
+ return ExitCode.OK
181
+
182
+ def _build_source(
183
+ self, args: argparse.Namespace, git: GitClient, settings: Settings
184
+ ) -> DiffSource:
185
+ if args.stdin:
186
+ return StdinDiffSource(self._stdin, settings.exclude_patterns)
187
+ if args.range:
188
+ return RevisionRangeDiffSource(git, args.range, settings.exclude_patterns)
189
+ return StagedDiffSource(git, settings.exclude_patterns)
190
+
191
+ def _renderer(self, args: argparse.Namespace) -> Renderer:
192
+ if args.json:
193
+ return JsonRenderer()
194
+ color = self._is_tty(self._stdout) and "NO_COLOR" not in self._env
195
+ return TextRenderer(color=color)
196
+
197
+ def _commit(self, git: GitClient, result: RoastResult, diff: Diff, *, assume_yes: bool) -> None:
198
+ if result.subject_too_long:
199
+ self._print_err(
200
+ f"warning: the subject is {len(result.commit_subject)} characters; "
201
+ f"git convention is {SUBJECT_MAX_CHARS} or fewer."
202
+ )
203
+ if not assume_yes:
204
+ question = "Commit staged changes with this message?"
205
+ if diff.truncated:
206
+ question = (
207
+ f"Claude reviewed only {len(diff.text):,} of {diff.original_chars:,} "
208
+ f"characters. Commit all staged changes with this message?"
209
+ )
210
+ self._stderr.write(f"\n{question} [y/N] ")
211
+ self._stderr.flush()
212
+ if self._stdin.readline().strip().lower() not in {"y", "yes"}:
213
+ self._print_err("Commit skipped.")
214
+ return
215
+ summary = git.commit(result.commit_message)
216
+ self._print_err(summary.strip())
217
+
218
+ def _configure_logging(self, verbosity: int) -> None:
219
+ level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
220
+ logging.basicConfig(
221
+ level=level,
222
+ format="%(levelname)s %(name)s: %(message)s",
223
+ stream=self._stderr,
224
+ force=True,
225
+ )
226
+
227
+ @staticmethod
228
+ def _is_tty(stream: TextIO) -> bool:
229
+ isatty = getattr(stream, "isatty", None)
230
+ return bool(isatty and isatty())
231
+
232
+ def _print_out(self, text: str) -> None:
233
+ print(text, file=self._stdout)
234
+
235
+ def _print_err(self, text: str) -> None:
236
+ print(text, file=self._stderr)
237
+
238
+
239
+ def main(argv: Sequence[str] | None = None) -> int:
240
+ return CommitRoasterCLI().run(argv)
@@ -0,0 +1,110 @@
1
+ """Runtime settings, resolved from defaults, then environment, then CLI flags."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, replace
8
+ from typing import Literal, get_args
9
+
10
+ from commit_roaster.exceptions import ConfigError
11
+
12
+ Effort = Literal["low", "medium", "high", "xhigh", "max"]
13
+ EFFORT_LEVELS: tuple[Effort, ...] = get_args(Effort)
14
+
15
+ DEFAULT_MODEL = "claude-haiku-5-5"
16
+ DEFAULT_EFFORT: Effort = "low"
17
+ DEFAULT_MAX_TOKENS = 16_000
18
+ # ~15k tokens of diff. Larger diffs are truncated, with a warning, not silently.
19
+ DEFAULT_MAX_DIFF_CHARS = 60_000
20
+ # Generated or vendored files that add noise and cost but nothing worth roasting.
21
+ DEFAULT_EXCLUDE_PATTERNS: tuple[str, ...] = (
22
+ "*.lock",
23
+ "package-lock.json",
24
+ "pnpm-lock.yaml",
25
+ "*.min.js",
26
+ "*.min.css",
27
+ "*.map",
28
+ )
29
+
30
+ ENV_MODEL = "ROAST_MODEL"
31
+ ENV_EFFORT = "ROAST_EFFORT"
32
+ ENV_MAX_DIFF_CHARS = "ROAST_MAX_DIFF_CHARS"
33
+
34
+
35
+ def parse_effort(value: str) -> Effort:
36
+ """Validate an effort level coming from untyped input (env var or flag)."""
37
+ normalized = value.strip().lower()
38
+ for level in EFFORT_LEVELS:
39
+ if level == normalized:
40
+ return level
41
+ raise ConfigError(f"Invalid effort {value!r}. Choose one of: {', '.join(EFFORT_LEVELS)}.")
42
+
43
+
44
+ def parse_positive_int(value: str, name: str | None = None) -> int:
45
+ """Validate a positive whole number from untyped input (env var or flag).
46
+
47
+ ``name`` starts the error message; leave it out when the caller already says
48
+ which input was wrong (argparse prefixes ``argument --flag:``).
49
+ """
50
+ subject = f"{name} " if name else ""
51
+ try:
52
+ number = int(value)
53
+ except ValueError:
54
+ raise ConfigError(f"{subject}must be a whole number, got {value!r}.") from None
55
+ if number <= 0:
56
+ raise ConfigError(f"{subject}must be greater than zero, got {number}.")
57
+ return number
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class Settings:
62
+ """Immutable configuration for one run."""
63
+
64
+ model: str = DEFAULT_MODEL
65
+ effort: Effort = DEFAULT_EFFORT
66
+ max_tokens: int = DEFAULT_MAX_TOKENS
67
+ max_diff_chars: int = DEFAULT_MAX_DIFF_CHARS
68
+ exclude_patterns: tuple[str, ...] = DEFAULT_EXCLUDE_PATTERNS
69
+
70
+ def __post_init__(self) -> None:
71
+ if not self.model.strip():
72
+ raise ConfigError("Model name must not be empty.")
73
+ # Frozen dataclass: store the normalized value ("MEDIUM" -> "medium") directly.
74
+ object.__setattr__(self, "effort", parse_effort(self.effort))
75
+ if self.max_tokens <= 0:
76
+ raise ConfigError("max_tokens must be greater than zero.")
77
+ if self.max_diff_chars <= 0:
78
+ raise ConfigError("max_diff_chars must be greater than zero.")
79
+
80
+ @classmethod
81
+ def from_env(cls, env: Mapping[str, str] | None = None) -> Settings:
82
+ """Build settings from defaults overridden by ``ROAST_*`` environment variables."""
83
+ source = os.environ if env is None else env
84
+ settings = cls()
85
+ if model := source.get(ENV_MODEL, "").strip():
86
+ settings = replace(settings, model=model)
87
+ if effort := source.get(ENV_EFFORT, "").strip():
88
+ settings = replace(settings, effort=parse_effort(effort))
89
+ if max_chars := source.get(ENV_MAX_DIFF_CHARS, "").strip():
90
+ settings = replace(
91
+ settings, max_diff_chars=parse_positive_int(max_chars, ENV_MAX_DIFF_CHARS)
92
+ )
93
+ return settings
94
+
95
+ def with_overrides(
96
+ self,
97
+ *,
98
+ model: str | None = None,
99
+ effort: str | None = None,
100
+ max_diff_chars: int | None = None,
101
+ ) -> Settings:
102
+ """Return a copy with any non-``None`` overrides applied (used for CLI flags)."""
103
+ settings = self
104
+ if model is not None:
105
+ settings = replace(settings, model=model)
106
+ if effort is not None:
107
+ settings = replace(settings, effort=parse_effort(effort))
108
+ if max_diff_chars is not None:
109
+ settings = replace(settings, max_diff_chars=max_diff_chars)
110
+ return settings
commit_roaster/diff.py ADDED
@@ -0,0 +1,221 @@
1
+ """Where the diff comes from.
2
+
3
+ :class:`DiffSource` is a template: subclasses only say how to read the raw
4
+ text, and the base class handles the shared rules (empty check, size limit).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import re
11
+ from abc import ABC, abstractmethod
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from fnmatch import fnmatchcase
15
+ from typing import TextIO
16
+
17
+ from commit_roaster.exceptions import ConfigError, EmptyDiffError
18
+ from commit_roaster.git import GitClient
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class Diff:
25
+ """A diff ready to send to the model."""
26
+
27
+ text: str
28
+ description: str
29
+ original_chars: int
30
+
31
+ @property
32
+ def truncated(self) -> bool:
33
+ return self.original_chars > len(self.text)
34
+
35
+
36
+ def truncate_at_line(text: str, limit: int) -> str:
37
+ """Cut ``text`` to at most ``limit`` characters, ending on a whole line when possible."""
38
+ if len(text) <= limit:
39
+ return text
40
+ cut = text[:limit]
41
+ last_newline = cut.rfind("\n")
42
+ return cut[: last_newline + 1] if last_newline > 0 else cut
43
+
44
+
45
+ _FILE_HEADER = "diff --git "
46
+ _QUOTED = r'"(?:[^"\\]|\\.)*"'
47
+ _HEADER_PATHS = (
48
+ re.compile(r"^diff --git (a/.+) (b/.+)$"),
49
+ # git quotes names with special or non-ASCII characters: "a/caf\303\251.lock"
50
+ re.compile(rf"^diff --git ({_QUOTED}) ({_QUOTED})$"),
51
+ )
52
+ # (line prefix, path prefix git puts in front of the name)
53
+ _PATH_LINES = (
54
+ ("--- ", "a/"),
55
+ ("+++ ", "b/"),
56
+ ("rename from ", ""),
57
+ ("rename to ", ""),
58
+ ("copy from ", ""),
59
+ ("copy to ", ""),
60
+ )
61
+
62
+
63
+ def _unquote(name: str) -> str:
64
+ """Undo git's C-style quoting (``\\t``, ``\\"``, octal UTF-8 bytes) if present."""
65
+ if len(name) < 2 or not (name.startswith('"') and name.endswith('"')):
66
+ return name
67
+ try:
68
+ raw = name[1:-1].encode("utf-8").decode("unicode_escape").encode("latin-1")
69
+ except UnicodeError:
70
+ return name
71
+ return raw.decode("utf-8", errors="replace")
72
+
73
+
74
+ def _strip_prefix(name: str, prefix: str) -> str | None:
75
+ name = _unquote(name)
76
+ return name[len(prefix) :] if name.startswith(prefix) else None
77
+
78
+
79
+ def _path_matches(path: str, patterns: Sequence[str]) -> bool:
80
+ """Approximate git's default pathspec rules: ``*`` also matches ``/``, and a
81
+ plain name matches that path or anything under it."""
82
+ for pattern in patterns:
83
+ directory = pattern.rstrip("/")
84
+ if fnmatchcase(path, pattern) or path.startswith(f"{directory}/"):
85
+ return True
86
+ return False
87
+
88
+
89
+ def _section_paths(lines: Sequence[str]) -> set[str]:
90
+ """Every path named in one ``diff --git`` section's header lines."""
91
+ candidates: set[str | None] = set()
92
+ header = lines[0].rstrip("\r\n")
93
+ for pattern in _HEADER_PATHS:
94
+ if match := pattern.match(header):
95
+ a_name, b_name = match.groups()
96
+ candidates.add(_strip_prefix(a_name, "a/"))
97
+ candidates.add(_strip_prefix(b_name, "b/"))
98
+ for line in lines[1:]:
99
+ if line.startswith("@@"):
100
+ break # hunks start here; anything below is file content, not headers
101
+ for line_prefix, path_prefix in _PATH_LINES:
102
+ if line.startswith(line_prefix):
103
+ # git appends a tab to ---/+++ names that contain spaces
104
+ name = line[len(line_prefix) :].rstrip("\r\n").removesuffix("\t")
105
+ candidates.add(_strip_prefix(name, path_prefix))
106
+ return {path for path in candidates if path}
107
+
108
+
109
+ def exclude_files(diff_text: str, patterns: Sequence[str]) -> str:
110
+ """Drop the per-file sections of a git diff whose path matches any pattern.
111
+
112
+ Does for piped diffs what git's ``:(exclude)`` pathspecs do for the other
113
+ sources. Text outside ``diff --git`` sections (e.g. ``git show`` commit
114
+ headers) is kept, and non-git diffs pass through unchanged.
115
+ """
116
+ if not patterns:
117
+ return diff_text
118
+ sections: list[list[str]] = [[]]
119
+ for line in diff_text.splitlines(keepends=True):
120
+ if line.startswith((_FILE_HEADER, "commit ")):
121
+ sections.append([])
122
+ sections[-1].append(line)
123
+ kept = [
124
+ section
125
+ for section in sections
126
+ if not (
127
+ section
128
+ and section[0].startswith(_FILE_HEADER)
129
+ and any(_path_matches(path, patterns) for path in _section_paths(section))
130
+ )
131
+ ]
132
+ return "".join(line for section in kept for line in section)
133
+
134
+
135
+ class DiffSource(ABC):
136
+ """Produces a :class:`Diff` from somewhere."""
137
+
138
+ @property
139
+ @abstractmethod
140
+ def description(self) -> str:
141
+ """Human-readable name, e.g. ``"staged changes"``."""
142
+
143
+ @property
144
+ def empty_hint(self) -> str:
145
+ """Extra advice shown when there is nothing to roast."""
146
+ return ""
147
+
148
+ @abstractmethod
149
+ def read_raw(self) -> str:
150
+ """Return the full, untruncated diff text."""
151
+
152
+ def load(self, max_chars: int) -> Diff:
153
+ raw = self.read_raw()
154
+ if not raw.strip():
155
+ message = f"Nothing to roast in the {self.description}."
156
+ raise EmptyDiffError(f"{message} {self.empty_hint}".strip())
157
+ text = truncate_at_line(raw, max_chars)
158
+ diff = Diff(text=text, description=self.description, original_chars=len(raw))
159
+ if diff.truncated:
160
+ logger.info("Diff truncated from %d to %d characters", len(raw), len(text))
161
+ return diff
162
+
163
+
164
+ class StagedDiffSource(DiffSource):
165
+ """Changes staged with ``git add`` (what the next commit will contain)."""
166
+
167
+ def __init__(self, git: GitClient, exclude_patterns: Sequence[str] = ()) -> None:
168
+ self._git = git
169
+ self._exclude_patterns = tuple(exclude_patterns)
170
+
171
+ @property
172
+ def description(self) -> str:
173
+ return "staged changes"
174
+
175
+ @property
176
+ def empty_hint(self) -> str:
177
+ return "Stage something with `git add` first, or use --range."
178
+
179
+ def read_raw(self) -> str:
180
+ self._git.ensure_repository()
181
+ return self._git.diff(staged=True, exclude_patterns=self._exclude_patterns)
182
+
183
+
184
+ class RevisionRangeDiffSource(DiffSource):
185
+ """Any revision or range git understands, e.g. ``HEAD~3..HEAD`` or ``main...``."""
186
+
187
+ def __init__(
188
+ self, git: GitClient, revision_range: str, exclude_patterns: Sequence[str] = ()
189
+ ) -> None:
190
+ revision_range = revision_range.strip()
191
+ if not revision_range:
192
+ raise ConfigError("Revision range must not be empty.")
193
+ if revision_range.startswith("-"):
194
+ # Would otherwise be parsed by git as an option.
195
+ raise ConfigError(f"Invalid revision range {revision_range!r}.")
196
+ self._git = git
197
+ self._revision_range = revision_range
198
+ self._exclude_patterns = tuple(exclude_patterns)
199
+
200
+ @property
201
+ def description(self) -> str:
202
+ return f"revision range {self._revision_range}"
203
+
204
+ def read_raw(self) -> str:
205
+ self._git.ensure_repository()
206
+ return self._git.diff(self._revision_range, exclude_patterns=self._exclude_patterns)
207
+
208
+
209
+ class StdinDiffSource(DiffSource):
210
+ """A diff piped in, e.g. ``git show HEAD | roast --stdin``."""
211
+
212
+ def __init__(self, stream: TextIO, exclude_patterns: Sequence[str] = ()) -> None:
213
+ self._stream = stream
214
+ self._exclude_patterns = tuple(exclude_patterns)
215
+
216
+ @property
217
+ def description(self) -> str:
218
+ return "diff from stdin"
219
+
220
+ def read_raw(self) -> str:
221
+ return exclude_files(self._stream.read(), self._exclude_patterns)
@@ -0,0 +1,62 @@
1
+ """Exception hierarchy.
2
+
3
+ Every error the tool expects to happen derives from :class:`CommitRoasterError`
4
+ and carries the process exit code the CLI should return for it. Anything else
5
+ is a bug and is allowed to surface as a traceback.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import IntEnum
11
+
12
+
13
+ class ExitCode(IntEnum):
14
+ OK = 0
15
+ ERROR = 1
16
+ USAGE = 2
17
+ NOTHING_TO_ROAST = 3
18
+ INTERRUPTED = 130
19
+
20
+
21
+ class CommitRoasterError(Exception):
22
+ """Base class for all expected errors."""
23
+
24
+ exit_code: ExitCode = ExitCode.ERROR
25
+
26
+
27
+ class ConfigError(CommitRoasterError):
28
+ """Invalid settings, flags or environment."""
29
+
30
+ exit_code = ExitCode.USAGE
31
+
32
+
33
+ class GitError(CommitRoasterError):
34
+ """A git command failed or git is unavailable."""
35
+
36
+
37
+ class GitCommandError(GitError):
38
+ """git ran but exited with a non-zero status."""
39
+
40
+
41
+ class NotAGitRepositoryError(GitError):
42
+ """The working directory is not inside a git repository."""
43
+
44
+ exit_code = ExitCode.USAGE
45
+
46
+
47
+ class EmptyDiffError(CommitRoasterError):
48
+ """There are no changes to roast."""
49
+
50
+ exit_code = ExitCode.NOTHING_TO_ROAST
51
+
52
+
53
+ class RoastError(CommitRoasterError):
54
+ """The Claude API call failed."""
55
+
56
+
57
+ class RoastRefusedError(RoastError):
58
+ """Claude declined to roast this diff."""
59
+
60
+
61
+ class RoastIncompleteError(RoastError):
62
+ """Claude's reply was cut off or did not match the expected shape."""