txa 1.3.2__tar.gz → 1.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {txa-1.3.2 → txa-1.4.0}/PKG-INFO +1 -1
  2. {txa-1.3.2 → txa-1.4.0}/src/txa/__init__.py +1 -1
  3. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/api.py +1 -1
  4. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/steps.py +111 -91
  5. {txa-1.3.2 → txa-1.4.0}/src/txa/cli.py +13 -0
  6. txa-1.4.0/src/txa/core/retention.py +40 -0
  7. {txa-1.3.2 → txa-1.4.0}/src/txa/core/winos.py +19 -0
  8. {txa-1.3.2 → txa-1.4.0}/src/txa/create/submit.py +23 -4
  9. {txa-1.3.2 → txa-1.4.0}/src/txa/create/winget.py +3 -7
  10. {txa-1.3.2 → txa-1.4.0}/src/txa/pm/cli.py +47 -3
  11. {txa-1.3.2 → txa-1.4.0}/src/txa/pm/installer.py +26 -8
  12. {txa-1.3.2 → txa-1.4.0}/src/txa/schemas/build.schema.json +6 -1
  13. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/PKG-INFO +1 -1
  14. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/SOURCES.txt +1 -0
  15. {txa-1.3.2 → txa-1.4.0}/README.md +0 -0
  16. {txa-1.3.2 → txa-1.4.0}/pyproject.toml +0 -0
  17. {txa-1.3.2 → txa-1.4.0}/setup.cfg +0 -0
  18. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/__init__.py +0 -0
  19. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/agreement.py +0 -0
  20. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/checks.py +0 -0
  21. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/cli.py +0 -0
  22. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/context.py +0 -0
  23. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/gate.py +0 -0
  24. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/pending.py +0 -0
  25. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/progress.py +0 -0
  26. {txa-1.3.2 → txa-1.4.0}/src/txa/ci/report.py +0 -0
  27. {txa-1.3.2 → txa-1.4.0}/src/txa/constants.py +0 -0
  28. {txa-1.3.2 → txa-1.4.0}/src/txa/core/__init__.py +0 -0
  29. {txa-1.3.2 → txa-1.4.0}/src/txa/core/config.py +0 -0
  30. {txa-1.3.2 → txa-1.4.0}/src/txa/core/console.py +0 -0
  31. {txa-1.3.2 → txa-1.4.0}/src/txa/core/credentials.py +0 -0
  32. {txa-1.3.2 → txa-1.4.0}/src/txa/core/engines.py +0 -0
  33. {txa-1.3.2 → txa-1.4.0}/src/txa/core/github.py +0 -0
  34. {txa-1.3.2 → txa-1.4.0}/src/txa/core/i18n.py +0 -0
  35. {txa-1.3.2 → txa-1.4.0}/src/txa/core/licenses.py +0 -0
  36. {txa-1.3.2 → txa-1.4.0}/src/txa/core/manifest.py +0 -0
  37. {txa-1.3.2 → txa-1.4.0}/src/txa/core/net.py +0 -0
  38. {txa-1.3.2 → txa-1.4.0}/src/txa/core/pe.py +0 -0
  39. {txa-1.3.2 → txa-1.4.0}/src/txa/core/portable.py +0 -0
  40. {txa-1.3.2 → txa-1.4.0}/src/txa/core/semver.py +0 -0
  41. {txa-1.3.2 → txa-1.4.0}/src/txa/core/signing.py +0 -0
  42. {txa-1.3.2 → txa-1.4.0}/src/txa/core/userpath.py +0 -0
  43. {txa-1.3.2 → txa-1.4.0}/src/txa/create/__init__.py +0 -0
  44. {txa-1.3.2 → txa-1.4.0}/src/txa/create/cli.py +0 -0
  45. {txa-1.3.2 → txa-1.4.0}/src/txa/create/draft.py +0 -0
  46. {txa-1.3.2 → txa-1.4.0}/src/txa/create/ghmeta.py +0 -0
  47. {txa-1.3.2 → txa-1.4.0}/src/txa/create/wizard.py +0 -0
  48. {txa-1.3.2 → txa-1.4.0}/src/txa/pm/__init__.py +0 -0
  49. {txa-1.3.2 → txa-1.4.0}/src/txa/pm/source.py +0 -0
  50. {txa-1.3.2 → txa-1.4.0}/src/txa/pm/uninstall.py +0 -0
  51. {txa-1.3.2 → txa-1.4.0}/src/txa/schemas/about.schema.json +0 -0
  52. {txa-1.3.2 → txa-1.4.0}/src/txa/schemas/core.schema.json +0 -0
  53. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/dependency_links.txt +0 -0
  54. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/entry_points.txt +0 -0
  55. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/requires.txt +0 -0
  56. {txa-1.3.2 → txa-1.4.0}/src/txa.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: txa
3
- Version: 1.3.2
3
+ Version: 1.4.0
4
4
  Summary: TXA package manager toolchain: txapm (install), txacreate (publish), txaci (16-step validator), txacli (WinGet & repo CLI)
5
5
  Author: TXA Software Dev
6
6
  License: MIT
@@ -1,3 +1,3 @@
1
1
  """TXA package manager toolchain."""
2
2
 
3
- __version__ = "1.3.2"
3
+ __version__ = "1.4.0"
@@ -72,7 +72,7 @@ def index_document(packages: dict[str, dict[str, dict]]) -> dict:
72
72
  "summary": about["summary"],
73
73
  "summaries": summaries,
74
74
  "tags": latest["core"].get("tags", []),
75
- "arches": [t["arch"] for t in latest["build"]["targets"]],
75
+ "arches": list(dict.fromkeys(t["arch"] for t in latest["build"]["targets"])),
76
76
  })
77
77
  generated = datetime.now(timezone.utc).isoformat(timespec="seconds")
78
78
  return {"api": "txa.v1", "generated": generated, "count": len(index), "packages": index}
@@ -113,8 +113,14 @@ def _targets_or_skip(ctx: Context, target: dict, out: Outcome) -> list[dict]:
113
113
  return bundle.targets()
114
114
 
115
115
 
116
- def _artifact_file(ctx: Context, target: dict, arch: str) -> Path | None:
117
- file = ctx.artifact(target, arch).get("file")
116
+ def _slot(item: dict) -> str:
117
+ """Key/label of one installer: the CPU, plus the language when one CPU has several (x64-vi)."""
118
+ locale = (item.get("locale") or "").split("-")[0]
119
+ return f"{item['arch']}-{locale}" if locale else item["arch"]
120
+
121
+
122
+ def _artifact_file(ctx: Context, target: dict, slot: str) -> Path | None:
123
+ file = ctx.artifact(target, slot).get("file")
118
124
  return Path(file) if file and Path(file).exists() else None
119
125
 
120
126
 
@@ -225,9 +231,9 @@ def structure(ctx: Context, target: dict, out: Outcome) -> None:
225
231
  for problem in schema_errors(kind, card):
226
232
  out.fail(f"{name}: {problem}")
227
233
  build = bundle.build or {}
228
- arches = [t.get("arch") for t in build.get("targets") or [] if isinstance(t, dict)]
229
- for arch in sorted({a for a in arches if arches.count(a) > 1}):
230
- out.fail(f"{BUILD_FILE}: architecture '{arch}' is declared more than once")
234
+ arches = [(t.get("arch"), t.get("locale")) for t in build.get("targets") or [] if isinstance(t, dict)]
235
+ for arch, locale in sorted({a for a in arches if arches.count(a) > 1}, key=str):
236
+ out.fail(f"{BUILD_FILE}: architecture '{arch}'{f' / locale {locale}' if locale else ''} is declared more than once")
231
237
  if not checked:
232
238
  out.fail("no TXA cards found in this directory")
233
239
  elif out.status in ("PASS", "SKIP"):
@@ -241,8 +247,12 @@ def structure(ctx: Context, target: dict, out: Outcome) -> None:
241
247
  def naming(ctx: Context, target: dict, out: Outcome) -> None:
242
248
  bundle = ctx.bundle(target)
243
249
  parts = target["path"].split("/")
244
- if ctx.mode == "ci" and len(ctx.targets) > 1:
245
- out.fail(f"this pull request touches {len(ctx.targets)} releases - submit exactly one release per PR")
250
+ if ctx.mode == "ci":
251
+ added = [t for t in ctx.targets if t.get("mode") != "removal"]
252
+ packages = {"/".join(t["path"].split("/")[:4]) for t in ctx.targets}
253
+ # one new release of one package; dropping that package's oldest versions (the keep-10 rule) rides along
254
+ if len(added) > 1 or len(packages) > 1:
255
+ out.fail(f"this pull request touches {len(ctx.targets)} releases - submit exactly one release per PR")
246
256
  if len(parts) != 5 or parts[0] != "manifests":
247
257
  out.fail(f"'{target['path']}' does not follow manifests/<shard>/<Namespace>/<AppName>/<X.Y.Z>/")
248
258
  if bundle.subdirs:
@@ -412,21 +422,22 @@ def protocol(ctx: Context, target: dict, out: Outcome) -> None:
412
422
  s = net.session()
413
423
  for item in _targets_or_skip(ctx, target, out):
414
424
  arch, source = item["arch"], item["source"]
415
- art = ctx.artifact(target, arch)
425
+ slot = _slot(item)
426
+ art = ctx.artifact(target, slot)
416
427
  art["mirrors"] = {}
417
428
  for role, url in [("primary", source["url"]), *(("mirror", m) for m in source.get("mirrors", []))]:
418
429
  if _SIGNED_QUERY.search(url):
419
- out.warn(f"[{arch}] {url}: looks like a signed/expiring link - it will stop working")
430
+ out.warn(f"[{slot}] {url}: looks like a signed/expiring link - it will stop working")
420
431
  try:
421
432
  result = net.probe(s, url, int(limits["max_redirects"]), float(limits["http_timeout_s"]))
422
433
  except net.RedirectLoop as exc:
423
- out.fail(f"[{arch}] redirect loop: {exc}")
434
+ out.fail(f"[{slot}] redirect loop: {exc}")
424
435
  continue
425
436
  except net.UnsafeURL as exc:
426
- out.fail(f"[{arch}] insecure hop: {exc}")
437
+ out.fail(f"[{slot}] insecure hop: {exc}")
427
438
  continue
428
439
  except Exception as exc: # DNS, TLS, timeouts - all mean "unreachable"
429
- out.fail(f"[{arch}] {role} unreachable: {type(exc).__name__}: {exc}")
440
+ out.fail(f"[{slot}] {role} unreachable: {type(exc).__name__}: {exc}")
430
441
  continue
431
442
  record = {
432
443
  "final_url": result.final_url, "status": result.status, "length": result.length,
@@ -439,9 +450,9 @@ def protocol(ctx: Context, target: dict, out: Outcome) -> None:
439
450
  art["mirrors"][url] = record
440
451
  chain = len(result.hops) - 1
441
452
  if result.status not in (200, 206):
442
- out.fail(f"[{arch}] {role} answered HTTP {result.status} after {chain} redirect(s)")
453
+ out.fail(f"[{slot}] {role} answered HTTP {result.status} after {chain} redirect(s)")
443
454
  else:
444
- out.ok(f"[{arch}] {role}: HTTPS end-to-end, {chain} redirect(s), HTTP {result.status} in {result.elapsed_ms} ms")
455
+ out.ok(f"[{slot}] {role}: HTTPS end-to-end, {chain} redirect(s), HTTP {result.status} in {result.elapsed_ms} ms")
445
456
 
446
457
 
447
458
  # =========================================================================== 07
@@ -454,35 +465,36 @@ def payload_headers(ctx: Context, target: dict, out: Outcome) -> None:
454
465
  max_bytes = int(ctx.policy["limits"]["max_payload_mb"]) * 1024 * 1024
455
466
  for item in _targets_or_skip(ctx, target, out):
456
467
  arch = item["arch"]
457
- probe = ctx.artifact(target, arch).get("probe")
468
+ slot = _slot(item)
469
+ probe = ctx.artifact(target, slot).get("probe")
458
470
  if not probe:
459
- out.skip(f"[{arch}] no probe result (see STEP 06)")
471
+ out.skip(f"[{slot}] no probe result (see STEP 06)")
460
472
  continue
461
473
  headers, length = probe["headers"], probe["length"]
462
474
  if length is None:
463
- out.warn(f"[{arch}] server sends no Content-Length - size limit enforced while streaming instead")
475
+ out.warn(f"[{slot}] server sends no Content-Length - size limit enforced while streaming instead")
464
476
  elif length > max_bytes:
465
- out.fail(f"[{arch}] payload is {length / 1048576:.1f} MiB, limit is {max_bytes // 1048576} MiB")
477
+ out.fail(f"[{slot}] payload is {length / 1048576:.1f} MiB, limit is {max_bytes // 1048576} MiB")
466
478
  declared = item["source"].get("size")
467
479
  if declared and length and declared != length:
468
- out.fail(f"[{arch}] source.size says {declared} bytes, server says {length}")
480
+ out.fail(f"[{slot}] source.size says {declared} bytes, server says {length}")
469
481
  ctype = headers.get("content-type", "").split(";", 1)[0].strip().lower()
470
482
  if ctype in _WEB_TYPES:
471
- out.fail(f"[{arch}] Content-Type '{ctype}' - the URL serves a web page, not an installer")
483
+ out.fail(f"[{slot}] Content-Type '{ctype}' - the URL serves a web page, not an installer")
472
484
  elif not ctype:
473
- out.warn(f"[{arch}] no Content-Type header")
485
+ out.warn(f"[{slot}] no Content-Type header")
474
486
  wanted = {"msi": ".msi", "portable": ".zip"}.get(item["engine"], ".exe")
475
487
  names = [probe["final_url"].split("?", 1)[0].rsplit("/", 1)[-1]]
476
488
  disposition = headers.get("content-disposition", "")
477
489
  if "filename=" in disposition:
478
490
  names.insert(0, disposition.split("filename=", 1)[1].split(";", 1)[0].strip().strip('"'))
479
491
  if not any(n.lower().endswith(wanted) for n in names):
480
- out.warn(f"[{arch}] file name '{names[0]}' does not end with {wanted} for engine '{item['engine']}'")
492
+ out.warn(f"[{slot}] file name '{names[0]}' does not end with {wanted} for engine '{item['engine']}'")
481
493
  cdn = net.cdn_fingerprint(headers) or "unknown"
482
494
  server = headers.get("server", "n/a")
483
495
  resumable = "yes" if headers.get("accept-ranges", "").lower() == "bytes" or probe["method"].startswith("GET") else "no"
484
496
  size = f"{length / 1048576:.2f} MiB" if length else "unknown size"
485
- out.ok(f"[{arch}] {size}, type {ctype or 'n/a'}, server '{server}', CDN {cdn}, resumable {resumable}, "
497
+ out.ok(f"[{slot}] {size}, type {ctype or 'n/a'}, server '{server}', CDN {cdn}, resumable {resumable}, "
486
498
  f"last-modified {headers.get('last-modified', 'n/a')}")
487
499
 
488
500
 
@@ -499,10 +511,11 @@ def availability(ctx: Context, target: dict, out: Outcome) -> None:
499
511
 
500
512
  for item in _targets_or_skip(ctx, target, out):
501
513
  arch = item["arch"]
502
- art = ctx.artifact(target, arch)
514
+ slot = _slot(item)
515
+ art = ctx.artifact(target, slot)
503
516
  probe = art.get("probe")
504
517
  if not probe:
505
- out.skip(f"[{arch}] no probe result (see STEP 06)")
518
+ out.skip(f"[{slot}] no probe result (see STEP 06)")
506
519
  continue
507
520
  url = probe["final_url"]
508
521
  host = urlsplit(url).hostname or ""
@@ -529,30 +542,30 @@ def availability(ctx: Context, target: dict, out: Outcome) -> None:
529
542
  except Exception:
530
543
  pass
531
544
  if ok == 3:
532
- out.warn(f"[{arch}] geo DNS unavailable - {host} answered 3/3 probes from the runner only")
545
+ out.warn(f"[{slot}] geo DNS unavailable - {host} answered 3/3 probes from the runner only")
533
546
  else:
534
- out.fail(f"[{arch}] {host} answered only {ok}/3 probes from the runner")
547
+ out.fail(f"[{slot}] {host} answered only {ok}/3 probes from the runner")
535
548
  else:
536
549
  good = [e for e in edges if e.ok]
537
550
  unique = {e.address for e in good}
538
551
  summary = ", ".join(f"{e.region}:{e.status or 'x'}" + (f"/{e.elapsed_ms}ms" if e.elapsed_ms else "") for e in edges)
539
552
  anycast = " (anycast edge)" if len(unique) == 1 and len(good) > 1 else ""
540
553
  if len(good) >= need:
541
- out.ok(f"[{arch}] {host}: {len(good)}/{len(edges)} regions healthy{anycast} - {summary}")
554
+ out.ok(f"[{slot}] {host}: {len(good)}/{len(edges)} regions healthy{anycast} - {summary}")
542
555
  elif good:
543
- out.warn(f"[{arch}] {host}: only {len(good)}/{len(edges)} regions healthy (want {need}) - {summary}")
556
+ out.warn(f"[{slot}] {host}: only {len(good)}/{len(edges)} regions healthy (want {need}) - {summary}")
544
557
  else:
545
- out.fail(f"[{arch}] {host}: no region could reach the CDN - {summary}")
558
+ out.fail(f"[{slot}] {host}: no region could reach the CDN - {summary}")
546
559
  for edge in edges:
547
560
  if edge.error and not edge.ok:
548
- out.info(f"[{arch}] {edge.region} @ {edge.address or '-'}: {edge.error}")
561
+ out.info(f"[{slot}] {edge.region} @ {edge.address or '-'}: {edge.error}")
549
562
  for mirror, record in (art.get("mirrors") or {}).items():
550
563
  if record["status"] not in (200, 206):
551
- out.fail(f"[{arch}] mirror {mirror} answered HTTP {record['status']}")
564
+ out.fail(f"[{slot}] mirror {mirror} answered HTTP {record['status']}")
552
565
  elif record["length"] and probe["length"] and record["length"] != probe["length"]:
553
- out.fail(f"[{arch}] mirror {mirror} serves {record['length']} bytes, primary serves {probe['length']}")
566
+ out.fail(f"[{slot}] mirror {mirror} serves {record['length']} bytes, primary serves {probe['length']}")
554
567
  else:
555
- out.ok(f"[{arch}] mirror {urlsplit(mirror).hostname} in sync with primary")
568
+ out.ok(f"[{slot}] mirror {urlsplit(mirror).hostname} in sync with primary")
556
569
 
557
570
 
558
571
  # =========================================================================== 09
@@ -566,38 +579,39 @@ def download(ctx: Context, target: dict, out: Outcome) -> None:
566
579
  s = net.session()
567
580
  for item in _targets_or_skip(ctx, target, out):
568
581
  arch = item["arch"]
569
- art = ctx.artifact(target, arch)
570
- if arch not in supplied and ctx.offline:
571
- out.skip(f"[{arch}] offline mode and no local payload")
582
+ slot = _slot(item)
583
+ art = ctx.artifact(target, slot)
584
+ if slot not in supplied and arch not in supplied and ctx.offline:
585
+ out.skip(f"[{slot}] offline mode and no local payload")
572
586
  continue
573
- if arch in supplied:
574
- path = Path(supplied[arch])
587
+ if slot in supplied or arch in supplied:
588
+ path = Path(supplied.get(slot) or supplied[arch])
575
589
  art.update({"file": str(path), "bytes": path.stat().st_size, "stream_sha256": None})
576
- out.ok(f"[{arch}] using local payload {path.name} ({path.stat().st_size} bytes)")
590
+ out.ok(f"[{slot}] using local payload {path.name} ({path.stat().st_size} bytes)")
577
591
  else:
578
592
  try:
579
- result = net.download(s, item["source"]["url"], ctx.payload_dir(target, arch), max_bytes,
593
+ result = net.download(s, item["source"]["url"], ctx.payload_dir(target, slot), max_bytes,
580
594
  int(limits["max_redirects"]), float(limits["http_timeout_s"]) * 2)
581
595
  except Exception as exc:
582
- out.fail(f"[{arch}] download failed: {type(exc).__name__}: {exc}")
596
+ out.fail(f"[{slot}] download failed: {type(exc).__name__}: {exc}")
583
597
  continue
584
598
  art.update({"file": str(result.path), "bytes": result.bytes, "stream_sha256": result.sha256})
585
599
  if result.expected is not None and result.bytes != result.expected:
586
- out.fail(f"[{arch}] truncated stream: {result.bytes}/{result.expected} bytes")
600
+ out.fail(f"[{slot}] truncated stream: {result.bytes}/{result.expected} bytes")
587
601
  continue
588
602
  probe_len = (art.get("probe") or {}).get("length")
589
603
  if probe_len and probe_len != result.bytes:
590
- out.fail(f"[{arch}] probe announced {probe_len} bytes but {result.bytes} arrived")
604
+ out.fail(f"[{slot}] probe announced {probe_len} bytes but {result.bytes} arrived")
591
605
  continue
592
606
  extra = f", resumed after {result.attempts - 1} interruption(s)" if result.resumed else \
593
607
  f", {result.attempts} attempt(s)" if result.attempts > 1 else ""
594
- out.ok(f"[{arch}] {result.path.name}: {result.bytes} bytes received intact{extra}")
608
+ out.ok(f"[{slot}] {result.path.name}: {result.bytes} bytes received intact{extra}")
595
609
  with open(art["file"], "rb") as fh:
596
610
  head = fh.read(16)
597
611
  is_zip = head[:4] == b"PK\x03\x04"
598
612
  if head[:2] != b"MZ" and head[:8] != engines.CFB_MAGIC and not (is_zip and item["engine"] == "portable"):
599
613
  sniff = head[:15].decode("ascii", "replace")
600
- out.fail(f"[{arch}] payload is not a Windows installer or portable ZIP (starts with {sniff!r})")
614
+ out.fail(f"[{slot}] payload is not a Windows installer or portable ZIP (starts with {sniff!r})")
601
615
 
602
616
 
603
617
  # =========================================================================== 10
@@ -625,31 +639,32 @@ def authenticode(ctx: Context, target: dict, out: Outcome) -> None:
625
639
  require = bool(ctx.policy["signature"].get("require"))
626
640
  for item in _targets_or_skip(ctx, target, out):
627
641
  arch = item["arch"]
628
- file = _artifact_file(ctx, target, arch)
642
+ slot = _slot(item)
643
+ file = _artifact_file(ctx, target, slot)
629
644
  if not file:
630
- out.skip(f"[{arch}] no payload (see STEP 09)")
645
+ out.skip(f"[{slot}] no payload (see STEP 09)")
631
646
  continue
632
647
  if item["engine"] == "portable":
633
- out.skip(f"[{arch}] portable ZIP - an archive cannot carry an Authenticode signature")
648
+ out.skip(f"[{slot}] portable ZIP - an archive cannot carry an Authenticode signature")
634
649
  continue
635
650
  sig = signing.verify(file)
636
- ctx.artifact(target, arch)["signature"] = {
651
+ ctx.artifact(target, slot)["signature"] = {
637
652
  "status": sig.status, "signer": sig.signer_cn, "issuer": sig.issuer,
638
653
  "thumbprint": sig.thumbprint, "timestamped": sig.timestamped, "engine": sig.engine,
639
654
  }
640
655
  if sig.status == "valid":
641
656
  stamp = "timestamped" if sig.timestamped else "NOT timestamped"
642
- out.ok(f"[{arch}] valid signature by '{sig.signer_cn}' ({stamp}, verified via {sig.engine})")
657
+ out.ok(f"[{slot}] valid signature by '{sig.signer_cn}' ({stamp}, verified via {sig.engine})")
643
658
  if publisher and sig.signer_cn and not _resembles(publisher, sig.signer_cn):
644
- out.warn(f"[{arch}] signer '{sig.signer_cn}' does not resemble publisher '{publisher}'")
659
+ out.warn(f"[{slot}] signer '{sig.signer_cn}' does not resemble publisher '{publisher}'")
645
660
  if not sig.timestamped:
646
- out.warn(f"[{arch}] signature is not timestamped - it becomes invalid when the certificate expires")
661
+ out.warn(f"[{slot}] signature is not timestamped - it becomes invalid when the certificate expires")
647
662
  elif sig.status == "unsigned":
648
- (out.fail if require else out.warn)(f"[{arch}] installer is not Authenticode-signed")
663
+ (out.fail if require else out.warn)(f"[{slot}] installer is not Authenticode-signed")
649
664
  elif sig.status in ("invalid", "untrusted"):
650
- out.fail(f"[{arch}] signature {sig.status}: {sig.detail}")
665
+ out.fail(f"[{slot}] signature {sig.status}: {sig.detail}")
651
666
  else:
652
- out.warn(f"[{arch}] signature could not be verified here: {sig.detail}")
667
+ out.warn(f"[{slot}] signature could not be verified here: {sig.detail}")
653
668
 
654
669
 
655
670
  # =========================================================================== 11
@@ -659,23 +674,24 @@ def authenticode(ctx: Context, target: dict, out: Outcome) -> None:
659
674
  def checksum(ctx: Context, target: dict, out: Outcome) -> None:
660
675
  for item in _targets_or_skip(ctx, target, out):
661
676
  arch = item["arch"]
662
- file = _artifact_file(ctx, target, arch)
677
+ slot = _slot(item)
678
+ file = _artifact_file(ctx, target, slot)
663
679
  if not file:
664
- out.skip(f"[{arch}] no payload (see STEP 09)")
680
+ out.skip(f"[{slot}] no payload (see STEP 09)")
665
681
  continue
666
- art = ctx.artifact(target, arch)
682
+ art = ctx.artifact(target, slot)
667
683
  disk = net.sha256_file(file)
668
684
  art["sha256"] = disk
669
685
  stream = art.get("stream_sha256")
670
686
  if stream and stream != disk:
671
- out.fail(f"[{arch}] streamed hash {stream} differs from on-disk hash {disk} - payload changed on disk")
687
+ out.fail(f"[{slot}] streamed hash {stream} differs from on-disk hash {disk} - payload changed on disk")
672
688
  continue
673
689
  declared = str(item["source"]["sha256"]).upper()
674
690
  if hmac.compare_digest(declared, disk):
675
691
  passes = "2 independent passes" if stream else "1 pass"
676
- out.ok(f"[{arch}] SHA-256 {disk} matches the manifest ({passes}, {file.stat().st_size} bytes)")
692
+ out.ok(f"[{slot}] SHA-256 {disk} matches the manifest ({passes}, {file.stat().st_size} bytes)")
677
693
  else:
678
- out.fail(f"[{arch}] SHA-256 mismatch - manifest {declared}, actual {disk}")
694
+ out.fail(f"[{slot}] SHA-256 mismatch - manifest {declared}, actual {disk}")
679
695
 
680
696
 
681
697
  # =========================================================================== 12
@@ -684,24 +700,25 @@ def checksum(ctx: Context, target: dict, out: Outcome) -> None:
684
700
  def _check_portable(item: dict, file: Path, found: engines.Inspection, out: Outcome) -> None:
685
701
  """Portable ZIP: safe to unpack, declared strip/PATH folders hold programs, CPU matches."""
686
702
  arch = item["arch"]
703
+ slot = _slot(item)
687
704
  if found.format != "zip":
688
- out.fail(f"[{arch}] engine 'portable' declared but the payload is {found.label}")
705
+ out.fail(f"[{slot}] engine 'portable' declared but the payload is {found.label}")
689
706
  return
690
707
  if item["engine"] != "portable":
691
- out.fail(f"[{arch}] the payload is a ZIP archive - declare engine: portable")
708
+ out.fail(f"[{slot}] the payload is a ZIP archive - declare engine: portable")
692
709
  return
693
710
  spec = item["portable"]
694
711
  strip, folders = int(spec.get("strip", 0)), spec["path"]
695
712
  try:
696
713
  by_folder = portable.exes(file, strip)
697
714
  except portable.ZipProblem as exc:
698
- out.fail(f"[{arch}] unsafe archive: {exc}")
715
+ out.fail(f"[{slot}] unsafe archive: {exc}")
699
716
  return
700
717
  ok = True
701
718
  for folder in folders:
702
719
  if folder not in by_folder:
703
720
  hint = f" (found programs in: {', '.join(by_folder)})" if by_folder else " (the archive has no .exe)"
704
- out.fail(f"[{arch}] PATH folder '{folder}' has no .exe after strip={strip}{hint}")
721
+ out.fail(f"[{slot}] PATH folder '{folder}' has no .exe after strip={strip}{hint}")
705
722
  ok = False
706
723
  if not ok:
707
724
  return
@@ -713,7 +730,7 @@ def _check_portable(item: dict, file: Path, found: engines.Inspection, out: Outc
713
730
  try:
714
731
  machine = pe.read_pe(sample, with_version=False).machine if sample else None
715
732
  except pe.PEError as exc:
716
- out.fail(f"[{arch}] {entry.parts[-1]}: {exc}")
733
+ out.fail(f"[{slot}] {entry.parts[-1]}: {exc}")
717
734
  return
718
735
  finally:
719
736
  if sample:
@@ -722,20 +739,21 @@ def _check_portable(item: dict, file: Path, found: engines.Inspection, out: Outc
722
739
  layout = found.layout
723
740
  summary = f"{layout.files} files, {layout.unpacked / 1048576:.0f} MiB unpacked, PATH {', '.join(folders)} → {programs}"
724
741
  if machine == arch:
725
- out.ok(f"[{arch}] portable ZIP, native {machine} programs; {summary}")
742
+ out.ok(f"[{slot}] portable ZIP, native {machine} programs; {summary}")
726
743
  elif machine == "x86" and arch in ("x64", "arm64"):
727
- out.warn(f"[{arch}] portable ZIP holds 32-bit programs; {summary}")
744
+ out.warn(f"[{slot}] portable ZIP holds 32-bit programs; {summary}")
728
745
  else:
729
- out.fail(f"[{arch}] programs in '{folders[0]}' are {machine}, which cannot be declared as {arch}")
746
+ out.fail(f"[{slot}] programs in '{folders[0]}' are {machine}, which cannot be declared as {arch}")
730
747
 
731
748
 
732
749
  @step(12)
733
750
  def binary(ctx: Context, target: dict, out: Outcome) -> None:
734
751
  for item in _targets_or_skip(ctx, target, out):
735
752
  arch, engine = item["arch"], item["engine"]
736
- file = _artifact_file(ctx, target, arch)
753
+ slot = _slot(item)
754
+ file = _artifact_file(ctx, target, slot)
737
755
  if not file:
738
- out.skip(f"[{arch}] no payload (see STEP 09)")
756
+ out.skip(f"[{slot}] no payload (see STEP 09)")
739
757
  continue
740
758
  found = engines.inspect(file)
741
759
  record = {"format": found.format, "engine": found.engine, "label": found.label,
@@ -743,44 +761,44 @@ def binary(ctx: Context, target: dict, out: Outcome) -> None:
743
761
  if found.pe:
744
762
  record.update({"os_version": list(found.pe.os_version), "subsystem_version": list(found.pe.subsystem_version),
745
763
  "product_version": found.product_version, "company": found.company})
746
- ctx.artifact(target, arch)["inspection"] = record
764
+ ctx.artifact(target, slot)["inspection"] = record
747
765
  for note in found.notes:
748
- out.info(f"[{arch}] {note}")
766
+ out.info(f"[{slot}] {note}")
749
767
  if found.format == "unknown":
750
- out.fail(f"[{arch}] unsupported payload format ({found.label})")
768
+ out.fail(f"[{slot}] unsupported payload format ({found.label})")
751
769
  continue
752
770
  if engine == "portable" or found.format == "zip":
753
771
  _check_portable(item, file, found, out)
754
772
  continue
755
773
  if engine == "msi" and found.format != "msi":
756
- out.fail(f"[{arch}] engine 'msi' declared but the payload is a {found.label}")
774
+ out.fail(f"[{slot}] engine 'msi' declared but the payload is a {found.label}")
757
775
  continue
758
776
  if engine != "msi" and found.format == "msi":
759
- out.fail(f"[{arch}] payload is a Windows Installer package - declare engine: msi")
777
+ out.fail(f"[{slot}] payload is a Windows Installer package - declare engine: msi")
760
778
  continue
761
779
  if engine != "msi":
762
780
  if found.engine == engine:
763
781
  pass
764
782
  elif engine == "exe":
765
783
  if found.engine != "exe":
766
- out.warn(f"[{arch}] detected {found.label} - declare engine: {found.engine} to get verified default switches")
784
+ out.warn(f"[{slot}] detected {found.label} - declare engine: {found.engine} to get verified default switches")
767
785
  else:
768
- out.fail(f"[{arch}] engine '{engine}' declared but {found.label} detected")
786
+ out.fail(f"[{slot}] engine '{engine}' declared but {found.label} detected")
769
787
  continue
770
788
  if found.format == "msi":
771
789
  if found.payload_arch and found.payload_arch != arch:
772
- out.fail(f"[{arch}] MSI template targets {found.payload_arch}, manifest says {arch}")
790
+ out.fail(f"[{slot}] MSI template targets {found.payload_arch}, manifest says {arch}")
773
791
  continue
774
- out.ok(f"[{arch}] {found.label}, template '{found.msi.get('template')}'")
792
+ out.ok(f"[{slot}] {found.label}, template '{found.msi.get('template')}'")
775
793
  continue
776
794
  machine = found.machine
777
795
  if machine == arch:
778
- out.ok(f"[{arch}] native {machine} PE, engine {found.label}")
796
+ out.ok(f"[{slot}] native {machine} PE, engine {found.label}")
779
797
  elif machine == "x86" and arch in ("x64", "arm64"):
780
- note = f"[{arch}] 32-bit {found.label} bootstrapper installing {arch} payload"
798
+ note = f"[{slot}] 32-bit {found.label} bootstrapper installing {arch} payload"
781
799
  (out.warn if engine == "exe" else out.ok)(note + ("" if engine != "exe" else " - confirm manually"))
782
800
  else:
783
- out.fail(f"[{arch}] PE machine is {machine}, which cannot be declared as {arch}")
801
+ out.fail(f"[{slot}] PE machine is {machine}, which cannot be declared as {arch}")
784
802
 
785
803
 
786
804
  # =========================================================================== 13
@@ -808,14 +826,15 @@ def os_compat(ctx: Context, target: dict, out: Outcome) -> None:
808
826
  out.fail(f"min_build {text} predates Windows 7 - not supported by TXA")
809
827
  for item in items:
810
828
  arch = item["arch"]
829
+ slot = _slot(item)
811
830
  if arch == "arm64" and declared < winos.ARM64_FLOOR:
812
831
  out.fail(f"[arm64] arm64 desktop apps need {winos.fmt(winos.ARM64_FLOOR)} or newer, min_build is {text}")
813
- inspection = ctx.artifact(target, arch).get("inspection") or {}
832
+ inspection = ctx.artifact(target, slot).get("inspection") or {}
814
833
  needs = max(tuple(inspection.get("os_version") or (0, 0)), tuple(inspection.get("subsystem_version") or (0, 0)))
815
834
  if needs > declared[:2]:
816
- out.fail(f"[{arch}] binary header requires Windows NT {needs[0]}.{needs[1]}, but min_build says {text}")
835
+ out.fail(f"[{slot}] binary header requires Windows NT {needs[0]}.{needs[1]}, but min_build says {text}")
817
836
  elif inspection.get("format") == "pe":
818
- out.ok(f"[{arch}] PE header needs NT {needs[0]}.{needs[1]} ≤ declared {declared[0]}.{declared[1]}")
837
+ out.ok(f"[{slot}] PE header needs NT {needs[0]}.{needs[1]} ≤ declared {declared[0]}.{declared[1]}")
819
838
  where = "below" if declared < floor else "at/above"
820
839
  out.ok(f"min_build {text} = {winos.describe(declared)} ({where} TXA floor {winos.fmt(floor)})")
821
840
 
@@ -827,8 +846,9 @@ def os_compat(ctx: Context, target: dict, out: Outcome) -> None:
827
846
  def switches(ctx: Context, target: dict, out: Outcome) -> None:
828
847
  for item in _targets_or_skip(ctx, target, out):
829
848
  arch, engine = item["arch"], item["engine"]
849
+ slot = _slot(item)
830
850
  if engine == "portable":
831
- out.ok(f"[{arch}] portable: txapm unpacks the archive and edits PATH - nothing is executed, no switches")
851
+ out.ok(f"[{slot}] portable: txapm unpacks the archive and edits PATH - nothing is executed, no switches")
832
852
  continue
833
853
  effective = engines.effective_switches(item)
834
854
  errors, warnings = engines.check_switches(engine, effective)
@@ -838,9 +858,9 @@ def switches(ctx: Context, target: dict, out: Outcome) -> None:
838
858
  if codes and 0 not in codes:
839
859
  warnings.append("success_codes does not include 0")
840
860
  for error in errors:
841
- out.fail(f"[{arch}] {error}")
861
+ out.fail(f"[{slot}] {error}")
842
862
  for warning in warnings:
843
- out.warn(f"[{arch}] {warning}")
863
+ out.warn(f"[{slot}] {warning}")
844
864
  if not errors:
845
865
  source = "declared" if item.get("switches") else "TXA defaults"
846
- out.ok(f"[{arch}] {engine}: silent '{effective['silent']}', progress '{effective['progress']}' ({source})")
866
+ out.ok(f"[{slot}] {engine}: silent '{effective['silent']}', progress '{effective['progress']}' ({source})")
@@ -175,6 +175,19 @@ def main(argv: list[str] | None = None) -> int:
175
175
  if first in ("scan", "installed", "ls") and len(args_list) == 1:
176
176
  do_scan(_resolve_repo_root(None))
177
177
  return 0
178
+ if first == "prune":
179
+ from txa.core import retention
180
+
181
+ ap = console.SmartArgumentParser(prog="txacli prune", description="Keep only the newest versions of every package")
182
+ ap.add_argument("-r", "--repo", default=None, help="Repository root containing manifests/ (default: current repo)")
183
+ ap.add_argument("--keep", type=int, default=retention.KEEP, help=f"versions to keep per package (default {retention.KEEP})")
184
+ ap.add_argument("--dry-run", action="store_true", help="only list what would be removed")
185
+ parsed = ap.parse_args(args_list[1:])
186
+ report = retention.prune_repo(_resolve_repo_root(parsed.repo), parsed.keep, parsed.dry_run)
187
+ for package, versions in report.items():
188
+ console.say(f" {package}: {'would remove' if parsed.dry_run else 'removed'} {', '.join(versions)}")
189
+ console.say(f"\n✓ {len(report)} package(s) had more than {parsed.keep} versions.")
190
+ return 0
178
191
  if first in ("sync", "update-all", "auto-update"):
179
192
  ap = console.SmartArgumentParser(prog="txacli sync", description="Auto-update all managed TXAVL packages in repo")
180
193
  ap.add_argument("package", nargs="?", default=None, help="Optional single package to check (e.g. Chrome)")
@@ -0,0 +1,40 @@
1
+ """How many versions of a package the repository keeps: the newest ``KEEP``; adding one drops the oldest."""
2
+ from __future__ import annotations
3
+
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ from txa.core import semver
8
+
9
+ KEEP = 10
10
+
11
+
12
+ def stale_versions(versions: list[str], keep: int = KEEP, protect: str | None = None) -> list[str]:
13
+ """Versions beyond the newest ``keep`` (oldest first). ``protect`` (a version being added) is never returned."""
14
+ valid = sorted((v for v in set(versions) if semver.is_valid(v)), key=semver.parse, reverse=True)
15
+ return [v for v in reversed(valid[keep:]) if v != protect]
16
+
17
+
18
+ def prune_package(package_dir: Path, keep: int = KEEP) -> list[str]:
19
+ """Delete the oldest release folders of one package; returns the versions removed."""
20
+ versions = [d.name for d in package_dir.iterdir() if d.is_dir() and semver.is_valid(d.name)] if package_dir.is_dir() else []
21
+ removed = stale_versions(versions, keep)
22
+ for version in removed:
23
+ shutil.rmtree(package_dir / version, ignore_errors=True)
24
+ return removed
25
+
26
+
27
+ def prune_repo(root: Path, keep: int = KEEP, dry_run: bool = False) -> dict[str, list[str]]:
28
+ """Apply the rule to every package under ``<root>/manifests``."""
29
+ report: dict[str, list[str]] = {}
30
+ for package_dir in sorted((root / "manifests").glob("*/*/*")):
31
+ if not package_dir.is_dir():
32
+ continue
33
+ versions = [d.name for d in package_dir.iterdir() if d.is_dir() and semver.is_valid(d.name)]
34
+ stale = stale_versions(versions, keep)
35
+ if stale:
36
+ report[f"{package_dir.parent.name}.{package_dir.name}"] = stale
37
+ if not dry_run:
38
+ for version in stale:
39
+ shutil.rmtree(package_dir / version, ignore_errors=True)
40
+ return report
@@ -60,6 +60,25 @@ def current() -> tuple[int, int, int] | None:
60
60
  return ver.major, ver.minor, ver.build
61
61
 
62
62
 
63
+ def ui_language() -> str:
64
+ """Two-letter display language of this PC ("vi", "en", ...); TXA_UI_LANG overrides it."""
65
+ forced = os.environ.get("TXA_UI_LANG", "").strip().lower()
66
+ if forced:
67
+ return forced.split("-")[0]
68
+ if sys.platform == "win32":
69
+ try:
70
+ import ctypes
71
+ import locale
72
+
73
+ langid = ctypes.windll.kernel32.GetUserDefaultUILanguage()
74
+ name = locale.windows_locale.get(langid, "")
75
+ if name:
76
+ return name.split("_")[0].lower()
77
+ except (AttributeError, OSError):
78
+ pass
79
+ return "en"
80
+
81
+
63
82
  def native_arch() -> str:
64
83
  """Real CPU architecture, even when this process runs under emulation."""
65
84
  if sys.platform == "win32":
@@ -4,7 +4,9 @@ from __future__ import annotations
4
4
  import time
5
5
  from dataclasses import dataclass
6
6
 
7
+ from txa.core import retention
7
8
  from txa.core.github import GitHub, GitHubError
9
+ from txa.core.manifest import package_dir
8
10
 
9
11
 
10
12
  @dataclass
@@ -42,6 +44,21 @@ def _free_branch(gh: GitHub, repo: str, name: str) -> str:
42
44
  return candidate
43
45
 
44
46
 
47
+ def stale_paths(gh: GitHub, repo: str, base_tree: str, package_id: str, version: str) -> list[str]:
48
+ """Files of the oldest releases that must go so that, with ``version`` added, only the newest KEEP remain."""
49
+ prefix = package_dir(package_id).rstrip("/") + "/"
50
+ try:
51
+ listing = gh.get(f"repos/{repo}/git/trees/{base_tree}", params={"recursive": "1"})
52
+ except GitHubError:
53
+ return []
54
+ by_version: dict[str, list[str]] = {}
55
+ for entry in listing.get("tree", []):
56
+ if entry.get("type") == "blob" and entry["path"].startswith(prefix):
57
+ by_version.setdefault(entry["path"][len(prefix):].split("/")[0], []).append(entry["path"])
58
+ by_version.setdefault(version, [])
59
+ return [path for stale in retention.stale_versions(list(by_version), protect=version) for path in by_version[stale]]
60
+
61
+
45
62
  def submit(gh: GitHub, upstream: str, login: str, package_id: str, version: str, files: dict[str, str],
46
63
  title: str, body: str, direct: bool = False, log=print) -> Submission:
47
64
  """`files` maps repo-relative paths to file contents."""
@@ -67,10 +84,12 @@ def submit(gh: GitHub, upstream: str, login: str, package_id: str, version: str,
67
84
 
68
85
  base_sha = _wait_for_branch(gh, head_repo, base_branch, 30)
69
86
  base_tree = gh.get(f"repos/{head_repo}/git/commits/{base_sha}")["tree"]["sha"]
70
- tree = gh.post(f"repos/{head_repo}/git/trees", json={
71
- "base_tree": base_tree,
72
- "tree": [{"path": path, "mode": "100644", "type": "blob", "content": text} for path, text in sorted(files.items())],
73
- })
87
+ entries = [{"path": path, "mode": "100644", "type": "blob", "content": text} for path, text in sorted(files.items())]
88
+ dropped = stale_paths(gh, head_repo, base_tree, package_id, version)
89
+ entries += [{"path": path, "mode": "100644", "type": "blob", "sha": None} for path in dropped]
90
+ if dropped:
91
+ log(f"→ the repository keeps the newest {retention.KEEP} versions - removing the oldest ({len(dropped)} file(s))")
92
+ tree = gh.post(f"repos/{head_repo}/git/trees", json={"base_tree": base_tree, "tree": entries})
74
93
  commit = gh.post(f"repos/{head_repo}/git/commits", json={
75
94
  "message": f"{title}\n\nSubmitted with txacreate.",
76
95
  "tree": tree["sha"],
@@ -12,7 +12,7 @@ from typing import Any
12
12
 
13
13
  import yaml
14
14
 
15
- from txa.core import config, licenses
15
+ from txa.core import config, licenses, retention
16
16
 
17
17
  ENGINE_MAP = {
18
18
  "inno": "inno",
@@ -916,9 +916,7 @@ def sync_txavl_packages(
916
916
  )
917
917
  save_draft_manifests(draft, root, dry_run=False)
918
918
  if not keep_old:
919
- for old_d in ver_dirs:
920
- if old_d.name != new_ver:
921
- shutil.rmtree(old_d, ignore_errors=True)
919
+ retention.prune_package(ver_dirs[0].parent) # newest 10 stay, the oldest go
922
920
  updated.append(f"{pkg_id} ({current_ver} -> {new_ver})")
923
921
  continue
924
922
 
@@ -971,9 +969,7 @@ def sync_txavl_packages(
971
969
  console.say(f" {console.paint('[UP]', 'green', 'bold')} {pkg_id}: {current_ver} -> {new_ver} (from {wg_id})")
972
970
  save_draft_manifests(draft, root, dry_run=dry_run)
973
971
  if not dry_run and not keep_old:
974
- for old_d in ver_dirs:
975
- if old_d.name != new_ver:
976
- shutil.rmtree(old_d, ignore_errors=True)
972
+ retention.prune_package(ver_dirs[0].parent) # newest 10 stay, the oldest go
977
973
  updated.append(f"{pkg_id} ({current_ver} -> {new_ver})")
978
974
 
979
975
  return {"updated": updated, "up_to_date": up_to_date, "skipped": skipped, "failed": failed}
@@ -24,7 +24,7 @@ from datetime import datetime, timezone
24
24
  from pathlib import Path
25
25
 
26
26
  from txa import __version__
27
- from txa.core import config, console, net, semver, winos
27
+ from txa.core import config, console, net, retention, semver, winos
28
28
  from txa.pm import installer, uninstall
29
29
  from txa.pm.installer import InstallError
30
30
  from txa.pm.source import LocalRelease, NotFound, Source, SourceError, Sources, check_url
@@ -244,6 +244,11 @@ def cmd_install(args) -> int:
244
244
  if waiting:
245
245
  return _refuse_pending(*waiting)
246
246
  src, package_id = _pick(args, args.package)
247
+ if getattr(args, "choose", False) and not args.version:
248
+ chosen = _choose_version(src, package_id)
249
+ if chosen is None:
250
+ return 1
251
+ args.version = chosen
247
252
  return _install(src, package_id, args.version, args)
248
253
 
249
254
 
@@ -569,6 +574,44 @@ def _show_waiting(source: Source, entry: dict) -> None:
569
574
  console.say("! it cannot be installed until a Contributor approves the pull request")
570
575
 
571
576
 
577
+ def _version_rows(src: Source, package_id: str) -> list[dict]:
578
+ """Every version kept in the repository, newest first, with the CPUs/languages it ships and whether it is installed."""
579
+ versions = sorted(src.versions(package_id), key=lambda v: semver.parse(v) if semver.is_valid(v) else (0, 0, 0), reverse=True)
580
+ installed = (installer.installed().get(package_id) or {}).get("version")
581
+ rows = []
582
+ for index, version in enumerate(versions):
583
+ try:
584
+ _, cards = src.release(package_id, version)
585
+ targets = cards["build"]["targets"]
586
+ ships = ", ".join(dict.fromkeys(t["arch"] + (f" {t['locale']}" if t.get("locale") else "") for t in targets))
587
+ except Exception: # noqa: BLE001 - a broken old release must not hide the others
588
+ ships = "?"
589
+ rows.append({"version": version, "latest": index == 0, "installed": version == installed, "ships": ships})
590
+ return rows
591
+
592
+
593
+ def _print_versions(src: Source, package_id: str) -> None:
594
+ rows = _version_rows(src, package_id)
595
+ print(console.head(f"{package_id} - {len(rows)} version(s) in the repository (the newest {retention.KEEP} are kept)"))
596
+ for row in rows:
597
+ marks = " ".join(m for m, on in (("latest", row["latest"]), ("installed", row["installed"])) if on)
598
+ print(f" {C(row['version'], 14, 'green', 'bold')} {C(row['ships'], 28, 'yellow')} {P(marks, 'cyan')}")
599
+ console.say(f"install one with {P('txapm install ' + package_id + ' --version <version>', 'bold')} or pick from a list with {P('--choose', 'bold')}")
600
+
601
+
602
+ def _choose_version(src: Source, package_id: str) -> str | None:
603
+ rows = _version_rows(src, package_id)
604
+ if len(rows) == 1:
605
+ return rows[0]["version"]
606
+ if not console._raw_available():
607
+ _print_versions(src, package_id)
608
+ _die("--choose needs an interactive terminal; pass --version <version> instead")
609
+ return None
610
+ options = [console.Option(r["version"], r["version"], " ".join(m for m, on in (("latest", r["latest"]), ("installed", r["installed"])) if on)
611
+ or r["ships"]) for r in rows]
612
+ return console.choose(f"Which version of {package_id} do you want to install?", "version", options).value
613
+
614
+
572
615
  def cmd_show(args) -> int:
573
616
  try:
574
617
  src, package_id = _pick(args, args.package)
@@ -581,7 +624,7 @@ def cmd_show(args) -> int:
581
624
  return 0
582
625
  build, about = cards["build"], _about(cards, package_id)
583
626
  if args.versions:
584
- print("\n".join(P(v, "green") for v in src.versions(package_id)))
627
+ _print_versions(src, package_id)
585
628
  return 0
586
629
  minimum = winos.parse_build(build["platform"]["min_build"])
587
630
  print(f"{P(about['name'], 'bold', 'cyan')} {P(version, 'green', 'bold')} {P('(' + package_id + ')', 'gray')}"
@@ -594,7 +637,7 @@ def cmd_show(args) -> int:
594
637
  print(f" {console.label('homepage')}{P(about['homepage'], 'cyan')}")
595
638
  print(f" {console.label('windows')}{build['platform']['min_build']}+ ({winos.describe(minimum)}) · scope {build.get('scope', 'machine')}")
596
639
  for target in build["targets"]:
597
- arch_tag = P("[" + target["arch"] + "]", "yellow", "bold")
640
+ arch_tag = P("[" + target["arch"] + (" " + target["locale"] if target.get("locale") else "") + "]", "yellow", "bold")
598
641
  engine_tag = P(target["engine"].ljust(5), "magenta")
599
642
  print(f" {arch_tag} {engine_tag} {P(target['source']['url'], 'cyan')}")
600
643
  print(f" {P('sha256', 'gray')} {target['source']['sha256']}")
@@ -941,6 +984,7 @@ def main(argv: list[str] | None = None) -> int:
941
984
  p.add_argument("package", nargs="?", help="package id (TXAVL.HelloTool) or alias")
942
985
  p.add_argument("--manifest", metavar="FOLDER", help="install from a local manifest folder (to test it before submitting)")
943
986
  p.add_argument("--version", dest="version", help="install this X.Y.Z instead of the newest")
987
+ p.add_argument("--choose", action="store_true", help="pick the version from the list of versions in the repository")
944
988
  p.add_argument("--download-only", action="store_true", help="stop after downloading and verifying")
945
989
  _install_options(p)
946
990
  p.set_defaults(func=cmd_install)
@@ -30,17 +30,35 @@ class InstallError(Exception):
30
30
  pass
31
31
 
32
32
 
33
- def pick_target(build: dict, arch: str | None = None) -> dict:
34
- targets = {t["arch"]: t for t in build.get("targets", [])}
33
+ def _by_language(candidates: list[dict], language: str) -> dict:
34
+ """Among installers of one CPU, the one built for this display language, else the one without a language."""
35
+ for target in candidates:
36
+ if (target.get("locale") or "").split("-")[0].lower() == language:
37
+ return target
38
+ for target in candidates:
39
+ if not target.get("locale"):
40
+ return target
41
+ for target in candidates:
42
+ if (target.get("locale") or "").lower().startswith("en"):
43
+ return target
44
+ return candidates[0]
45
+
46
+
47
+ def pick_target(build: dict, arch: str | None = None, language: str | None = None) -> dict:
48
+ """The installer for this CPU (``arch`` forces one) and, when a CPU has several, for the PC's display language."""
49
+ groups: dict[str, list[dict]] = {}
50
+ for target in build.get("targets", []):
51
+ groups.setdefault(target["arch"], []).append(target)
52
+ language = (language or winos.ui_language()).split("-")[0].lower()
35
53
  if arch:
36
- if arch not in targets:
37
- raise InstallError(f"no {arch} installer (available: {', '.join(targets)})")
38
- return targets[arch]
54
+ if arch not in groups:
55
+ raise InstallError(f"no {arch} installer (available: {', '.join(groups)})")
56
+ return _by_language(groups[arch], language)
39
57
  native = winos.native_arch()
40
58
  for candidate in winos.arch_preference(native):
41
- if candidate in targets:
42
- return targets[candidate]
43
- raise InstallError(f"no installer runs on {native} (available: {', '.join(targets)})")
59
+ if candidate in groups:
60
+ return _by_language(groups[candidate], language)
61
+ raise InstallError(f"no installer runs on {native} (available: {', '.join(groups)})")
44
62
 
45
63
 
46
64
  def check_os(build: dict) -> None:
@@ -31,7 +31,7 @@
31
31
  "targets": {
32
32
  "type": "array",
33
33
  "minItems": 1,
34
- "maxItems": 3,
34
+ "maxItems": 8,
35
35
  "items": { "$ref": "#/$defs/target" }
36
36
  }
37
37
  },
@@ -44,6 +44,11 @@
44
44
  "required": ["arch", "engine", "source"],
45
45
  "properties": {
46
46
  "arch": { "enum": ["x64", "x86", "arm64"] },
47
+ "locale": {
48
+ "type": "string",
49
+ "pattern": "^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$",
50
+ "description": "Optional: this installer is for machines whose display language starts with this tag (vi, en...). Give one without a locale as the fallback."
51
+ },
47
52
  "engine": { "enum": ["inno", "nsis", "msi", "wix", "exe", "portable"] },
48
53
  "source": {
49
54
  "type": "object",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: txa
3
- Version: 1.3.2
3
+ Version: 1.4.0
4
4
  Summary: TXA package manager toolchain: txapm (install), txacreate (publish), txaci (16-step validator), txacli (WinGet & repo CLI)
5
5
  Author: TXA Software Dev
6
6
  License: MIT
@@ -32,6 +32,7 @@ src/txa/core/manifest.py
32
32
  src/txa/core/net.py
33
33
  src/txa/core/pe.py
34
34
  src/txa/core/portable.py
35
+ src/txa/core/retention.py
35
36
  src/txa/core/semver.py
36
37
  src/txa/core/signing.py
37
38
  src/txa/core/userpath.py
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes