-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetKernel.py
More file actions
1349 lines (1260 loc) · 46.2 KB
/
Copy pathGetKernel.py
File metadata and controls
1349 lines (1260 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
GetKernel — main CLI entry (orchestrator).
Developer: Cuma KURT <cumakurt@gmail.com>
Project: https://github.com/cumakurt/GetKernel
"""
from __future__ import annotations
import json
import logging
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Set
import click
from modules.compiler import Compiler
from modules.config_manager import ConfigManager
from modules.dependency_manager import DependencyManager
from modules.grub_manager import GrubManager
from modules.installer import Installer
from modules.kernel_fetcher import KernelFetcher
from modules.package_builder import PackageBuilder, find_matching_stored_packages
from modules.package_depot import (
list_archived_builds,
list_latest_packages,
read_build_history,
read_build_info,
resolve_package_paths,
)
from modules.system_advisor import (
collect_build_warnings,
collect_install_warnings,
status_secure_boot,
)
from modules.system_checker import SystemChecker
from modules.uninstaller import detect_remnants, uninstall_getkernel
from utils.constants import (
APP_VERSION,
DEVELOPER_EMAIL,
DEVELOPER_GITHUB_REPO_URL,
DEVELOPER_LINKEDIN_URL,
DEVELOPER_NAME,
)
from utils.exceptions import (
CompilationError,
ConfigError,
DependencyError,
GetKernelError,
)
from utils.helpers import (
assume_yes_from_env,
ensure_elevated,
generate_build_id,
load_yaml_config,
merge_dict,
project_root,
resolve_path,
)
from utils.logger import log_build_event, log_exception, setup_logging
from utils.ui import (
banner,
build_progress_display,
confirm,
print_build_step_summary,
print_build_success_summary,
print_error_block,
print_interactive_snapshot,
print_step,
print_table,
prompt_kernel_selection,
)
from utils.validator import (
canonical_kernel_release,
validate_backup_id,
validate_build_id,
validate_kernel_release,
validate_kernel_version,
validate_localversion,
)
_VERSION_MESSAGE = (
"%(prog)s %(version)s\n"
f"{DEVELOPER_NAME} <{DEVELOPER_EMAIL}>\n"
f"{DEVELOPER_GITHUB_REPO_URL}"
)
def _emit_json(data: Any, *, exit_code: int = 0) -> None:
click.echo(json.dumps(data, indent=2, default=str))
sys.exit(exit_code)
def _make_fetcher(cfg: Dict[str, Any], cache_dir: Path) -> KernelFetcher:
return KernelFetcher.from_config(str(cache_dir), cfg.get("kernel") or {})
def _resolve_profile_path(cfg: Dict[str, Any], profile: str) -> Path:
build_cfg = cfg.get("build") or {}
profiles = build_cfg.get("profiles") or {}
rel = profiles.get(profile)
if not rel:
raise click.UsageError(
f"Unknown profile {profile!r}. Available: {', '.join(sorted(profiles)) or '(none)'}"
)
path = resolve_path(project_root(), str(rel))
if not path.is_file():
raise click.UsageError(f"Profile file not found: {path}")
return path
def _latest_build_log(logs_dir: Path) -> Optional[Path]:
if not logs_dir.is_dir():
return None
logs = sorted(logs_dir.glob("build-*.log"), key=lambda p: p.stat().st_mtime, reverse=True)
return logs[0] if logs else None
def _load_config() -> Dict[str, Any]:
root = project_root()
base = load_yaml_config(root / "config" / "default_config.yaml")
user = load_yaml_config(root / "config" / "user_config.yaml")
cfg = merge_dict(base, user)
sections = (
"paths",
"kernel",
"build",
"system",
"logging",
"dependencies",
)
for name in sections:
if name in cfg and not isinstance(cfg[name], dict):
raise ConfigError(f"Configuration section {name!r} must be a mapping.")
boolean_fields = {
"kernel": ("include_beta", "include_rc", "verify_checksum", "verify_signature", "reuse_downloads"),
"build": ("use_ccache", "use_llvm", "localmodconfig"),
"logging": ("json_format",),
"dependencies": ("auto_install", "apt_update", "install_optional"),
}
for section, fields in boolean_fields.items():
values = cfg.get(section) or {}
for field in fields:
if field in values and not isinstance(values[field], bool):
raise ConfigError(
f"Configuration value {section}.{field} must be true or false."
)
return cfg
def _paths(cfg: Dict[str, Any]) -> Dict[str, Path]:
root = project_root()
p = cfg.get("paths") or {}
return {
"cache": resolve_path(root, str(p.get("cache_dir", "data/cache"))),
"logs": resolve_path(root, str(p.get("log_dir", "data/logs"))),
"builds": resolve_path(root, str(p.get("build_root", "data/builds"))),
"packages": resolve_path(root, str(p.get("packages_dir", "data/packages"))),
}
def _make_system_checker(cfg: Dict[str, Any], paths: Dict[str, Path]) -> SystemChecker:
"""Create a checker that honours configured limits and the real build filesystem."""
raw = cfg.get("system") or {}
system_cfg = raw if isinstance(raw, dict) else {}
try:
min_disk_gb = int(system_cfg.get("min_disk_gb", 20))
min_ram_gb = int(system_cfg.get("min_ram_gb", 4))
except (TypeError, ValueError) as exc:
raise click.UsageError(
"system.min_disk_gb and system.min_ram_gb must be positive integers."
) from exc
if min_disk_gb < 1 or min_ram_gb < 1:
raise click.UsageError(
"system.min_disk_gb and system.min_ram_gb must be positive integers."
)
return SystemChecker(
min_disk_gb=min_disk_gb,
min_ram_gb=min_ram_gb,
disk_path=str(paths["builds"]),
)
def _collect_config_fragments(
cfg: Dict[str, Any],
root: Path,
cli_fragments: Optional[List[str]],
) -> List[Path]:
"""Paths from config build.config_fragments plus CLI --fragment (order preserved, deduped)."""
build_cfg = cfg.get("build") or {}
frag_paths: List[Path] = []
for f in build_cfg.get("config_fragments") or []:
if isinstance(f, str) and f.strip():
frag_paths.append(resolve_path(root, f.strip()))
for c in cli_fragments or []:
if c:
frag_paths.append(Path(c).resolve())
seen: Set[Path] = set()
uniq: List[Path] = []
for p in frag_paths:
r = p.resolve()
if r not in seen:
seen.add(r)
uniq.append(r)
return uniq
def _prompt_rebuild_or_quit(
version: str,
pkg_out: Path,
debs: List[Path],
) -> str:
"""Return ``rebuild`` or ``quit`` when stored packages exist (depot install is disabled)."""
click.echo("")
click.echo(
click.style(
"Stored packages for this kernel version already exist in the package depot.",
fg="yellow",
bold=True,
)
)
click.echo(
"Only a fresh build can be installed; stored packages are not offered for installation."
)
click.echo(f" Version: {version}")
click.echo(f" Directory: {pkg_out / 'latest'}")
for p in debs:
click.echo(f" • {p.name}")
if not sys.stdin.isatty():
click.echo(
click.style(
"Non-interactive: rebuilding. Use --force-rebuild to skip this notice.",
fg="dim",
),
err=True,
)
return "rebuild"
c = click.prompt(
"Choice [r]ebuild / [q]uit",
default="r",
type=click.Choice(["r", "q"], case_sensitive=False),
)
return "quit" if c == "q" else "rebuild"
def _install_kernel_packages_phase(
moved: List[Path],
kernel_release: str,
skip_install: bool,
assume_yes_install: bool,
log: logging.Logger,
*,
build_log: Optional[Path] = None,
) -> None:
"""After a fresh build: success message and optional install prompt (latest build only)."""
if not moved:
return
if skip_install:
print_build_success_summary(len(moved), moved[0].parent, build_log)
click.echo("Packages:")
for p in moved:
click.echo(f" {p}")
click.echo("Skipping installation (--skip-install).")
return
print_build_success_summary(len(moved), moved[0].parent, build_log)
inst = Installer()
runtime_packages = inst.select_runtime_packages(moved)
if not runtime_packages:
raise click.ClickException(
"No installable kernel image/header packages were found in the build output."
)
install_yes = assume_yes_install or assume_yes_from_env()
if not inst.request_installation_approval(
runtime_packages,
assume_yes=install_yes,
default_confirm=True,
):
click.echo("Installation skipped.")
return
hint = kernel_release
try:
ok, ilog, (verified, issues) = inst.install_from_paths(
runtime_packages,
kernel_version_hint=hint,
create_backup_first=True,
)
click.echo(ilog[-2000:] if len(ilog) > 2000 else ilog)
if not ok:
click.echo("Installation reported errors; check logs.", err=True)
sys.exit(1)
if verified:
click.echo(click.style(f"Verified installation for {hint}.", fg="green"))
else:
click.echo(
click.style(
"Installation finished but verification reported issues: "
+ "; ".join(issues),
fg="yellow",
)
)
except GetKernelError as exc:
log_exception(log, exc, {})
raise
click.echo("Done. Reboot to boot the new kernel when ready.")
def _ensure_build_dependencies(cfg: Dict[str, Any], log: logging.Logger) -> None:
"""If enabled in config, run apt-get update and install all missing build packages."""
dep = cfg.get("dependencies") or {}
if not dep.get("auto_install", True):
click.echo(
click.style(
"Skipping automatic apt install (dependencies.auto_install is false).",
fg="yellow",
)
)
return
dm = DependencyManager()
include_opt = bool(dep.get("install_optional", False))
missing = dm.get_missing_packages(include_optional=include_opt)
if not missing:
click.echo(click.style("Build dependencies satisfied.", fg="green"))
return
click.echo("Missing packages: " + ", ".join(missing))
click.echo("Installing via apt (non-interactive) …")
try:
if dep.get("apt_update", True):
if not dm.update_package_cache():
click.echo("apt-get update failed; continuing.", err=True)
ok, failed = dm.install_all_dependencies(include_optional=include_opt)
except DependencyError as exc:
click.echo(
click.style(
"Cannot install packages without root. Run: sudo getkernel …",
fg="red",
),
err=True,
)
log_exception(log, exc, {})
raise
if not ok:
click.echo("Failed to install: " + ", ".join(failed), err=True)
log_exception(log, RuntimeError("apt install failed"), {"failed": failed})
raise DependencyError("Failed to install: " + ", ".join(failed))
click.echo(click.style("Dependencies installed.", fg="green"))
@click.group(invoke_without_command=True)
@click.option(
"--yes",
"-y",
"assume_yes",
is_flag=True,
help="Assume yes for package installation prompts (non-interactive).",
)
@click.pass_context
@click.version_option(APP_VERSION, prog_name="getkernel", message=_VERSION_MESSAGE)
def cli(ctx: click.Context, assume_yes: bool) -> None:
"""Build and install Linux kernel packages on Debian-based systems."""
ctx.ensure_object(dict)
ctx.obj["assume_yes"] = assume_yes
if ctx.invoked_subcommand is None:
ctx.invoke(interactive)
@cli.command("check")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON")
def cmd_check(as_json: bool) -> None:
"""Validate OS, disk, RAM, and toolchain."""
cfg = _load_config()
paths = _paths(cfg)
setup_logging(paths["logs"], **cfg.get("logging", {}))
sc = _make_system_checker(cfg, paths)
vr = sc.validate_environment()
payload = {
"valid": vr.is_valid,
"debian_based": sc.is_debian_based(),
"root_or_sudo": sc.check_root_privileges(),
"kernel": sc.get_current_kernel_version(),
"errors": vr.errors,
"warnings": vr.warnings,
"secure_boot": status_secure_boot(),
}
if as_json:
_emit_json(payload, exit_code=0 if vr.is_valid else 1)
print_table(
"System check",
[
{"field": "Debian-based", "value": str(sc.is_debian_based())},
{"field": "Root/sudo", "value": str(sc.check_root_privileges())},
{"field": "Kernel", "value": sc.get_current_kernel_version()},
],
["field", "value"],
)
for e in vr.errors:
click.echo(click.style(f"Error: {e}", fg="red"))
for w in vr.warnings:
click.echo(click.style(f"Warning: {w}", fg="yellow"))
sys.exit(0 if vr.is_valid else 1)
@cli.command("about")
def cmd_about() -> None:
"""Show developer name, contact, and project links."""
click.echo(f"GetKernel {APP_VERSION}")
click.echo(f"Name: {DEVELOPER_NAME}")
click.echo(f"Email: {DEVELOPER_EMAIL}")
click.echo(f"LinkedIn: {DEVELOPER_LINKEDIN_URL}")
click.echo(f"GitHub: {DEVELOPER_GITHUB_REPO_URL}")
@cli.command("list")
@click.option("--no-rc", is_flag=True, help="Hide release candidates")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON")
def cmd_list(no_rc: bool, as_json: bool) -> None:
"""List kernel versions from kernel.org."""
cfg = _load_config()
paths = _paths(cfg)
setup_logging(paths["logs"], **cfg.get("logging", {}))
fetcher = _make_fetcher(cfg, paths["cache"])
data = fetcher.fetch_kernel_versions(include_rc=not no_rc)
rows = []
for v in data.get("versions", [])[:40]:
rows.append(
{
"version": v.get("version", ""),
"type": v.get("type", ""),
"released": v.get("released", ""),
}
)
if as_json:
_emit_json({"stable": data.get("stable"), "mainline": data.get("mainline"), "versions": rows})
print_table("Kernel versions (kernel.org)", rows, ["version", "type", "released"])
@cli.command("deps")
@click.option("--install", is_flag=True, help="Install missing packages via apt")
def cmd_deps(install: bool) -> None:
"""Show or install build dependencies."""
cfg = _load_config()
paths = _paths(cfg)
log = setup_logging(paths["logs"], **cfg.get("logging", {}))
dm = DependencyManager(auto_install=install)
missing = dm.get_missing_packages()
if not missing:
click.echo("All required packages are installed.")
return
click.echo("Missing: " + ", ".join(missing))
if install:
if not dm.update_package_cache():
click.echo("apt-get update failed (continuing).", err=True)
ok, failed = dm.install_all_dependencies()
if not ok:
log_exception(log, RuntimeError("apt install failed"), {"failed": failed})
raise DependencyError("Failed to install: " + ", ".join(failed))
click.echo("Dependencies installed.")
else:
click.echo("Run with --install to apt-get install these packages.")
@cli.command("cleanup")
@click.option("--old-kernels", is_flag=True, help="Remove old kernel packages (keep running + 2 newest)")
@click.option("--build-artifacts", is_flag=True, help="Remove intermediate build files from data/builds")
@click.option("--keep", type=int, default=2, help="Number of old kernels to keep (default: 2)")
@click.option("--dry-run", is_flag=True, help="Show what would be removed without deleting")
def cmd_cleanup(old_kernels: bool, build_artifacts: bool, keep: int, dry_run: bool) -> None:
"""Remove old kernels and/or build artifacts."""
if keep < 0:
raise click.BadParameter("--keep must be >= 0")
if not old_kernels and not build_artifacts:
click.echo("Specify --old-kernels and/or --build-artifacts. See: getkernel cleanup --help")
return
cfg = _load_config()
paths = _paths(cfg)
if old_kernels:
inst = Installer()
try:
removed = inst.remove_old_kernels(keep_count=keep, dry_run=dry_run)
except ValueError as exc:
raise click.BadParameter(str(exc)) from exc
if removed:
for r in removed:
click.echo(f" {r}")
else:
click.echo("No old kernels to remove.")
if build_artifacts:
builds = paths["builds"]
if not builds.is_dir():
click.echo("No build directory found.")
return
for src_dir in sorted(builds.iterdir()):
if not src_dir.is_dir() or src_dir.name.startswith("."):
continue
pb = PackageBuilder(str(src_dir))
count = pb.cleanup_build_artifacts(keep_packages=True, dry_run=dry_run)
if dry_run:
click.echo(
f" {src_dir.name}: would remove {count} intermediate file(s) (dry-run)"
)
else:
click.echo(f" {src_dir.name}: removed {count} intermediate file(s)")
@cli.command("status")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON")
def cmd_status(as_json: bool) -> None:
"""Show running kernel, installed kernels, GRUB, depot, and last build log."""
cfg = _load_config()
paths = _paths(cfg)
setup_logging(paths["logs"], **cfg.get("logging", {}))
inst = Installer()
gm = GrubManager()
payload: Dict[str, Any] = {
"running_kernel": os.uname().release,
"installed_kernels": inst.list_installed_kernels(),
"grub_default": gm.get_default_entry(),
"grub_entries": gm.get_menu_entries()[:10],
"packages_latest": list_latest_packages(paths["packages"]),
"packages_archives": list_archived_builds(paths["packages"]),
"build_history": read_build_history(paths["packages"], limit=5),
"last_build_log": str(_latest_build_log(paths["logs"]) or ""),
"secure_boot": status_secure_boot(),
}
if as_json:
_emit_json(payload)
click.echo(f"Running kernel: {payload['running_kernel']}")
click.echo(f"GRUB default: {payload['grub_default'] or '(unknown)'}")
click.echo(f"Secure Boot: {payload['secure_boot']['note']}")
print_table("Installed kernels", payload["installed_kernels"][:10], ["version", "is_running"])
latest = payload["packages_latest"]
click.echo(f"Package depot (latest): {len(latest)} .deb file(s)")
if payload["last_build_log"]:
click.echo(f"Last build log: {payload['last_build_log']}")
@cli.command("install")
@click.pass_context
@click.option("--build-id", default=None, help="Install packages from archive/build-<id>/ instead of latest/")
@click.option("--kernel-version", default=None, help="Expected kernel release for post-install verification")
def cmd_install(ctx: click.Context, build_id: Optional[str], kernel_version: Optional[str]) -> None:
"""Install .deb packages from the package depot (latest or archived build)."""
if build_id is not None and not validate_build_id(build_id):
click.echo("Invalid --build-id (expected 12 lowercase hex characters).", err=True)
sys.exit(1)
cfg = _load_config()
paths = _paths(cfg)
log = setup_logging(paths["logs"], **cfg.get("logging", {}))
packages = resolve_package_paths(paths["packages"], build_id=build_id)
if not packages:
click.echo("No packages found in the depot.", err=True)
sys.exit(1)
hint = kernel_version
if not hint:
meta = read_build_info(paths["packages"], build_id=build_id)
recorded_release = meta.get("kernel_release", "")
if isinstance(recorded_release, str) and recorded_release:
hint = recorded_release
else:
rv = meta.get("requested_version", "")
lv = meta.get("localversion", "")
suffix = lv if isinstance(lv, str) else ""
if (
isinstance(rv, str)
and validate_kernel_version(rv)
and validate_localversion(suffix)
):
hint = canonical_kernel_release(rv, suffix)
if hint and not validate_kernel_release(hint):
click.echo(f"Invalid kernel release: {hint!r}", err=True)
sys.exit(1)
verifier = PackageBuilder(str(paths["builds"]), output_dir=str(paths["packages"]))
valid, package_errors = verifier.verify_packages(
packages,
expected_kernel_release=hint,
require_headers=bool(hint),
)
if not valid:
click.echo("Package verification failed: " + "; ".join(package_errors), err=True)
sys.exit(1)
inst = Installer()
runtime_packages = inst.select_runtime_packages(packages)
if not runtime_packages:
click.echo("No kernel image/header packages found in the selected build.", err=True)
sys.exit(1)
assume_yes = bool(ctx.obj.get("assume_yes")) or assume_yes_from_env()
for warning in collect_install_warnings(hint or ""):
click.echo(click.style(f"Warning: {warning}", fg="yellow"))
if not inst.request_installation_approval(runtime_packages, assume_yes=assume_yes):
click.echo("Installation cancelled.")
return
try:
ok, ilog, (verified, issues) = inst.install_from_paths(
runtime_packages,
kernel_version_hint=hint,
create_backup_first=True,
)
click.echo(ilog[-2000:] if len(ilog) > 2000 else ilog)
if not ok:
sys.exit(1)
if hint and verified:
click.echo(click.style(f"Verified installation for {hint}.", fg="green"))
elif hint:
click.echo(
click.style("Verification issues: " + "; ".join(issues), fg="yellow")
)
except GetKernelError as exc:
log_exception(log, exc, {})
raise
@cli.group("packages")
def cmd_packages_group() -> None:
"""Inspect built kernel packages in the depot."""
@cmd_packages_group.command("list")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON")
def cmd_packages_list(as_json: bool) -> None:
"""List packages under latest/ and archived builds."""
cfg = _load_config()
paths = _paths(cfg)
payload = {
"latest": list_latest_packages(paths["packages"]),
"archives": list_archived_builds(paths["packages"]),
"history": read_build_history(paths["packages"]),
}
if as_json:
_emit_json(payload)
print_table("Latest packages", payload["latest"], ["name", "size_bytes", "built_at"])
print_table("Archived builds", payload["archives"], ["build_id", "deb_count", "built_at"])
@cli.command("backups")
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON")
def cmd_backups(as_json: bool) -> None:
"""List boot file backups created before kernel installation."""
inst = Installer()
rows = inst.list_backups()
if as_json:
_emit_json({"backups": rows})
if not rows:
click.echo("No backups found.")
return
print_table("GetKernel backups", rows, ["id", "kernel_version", "date"])
@cli.command("rollback")
@click.argument("backup_id")
def cmd_rollback(backup_id: str) -> None:
"""Restore /boot files from a backup created by GetKernel."""
if not validate_backup_id(backup_id):
click.echo(
"Invalid backup id (expected format: backup-YYYYMMDD-HHMMSS).",
err=True,
)
sys.exit(1)
inst = Installer()
if not inst.rollback(backup_id):
click.echo(f"Rollback failed for backup {backup_id!r}.", err=True)
sys.exit(1)
click.echo(click.style(f"Restored backup {backup_id}. Run reboot when ready.", fg="green"))
@cli.command("uninstall")
@click.option("--yes", "-y", "assume_yes", is_flag=True, help="Skip confirmation")
def cmd_uninstall(assume_yes: bool) -> None:
"""Remove GetKernel from /usr/local/getkernel and related symlinks."""
paths, rc_files = detect_remnants()
if not paths and not rc_files:
click.echo("No GetKernel installation remnants detected.")
return
click.echo("Will remove:")
from utils.constants import GETKERNEL_INSTALL_DIR
if any(p.resolve() == GETKERNEL_INSTALL_DIR.resolve() for p in paths):
click.echo(
click.style(
" Warning: this deletes all runtime data under data/cache, "
"data/builds, data/logs, and data/packages.",
fg="yellow",
)
)
for p in paths:
click.echo(f" {p}")
for f in rc_files:
click.echo(f" PATH snippet in {f}")
if not assume_yes and not confirm("Proceed with uninstall?", default=False):
click.echo("Cancelled.")
return
try:
removed = uninstall_getkernel()
except PermissionError as exc:
click.echo(str(exc), err=True)
sys.exit(1)
click.echo(click.style("Removed:", fg="green"))
for item in removed:
click.echo(f" {item}")
def run_build_flow(
version: str,
source_dir: Optional[str],
skip_install: bool,
*,
dry_run: bool = False,
config_path: Optional[str] = None,
assume_yes_install: bool = False,
packages_output_dir: Optional[str] = None,
quiet_build: bool = False,
verbose_build: bool = False,
config_fragments: Optional[List[str]] = None,
use_llvm: bool = False,
localmodconfig: bool = False,
force_rebuild: bool = False,
menuconfig: bool = False,
resume_build: bool = False,
profile: Optional[str] = None,
) -> None:
"""Download, configure, compile, package, and optionally install a kernel."""
cfg = _load_config()
paths = _paths(cfg)
log = setup_logging(paths["logs"], **cfg.get("logging", {}))
# Validate kernel version to prevent path traversal or malformed URLs
if not validate_kernel_version(version):
click.echo(
click.style(
f"Invalid kernel version format: {version!r}. "
"Expected something like 6.12.8 or 6.13-rc1.",
fg="red",
),
err=True,
)
sys.exit(1)
kv_value = cfg.get("kernel") or {}
kv = kv_value if isinstance(kv_value, dict) else {}
configured_localver = kv.get("localversion", "")
localver = "" if configured_localver is None else str(configured_localver).strip()
if not validate_localversion(localver):
raise click.UsageError(
"kernel.localversion must be empty or a path-safe suffix such as '-custom'."
)
build_cfg = cfg.get("build") or {}
pkg_target = str(build_cfg.get("target", "bindeb-pkg"))
root = project_root()
pkg_out = (
resolve_path(root, packages_output_dir)
if packages_output_dir
else paths["packages"]
)
sc = _make_system_checker(cfg, paths)
vr = sc.validate_environment()
dependencies_checked = False
repairable_errors = [
error
for error in vr.errors
if error.startswith("Required command not found in PATH: ")
and not error.endswith(("dpkg", "apt-get"))
]
blocking_errors = [error for error in vr.errors if error not in repairable_errors]
dependency_cfg = cfg.get("dependencies") or {}
if (
repairable_errors
and not blocking_errors
and dependency_cfg.get("auto_install", True)
):
click.echo("Build tools are missing; attempting configured dependency installation.")
_ensure_build_dependencies(cfg, log)
dependencies_checked = True
vr = sc.validate_environment()
if not vr.is_valid:
for e in vr.errors:
print_error_block("Environment check failed", e, vr.recommendations)
sys.exit(1)
build_warnings = collect_build_warnings(version)
if not bool(kv.get("verify_checksum", True)):
build_warnings.insert(
0,
"SHA256 source verification is disabled; authenticity relies on HTTPS "
"unless PGP verification is enabled.",
)
for warning in build_warnings:
click.echo(click.style(f"Warning: {warning}", fg="yellow"))
if (
build_warnings
and sys.stdin.isatty()
and not assume_yes_install
and not assume_yes_from_env()
and not confirm("Continue despite these warnings?", default=True)
):
click.echo("Cancelled.")
return
has_frags = bool(config_fragments) or bool(build_cfg.get("config_fragments")) or bool(profile)
reuse_allowed = (
not dry_run
and not force_rebuild
and not source_dir
and not config_path
and not has_frags
and not (bool(build_cfg.get("use_llvm")) or use_llvm)
and not (bool(build_cfg.get("localmodconfig")) or localmodconfig)
and not menuconfig
and not resume_build
and not profile
)
if reuse_allowed:
existing = find_matching_stored_packages(pkg_out, version, localver)
if existing:
action = _prompt_rebuild_or_quit(version, pkg_out, existing)
if action == "quit":
return
if not dependencies_checked:
_ensure_build_dependencies(cfg, log)
if source_dir:
src = Path(source_dir).resolve()
if not all(
(
(src / "Makefile").is_file(),
(src / "Kconfig").is_file(),
(src / "scripts" / "kconfig").is_dir(),
)
):
click.echo(
"Invalid kernel source (expected Makefile, Kconfig, and scripts/kconfig).",
err=True,
)
sys.exit(1)
else:
fetcher = _make_fetcher(cfg, paths["cache"])
reuse = bool(kv.get("reuse_downloads", True))
click.echo(f"Preparing kernel source linux-{version} …")
try:
extracted, prep_status = fetcher.download_kernel_source(
version,
target_dir=str(paths["builds"]),
reuse_existing=reuse,
verify_signature=bool(kv.get("verify_signature", False)),
)
except GetKernelError as exc:
log_exception(log, exc, {})
raise
if prep_status == "reuse_tree":
click.echo(click.style("Reusing existing source tree (skip download).", fg="green"))
elif prep_status == "reuse_tarball":
click.echo(click.style("Reusing cached tarball (skip download).", fg="green"))
elif prep_status == "resume":
click.echo(click.style("Resuming interrupted download …", fg="green"))
src = Path(extracted)
use_llvm_build = bool(build_cfg.get("use_llvm", False)) or use_llvm
use_lmc_build = bool(build_cfg.get("localmodconfig", False)) or localmodconfig
cm = ConfigManager(str(src))
try:
if config_path:
cf = Path(config_path).resolve()
if not cf.is_file():
raise ConfigError(f"Kernel config file not found: {cf}")
click.echo(f"Using kernel config from {cf} …")
base = cf.read_text(encoding="utf-8", errors="replace")
cm.create_new_config(base)
else:
click.echo("Applying running kernel configuration …")
base = cm.get_current_config()
cm.create_new_config(base)
frag_paths = _collect_config_fragments(cfg, root, config_fragments)
if profile:
frag_paths.append(_resolve_profile_path(cfg, profile))
if frag_paths:
click.echo(f"Merging {len(frag_paths)} config fragment(s) …")
cm.merge_config_fragments(frag_paths)
if menuconfig:
click.echo("Launching make menuconfig …")
cm.run_menuconfig()
if use_lmc_build:
click.echo("Running make localmodconfig …")
cm.run_localmodconfig()
cleared_keys = cm.prepare_external_module_config(localver)
if cleared_keys:
click.echo(
click.style(
"Cleared unavailable distribution certificate paths: "
+ ", ".join(cleared_keys),
fg="yellow",
)
)
config_ok, config_errors = cm.validate_config()
if not config_ok:
raise ConfigError("Kernel config is not module-compatible: " + "; ".join(config_errors))
except GetKernelError as exc:
log_exception(log, exc, {})
raise
comp = Compiler(str(src))
if bool(build_cfg.get("use_ccache", True)) and not use_llvm_build:
comp.enable_ccache()
last_build_log: Optional[Path] = None
try:
if resume_build and comp.has_partial_build():
click.echo(click.style("Resuming previous partial build …", fg="green"))
comp.prepare_source(resume=True, local_version=localver)
else:
if not dry_run and comp.has_partial_build():
click.echo("Cleaning previous partial build artifacts …")
if not comp.clean_build("normal"):
raise CompilationError("make clean failed before the fresh build")
comp.prepare_source(local_version=localver)
kernel_release = comp.get_kernel_release(localver)
expected_release = canonical_kernel_release(version, localver)
if not source_dir and kernel_release != expected_release:
raise CompilationError(
"Unexpected kernel release: "
f"Kbuild reported {kernel_release!r}, expected {expected_release!r}. "
"Refusing to create packages under an unrequested module path."
)
click.echo(f"Kernel release: {kernel_release}")
if dry_run:
click.echo(
click.style(
"Dry run: source prepared and .config applied; skipping compile.",
fg="green",
)
)
click.echo(f"Kernel tree: {src}")
click.echo(f"Packages output (when built): {pkg_out}")
return
make_t, _ = comp.resolve_make_package_target(pkg_target)
build_id = generate_build_id()
build_log = paths["logs"] / f"build-{build_id}.log"
last_build_log = build_log
log_build_event(
log,
"build_start",
build_id,
{
"version": version,
"kernel_release": kernel_release,
"target": make_t,
"log": str(build_log),
"llvm": use_llvm_build,
},
)
if use_llvm_build:
click.echo("Building with LLVM=1 (clang); ensure clang/llvm are installed.", err=True)
compile_kwargs = {
"target": pkg_target,
"jobs": build_cfg.get("jobs"),
"local_version": localver,
"log_path": build_log,
"build_id": build_id,
"use_llvm": use_llvm_build,
}
if verbose_build:
click.echo(f"Starting build (make {make_t}); full log → {build_log}")
comp.compile_kernel(**compile_kwargs, verbose=True)
elif quiet_build:
click.echo(f"Building (make {make_t}); log → {build_log}")
comp.compile_kernel(**compile_kwargs, verbose=False)
else:
with build_progress_display(build_log, make_t) as on_progress:
comp.compile_kernel(
**compile_kwargs,
verbose=False,
progress_callback=on_progress,
)
log_build_event(
log,
"build_done",
build_id,
{
"seconds": comp.estimated_duration,
"log": str(build_log),
},
)
except GetKernelError as exc:
log_exception(
log,
exc,
{
"build_id": getattr(comp, "build_id", None),
"log": str(getattr(comp, "last_build_log_path", "") or ""),
},
)
raise
pb = PackageBuilder(str(src), output_dir=str(pkg_out))
debs = pb.find_built_packages(
expected_kernel_release=kernel_release,