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,584 @@
1
+ """CLI adapter wiring the behavior helpers into a rich-click interface.
2
+
3
+ Purpose
4
+ -------
5
+ Expose a stable command-line surface so tooling, documentation, and packaging
6
+ automation can be exercised while the richer logging helpers are being built.
7
+ By delegating to :mod:`keep_github_workflows_active.behaviors` the transport stays
8
+ aligned with the Clean Code rules captured in
9
+ ``docs/systemdesign/module_reference.md``.
10
+
11
+ Contents
12
+ --------
13
+ * :data:`CLICK_CONTEXT_SETTINGS` – shared Click settings ensuring consistent
14
+ ``--help`` behavior across commands.
15
+ * :func:`apply_traceback_preferences` – helper that synchronises the shared
16
+ traceback configuration flags.
17
+ * :func:`snapshot_traceback_state` / :func:`restore_traceback_state` – utilities
18
+ for preserving and reapplying the global traceback preference.
19
+ * :func:`cli` – root command group wiring the global options.
20
+ * :func:`cli_main` – default action when no subcommand is provided.
21
+ * :func:`cli_info`, :func:`cli_hello`, :func:`cli_fail` – subcommands covering
22
+ metadata printing, success path, and failure path.
23
+ * :func:`_record_traceback_choice`, :func:`_announce_traceback_choice` – persist
24
+ traceback preferences across context and shared tooling.
25
+ * :func:`_invoke_cli`, :func:`_current_traceback_mode`, :func:`_traceback_limit`,
26
+ :func:`_print_exception`, :func:`_run_cli_via_exit_tools` – isolate the error
27
+ handling and delegation path.
28
+ * :func:`_restore_when_requested` – restores tracebacks when ``main`` finishes.
29
+ * :func:`main` – composition helper delegating to ``lib_cli_exit_tools`` while
30
+ honouring the shared traceback preferences.
31
+
32
+ System Role
33
+ -----------
34
+ The CLI is the primary adapter for local development workflows; packaging
35
+ targets register the console script defined in :mod:`keep_github_workflows_active.__init__conf__`.
36
+ Other transports (including ``python -m`` execution) reuse the same helpers so
37
+ behaviour remains consistent regardless of entry point.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from collections.abc import Sequence
43
+ from typing import Final
44
+
45
+ import rich_click as click
46
+
47
+ import lib_cli_exit_tools
48
+ from click.core import ParameterSource
49
+
50
+ from . import __init__conf__
51
+ from . import keep_github_workflow_active as keep_active
52
+ from .behaviors import emit_greeting, noop_main, raise_intentional_failure
53
+
54
+ #: Shared Click context flags so help output stays consistent across commands.
55
+ CLICK_CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]} # noqa: C408
56
+ #: Character budget used when printing truncated tracebacks.
57
+ TRACEBACK_SUMMARY_LIMIT: Final[int] = 500
58
+ #: Character budget used when verbose tracebacks are enabled.
59
+ TRACEBACK_VERBOSE_LIMIT: Final[int] = 10_000
60
+ TracebackState = tuple[bool, bool]
61
+
62
+
63
+ def _fallback_owner(owner: str | None) -> str:
64
+ try:
65
+ return owner or keep_active.get_owner()
66
+ except RuntimeError as exc: # pragma: no cover - handled by Click
67
+ raise click.ClickException(str(exc)) from exc
68
+
69
+
70
+ def _fallback_token(token: str | None) -> str:
71
+ try:
72
+ return token or keep_active.get_github_token()
73
+ except RuntimeError as exc: # pragma: no cover - handled by Click
74
+ raise click.ClickException(str(exc)) from exc
75
+
76
+
77
+ def apply_traceback_preferences(enabled: bool) -> None:
78
+ """Synchronise shared traceback flags with the requested preference.
79
+
80
+ Why
81
+ ``lib_cli_exit_tools`` inspects global flags to decide whether tracebacks
82
+ should be truncated and whether colour should be forced. Updating both
83
+ attributes together ensures the ``--traceback`` flag behaves the same for
84
+ console scripts and ``python -m`` execution.
85
+
86
+ Parameters
87
+ ----------
88
+ enabled:
89
+ ``True`` enables full tracebacks with colour. ``False`` restores the
90
+ compact summary mode.
91
+
92
+ Examples
93
+ --------
94
+ >>> apply_traceback_preferences(True)
95
+ >>> bool(lib_cli_exit_tools.config.traceback)
96
+ True
97
+ >>> bool(lib_cli_exit_tools.config.traceback_force_color)
98
+ True
99
+ """
100
+
101
+ lib_cli_exit_tools.config.traceback = bool(enabled)
102
+ lib_cli_exit_tools.config.traceback_force_color = bool(enabled)
103
+
104
+
105
+ def snapshot_traceback_state() -> TracebackState:
106
+ """Capture the current traceback configuration for later restoration.
107
+
108
+ Returns
109
+ -------
110
+ TracebackState
111
+ Tuple of ``(traceback_enabled, force_color)``.
112
+
113
+ Examples
114
+ --------
115
+ >>> snapshot = snapshot_traceback_state()
116
+ >>> isinstance(snapshot, tuple)
117
+ True
118
+ """
119
+
120
+ return (
121
+ bool(getattr(lib_cli_exit_tools.config, "traceback", False)),
122
+ bool(getattr(lib_cli_exit_tools.config, "traceback_force_color", False)),
123
+ )
124
+
125
+
126
+ def restore_traceback_state(state: TracebackState) -> None:
127
+ """Reapply a previously captured traceback configuration.
128
+
129
+ Parameters
130
+ ----------
131
+ state:
132
+ Tuple returned by :func:`snapshot_traceback_state`.
133
+
134
+ Examples
135
+ --------
136
+ >>> prev = snapshot_traceback_state()
137
+ >>> apply_traceback_preferences(True)
138
+ >>> restore_traceback_state(prev)
139
+ >>> snapshot_traceback_state() == prev
140
+ True
141
+ """
142
+
143
+ lib_cli_exit_tools.config.traceback = bool(state[0])
144
+ lib_cli_exit_tools.config.traceback_force_color = bool(state[1])
145
+
146
+
147
+ def _record_traceback_choice(ctx: click.Context, *, enabled: bool) -> None:
148
+ """Remember the chosen traceback mode inside the Click context.
149
+
150
+ Why
151
+ Downstream commands need to know whether verbose tracebacks were
152
+ requested so they can honour the user's preference without re-parsing
153
+ flags.
154
+
155
+ What
156
+ Ensures the context has a dict backing store and persists the boolean
157
+ under the ``"traceback"`` key.
158
+
159
+ Inputs
160
+ ctx:
161
+ Click context associated with the current invocation.
162
+ enabled:
163
+ ``True`` when verbose tracebacks were requested; ``False`` otherwise.
164
+
165
+ Side Effects
166
+ Mutates ``ctx.obj``.
167
+ """
168
+
169
+ ctx.ensure_object(dict)
170
+ ctx.obj["traceback"] = enabled
171
+
172
+
173
+ def _announce_traceback_choice(enabled: bool) -> None:
174
+ """Keep ``lib_cli_exit_tools`` in sync with the selected traceback mode.
175
+
176
+ Why
177
+ ``lib_cli_exit_tools`` reads global configuration to decide how to print
178
+ tracebacks; we mirror the user's choice into that configuration.
179
+
180
+ Inputs
181
+ enabled:
182
+ ``True`` when verbose tracebacks should be shown; ``False`` when the
183
+ summary view is desired.
184
+
185
+ Side Effects
186
+ Mutates ``lib_cli_exit_tools.config``.
187
+ """
188
+
189
+ apply_traceback_preferences(enabled)
190
+
191
+
192
+ def _no_subcommand_requested(ctx: click.Context) -> bool:
193
+ """Return ``True`` when the invocation did not name a subcommand.
194
+
195
+ Why
196
+ The CLI defaults to calling ``noop_main`` when no subcommand appears; we
197
+ need a readable predicate to capture that intent.
198
+
199
+ Inputs
200
+ ctx:
201
+ Click context describing the current CLI invocation.
202
+
203
+ Outputs
204
+ bool:
205
+ ``True`` when no subcommand was invoked; ``False`` otherwise.
206
+ """
207
+
208
+ return ctx.invoked_subcommand is None
209
+
210
+
211
+ def _invoke_cli(argv: Sequence[str] | None) -> int:
212
+ """Ask ``lib_cli_exit_tools`` to execute the Click command.
213
+
214
+ Why
215
+ ``lib_cli_exit_tools`` normalises exit codes and exception handling; we
216
+ centralise the call so tests can stub it cleanly.
217
+
218
+ Inputs
219
+ argv:
220
+ Sequence of command-line arguments. ``None`` delegates to
221
+ ``sys.argv`` inside ``lib_cli_exit_tools``.
222
+
223
+ Outputs
224
+ int:
225
+ Exit code returned by the CLI execution.
226
+ """
227
+
228
+ return lib_cli_exit_tools.run_cli(
229
+ cli,
230
+ argv=list(argv) if argv is not None else None,
231
+ prog_name=__init__conf__.shell_command,
232
+ )
233
+
234
+
235
+ def _current_traceback_mode() -> bool:
236
+ """Return the global traceback preference as a boolean.
237
+
238
+ Why
239
+ Error handling logic needs to know whether verbose tracebacks are active
240
+ so it can pick the right character budget and ensure colouring is
241
+ consistent.
242
+
243
+ Outputs
244
+ bool:
245
+ ``True`` when verbose tracebacks are enabled; ``False`` otherwise.
246
+ """
247
+
248
+ return bool(getattr(lib_cli_exit_tools.config, "traceback", False))
249
+
250
+
251
+ def _traceback_limit(tracebacks_enabled: bool, *, summary_limit: int, verbose_limit: int) -> int:
252
+ """Return the character budget that matches the current traceback mode.
253
+
254
+ Why
255
+ Verbose tracebacks should show the full story while compact ones keep the
256
+ terminal tidy. This helper makes that decision explicit.
257
+
258
+ Inputs
259
+ tracebacks_enabled:
260
+ ``True`` when verbose tracebacks are active.
261
+ summary_limit:
262
+ Character budget for truncated output.
263
+ verbose_limit:
264
+ Character budget for the full traceback.
265
+
266
+ Outputs
267
+ int:
268
+ The applicable character limit.
269
+ """
270
+
271
+ return verbose_limit if tracebacks_enabled else summary_limit
272
+
273
+
274
+ def _print_exception(exc: BaseException, *, tracebacks_enabled: bool, length_limit: int) -> int:
275
+ """Render the exception through ``lib_cli_exit_tools`` and return its exit code.
276
+
277
+ Why
278
+ All transports funnel errors through ``lib_cli_exit_tools`` so that exit
279
+ codes and formatting stay consistent; this helper keeps the plumbing in
280
+ one place.
281
+
282
+ Inputs
283
+ exc:
284
+ Exception raised by the CLI.
285
+ tracebacks_enabled:
286
+ ``True`` when verbose tracebacks should be shown.
287
+ length_limit:
288
+ Maximum number of characters to print.
289
+
290
+ Outputs
291
+ int:
292
+ Exit code to surface to the shell.
293
+
294
+ Side Effects
295
+ Writes the formatted exception to stderr via ``lib_cli_exit_tools``.
296
+ """
297
+
298
+ lib_cli_exit_tools.print_exception_message(
299
+ trace_back=tracebacks_enabled,
300
+ length_limit=length_limit,
301
+ )
302
+ return lib_cli_exit_tools.get_system_exit_code(exc)
303
+
304
+
305
+ def _traceback_option_requested(ctx: click.Context) -> bool:
306
+ """Return ``True`` when the user explicitly requested ``--traceback``.
307
+
308
+ Why
309
+ Determines whether a no-command invocation should run the default
310
+ behaviour or display the help screen.
311
+
312
+ Inputs
313
+ ctx:
314
+ Click context associated with the current invocation.
315
+
316
+ Outputs
317
+ bool:
318
+ ``True`` when the user provided ``--traceback`` or ``--no-traceback``;
319
+ ``False`` when the default value is in effect.
320
+ """
321
+
322
+ source = ctx.get_parameter_source("traceback")
323
+ return source not in (ParameterSource.DEFAULT, None)
324
+
325
+
326
+ def _show_help(ctx: click.Context) -> None:
327
+ """Render the command help to stdout."""
328
+
329
+ click.echo(ctx.get_help())
330
+
331
+
332
+ def _run_cli_via_exit_tools(
333
+ argv: Sequence[str] | None,
334
+ *,
335
+ summary_limit: int,
336
+ verbose_limit: int,
337
+ ) -> int:
338
+ """Run the command while narrating the failure path with care.
339
+
340
+ Why
341
+ Consolidates the call to ``lib_cli_exit_tools`` so happy paths and error
342
+ handling remain consistent across the application and tests.
343
+
344
+ Inputs
345
+ argv:
346
+ Sequence of CLI arguments when provided.
347
+ summary_limit / verbose_limit:
348
+ Character budgets steering exception output length.
349
+
350
+ Outputs
351
+ int:
352
+ Exit code produced by the command.
353
+
354
+ Side Effects
355
+ Delegates to ``lib_cli_exit_tools`` which may write to stderr.
356
+ """
357
+
358
+ try:
359
+ return _invoke_cli(argv)
360
+ except BaseException as exc: # noqa: BLE001 - handled by shared printers
361
+ tracebacks_enabled = _current_traceback_mode()
362
+ apply_traceback_preferences(tracebacks_enabled)
363
+ return _print_exception(
364
+ exc,
365
+ tracebacks_enabled=tracebacks_enabled,
366
+ length_limit=_traceback_limit(
367
+ tracebacks_enabled,
368
+ summary_limit=summary_limit,
369
+ verbose_limit=verbose_limit,
370
+ ),
371
+ )
372
+
373
+
374
+ @click.group(
375
+ help=__init__conf__.title,
376
+ context_settings=CLICK_CONTEXT_SETTINGS,
377
+ invoke_without_command=True,
378
+ )
379
+ @click.version_option(
380
+ version=__init__conf__.version,
381
+ prog_name=__init__conf__.shell_command,
382
+ message=f"{__init__conf__.shell_command} version {__init__conf__.version}",
383
+ )
384
+ @click.option(
385
+ "--traceback/--no-traceback",
386
+ is_flag=True,
387
+ default=False,
388
+ help="Show full Python traceback on errors",
389
+ )
390
+ @click.pass_context
391
+ def cli(ctx: click.Context, traceback: bool) -> None:
392
+ """Root command storing global flags and syncing shared traceback state.
393
+
394
+ Why
395
+ The CLI must provide a switch for verbose tracebacks so developers can
396
+ toggle diagnostic depth without editing configuration files.
397
+
398
+ What
399
+ Ensures a dict-based context, stores the ``traceback`` flag, and mirrors
400
+ the value into ``lib_cli_exit_tools.config`` so downstream helpers observe
401
+ the preference. When no subcommand (or options) are provided, the command
402
+ prints help instead of running the domain stub; otherwise the default
403
+ action delegates to :func:`cli_main`.
404
+
405
+ Side Effects
406
+ Mutates :mod:`lib_cli_exit_tools.config` to reflect the requested
407
+ traceback mode, including ``traceback_force_color`` when tracebacks are
408
+ enabled.
409
+
410
+ Examples
411
+ --------
412
+ >>> from click.testing import CliRunner
413
+ >>> runner = CliRunner()
414
+ >>> result = runner.invoke(cli, ["hello"])
415
+ >>> result.exit_code
416
+ 0
417
+ >>> "Hello World" in result.output
418
+ True
419
+ """
420
+
421
+ _record_traceback_choice(ctx, enabled=traceback)
422
+ _announce_traceback_choice(traceback)
423
+ if _no_subcommand_requested(ctx):
424
+ if _traceback_option_requested(ctx):
425
+ cli_main()
426
+ else:
427
+ _show_help(ctx)
428
+
429
+
430
+ def cli_main() -> None:
431
+ """Run the placeholder domain entry when callers opt into execution.
432
+
433
+ Why
434
+ Maintains compatibility with tooling that expects the original
435
+ "do-nothing" behaviour by explicitly opting in via options (e.g.
436
+ ``--traceback`` without subcommands).
437
+
438
+ Side Effects
439
+ Delegates to :func:`noop_main`.
440
+
441
+ Examples
442
+ --------
443
+ >>> cli_main()
444
+ """
445
+
446
+ noop_main()
447
+
448
+
449
+ @cli.command("info", context_settings=CLICK_CONTEXT_SETTINGS)
450
+ def cli_info() -> None:
451
+ """Print resolved metadata so users can inspect installation details."""
452
+
453
+ __init__conf__.print_info()
454
+
455
+
456
+ @cli.command("hello", context_settings=CLICK_CONTEXT_SETTINGS)
457
+ def cli_hello() -> None:
458
+ """Demonstrate the success path by emitting the canonical greeting."""
459
+
460
+ emit_greeting()
461
+
462
+
463
+ @cli.command("fail", context_settings=CLICK_CONTEXT_SETTINGS)
464
+ def cli_fail() -> None:
465
+ """Trigger the intentional failure helper to test error handling."""
466
+
467
+ raise_intentional_failure()
468
+
469
+
470
+ @cli.command("enable-all-workflows", context_settings=CLICK_CONTEXT_SETTINGS)
471
+ @click.option(
472
+ "--owner",
473
+ metavar="OWNER",
474
+ help="GitHub username owning the repositories (defaults to environment/.env)",
475
+ )
476
+ @click.option(
477
+ "--token",
478
+ metavar="TOKEN",
479
+ help="Fine-grained personal access token (defaults to environment/.env)",
480
+ )
481
+ def cli_enable_all_workflows(owner: str | None, token: str | None) -> None:
482
+ """Ensure every workflow in the configured account stays enabled."""
483
+
484
+ resolved_owner = _fallback_owner(owner)
485
+ resolved_token = _fallback_token(token)
486
+ keep_active.enable_all_workflows(owner=resolved_owner, github_token=resolved_token)
487
+
488
+
489
+ @cli.command("delete-old-workflow-runs", context_settings=CLICK_CONTEXT_SETTINGS)
490
+ @click.option(
491
+ "--owner",
492
+ metavar="OWNER",
493
+ help="GitHub username owning the repositories (defaults to environment/.env)",
494
+ )
495
+ @click.option(
496
+ "--token",
497
+ metavar="TOKEN",
498
+ help="Fine-grained personal access token (defaults to environment/.env)",
499
+ )
500
+ @click.option(
501
+ "--keep",
502
+ metavar="COUNT",
503
+ type=int,
504
+ default=50,
505
+ show_default=True,
506
+ help="Number of recent workflow runs to retain per repository",
507
+ )
508
+ def cli_delete_old_workflow_runs(owner: str | None, token: str | None, keep: int) -> None:
509
+ """Prune historic workflow runs while keeping the freshest executions."""
510
+
511
+ resolved_owner = _fallback_owner(owner)
512
+ resolved_token = _fallback_token(token)
513
+ keep_active.delete_old_workflow_runs(
514
+ owner=resolved_owner,
515
+ github_token=resolved_token,
516
+ number_of_workflow_runs_to_keep=keep,
517
+ )
518
+
519
+
520
+ def main(
521
+ argv: Sequence[str] | None = None,
522
+ *,
523
+ restore_traceback: bool = True,
524
+ summary_limit: int = TRACEBACK_SUMMARY_LIMIT,
525
+ verbose_limit: int = TRACEBACK_VERBOSE_LIMIT,
526
+ ) -> int:
527
+ """Execute the CLI with deliberate error handling and return the exit code.
528
+
529
+ Why
530
+ Provides the single entry point used by console scripts and
531
+ ``python -m`` execution so that behaviour stays identical across
532
+ transports.
533
+
534
+ Inputs
535
+ argv:
536
+ Sequence of CLI arguments. ``None`` lets Click consume ``sys.argv``
537
+ directly.
538
+ restore_traceback:
539
+ ``True`` to restore the prior ``lib_cli_exit_tools`` traceback
540
+ configuration after execution.
541
+ summary_limit / verbose_limit:
542
+ Character budgets used when formatting exceptions.
543
+
544
+ Outputs
545
+ int:
546
+ Exit code reported by the CLI run.
547
+
548
+ Side Effects
549
+ Mutates the global traceback configuration while the CLI runs.
550
+ """
551
+
552
+ previous_state = snapshot_traceback_state()
553
+ try:
554
+ return _run_cli_via_exit_tools(
555
+ argv,
556
+ summary_limit=summary_limit,
557
+ verbose_limit=verbose_limit,
558
+ )
559
+ finally:
560
+ _restore_when_requested(previous_state, restore_traceback)
561
+
562
+
563
+ def _restore_when_requested(state: TracebackState, should_restore: bool) -> None:
564
+ """Restore the prior traceback configuration when requested.
565
+
566
+ Why
567
+ CLI execution may toggle verbose tracebacks for the duration of the run.
568
+ Once the command ends we restore the previous configuration so other
569
+ code paths continue with their expected defaults.
570
+
571
+ Inputs
572
+ state:
573
+ Tuple captured by :func:`snapshot_traceback_state` describing the
574
+ prior configuration.
575
+ should_restore:
576
+ ``True`` to reapply the stored configuration; ``False`` to keep the
577
+ current settings.
578
+
579
+ Side Effects
580
+ May mutate ``lib_cli_exit_tools.config``.
581
+ """
582
+
583
+ if should_restore:
584
+ restore_traceback_state(state)