-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrosspad_app_manager.py
More file actions
2095 lines (1821 loc) · 74.6 KB
/
crosspad_app_manager.py
File metadata and controls
2095 lines (1821 loc) · 74.6 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
# SPDX-License-Identifier: MIT
"""CrossPad App Package Manager — shared core.
Platform-agnostic app management logic. Each platform repo provides
a thin wrapper that configures platform-specific settings.
Usage:
from crosspad_app_manager import AppManager, PlatformConfig
config = PlatformConfig(
platform="esp-idf",
lib_dir="components",
official_org="CrossPad",
)
mgr = AppManager("/path/to/project", config)
mgr.list_apps()
"""
import json
import os
import subprocess
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
REMOTE_REGISTRY_REPO = "CrossPad/crosspad-apps"
REMOTE_REGISTRY_PATH = "registry.json"
LOCAL_REGISTRY_FILE = "app-registry.json"
MANIFEST_FILE = "apps.json"
CACHE_MAX_AGE_SECONDS = 3600 # 1 hour
@dataclass
class PlatformConfig:
platform: str # "esp-idf", "arduino", "pc"
lib_dir: str = "components" # where submodules go ("components" or "lib")
official_org: str = "CrossPad"
lib_prefix: str = "crosspad-" # prefix for component dirs
class AppManager:
def __init__(self, project_dir: str, config: PlatformConfig):
self.project_dir = Path(project_dir)
self.config = config
self.local_registry_path = self.project_dir / LOCAL_REGISTRY_FILE
self.manifest_path = self.project_dir / MANIFEST_FILE
# -- registry loading -----------------------------------------------------
def _fetch_remote_registry(self) -> dict | None:
try:
result = subprocess.run(
["gh", "api",
f"repos/{REMOTE_REGISTRY_REPO}/contents/{REMOTE_REGISTRY_PATH}",
"--jq", ".content"],
capture_output=True, text=True, check=True, timeout=15,
)
import base64
content = base64.b64decode(result.stdout.strip()).decode()
data = json.loads(content)
with open(self.local_registry_path, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
return data
except (subprocess.CalledProcessError, FileNotFoundError,
subprocess.TimeoutExpired) as e:
print(f" Warning: Could not fetch remote registry via gh: {e}")
return None
def _is_cache_fresh(self) -> bool:
if not self.local_registry_path.exists():
return False
age = datetime.now().timestamp() - self.local_registry_path.stat().st_mtime
return age < CACHE_MAX_AGE_SECONDS
def _load_registry(self) -> dict:
if not self._is_cache_fresh():
remote = self._fetch_remote_registry()
if remote:
return remote
if self.local_registry_path.exists():
with open(self.local_registry_path) as f:
return json.load(f)
print("Error: No registry available (remote unreachable, no local cache).")
print(f" Check your network or create {LOCAL_REGISTRY_FILE} manually.")
sys.exit(1)
# -- manifest -------------------------------------------------------------
def _load_manifest(self) -> dict:
if self.manifest_path.exists():
with open(self.manifest_path) as f:
return json.load(f)
return {"installed": {}}
def _save_manifest(self, manifest: dict):
with open(self.manifest_path, "w") as f:
json.dump(manifest, f, indent=2)
f.write("\n")
# -- git helpers ----------------------------------------------------------
def _git(self, *args, check=True, capture=False) -> subprocess.CompletedProcess:
cmd = ["git", "-C", str(self.project_dir)] + list(args)
if capture:
return subprocess.run(cmd, check=check, capture_output=True, text=True)
return subprocess.run(cmd, check=check)
def _get_submodule_commit(self, path: str) -> str:
result = self._git("submodule", "status", path, check=False, capture=True)
if result.returncode == 0 and result.stdout.strip():
line = result.stdout.strip()
return line.lstrip(" -+").split()[0][:8]
return "unknown"
def _get_default_branch(self, path: str) -> str:
"""Detect the default branch of a submodule (main or master)."""
full_path = self.project_dir / path
result = subprocess.run(
["git", "-C", str(full_path), "remote", "show", "origin"],
capture_output=True, text=True, check=False, timeout=10,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
if "HEAD branch" in line:
return line.split(":")[-1].strip()
for branch in ["main", "master"]:
r = subprocess.run(
["git", "-C", str(full_path), "rev-parse", "--verify",
f"origin/{branch}"],
capture_output=True, check=False,
)
if r.returncode == 0:
return branch
return "main"
# -- path resolution ------------------------------------------------------
def _resolve_install_path(self, info: dict) -> str:
registry_path = info.get("component_path", "")
dir_name = os.path.basename(registry_path) if registry_path else ""
if not dir_name:
app_id = info.get("name", "unknown").lower().replace(" ", "-")
dir_name = f"{self.config.lib_prefix}{app_id}"
return f"{self.config.lib_dir}/{dir_name}"
# -- checks ---------------------------------------------------------------
def _is_compatible(self, info: dict) -> bool:
platforms = info.get("platforms", [])
return not platforms or self.config.platform in platforms
def _is_official(self, info: dict) -> bool:
repo = info.get("repo", "")
return f"/{self.config.official_org}/" in repo
@staticmethod
def _format_requires(info: dict) -> str:
requires = info.get("requires", {})
if isinstance(requires, list):
requires = {r: "*" for r in requires}
parts = []
for dep, ver in requires.items():
short = dep.replace("crosspad-", "")
parts.append(f"{short} {ver}" if ver != "*" else short)
return ", ".join(parts) if parts else ""
# -- extended helpers (for TUI) -------------------------------------------
def get_cache_age(self) -> int:
"""Return cache age in seconds, or -1 if no cache."""
if not self.local_registry_path.exists():
return -1
return int(datetime.now().timestamp()
- self.local_registry_path.stat().st_mtime)
def get_submodule_dirty(self, path: str) -> bool:
"""Check if a submodule has uncommitted changes."""
full = self.project_dir / path
if not full.exists():
return False
r = subprocess.run(
["git", "-C", str(full), "status", "--porcelain"],
capture_output=True, text=True, check=False, timeout=5,
)
return bool(r.stdout.strip())
def get_app_disk_usage(self, path: str) -> int:
"""Get disk usage of an app directory in bytes."""
full = self.project_dir / path
if not full.exists():
return 0
total = 0
for dirpath, _, filenames in os.walk(full):
for f in filenames:
try:
total += os.path.getsize(os.path.join(dirpath, f))
except OSError:
pass
return total
def get_app_git_log(self, path: str, count: int = 5) -> list[str]:
"""Get recent git log for an app submodule."""
full = self.project_dir / path
if not full.exists():
return []
r = subprocess.run(
["git", "-C", str(full), "log", "--oneline", f"-{count}"],
capture_output=True, text=True, check=False, timeout=5,
)
return r.stdout.strip().splitlines() if r.returncode == 0 else []
def fetch_app_changelog(self, app_id: str, registry: dict = None) -> list[str]:
"""Fetch changelog from app's crosspad-app.json via GitHub API."""
if registry is None:
registry = self._load_registry()
info = registry.get("apps", {}).get(app_id, {})
repo = info.get("repo", "")
if not repo:
return []
parts = repo.rstrip("/").rstrip(".git").split("/")
if len(parts) < 2:
return []
owner_repo = f"{parts[-2]}/{parts[-1]}"
try:
import base64
r = subprocess.run(
["gh", "api",
f"repos/{owner_repo}/contents/crosspad-app.json",
"--jq", ".content"],
capture_output=True, text=True, check=True, timeout=10,
)
data = json.loads(base64.b64decode(r.stdout.strip()).decode())
return data.get("changelog", [])
except Exception:
return []
def detect_serial_port(self) -> str:
"""Try to auto-detect CrossPad serial port."""
import glob as _glob
for pattern in ["/dev/ttyACM*", "/dev/ttyUSB*", "/dev/cu.usbmodem*"]:
matches = _glob.glob(pattern)
if matches:
return matches[0]
# Windows COM ports
if sys.platform == "win32":
for i in range(1, 20):
port = f"COM{i}"
try:
import serial
s = serial.Serial(port)
s.close()
return port
except Exception:
continue
return ""
def _find_idf_path(self) -> str:
"""Find ESP-IDF installation path."""
# 1. Environment variable
p = os.environ.get("IDF_PATH", "")
if p and os.path.isdir(p):
return p
# 2. VSCode settings (idf.espIdfPath)
vscode_settings = self.project_dir / ".vscode" / "settings.json"
if vscode_settings.exists():
try:
with open(vscode_settings) as f:
data = json.load(f)
p = data.get("idf.espIdfPath", "")
if p and os.path.isdir(p):
return p
except (json.JSONDecodeError, OSError):
pass
# 3. Common locations
for candidate in [
Path.home() / "esp" / "esp-idf",
Path.home() / "esp" / "v5.5" / "esp-idf",
Path("/opt/esp-idf"),
]:
if candidate.is_dir():
return str(candidate)
return ""
def run_command(self, cmd: str) -> int:
"""Run a shell command in the project dir, return exit code."""
if self.config.platform == "esp-idf":
idf_path = self._find_idf_path()
if idf_path:
# Source export.sh — puts idf.py + toolchain on PATH
export_sh = os.path.join(idf_path, "export.sh")
if os.path.exists(export_sh):
cmd = (f"export IDF_PATH={idf_path} "
f"IDF_PATH_FORCE=1 && "
f". {export_sh} > /dev/null 2>&1 && {cmd}")
sys.stdout.write(f"\n Running: {cmd}\n\n")
sys.stdout.flush()
_restore_terminal()
proc = subprocess.Popen(
cmd, shell=True, cwd=str(self.project_dir),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
bufsize=0,
)
while True:
chunk = proc.stdout.read(256)
if not chunk:
break
os.write(sys.stdout.fileno(), chunk)
rc = proc.wait()
if rc != 0:
sys.stdout.write(f"\n \033[1;31mFailed (exit code {rc})\033[0m\n")
sys.stdout.flush()
return rc
def check_gh_auth(self) -> tuple[bool, str]:
"""Check if gh CLI is authenticated. Returns (ok, username)."""
try:
r = subprocess.run(
["gh", "auth", "status"],
capture_output=True, text=True, check=False, timeout=5,
)
if r.returncode == 0:
for line in (r.stdout + r.stderr).splitlines():
if "Logged in" in line or "account" in line:
parts = line.strip().split()
for p in parts:
if not p.startswith(("-", "~", "/", "(")):
if len(p) > 2 and p[0].isalpha():
return True, p
return True, "authenticated"
return False, ""
except (FileNotFoundError, subprocess.TimeoutExpired):
return False, ""
def get_all_submodules(self) -> list[dict]:
"""Get status of all git submodules."""
result = self._git("submodule", "status", check=False, capture=True)
subs = []
if result.returncode != 0 or not result.stdout.strip():
return subs
for line in result.stdout.strip().splitlines():
raw = line.strip()
modified = raw.startswith("+")
uninitialized = raw.startswith("-")
parts = raw.lstrip(" -+").split()
if len(parts) >= 2:
commit = parts[0][:7]
path = parts[1]
name = os.path.basename(path)
infra = name in ("crosspad-core", "crosspad-gui",
"crosspad-platform-idf",
"FreeRTOS", "lvgl")
is_app = name.startswith("crosspad-") and not infra
subs.append({
"name": name, "path": path, "commit": commit,
"modified": modified, "uninitialized": uninitialized,
"infra": infra, "is_app": is_app,
})
return subs
def get_build_info(self) -> dict:
"""Get firmware build status. Returns dict with binary info."""
# Platform-specific binary paths
if self.config.platform == "esp-idf":
candidates = [
self.project_dir / "build" / "CrossPad.bin",
# fallback: find any .bin in build/
]
elif self.config.platform == "arduino":
candidates = [
self.project_dir / ".pio" / "build" / "esp32s3" / "firmware.bin",
]
elif self.config.platform == "pc":
candidates = [
self.project_dir / "bin" / "CrossPad",
self.project_dir / "bin" / "CrossPad.exe",
]
else:
return {"exists": False}
binary = None
for c in candidates:
if c.exists():
binary = c
break
if not binary:
return {"exists": False}
stat = binary.stat()
build_time = stat.st_mtime
size = stat.st_size
# Check if any source files are newer than the binary
stale = False
newest_src = 0
src_dirs = ["main", "components", "src"]
src_exts = {".c", ".cpp", ".h", ".hpp", ".cmake"}
for src_dir in src_dirs:
full_dir = self.project_dir / src_dir
if not full_dir.exists():
continue
for dirpath, _, filenames in os.walk(full_dir):
for fn in filenames:
if any(fn.endswith(ext) for ext in src_exts):
try:
mt = os.path.getmtime(os.path.join(dirpath, fn))
if mt > newest_src:
newest_src = mt
except OSError:
pass
stale = newest_src > build_time if newest_src > 0 else False
return {
"exists": True,
"path": str(binary),
"size": size,
"build_time": build_time,
"stale": stale,
"age_seconds": int(datetime.now().timestamp() - build_time),
}
# -- commands -------------------------------------------------------------
def _print_app_line(self, app_id: str, info: dict, manifest: dict):
installed = app_id in manifest.get("installed", {})
status_icon = "\u2713" if installed else " "
status_text = ""
if installed:
inst = manifest["installed"][app_id]
ref = inst.get("ref", "main")
commit = inst.get("version", "")
status_text = f" [{ref} @ {commit}]"
print(f" [{status_icon}] {app_id:<16} {info['description']}{status_text}")
def list_apps(self, show_all: bool = False):
registry = self._load_registry()
manifest = self._load_manifest()
apps = registry.get("apps", {})
if not apps:
print("No apps available in registry.")
return
compatible = {k: v for k, v in apps.items() if self._is_compatible(v)}
incompatible = {k: v for k, v in apps.items()
if not self._is_compatible(v)}
official = {k: v for k, v in compatible.items() if self._is_official(v)}
community = {k: v for k, v in compatible.items()
if not self._is_official(v)}
print(f"\nCrossPad Apps (platform: {self.config.platform}):")
print("-" * 75)
if official:
print("\n Official:")
for app_id, info in official.items():
self._print_app_line(app_id, info, manifest)
if community:
print("\n Community:")
for app_id, info in community.items():
self._print_app_line(app_id, info, manifest)
if not official and not community:
print(" No compatible apps found.")
if show_all and incompatible:
print(f"\n Incompatible with {self.config.platform}:")
for app_id, info in incompatible.items():
platforms = ", ".join(info.get("platforms", []))
req = self._format_requires(info)
req_text = f" [{req}]" if req else ""
print(f" [ ] {app_id:<16} {info['description']}"
f" ({platforms} only){req_text}")
print()
installed_count = sum(1 for k in manifest.get("installed", {})
if k in compatible)
print(f" {installed_count}/{len(compatible)} compatible installed"
f" ({len(apps)} total in registry)")
print()
def install(self, app_name: str, ref: str = "main",
origin: str = None, force: bool = False):
registry = self._load_registry()
manifest = self._load_manifest()
apps = registry.get("apps", {})
if app_name not in apps:
print(f"Error: Unknown app '{app_name}'.")
print(f"Available: {', '.join(apps.keys())}")
sys.exit(1)
info = apps[app_name]
if info.get("built_in"):
print(f"Error: '{app_name}' is a built-in app and cannot "
f"be installed or removed via the app manager.")
return
if app_name in manifest.get("installed", {}):
print(f"App '{app_name}' is already installed.")
return
info = apps[app_name]
if not self._is_compatible(info) and not force:
platforms = ", ".join(info.get("platforms", []))
print(f"Warning: '{app_name}' is not compatible "
f"with {self.config.platform}.")
print(f" Supported platforms: {platforms}")
print(f" Use --force to install anyway.")
return
repo = origin if origin else info["repo"]
install_path = self._resolve_install_path(info)
requires = info.get("requires", {})
if isinstance(requires, list):
requires = {r: "*" for r in requires}
for req, ver in requires.items():
# Check lib_dir (apps), lib/ (shared deps), and project root
candidates = [
self.project_dir / self.config.lib_dir / req,
self.project_dir / "lib" / req,
self.project_dir / req,
]
if not any(c.exists() for c in candidates):
print(f"Warning: Required component '{req}' ({ver}) "
f"not found")
print(f"Installing {info['name']}...")
print(f" Repo: {repo}")
print(f" Path: {install_path}")
print(f" Ref: {ref}")
full_path = self.project_dir / install_path
already_exists = full_path.exists() and (full_path / ".git").exists()
if already_exists:
print(f" Submodule already exists at {install_path}, "
"registering in manifest.")
else:
try:
self._git("submodule", "add", repo, install_path)
except subprocess.CalledProcessError:
print("Error: Failed to add submodule. "
"Check repo URL and network.")
sys.exit(1)
if ref != "main":
try:
subprocess.run(
["git", "-C", str(full_path), "fetch", "origin"],
check=True)
subprocess.run(
["git", "-C", str(full_path), "checkout", ref],
check=True)
self._git("add", install_path)
except subprocess.CalledProcessError:
print(f"Error: Failed to checkout ref '{ref}'.")
sys.exit(1)
commit = self._get_submodule_commit(install_path)
manifest.setdefault("installed", {})[app_name] = {
"version": commit,
"ref": ref,
"repo": repo,
"installed_at": datetime.now(timezone.utc).isoformat(),
}
self._save_manifest(manifest)
print(f"\n {info['name']} installed successfully.")
self._print_next_steps()
def remove(self, app_name: str):
manifest = self._load_manifest()
registry = self._load_registry()
apps = registry.get("apps", {})
if apps.get(app_name, {}).get("built_in"):
print(f"Error: '{app_name}' is a built-in app and cannot "
f"be removed.")
return
if app_name not in manifest.get("installed", {}):
print(f"App '{app_name}' is not installed.")
return
info = apps.get(app_name, {})
install_path = (self._resolve_install_path(info) if info else
f"{self.config.lib_dir}/{self.config.lib_prefix}"
f"{app_name}")
print(f"Removing {info.get('name', app_name)}...")
try:
self._git("submodule", "deinit", "-f", install_path)
self._git("rm", "-f", install_path)
except subprocess.CalledProcessError:
print("Warning: git submodule removal had issues, "
"cleaning up manually.")
modules_path = self.project_dir / ".git" / "modules" / install_path
if modules_path.exists():
import shutil
shutil.rmtree(modules_path)
del manifest["installed"][app_name]
self._save_manifest(manifest)
print(f"\n {info.get('name', app_name)} removed.")
self._print_next_steps()
def update(self, app_name: str = None, update_all: bool = False):
manifest = self._load_manifest()
registry = self._load_registry()
apps = registry.get("apps", {})
if update_all:
targets = list(manifest.get("installed", {}).keys())
elif app_name:
if app_name not in manifest.get("installed", {}):
print(f"App '{app_name}' is not installed.")
return
targets = [app_name]
else:
print("Specify an app name or --all.")
return
if not targets:
print("No apps installed.")
return
for name in targets:
info = apps.get(name, {})
inst = manifest["installed"][name]
install_path = (self._resolve_install_path(info) if info else
f"{self.config.lib_dir}/{self.config.lib_prefix}"
f"{name}")
ref = inst.get("ref", "main")
full_path = self.project_dir / install_path
if not full_path.exists():
print(f" {name}: path missing, skipping.")
continue
print(f"Updating {info.get('name', name)} ({ref})...")
try:
subprocess.run(
["git", "-C", str(full_path), "fetch", "origin"],
check=True)
checkout_ref = (f"origin/{ref}"
if not ref.startswith(("origin/", "refs/"))
and len(ref) < 12
else ref)
subprocess.run(
["git", "-C", str(full_path), "checkout", checkout_ref],
check=True)
self._git("add", install_path)
except subprocess.CalledProcessError:
print(f" Error updating {name}.")
continue
commit = self._get_submodule_commit(install_path)
old_commit = inst.get("version", "?")
inst["version"] = commit
inst["updated_at"] = datetime.now(timezone.utc).isoformat()
print(f" {old_commit} -> {commit}")
self._save_manifest(manifest)
if targets:
self._print_next_steps()
def sync(self):
"""Detect existing app submodules and sync manifest."""
registry = self._load_registry()
manifest = self._load_manifest()
apps = registry.get("apps", {})
synced = 0
for app_id, info in apps.items():
install_path = self._resolve_install_path(info)
full_path = self.project_dir / install_path
already_in_manifest = app_id in manifest.get("installed", {})
exists_on_disk = (full_path.exists()
and (full_path / ".git").exists())
if exists_on_disk and not already_in_manifest:
commit = self._get_submodule_commit(install_path)
ref = self._get_default_branch(install_path)
manifest.setdefault("installed", {})[app_id] = {
"version": commit,
"ref": ref,
"repo": info.get("repo", ""),
"installed_at": datetime.now(timezone.utc).isoformat(),
}
print(f" + {app_id} ({install_path} @ {commit}, ref={ref})")
synced += 1
elif not exists_on_disk and already_in_manifest:
del manifest["installed"][app_id]
print(f" - {app_id} (removed from manifest, not on disk)")
synced += 1
if synced:
self._save_manifest(manifest)
print(f"\nSynced {synced} app(s).")
else:
print("Manifest is up to date.")
def _print_next_steps(self):
if self.config.platform == "esp-idf":
print(f"\n Next: idf.py fullclean && idf.py build")
elif self.config.platform == "arduino":
print(f"\n Next: pio run --target clean && pio run")
elif self.config.platform == "pc":
print(f"\n Next: rm -rf build && cmake -B build -G Ninja && cmake --build build")
else:
print(f"\n Next: rebuild your project")
# == Standalone CLI ===========================================================
def cli_main(config: PlatformConfig):
"""Generic CLI entry point for any platform."""
import argparse
parser = argparse.ArgumentParser(
prog="crosspad-apps",
description="CrossPad App Package Manager",
)
sub = parser.add_subparsers(dest="command")
list_cmd = sub.add_parser("list", help="List available and installed apps")
list_cmd.add_argument("--all", action="store_true",
help="Show incompatible apps too")
install_cmd = sub.add_parser("install", help="Install an app")
install_cmd.add_argument("app", help="App name")
install_cmd.add_argument("--ref", default="main",
help="Branch/tag/commit")
install_cmd.add_argument("--origin", default=None,
help="Override repo URL")
install_cmd.add_argument("--force", action="store_true",
help="Install despite platform incompatibility")
remove_cmd = sub.add_parser("remove", help="Remove an app")
remove_cmd.add_argument("app", help="App name")
update_cmd = sub.add_parser("update", help="Update app(s)")
update_cmd.add_argument("app", nargs="?", help="App name")
update_cmd.add_argument("--all", action="store_true", help="Update all")
sub.add_parser("sync", help="Sync manifest with existing submodules")
sub.add_parser("tui", help="Interactive terminal UI")
args = parser.parse_args()
mgr = AppManager(os.getcwd(), config)
if args.command == "list":
mgr.list_apps(show_all=args.all)
elif args.command == "install":
mgr.install(args.app, ref=args.ref, origin=args.origin,
force=args.force)
elif args.command == "remove":
mgr.remove(args.app)
elif args.command == "update":
mgr.update(app_name=args.app, update_all=args.all)
elif args.command == "sync":
mgr.sync()
elif args.command == "tui" or args.command is None:
if _is_interactive():
tui_main(config)
elif args.command is None:
parser.print_help()
else:
print("Error: TUI requires an interactive terminal.")
sys.exit(1)
else:
parser.print_help()
# =============================================================================
# Interactive TUI
# =============================================================================
def _is_interactive():
"""Check if stdin is a real terminal."""
try:
return os.isatty(sys.stdin.fileno())
except (OSError, AttributeError):
return False
# -- ANSI helpers -------------------------------------------------------------
class _C:
"""ANSI escape codes."""
RST = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
UL = "\033[4m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
GRAY = "\033[90m"
BRED = "\033[1;31m"
BGREEN = "\033[1;32m"
BYELLOW = "\033[1;33m"
BBLUE = "\033[1;34m"
BMAGENTA = "\033[1;35m"
BCYAN = "\033[1;36m"
BWHITE = "\033[1;37m"
BGBLUE = "\033[44m"
BGCYAN = "\033[46m"
def _w(s: str):
"""Write to stdout without newline."""
sys.stdout.write(s)
sys.stdout.flush()
def _get_size() -> tuple[int, int]:
"""Return (columns, rows) of terminal."""
try:
import shutil as _sh
return _sh.get_terminal_size((80, 24))
except Exception:
return (80, 24)
def _clear():
_w("\033[2J\033[H")
def _hide_cursor():
_w("\033[?25l")
def _show_cursor():
_w("\033[?25h")
# Terminal state management — raw mode breaks subprocess output
_saved_termios = None
def _save_terminal():
"""Save terminal attributes before entering TUI."""
global _saved_termios
try:
import termios
_saved_termios = termios.tcgetattr(sys.stdin.fileno())
except (ImportError, OSError):
pass
def _restore_terminal():
"""Restore terminal to normal (cooked) mode for subprocess output."""
if _saved_termios is not None:
try:
import termios
termios.tcsetattr(sys.stdin.fileno(),
termios.TCSADRAIN, _saved_termios)
except (ImportError, OSError):
pass
_show_cursor()
def _read_key() -> str:
"""Read a single keypress, return normalized key name."""
try:
import termios
import tty
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
if ch == "\x1b":
seq = sys.stdin.read(2)
if seq == "[A": return "up"
if seq == "[B": return "down"
if seq == "[C": return "right"
if seq == "[D": return "left"
if seq == "[5":
sys.stdin.read(1)
return "pgup"
if seq == "[6":
sys.stdin.read(1)
return "pgdn"
if seq == "[H": return "home"
if seq == "[F": return "end"
return "esc"
if ch in ("\r", "\n"): return "enter"
if ch in ("\x7f", "\x08"): return "backspace"
if ch == "\t": return "tab"
if ch == "\x03": return "ctrl-c"
return ch
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
except (ImportError, OSError):
import msvcrt
ch = msvcrt.getch()
if ch in (b"\xe0", b"\x00"):
ch2 = msvcrt.getch()
m = {b"H": "up", b"P": "down", b"K": "left", b"M": "right",
b"I": "pgup", b"Q": "pgdn", b"G": "home", b"O": "end"}
return m.get(ch2, "")
if ch == b"\r": return "enter"
if ch == b"\x1b": return "esc"
if ch == b"\x08": return "backspace"
if ch == b"\t": return "tab"
if ch == b"\x03": return "ctrl-c"
return ch.decode("utf-8", errors="ignore")
# -- TUI widgets --------------------------------------------------------------
def _confirm(prompt: str) -> bool:
"""Yes/no prompt. Returns True on 'y'."""
_w(f"\n {prompt} {_C.DIM}[y/N]{_C.RST} ")
_show_cursor()
while True:
key = _read_key()
if key in ("y", "Y"):
_w(f"{_C.BGREEN}yes{_C.RST}\n")
_hide_cursor()
return True
if key in ("n", "N", "enter", "esc", "ctrl-c"):
_w(f"{_C.GRAY}no{_C.RST}\n")
_hide_cursor()
return False
def _text_input(prompt: str, default: str = "") -> str | None:
"""Single-line text input. Returns None on cancel."""
buf = list(default)
_show_cursor()
while True:
_w(f"\r\033[K {prompt}: {_C.BWHITE}{''.join(buf)}{_C.RST}\033[K")
key = _read_key()
if key == "enter":
_w("\n")
_hide_cursor()
return "".join(buf)
elif key in ("esc", "ctrl-c"):
_w("\n")
_hide_cursor()
return None
elif key == "backspace":
if buf:
buf.pop()
elif len(key) == 1 and key.isprintable():
buf.append(key)
def _menu_select(title: str, items: list[str],
descriptions: list[str] = None,
hotkeys: list[str] = None) -> int:
"""Arrow-key menu. Returns selected index or -1."""
cursor = 0
while True:
_clear()
_w(f"\n {_C.BCYAN}{title}{_C.RST}\n")
_w(f" {_C.GRAY}{'─' * (_get_size()[0] - 4)}{_C.RST}\n\n")
for i, item in enumerate(items):
if i == cursor:
_w(f" {_C.BYELLOW}> {item}{_C.RST}\n")
if descriptions and i < len(descriptions) and descriptions[i]:
_w(f" {_C.GRAY}{descriptions[i]}{_C.RST}\n")
else:
_w(f" {item}\n")
_w(f"\n {_C.GRAY}[arrows] navigate "
f"[enter] select [q/esc] back{_C.RST}\n")
key = _read_key()
if key == "up":
cursor = (cursor - 1) % len(items)
elif key == "down":
cursor = (cursor + 1) % len(items)
elif key == "enter":
return cursor
elif key in ("esc", "ctrl-c"):