keep-github-workflows-active 2.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.
@@ -0,0 +1,516 @@
1
+ # STDLIB
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import os
6
+ import pathlib
7
+ import sys
8
+
9
+ # EXT
10
+ import requests
11
+
12
+ REQUEST_TIMEOUT_SECONDS = 30
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _candidate_env_files() -> list[pathlib.Path]:
18
+ """Return existing ``.env`` files to inspect in priority order.
19
+
20
+ Why
21
+ Developers often run the script from varying working directories. We
22
+ probe common locations (current working directory, the package folder,
23
+ and the repository root) so local and CI workflows can share the same
24
+ fallback behaviour.
25
+
26
+ Returns
27
+ -------
28
+ list[pathlib.Path]
29
+ Detected ``.env`` files ordered by precedence.
30
+
31
+ Examples
32
+ --------
33
+ >>> isinstance(_candidate_env_files(), list)
34
+ True
35
+ """
36
+
37
+ script_dir = pathlib.Path(__file__).resolve().parent
38
+ repo_root = script_dir.parent
39
+ candidates: list[pathlib.Path] = []
40
+
41
+ override = os.environ.get("KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH")
42
+ if override:
43
+ candidates.append(pathlib.Path(override))
44
+
45
+ candidates.extend(
46
+ [
47
+ pathlib.Path.cwd() / ".env",
48
+ script_dir / ".env",
49
+ repo_root / ".env",
50
+ ]
51
+ )
52
+
53
+ seen: set[pathlib.Path] = set()
54
+ existing_files: list[pathlib.Path] = []
55
+ for candidate in candidates:
56
+ resolved = candidate.resolve()
57
+ if resolved in seen or not resolved.exists():
58
+ continue
59
+ seen.add(resolved)
60
+ existing_files.append(resolved)
61
+ return existing_files
62
+
63
+
64
+ def _read_env_file(path: pathlib.Path) -> dict[str, str]:
65
+ """Parse ``key=value`` pairs from a ``.env`` file.
66
+
67
+ Parameters
68
+ ----------
69
+ path:
70
+ Path to the ``.env`` file that should be parsed.
71
+
72
+ Returns
73
+ -------
74
+ dict[str, str]
75
+ Mapping of keys to values discovered in the file.
76
+
77
+ Examples
78
+ --------
79
+ >>> from tempfile import NamedTemporaryFile
80
+ >>> with NamedTemporaryFile(mode="w+", suffix=".env", delete=True) as tmp:
81
+ ... _ = tmp.write("FOO=bar\\n# comment\\nBAZ = qux\\n")
82
+ ... _ = tmp.flush()
83
+ ... parsed = _read_env_file(pathlib.Path(tmp.name))
84
+ >>> parsed == {"FOO": "bar", "BAZ": "qux"}
85
+ True
86
+ """
87
+
88
+ values: dict[str, str] = {}
89
+ with path.open(encoding="utf-8") as stream:
90
+ for raw_line in stream:
91
+ stripped = raw_line.strip()
92
+ if not stripped or stripped.startswith("#"):
93
+ continue
94
+ key, separator, remainder = stripped.partition("=")
95
+ if not separator:
96
+ continue
97
+ values[key.strip()] = remainder.strip().strip('"').strip("'")
98
+ return values
99
+
100
+
101
+ def _lookup_config_value(key: str) -> str:
102
+ """Return the configuration value for ``key`` from env or ``.env`` files.
103
+
104
+ Why
105
+ GitHub Actions secrets provide the environment variables automatically,
106
+ but local runs depend on the repo's ``.env`` helper. This function keeps
107
+ the retrieval logic consistent across both environments.
108
+
109
+ Parameters
110
+ ----------
111
+ key:
112
+ Environment variable name to resolve.
113
+
114
+ Returns
115
+ -------
116
+ str
117
+ The resolved configuration value.
118
+
119
+ Raises
120
+ ------
121
+ RuntimeError
122
+ If the value cannot be found in the environment or any ``.env`` file.
123
+
124
+ Examples
125
+ --------
126
+ >>> os.environ["__EXAMPLE_KEY__"] = "value"
127
+ >>> _lookup_config_value("__EXAMPLE_KEY__")
128
+ 'value'
129
+ >>> del os.environ["__EXAMPLE_KEY__"]
130
+ >>> from pathlib import Path
131
+ >>> tmp_env = Path('doctest.env')
132
+ >>> _ = tmp_env.write_text("__EXAMPLE_KEY__=fallback\\n", encoding='utf-8')
133
+ >>> os.environ["KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH"] = str(tmp_env)
134
+ >>> _lookup_config_value("__EXAMPLE_KEY__")
135
+ 'fallback'
136
+ >>> tmp_env.unlink()
137
+ >>> _ = os.environ.pop("KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH", None)
138
+ """
139
+
140
+ env_value = os.environ.get(key)
141
+ if env_value:
142
+ return env_value
143
+
144
+ for env_file in _candidate_env_files():
145
+ config = _read_env_file(env_file)
146
+ file_value = config.get(key)
147
+ if file_value:
148
+ return file_value
149
+
150
+ raise RuntimeError(f"Missing required configuration: {key}")
151
+
152
+
153
+ def enable_all_workflows(owner: str, github_token: str) -> None:
154
+ """
155
+ :param owner: the repo owner
156
+ :param github_token:
157
+ :return:
158
+
159
+ >>> try:
160
+ ... my_owner = get_owner()
161
+ ... my_github_token = get_github_token()
162
+ ... except RuntimeError:
163
+ ... my_owner = my_github_token = None
164
+ >>> if my_owner and my_github_token:
165
+ ... from contextlib import redirect_stdout
166
+ ... from io import StringIO
167
+ ... stdout = StringIO()
168
+ ... with redirect_stdout(stdout):
169
+ ... enable_all_workflows(owner=my_owner, github_token=my_github_token)
170
+ ... assert stdout.getvalue()
171
+
172
+ """
173
+ print(f"Activating and maintaining all workflows for owner {owner}:")
174
+ repositories = get_repositories(owner=owner, github_token=github_token)
175
+ for repository in repositories:
176
+ workflows = get_workflows(owner=owner, repository=repository, github_token=github_token)
177
+ for workflow_filename in workflows:
178
+ print(f"activate workflow {repository}/{workflow_filename}")
179
+ enable_workflow(owner=owner, repository=repository, workflow_filename=workflow_filename, github_token=github_token)
180
+
181
+
182
+ def delete_old_workflow_runs(owner: str, github_token: str, number_of_workflow_runs_to_keep: int = 50) -> None:
183
+ """
184
+ :param owner:
185
+ :param github_token:
186
+ :param number_of_workflow_runs_to_keep:
187
+ :return:
188
+
189
+ >>> try:
190
+ ... owner = get_owner()
191
+ ... token = get_github_token()
192
+ ... except RuntimeError:
193
+ ... owner = token = None
194
+ >>> if owner and token:
195
+ ... from contextlib import redirect_stdout
196
+ ... from io import StringIO
197
+ ... stdout = StringIO()
198
+ ... with redirect_stdout(stdout):
199
+ ... delete_old_workflow_runs(owner=owner, github_token=token, number_of_workflow_runs_to_keep=50)
200
+ ... assert stdout.getvalue()
201
+
202
+ """
203
+ print(
204
+ f"Removing outdated workflow executions for owner {owner}, while retaining a maximum of {number_of_workflow_runs_to_keep} workflow runs per repository:"
205
+ )
206
+ l_repositories = get_repositories(owner=owner, github_token=github_token)
207
+ for repository in l_repositories:
208
+ workflow_run_ids = get_workflow_runs(owner=owner, repository=repository, github_token=github_token)
209
+ workflow_run_ids_sorted = sorted(workflow_run_ids, reverse=True)
210
+ workflow_run_ids_to_delete = workflow_run_ids_sorted[number_of_workflow_runs_to_keep:]
211
+ logger.info(f"repository: {repository}, {len(workflow_run_ids)} workflow runs found, {len(workflow_run_ids_to_delete)} to delete.")
212
+ for run_id_to_delete in workflow_run_ids_to_delete:
213
+ print(f"remove workflow run {repository}/{run_id_to_delete}")
214
+ delete_workflow_run(owner=owner, repository=repository, github_token=github_token, run_id_to_delete=run_id_to_delete)
215
+
216
+
217
+ def get_owner() -> str:
218
+ """Return the configured GitHub owner from env or ``.env`` files.
219
+
220
+ Why
221
+ The automation needs the owner to discover repositories. This helper
222
+ centralises the lookup logic so callers do not replicate fallback
223
+ behaviour.
224
+
225
+ Returns
226
+ -------
227
+ str
228
+ GitHub username configured for the automation.
229
+
230
+ Raises
231
+ ------
232
+ RuntimeError
233
+ If the value is missing from both the environment and ``.env`` files.
234
+
235
+ Examples
236
+ --------
237
+ >>> os.environ["SECRET_GITHUB_OWNER"] = "demo-user"
238
+ >>> get_owner()
239
+ 'demo-user'
240
+ >>> _ = os.environ.pop("SECRET_GITHUB_OWNER")
241
+ """
242
+
243
+ return _lookup_config_value("SECRET_GITHUB_OWNER")
244
+
245
+
246
+ def get_github_token() -> str:
247
+ """Return the GitHub token from env or ``.env`` files.
248
+
249
+ Why
250
+ All API calls depend on the authentication token. Centralising the
251
+ lookup keeps the behaviour consistent between CI and local execution.
252
+
253
+ Returns
254
+ -------
255
+ str
256
+ Personal access token used to authenticate against the GitHub API.
257
+
258
+ Raises
259
+ ------
260
+ RuntimeError
261
+ If the token is missing everywhere we check.
262
+
263
+ Examples
264
+ --------
265
+ >>> os.environ["SECRET_GITHUB_TOKEN"] = "abc123"
266
+ >>> get_github_token()
267
+ 'abc123'
268
+ >>> _ = os.environ.pop("SECRET_GITHUB_TOKEN")
269
+ """
270
+
271
+ return _lookup_config_value("SECRET_GITHUB_TOKEN")
272
+
273
+
274
+ def get_repositories(owner: str, github_token: str) -> list[str]:
275
+ """
276
+ Fetch all repositories for a given GitHub user, handling pagination and setting the page size to 100.
277
+
278
+ :param owner: The username of the repository owner.
279
+ :param github_token: A personal access token for GitHub API authentication.
280
+ :return: A list of repository names.
281
+
282
+ >>> has_secrets = {"SECRET_GITHUB_OWNER", "SECRET_GITHUB_TOKEN"}.issubset(os.environ)
283
+ >>> if has_secrets:
284
+ ... repos = get_repositories(get_owner(), get_github_token())
285
+ ... else:
286
+ ... repos = []
287
+ >>> isinstance(repos, list)
288
+ True
289
+
290
+
291
+ """
292
+ repositories: list[str] = []
293
+ url = f"https://api.github.com/users/{owner}/repos?per_page=100"
294
+ headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
295
+
296
+ while url:
297
+ try:
298
+ response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
299
+ response.raise_for_status() # Raises HTTPError for bad responses
300
+ data = response.json()
301
+ repositories.extend([repo["name"] for repo in data])
302
+
303
+ # Get the URL for the next page from the response headers, if present
304
+ url = response.links.get("next", {}).get("url", None)
305
+
306
+ except requests.exceptions.HTTPError as exc:
307
+ error_message = exc.response.json().get("message", "Error")
308
+ result = f"ERROR reading repositories for user {owner}: {error_message}"
309
+ logger.error(result)
310
+ raise RuntimeError(result) from exc
311
+
312
+ result = f"Found {len(repositories)} repositories for user {owner}"
313
+ logger.info(result)
314
+ return repositories
315
+
316
+
317
+ def get_workflows(owner: str, repository: str, github_token: str) -> list[str]:
318
+ """
319
+ Fetch all workflows for a given GitHub repository, handling pagination and setting the page size to 100.
320
+
321
+ :param owner: The username of the repository owner.
322
+ :param repository: The name of the repository.
323
+ :param github_token: A personal access token for GitHub API authentication.
324
+ :return: A list of workflow names.
325
+
326
+
327
+ >>> try:
328
+ ... owner = get_owner()
329
+ ... token = get_github_token()
330
+ ... except RuntimeError:
331
+ ... owner = token = None
332
+ >>> if owner and token:
333
+ ... repos = get_repositories(owner=owner, github_token=token)
334
+ ... for repo in repos:
335
+ ... _ = get_workflows(owner=owner, repository=repo, github_token=token)
336
+
337
+
338
+ """
339
+ workflows: list[str] = []
340
+ url = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows?per_page=100"
341
+ headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
342
+
343
+ while url:
344
+ try:
345
+ response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
346
+ response.raise_for_status() # Raises HTTPError for bad responses
347
+ data = response.json()
348
+ workflows.extend([pathlib.Path(workflow["path"]).name for workflow in data.get("workflows", [])])
349
+
350
+ # Get the URL for the next page from the response headers, if present
351
+ url = response.links.get("next", {}).get("url", None)
352
+
353
+ except requests.exceptions.HTTPError as exc:
354
+ error_message = exc.response.json().get("message", "Error")
355
+ result = f"ERROR reading workflows for user: {owner}, repository: {repository}, {error_message}"
356
+ logger.error(result)
357
+ raise RuntimeError(result) from exc
358
+
359
+ result = f"Found {len(workflows)} workflows for user: {owner}, repository: {repository}"
360
+ logger.info(result)
361
+ return workflows
362
+
363
+
364
+ def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[str]:
365
+ """
366
+ Fetch all workflow runs for a GitHub repository using the GitHub API v3, handling pagination.
367
+
368
+ :param owner: The username of the repository owner.
369
+ :param repository: The name of the repository.
370
+ :param github_token: A GitHub personal access token for authentication.
371
+ :return: A list of workflow run IDs.
372
+
373
+ >>> try:
374
+ ... owner = get_owner()
375
+ ... token = get_github_token()
376
+ ... except RuntimeError:
377
+ ... owner = token = None
378
+ >>> if owner and token:
379
+ ... repos = get_repositories(owner=owner, github_token=token)
380
+ ... for repo in repos:
381
+ ... _ = get_workflow_runs(owner=owner, repository=repo, github_token=token)
382
+
383
+
384
+ """
385
+ # set pagination to 100 (the maximum at GitHub), to have fewer requests
386
+ url = f"https://api.github.com/repos/{owner}/{repository}/actions/runs?per_page=100"
387
+ headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
388
+
389
+ workflow_run_ids: list[str] = []
390
+ while url:
391
+ try:
392
+ response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
393
+ response.raise_for_status() # Raises an HTTPError if the response was an error
394
+
395
+ # Process response data
396
+ data = response.json()
397
+ workflow_run_ids.extend([run["id"] for run in data.get("workflow_runs", [])])
398
+
399
+ # Check for the 'next' page link
400
+ url = response.links.get("next", {}).get("url", None)
401
+
402
+ except requests.exceptions.HTTPError as exc:
403
+ result_error_message = exc.response.json().get("message", "Error")
404
+ result = f"ERROR reading workflow runs for user: {owner}, repository: {repository}, {result_error_message}"
405
+ logger.error(result)
406
+ raise RuntimeError(result) from exc
407
+
408
+ result = f"Found {len(workflow_run_ids)} workflow runs for user: {owner}, repository: {repository}"
409
+ logger.info(result)
410
+ return workflow_run_ids
411
+
412
+
413
+ def delete_workflow_run(owner: str, repository: str, github_token: str, run_id_to_delete: str) -> None:
414
+ """
415
+ Delete a specified workflow run for a GitHub repository.
416
+
417
+ :param owner: The username of the repository owner.
418
+ :param repository: The name of the repository.
419
+ :param github_token: A personal access token for GitHub API authentication.
420
+ :param run_id_to_delete: The ID of the workflow run to delete.
421
+ :return: None
422
+ """
423
+ url = f"https://api.github.com/repos/{owner}/{repository}/actions/runs/{run_id_to_delete}"
424
+ headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
425
+
426
+ try:
427
+ response = requests.delete(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
428
+
429
+ if response.status_code == 204:
430
+ result = f"Deleted workflow run ID: {run_id_to_delete} for user: {owner}, repository: {repository}"
431
+ logger.info(result)
432
+
433
+ except requests.exceptions.RequestException as exc:
434
+ # For HTTP errors, requests will raise a RequestException. Here we catch all errors derived from RequestException
435
+ result_error_message = f"ERROR deleting workflow run ID: {run_id_to_delete} for user: {owner}, repository: {repository}: {exc}"
436
+ logger.error(result_error_message)
437
+ raise RuntimeError(result_error_message) from exc
438
+
439
+
440
+ def enable_workflow(owner: str, repository: str, workflow_filename: str, github_token: str) -> str:
441
+ """
442
+ Enable a workflow in a GitHub repository using the GitHub API.
443
+
444
+ :param owner: The username of the repository owner.
445
+ :param repository: The name of the repository.
446
+ :param workflow_filename: The name of the workflow file, for example, "python-package.yml".
447
+ :param github_token: A GitHub access token with permissions to enable workflows.
448
+ :return: A success message if the workflow is enabled.
449
+
450
+
451
+ >>> try:
452
+ ... owner = get_owner()
453
+ ... token = get_github_token()
454
+ ... except RuntimeError:
455
+ ... owner = token = None
456
+ >>> if owner and token:
457
+ ... from contextlib import redirect_stdout
458
+ ... from io import StringIO
459
+ ... stdout = StringIO()
460
+ ... with redirect_stdout(stdout):
461
+ ... enable_workflow(
462
+ ... owner=owner,
463
+ ... repository="lib_path",
464
+ ... workflow_filename="python-package.yml",
465
+ ... github_token=token,
466
+ ... )
467
+ ... assert stdout.getvalue()
468
+
469
+
470
+ """
471
+ url = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows/{workflow_filename}/enable"
472
+
473
+ headers = {"Accept": "application/vnd.github.v3+json", "Authorization": f"Bearer {github_token}"}
474
+
475
+ response: requests.Response | None = None
476
+ try:
477
+ if workflow_filename.startswith("pages-build-deployment"):
478
+ result = f"Repository {repository}, workflow {workflow_filename} skipped - those can not be enabled"
479
+ elif workflow_filename.startswith("dependabot"):
480
+ result = f"Repository {repository}, workflow {workflow_filename} skipped - managed by Dependabot"
481
+ else:
482
+ response = requests.put(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
483
+ response.raise_for_status() # This will raise an exception for HTTP error codes
484
+ result = f"Enabled repository {repository}, workflow {workflow_filename}"
485
+ logger.info(result)
486
+ return result
487
+
488
+ except requests.exceptions.HTTPError as exc:
489
+ resp = exc.response if exc.response is not None else response
490
+ if resp is not None:
491
+ try:
492
+ error_message = resp.json().get("message", "Error")
493
+ except ValueError:
494
+ error_message = resp.text or resp.reason or "Error"
495
+ else:
496
+ error_message = str(exc)
497
+ result = f"ERROR enabling repository {repository}, workflow {workflow_filename}: {error_message}"
498
+ logger.error(result)
499
+ raise RuntimeError(result) from exc
500
+
501
+
502
+ def main() -> None:
503
+ """
504
+ enable all workflows in all repositories for the given owner
505
+ >>> # we actually don't do that here AGAIN because of GitHub Rate limits
506
+ >>> # those functions are called anyway already by doctest
507
+ >>> # main()
508
+
509
+ """
510
+
511
+ enable_all_workflows(owner=get_owner(), github_token=get_github_token())
512
+ delete_old_workflow_runs(owner=get_owner(), github_token=get_github_token(), number_of_workflow_runs_to_keep=50)
513
+
514
+
515
+ if __name__ == "__main__":
516
+ print("this is a library only, the executable is named 'keep_github_workflows_active_cli.py'", file=sys.stderr)
File without changes