keep-github-workflows-active 2.3.5__py3-none-any.whl → 3.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.
- keep_github_workflows_active/__init__conf__.py +5 -5
- keep_github_workflows_active/behaviors.py +17 -19
- keep_github_workflows_active/cli.py +34 -22
- keep_github_workflows_active/keep_github_workflow_active.py +222 -105
- keep_github_workflows_active-3.0.0.dist-info/METADATA +280 -0
- {keep_github_workflows_active-2.3.5.dist-info → keep_github_workflows_active-3.0.0.dist-info}/RECORD +9 -9
- {keep_github_workflows_active-2.3.5.dist-info → keep_github_workflows_active-3.0.0.dist-info}/WHEEL +1 -1
- keep_github_workflows_active-2.3.5.dist-info/METADATA +0 -240
- {keep_github_workflows_active-2.3.5.dist-info → keep_github_workflows_active-3.0.0.dist-info}/entry_points.txt +0 -0
- {keep_github_workflows_active-2.3.5.dist-info → keep_github_workflows_active-3.0.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,3 +1,34 @@
|
|
|
1
|
+
"""Keep the GitHub Actions workflows of an owner's repositories enabled and prune old runs.
|
|
2
|
+
|
|
3
|
+
Purpose
|
|
4
|
+
-------
|
|
5
|
+
Talk to the GitHub REST API for the two maintenance commands: re-enable every
|
|
6
|
+
workflow of every repository of an owner, and delete all but the newest
|
|
7
|
+
workflow runs of each repository.
|
|
8
|
+
|
|
9
|
+
Contents
|
|
10
|
+
--------
|
|
11
|
+
* :func:`get_owner` / :func:`get_github_token` - read ``SECRET_GITHUB_OWNER`` /
|
|
12
|
+
``SECRET_GITHUB_TOKEN`` from the environment or a ``.env`` file
|
|
13
|
+
(:func:`_lookup_config_value`, :func:`_candidate_env_files`,
|
|
14
|
+
``KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH``).
|
|
15
|
+
* :func:`github_session` - the ``requests.Session`` every API call of a run uses.
|
|
16
|
+
* :func:`enable_all_workflows` / :func:`delete_old_workflow_runs` - the entry
|
|
17
|
+
points behind the CLI commands; they take ``owner`` and ``github_token``.
|
|
18
|
+
* :func:`get_repositories`, :func:`get_workflows`, :func:`get_workflow_runs`,
|
|
19
|
+
:func:`enable_workflow`, :func:`delete_workflow_run` - single API steps that
|
|
20
|
+
take the session.
|
|
21
|
+
* Pydantic reply models and :func:`_parse_reply`, which refuses a reply missing
|
|
22
|
+
a field the tool acts on with ``RuntimeError("Unexpected GitHub reply for ...")``.
|
|
23
|
+
|
|
24
|
+
System Role
|
|
25
|
+
-----------
|
|
26
|
+
The GitHub boundary: replies are parsed into the models here, and every log
|
|
27
|
+
message passes through :func:`keep_github_workflows_active.sanitization.sanitize_message`.
|
|
28
|
+
pytest's ``addopts`` ignores this module, so its doctests do not run; several of
|
|
29
|
+
them call the live API when credentials are configured.
|
|
30
|
+
"""
|
|
31
|
+
|
|
1
32
|
# STDLIB
|
|
2
33
|
from __future__ import annotations
|
|
3
34
|
|
|
@@ -6,18 +37,24 @@ import os
|
|
|
6
37
|
import pathlib
|
|
7
38
|
import sys
|
|
8
39
|
from enum import IntEnum
|
|
9
|
-
from
|
|
40
|
+
from types import MappingProxyType
|
|
41
|
+
from typing import TYPE_CHECKING, Final, NamedTuple, cast
|
|
10
42
|
|
|
11
43
|
# EXT
|
|
12
44
|
import requests
|
|
13
|
-
from pydantic import BaseModel, ConfigDict,
|
|
45
|
+
from pydantic import BaseModel, ConfigDict, ValidationError, model_validator
|
|
14
46
|
|
|
15
47
|
# LOCAL
|
|
16
48
|
from . import sanitization
|
|
17
49
|
|
|
50
|
+
if TYPE_CHECKING:
|
|
51
|
+
from collections.abc import Mapping
|
|
52
|
+
|
|
18
53
|
REQUEST_TIMEOUT_SECONDS = 30
|
|
19
54
|
#: GitHub API status code returned when the org endpoint has no matching organization.
|
|
20
55
|
HTTP_STATUS_NOT_FOUND = 404
|
|
56
|
+
#: Media type GitHub's REST API v3 answers with.
|
|
57
|
+
GITHUB_ACCEPT_HEADER = "application/vnd.github.v3+json"
|
|
21
58
|
|
|
22
59
|
logger = logging.getLogger(__name__)
|
|
23
60
|
|
|
@@ -35,11 +72,22 @@ class SkippedWorkflowType(IntEnum):
|
|
|
35
72
|
UPDATE_GRAPH = 3
|
|
36
73
|
|
|
37
74
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
75
|
+
class SkippedWorkflowRule(NamedTuple):
|
|
76
|
+
"""File name prefix of a skipped workflow and the reason the skip message gives."""
|
|
77
|
+
|
|
78
|
+
prefix: str
|
|
79
|
+
reason: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
#: One row per :class:`SkippedWorkflowType`; ``tests/test_github_api.py`` checks every member
|
|
83
|
+
#: has a row, so a new type cannot be added without its prefix and its reason.
|
|
84
|
+
SKIPPED_WORKFLOWS: Final[Mapping[SkippedWorkflowType, SkippedWorkflowRule]] = MappingProxyType(
|
|
85
|
+
{
|
|
86
|
+
SkippedWorkflowType.PAGES_BUILD_DEPLOYMENT: SkippedWorkflowRule("pages-build-deployment", "those can not be enabled"),
|
|
87
|
+
SkippedWorkflowType.DEPENDABOT: SkippedWorkflowRule("dependabot", "managed by Dependabot"),
|
|
88
|
+
SkippedWorkflowType.UPDATE_GRAPH: SkippedWorkflowRule("update-graph", "managed by GitHub dependency graph"),
|
|
89
|
+
}
|
|
90
|
+
)
|
|
43
91
|
|
|
44
92
|
|
|
45
93
|
# =============================================================================
|
|
@@ -51,37 +99,36 @@ class GitHubRepository(BaseModel):
|
|
|
51
99
|
"""GitHub repository from API response."""
|
|
52
100
|
|
|
53
101
|
model_config = ConfigDict(extra="ignore")
|
|
54
|
-
name: str
|
|
102
|
+
name: str
|
|
55
103
|
|
|
56
104
|
|
|
57
105
|
class GitHubRepositoriesResponse(BaseModel):
|
|
58
106
|
"""List of repositories from GitHub API.
|
|
59
107
|
|
|
60
|
-
|
|
61
|
-
|
|
108
|
+
GitHub answers the repository listing with a bare JSON array; the validator wraps it into
|
|
109
|
+
``{"repositories": [...]}``. Any other shape is passed on unchanged, so validation refuses
|
|
110
|
+
it rather than reading it as an empty listing.
|
|
62
111
|
"""
|
|
63
112
|
|
|
64
113
|
model_config = ConfigDict(extra="ignore")
|
|
65
|
-
repositories: list[GitHubRepository]
|
|
66
|
-
default_factory=list
|
|
67
|
-
)
|
|
114
|
+
repositories: list[GitHubRepository]
|
|
68
115
|
|
|
69
116
|
@model_validator(mode="before")
|
|
70
117
|
@classmethod
|
|
71
|
-
def _wrap_list_response(cls, data:
|
|
72
|
-
"""Wrap
|
|
118
|
+
def _wrap_list_response(cls, data: object) -> object:
|
|
119
|
+
"""Wrap a bare JSON array into the ``repositories`` field."""
|
|
73
120
|
if isinstance(data, list):
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return
|
|
77
|
-
return
|
|
121
|
+
# isinstance cannot name the element type; the elements are validated as
|
|
122
|
+
# GitHubRepository right after this hook.
|
|
123
|
+
return {"repositories": cast("list[object]", data)}
|
|
124
|
+
return data
|
|
78
125
|
|
|
79
126
|
|
|
80
127
|
class GitHubWorkflow(BaseModel):
|
|
81
128
|
"""GitHub workflow from API response."""
|
|
82
129
|
|
|
83
130
|
model_config = ConfigDict(extra="ignore")
|
|
84
|
-
path: str
|
|
131
|
+
path: str
|
|
85
132
|
|
|
86
133
|
@property
|
|
87
134
|
def filename(self) -> str:
|
|
@@ -96,16 +143,14 @@ class GitHubWorkflowsResponse(BaseModel):
|
|
|
96
143
|
"""
|
|
97
144
|
|
|
98
145
|
model_config = ConfigDict(extra="ignore")
|
|
99
|
-
workflows: list[GitHubWorkflow]
|
|
100
|
-
default_factory=list
|
|
101
|
-
)
|
|
146
|
+
workflows: list[GitHubWorkflow]
|
|
102
147
|
|
|
103
148
|
|
|
104
149
|
class GitHubWorkflowRun(BaseModel):
|
|
105
150
|
"""GitHub workflow run from API response."""
|
|
106
151
|
|
|
107
152
|
model_config = ConfigDict(extra="ignore")
|
|
108
|
-
id: int
|
|
153
|
+
id: int
|
|
109
154
|
|
|
110
155
|
|
|
111
156
|
class GitHubWorkflowRunsResponse(BaseModel):
|
|
@@ -115,9 +160,7 @@ class GitHubWorkflowRunsResponse(BaseModel):
|
|
|
115
160
|
"""
|
|
116
161
|
|
|
117
162
|
model_config = ConfigDict(extra="ignore")
|
|
118
|
-
workflow_runs: list[GitHubWorkflowRun]
|
|
119
|
-
default_factory=list
|
|
120
|
-
)
|
|
163
|
+
workflow_runs: list[GitHubWorkflowRun]
|
|
121
164
|
|
|
122
165
|
|
|
123
166
|
class GitHubErrorResponse(BaseModel):
|
|
@@ -136,7 +179,7 @@ class GitHubErrorResponse(BaseModel):
|
|
|
136
179
|
return cls()
|
|
137
180
|
try:
|
|
138
181
|
return cls.model_validate(response.json())
|
|
139
|
-
except
|
|
182
|
+
except ValueError, AttributeError:
|
|
140
183
|
return cls(message=response.text or response.reason or "Error")
|
|
141
184
|
|
|
142
185
|
|
|
@@ -222,9 +265,11 @@ def _candidate_env_files() -> list[pathlib.Path]:
|
|
|
222
265
|
|
|
223
266
|
Why
|
|
224
267
|
Developers often run the script from varying working directories. We
|
|
225
|
-
probe
|
|
226
|
-
|
|
227
|
-
|
|
268
|
+
probe the file named by ``KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH`` (if
|
|
269
|
+
set), then common locations (current working directory, the package
|
|
270
|
+
folder, and two levels above it, which is the repository root in a source
|
|
271
|
+
checkout) so local and CI workflows can share the same fallback
|
|
272
|
+
behaviour.
|
|
228
273
|
|
|
229
274
|
Returns
|
|
230
275
|
-------
|
|
@@ -353,11 +398,48 @@ def _lookup_config_value(key: str) -> str:
|
|
|
353
398
|
raise RuntimeError(f"Missing required configuration: {key}")
|
|
354
399
|
|
|
355
400
|
|
|
401
|
+
def github_session(github_token: str) -> requests.Session:
|
|
402
|
+
"""Return a session that carries the GitHub auth headers and reuses its connections.
|
|
403
|
+
|
|
404
|
+
Why
|
|
405
|
+
A run makes one API call per repository page, per repository for workflows and runs,
|
|
406
|
+
one PUT per workflow and one DELETE per old run. A bare ``requests.get`` opens a new
|
|
407
|
+
TLS connection for each; a session keeps it alive (measured against api.github.com:
|
|
408
|
+
128 ms per call without, 45 ms with).
|
|
409
|
+
|
|
410
|
+
Parameters
|
|
411
|
+
----------
|
|
412
|
+
github_token:
|
|
413
|
+
Personal access token sent as the Bearer authorization.
|
|
414
|
+
|
|
415
|
+
Returns
|
|
416
|
+
-------
|
|
417
|
+
requests.Session
|
|
418
|
+
Session to pass to the API functions; close it (``with``) when the run ends.
|
|
419
|
+
|
|
420
|
+
Examples
|
|
421
|
+
--------
|
|
422
|
+
>>> with github_session("t0ken") as session:
|
|
423
|
+
... session.headers["Authorization"], session.headers["Accept"]
|
|
424
|
+
('Bearer t0ken', 'application/vnd.github.v3+json')
|
|
425
|
+
"""
|
|
426
|
+
session = requests.Session()
|
|
427
|
+
session.headers.update({"Authorization": f"Bearer {github_token}", "Accept": GITHUB_ACCEPT_HEADER})
|
|
428
|
+
return session
|
|
429
|
+
|
|
430
|
+
|
|
356
431
|
def enable_all_workflows(owner: str, github_token: str) -> None:
|
|
357
432
|
"""
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
:
|
|
433
|
+
Enable every workflow of every repository of ``owner``.
|
|
434
|
+
|
|
435
|
+
Opens one :func:`github_session` for the run, lists the repositories and their
|
|
436
|
+
workflow files, writes ``activate workflow <repo>/<file>`` for each and calls
|
|
437
|
+
:func:`enable_workflow`, which skips the prefixes in ``SKIPPED_WORKFLOWS``.
|
|
438
|
+
|
|
439
|
+
:param owner: The user or organisation owning the repositories.
|
|
440
|
+
:param github_token: Personal access token for the session.
|
|
441
|
+
:return: None
|
|
442
|
+
:raises RuntimeError: When GitHub answers an error status or a malformed reply.
|
|
361
443
|
|
|
362
444
|
>>> try:
|
|
363
445
|
... my_owner = get_owner()
|
|
@@ -370,20 +452,29 @@ def enable_all_workflows(owner: str, github_token: str) -> None:
|
|
|
370
452
|
|
|
371
453
|
"""
|
|
372
454
|
sys.stdout.write(f"Activating and maintaining all workflows for owner {owner}:\n")
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
455
|
+
with github_session(github_token) as session:
|
|
456
|
+
repositories = get_repositories(owner=owner, session=session)
|
|
457
|
+
for repository in repositories:
|
|
458
|
+
workflows = get_workflows(owner=owner, repository=repository, session=session)
|
|
459
|
+
for workflow_filename in workflows:
|
|
460
|
+
sys.stdout.write(f"activate workflow {repository}/{workflow_filename}\n")
|
|
461
|
+
enable_workflow(owner=owner, repository=repository, workflow_filename=workflow_filename, session=session)
|
|
379
462
|
|
|
380
463
|
|
|
381
464
|
def delete_old_workflow_runs(owner: str, github_token: str, number_of_workflow_runs_to_keep: int = 50) -> None:
|
|
382
465
|
"""
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
:
|
|
386
|
-
|
|
466
|
+
Delete all but the newest workflow runs of every repository of ``owner``.
|
|
467
|
+
|
|
468
|
+
Opens one :func:`github_session` for the run. Per repository, all run ids (across
|
|
469
|
+
all of its workflows) are sorted descending; the first
|
|
470
|
+
``number_of_workflow_runs_to_keep`` are kept and :func:`delete_workflow_run` is
|
|
471
|
+
called for the rest, writing ``remove workflow run <repo>/<run_id>`` for each.
|
|
472
|
+
|
|
473
|
+
:param owner: The user or organisation owning the repositories.
|
|
474
|
+
:param github_token: Personal access token for the session.
|
|
475
|
+
:param number_of_workflow_runs_to_keep: Runs to keep per repository.
|
|
476
|
+
:return: None
|
|
477
|
+
:raises RuntimeError: When GitHub answers an error status or a malformed reply.
|
|
387
478
|
|
|
388
479
|
>>> try:
|
|
389
480
|
... owner = get_owner()
|
|
@@ -400,19 +491,20 @@ def delete_old_workflow_runs(owner: str, github_token: str, number_of_workflow_r
|
|
|
400
491
|
f"Removing outdated workflow executions for owner {owner}, "
|
|
401
492
|
f"while retaining a maximum of {number_of_workflow_runs_to_keep} workflow runs per repository:\n"
|
|
402
493
|
)
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
494
|
+
with github_session(github_token) as session:
|
|
495
|
+
l_repositories = get_repositories(owner=owner, session=session)
|
|
496
|
+
for repository in l_repositories:
|
|
497
|
+
workflow_run_ids = get_workflow_runs(owner=owner, repository=repository, session=session)
|
|
498
|
+
workflow_run_ids_sorted = sorted(workflow_run_ids, reverse=True)
|
|
499
|
+
workflow_run_ids_to_delete = workflow_run_ids_sorted[number_of_workflow_runs_to_keep:]
|
|
500
|
+
logger.info(
|
|
501
|
+
sanitization.sanitize_message(
|
|
502
|
+
f"repository: {repository}, {len(workflow_run_ids)} workflow runs found, {len(workflow_run_ids_to_delete)} to delete."
|
|
503
|
+
)
|
|
411
504
|
)
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
delete_workflow_run(owner=owner, repository=repository, github_token=github_token, run_id_to_delete=run_id_to_delete)
|
|
505
|
+
for run_id_to_delete in workflow_run_ids_to_delete:
|
|
506
|
+
sys.stdout.write(f"remove workflow run {repository}/{run_id_to_delete}\n")
|
|
507
|
+
delete_workflow_run(owner=owner, repository=repository, session=session, run_id_to_delete=run_id_to_delete)
|
|
416
508
|
|
|
417
509
|
|
|
418
510
|
def get_owner() -> str:
|
|
@@ -458,6 +550,33 @@ def get_github_token() -> str:
|
|
|
458
550
|
return _lookup_config_value("SECRET_GITHUB_TOKEN")
|
|
459
551
|
|
|
460
552
|
|
|
553
|
+
def _parse_reply[ReplyModelT: BaseModel](model: type[ReplyModelT], response: requests.Response, *, what: str) -> ReplyModelT:
|
|
554
|
+
"""Parse a successful GitHub reply into ``model``, refusing a body that does not fit it.
|
|
555
|
+
|
|
556
|
+
Why
|
|
557
|
+
A reply missing a field the tool acts on (a run id, a repository name, the listing
|
|
558
|
+
itself) must stop the run: read with defaults it would delete run 0 or report an empty
|
|
559
|
+
listing and exit 0.
|
|
560
|
+
|
|
561
|
+
Raises
|
|
562
|
+
------
|
|
563
|
+
RuntimeError
|
|
564
|
+
Naming ``what`` and one ``<field path>: <reason>`` per validation error, or saying the
|
|
565
|
+
body is not JSON. The original exception is kept as ``__cause__``.
|
|
566
|
+
"""
|
|
567
|
+
try:
|
|
568
|
+
return model.model_validate(response.json())
|
|
569
|
+
except ValidationError as exc:
|
|
570
|
+
details = "; ".join(f"{'.'.join(str(part) for part in error['loc']) or '<reply>'}: {error['msg']}" for error in exc.errors())
|
|
571
|
+
message = f"Unexpected GitHub reply for {what}: {details}"
|
|
572
|
+
logger.error(sanitization.sanitize_message(message))
|
|
573
|
+
raise RuntimeError(message) from exc
|
|
574
|
+
except ValueError as exc:
|
|
575
|
+
message = f"Unexpected GitHub reply for {what}: the body is not JSON"
|
|
576
|
+
logger.error(sanitization.sanitize_message(message))
|
|
577
|
+
raise RuntimeError(message) from exc
|
|
578
|
+
|
|
579
|
+
|
|
461
580
|
def _get_next_page_url(response: requests.Response) -> str | None:
|
|
462
581
|
"""Extract next page URL from GitHub API pagination links.
|
|
463
582
|
|
|
@@ -479,17 +598,21 @@ def _get_next_page_url(response: requests.Response) -> str | None:
|
|
|
479
598
|
return link.url if link else None
|
|
480
599
|
|
|
481
600
|
|
|
482
|
-
def get_repositories(owner: str,
|
|
601
|
+
def get_repositories(owner: str, session: requests.Session) -> list[str]:
|
|
483
602
|
"""
|
|
484
|
-
Fetch all
|
|
603
|
+
Fetch all repository names of an organisation or user, handling pagination and setting the page size to 100.
|
|
604
|
+
|
|
605
|
+
Requests ``/orgs/<owner>/repos`` first; when GitHub answers 404 the owner is no
|
|
606
|
+
organisation and ``/users/<owner>/repos`` is listed instead.
|
|
485
607
|
|
|
486
608
|
:param owner: The username of the repository owner.
|
|
487
|
-
:param
|
|
609
|
+
:param session: Session from :func:`github_session` carrying the auth headers.
|
|
488
610
|
:return: A list of repository names.
|
|
489
611
|
|
|
490
612
|
>>> has_secrets = {"SECRET_GITHUB_OWNER", "SECRET_GITHUB_TOKEN"}.issubset(os.environ)
|
|
491
613
|
>>> if has_secrets:
|
|
492
|
-
...
|
|
614
|
+
... with github_session(get_github_token()) as session:
|
|
615
|
+
... repos = get_repositories(get_owner(), session)
|
|
493
616
|
... else:
|
|
494
617
|
... repos = []
|
|
495
618
|
>>> isinstance(repos, list)
|
|
@@ -498,12 +621,11 @@ def get_repositories(owner: str, github_token: str) -> list[str]:
|
|
|
498
621
|
|
|
499
622
|
"""
|
|
500
623
|
repositories: list[str] = []
|
|
501
|
-
headers: dict[str, str | bytes] = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
502
624
|
|
|
503
625
|
# Try the org endpoint first (returns private repos too), fall back to user endpoint.
|
|
504
626
|
org_url = f"https://api.github.com/orgs/{owner}/repos?per_page=100"
|
|
505
627
|
user_url = f"https://api.github.com/users/{owner}/repos?per_page=100"
|
|
506
|
-
probe =
|
|
628
|
+
probe = session.get(org_url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
507
629
|
if probe.status_code == HTTP_STATUS_NOT_FOUND:
|
|
508
630
|
url: str | None = user_url
|
|
509
631
|
probe = None # Discard the 404 so the loop fetches fresh from user endpoint.
|
|
@@ -518,9 +640,9 @@ def get_repositories(owner: str, github_token: str) -> list[str]:
|
|
|
518
640
|
probe = None
|
|
519
641
|
response.raise_for_status()
|
|
520
642
|
else:
|
|
521
|
-
response =
|
|
643
|
+
response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
522
644
|
response.raise_for_status()
|
|
523
|
-
parsed = GitHubRepositoriesResponse
|
|
645
|
+
parsed = _parse_reply(GitHubRepositoriesResponse, response, what=f"repositories of {owner}")
|
|
524
646
|
repositories.extend(repo.name for repo in parsed.repositories)
|
|
525
647
|
url = _get_next_page_url(response)
|
|
526
648
|
|
|
@@ -535,14 +657,14 @@ def get_repositories(owner: str, github_token: str) -> list[str]:
|
|
|
535
657
|
return repositories
|
|
536
658
|
|
|
537
659
|
|
|
538
|
-
def get_workflows(owner: str, repository: str,
|
|
660
|
+
def get_workflows(owner: str, repository: str, session: requests.Session) -> list[str]:
|
|
539
661
|
"""
|
|
540
662
|
Fetch all workflows for a given GitHub repository, handling pagination and setting the page size to 100.
|
|
541
663
|
|
|
542
664
|
:param owner: The username of the repository owner.
|
|
543
665
|
:param repository: The name of the repository.
|
|
544
|
-
:param
|
|
545
|
-
:return:
|
|
666
|
+
:param session: Session from :func:`github_session` carrying the auth headers.
|
|
667
|
+
:return: The workflow file names (last component of each workflow's path).
|
|
546
668
|
|
|
547
669
|
|
|
548
670
|
>>> try:
|
|
@@ -551,21 +673,20 @@ def get_workflows(owner: str, repository: str, github_token: str) -> list[str]:
|
|
|
551
673
|
... except RuntimeError:
|
|
552
674
|
... owner = token = None
|
|
553
675
|
>>> if owner and token:
|
|
554
|
-
...
|
|
555
|
-
...
|
|
556
|
-
...
|
|
676
|
+
... with github_session(token) as session:
|
|
677
|
+
... for repo in get_repositories(owner=owner, session=session):
|
|
678
|
+
... _ = get_workflows(owner=owner, repository=repo, session=session)
|
|
557
679
|
|
|
558
680
|
|
|
559
681
|
"""
|
|
560
682
|
workflows: list[str] = []
|
|
561
683
|
url: str | None = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows?per_page=100"
|
|
562
|
-
headers: dict[str, str | bytes] = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
563
684
|
|
|
564
685
|
while url:
|
|
565
686
|
try:
|
|
566
|
-
response =
|
|
687
|
+
response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
567
688
|
response.raise_for_status()
|
|
568
|
-
parsed = GitHubWorkflowsResponse
|
|
689
|
+
parsed = _parse_reply(GitHubWorkflowsResponse, response, what=f"workflows of {owner}/{repository}")
|
|
569
690
|
workflows.extend(workflow.filename for workflow in parsed.workflows)
|
|
570
691
|
url = _get_next_page_url(response)
|
|
571
692
|
|
|
@@ -580,13 +701,13 @@ def get_workflows(owner: str, repository: str, github_token: str) -> list[str]:
|
|
|
580
701
|
return workflows
|
|
581
702
|
|
|
582
703
|
|
|
583
|
-
def get_workflow_runs(owner: str, repository: str,
|
|
704
|
+
def get_workflow_runs(owner: str, repository: str, session: requests.Session) -> list[int]:
|
|
584
705
|
"""
|
|
585
706
|
Fetch all workflow runs for a GitHub repository using the GitHub API v3, handling pagination.
|
|
586
707
|
|
|
587
708
|
:param owner: The username of the repository owner.
|
|
588
709
|
:param repository: The name of the repository.
|
|
589
|
-
:param
|
|
710
|
+
:param session: Session from :func:`github_session` carrying the auth headers.
|
|
590
711
|
:return: A list of workflow run IDs.
|
|
591
712
|
|
|
592
713
|
>>> try:
|
|
@@ -595,21 +716,20 @@ def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[in
|
|
|
595
716
|
... except RuntimeError:
|
|
596
717
|
... owner = token = None
|
|
597
718
|
>>> if owner and token:
|
|
598
|
-
...
|
|
599
|
-
...
|
|
600
|
-
...
|
|
719
|
+
... with github_session(token) as session:
|
|
720
|
+
... for repo in get_repositories(owner=owner, session=session):
|
|
721
|
+
... _ = get_workflow_runs(owner=owner, repository=repo, session=session)
|
|
601
722
|
|
|
602
723
|
|
|
603
724
|
"""
|
|
604
725
|
url: str | None = f"https://api.github.com/repos/{owner}/{repository}/actions/runs?per_page=100"
|
|
605
|
-
headers: dict[str, str | bytes] = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
606
726
|
|
|
607
727
|
workflow_run_ids: list[int] = []
|
|
608
728
|
while url:
|
|
609
729
|
try:
|
|
610
|
-
response =
|
|
730
|
+
response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
611
731
|
response.raise_for_status()
|
|
612
|
-
parsed = GitHubWorkflowRunsResponse
|
|
732
|
+
parsed = _parse_reply(GitHubWorkflowRunsResponse, response, what=f"workflow runs of {owner}/{repository}")
|
|
613
733
|
workflow_run_ids.extend(run.id for run in parsed.workflow_runs)
|
|
614
734
|
url = _get_next_page_url(response)
|
|
615
735
|
|
|
@@ -627,21 +747,20 @@ def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[in
|
|
|
627
747
|
HTTP_NO_CONTENT = 204
|
|
628
748
|
|
|
629
749
|
|
|
630
|
-
def delete_workflow_run(owner: str, repository: str,
|
|
750
|
+
def delete_workflow_run(owner: str, repository: str, session: requests.Session, run_id_to_delete: int) -> None:
|
|
631
751
|
"""
|
|
632
752
|
Delete a specified workflow run for a GitHub repository.
|
|
633
753
|
|
|
634
754
|
:param owner: The username of the repository owner.
|
|
635
755
|
:param repository: The name of the repository.
|
|
636
|
-
:param
|
|
756
|
+
:param session: Session from :func:`github_session` carrying the auth headers.
|
|
637
757
|
:param run_id_to_delete: The ID of the workflow run to delete.
|
|
638
758
|
:return: None
|
|
639
759
|
"""
|
|
640
760
|
url = f"https://api.github.com/repos/{owner}/{repository}/actions/runs/{run_id_to_delete}"
|
|
641
|
-
headers: dict[str, str | bytes] = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
642
761
|
|
|
643
762
|
try:
|
|
644
|
-
response =
|
|
763
|
+
response = session.delete(url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
645
764
|
|
|
646
765
|
if response.status_code == HTTP_NO_CONTENT:
|
|
647
766
|
result = f"Deleted workflow run ID: {run_id_to_delete} for user: {owner}, repository: {repository}"
|
|
@@ -655,21 +774,23 @@ def delete_workflow_run(owner: str, repository: str, github_token: str, run_id_t
|
|
|
655
774
|
|
|
656
775
|
def _is_skipped_workflow(workflow_filename: str) -> SkippedWorkflowType | None:
|
|
657
776
|
"""Check if workflow should be skipped and return the reason."""
|
|
658
|
-
for skip_type,
|
|
659
|
-
if workflow_filename.startswith(prefix):
|
|
777
|
+
for skip_type, rule in SKIPPED_WORKFLOWS.items():
|
|
778
|
+
if workflow_filename.startswith(rule.prefix):
|
|
660
779
|
return skip_type
|
|
661
780
|
return None
|
|
662
781
|
|
|
663
782
|
|
|
664
|
-
def enable_workflow(owner: str, repository: str, workflow_filename: str,
|
|
783
|
+
def enable_workflow(owner: str, repository: str, workflow_filename: str, session: requests.Session) -> str:
|
|
665
784
|
"""
|
|
666
785
|
Enable a workflow in a GitHub repository using the GitHub API.
|
|
667
786
|
|
|
668
787
|
:param owner: The username of the repository owner.
|
|
669
788
|
:param repository: The name of the repository.
|
|
670
789
|
:param workflow_filename: The name of the workflow file, for example, "python-package.yml".
|
|
671
|
-
:param
|
|
672
|
-
:return:
|
|
790
|
+
:param session: Session from :func:`github_session`, its token allowed to enable workflows.
|
|
791
|
+
:return: ``Enabled repository <repo>, workflow <file>``, or a ``... skipped - ...`` message for a
|
|
792
|
+
file whose name starts with a prefix in ``SKIPPED_WORKFLOWS`` (no request is sent then).
|
|
793
|
+
:raises RuntimeError: When GitHub answers an error status.
|
|
673
794
|
|
|
674
795
|
|
|
675
796
|
>>> try:
|
|
@@ -681,31 +802,26 @@ def enable_workflow(owner: str, repository: str, workflow_filename: str, github_
|
|
|
681
802
|
... from contextlib import redirect_stdout
|
|
682
803
|
... from io import StringIO
|
|
683
804
|
... stdout = StringIO()
|
|
684
|
-
... with redirect_stdout(stdout):
|
|
805
|
+
... with redirect_stdout(stdout), github_session(token) as session:
|
|
685
806
|
... enable_workflow(
|
|
686
807
|
... owner=owner,
|
|
687
808
|
... repository="lib_path",
|
|
688
809
|
... workflow_filename="python-package.yml",
|
|
689
|
-
...
|
|
810
|
+
... session=session,
|
|
690
811
|
... )
|
|
691
812
|
... assert stdout.getvalue()
|
|
692
813
|
|
|
693
814
|
|
|
694
815
|
"""
|
|
695
816
|
url = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows/{workflow_filename}/enable"
|
|
696
|
-
headers: dict[str, str | bytes] = {"Accept": "application/vnd.github.v3+json", "Authorization": f"Bearer {github_token}"}
|
|
697
817
|
|
|
698
818
|
response: requests.Response | None = None
|
|
699
819
|
try:
|
|
700
|
-
|
|
701
|
-
if
|
|
702
|
-
result = f"Repository {repository}, workflow {workflow_filename} skipped -
|
|
703
|
-
elif skip_reason == SkippedWorkflowType.DEPENDABOT:
|
|
704
|
-
result = f"Repository {repository}, workflow {workflow_filename} skipped - managed by Dependabot"
|
|
705
|
-
elif skip_reason == SkippedWorkflowType.UPDATE_GRAPH:
|
|
706
|
-
result = f"Repository {repository}, workflow {workflow_filename} skipped - managed by GitHub dependency graph"
|
|
820
|
+
skip_type = _is_skipped_workflow(workflow_filename)
|
|
821
|
+
if skip_type is not None:
|
|
822
|
+
result = f"Repository {repository}, workflow {workflow_filename} skipped - {SKIPPED_WORKFLOWS[skip_type].reason}"
|
|
707
823
|
else:
|
|
708
|
-
response =
|
|
824
|
+
response = session.put(url, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
709
825
|
response.raise_for_status()
|
|
710
826
|
result = f"Enabled repository {repository}, workflow {workflow_filename}"
|
|
711
827
|
logger.info(sanitization.sanitize_message(result))
|
|
@@ -721,9 +837,10 @@ def enable_workflow(owner: str, repository: str, workflow_filename: str, github_
|
|
|
721
837
|
|
|
722
838
|
def main() -> None:
|
|
723
839
|
"""
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
>>> #
|
|
840
|
+
Enable all workflows and delete old runs (keeping 50) for the configured owner.
|
|
841
|
+
|
|
842
|
+
>>> # Not called here: it acts on the live account. pytest's addopts ignores this
|
|
843
|
+
>>> # module's doctests anyway.
|
|
727
844
|
>>> # main()
|
|
728
845
|
|
|
729
846
|
"""
|
|
@@ -733,4 +850,4 @@ def main() -> None:
|
|
|
733
850
|
|
|
734
851
|
|
|
735
852
|
if __name__ == "__main__":
|
|
736
|
-
sys.stderr.write("this is a library only, the executable is named '
|
|
853
|
+
sys.stderr.write("this is a library only, the executable is named 'keep-github-workflows-active'\n")
|