-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzuzzler.py
More file actions
2570 lines (2144 loc) · 82.3 KB
/
zuzzler.py
File metadata and controls
2570 lines (2144 loc) · 82.3 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
import base64
import io
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import traceback
from urllib.parse import quote
from urllib.parse import urlparse
import requests
import yaml
try:
import questionary
except ImportError:
questionary = None
try:
from prompt_toolkit.application import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout import HSplit, Layout
from prompt_toolkit.layout.containers import Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.widgets import TextArea
except ImportError:
Application = None
FormattedTextControl = None
HSplit = None
KeyBindings = None
Layout = None
TextArea = None
Window = None
API_ROOT = "https://api.github.com"
PACKAGE_TYPES = ["container", "docker", "npm", "maven", "rubygems", "nuget"]
APP_NAME = "Zuzzler"
RELEASES_API_URL = "https://api.github.com/repos/deexno/zuzzler/releases/latest"
VERSION_FILE_NAME = ".zuzzler-version.json"
SHORTCUT_LIMIT = 36
VERSION_PAGE_SIZE = 20
COMPOSE_FILENAMES = [
"docker-compose.yml",
"docker-compose.yaml",
"compose.yml",
"compose.yaml",
]
DOCKER_REGISTRY = "ghcr.io"
GENERATED_PROJECTS_DIR = "generated-projects"
SOURCE_EXPORT_DIR = ".zuzzler-generated"
BACK = "__back__"
NEXT = "__next__"
PREVIOUS = "__prev__"
def clear_console():
# Prefer native terminal commands and fall back to ANSI escape sequences
# so the script behaves consistently on Windows and Unix-like systems.
command = "cls" if os.name == "nt" else "clear"
try:
subprocess.run(command, check=False, shell=True)
except OSError:
print("\033[2J\033[H", end="")
def render_screen(title, details=None):
clear_console()
print(title)
print("=" * len(title))
if details:
for detail in details:
print(detail)
print()
def log_file_path():
return app_install_root() / "zuzzler.log"
def log_event(message):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
log_file_path().parent.mkdir(parents=True, exist_ok=True)
with open(log_file_path(), "a", encoding="utf-8") as handle:
handle.write(f"[{timestamp}] {message}\n")
def log_exception(context, exc):
log_event(f"{context}: {exc}")
log_event(traceback.format_exc().rstrip())
def run_command(args, input_text=None, check=True, cwd=None):
return subprocess.run(
args,
input=input_text,
text=True,
capture_output=True,
check=check,
cwd=cwd,
)
def parse_version_tag(version_text):
cleaned = version_text.strip().lower()
if cleaned.startswith("v"):
cleaned = cleaned[1:]
parts = []
for token in cleaned.split("."):
digits = "".join(character for character in token if character.isdigit())
parts.append(int(digits) if digits else 0)
while len(parts) < 3:
parts.append(0)
return tuple(parts)
def app_install_root():
return Path(__file__).resolve().parent
def version_file_path():
return app_install_root() / VERSION_FILE_NAME
def write_installed_version(version_text):
version_file_path().write_text(
json.dumps({"version": version_text}, indent=2),
encoding="utf-8",
)
def read_installed_version():
path = version_file_path()
if not path.exists():
return None
payload = json.loads(path.read_text(encoding="utf-8"))
version_text = str(payload.get("version", "")).strip()
return version_text or None
def latest_release_info():
response = requests.get(
RELEASES_API_URL,
headers={"Accept": "application/vnd.github+json"},
timeout=30,
)
response.raise_for_status()
payload = response.json()
return {
"tag_name": payload["tag_name"],
"tarball_url": payload["tarball_url"],
"html_url": payload["html_url"],
}
def prompt_current_version(suggested_version):
if questionary is not None:
version_text = questionary.text(
"Installed version:",
default=suggested_version,
qmark=">",
).ask()
return (version_text or "").strip()
return input(f"Installed version [{suggested_version}]: ").strip() or suggested_version
def determine_current_version(latest_release=None):
stored_version = read_installed_version()
if stored_version:
return stored_version
suggested_version = latest_release["tag_name"] if latest_release else "v0.0.0"
render_screen(
"Version Information Missing",
[
f"{VERSION_FILE_NAME} was not found in the installation directory.",
"Please enter the version currently installed on this machine.",
f"Suggested version: {suggested_version}",
],
)
selected_version = prompt_current_version(suggested_version)
if not selected_version:
selected_version = suggested_version
write_installed_version(selected_version)
return selected_version
def remove_installed_app_files(install_root):
for child in install_root.iterdir():
if child.name in {".venv", "__pycache__"}:
continue
if child.is_dir():
shutil.rmtree(child)
else:
child.unlink()
def extract_release_tarball(tarball_bytes, install_root):
with tarfile.open(fileobj=io.BytesIO(tarball_bytes), mode="r:gz") as archive:
members = archive.getmembers()
if not members:
raise RuntimeError("Release archive is empty.")
top_level = members[0].name.split("/", 1)[0]
for member in members:
relative_name = member.name[len(top_level):].lstrip("/")
if not relative_name:
continue
target_path = install_root / relative_name
if member.isdir():
target_path.mkdir(parents=True, exist_ok=True)
continue
target_path.parent.mkdir(parents=True, exist_ok=True)
extracted = archive.extractfile(member)
if extracted is None:
continue
with extracted, open(target_path, "wb") as destination:
shutil.copyfileobj(extracted, destination)
def reinstall_python_dependencies(install_root):
venv_root = install_root / ".venv"
if os.name == "nt":
python_bin = venv_root / "Scripts" / "python.exe"
else:
python_bin = venv_root / "bin" / "python"
if not python_bin.exists():
raise RuntimeError("Virtual environment not found for self-update.")
run_command([str(python_bin), "-m", "pip", "install", "--upgrade", "pip"], check=True)
run_command(
[str(python_bin), "-m", "pip", "install", "-r", str(install_root / "requirements.txt")],
check=True,
)
def self_update_and_restart(release):
install_root = app_install_root()
response = requests.get(release["tarball_url"], timeout=60)
response.raise_for_status()
tarball_bytes = response.content
backup_dir = install_root.parent / f"{install_root.name}.backup"
if backup_dir.exists():
shutil.rmtree(backup_dir)
shutil.copytree(install_root, backup_dir, dirs_exist_ok=True)
try:
remove_installed_app_files(install_root)
extract_release_tarball(tarball_bytes, install_root)
write_installed_version(release["tag_name"])
reinstall_python_dependencies(install_root)
except Exception:
remove_installed_app_files(install_root)
shutil.copytree(backup_dir, install_root, dirs_exist_ok=True)
raise
finally:
if backup_dir.exists():
shutil.rmtree(backup_dir)
os.execv(sys.executable, [sys.executable, str(Path(__file__).resolve()), *sys.argv[1:]])
def github_get(session, url, params=None):
response = session.get(url, params=params, timeout=30)
response.raise_for_status()
return response
def paginate(session, url, params=None):
page = 1
while True:
merged_params = {"per_page": 100, "page": page}
if params:
merged_params.update(params)
response = github_get(session, url, params=merged_params)
data = response.json()
if not data:
break
yield from data
page += 1
def list_user_orgs(session):
return [org["login"] for org in paginate(session, f"{API_ROOT}/user/orgs")]
def list_packages_for_namespace(session, scope_name, api_url):
# GitHub packages are queried per package type, so we aggregate them here
# into a single scope-local list.
packages = []
errors = []
for package_type in PACKAGE_TYPES:
try:
entries = list(
paginate(session, api_url, params={"package_type": package_type})
)
for entry in entries:
entry["_scope"] = scope_name
packages.append(entry)
except requests.HTTPError as exc:
status = exc.response.status_code if exc.response is not None else "unknown"
errors.append((package_type, status))
return packages, errors
def list_package_versions(session, scope, package):
package_type = package["package_type"]
package_name = quote(package["name"], safe="")
if scope["kind"] == "user":
api_url = f"{API_ROOT}/user/packages/{package_type}/{package_name}/versions"
else:
api_url = f"{API_ROOT}/orgs/{scope['label']}/packages/{package_type}/{package_name}/versions"
return list(paginate(session, api_url))
def repo_contents_exists(session, owner, repo, path):
api_url = f"{API_ROOT}/repos/{owner}/{repo}/contents/{quote(path, safe='/')}"
response = session.get(api_url, timeout=30)
if response.status_code == 404:
return False
response.raise_for_status()
return True
def get_repo_file_content(session, owner, repo, path):
api_url = f"{API_ROOT}/repos/{owner}/{repo}/contents/{quote(path, safe='/')}"
response = session.get(api_url, timeout=30)
response.raise_for_status()
payload = response.json()
if payload.get("encoding") != "base64" or "content" not in payload:
raise RuntimeError(f"Could not decode repository file '{path}'.")
return base64.b64decode(payload["content"]).decode("utf-8")
def unique_packages(packages):
unique = {}
for package in packages:
# The same package can appear in repeated fetches across retries or
# package-type sweeps, so de-duplicate on stable display fields.
key = (
package.get("_scope", ""),
package.get("package_type", ""),
package.get("name", ""),
package.get("html_url", ""),
)
unique[key] = package
return list(unique.values())
def ensure_questionary():
if questionary is None:
print("The 'questionary' package is not installed.")
print("Install it with: pip install questionary")
return False
return True
def prompt_github_token():
if questionary is not None:
token = questionary.password(
"API key:",
qmark=">",
).ask()
return (token or "").strip()
import getpass
return getpass.getpass("API key: ").strip()
def extract_source_repo_url(package, version):
metadata = version.get("metadata") or {}
container = metadata.get("container") or {}
labels = container.get("labels") or {}
if isinstance(labels, dict):
source_url = labels.get("org.opencontainers.image.source")
if source_url:
return source_url
repository = package.get("repository") or {}
if isinstance(repository, dict):
html_url = repository.get("html_url")
if html_url:
return html_url
repository_url = repository.get("url")
if repository_url:
return repository_url
package_url = package.get("html_url") or ""
if "/packages/" in package_url:
return package_url.split("/packages/")[0]
return None
def parse_github_repo_url(source_url):
if not source_url:
return None
parsed = urlparse(source_url)
if parsed.netloc not in {"github.com", "www.github.com"}:
return None
parts = [part for part in parsed.path.strip("/").split("/") if part]
if len(parts) < 2:
return None
owner = parts[0]
repo = parts[1]
if repo.endswith(".git"):
repo = repo[:-4]
return owner, repo
def find_compose_file(session, owner, repo):
# Keep the initial check cheap and predictable by probing the canonical
# compose filenames in the repository root.
for filename in COMPOSE_FILENAMES:
try:
if repo_contents_exists(session, owner, repo, filename):
return filename
except requests.HTTPError:
return None
return None
def docker_available():
try:
run_command(["docker", "version"], check=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return False
return True
def docker_compose_command():
candidates = [
["docker", "compose"],
["docker-compose"],
]
for command in candidates:
try:
result = run_command(command + ["version"], check=False)
except FileNotFoundError:
continue
if result.returncode == 0:
return command
return None
def list_docker_containers(all_containers=False):
format_string = "{{.Names}}\t{{.Image}}\t{{.Status}}"
command = ["docker", "ps", "--format", format_string]
if all_containers:
command.insert(2, "-a")
try:
result = run_command(command, check=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return []
containers = []
for line in result.stdout.splitlines():
parts = line.split("\t")
if len(parts) != 3:
continue
containers.append({"name": parts[0], "image": parts[1], "status": parts[2]})
return containers
def docker_login(registry, username, token):
result = run_command(
["docker", "login", registry, "-u", username, "--password-stdin"],
input_text=f"{token}\n",
check=False,
)
if result.returncode != 0:
stderr = result.stderr.strip() or result.stdout.strip() or "docker login failed"
raise RuntimeError(stderr)
def docker_pull(image_reference):
result = run_command(["docker", "pull", image_reference], check=False)
if result.returncode != 0:
stderr = result.stderr.strip() or result.stdout.strip() or "docker pull failed"
raise RuntimeError(stderr)
def docker_run(image_reference, container_name):
result = run_command(
["docker", "run", "-d", "--name", container_name, image_reference],
check=False,
)
if result.returncode != 0:
stderr = result.stderr.strip() or result.stdout.strip() or "docker run failed"
raise RuntimeError(stderr)
return result.stdout.strip()
def docker_inspect_container(container_name):
result = run_command(["docker", "inspect", container_name], check=False)
if result.returncode != 0:
stderr = (
result.stderr.strip() or result.stdout.strip() or "docker inspect failed"
)
raise RuntimeError(stderr)
return result.stdout
def docker_logs(container_name, tail=20):
result = run_command(
["docker", "logs", "--tail", str(tail), container_name],
check=False,
)
if result.returncode != 0:
stderr = result.stderr.strip() or result.stdout.strip() or "docker logs failed"
raise RuntimeError(stderr)
# Docker writes logs to stderr for some drivers, so combine both streams.
combined = []
if result.stdout.strip():
combined.append(result.stdout.strip())
if result.stderr.strip():
combined.append(result.stderr.strip())
return "\n".join(combined).strip()
def docker_compose_ps(compose_command, compose_file_path):
result = run_command(
compose_command + ["-f", compose_file_path, "ps"],
check=False,
cwd=str(Path(compose_file_path).parent),
)
if result.returncode != 0:
stderr = (
result.stderr.strip() or result.stdout.strip() or "docker compose ps failed"
)
raise RuntimeError(stderr)
return result.stdout.strip()
def docker_compose_logs(compose_command, compose_file_path, tail=20):
result = run_command(
compose_command + ["-f", compose_file_path, "logs", "--tail", str(tail)],
check=False,
cwd=str(Path(compose_file_path).parent),
)
if result.returncode != 0:
stderr = (
result.stderr.strip()
or result.stdout.strip()
or "docker compose logs failed"
)
raise RuntimeError(stderr)
combined = []
if result.stdout.strip():
combined.append(result.stdout.strip())
if result.stderr.strip():
combined.append(result.stderr.strip())
return "\n".join(combined).strip()
def docker_compose_up(compose_command, compose_file_path, project_dir):
result = run_command(
compose_command + ["-f", compose_file_path, "up", "-d"],
check=False,
cwd=project_dir,
)
if result.returncode != 0:
stderr = (
result.stderr.strip() or result.stdout.strip() or "docker compose up failed"
)
raise RuntimeError(stderr)
return result.stdout.strip() or result.stderr.strip()
def docker_stop(container_name):
result = run_command(["docker", "stop", container_name], check=False)
if result.returncode not in {0, 1}:
stderr = result.stderr.strip() or result.stdout.strip() or "docker stop failed"
raise RuntimeError(stderr)
def docker_remove(container_name):
result = run_command(["docker", "rm", container_name], check=False)
if result.returncode != 0:
stderr = result.stderr.strip() or result.stdout.strip() or "docker rm failed"
raise RuntimeError(stderr)
def normalize_image_component(value):
normalized = value.strip().lower().replace(" ", "-")
normalized = re.sub(r"[^a-z0-9._/-]+", "-", normalized)
normalized = re.sub(r"/{2,}", "/", normalized)
normalized = re.sub(r"-{2,}", "-", normalized)
normalized = normalized.strip("/.-")
return normalized
def normalize_container_name(value):
normalized = value.strip().lower().replace("_", "-").replace(" ", "-")
normalized = re.sub(r"[^a-z0-9.-]+", "-", normalized)
normalized = re.sub(r"-{2,}", "-", normalized)
normalized = normalized.strip(".-")
return normalized
def container_image_reference(scope, package, version):
metadata = version.get("metadata") or {}
container = metadata.get("container") or {}
tags = container.get("tags") or []
if not tags:
return None
package_name = normalize_image_component(package["name"].lstrip("/"))
namespace = normalize_image_component(scope["label"])
if not package_name or not namespace:
return None
return f"{DOCKER_REGISTRY}/{namespace}/{package_name}:{tags[0]}"
def split_image_reference(image_reference):
digest_split = image_reference.split("@", 1)
without_digest = digest_split[0]
last_slash = without_digest.rfind("/")
last_colon = without_digest.rfind(":")
if last_colon > last_slash:
return without_digest[:last_colon], without_digest[last_colon + 1 :]
return without_digest, None
def normalized_repo_reference(image_reference):
repository, _ = split_image_reference(image_reference)
return normalize_image_component(repository)
def likely_service_match(service_name, service_definition, package, source_repo):
package_leaf = normalize_container_name(package["name"].strip("/").split("/")[-1])
repo_name = (
normalize_container_name(source_repo[1]) if source_repo else package_leaf
)
normalized_service_name = normalize_container_name(service_name)
container_name = normalize_container_name(
str((service_definition or {}).get("container_name", ""))
)
candidates = {value for value in [package_leaf, repo_name] if value}
if normalized_service_name in candidates:
return True
for candidate in candidates:
if candidate and candidate in container_name:
return True
return False
def auto_patch_compose_images(compose_content, image_reference, package, source_repo):
try:
compose_data = yaml.safe_load(compose_content) or {}
except yaml.YAMLError:
return compose_content, []
if not isinstance(compose_data, dict):
return compose_content, []
services = compose_data.get("services")
if not isinstance(services, dict):
return compose_content, []
target_repo = normalized_repo_reference(image_reference)
updated_services = []
for service_name, service_definition in services.items():
if not isinstance(service_definition, dict):
continue
current_image = service_definition.get("image")
if isinstance(current_image, str) and current_image.strip():
current_repo = normalized_repo_reference(current_image.strip())
# Only rewrite services that already point to the same repository but
# with an outdated tag or missing digest/tag details.
if current_repo == target_repo and current_image.strip() != image_reference:
service_definition["image"] = image_reference
updated_services.append(service_name)
continue
# Only fill in a missing image when the service strongly looks like the
# selected package, to avoid mutating unrelated services in multi-service stacks.
if likely_service_match(service_name, service_definition, package, source_repo):
service_definition["image"] = image_reference
updated_services.append(service_name)
if not updated_services:
return compose_content, []
normalized_content = yaml.safe_dump(
compose_data,
sort_keys=False,
default_flow_style=False,
)
return normalized_content, updated_services
def default_container_name(package, source_repo):
if source_repo:
return normalize_container_name(source_repo[1])
package_name = package["name"].strip("/").split("/")[-1]
return normalize_container_name(package_name)
def running_container_lines(containers):
if not containers:
return ["Running containers: none"]
lines = ["Running containers:"]
for container in containers[:8]:
lines.append(
f"- {container['name']} [{container['image']}] {container['status']}"
)
if len(containers) > 8:
lines.append(f"- +{len(containers) - 8} more")
return lines
def prompt_target_container(existing_containers, running_containers, suggested_name):
if not ensure_questionary():
return None
details = running_container_lines(running_containers)
render_screen(
"Choose Container Name",
details + [f"Suggested new container name: {suggested_name}"],
)
existing_by_name = {
container["name"]: container for container in existing_containers
}
choices = [
questionary.Choice(
title=f"Create new container ({suggested_name})",
value={"mode": "new"},
)
]
choices.extend(
questionary.Choice(
title=f"{container['name']} [{container['image']}] {container['status']}",
value={"mode": "existing", "container": container},
)
for container in sorted(
existing_containers, key=lambda item: item["name"].lower()
)
)
choices.append(questionary.Choice(title="Back", value={"mode": "back"}))
selection = questionary.select(
"Select a target container or create a new one.",
choices=choices,
use_shortcuts=len(choices) <= SHORTCUT_LIMIT,
use_arrow_keys=True,
qmark=">",
pointer=">>",
).ask()
if selection is None:
return None
if selection["mode"] == "back":
return BACK
if selection["mode"] == "existing":
return selection["container"]["name"]
while True:
render_screen(
"Enter Container Name",
details + [f"Suggested name: {suggested_name}"],
)
container_name = questionary.text(
"Container name:",
default=suggested_name,
qmark=">",
).ask()
if container_name is None:
return BACK
container_name = normalize_container_name(container_name)
if not container_name:
continue
return container_name
def prompt_update_existing(container_name):
if not ensure_questionary():
return None
choices = [
questionary.Choice(
title=f"Update existing container ({container_name})", value=True
),
questionary.Choice(title="Do not update", value=False),
questionary.Choice(title="Back", value=BACK),
]
return questionary.select(
f"A container named '{container_name}' already exists. What do you want to do?",
choices=choices,
use_shortcuts=True,
use_arrow_keys=True,
qmark=">",
pointer=">>",
).ask()
def install_direct_container(
github_token,
github_username,
scope,
package,
version,
source_repo,
):
image_reference = container_image_reference(scope, package, version)
if not image_reference:
render_screen(
"Direct Installation Unavailable",
["The selected package version does not expose a usable container tag."],
)
return BACK
if not docker_available():
render_screen(
"Docker Not Available",
["Docker CLI is not installed or not available in PATH."],
)
return BACK
while True:
running_containers = list_docker_containers(all_containers=False)
existing_containers = list_docker_containers(all_containers=True)
suggested_name = default_container_name(package, source_repo)
target_container_name = prompt_target_container(
existing_containers,
running_containers,
suggested_name,
)
if target_container_name is None or target_container_name == BACK:
return BACK
existing_names = {container["name"] for container in existing_containers}
should_update = target_container_name in existing_names
if should_update:
render_screen(
"Existing Container Detected",
running_container_lines(running_containers)
+ [
f"Selected container: {target_container_name}",
f"New image: {image_reference}",
],
)
should_update = prompt_update_existing(target_container_name)
if should_update is None or should_update == BACK:
continue
if not should_update:
render_screen(
"No Changes Applied",
[
f"Skipped update for existing container '{target_container_name}'."
],
)
if prompt_retry("Do you want to choose another target container?"):
continue
return BACK
render_screen(
"Installing Container",
[
f"Container: {target_container_name}",
f"Image: {image_reference}",
"Authenticating with GHCR and pulling the image.",
],
)
try:
docker_login(DOCKER_REGISTRY, github_username, github_token)
docker_pull(image_reference)
if should_update:
update_result = update_existing_container(
target_container_name, image_reference
)
render_screen(
"Container Updated",
[
f"Container: {target_container_name}",
f"Image: {image_reference}",
f"Container ID: {update_result['container_id']}",
f"Recreated from: {update_result['recreated_command']}",
],
)
watch_container_status(target_container_name)
else:
container_id = docker_run(image_reference, target_container_name)
render_screen(
"Container Installed",
[
f"Container: {target_container_name}",
f"Image: {image_reference}",
f"Container ID: {container_id}",
],
)
watch_container_status(target_container_name)
return "done"
except RuntimeError as exc:
render_screen(
"Docker Operation Failed",
[
f"Container: {target_container_name}",
f"Image: {image_reference}",
str(exc),
],
)
if not prompt_retry("The Docker operation failed. What do you want to do?"):
return BACK
def shell_join(parts):
return " ".join(shlex.quote(part) for part in parts)
def format_timestamp(value):
if not value:
return "unknown"
return value.replace("T", " ").replace("Z", " UTC")
def container_status_lines(container_name):
inspect_raw = docker_inspect_container(container_name)
inspect_payload = json.loads(inspect_raw)
container = inspect_payload[0]
state = container.get("State") or {}
config = container.get("Config") or {}
lines = [
f"Container: {container_name}",
f"Image: {config.get('Image', 'unknown')}",
f"Status: {state.get('Status', 'unknown')}",
f"Running: {state.get('Running', False)}",
f"Started at: {format_timestamp(state.get('StartedAt'))}",
f"Finished at: {format_timestamp(state.get('FinishedAt'))}",
f"Restarting: {state.get('Restarting', False)}",
f"Exit code: {state.get('ExitCode', 'unknown')}",
]
health = state.get("Health") or {}
if health:
lines.append(f"Health: {health.get('Status', 'unknown')}")
return lines