Repository navigation
Expand file tree
/
Copy pathbuild_pcm.py
More file actions
1484 lines (1151 loc) · 35.7 KB
/
Copy pathbuild_pcm.py
File metadata and controls
1484 lines (1151 loc) · 35.7 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 argparse
import copy
import datetime
import hashlib
import json
import os
import zipfile
from io import BytesIO
from pathlib import Path
PCM_DIR = "pcm"
RELEASES_DIR = "releases"
DEFAULT_BRANCH = os.environ.get("WAYRICAD_BRANCH", "develop")
DEFAULT_RELEASE_TAG = os.environ.get("WAYRICAD_RELEASE_TAG", "5.1.0")
REPO_OWNER = "wayri"
REPO_NAME = "WayriCAD"
GITHUB_PROFILE = "https://github.com/wayri"
REPO_HOMEPAGE = f"https://github.com/{REPO_OWNER}/{REPO_NAME}"
REPO_URL_BASE = f"{REPO_HOMEPAGE}/releases/download"
PCM_SCHEMA = "https://go.kicad.org/pcm/schemas/v2"
SUPPORTED_RUNTIMES = {"swig", "ipc"}
# Fixed zip entry timestamp so identical inputs produce byte-identical
# archives (zipfile.writestr otherwise embeds the current time, which
# makes every rebuild change package/resource hashes and dirty the feed).
FIXED_ZIP_TIME = (1980, 1, 1, 0, 0, 0)
def zip_entry(name, compress_type=zipfile.ZIP_STORED, mode=0o644):
info = zipfile.ZipInfo(name, date_time=FIXED_ZIP_TIME)
info.compress_type = compress_type
info.external_attr = mode << 16
info.create_system = 3
return info
# KiCad PCM v1 uses the older SPDX spelling for this license.
PCM_LICENSE_ALIASES = {
"GPL-3.0-only": "GPL-3.0",
}
def calculate_sha256(file_path):
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(1024 * 1024), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def load_json(path):
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def atomic_write_json(path, data):
path = Path(path)
tmp_path = path.with_suffix(path.suffix + ".tmp")
with open(tmp_path, "w", encoding="utf-8", newline="\n") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
f.write("\n")
os.replace(tmp_path, path)
def discover_plugins(base_path):
return sorted(
path
for path in base_path.iterdir()
if path.is_dir() and (path / "metadata.json").exists()
)
def plugin_files(plugin_path):
"""Yield distributable production files in deterministic order."""
excluded = {"__pycache__", ".git", ".vscode", ".pytest_cache", "tests",
"tools", "scripts", "docs", "examples", "node_modules"}
if plugin_path.name in {"protocol_constraint_composer_plugin", "quick_therm_plugin"}:
excluded -= {"docs", "examples"}
if plugin_path.name in {"bom_studio_plugin", "manufacturing_readiness_plugin", "heater_designer_plugin", "quick_pi_plugin"}:
excluded.discard("examples")
for root, dirs, files in os.walk(plugin_path):
dirs[:] = sorted(d for d in dirs if d not in excluded and not d.startswith("."))
for name in sorted(files):
if name.startswith(".") or name.endswith((".pyc", ".pyo", ".log")):
continue
source = Path(root) / name
if source.relative_to(plugin_path).as_posix() == "__init__.py":
continue
yield source
def bundle_assistant_backends(archive, base_path):
"""Place inert providers beside this package's private shared runtime."""
for backend in discover_plugins(base_path):
if backend.name == "suite_assistant_plugin":
continue
prefix = "plugins/" + backend.name + "/"
for source in plugin_files(backend):
relative = source.relative_to(backend).as_posix()
if relative == "plugin.json":
continue
archive.writestr(zip_entry(prefix + relative,
compress_type=zipfile.ZIP_DEFLATED), source.read_bytes())
version = load_json(backend / "metadata.json")["versions"][0]["version"]
initializer = ('"""Backend package; editor actions are not registered here."""\n'
+ "__version__ = " + repr(version) + "\n")
archive.writestr(zip_entry(prefix + "__init__.py", compress_type=zipfile.ZIP_DEFLATED),
initializer)
if not (backend / "LICENSE").is_file():
archive.writestr(zip_entry(prefix + "LICENSE"), (base_path / "LICENSE").read_bytes())
def normalize_runtime(version_info):
"""Normalize old runtime names to KiCad PCM v1 runtime values."""
normalized = dict(version_info)
if normalized.get("runtime") == "action-plugin":
normalized["runtime"] = "swig"
runtime = normalized.get("runtime", "swig")
if runtime not in SUPPORTED_RUNTIMES:
raise ValueError(
f"Unsupported KiCad PCM runtime: {runtime!r}. "
f"Expected one of {sorted(SUPPORTED_RUNTIMES)}."
)
normalized["runtime"] = runtime
return normalized
def normalize_author(author, plugin_path):
"""Ensure author data satisfies KiCad PCM v1."""
if not isinstance(author, dict):
raise ValueError(f"{plugin_path}: 'author' must be a JSON object.")
normalized = copy.deepcopy(author)
name = normalized.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"{plugin_path}: 'author.name' is required.")
contact = normalized.get("contact")
if contact is None:
contact = {}
elif not isinstance(contact, dict):
raise ValueError(
f"{plugin_path}: 'author.contact' must be a JSON object."
)
# All WayriCAD packages use the same repository maintainer.
if not contact:
contact = {"github": GITHUB_PROFILE}
normalized["contact"] = contact
return normalized
def normalize_license(license_name, plugin_path):
if not isinstance(license_name, str) or not license_name.strip():
raise ValueError(f"{plugin_path}: 'license' is required.")
normalized = PCM_LICENSE_ALIASES.get(license_name, license_name)
if normalized != license_name:
print(
f" Normalized PCM license for {plugin_path.name}: "
f"{license_name!r} -> {normalized!r}"
)
return normalized
def require_string(metadata, key, plugin_path):
value = metadata.get(key)
if not isinstance(value, str) or not value.strip():
raise ValueError(
f"{plugin_path}: required string field {key!r} is missing."
)
return value
def normalize_metadata(metadata, plugin_path, branch):
"""
Return PCM-safe metadata without changing the source dictionary.
The same normalized metadata is used for pcm/pkgs.json and for the
metadata.json embedded in each generated package ZIP.
"""
if not isinstance(metadata, dict):
raise ValueError(
f"{plugin_path}: metadata.json root must be an object."
)
normalized = copy.deepcopy(metadata)
normalized["$schema"] = PCM_SCHEMA
for key in (
"name",
"description",
"description_full",
"identifier",
"type",
"license",
):
require_string(normalized, key, plugin_path)
normalized["author"] = normalize_author(
normalized.get("author"),
plugin_path,
)
normalized["license"] = normalize_license(
normalized["license"],
plugin_path,
)
versions = normalized.get("versions")
if not isinstance(versions, list) or not versions:
raise ValueError(
f"{plugin_path}: 'versions' must be a non-empty array."
)
normalized_versions = []
for index, version in enumerate(versions):
if not isinstance(version, dict):
raise ValueError(
f"{plugin_path}: versions[{index}] must be a JSON object."
)
version = normalize_runtime(version)
if (
not isinstance(version.get("version"), str)
or not version["version"].strip()
):
raise ValueError(
f"{plugin_path}: versions[{index}].version is required."
)
if (
not isinstance(version.get("status"), str)
or not version["status"].strip()
):
raise ValueError(
f"{plugin_path}: versions[{index}].status is required."
)
if (
not isinstance(version.get("kicad_version"), str)
or not version["kicad_version"].strip()
):
raise ValueError(
f"{plugin_path}: versions[{index}].kicad_version is required."
)
normalized_versions.append(version)
normalized["versions"] = normalized_versions
resources = normalized.get("resources")
if resources is None:
resources = {}
elif not isinstance(resources, dict):
raise ValueError(
f"{plugin_path}: 'resources' must be a JSON object."
)
resources = copy.deepcopy(resources)
resources.setdefault(
"homepage",
REPO_HOMEPAGE,
)
# IMPORTANT:
#
# KiCad does NOT use a per-package URL here for icons shown in
# Plugin and Content Manager.
#
# Those icons come from the separate repository-level resources.zip.
#
# The package itself will still contain:
#
# resources/icon.png
#
# for use after installation.
resources.pop("icon", None)
normalized["resources"] = resources
return normalized
def get_pcm_icon_bytes(icon_path):
"""
Return a 64x64 PNG icon suitable for KiCad PCM.
Pillow is preferred. If Pillow is unavailable or conversion fails,
the original PNG is returned.
"""
icon_path = Path(icon_path)
if not icon_path.exists():
return None
try:
from PIL import Image
with Image.open(icon_path) as image:
image = image.convert("RGBA").resize(
(64, 64),
Image.Resampling.LANCZOS,
)
buffer = BytesIO()
image.save(
buffer,
format="PNG",
optimize=True,
)
return buffer.getvalue()
except Exception as exc:
print(
f" Warning: could not normalize {icon_path}: {exc}. "
"Using the original PNG."
)
return icon_path.read_bytes()
def create_repository_resources_zip(
plugin_paths,
metadata_by_path,
output_dir,
):
"""
Create KiCad's repository-level resources.zip.
THIS is what supplies icons in Plugin and Content Manager before a
package is installed.
KiCad expects icons inside the ZIP using:
<package-identifier>/icon.png
Examples:
wayricad.extract.pins/icon.png
wayricad.fanout.generator/icon.png
wayricad.via.stitching/icon.png
"""
output_dir = Path(output_dir)
output_dir.mkdir(
parents=True,
exist_ok=True,
)
zip_path = output_dir / "resources.zip"
icon_count = 0
with zipfile.ZipFile(
zip_path,
"w",
compression=zipfile.ZIP_DEFLATED,
compresslevel=9,
) as zipf:
for plugin_path in plugin_paths:
metadata = metadata_by_path[plugin_path]
identifier = metadata["identifier"]
icon_path = plugin_path / "icon.png"
icon_bytes = get_pcm_icon_bytes(icon_path)
if icon_bytes is None:
print(
f" Warning: no PCM icon found for {identifier}: "
f"{icon_path}"
)
continue
# ZIP filenames MUST use forward slashes,
# including when building under Windows.
archive_name = f"{identifier}/icon.png"
zipf.writestr(
zip_entry(archive_name),
icon_bytes,
)
icon_count += 1
if icon_count == 0:
zip_path.unlink(
missing_ok=True
)
raise RuntimeError(
"No plugin icons were found; refusing to create an empty "
"repository resources.zip."
)
print(
f"Created repository resources archive: "
f"{zip_path} ({icon_count} icons)"
)
return zip_path, icon_count
def create_plugin_zip(
plugin_path,
version,
output_dir,
metadata,
):
"""
Create one KiCad PCM plugin archive.
Archive layout:
metadata.json
plugins/
...
resources/
icon.png
"""
output_dir = Path(output_dir)
output_dir.mkdir(
parents=True,
exist_ok=True,
)
zip_filename = (
f"WayriCAD-{plugin_path.name.removesuffix('_plugin').replace('_', '-')}-{version}-PCM.zip"
)
zip_path = (
output_dir / zip_filename
)
print(
f"Zipping {plugin_path} -> {zip_path}"
)
with zipfile.ZipFile(
zip_path,
"w",
compression=zipfile.ZIP_DEFLATED,
compresslevel=9,
) as zipf:
#
# metadata.json
#
# Write NORMALIZED metadata, not the original source metadata.
#
# This guarantees:
#
# author.contact
# normalized license
# normalized runtime
#
# are also correct inside the downloadable package.
#
normalized_metadata_text = (
json.dumps(
metadata,
indent=2,
ensure_ascii=False,
)
+ "\n"
)
zipf.writestr(
zip_entry("metadata.json"),
normalized_metadata_text,
)
#
# Plugin files
#
for file_path in plugin_files(plugin_path):
if file_path.name == "metadata.json":
continue
archive_name = (Path("plugins") / file_path.relative_to(plugin_path)).as_posix()
zipf.writestr(zip_entry(archive_name, compress_type=zipfile.ZIP_DEFLATED),
file_path.read_bytes())
if plugin_path.name == "suite_assistant_plugin":
bundle_assistant_backends(zipf, plugin_path.parent)
if metadata.get("versions", [{}])[0].get("runtime") == "swig":
# Native action plugins own registration; do not route through IPC discovery.
initializer = (plugin_path / "__init__.py").read_text(encoding="utf-8")
else:
initializer = ("\"\"\"KiCad menu bridge.\"\"\"\n"
+ "__version__ = " + repr(version) + "\n"
"from pathlib import Path\nimport sys\n"
"_root = Path(__file__).resolve().parent\n"
"if str(_root) not in sys.path: sys.path.insert(0, str(_root))\n"
"from wayricad_runtime.legacy_menu import register\nregister(__name__, _root)\n")
zipf.writestr(
zip_entry("plugins/__init__.py", compress_type=zipfile.ZIP_DEFLATED),
initializer,
)
# Every package carries its own runtime; installed tools never import siblings.
if metadata.get("versions", [{}])[0].get("runtime") != "swig":
runtime_root = Path(__file__).resolve().parent / "wayricad_runtime"
for source in sorted(p for p in runtime_root.rglob("*") if p.is_file() and
(p.suffix in (".py", ".md") or
(p.is_relative_to(runtime_root / 'assets' / 'thermoelectric') and p.suffix in ('.js','.html','.txt','.png')) or
p.name == 'THERMOELECTRIC_3D.html')):
zipf.writestr(zip_entry("plugins/wayricad_runtime/" + source.relative_to(runtime_root).as_posix(),
compress_type=zipfile.ZIP_DEFLATED), source.read_bytes())
zipf.writestr(zip_entry("plugins/wayricad_runtime/LICENSE"),
(Path(__file__).resolve().parent / "LICENSE").read_bytes())
if plugin_path.name == "extract_pins_plugin":
# The automation CLI advertises suite analyses, so its ZIP includes their pure backends.
backends = {
"harness_workbench_plugin": ("analysis.py", "report.py"),
"protocol_constraint_composer_plugin": ("analysis.py",),
"manufacturing_readiness_plugin": ("analysis.py",),
"heater_designer_plugin": ("analysis.py", "materials.py", "patterns.py"),
"quick_pi_plugin/decoupling": ("analysis.py",),
"signal_integrity_advisor_plugin/return_path": ("analysis.py", "diff_pairs.py"),
"planar_magnetics_plugin": ("analysis.py", "magnetic_circuit.py"),
"signal_integrity_advisor_plugin/test_points": ("fixture.py",),
}
for folder, filenames in sorted(backends.items()):
for filename in filenames:
source = Path(__file__).resolve().parent / folder / filename
zipf.writestr(zip_entry(f"plugins/_suite_backends/{folder}/{filename}",
compress_type=zipfile.ZIP_DEFLATED), source.read_bytes())
license_path = plugin_path / "LICENSE"
if not license_path.exists():
license_path = Path(__file__).resolve().parent / "LICENSE"
zipf.writestr(zip_entry("plugins/LICENSE"), license_path.read_bytes())
# Installed-package icon
#
icon_bytes = get_pcm_icon_bytes(
plugin_path / "icon.png"
)
if icon_bytes is not None:
zipf.writestr(
zip_entry(
"resources/icon.png",
compress_type=zipfile.ZIP_DEFLATED,
),
icon_bytes,
)
return (
zip_path,
zip_filename,
)
def calculate_install_size(zip_path):
with zipfile.ZipFile(
zip_path,
"r",
) as zipf:
return sum(
info.file_size
for info
in zipf.infolist()
)
def validate_feed(packages_data):
"""
Catch common PCM feed errors before publishing.
This is deliberately strict about the errors we already encountered.
"""
if not isinstance(
packages_data,
dict,
):
raise ValueError(
"packages feed root must be a JSON object."
)
packages = packages_data.get(
"packages"
)
if not isinstance(
packages,
list,
):
raise ValueError(
"packages feed must contain a 'packages' array."
)
identifiers = set()
for index, package in enumerate(
packages
):
prefix = (
f"/packages/{index}"
)
if not isinstance(
package,
dict,
):
raise ValueError(
f"{prefix}: package must be a JSON object."
)
identifier = package.get(
"identifier"
)
if (
not isinstance(
identifier,
str,
)
or not identifier.strip()
):
raise ValueError(
f"{prefix}/identifier: required."
)
if identifier in identifiers:
raise ValueError(
f"{prefix}/identifier: "
f"duplicate identifier "
f"{identifier!r}."
)
identifiers.add(
identifier
)
#
# Author validation
#
author = package.get(
"author"
)
if not isinstance(
author,
dict,
):
raise ValueError(
f"{prefix}/author: "
"must be an object."
)
if (
not isinstance(
author.get("name"),
str,
)
or not author["name"].strip()
):
raise ValueError(
f"{prefix}/author/name: required."
)
contact = author.get(
"contact"
)
if (
not isinstance(
contact,
dict,
)
or not contact
):
raise ValueError(
f"{prefix}/author/contact: "
"required by KiCad PCM v1."
)
#
# License validation
#
license_name = package.get(
"license"
)
if license_name in PCM_LICENSE_ALIASES:
raise ValueError(
f"{prefix}/license: "
f"unnormalized license "
f"{license_name!r}; "
f"expected "
f"{PCM_LICENSE_ALIASES[license_name]!r}."
)
#
# Versions
#
versions = package.get(
"versions"
)
if (
not isinstance(
versions,
list,
)
or not versions
):
raise ValueError(
f"{prefix}/versions: "
"must be a non-empty array."
)
seen_versions = set()
for v_index, version in enumerate(
versions
):
v_prefix = (
f"{prefix}/versions/{v_index}"
)
if not isinstance(
version,
dict,
):
raise ValueError(
f"{v_prefix}: "
"must be an object."
)
version_name = version.get(
"version"
)
if (
not isinstance(
version_name,
str,
)
or not version_name.strip()
):
raise ValueError(
f"{v_prefix}/version: required."
)
if version_name in seen_versions:
raise ValueError(
f"{v_prefix}/version: "
f"duplicate version "
f"{version_name!r}."
)
seen_versions.add(
version_name
)
runtime = version.get(
"runtime"
)
if runtime not in SUPPORTED_RUNTIMES:
raise ValueError(
f"{v_prefix}/runtime: "
f"{runtime!r} is invalid."
)
for required_key in (
"download_sha256",
"download_size",
"download_url",
"install_size",
"platforms",
):
if required_key not in version:
raise ValueError(
f"{v_prefix}/{required_key}: "
"required in generated feed."
)
def parse_args():
parser = argparse.ArgumentParser(
description=(
"Build WayriCAD KiCad PCM packages "
"and repository metadata."
)
)
parser.add_argument(
"--release-tag",
default=DEFAULT_RELEASE_TAG,
help=(
"GitHub release tag WITHOUT "
"the leading 'v'. "
f"Default: {DEFAULT_RELEASE_TAG}"
),
)
parser.add_argument(
"--branch",
default=DEFAULT_BRANCH,
help=(
"Branch used for raw "
"pcm/pkgs.json. "
f"Default: {DEFAULT_BRANCH}"
),
)
parser.add_argument(
"--clean-feed",
action="store_true",
help=(
"Ignore existing pcm/pkgs.json "
"version history and rebuild "
"the feed from only the current "
"metadata versions."
),
)
parser.add_argument(
"--output-dir",
type=Path,
help="Build disposable current-source PCM ZIPs in this directory without changing releases/ or pcm/.",
)
return parser.parse_args()
def main():
args = parse_args()
release_tag = (
args.release_tag.removeprefix("v")
)
branch = args.branch
base_path = Path(".")
if args.output_dir is not None:
if args.clean_feed:
raise ValueError("--clean-feed cannot be used with --output-dir.")
output_dir = args.output_dir.resolve()
if output_dir == (Path(__file__).resolve().parent / RELEASES_DIR).resolve():
raise ValueError("Use the default build for releases/; --output-dir is for disposable ZIPs.")
plugin_paths = discover_plugins(base_path)
if not plugin_paths:
raise RuntimeError("No plugin directories containing metadata.json found.")
for plugin_path in plugin_paths:
metadata = normalize_metadata(
load_json(plugin_path / "metadata.json"), plugin_path, branch
)
archive_path, _ = create_plugin_zip(
plugin_path, metadata["versions"][0]["version"], output_dir, metadata
)
with zipfile.ZipFile(archive_path) as archive:
corrupt_entry = archive.testzip()
if corrupt_entry is not None:
raise ValueError(f"Corrupt entry in {archive_path}: {corrupt_entry}")
if metadata["versions"][0]["runtime"] == "ipc":
manifest = json.loads(archive.read("plugins/plugin.json"))
if manifest.get("identifier") != metadata["identifier"]:
raise ValueError(f"Plugin identifier mismatch in {archive_path}")
elif "plugins/plugin.json" in archive.namelist():
raise ValueError("SWIG packages must not enable IPC discovery")
print(f"Built {len(plugin_paths)} disposable PCM ZIPs in {output_dir}")
return
pcm_dir = Path(
PCM_DIR
)
releases_dir = Path(
RELEASES_DIR
)
pcm_dir.mkdir(
parents=True,
exist_ok=True,
)
releases_dir.mkdir(
parents=True,
exist_ok=True,
)
packages_file = (
pcm_dir / "pkgs.json"
)
repo_file = (
pcm_dir / "repo.json"
)
packages_data = {
"packages": []
}
#
# Load existing package history
#
if (
packages_file.exists()
and not args.clean_feed
):
try:
existing = load_json(
packages_file
)
if (
isinstance(existing, dict)
and isinstance(
existing.get("packages"),
list,
)
):
packages_data = existing
elif isinstance(
existing,
list,
):
#
# Migration from older
# root-array feeds.
#
packages_data[
"packages"
] = existing
else: