pretty-release-notes 1.4.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 (37) hide show
  1. pretty_release_notes/__init__.py +38 -0
  2. pretty_release_notes/__main__.py +6 -0
  3. pretty_release_notes/adapters/__init__.py +1 -0
  4. pretty_release_notes/adapters/cli_progress.py +25 -0
  5. pretty_release_notes/api.py +239 -0
  6. pretty_release_notes/core/__init__.py +1 -0
  7. pretty_release_notes/core/config.py +166 -0
  8. pretty_release_notes/core/config_loader.py +221 -0
  9. pretty_release_notes/core/execution.py +74 -0
  10. pretty_release_notes/core/interfaces.py +35 -0
  11. pretty_release_notes/database.py +152 -0
  12. pretty_release_notes/generator.py +317 -0
  13. pretty_release_notes/github_client.py +232 -0
  14. pretty_release_notes/main.py +245 -0
  15. pretty_release_notes/models/__init__.py +15 -0
  16. pretty_release_notes/models/_utils.py +47 -0
  17. pretty_release_notes/models/change.py +34 -0
  18. pretty_release_notes/models/commit.py +75 -0
  19. pretty_release_notes/models/issue.py +17 -0
  20. pretty_release_notes/models/pull_request.py +208 -0
  21. pretty_release_notes/models/release_notes.py +241 -0
  22. pretty_release_notes/models/release_notes_line.py +36 -0
  23. pretty_release_notes/models/repository.py +20 -0
  24. pretty_release_notes/openai_client.py +165 -0
  25. pretty_release_notes/prompt.txt +34 -0
  26. pretty_release_notes/py.typed +0 -0
  27. pretty_release_notes/setup_command.py +336 -0
  28. pretty_release_notes/ui.py +46 -0
  29. pretty_release_notes/web/__init__.py +1 -0
  30. pretty_release_notes/web/app.py +193 -0
  31. pretty_release_notes/web/server.py +11 -0
  32. pretty_release_notes-1.4.0.dist-info/METADATA +335 -0
  33. pretty_release_notes-1.4.0.dist-info/RECORD +37 -0
  34. pretty_release_notes-1.4.0.dist-info/WHEEL +5 -0
  35. pretty_release_notes-1.4.0.dist-info/entry_points.txt +2 -0
  36. pretty_release_notes-1.4.0.dist-info/licenses/LICENSE +7 -0
  37. pretty_release_notes-1.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,232 @@
1
+ from typing import Any
2
+
3
+ import requests
4
+ from requests.adapters import HTTPAdapter
5
+ from urllib3.util import Retry
6
+
7
+ from .models import Issue, PullRequest, Repository
8
+ from .models.commit import Commit
9
+
10
+
11
+ class GitHubClient:
12
+ """Client to interact with the GitHub API."""
13
+
14
+ def __init__(self, token: str):
15
+ self.session = requests.Session()
16
+ self.session.headers.update(
17
+ {
18
+ "Authorization": f"Bearer {token}",
19
+ }
20
+ )
21
+ retries = Retry(
22
+ total=3,
23
+ backoff_factor=0.1,
24
+ status_forcelist=[500, 502, 503, 504],
25
+ allowed_methods=None,
26
+ )
27
+ self.session.mount("https://", HTTPAdapter(max_retries=retries))
28
+
29
+ def get_repository(self, owner: str, name: str) -> Repository:
30
+ """Return a repository object."""
31
+ r = self.session.get(
32
+ f"https://api.github.com/repos/{owner}/{name}",
33
+ headers={
34
+ "Accept": "application/vnd.github+json",
35
+ },
36
+ )
37
+ r.raise_for_status()
38
+ return Repository.from_dict(r.json())
39
+
40
+ def get_closed_issues(self, repository: Repository, pr_no: str, first: int = 1) -> list[Issue]:
41
+ """Get a list of issues (title and body) that are closed by a PR."""
42
+ response = self.session.post(
43
+ "https://api.github.com/graphql",
44
+ json={
45
+ "query": """
46
+ query($owner: String!, $name: String!, $pr_no: Int!, $first: Int!) {
47
+ repository(owner: $owner, name: $name) {
48
+ pullRequest(number: $pr_no) {
49
+ closingIssuesReferences (first: $first) {
50
+ edges {
51
+ node {
52
+ body
53
+ title
54
+ }
55
+ }
56
+ }
57
+ }
58
+ }
59
+ }
60
+ """,
61
+ "variables": {
62
+ "owner": repository.owner,
63
+ "name": repository.name,
64
+ "pr_no": int(pr_no),
65
+ "first": first,
66
+ },
67
+ },
68
+ ).json()
69
+
70
+ if "data" not in response:
71
+ return []
72
+
73
+ return [
74
+ Issue.from_dict(issue["node"])
75
+ for issue in response["data"]["repository"]["pullRequest"]["closingIssuesReferences"]["edges"]
76
+ ]
77
+
78
+ def get_diff_commits(self, repository: Repository, tag: str, prev_tag: str) -> list[Commit]:
79
+ """Return a list of commits between two tags.
80
+
81
+ Use this to get the commits for a tag that has a previous tag. Else, use get_tag_commits.
82
+ """
83
+ r = self.session.get(
84
+ f"{repository.url}/compare/{prev_tag}...{tag}",
85
+ headers={
86
+ "Accept": "application/vnd.github+json",
87
+ },
88
+ )
89
+ r.raise_for_status()
90
+ data = r.json()
91
+
92
+ return [Commit.from_dict(self, repository, commit) for commit in data.get("commits", [])]
93
+
94
+ def get_tag_commits(self, repository: Repository, tag: str) -> list[Commit]:
95
+ """Return a list of commits for a given tag.
96
+
97
+ Use this to get the commits for a tag that doesn't have a previous tag. Else, use get_diff_commits.
98
+ """
99
+ params: dict[str, str | int] = {
100
+ "sha": tag,
101
+ "per_page": 100,
102
+ }
103
+ r = self.session.get(
104
+ f"{repository.url}/commits",
105
+ params=params,
106
+ headers={
107
+ "Accept": "application/vnd.github+json",
108
+ },
109
+ )
110
+ r.raise_for_status()
111
+
112
+ commits = r.json()
113
+ commits.sort(key=lambda x: x["commit"]["committer"]["date"])
114
+ return [Commit.from_dict(self, repository, commit) for commit in commits]
115
+
116
+ def get_commit_diff(self, repository: Repository, commit_sha: str) -> str:
117
+ """Return the diff of a particular commit."""
118
+ r = self.session.get(
119
+ f"{repository.url}/commits/{commit_sha}",
120
+ headers={
121
+ "Accept": "application/vnd.github.diff",
122
+ },
123
+ )
124
+ r.raise_for_status()
125
+ return r.text
126
+
127
+ def get_pr(self, repository: Repository, pr_no: str) -> PullRequest:
128
+ """Get PR information from GitHub API."""
129
+ r = self.session.get(
130
+ f"{repository.url}/pulls/{pr_no}",
131
+ headers={
132
+ "Accept": "application/vnd.github+json",
133
+ },
134
+ )
135
+ r.raise_for_status()
136
+ return PullRequest.from_dict(self, repository, r.json())
137
+
138
+ def get_pr_patch(self, repository: Repository, pr_no: str) -> str:
139
+ """Return the patch of a PR."""
140
+ r = self.session.get(
141
+ f"{repository.url}/pulls/{pr_no}",
142
+ headers={
143
+ "Accept": "application/vnd.github.patch",
144
+ },
145
+ )
146
+
147
+ try:
148
+ r.raise_for_status()
149
+ except requests.HTTPError:
150
+ if r.status_code == 406:
151
+ # patch is too big, return empty string
152
+ return ""
153
+ raise
154
+
155
+ return r.text
156
+
157
+ def get_pr_reviewers(self, repository: Repository, pr_no: str) -> set[str]:
158
+ """Get reviewers from GitHub API."""
159
+ r = self.session.get(
160
+ f"{repository.url}/pulls/{pr_no}/reviews",
161
+ headers={
162
+ "Accept": "application/vnd.github+json",
163
+ },
164
+ )
165
+ r.raise_for_status()
166
+ return {review["user"]["login"] for review in r.json()}
167
+
168
+ def list_releases(self, owner: str, repo: str, limit: int = 5) -> list[dict[str, Any]]:
169
+ """List recent releases for a repository."""
170
+ r = self.session.get(
171
+ f"https://api.github.com/repos/{owner}/{repo}/releases",
172
+ params={"per_page": limit},
173
+ headers={"Accept": "application/vnd.github+json"},
174
+ )
175
+ r.raise_for_status()
176
+ result: list[dict[str, Any]] = r.json()
177
+ return result
178
+
179
+ def get_release(self, repository: Repository, tag: str):
180
+ """Get release information from GitHub API."""
181
+ return self.session.get(
182
+ f"{repository.url}/releases/tags/{tag}",
183
+ headers={
184
+ "Accept": "application/vnd.github+json",
185
+ },
186
+ ).json()
187
+
188
+ def generate_release_notes(self, repository: Repository, tag: str, previous_tag_name: str | None = None):
189
+ """Generate release notes for a given tag.
190
+
191
+ Args:
192
+ repository: Repository object
193
+ tag: Tag name for the release
194
+ previous_tag_name: Optional previous tag to use as starting point for comparison
195
+ """
196
+ json_payload = {"tag_name": tag}
197
+ if previous_tag_name:
198
+ json_payload["previous_tag_name"] = previous_tag_name
199
+
200
+ response = self.session.post(
201
+ f"{repository.url}/releases/generate-notes",
202
+ headers={
203
+ "Accept": "application/vnd.github+json",
204
+ },
205
+ json=json_payload,
206
+ )
207
+
208
+ response.raise_for_status()
209
+ return response.json()
210
+
211
+ def update_release(self, repository: Repository, release_id: str, body: str):
212
+ """Update release notes for a given tag."""
213
+ response = self.session.patch(
214
+ f"{repository.url}/releases/{release_id}",
215
+ headers={
216
+ "Accept": "application/vnd.github+json",
217
+ },
218
+ json={"body": body},
219
+ )
220
+ response.raise_for_status()
221
+ return response.json()
222
+
223
+ def get_commit_messages(self, url: str) -> list[str]:
224
+ """Get commit messages from GitHub API."""
225
+ r = self.session.get(
226
+ url,
227
+ headers={
228
+ "Accept": "application/json",
229
+ },
230
+ )
231
+ r.raise_for_status()
232
+ return [data["commit"]["message"] for data in r.json()]
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env python
2
+ """Pretty Release Notes CLI."""
3
+
4
+ import json
5
+ import time
6
+ import tomllib
7
+ from pathlib import Path
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from .adapters.cli_progress import CLIProgressReporter
13
+ from .core.config_loader import TomlConfigLoader
14
+ from .generator import ReleaseNotesGenerator
15
+ from .github_client import GitHubClient
16
+ from .openai_client import SUPPORTED_REASONING_EFFORTS, normalize_reasoning_effort
17
+ from .setup_command import setup_config
18
+ from .ui import CLI
19
+
20
+ app = typer.Typer(
21
+ help="Transform GitHub release notes with AI",
22
+ invoke_without_command=True,
23
+ no_args_is_help=True,
24
+ )
25
+
26
+
27
+ @app.callback()
28
+ def callback():
29
+ """Transform GitHub release notes with AI."""
30
+ pass
31
+
32
+
33
+ @app.command()
34
+ def generate(
35
+ repo: str,
36
+ tag: str,
37
+ owner: str | None = None,
38
+ previous_tag: str | None = None,
39
+ no_database: Annotated[bool, typer.Option("--no-database", help="Skip cache reads and writes")] = False,
40
+ no_db_read: Annotated[bool, typer.Option("--no-db-read", help="Skip reading cached summaries")] = False,
41
+ no_db_write: Annotated[bool, typer.Option("--no-db-write", help="Skip writing new summaries to the cache")] = False,
42
+ prompt_path: Path | None = None,
43
+ force_use_commits: bool = False,
44
+ group_by_type: bool = True,
45
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation and update release notes on GitHub"),
46
+ config_path: Path | None = None,
47
+ reasoning_effort: str | None = typer.Option(
48
+ None,
49
+ "--reasoning-effort",
50
+ help=(f"Override reasoning effort for this run. Supported values: {', '.join(SUPPORTED_REASONING_EFFORTS)}"),
51
+ ),
52
+ ):
53
+ """Generate pretty release notes for a GitHub repository.
54
+
55
+ Configuration is loaded from ~/.pretty-release-notes/config.toml by default.
56
+ Use --config-path to specify a different location.
57
+ """
58
+ start_time = time.time()
59
+
60
+ # Load base config from TOML
61
+ loader = TomlConfigLoader(config_path)
62
+ config = loader.load()
63
+
64
+ # Override with CLI arguments
65
+ if owner:
66
+ config.github.owner = owner
67
+ if prompt_path:
68
+ config.prompt_path = prompt_path
69
+ if no_database:
70
+ config.database.enabled = False
71
+ if no_db_read:
72
+ config.database.read_enabled = False
73
+ if no_db_write:
74
+ config.database.write_enabled = False
75
+ config.force_use_commits = force_use_commits
76
+ if reasoning_effort is not None:
77
+ config.llm.reasoning_effort = normalize_reasoning_effort(reasoning_effort)
78
+ if not group_by_type:
79
+ config.grouping.group_by_type = False
80
+
81
+ # Create UI and adapter
82
+ cli = CLI()
83
+ progress_reporter = CLIProgressReporter(cli)
84
+
85
+ # Determine the owner to use
86
+ repo_owner = owner or config.github.owner
87
+ if not repo_owner:
88
+ raise ValueError("Owner must be specified either via --owner flag or DEFAULT_OWNER in .env")
89
+
90
+ # Create generator with config
91
+ generator = ReleaseNotesGenerator(config, progress_reporter)
92
+ generator.initialize_repository(repo_owner, repo)
93
+ notes = generator.generate(tag, previous_tag_name=previous_tag)
94
+ cli.show_release_notes("New Release Notes", notes)
95
+ end_time = time.time()
96
+ cli.show_success(f"Generated release notes in {end_time - start_time:.2f} seconds total.")
97
+
98
+ if yes or cli.confirm_update():
99
+ generator.update_on_github(notes, tag)
100
+
101
+
102
+ @app.command()
103
+ def setup(
104
+ config_path: Path | None = typer.Option(
105
+ None,
106
+ "--config-path",
107
+ help="Path to config file (default: ~/.pretty-release-notes/config.toml)",
108
+ ),
109
+ migrate_env: bool = typer.Option(
110
+ False,
111
+ "--migrate-env",
112
+ help="Attempt to read and migrate values from .env file",
113
+ ),
114
+ ) -> None:
115
+ """Interactive setup to create or update configuration file.
116
+
117
+ This command walks you through creating a configuration file with
118
+ interactive prompts. Use --migrate-env to read values from an existing
119
+ .env file (useful for one-time migration).
120
+ """
121
+ setup_config(config_path=config_path, migrate_env=migrate_env)
122
+
123
+
124
+ STATE_DIR = Path.home() / ".pretty-release-notes"
125
+ STATE_FILE = STATE_DIR / "processed_releases.json"
126
+
127
+
128
+ def _load_state() -> dict[str, list[str]]:
129
+ if STATE_FILE.exists():
130
+ result: dict[str, list[str]] = json.loads(STATE_FILE.read_text())
131
+ return result
132
+ return {}
133
+
134
+
135
+ def _save_state(state: dict[str, list[str]]) -> None:
136
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
137
+ STATE_FILE.write_text(json.dumps(state, indent=2) + "\n")
138
+
139
+
140
+ def _load_poll_repos(config_path: Path) -> list[str]:
141
+ with open(config_path, "rb") as f:
142
+ raw = tomllib.load(f)
143
+ repos: list[str] = raw.get("poll", {}).get("repos", [])
144
+ if not repos:
145
+ raise typer.BadParameter("No repos configured. Add [poll] repos = [...] to your config file.")
146
+ return repos
147
+
148
+
149
+ @app.command()
150
+ def poll(
151
+ seed: bool = typer.Option(False, "--seed", help="Seed state with current releases without processing them"),
152
+ install_cron: bool = typer.Option(False, "--install-cron", help="Install a crontab entry to poll every 15 minutes"),
153
+ config_path: Path | None = typer.Option(None, "--config-path", help="Path to config file"),
154
+ ):
155
+ """Poll GitHub for new releases and generate notes automatically.
156
+
157
+ Reads the list of repositories from [poll] repos in the config file.
158
+ Run with --seed first to skip existing releases, then --install-cron to automate.
159
+ """
160
+ loader = TomlConfigLoader(config_path)
161
+ config = loader.load()
162
+ repos = _load_poll_repos(loader.config_path)
163
+ github = GitHubClient(config.github.token)
164
+
165
+ state = _load_state()
166
+
167
+ if seed:
168
+ for repo_spec in repos:
169
+ owner, repo_name = repo_spec.split("/", 1)
170
+ releases = github.list_releases(owner, repo_name)
171
+ tags = [str(r["tag_name"]) for r in releases if not r.get("draft")]
172
+ state[repo_spec] = tags
173
+ typer.echo(f"Seeded {repo_spec}: {', '.join(tags)}")
174
+ _save_state(state)
175
+
176
+ if install_cron:
177
+ import shutil
178
+ import subprocess
179
+
180
+ exe = shutil.which("pretty-release-notes")
181
+ if not exe:
182
+ raise typer.BadParameter("pretty-release-notes not found in PATH")
183
+
184
+ cmd = f"{exe} poll"
185
+ if config_path:
186
+ cmd += f" --config-path {config_path}"
187
+
188
+ log_file = STATE_DIR / "poll.log"
189
+ cron_line = f"*/15 * * * * {cmd} >> {log_file} 2>&1"
190
+
191
+ result = subprocess.run(["crontab", "-l"], capture_output=True, text=True)
192
+ existing = result.stdout if result.returncode == 0 else ""
193
+
194
+ if "pretty-release-notes poll" in existing:
195
+ typer.echo("Cron entry already exists.")
196
+ else:
197
+ new_crontab = existing.rstrip("\n") + "\n" + cron_line + "\n"
198
+ subprocess.run(["crontab", "-"], input=new_crontab, text=True, check=True)
199
+ typer.echo(f"Installed: {cron_line}")
200
+
201
+ if seed or install_cron:
202
+ return
203
+
204
+ # One poll cycle
205
+ cli = CLI()
206
+ progress_reporter = CLIProgressReporter(cli)
207
+
208
+ for repo_spec in repos:
209
+ owner, repo_name = repo_spec.split("/", 1)
210
+
211
+ try:
212
+ releases = github.list_releases(owner, repo_name)
213
+ except Exception as e:
214
+ typer.echo(f"ERROR listing {repo_spec}: {e}", err=True)
215
+ continue
216
+
217
+ processed = state.get(repo_spec, [])
218
+
219
+ for release in releases:
220
+ if release.get("draft"):
221
+ continue
222
+
223
+ tag = str(release["tag_name"])
224
+ if tag in processed:
225
+ continue
226
+
227
+ typer.echo(f"Processing {repo_spec} {tag}")
228
+
229
+ try:
230
+ generator = ReleaseNotesGenerator(config, progress_reporter)
231
+ generator.initialize_repository(owner, repo_name)
232
+ notes = generator.generate(tag)
233
+ generator.update_on_github(notes, tag)
234
+
235
+ processed.insert(0, tag)
236
+ state[repo_spec] = processed[:50]
237
+ _save_state(state)
238
+
239
+ typer.echo(f"Done {repo_spec} {tag}")
240
+ except Exception as e:
241
+ typer.echo(f"FAILED {repo_spec} {tag}: {e}", err=True)
242
+
243
+
244
+ if __name__ == "__main__":
245
+ app()
@@ -0,0 +1,15 @@
1
+ from .commit import Commit
2
+ from .issue import Issue
3
+ from .pull_request import PullRequest
4
+ from .release_notes import ReleaseNotes
5
+ from .release_notes_line import ReleaseNotesLine
6
+ from .repository import Repository
7
+
8
+ __all__ = [
9
+ "Issue",
10
+ "PullRequest",
11
+ "Repository",
12
+ "ReleaseNotes",
13
+ "ReleaseNotesLine",
14
+ "Commit",
15
+ ]
@@ -0,0 +1,47 @@
1
+ import re
2
+
3
+ CONVENTIONAL_TYPE_AND_SCOPE = re.compile(r"^([a-zA-Z]{2,8})(?:\(([^)]+)\))?!?:")
4
+ BREAKING_CHANGE_PATTERN = re.compile(r"^[a-zA-Z]{2,8}(?:\([^)]+\))?!:")
5
+
6
+
7
+ def get_conventional_type(msg: str) -> str | None:
8
+ """Extract the conventional type from a message.
9
+
10
+ Examples:
11
+ 'feat(regional): Address Template for Germany & Switzerland' -> 'feat'
12
+ 'Revert "perf: timeout while renaming cost center"' -> None
13
+ 'fix!: breaking change' -> 'fix'
14
+ """
15
+ if not msg:
16
+ return None
17
+
18
+ # Strip leading/trailing whitespace
19
+ msg = msg.strip()
20
+
21
+ if len(msg) < 3:
22
+ return None
23
+
24
+ match = CONVENTIONAL_TYPE_AND_SCOPE.match(msg)
25
+ return match.group(1).lower() if match else None
26
+
27
+
28
+ def is_breaking_change(msg: str) -> bool:
29
+ """Check if a message indicates a breaking change.
30
+
31
+ Breaking changes are indicated by an exclamation mark (!) after the type/scope
32
+ and before the colon, following the Conventional Commits specification.
33
+
34
+ Examples:
35
+ 'feat!: breaking feature' -> True
36
+ 'fix(api)!: breaking fix' -> True
37
+ 'feat: regular feature' -> False
38
+ """
39
+ if not msg:
40
+ return False
41
+
42
+ # Strip leading/trailing whitespace
43
+ msg = msg.strip()
44
+
45
+ # Check for the ! indicator before the colon
46
+ # Pattern: type(scope)!: or type!:
47
+ return bool(BREAKING_CHANGE_PATTERN.match(msg))
@@ -0,0 +1,34 @@
1
+ from typing import TYPE_CHECKING, Protocol
2
+
3
+ if TYPE_CHECKING:
4
+ from pretty_release_notes.github_client import GitHubClient
5
+ from pretty_release_notes.models.repository import Repository
6
+
7
+
8
+ class Change(Protocol):
9
+ github: "GitHubClient"
10
+ repository: "Repository"
11
+ author: str
12
+ labels: set[str] | None
13
+ reviewers: set[str] | None
14
+
15
+ @property
16
+ def conventional_type(self) -> str | None:
17
+ """Extract the conventional type from the change."""
18
+ ...
19
+
20
+ def get_prompt(self, prompt_template: str, max_patch_size: int) -> str:
21
+ """Return the prompt used for summarising this change."""
22
+ ...
23
+
24
+ def set_reviewers(self) -> set[str]:
25
+ """Set the reviewers of this change and the original change that this is a backport of."""
26
+ ...
27
+
28
+ def get_author(self) -> str:
29
+ """Return the author of this change, or of the original change that this is a backport of."""
30
+ ...
31
+
32
+ def get_summary_key(self) -> str:
33
+ """Return the key used for storing the summary in the database."""
34
+ ...
@@ -0,0 +1,75 @@
1
+ from dataclasses import dataclass
2
+ from typing import TYPE_CHECKING
3
+
4
+ from ._utils import get_conventional_type, is_breaking_change
5
+ from .change import Change
6
+
7
+ if TYPE_CHECKING:
8
+ from pretty_release_notes.github_client import GitHubClient
9
+ from pretty_release_notes.models.repository import Repository
10
+
11
+
12
+ @dataclass
13
+ class Commit(Change):
14
+ github: "GitHubClient"
15
+ repository: "Repository"
16
+ id: str # sha
17
+ message: str
18
+ author: str
19
+ html_url: str
20
+ labels: set[str] | None = None
21
+ reviewers: set[str] | None = None
22
+
23
+ @property
24
+ def conventional_type(self) -> str | None:
25
+ return get_conventional_type(self.message)
26
+
27
+ @property
28
+ def is_breaking(self) -> bool:
29
+ """Check if this commit represents a breaking change."""
30
+ return is_breaking_change(self.message)
31
+
32
+ def get_prompt(self, prompt_template: str, max_patch_size: int) -> str:
33
+ prompt = prompt_template
34
+
35
+ changes = self._get_changes(max_patch_size)
36
+ prompt += f"\n\n\n{self}\n\nDiff: {changes}"
37
+
38
+ return prompt
39
+
40
+ def set_reviewers(self) -> set[str]:
41
+ self.reviewers = set()
42
+ return self.reviewers
43
+
44
+ def get_author(self) -> str:
45
+ return self.author
46
+
47
+ def get_summary_key(self) -> str:
48
+ """Return the commit SHA as the summary key."""
49
+ return self.id
50
+
51
+ def _get_changes(self, max_patch_size: int) -> str:
52
+ """Return the diff if it is not too large. Otherwise, return a truncated diff."""
53
+ diff = self._get_diff()
54
+ if len(diff) > max_patch_size:
55
+ return f"{diff[: max_patch_size - 13]}\n\n[TRUNCATED]"
56
+
57
+ return diff
58
+
59
+ def _get_diff(self) -> str:
60
+ """Get the diff for this commit."""
61
+ return self.github.get_commit_diff(self.repository, self.id)
62
+
63
+ @classmethod
64
+ def from_dict(cls, github: "GitHubClient", repository: "Repository", data: dict) -> "Commit":
65
+ return cls(
66
+ github=github,
67
+ repository=repository,
68
+ id=data["sha"],
69
+ message=data["commit"]["message"],
70
+ author=data["author"]["login"],
71
+ html_url=data["html_url"],
72
+ )
73
+
74
+ def __str__(self):
75
+ return f"""Commit Message: {self.message}"""
@@ -0,0 +1,17 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class Issue:
6
+ title: str
7
+ body: str
8
+
9
+ @classmethod
10
+ def from_dict(cls, data: dict) -> "Issue":
11
+ return cls(
12
+ title=data["title"],
13
+ body=data["body"],
14
+ )
15
+
16
+ def __str__(self):
17
+ return f"""Issue Title: {self.title}\n\nIssue Body: {self.body}"""