rooster 0.0.10a1__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.
rooster/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from ._cli import app as app
rooster/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from rooster import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
rooster/_cache.py ADDED
@@ -0,0 +1,45 @@
1
+ import contextlib
2
+ import os
3
+
4
+ import hishel
5
+ import httpx
6
+ from httpcore import Request, Response
7
+
8
+
9
+ class GraphQLCacheController(hishel.Controller):
10
+ def is_cachable(self, request: Request, response: Response) -> bool:
11
+ # Allow the cache to be disabled
12
+ if os.environ.get("ROOSTER_NO_CACHE"):
13
+ return False
14
+
15
+ # Since GraphQL always returns a 200, we check the response body for errors
16
+ error_in_response_body = False
17
+ try:
18
+ cooked_response = httpx.Response(
19
+ status_code=response.status,
20
+ headers=response.headers,
21
+ content=response.content,
22
+ )
23
+ error_in_response_body = cooked_response.json().get("errors")
24
+ except Exception:
25
+ pass # The response cannot be parsed as JSON
26
+ return super().is_cachable(request, response) and not error_in_response_body
27
+
28
+
29
+ @contextlib.contextmanager
30
+ def cached_graphql_client():
31
+ """
32
+ A HTTP client with support for caching GraphQL requests.
33
+
34
+ The cache will be stored at `$PWD/.cache`.
35
+ """
36
+ with httpx.Client(
37
+ transport=hishel.CacheTransport(
38
+ transport=httpx.HTTPTransport(),
39
+ controller=GraphQLCacheController(
40
+ allow_heuristics=True, cacheable_methods=["POST"]
41
+ ),
42
+ ),
43
+ timeout=None,
44
+ ) as client:
45
+ yield client
rooster/_changelog.py ADDED
@@ -0,0 +1,523 @@
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ import copy
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass, field
7
+ from datetime import date
8
+ from pathlib import Path
9
+ from typing import Iterable, Self, cast
10
+
11
+ import marko
12
+ import marko.ast_renderer
13
+ import marko.inline
14
+ import marko.md_renderer
15
+
16
+ from rooster._config import Config
17
+ from rooster._github import PullRequest
18
+ from rooster._versions import (
19
+ Version,
20
+ get_previous_version,
21
+ parse_version,
22
+ to_cargo_version,
23
+ )
24
+
25
+ VERSION_HEADING_PREFIX = "## "
26
+
27
+
28
+ def new_heading(text: str, level: int = 1):
29
+ return marko.parse("#" * level + " " + text + "\n").children[0]
30
+
31
+
32
+ class Section(abc.ABC):
33
+ @abc.abstractclassmethod
34
+ def new(
35
+ cls, document: Document, element: marko.block.BlockElement, title: str
36
+ ) -> Self:
37
+ raise NotImplementedError
38
+
39
+ @classmethod
40
+ def from_elements(
41
+ cls, document: Document, elements: list[marko.block.BlockElement], level: int
42
+ ) -> list[Self]:
43
+ renderer = document.renderer()
44
+ sections = []
45
+ last_section = None
46
+ for element in elements:
47
+ if isinstance(element, marko.block.Heading):
48
+ if element.level < level:
49
+ last_section = None
50
+ continue
51
+ if element.level > level:
52
+ if last_section:
53
+ last_section.children.append(element)
54
+ continue
55
+
56
+ if element.children:
57
+ title = renderer.render(element.children[0])
58
+ entry = cls.new(document=document, element=element, title=title)
59
+ sections.append(entry)
60
+ last_section = entry
61
+ elif isinstance(element, marko.block.BlankLine):
62
+ continue
63
+ else:
64
+ if last_section:
65
+ last_section.children.append(element)
66
+
67
+ return sections
68
+
69
+ def print(self):
70
+ renderer = self.document.renderer()
71
+ if not hasattr(self.element, "link_ref_defs"):
72
+ self.element.link_ref_defs = {}
73
+ print(renderer.render(self.element), end="")
74
+ for child in self.children:
75
+ if isinstance(child, marko.block.BlankLine):
76
+ print()
77
+ else:
78
+ # TODO: Report this as a bug upstream
79
+ if not hasattr(child, "link_ref_defs"):
80
+ child.link_ref_defs = {}
81
+ print(renderer.render(child), end="")
82
+
83
+
84
+ @dataclass
85
+ class Document:
86
+ document: marko.block.Document
87
+
88
+ @classmethod
89
+ def from_markdown(cls, contents: str) -> Self:
90
+ return cls(document=marko.parse(contents))
91
+
92
+ @classmethod
93
+ def from_file(cls, file: str | Path) -> Self:
94
+ return cls.from_markdown(Path(file).read_text())
95
+
96
+ def to_markdown(self) -> str:
97
+ return self.renderer().render(self.document)
98
+
99
+ def to_dict(self) -> dict:
100
+ return marko.ast_renderer.ASTRenderer().render(self.document)
101
+
102
+ def renderer(self) -> marko.md_renderer.MarkdownRenderer:
103
+ renderer = marko.md_renderer.MarkdownRenderer()
104
+ # Workaround for issues rendering links in children
105
+ renderer.root_node = self.document
106
+ return renderer
107
+
108
+ @classmethod
109
+ def empty(cls) -> Self:
110
+ return cls(document=marko.block.Document())
111
+
112
+ def add_child(self, child) -> None:
113
+ self.document.children.append(child)
114
+
115
+ def add_children(self, children) -> None:
116
+ self.document.children.extend(children)
117
+
118
+
119
+ @dataclass
120
+ class Changelog(Document):
121
+ def versions(self, level: int = 2) -> list[VersionSection]:
122
+ """
123
+ Extract version entries from the changelog.
124
+
125
+ Each version is expected to be indicated by a header.
126
+
127
+ By default, we expect versions to all be declared as level two headers.
128
+ An alternative level can be requested.
129
+ """
130
+ return VersionSection.from_elements(self, self.document.children, level=level)
131
+
132
+ def get_version_section(
133
+ self, config: Config, version: Version
134
+ ) -> VersionSection | None:
135
+ for section in self.versions():
136
+ if section.version == (
137
+ to_cargo_version(version)
138
+ if config.version_format == "cargo"
139
+ else str(version)
140
+ ):
141
+ return section
142
+ return None
143
+
144
+ def insert_version_section(self, section: VersionSection, level: int = 2) -> None:
145
+ renderer = self.renderer()
146
+ elements = cast(list, self.document.children)
147
+ remove = None
148
+ i = 0
149
+
150
+ # Scan for an existing version
151
+ for i, element in enumerate(tuple(elements)):
152
+ # Append items to remove...
153
+ if remove:
154
+ remove.append(i)
155
+
156
+ if isinstance(element, marko.block.Heading):
157
+ if element.level == level:
158
+ title = renderer.render(element.children[0])
159
+
160
+ # We got to the next version heading
161
+ if remove:
162
+ # Don't remove the next version
163
+ remove.pop()
164
+ break
165
+
166
+ # Replace the existing version
167
+ if title == section.version:
168
+ remove = [i]
169
+ if remove:
170
+ # As we remove each item, the index of the next item to remove will change
171
+ for i, to_remove in enumerate(sorted(remove)):
172
+ elements.pop(to_remove - i)
173
+ i = remove[0]
174
+ else:
175
+ # Scan for an insertion position
176
+ try:
177
+ compare_version = Version(section.version)
178
+ except Exception:
179
+ # We cannot compare in this case
180
+ compare_version = None
181
+
182
+ for i, element in enumerate(tuple(elements)):
183
+ if not isinstance(element, marko.block.Heading):
184
+ continue
185
+ if element.level != level:
186
+ continue
187
+
188
+ # If we can't compare versions, just stop at the top
189
+ if not compare_version:
190
+ break
191
+
192
+ try:
193
+ version = Version(renderer.render(element.children[0]))
194
+ except Exception:
195
+ # We encountered an invalid version, stop here
196
+ break
197
+
198
+ # Otherwise, stop at the first smaller version
199
+ if version < compare_version:
200
+ break
201
+
202
+ elements.insert(i, section.element)
203
+ elements.insert(i + 1, marko.block.BlankLine)
204
+
205
+ # Insert all the version components
206
+ offset = 0
207
+ for offset, child in enumerate(section.children):
208
+ elements.insert(i + 2 + offset, child)
209
+
210
+ if not section.children:
211
+ elements.insert(i + 2, marko.block.BlankLine)
212
+ elements.insert(i + 2, marko.block.HTMLBlock("<!-- No changes -->"))
213
+
214
+ @classmethod
215
+ def new(cls) -> Self:
216
+ new = cls.empty()
217
+ new.add_child(new_heading("Changelog"))
218
+ new.add_child(marko.block.BlankLine)
219
+ new.add_child(marko.block.BlankLine)
220
+ return new
221
+
222
+
223
+ @dataclass
224
+ class VersionSection(Section):
225
+ document: Document
226
+ element: marko.block.Heading
227
+ title: str
228
+ version: str
229
+ children: list[marko.parser.element.Element] = field(default_factory=list)
230
+
231
+ @classmethod
232
+ def new(
233
+ cls, document: Document, element: marko.block.BlockElement, title: str
234
+ ) -> Self:
235
+ return cls(document, element, title, version=title)
236
+
237
+ def sections(self):
238
+ """
239
+ Extract entry sections from the version section.
240
+ """
241
+ # Sections are expected to be nested a single level deeper
242
+ return ChangesSection.from_elements(
243
+ self.document, self.children, level=self.element.level + 1
244
+ )
245
+
246
+ def all_entries(self):
247
+ entries = []
248
+ for section in self.sections():
249
+ entries.extend(section.entries())
250
+ return entries
251
+
252
+ @classmethod
253
+ def from_pull_requests(
254
+ cls,
255
+ document: Document,
256
+ config: Config,
257
+ version: Version,
258
+ pull_requests: Iterable[PullRequest],
259
+ only_sections: set[str],
260
+ without_sections: set[str],
261
+ level: int = 2,
262
+ release_date: date | None = None,
263
+ ) -> Self:
264
+ section_labels = defaultdict(list, copy.deepcopy(config.section_labels))
265
+
266
+ # Backwards compatibility
267
+ for label, section in config.changelog_sections.items():
268
+ section_labels[section].append(label)
269
+
270
+ # Initialize the sections dictionary to match the config ordering
271
+ sections = {section: [] for section in section_labels.keys()}
272
+
273
+ # If there are no sections, put all changes into "Changes", otherwise,
274
+ # use `Other changes`
275
+ other_section = "Other changes" if sections else "Changes"
276
+ sections[other_section] = []
277
+
278
+ authors = {
279
+ pull_request.author
280
+ for pull_request in pull_requests
281
+ if pull_request.author not in config.changelog_ignore_authors
282
+ }
283
+
284
+ # De-duplicate pull requests and sort into sections
285
+ for pull_request in sorted(set(pull_requests)):
286
+ for label in pull_request.labels:
287
+ if label in config.changelog_ignore_labels:
288
+ break
289
+ if label in without_sections:
290
+ break
291
+ else:
292
+ # Iterate in-order of changelog sections to support user-configured precedence
293
+ for section, labels in section_labels.items():
294
+ if only_sections and section not in only_sections:
295
+ continue
296
+ if pull_request.labels.intersection(labels):
297
+ sections[section].append(pull_request)
298
+ break
299
+ else:
300
+ if not only_sections:
301
+ sections[
302
+ section_labels.get("__unknown__", other_section)
303
+ ].append(pull_request)
304
+
305
+ children = []
306
+ for section, pull_requests in sections.items():
307
+ # Omit empty sections
308
+ if not pull_requests:
309
+ continue
310
+
311
+ pull_requests = sorted(pull_requests, key=lambda pr: pr.title)
312
+
313
+ changes_section = ChangesSection.from_pull_requests(
314
+ document=document,
315
+ config=config,
316
+ section=section,
317
+ pull_requests=pull_requests,
318
+ )
319
+ children.append(changes_section.element)
320
+ children.extend(changes_section.children)
321
+
322
+ if config.changelog_contributors and authors:
323
+ section = ContributorsSection.from_authors(
324
+ document=document, authors=authors
325
+ )
326
+ children.append(section.element)
327
+ children.extend(section.children)
328
+
329
+ version = (
330
+ to_cargo_version(version)
331
+ if config.version_format == "cargo"
332
+ else str(version)
333
+ )
334
+ heading_element = new_heading(version, level=level)
335
+
336
+ # Add release date paragraph
337
+ if release_date is None:
338
+ release_date = date.today()
339
+ date_str = release_date.strftime("%Y-%m-%d")
340
+ release_date_text = f"Released on {date_str}."
341
+ release_date_paragraph = marko.parse(release_date_text + "\n").children[0]
342
+
343
+ # Insert release date at the beginning of children
344
+ all_children = [release_date_paragraph, marko.block.BlankLine] + children
345
+
346
+ return cls(
347
+ document=document,
348
+ element=heading_element,
349
+ title=version,
350
+ version=version,
351
+ children=all_children,
352
+ )
353
+
354
+ def as_document(self) -> Document:
355
+ document = Document.empty()
356
+ document.add_child(self.element)
357
+ document.add_child(marko.block.BlankLine)
358
+ document.add_children(self.children)
359
+ return document
360
+
361
+
362
+ @dataclass
363
+ class ListSection(Section):
364
+ document: Document
365
+ element: marko.block.Heading
366
+ title: str
367
+ children: list[marko.parser.element.Element] = field(default_factory=list)
368
+
369
+ @classmethod
370
+ def new(
371
+ cls, document: Document, element: marko.block.BlockElement, title: str
372
+ ) -> Self:
373
+ return cls(document, element, title)
374
+
375
+ def entries(self):
376
+ """ """
377
+ entries = []
378
+ for element in self.children:
379
+ if isinstance(element, marko.block.List):
380
+ for item in element.children:
381
+ entries.append(Entry(self.document, item))
382
+
383
+ return entries
384
+
385
+
386
+ @dataclass
387
+ class ChangesSection(ListSection):
388
+ @classmethod
389
+ def from_pull_requests(
390
+ cls,
391
+ document: Document,
392
+ config: Config,
393
+ section: str,
394
+ pull_requests: Iterable[PullRequest],
395
+ level: int = 3,
396
+ ) -> Self:
397
+ heading = new_heading(section, level)
398
+
399
+ lines = []
400
+ for pull_request in pull_requests:
401
+ line = config.change_template.format(pull_request=pull_request)
402
+ lines.append(line)
403
+
404
+ return cls(
405
+ document=document,
406
+ element=heading,
407
+ title=section,
408
+ children=(
409
+ [marko.block.BlankLine]
410
+ + marko.parse("\n".join(lines)).children
411
+ + [marko.block.BlankLine]
412
+ ),
413
+ )
414
+
415
+
416
+ @dataclass
417
+ class ContributorsSection(ListSection):
418
+ @classmethod
419
+ def from_authors(
420
+ cls,
421
+ document: Document,
422
+ authors: Iterable[PullRequest],
423
+ level: int = 3,
424
+ ) -> Self:
425
+ heading = new_heading("Contributors", level)
426
+
427
+ lines = []
428
+ for author in authors:
429
+ line = f"- [@{author}](https://github.com/{author})"
430
+ lines.append(line)
431
+
432
+ return cls(
433
+ document=document,
434
+ element=heading,
435
+ title="Contributors",
436
+ children=(
437
+ [marko.block.BlankLine]
438
+ + marko.parse("\n".join(lines)).children
439
+ + [marko.block.BlankLine]
440
+ ),
441
+ )
442
+
443
+
444
+ @dataclass
445
+ class Entry:
446
+ document: Document
447
+ element: marko.block.ListItem
448
+
449
+ def content(self) -> str:
450
+ return self.document.renderer().render_children(self.element)
451
+
452
+
453
+ def ensure_spacing(changelog: str) -> str:
454
+ # Sloppily ensure we don't have too much spacing
455
+ while "\n\n\n" in changelog:
456
+ changelog = changelog.replace("\n\n\n", "\n\n")
457
+
458
+ # Ensure we always end with a single newline
459
+ return changelog.rstrip("\n") + "\n"
460
+
461
+
462
+ def get_versions_from_changelog(config: Config, changelog: str) -> list[Version]:
463
+ """
464
+ Get all versions from headings from the changelog
465
+ """
466
+
467
+ return filter(
468
+ lambda x: x is not None,
469
+ [
470
+ parse_version(config, line[2:].strip())
471
+ for line in changelog.splitlines()
472
+ if line.startswith(VERSION_HEADING_PREFIX)
473
+ ],
474
+ )
475
+
476
+
477
+ def extract_entry(config: Config, changelog: str, version: Version) -> str | None:
478
+ """
479
+ Extract an entry for the given version from the changelog
480
+ """
481
+ version_str = (
482
+ to_cargo_version(version) if config.version_format == "cargo" else str(version)
483
+ )
484
+ heading = f"{VERSION_HEADING_PREFIX}{version_str}\n\n"
485
+
486
+ versions = get_versions_from_changelog(config, changelog)
487
+ previous_version = get_previous_version(versions, version)
488
+
489
+ # If there are no versions in the file, return `None`
490
+ if not previous_version and heading not in changelog:
491
+ return None
492
+
493
+ previous_version_str = (
494
+ (
495
+ to_cargo_version(version)
496
+ if config.version_format == "cargo"
497
+ else str(version)
498
+ )
499
+ if previous_version
500
+ else None
501
+ )
502
+ previous_heading = (
503
+ f"{VERSION_HEADING_PREFIX}{previous_version_str}\n\n"
504
+ if previous_version
505
+ else None
506
+ )
507
+
508
+ if heading not in changelog:
509
+ return None
510
+
511
+ start = changelog.index(heading)
512
+ end = changelog.index(previous_heading) if previous_heading else len(changelog)
513
+ return changelog[start:end]
514
+
515
+
516
+ def entry_to_standalone(changelog_entry: str, version: Version) -> str:
517
+ """
518
+ Convert an entry from the CHANGELOG file to a standalone entry (omitting the version)
519
+ """
520
+ return changelog_entry.replace(
521
+ f"{VERSION_HEADING_PREFIX} {version}\n",
522
+ f"{VERSION_HEADING_PREFIX} Changes\n<!-- Generated from the CHANGELOG file -->\n",
523
+ )