gitgatekeeper 0.1.1__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.
- gitgatekeeper/__init__.py +10 -0
- gitgatekeeper/cli/main.py +1074 -0
- gitgatekeeper/config/__init__.py +18 -0
- gitgatekeeper/config/loader.py +100 -0
- gitgatekeeper/config/models.py +205 -0
- gitgatekeeper/core/__init__.py +46 -0
- gitgatekeeper/core/buffer.py +125 -0
- gitgatekeeper/core/commit_engine.py +900 -0
- gitgatekeeper/core/detector.py +154 -0
- gitgatekeeper/core/discovery.py +172 -0
- gitgatekeeper/core/doctor.py +220 -0
- gitgatekeeper/core/events.py +89 -0
- gitgatekeeper/core/filters.py +79 -0
- gitgatekeeper/core/grouping.py +139 -0
- gitgatekeeper/core/inactivity.py +154 -0
- gitgatekeeper/core/instance.py +202 -0
- gitgatekeeper/core/locking.py +85 -0
- gitgatekeeper/core/migrate.py +134 -0
- gitgatekeeper/core/monitor.py +408 -0
- gitgatekeeper/core/project_manager.py +141 -0
- gitgatekeeper/core/push_engine.py +441 -0
- gitgatekeeper/core/service.py +703 -0
- gitgatekeeper/core/systemd.py +223 -0
- gitgatekeeper/core/undo.py +104 -0
- gitgatekeeper/git/__init__.py +43 -0
- gitgatekeeper/git/analyzer.py +96 -0
- gitgatekeeper/git/diff.py +252 -0
- gitgatekeeper/git/ignore.py +36 -0
- gitgatekeeper/git/models.py +118 -0
- gitgatekeeper/git/repository.py +123 -0
- gitgatekeeper/git/secrets.py +150 -0
- gitgatekeeper/git/sensitive.py +114 -0
- gitgatekeeper/git/status_parser.py +134 -0
- gitgatekeeper/intelligence/__init__.py +23 -0
- gitgatekeeper/intelligence/analysis.py +358 -0
- gitgatekeeper/intelligence/context.py +57 -0
- gitgatekeeper/intelligence/message.py +117 -0
- gitgatekeeper/intelligence/profile.py +213 -0
- gitgatekeeper/intelligence/provider.py +65 -0
- gitgatekeeper/intelligence/rules.py +561 -0
- gitgatekeeper/logging_setup.py +122 -0
- gitgatekeeper/storage/__init__.py +16 -0
- gitgatekeeper/storage/database.py +235 -0
- gitgatekeeper/storage/history.py +440 -0
- gitgatekeeper/storage/models.py +78 -0
- gitgatekeeper/storage/recorder.py +178 -0
- gitgatekeeper-0.1.1.dist-info/METADATA +671 -0
- gitgatekeeper-0.1.1.dist-info/RECORD +52 -0
- gitgatekeeper-0.1.1.dist-info/WHEEL +5 -0
- gitgatekeeper-0.1.1.dist-info/entry_points.txt +2 -0
- gitgatekeeper-0.1.1.dist-info/licenses/LICENSE +21 -0
- gitgatekeeper-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1074 @@
|
|
|
1
|
+
"""GitGatekeeper command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import signal
|
|
7
|
+
import time
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from fnmatch import fnmatchcase
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Annotated, NoReturn
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.markup import escape
|
|
16
|
+
from rich.table import Table
|
|
17
|
+
|
|
18
|
+
from gitgatekeeper import __version__
|
|
19
|
+
from gitgatekeeper.config import ConfigError, default_config_path
|
|
20
|
+
from gitgatekeeper.config.loader import CONFIG_ENV_VAR, USER_CONFIG
|
|
21
|
+
from gitgatekeeper.core import ProjectManager, default_state_dir, migrate, systemd
|
|
22
|
+
from gitgatekeeper.core.discovery import (
|
|
23
|
+
DEFAULT_DEPTH,
|
|
24
|
+
default_roots,
|
|
25
|
+
discover,
|
|
26
|
+
parse_selection,
|
|
27
|
+
)
|
|
28
|
+
from gitgatekeeper.core.doctor import Level, check_project
|
|
29
|
+
from gitgatekeeper.core.instance import (
|
|
30
|
+
AlreadyRunningError,
|
|
31
|
+
SignalOutcome,
|
|
32
|
+
StopOutcome,
|
|
33
|
+
signal_running,
|
|
34
|
+
)
|
|
35
|
+
from gitgatekeeper.core.instance import running_pid as _running_pid
|
|
36
|
+
from gitgatekeeper.core.instance import stop_running as _stop_running
|
|
37
|
+
from gitgatekeeper.core.service import (
|
|
38
|
+
GitGatekeeperService,
|
|
39
|
+
ServiceError,
|
|
40
|
+
history_path,
|
|
41
|
+
read_status,
|
|
42
|
+
)
|
|
43
|
+
from gitgatekeeper.core.undo import UndoError, undo_commit
|
|
44
|
+
from gitgatekeeper.git import GitError, analyze_repository
|
|
45
|
+
from gitgatekeeper.intelligence.profile import detect_profile
|
|
46
|
+
from gitgatekeeper.logging_setup import configure_logging, log_file_path, read_log_tail
|
|
47
|
+
from gitgatekeeper.storage import HistoryStore, StorageError
|
|
48
|
+
|
|
49
|
+
app = typer.Typer(
|
|
50
|
+
name="gitgatekeeper",
|
|
51
|
+
help="Intelligent Git automation agent.",
|
|
52
|
+
no_args_is_help=True,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
service_app = typer.Typer(
|
|
56
|
+
help="Run GitGatekeeper in the background as a systemd user service.",
|
|
57
|
+
no_args_is_help=True,
|
|
58
|
+
)
|
|
59
|
+
app.add_typer(service_app, name="service")
|
|
60
|
+
|
|
61
|
+
console = Console()
|
|
62
|
+
err_console = Console(stderr=True)
|
|
63
|
+
|
|
64
|
+
ConfigOption = Annotated[
|
|
65
|
+
Path | None,
|
|
66
|
+
typer.Option(
|
|
67
|
+
"--config",
|
|
68
|
+
"-c",
|
|
69
|
+
help="Path to projects.yaml (default: $GITGATEKEEPER_CONFIG, "
|
|
70
|
+
"./config/projects.yaml or ~/.config/gitgatekeeper/projects.yaml).",
|
|
71
|
+
),
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
StateDirOption = Annotated[
|
|
76
|
+
Path | None,
|
|
77
|
+
typer.Option(
|
|
78
|
+
"--state-dir",
|
|
79
|
+
envvar="GITGATEKEEPER_STATE_DIR",
|
|
80
|
+
help="Where GitGatekeeper keeps its database, logs and locks "
|
|
81
|
+
"(default: ~/.local/state/gitgatekeeper).",
|
|
82
|
+
),
|
|
83
|
+
]
|
|
84
|
+
LimitOption = Annotated[
|
|
85
|
+
int, typer.Option("--limit", "-n", min=1, max=1000, help="Rows to show.")
|
|
86
|
+
]
|
|
87
|
+
ProjectOption = Annotated[
|
|
88
|
+
str | None, typer.Option("--project", "-p", help="Only this project.")
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _state(state_dir: Path | None) -> Path:
|
|
93
|
+
return state_dir.expanduser().resolve() if state_dir else default_state_dir()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _restart_note(state_dir: Path | None) -> None:
|
|
97
|
+
"""The service reads the config once, so tell the user when it is running."""
|
|
98
|
+
if _running_pid(_state(state_dir)) is not None:
|
|
99
|
+
console.print(
|
|
100
|
+
"[yellow]GitGatekeeper is running; apply this change with "
|
|
101
|
+
"`gitgatekeeper reload`.[/yellow]"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _manager(config: Path | None) -> ProjectManager:
|
|
106
|
+
path = config.expanduser().resolve() if config else default_config_path()
|
|
107
|
+
return ProjectManager(path)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def manager_path(config: Path | None) -> Path:
|
|
111
|
+
return _manager(config).config_path
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _fail(message: str) -> NoReturn:
|
|
115
|
+
err_console.print(f"[bold red]Error:[/bold red] {escape(message)}")
|
|
116
|
+
raise typer.Exit(code=1)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.command()
|
|
120
|
+
def version() -> None:
|
|
121
|
+
"""Display GitGatekeeper version."""
|
|
122
|
+
console.print(f"[bold green]GitGatekeeper[/bold green] v{__version__}")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@app.command()
|
|
126
|
+
def projects(config: ConfigOption = None) -> None:
|
|
127
|
+
"""List registered projects and their current situation."""
|
|
128
|
+
manager = _manager(config)
|
|
129
|
+
try:
|
|
130
|
+
statuses = manager.statuses()
|
|
131
|
+
except (ConfigError, GitError) as exc:
|
|
132
|
+
_fail(str(exc))
|
|
133
|
+
|
|
134
|
+
if not statuses:
|
|
135
|
+
console.print(
|
|
136
|
+
"No projects registered. Use [bold]gitgatekeeper add <path>[/bold]."
|
|
137
|
+
)
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
table = Table(title="GitGatekeeper projects")
|
|
141
|
+
table.add_column("Name", style="bold")
|
|
142
|
+
table.add_column("State")
|
|
143
|
+
table.add_column("Inactivity (min)", justify="right")
|
|
144
|
+
table.add_column("Auto-push")
|
|
145
|
+
table.add_column("Path", overflow="fold")
|
|
146
|
+
colors = {"enabled": "green", "disabled": "yellow"}
|
|
147
|
+
for item in statuses:
|
|
148
|
+
color = colors.get(item.state, "red")
|
|
149
|
+
table.add_row(
|
|
150
|
+
escape(item.project.name),
|
|
151
|
+
f"[{color}]{item.state}[/{color}]",
|
|
152
|
+
str(item.inactivity_minutes),
|
|
153
|
+
"yes" if item.auto_push else "no",
|
|
154
|
+
escape(str(item.project.path)),
|
|
155
|
+
)
|
|
156
|
+
console.print(table)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@app.command()
|
|
160
|
+
def add(
|
|
161
|
+
path: Annotated[Path, typer.Argument(help="Path inside a Git repository.")],
|
|
162
|
+
name: Annotated[
|
|
163
|
+
str | None, typer.Option("--name", "-n", help="Project name.")
|
|
164
|
+
] = None,
|
|
165
|
+
config: ConfigOption = None,
|
|
166
|
+
state_dir: StateDirOption = None,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""Register a Git repository for monitoring."""
|
|
169
|
+
try:
|
|
170
|
+
project = _manager(config).add(path, name=name)
|
|
171
|
+
except (ConfigError, GitError) as exc:
|
|
172
|
+
_fail(str(exc))
|
|
173
|
+
console.print(
|
|
174
|
+
f"Added [bold]{escape(project.name)}[/bold] → {escape(str(project.path))}"
|
|
175
|
+
)
|
|
176
|
+
_restart_note(state_dir)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@app.command()
|
|
180
|
+
def remove(
|
|
181
|
+
name: Annotated[str, typer.Argument(help="Project name.")],
|
|
182
|
+
config: ConfigOption = None,
|
|
183
|
+
state_dir: StateDirOption = None,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""Unregister a project (the repository itself is never touched)."""
|
|
186
|
+
try:
|
|
187
|
+
project = _manager(config).remove(name)
|
|
188
|
+
except (ConfigError, GitError) as exc:
|
|
189
|
+
_fail(str(exc))
|
|
190
|
+
console.print(f"Removed [bold]{escape(project.name)}[/bold] from GitGatekeeper.")
|
|
191
|
+
_restart_note(state_dir)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@app.command()
|
|
195
|
+
def enable(
|
|
196
|
+
name: Annotated[str, typer.Argument(help="Project name.")],
|
|
197
|
+
config: ConfigOption = None,
|
|
198
|
+
state_dir: StateDirOption = None,
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Enable monitoring for a project."""
|
|
201
|
+
try:
|
|
202
|
+
project = _manager(config).set_enabled(name, True)
|
|
203
|
+
except (ConfigError, GitError) as exc:
|
|
204
|
+
_fail(str(exc))
|
|
205
|
+
console.print(f"Enabled [bold]{escape(project.name)}[/bold].")
|
|
206
|
+
_restart_note(state_dir)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@app.command()
|
|
210
|
+
def disable(
|
|
211
|
+
name: Annotated[str, typer.Argument(help="Project name.")],
|
|
212
|
+
config: ConfigOption = None,
|
|
213
|
+
state_dir: StateDirOption = None,
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Disable monitoring for a project."""
|
|
216
|
+
try:
|
|
217
|
+
project = _manager(config).set_enabled(name, False)
|
|
218
|
+
except (ConfigError, GitError) as exc:
|
|
219
|
+
_fail(str(exc))
|
|
220
|
+
console.print(f"Disabled [bold]{escape(project.name)}[/bold].")
|
|
221
|
+
_restart_note(state_dir)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@app.command()
|
|
225
|
+
def profile(
|
|
226
|
+
name: Annotated[str, typer.Argument(help="Project name.")],
|
|
227
|
+
path: Annotated[
|
|
228
|
+
list[str] | None,
|
|
229
|
+
typer.Option("--path", "-p", help="Show which module this file belongs to."),
|
|
230
|
+
] = None,
|
|
231
|
+
config: ConfigOption = None,
|
|
232
|
+
) -> None:
|
|
233
|
+
"""Show how GitGatekeeper sees a project's architecture (read-only)."""
|
|
234
|
+
try:
|
|
235
|
+
project = _manager(config).get(name)
|
|
236
|
+
except (ConfigError, GitError) as exc:
|
|
237
|
+
_fail(str(exc))
|
|
238
|
+
detected = detect_profile(project.path, project.modules)
|
|
239
|
+
info = detected.describe()
|
|
240
|
+
console.print(f"[bold]{escape(project.name)}[/bold] → {escape(str(project.path))}")
|
|
241
|
+
console.print(f"Tracked files: {info['tracked_files']}")
|
|
242
|
+
console.print(f"Languages: {escape(', '.join(detected.languages) or '—')}")
|
|
243
|
+
console.print(f"Project kinds: {escape(', '.join(detected.kinds) or '—')}")
|
|
244
|
+
if detected.python_packages:
|
|
245
|
+
console.print(
|
|
246
|
+
f"Python packages: {escape(', '.join(sorted(detected.python_packages)))}"
|
|
247
|
+
)
|
|
248
|
+
if detected.rules:
|
|
249
|
+
table = Table(title="Modules from your configuration")
|
|
250
|
+
table.add_column("Module", style="bold")
|
|
251
|
+
table.add_column("Paths")
|
|
252
|
+
for rule in detected.rules:
|
|
253
|
+
table.add_row(escape(rule.name), escape(", ".join(rule.patterns)))
|
|
254
|
+
console.print(table)
|
|
255
|
+
else:
|
|
256
|
+
console.print(
|
|
257
|
+
"Modules are inferred from the folder and file names "
|
|
258
|
+
"(add a `modules:` block to the project to override)."
|
|
259
|
+
)
|
|
260
|
+
for item in path or []:
|
|
261
|
+
module = detected.module_for(item)
|
|
262
|
+
console.print(f"{escape(item)} → {escape(module) if module else '—'}")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
@app.command()
|
|
266
|
+
def check(
|
|
267
|
+
name: Annotated[
|
|
268
|
+
str | None, typer.Argument(help="Project to check (default: all).")
|
|
269
|
+
] = None,
|
|
270
|
+
config: ConfigOption = None,
|
|
271
|
+
offline: Annotated[
|
|
272
|
+
bool,
|
|
273
|
+
typer.Option(
|
|
274
|
+
"--offline", help="Do not contact the remotes (skip the access probe)."
|
|
275
|
+
),
|
|
276
|
+
] = False,
|
|
277
|
+
) -> None:
|
|
278
|
+
"""Check that each project can be committed and published (read-only).
|
|
279
|
+
|
|
280
|
+
Unless --offline is given, it asks each remote once (git ls-remote, never
|
|
281
|
+
prompting) whether it is reachable and accepts you.
|
|
282
|
+
"""
|
|
283
|
+
try:
|
|
284
|
+
manager = _manager(config)
|
|
285
|
+
loaded = manager.load()
|
|
286
|
+
selected = [manager.get(name)] if name else list(loaded.projects)
|
|
287
|
+
except (ConfigError, GitError) as exc:
|
|
288
|
+
_fail(str(exc))
|
|
289
|
+
if not selected:
|
|
290
|
+
_fail("no projects configured; add one with `gitgatekeeper add <path>`")
|
|
291
|
+
marks = {
|
|
292
|
+
Level.OK: "[green]ok[/green]",
|
|
293
|
+
Level.WARN: "[yellow]warn[/yellow]",
|
|
294
|
+
Level.FAIL: "[red]FAIL[/red]",
|
|
295
|
+
}
|
|
296
|
+
failed = False
|
|
297
|
+
for project in selected:
|
|
298
|
+
console.print(
|
|
299
|
+
f"[bold]{escape(project.name)}[/bold] → {escape(str(project.path))}"
|
|
300
|
+
)
|
|
301
|
+
for item in check_project(loaded, project, probe_remote=not offline):
|
|
302
|
+
failed = failed or item.level is Level.FAIL
|
|
303
|
+
console.print(f" {marks[item.level]} {escape(item.text)}")
|
|
304
|
+
if item.fix:
|
|
305
|
+
console.print(f" fix: [cyan]{escape(item.fix)}[/cyan]")
|
|
306
|
+
if failed:
|
|
307
|
+
raise typer.Exit(1)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# -- service control ----------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _build_service(config: Path | None, state: Path) -> GitGatekeeperService:
|
|
314
|
+
"""Separate function so tests can substitute a fast service."""
|
|
315
|
+
manager = _manager(config)
|
|
316
|
+
try:
|
|
317
|
+
loaded = manager.load()
|
|
318
|
+
return GitGatekeeperService(loaded, state_dir=state, config_loader=manager.load)
|
|
319
|
+
except ServiceError as exc:
|
|
320
|
+
message = f"{exc} (config file in use: {manager.config_path})"
|
|
321
|
+
user_config = USER_CONFIG.expanduser()
|
|
322
|
+
if manager.config_path != user_config.resolve() and user_config.is_file():
|
|
323
|
+
message += (
|
|
324
|
+
f". Another config exists at {user_config}; to use it, pass "
|
|
325
|
+
"--config or set GITGATEKEEPER_CONFIG."
|
|
326
|
+
)
|
|
327
|
+
_fail(message)
|
|
328
|
+
except ConfigError as exc:
|
|
329
|
+
_fail(str(exc))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@app.command()
|
|
333
|
+
def start(
|
|
334
|
+
config: ConfigOption = None,
|
|
335
|
+
state_dir: StateDirOption = None,
|
|
336
|
+
log_level: Annotated[
|
|
337
|
+
str, typer.Option("--log-level", help="DEBUG, INFO, WARNING or ERROR.")
|
|
338
|
+
] = "INFO",
|
|
339
|
+
) -> None:
|
|
340
|
+
"""Run GitGatekeeper in the foreground until Ctrl+C or `gitgatekeeper stop`.
|
|
341
|
+
|
|
342
|
+
To keep it running in the background, use a supervisor such as systemd.
|
|
343
|
+
"""
|
|
344
|
+
state = _state(state_dir)
|
|
345
|
+
pid = _running_pid(state)
|
|
346
|
+
if pid is not None:
|
|
347
|
+
_fail(
|
|
348
|
+
"GitGatekeeper is already running"
|
|
349
|
+
+ (f" (pid {pid})" if pid else "")
|
|
350
|
+
+ ". See it with `gitgatekeeper status`; stop it with `gitgatekeeper stop`."
|
|
351
|
+
)
|
|
352
|
+
try:
|
|
353
|
+
configure_logging(state, log_level, console=False)
|
|
354
|
+
except (ValueError, OSError) as exc:
|
|
355
|
+
_fail(str(exc))
|
|
356
|
+
service = _build_service(config, state)
|
|
357
|
+
|
|
358
|
+
def _handler(signum: int, _frame: object) -> None:
|
|
359
|
+
service.request_stop()
|
|
360
|
+
|
|
361
|
+
def _reload_handler(signum: int, _frame: object) -> None:
|
|
362
|
+
service.request_reload()
|
|
363
|
+
|
|
364
|
+
previous = {s: signal.signal(s, _handler) for s in (signal.SIGINT, signal.SIGTERM)}
|
|
365
|
+
previous[signal.SIGUSR1] = signal.signal(signal.SIGUSR1, _reload_handler)
|
|
366
|
+
console.print(
|
|
367
|
+
f"[bold green]GitGatekeeper[/bold green] v{__version__} running "
|
|
368
|
+
f"(logs: {escape(str(log_file_path(state)))}). Ctrl+C to stop."
|
|
369
|
+
)
|
|
370
|
+
console.print(f"Config: {escape(str(manager_path(config)))}")
|
|
371
|
+
try:
|
|
372
|
+
service.run()
|
|
373
|
+
except AlreadyRunningError as exc:
|
|
374
|
+
_fail(str(exc))
|
|
375
|
+
except (ServiceError, OSError) as exc:
|
|
376
|
+
_fail(f"could not start: {exc}")
|
|
377
|
+
finally:
|
|
378
|
+
for number, handler in previous.items():
|
|
379
|
+
signal.signal(number, handler)
|
|
380
|
+
console.print("GitGatekeeper stopped.")
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
@app.command()
|
|
384
|
+
def stop(
|
|
385
|
+
state_dir: StateDirOption = None,
|
|
386
|
+
timeout: Annotated[
|
|
387
|
+
float, typer.Option("--timeout", min=1, help="Seconds to wait.")
|
|
388
|
+
] = 30.0,
|
|
389
|
+
) -> None:
|
|
390
|
+
"""Ask a running GitGatekeeper to stop (SIGTERM; never SIGKILL)."""
|
|
391
|
+
outcome, pid = _stop_running(_state(state_dir), timeout=timeout)
|
|
392
|
+
if outcome is StopOutcome.NOT_RUNNING:
|
|
393
|
+
console.print("GitGatekeeper is not running.")
|
|
394
|
+
elif outcome is StopOutcome.STOPPED:
|
|
395
|
+
console.print(f"Stopped GitGatekeeper (pid {pid}).")
|
|
396
|
+
elif outcome is StopOutcome.TIMEOUT:
|
|
397
|
+
_fail(
|
|
398
|
+
f"pid {pid} did not exit within {timeout:g}s; it may be finishing a "
|
|
399
|
+
"commit or push. Check again with `gitgatekeeper status`."
|
|
400
|
+
)
|
|
401
|
+
elif outcome is StopOutcome.NO_PERMISSION:
|
|
402
|
+
_fail(f"not allowed to signal pid {pid}.")
|
|
403
|
+
else:
|
|
404
|
+
_fail(f"pid {pid} does not look like GitGatekeeper; refusing to signal it.")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@app.command()
|
|
408
|
+
def reload(
|
|
409
|
+
state_dir: StateDirOption = None,
|
|
410
|
+
timeout: Annotated[
|
|
411
|
+
float, typer.Option("--timeout", min=1, help="Seconds to wait for the answer.")
|
|
412
|
+
] = 20.0,
|
|
413
|
+
) -> None:
|
|
414
|
+
"""Make the running GitGatekeeper re-read its configuration, without a restart.
|
|
415
|
+
|
|
416
|
+
If the file is invalid, the running configuration stays in force.
|
|
417
|
+
"""
|
|
418
|
+
state = _state(state_dir)
|
|
419
|
+
if _running_pid(state) is None:
|
|
420
|
+
_fail("GitGatekeeper is not running; start it with `gitgatekeeper start`.")
|
|
421
|
+
status = read_status(state)
|
|
422
|
+
if not status or not status.get("reload_supported"):
|
|
423
|
+
_fail(
|
|
424
|
+
"the running GitGatekeeper was started before `reload` existed (or has not "
|
|
425
|
+
"written its status yet). Restart it once with `gitgatekeeper stop` and "
|
|
426
|
+
"`gitgatekeeper start`; after that `gitgatekeeper reload` works."
|
|
427
|
+
)
|
|
428
|
+
before = _reload_seq(status)
|
|
429
|
+
outcome, pid = signal_running(state, signal.SIGUSR1)
|
|
430
|
+
if outcome is SignalOutcome.NOT_RUNNING:
|
|
431
|
+
_fail("GitGatekeeper is not running; start it with `gitgatekeeper start`.")
|
|
432
|
+
if outcome is SignalOutcome.NO_PERMISSION:
|
|
433
|
+
_fail(f"not allowed to signal pid {pid}.")
|
|
434
|
+
if outcome is SignalOutcome.REFUSED:
|
|
435
|
+
_fail(f"pid {pid} does not look like GitGatekeeper; refusing to signal it.")
|
|
436
|
+
deadline = time.monotonic() + timeout
|
|
437
|
+
while time.monotonic() < deadline:
|
|
438
|
+
time.sleep(0.2)
|
|
439
|
+
latest = read_status(state)
|
|
440
|
+
info = latest.get("reload") if latest else None
|
|
441
|
+
if isinstance(info, dict) and _reload_seq(latest) > before:
|
|
442
|
+
detail = escape(str(info.get("detail", "")))
|
|
443
|
+
if info.get("ok"):
|
|
444
|
+
console.print(f"[green]Reloaded[/green]: {detail}")
|
|
445
|
+
return
|
|
446
|
+
err_console.print(f"[red]Not reloaded[/red]: {detail}")
|
|
447
|
+
err_console.print("The running configuration was kept.")
|
|
448
|
+
raise typer.Exit(code=1)
|
|
449
|
+
_fail(
|
|
450
|
+
f"no answer within {timeout:g}s; the service may be busy with a commit. "
|
|
451
|
+
"Check `gitgatekeeper logs --raw`."
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _reload_seq(status: dict[str, object] | None) -> int:
|
|
456
|
+
info = status.get("reload") if status else None
|
|
457
|
+
seq = info.get("seq") if isinstance(info, dict) else 0
|
|
458
|
+
return seq if isinstance(seq, int) else 0
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _fmt_seconds(value: object) -> str:
|
|
462
|
+
if not isinstance(value, int | float):
|
|
463
|
+
return "—"
|
|
464
|
+
seconds = int(value)
|
|
465
|
+
minutes, secs = divmod(seconds, 60)
|
|
466
|
+
return f"{minutes}m{secs:02d}s" if minutes else f"{secs}s"
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _ago(stamp: str | None) -> str:
|
|
470
|
+
if not stamp:
|
|
471
|
+
return "—"
|
|
472
|
+
try:
|
|
473
|
+
then = datetime.fromisoformat(stamp)
|
|
474
|
+
except ValueError:
|
|
475
|
+
return stamp
|
|
476
|
+
if then.tzinfo is None:
|
|
477
|
+
then = then.replace(tzinfo=UTC)
|
|
478
|
+
seconds = (datetime.now(UTC) - then).total_seconds()
|
|
479
|
+
return f"{_fmt_seconds(max(seconds, 0))} ago" if seconds < 3600 else stamp[:16]
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _open_store(state: Path) -> HistoryStore | None:
|
|
483
|
+
path = history_path(state)
|
|
484
|
+
if not path.exists():
|
|
485
|
+
return None
|
|
486
|
+
try:
|
|
487
|
+
return HistoryStore.open(path)
|
|
488
|
+
except StorageError as exc:
|
|
489
|
+
_fail(f"history database unavailable: {exc}")
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
@app.command()
|
|
493
|
+
def status(config: ConfigOption = None, state_dir: StateDirOption = None) -> None:
|
|
494
|
+
"""Show whether GitGatekeeper is running and what each project is doing."""
|
|
495
|
+
state = _state(state_dir)
|
|
496
|
+
pid = _running_pid(state)
|
|
497
|
+
live = read_status(state) if pid is not None else None
|
|
498
|
+
if pid is None:
|
|
499
|
+
console.print("[yellow]GitGatekeeper is not running.[/yellow]")
|
|
500
|
+
else:
|
|
501
|
+
started = live.get("started_at") if live else None
|
|
502
|
+
console.print(
|
|
503
|
+
f"[green]GitGatekeeper is running[/green] (pid {pid or '?'}"
|
|
504
|
+
f"{', since ' + str(started) if started else ''})."
|
|
505
|
+
)
|
|
506
|
+
try:
|
|
507
|
+
loaded = _manager(config).load()
|
|
508
|
+
except ConfigError as exc:
|
|
509
|
+
_fail(str(exc))
|
|
510
|
+
|
|
511
|
+
by_name = {}
|
|
512
|
+
if live and isinstance(live.get("projects"), list):
|
|
513
|
+
by_name = {p.get("name"): p for p in live["projects"] if isinstance(p, dict)}
|
|
514
|
+
store = _open_store(state)
|
|
515
|
+
|
|
516
|
+
table = Table(title="GitGatekeeper status")
|
|
517
|
+
for column in (
|
|
518
|
+
"Project",
|
|
519
|
+
"Branch",
|
|
520
|
+
"State",
|
|
521
|
+
"Idle",
|
|
522
|
+
"Next cycle",
|
|
523
|
+
"Pending",
|
|
524
|
+
"Last commit",
|
|
525
|
+
):
|
|
526
|
+
table.add_column(column)
|
|
527
|
+
table.add_column("Auto-push")
|
|
528
|
+
for project in loaded.projects:
|
|
529
|
+
info = by_name.get(project.name, {})
|
|
530
|
+
if not project.enabled:
|
|
531
|
+
state_text = "[yellow]disabled[/yellow]"
|
|
532
|
+
elif info.get("error"):
|
|
533
|
+
state_text = f"[red]error: {escape(str(info['error']))}[/red]"
|
|
534
|
+
elif info:
|
|
535
|
+
state_text = escape(str(info.get("state", "idle")))
|
|
536
|
+
else:
|
|
537
|
+
state_text = "—" if pid is None else "[yellow]not watched[/yellow]"
|
|
538
|
+
branch = "—"
|
|
539
|
+
try:
|
|
540
|
+
snap = analyze_repository(project.path)
|
|
541
|
+
pending = str(len(snap.files))
|
|
542
|
+
if snap.branch.name:
|
|
543
|
+
patterns = loaded.effective_protected_branches(project)
|
|
544
|
+
locked = any(fnmatchcase(snap.branch.name, p) for p in patterns)
|
|
545
|
+
branch = escape(snap.branch.name)
|
|
546
|
+
if snap.branch.ahead:
|
|
547
|
+
branch += f" ↑{snap.branch.ahead}"
|
|
548
|
+
if locked:
|
|
549
|
+
branch += " [yellow](protected)[/yellow]"
|
|
550
|
+
except GitError:
|
|
551
|
+
pending = "[red]unavailable[/red]"
|
|
552
|
+
last = store.last_commit(project.name) if store else None
|
|
553
|
+
table.add_row(
|
|
554
|
+
escape(project.name),
|
|
555
|
+
branch,
|
|
556
|
+
state_text,
|
|
557
|
+
_fmt_seconds(info.get("idle_seconds")),
|
|
558
|
+
_fmt_seconds(info.get("remaining_seconds")),
|
|
559
|
+
pending,
|
|
560
|
+
escape(f"{last.header} ({_ago(last.created_at)})") if last else "—",
|
|
561
|
+
"yes" if loaded.effective_auto_push(project) else "no",
|
|
562
|
+
)
|
|
563
|
+
console.print(table)
|
|
564
|
+
waiting = len(store.pending()) if store else 0
|
|
565
|
+
if waiting:
|
|
566
|
+
console.print(
|
|
567
|
+
f"[yellow]{waiting} commit(s) waiting for approval: "
|
|
568
|
+
"see `gitgatekeeper pending`.[/yellow]"
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
@app.command()
|
|
573
|
+
def history(
|
|
574
|
+
project: ProjectOption = None,
|
|
575
|
+
limit: LimitOption = 20,
|
|
576
|
+
files: Annotated[bool, typer.Option("--files", help="List changed files.")] = False,
|
|
577
|
+
state_dir: StateDirOption = None,
|
|
578
|
+
) -> None:
|
|
579
|
+
"""Show the commits GitGatekeeper made."""
|
|
580
|
+
store = _open_store(_state(state_dir))
|
|
581
|
+
commits = store.recent_commits(project, limit) if store else []
|
|
582
|
+
if not commits:
|
|
583
|
+
console.print("No commits recorded yet.")
|
|
584
|
+
return
|
|
585
|
+
table = Table(title="GitGatekeeper commits")
|
|
586
|
+
for column in ("When (UTC)", "Project", "Commit", "Message", "Pushed"):
|
|
587
|
+
table.add_column(column)
|
|
588
|
+
for item in commits:
|
|
589
|
+
message = escape(item.header)
|
|
590
|
+
if files:
|
|
591
|
+
message += "\n" + "\n".join(f" {escape(f)}" for f in item.files)
|
|
592
|
+
if item.undone:
|
|
593
|
+
message = f"[dim strike]{message}[/dim strike] [yellow](undone)[/yellow]"
|
|
594
|
+
table.add_row(
|
|
595
|
+
item.created_at[:19].replace("T", " "),
|
|
596
|
+
escape(item.project),
|
|
597
|
+
item.oid[:8],
|
|
598
|
+
message,
|
|
599
|
+
"[green]✓[/green]" if item.pushed else "—",
|
|
600
|
+
)
|
|
601
|
+
console.print(table)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _pick_pending(
|
|
605
|
+
store: HistoryStore | None,
|
|
606
|
+
ids: list[int] | None,
|
|
607
|
+
everything: bool,
|
|
608
|
+
project: str | None,
|
|
609
|
+
) -> list[int]:
|
|
610
|
+
"""The proposals a command applies to, oldest first."""
|
|
611
|
+
if not ids and not everything:
|
|
612
|
+
_fail("Give one or more ids (see `gitgatekeeper pending`) or use --all.")
|
|
613
|
+
if ids and everything:
|
|
614
|
+
_fail("Use either ids or --all, not both.")
|
|
615
|
+
if everything:
|
|
616
|
+
return [p.id for p in store.pending(project)] if store else []
|
|
617
|
+
return sorted(set(ids or []))
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
@app.command()
|
|
621
|
+
def pending(
|
|
622
|
+
project: ProjectOption = None,
|
|
623
|
+
files: Annotated[bool, typer.Option("--files", help="List changed files.")] = False,
|
|
624
|
+
state_dir: StateDirOption = None,
|
|
625
|
+
) -> None:
|
|
626
|
+
"""Show the commits GitGatekeeper prepared and is holding for your approval."""
|
|
627
|
+
store = _open_store(_state(state_dir))
|
|
628
|
+
held = store.pending(project) if store else []
|
|
629
|
+
if not held:
|
|
630
|
+
console.print("Nothing is waiting for approval.")
|
|
631
|
+
return
|
|
632
|
+
table = Table(title="Waiting for approval")
|
|
633
|
+
for column in ("Id", "Project", "Branch", "Prepared (UTC)", "Message", "Files"):
|
|
634
|
+
table.add_column(column)
|
|
635
|
+
for item in held:
|
|
636
|
+
message = escape(item.header)
|
|
637
|
+
if files:
|
|
638
|
+
message += "\n" + "\n".join(f" {escape(f)}" for f in item.files)
|
|
639
|
+
table.add_row(
|
|
640
|
+
str(item.id),
|
|
641
|
+
escape(item.project),
|
|
642
|
+
escape(item.branch or "—"),
|
|
643
|
+
item.created_at[:19].replace("T", " "),
|
|
644
|
+
message,
|
|
645
|
+
str(len(item.files)),
|
|
646
|
+
)
|
|
647
|
+
console.print(table)
|
|
648
|
+
console.print(
|
|
649
|
+
"Commit with [bold]gitgatekeeper approve <id>[/bold] (or --all); "
|
|
650
|
+
"discard with [bold]gitgatekeeper reject <id>[/bold]."
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
@app.command()
|
|
655
|
+
def approve(
|
|
656
|
+
ids: Annotated[list[int] | None, typer.Argument(help="Ids to approve.")] = None,
|
|
657
|
+
everything: Annotated[
|
|
658
|
+
bool, typer.Option("--all", help="Approve everything that is waiting.")
|
|
659
|
+
] = False,
|
|
660
|
+
project: ProjectOption = None,
|
|
661
|
+
config: ConfigOption = None,
|
|
662
|
+
state_dir: StateDirOption = None,
|
|
663
|
+
) -> None:
|
|
664
|
+
"""Commit what GitGatekeeper prepared, if the files are unchanged."""
|
|
665
|
+
state = _state(state_dir)
|
|
666
|
+
chosen = _pick_pending(_open_store(state), ids, everything, project)
|
|
667
|
+
if not chosen:
|
|
668
|
+
console.print("Nothing is waiting for approval.")
|
|
669
|
+
return
|
|
670
|
+
service = _build_service(config, state)
|
|
671
|
+
failed = False
|
|
672
|
+
for pending_id in chosen:
|
|
673
|
+
try:
|
|
674
|
+
result, push = service.approve(pending_id)
|
|
675
|
+
except ServiceError as exc:
|
|
676
|
+
err_console.print(f"[red]#{pending_id}[/red] {escape(str(exc))}")
|
|
677
|
+
failed = True
|
|
678
|
+
continue
|
|
679
|
+
if result.committed:
|
|
680
|
+
line = f"[green]#{pending_id} committed[/green] {(result.commit or '')[:8]}"
|
|
681
|
+
if result.message:
|
|
682
|
+
line += f" {escape(result.message.header)}"
|
|
683
|
+
if push is not None:
|
|
684
|
+
line += f" (push: {push.outcome.value})"
|
|
685
|
+
console.print(line)
|
|
686
|
+
continue
|
|
687
|
+
failed = True
|
|
688
|
+
err_console.print(
|
|
689
|
+
f"[red]#{pending_id} not committed[/red] "
|
|
690
|
+
f"({result.reason.value if result.reason else result.outcome.value}): "
|
|
691
|
+
f"{escape(result.detail or 'nothing to commit')}"
|
|
692
|
+
)
|
|
693
|
+
if failed:
|
|
694
|
+
raise typer.Exit(code=1)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
@app.command()
|
|
698
|
+
def reject(
|
|
699
|
+
ids: Annotated[list[int] | None, typer.Argument(help="Ids to discard.")] = None,
|
|
700
|
+
everything: Annotated[
|
|
701
|
+
bool, typer.Option("--all", help="Discard everything that is waiting.")
|
|
702
|
+
] = False,
|
|
703
|
+
project: ProjectOption = None,
|
|
704
|
+
state_dir: StateDirOption = None,
|
|
705
|
+
) -> None:
|
|
706
|
+
"""Discard prepared commits. Your files are not touched."""
|
|
707
|
+
store = _open_store(_state(state_dir))
|
|
708
|
+
chosen = _pick_pending(store, ids, everything, project)
|
|
709
|
+
if not chosen or store is None:
|
|
710
|
+
console.print("Nothing is waiting for approval.")
|
|
711
|
+
return
|
|
712
|
+
failed = False
|
|
713
|
+
for pending_id in chosen:
|
|
714
|
+
record = store.get_pending(pending_id)
|
|
715
|
+
if record is None or not store.decide_pending(pending_id, "rejected"):
|
|
716
|
+
state = record.status if record else "unknown"
|
|
717
|
+
err_console.print(f"[red]#{pending_id}[/red] not waiting ({state})")
|
|
718
|
+
failed = True
|
|
719
|
+
continue
|
|
720
|
+
console.print(f"#{pending_id} rejected: {escape(record.header)}")
|
|
721
|
+
if failed:
|
|
722
|
+
raise typer.Exit(code=1)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _free_name(wanted: str, parent: str, taken: set[str]) -> str:
|
|
726
|
+
"""``wanted``, or ``parent-wanted`` / ``wanted-2`` if the name is in use."""
|
|
727
|
+
for candidate in (wanted, f"{parent}-{wanted}"):
|
|
728
|
+
if candidate.casefold() not in taken:
|
|
729
|
+
return candidate
|
|
730
|
+
number = 2
|
|
731
|
+
while f"{wanted}-{number}".casefold() in taken:
|
|
732
|
+
number += 1
|
|
733
|
+
return f"{wanted}-{number}"
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
@app.command()
|
|
737
|
+
def init(
|
|
738
|
+
root: Annotated[
|
|
739
|
+
list[Path] | None,
|
|
740
|
+
typer.Option(
|
|
741
|
+
"--root",
|
|
742
|
+
"-r",
|
|
743
|
+
help="Folder to search for repositories (repeatable). Default: the "
|
|
744
|
+
"usual code folders under your home, such as ~/Projects or ~/dev.",
|
|
745
|
+
),
|
|
746
|
+
] = None,
|
|
747
|
+
depth: Annotated[
|
|
748
|
+
int, typer.Option("--depth", min=1, max=8, help="How deep to search.")
|
|
749
|
+
] = DEFAULT_DEPTH,
|
|
750
|
+
yes: Annotated[
|
|
751
|
+
bool, typer.Option("--yes", "-y", help="Register everything found.")
|
|
752
|
+
] = False,
|
|
753
|
+
config: ConfigOption = None,
|
|
754
|
+
state_dir: StateDirOption = None,
|
|
755
|
+
) -> None:
|
|
756
|
+
"""Find your repositories and register them (first-time setup).
|
|
757
|
+
|
|
758
|
+
Read-only until you confirm: nothing in any repository is changed, and an
|
|
759
|
+
existing configuration is only added to, never overwritten.
|
|
760
|
+
"""
|
|
761
|
+
manager = _manager(config)
|
|
762
|
+
try:
|
|
763
|
+
current = manager.load()
|
|
764
|
+
except ConfigError as exc:
|
|
765
|
+
_fail(str(exc))
|
|
766
|
+
roots = list(root) if root else default_roots()
|
|
767
|
+
if not roots:
|
|
768
|
+
_fail(
|
|
769
|
+
"no usual code folder found under your home; "
|
|
770
|
+
"say where to look with --root PATH"
|
|
771
|
+
)
|
|
772
|
+
try:
|
|
773
|
+
found = discover(roots, depth=depth)
|
|
774
|
+
except (OSError, GitError) as exc:
|
|
775
|
+
_fail(str(exc))
|
|
776
|
+
known = {project.path for project in current.projects}
|
|
777
|
+
fresh = [item for item in found if item.path not in known]
|
|
778
|
+
where = ", ".join(escape(str(r)) for r in roots)
|
|
779
|
+
if not fresh:
|
|
780
|
+
console.print(
|
|
781
|
+
f"No new repositories found under {where} "
|
|
782
|
+
f"({len(found) - len(fresh)} already registered)."
|
|
783
|
+
)
|
|
784
|
+
return
|
|
785
|
+
|
|
786
|
+
table = Table(title=f"Repositories found under {where}")
|
|
787
|
+
table.add_column("#", justify="right")
|
|
788
|
+
table.add_column("Name", style="bold")
|
|
789
|
+
table.add_column("Branch")
|
|
790
|
+
table.add_column("Remote", overflow="fold")
|
|
791
|
+
table.add_column("Note")
|
|
792
|
+
for number, item in enumerate(fresh, start=1):
|
|
793
|
+
protected = item.branch in current.protected_branches
|
|
794
|
+
notes = []
|
|
795
|
+
if protected:
|
|
796
|
+
notes.append("protected branch: not committed")
|
|
797
|
+
if item.remote is None:
|
|
798
|
+
notes.append("no remote")
|
|
799
|
+
table.add_row(
|
|
800
|
+
str(number),
|
|
801
|
+
escape(item.name),
|
|
802
|
+
escape(item.branch or "(detached)"),
|
|
803
|
+
escape(item.remote or "—"),
|
|
804
|
+
"; ".join(notes) or "—",
|
|
805
|
+
)
|
|
806
|
+
console.print(table)
|
|
807
|
+
|
|
808
|
+
if yes:
|
|
809
|
+
chosen = list(range(len(fresh)))
|
|
810
|
+
else:
|
|
811
|
+
while True:
|
|
812
|
+
answer = typer.prompt(
|
|
813
|
+
"Register which ones? (all, none, or e.g. 1,3,5-7)", default="all"
|
|
814
|
+
)
|
|
815
|
+
try:
|
|
816
|
+
chosen = parse_selection(answer, len(fresh))
|
|
817
|
+
break
|
|
818
|
+
except ValueError as exc:
|
|
819
|
+
err_console.print(f"[red]{escape(str(exc))}[/red]")
|
|
820
|
+
if not chosen:
|
|
821
|
+
console.print("Nothing registered.")
|
|
822
|
+
return
|
|
823
|
+
|
|
824
|
+
taken = {project.name.casefold() for project in current.projects}
|
|
825
|
+
added = 0
|
|
826
|
+
for index in chosen:
|
|
827
|
+
item = fresh[index]
|
|
828
|
+
name = _free_name(item.name, item.path.parent.name, taken)
|
|
829
|
+
try:
|
|
830
|
+
manager.add(item.path, name=name)
|
|
831
|
+
except (ConfigError, GitError) as exc:
|
|
832
|
+
err_console.print(
|
|
833
|
+
f"[red]Skipped {escape(item.name)}:[/red] {escape(str(exc))}"
|
|
834
|
+
)
|
|
835
|
+
continue
|
|
836
|
+
taken.add(name.casefold())
|
|
837
|
+
added += 1
|
|
838
|
+
console.print(
|
|
839
|
+
f"Registered [bold]{added}[/bold] repositor{'y' if added == 1 else 'ies'} in "
|
|
840
|
+
f"{escape(str(manager.config_path))}."
|
|
841
|
+
)
|
|
842
|
+
console.print(
|
|
843
|
+
"Safe defaults: nothing is pushed (auto_push off) and main/master are never "
|
|
844
|
+
"committed.\nNext: [bold]gitgatekeeper check[/bold], then "
|
|
845
|
+
"[bold]gitgatekeeper service install[/bold] "
|
|
846
|
+
"(or [bold]gitgatekeeper start[/bold])."
|
|
847
|
+
)
|
|
848
|
+
_restart_note(state_dir)
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _unit_error(exc: systemd.SystemdError) -> NoReturn:
|
|
852
|
+
_fail(str(exc))
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
@app.command("migrate")
|
|
856
|
+
def migrate_command(
|
|
857
|
+
config: ConfigOption = None,
|
|
858
|
+
state_dir: StateDirOption = None,
|
|
859
|
+
) -> None:
|
|
860
|
+
"""Copy your settings and history from the old name (GitPilot).
|
|
861
|
+
|
|
862
|
+
Only copies: the old files are never changed or deleted, and nothing that
|
|
863
|
+
already exists under the new name is overwritten.
|
|
864
|
+
"""
|
|
865
|
+
# Not default_config_path(): a ./config/projects.yaml in the current folder
|
|
866
|
+
# (this repository's own template, say) must never be taken for the user's
|
|
867
|
+
# settings and made to shadow the copy.
|
|
868
|
+
if config is not None:
|
|
869
|
+
target = config.expanduser().resolve()
|
|
870
|
+
else:
|
|
871
|
+
target = Path(os.environ.get(CONFIG_ENV_VAR) or USER_CONFIG).expanduser()
|
|
872
|
+
try:
|
|
873
|
+
steps = migrate.migrate(migrate.legacy_paths(), target, _state(state_dir))
|
|
874
|
+
except migrate.MigrationError as exc:
|
|
875
|
+
_fail(str(exc))
|
|
876
|
+
for step in steps:
|
|
877
|
+
mark = "[green]✓[/green]" if step.done else "[yellow]•[/yellow]"
|
|
878
|
+
console.print(f"{mark} {escape(step.message)}")
|
|
879
|
+
if any(step.done for step in steps):
|
|
880
|
+
console.print(
|
|
881
|
+
"Old files were left in place; delete them yourself when you are happy."
|
|
882
|
+
)
|
|
883
|
+
console.print("Next: [bold]gitgatekeeper check[/bold].")
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
@service_app.command("install")
|
|
887
|
+
def service_install(
|
|
888
|
+
config: ConfigOption = None,
|
|
889
|
+
state_dir: StateDirOption = None,
|
|
890
|
+
start: Annotated[
|
|
891
|
+
bool, typer.Option("--start/--no-start", help="Start it now.")
|
|
892
|
+
] = True,
|
|
893
|
+
force: Annotated[
|
|
894
|
+
bool, typer.Option("--force", help="Replace a different existing unit.")
|
|
895
|
+
] = False,
|
|
896
|
+
) -> None:
|
|
897
|
+
"""Install and enable GitGatekeeper as a systemd user service."""
|
|
898
|
+
manager = _manager(config)
|
|
899
|
+
try:
|
|
900
|
+
loaded = manager.load()
|
|
901
|
+
except ConfigError as exc:
|
|
902
|
+
_fail(str(exc))
|
|
903
|
+
if not manager.config_path.is_file() or not any(p.enabled for p in loaded.projects):
|
|
904
|
+
_fail(
|
|
905
|
+
f"{manager.config_path} watches no project yet; "
|
|
906
|
+
"run `gitgatekeeper init` (or `gitgatekeeper add <path>`) first"
|
|
907
|
+
)
|
|
908
|
+
state = _state(state_dir)
|
|
909
|
+
try:
|
|
910
|
+
before = systemd.unit_status()
|
|
911
|
+
pid = _running_pid(state)
|
|
912
|
+
if start and pid is not None and before.active != "active":
|
|
913
|
+
_fail(
|
|
914
|
+
"GitGatekeeper is already running in the foreground"
|
|
915
|
+
+ (f" (pid {pid})" if pid else "")
|
|
916
|
+
+ "; stop it with `gitgatekeeper stop` first, or use --no-start"
|
|
917
|
+
)
|
|
918
|
+
unit = systemd.render_unit(
|
|
919
|
+
systemd.find_executable(),
|
|
920
|
+
manager.config_path,
|
|
921
|
+
state_dir=_state(state_dir) if state_dir is not None else None,
|
|
922
|
+
ssh_auth_sock=systemd.ssh_socket(),
|
|
923
|
+
)
|
|
924
|
+
path = systemd.install(unit, start=start, force=force)
|
|
925
|
+
except systemd.SystemdError as exc:
|
|
926
|
+
_unit_error(exc)
|
|
927
|
+
console.print(f"Installed [bold]{escape(str(path))}[/bold].")
|
|
928
|
+
console.print(
|
|
929
|
+
"Running now. Follow it with `gitgatekeeper status`."
|
|
930
|
+
if start
|
|
931
|
+
else "Enabled; it starts at your next login, or run "
|
|
932
|
+
"`systemctl --user start gitgatekeeper`."
|
|
933
|
+
)
|
|
934
|
+
console.print(
|
|
935
|
+
"It runs while you are logged in. To keep it running after logout, run "
|
|
936
|
+
"`loginctl enable-linger $USER` yourself; GitGatekeeper never does that."
|
|
937
|
+
)
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
@service_app.command("uninstall")
|
|
941
|
+
def service_uninstall() -> None:
|
|
942
|
+
"""Stop, disable and remove the systemd user service."""
|
|
943
|
+
try:
|
|
944
|
+
removed = systemd.uninstall()
|
|
945
|
+
except systemd.SystemdError as exc:
|
|
946
|
+
_unit_error(exc)
|
|
947
|
+
if removed:
|
|
948
|
+
console.print("Service stopped, disabled and removed.")
|
|
949
|
+
else:
|
|
950
|
+
console.print("The service is not installed.")
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
@service_app.command("status")
|
|
954
|
+
def service_status() -> None:
|
|
955
|
+
"""Show whether the systemd user service is installed and running."""
|
|
956
|
+
try:
|
|
957
|
+
info = systemd.unit_status()
|
|
958
|
+
except systemd.SystemdError as exc:
|
|
959
|
+
_unit_error(exc)
|
|
960
|
+
if not info.installed:
|
|
961
|
+
console.print("Not installed. Use `gitgatekeeper service install`.")
|
|
962
|
+
return
|
|
963
|
+
console.print(
|
|
964
|
+
f"Unit: {escape(str(info.path))}\n"
|
|
965
|
+
f"Enabled: {info.enabled}\nActive: {info.active}"
|
|
966
|
+
)
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
@app.command()
|
|
970
|
+
def undo(
|
|
971
|
+
project: Annotated[str, typer.Argument(help="Project whose last commit to undo.")],
|
|
972
|
+
yes: Annotated[bool, typer.Option("--yes", "-y", help="Do not ask.")] = False,
|
|
973
|
+
config: ConfigOption = None,
|
|
974
|
+
state_dir: StateDirOption = None,
|
|
975
|
+
) -> None:
|
|
976
|
+
"""Take back the last commit GitGatekeeper made in a project.
|
|
977
|
+
|
|
978
|
+
Your files are left exactly as they are; only the commit goes away. It is
|
|
979
|
+
refused if the commit was pushed, is not the latest one, or you have staged
|
|
980
|
+
changes. The same set of changes is not committed again automatically.
|
|
981
|
+
"""
|
|
982
|
+
try:
|
|
983
|
+
name = _manager(config).get(project).name
|
|
984
|
+
except ConfigError as exc:
|
|
985
|
+
_fail(str(exc))
|
|
986
|
+
state = _state(state_dir)
|
|
987
|
+
store = _open_store(state)
|
|
988
|
+
record = store.last_commit(name) if store else None
|
|
989
|
+
if store is None or record is None:
|
|
990
|
+
_fail(f"GitGatekeeper has no commit to undo in {name!r}")
|
|
991
|
+
if record.pushed:
|
|
992
|
+
_fail(
|
|
993
|
+
f"{record.oid[:8]} was already pushed; GitGatekeeper never rewrites "
|
|
994
|
+
f"published history. Use `git revert {record.oid[:8]}` instead"
|
|
995
|
+
)
|
|
996
|
+
shown = record.files[:8]
|
|
997
|
+
console.print(
|
|
998
|
+
f"[bold]{escape(record.header)}[/bold]\n"
|
|
999
|
+
f"{record.oid[:8]} on {escape(record.branch or '(detached)')}, "
|
|
1000
|
+
f"{record.created_at[:19].replace('T', ' ')} UTC, {len(record.files)} file(s)"
|
|
1001
|
+
)
|
|
1002
|
+
for path in shown:
|
|
1003
|
+
console.print(f" {escape(path)}")
|
|
1004
|
+
if len(record.files) > len(shown):
|
|
1005
|
+
console.print(f" ... and {len(record.files) - len(shown)} more")
|
|
1006
|
+
if not yes and not typer.confirm(
|
|
1007
|
+
"Undo this commit? Your files stay exactly as they are", default=False
|
|
1008
|
+
):
|
|
1009
|
+
console.print("Nothing changed.")
|
|
1010
|
+
return
|
|
1011
|
+
try:
|
|
1012
|
+
result = undo_commit(Path(record.repo), record.oid, lock_dir=state / "locks")
|
|
1013
|
+
except UndoError as exc:
|
|
1014
|
+
_fail(str(exc))
|
|
1015
|
+
store.mark_undone(record.id)
|
|
1016
|
+
store.add_event(
|
|
1017
|
+
project=name,
|
|
1018
|
+
kind="commit",
|
|
1019
|
+
outcome="undone",
|
|
1020
|
+
detail=record.header,
|
|
1021
|
+
commit_oid=record.oid,
|
|
1022
|
+
)
|
|
1023
|
+
console.print(
|
|
1024
|
+
f"Undone: {escape(record.header)}. The changes are back in your working "
|
|
1025
|
+
"tree, not staged.\n"
|
|
1026
|
+
"GitGatekeeper will not commit this exact set of changes again; once you "
|
|
1027
|
+
"edit them it commits the new version after the usual inactivity.\n"
|
|
1028
|
+
f"To put the commit back: git reset {result.oid[:8]}"
|
|
1029
|
+
)
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
@app.command()
|
|
1033
|
+
def logs(
|
|
1034
|
+
project: ProjectOption = None,
|
|
1035
|
+
kind: Annotated[str | None, typer.Option("--kind", help="commit or push.")] = None,
|
|
1036
|
+
limit: LimitOption = 30,
|
|
1037
|
+
raw: Annotated[
|
|
1038
|
+
bool, typer.Option("--raw", help="Tail the JSON log file instead.")
|
|
1039
|
+
] = False,
|
|
1040
|
+
state_dir: StateDirOption = None,
|
|
1041
|
+
) -> None:
|
|
1042
|
+
"""Show recent cycle events (or, with --raw, the service log file)."""
|
|
1043
|
+
state = _state(state_dir)
|
|
1044
|
+
if raw:
|
|
1045
|
+
lines = read_log_tail(log_file_path(state), limit)
|
|
1046
|
+
if not lines:
|
|
1047
|
+
console.print("No log file yet.")
|
|
1048
|
+
for line in lines:
|
|
1049
|
+
console.print(escape(line), soft_wrap=True, highlight=False)
|
|
1050
|
+
return
|
|
1051
|
+
if kind not in (None, "commit", "push"):
|
|
1052
|
+
_fail("--kind must be 'commit' or 'push'")
|
|
1053
|
+
store = _open_store(state)
|
|
1054
|
+
events = store.recent_events(project, kind=kind, limit=limit) if store else []
|
|
1055
|
+
if not events:
|
|
1056
|
+
console.print("No events recorded yet.")
|
|
1057
|
+
return
|
|
1058
|
+
table = Table(title="GitGatekeeper events")
|
|
1059
|
+
for column in ("When (UTC)", "Project", "Kind", "Outcome", "Reason", "Detail"):
|
|
1060
|
+
table.add_column(column)
|
|
1061
|
+
for ev in events:
|
|
1062
|
+
table.add_row(
|
|
1063
|
+
ev.created_at[:19].replace("T", " "),
|
|
1064
|
+
escape(ev.project),
|
|
1065
|
+
ev.kind,
|
|
1066
|
+
ev.outcome,
|
|
1067
|
+
ev.reason or "—",
|
|
1068
|
+
escape(ev.detail),
|
|
1069
|
+
)
|
|
1070
|
+
console.print(table)
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
if __name__ == "__main__":
|
|
1074
|
+
app()
|