Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
1450 lines (1293 loc) · 68.3 KB
/
Copy pathbuild.py
File metadata and controls
1450 lines (1293 loc) · 68.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Builds the RustGIS plugin registry: registry.json, the package index and new packages.
python scripts/build.py # build what changed, write dist/
python scripts/build.py --check # also fail on any problem (CI)
python scripts/build.py --no-cache # ignore the published index (rebuild or reuse from R2)
python scripts/build.py --inspect <checkout> <out> registry/<id>.json...
# unpack the packages these entries point at, for review
Each plugin has an entry in registry/<id>.json:
- a plugin names its published package: {"id": ..., "source": {"url": "https://...rgplugin",
"sha256": "..."}}; it is downloaded and checked against the hash. A process plugin
("runtime": "process", a program such as a Python script, not sandboxed) is listed this way
only: its package holds its files, which are checked in place of a module.
- a process plugin that ships a program for each platform can name one package per platform:
{"id": ..., "source": {"windows": {"url": ..., "sha256": ...}, "macos": {...}, "linux": {...}}}.
Each is downloaded and checked like any other; they must be the same plugin (one plugin.json,
but for `run`), and RustGIS downloads the one for the platform it runs on.
- the plugins in LEGACY_PATHS still name their folder here, {"id": ..., "path": "plugins/<dir>"},
and are built from source with cargo, until they move to a repository of their own. No other
plugin may: plugin source belongs in its own repository, and only registry entries here.
Packages are served from packages.rustgis.app (a Cloudflare R2 bucket) at <id>/<id>-<version>.rgplugin
(<id>/<id>-<version>-<platform>.rgplugin for a package per platform) and never change once published. So the build is incremental: the previous deploy's package
index (plugins.rustgis.app/packages.json) says what is published, and only plugins whose version
(or source) changed are built or downloaded. An in-repository plugin whose files changed without
a version bump is a problem. Without the index, packages already in the bucket are reused rather
than rebuilt. Output goes to dist/:
dist/registry.json what RustGIS lists (every plugin, with its package URL and SHA-256)
dist/packages.json the package index: each plugin's package, manifest and source hash
dist/packages/<id>/... the packages built or downloaded by this run (to upload)
dist/new.txt their paths, relative to dist/packages
Everything users see (name, version, description, permissions...) comes from the package's
plugin.json, so it can't disagree with what is installed.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
import zipfile
import zlib
from collections import Counter
from pathlib import Path
if sys.version_info < (3, 11):
sys.exit("scripts/build.py needs Python 3.11 or later (for tomllib)")
import tomllib
ROOT = Path(__file__).resolve().parent.parent
# Where packages are served (the R2 bucket's domain), and the previous deploy's package index.
PACKAGES_URL = "https://packages.rustgis.app"
INDEX_URL = "https://plugins.rustgis.app/packages.json"
DIST = ROOT / "dist"
TARGET = ROOT / "target" / "wasm32-unknown-unknown" / "release"
# Plugins still built from a folder in plugins/. None is left: every plugin is listed by 'source',
# from a release of its own repository, and nothing is added here.
LEGACY_PATHS: set[str] = set()
ID_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
# Versions name objects in the bucket, so only safe characters: 1.2.3, 1.2.3-beta.1, 1.2.3+build.5.
VERSION_RE = re.compile(r"^\d+(\.\d+){0,2}([-+][0-9A-Za-z]+(\.[0-9A-Za-z]+)*)*$")
SHA_RE = re.compile(r"^[0-9a-f]{64}$")
PERMISSIONS = {"edit", "files", "network"}
PARAM_KINDS = {"layer", "vectorLayer", "polygonLayer", "pointLayer", "field", "numericField", "number", "text", "choice", "bool", "file"}
# RustGIS's (crates/plugins/src/panel.rs, KINDS): a form since #1539, a pick since #1643.
PANEL_KINDS = {"text", "checkbox", "slider", "button", "tree", "form", "choice", "date", "range", "pick"}
# What a pick asks for on the map: a point (when unset) or a box.
PICK_SHAPES = {"point", "box"}
# A dropdown's (choice's) most options, and the longest option id.
PANEL_CHOICES = 1_000
# The largest plugin.json RustGIS reads.
MANIFEST_MAX = 512 * 1024
PANEL_OPTION_ID = 200
# RustGIS's panel limits (crates/plugins/src/panel.rs).
PANEL_TITLE = 48
PANEL_DECLARED = 2_000
SLIDER_LIMIT = 1_000_000_000
EXTENSION_RE = re.compile(r"[A-Za-z0-9]{1,16}")
CATEGORIES = {
"Analysis", "Basemaps", "Cartography", "Data", "Editing", "Example", "Hydrology", "Imagery",
"Raster", "Sampling", "Terrain", "Utilities", "Vector", "Visualization",
}
MAX_PACKAGE = 64 * 1024 * 1024
# What RustGIS takes in a process plugin's package: files, unpacked size, `run` arguments.
MAX_ENTRIES = 4096
MAX_UNPACKED = 1024 * 1024 * 1024
MAX_RUN_ARGS = 64
MAX_TEXT = 2000
RUN_PLATFORMS = ("windows", "macos", "linux", "default")
# The platforms an entry can name a package for (RustGIS's registry.rs PLATFORMS).
PACKAGE_PLATFORMS = ("windows", "macos", "linux")
PYTHON_VERSION_RE = re.compile(r"3\.\d{1,3}(\.\d{1,3})?", re.ASCII)
# The programs RustGIS swaps for the plugin's own environment's interpreter.
PYTHONS = {"python", "python3", "python.exe"}
# RustGIS's own tabs: a plugin's tab can't take their names.
RESERVED_TABS = {
"project", "map", "insert", "analysis", "view", "edit", "imagery", "share", "plugins", "help",
"feature layer", "labeling", "data", "raster layer", "raster data", "layout",
}
# A fixed timestamp keeps packages byte-for-byte reproducible.
ZIP_TIME = (2026, 1, 1, 0, 0, 0)
problems: list[str] = []
def listing_i18n(manifest: dict) -> dict:
"""The translations of a plugin's name and description, for its registry entry.
The Plugin Manager lists plugins in the interface language before they're installed, so
the entry carries these two strings from the manifest's `i18n`. Keep it in step with
`preview.py`'s copy: CI checks the two scripts build the same entry.
Args:
manifest: The package's plugin.json.
Returns:
`{lang: {english: translation}}` for the languages that translate either string.
"""
tables = manifest.get("i18n")
out: dict = {}
for lang, table in sorted(tables.items()) if isinstance(tables, dict) else []:
if not isinstance(table, dict):
continue
keep = {k: v for k in (manifest.get("name"), manifest.get("description")) if isinstance(k, str) and isinstance(v := table.get(k), str) and v.strip()}
if keep:
out[lang] = keep
return out
def runtime_fields(manifest: dict) -> dict:
"""What a registry entry says about how the plugin runs: nothing for a WebAssembly plugin.
A process plugin's entry says `"runtime": "process"` (not sandboxed; the desktop and the
command line only), and `"python": "<version>"` when RustGIS makes it a Python environment.
Keep it in step with `preview.py`'s copy: CI checks the two scripts build the same entry.
Args:
manifest: The package's plugin.json.
Returns:
The fields to add to the entry.
"""
if manifest.get("runtime") != "process":
return {}
out: dict = {"runtime": "process"}
py = manifest.get("python")
if isinstance(py, dict):
out["python"] = str(py.get("version", "3.12"))
return out
def problem(msg: str) -> None:
problems.append(msg)
print(f"error: {msg}", file=sys.stderr)
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
# --------------------------------------------------------------------------------------------
# WebAssembly checks: the exports RustGIS needs, and no imports it doesn't provide.
def leb(data: bytes, i: int) -> tuple[int, int]:
result = shift = 0
while True:
b = data[i]
i += 1
result |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
return result, i
def wasm_interface(data: bytes) -> tuple[set[str], list[str]]:
"""Returns (exports, imports as 'module.name') of a WebAssembly module."""
if data[:4] != b"\0asm":
raise ValueError("not a WebAssembly module")
i, exports, imports = 8, set(), []
def name(i: int) -> tuple[str, int]:
n, i = leb(data, i)
return data[i : i + n].decode("utf-8", "replace"), i + n
while i < len(data):
sid = data[i]
size, i = leb(data, i + 1)
end = i + size
if sid == 2: # imports
count, j = leb(data, i)
for _ in range(count):
mod, j = name(j)
nm, j = name(j)
kind = data[j]
j += 1
imports.append(f"{mod}.{nm}")
if kind == 0: # function: type index
_, j = leb(data, j)
elif kind == 1: # table: reftype + limits
j += 1
flags, j = leb(data, j)
_, j = leb(data, j)
if flags & 1:
_, j = leb(data, j)
elif kind == 2: # memory: limits
flags, j = leb(data, j)
_, j = leb(data, j)
if flags & 1:
_, j = leb(data, j)
elif kind == 3: # global: type + mutability
j += 2
else:
break
elif sid == 7: # exports
count, j = leb(data, i)
for _ in range(count):
nm, j = name(j)
j += 1
_, j = leb(data, j)
exports.add(nm)
i = end
return exports, imports
def wasm_data(data: bytes) -> bytes:
"""Returns the bytes of a WebAssembly module's data segments (its string literals), joined."""
if data[:4] != b"\0asm":
raise ValueError("not a WebAssembly module")
i, out = 8, []
while i < len(data):
sid = data[i]
size, i = leb(data, i + 1)
end = i + size
if sid == 11: # data
count, j = leb(data, i)
for _ in range(count):
flags, j = leb(data, j)
if flags == 2: # explicit memory index
_, j = leb(data, j)
if flags in (0, 2): # offset expression: constants, globals and arithmetic, then end
while data[j] != 0x0B:
op = data[j]
j += 1
if op in (0x23, 0x41, 0x42): # global.get, i32.const, i64.const
_, j = leb(data, j)
elif op not in (0x6A, 0x6B, 0x6C, 0x7C, 0x7D, 0x7E): # i32/i64 add, sub, mul
raise ValueError(f"unsupported data segment offset instruction 0x{op:02x}")
j += 1
elif flags != 1:
raise ValueError(f"unknown data segment kind {flags}")
n, j = leb(data, j)
out.append(data[j : j + n])
j += n
i = end
return b"\0".join(out)
COMMANDS = ROOT / "scripts" / "rustgis-commands.txt"
URL_RE = re.compile(rb"https?://[!#-~]{3,}")
MAX_URLS = 100
def module_strings(data: bytes, known: list[str]) -> tuple[list[str], list[str], int]:
"""Returns (the RustGIS command ids, the URLs, how many URLs in all) a module's data segments
name. Rust packs its string literals end to end with no separator, so an id counts where no
longer known id starts at the same place (`layer.addData` hides `layer.add` there), and a URL
may run into the string after it."""
seg = wasm_data(data)
longer = {cid: [k.encode() for k in known if k != cid and k.startswith(cid)] for cid in known}
found = set()
for cid in known:
# Bounded, so a module repeating a longer id can't make the scan crawl; one that hits the
# bound counts as naming the id, so the repeats can't hide it either.
at, tries = seg.find(cid.encode()), 0
while at != -1:
if tries == 1000 or not any(seg.startswith(k, at) for k in longer[cid]):
found.add(cid)
break
at, tries = seg.find(cid.encode(), at + 1), tries + 1
urls = sorted({m.group().decode("ascii")[:200] for m in URL_RE.finditer(seg)})
return sorted(found), urls[:MAX_URLS], len(urls)
def known_commands() -> list[str]:
try:
lines = COMMANDS.read_text(encoding="utf-8").splitlines()
except OSError:
return []
# A one-word id (`identify`) matches ordinary text too often to say anything.
stripped = (ln.strip() for ln in lines)
return [ln for ln in stripped if "." in ln and not ln.startswith("#")]
# --------------------------------------------------------------------------------------------
# Manifests and packages
def check_manifest(m: dict, where: str) -> None:
for key in ("id", "name", "version"):
if not isinstance(m.get(key), str) or not m[key].strip():
problem(f"{where}: plugin.json needs '{key}'")
if not ID_RE.match(m.get("id", "")):
problem(f"{where}: id must be lower-case letters, digits and hyphens")
if not VERSION_RE.match(m.get("version", "")):
problem(f"{where}: version must look like 1.0.0")
if m.get("abi", 1) != 1:
problem(f"{where}: abi must be 1")
for p in m.get("permissions", []):
if p not in PERMISSIONS:
problem(f"{where}: unknown permission '{p}'")
if m.get("homepage") and not str(m["homepage"]).startswith("https://"):
problem(f"{where}: homepage must be an https:// address")
if not m.get("commands") and not m.get("tools"):
problem(f"{where}: the plugin adds no commands and no tools")
runtime = m.get("runtime", "wasm")
if runtime not in ("wasm", "process"):
problem(f"{where}: runtime must be 'wasm' (the default) or 'process'")
if runtime != "process" and ("run" in m or "python" in m):
problem(f"{where}: 'run' and 'python' are for process plugins (\"runtime\": \"process\")")
if runtime == "process" and "entry" in m:
problem(f"{where}: a process plugin has no 'entry' (it names its program in 'run')")
for c in m.get("commands", []):
if not ID_RE.match(c.get("id", "")) or not c.get("label"):
problem(f"{where}: command {c.get('id')!r} needs a valid id and a label")
for t in m.get("tools", []):
if not ID_RE.match(t.get("id", "")) or not t.get("name"):
problem(f"{where}: tool {t.get('id')!r} needs a valid id and a name")
for p in t.get("params", []):
if p.get("kind") not in PARAM_KINDS:
problem(f"{where}: tool {t.get('id')}: parameter {p.get('name')!r} has unknown kind {p.get('kind')!r}")
# RustGIS hands a tool a file only with `files`, and filters its picker by plain extensions.
if p.get("kind") == "file" and "files" not in m.get("permissions", []):
problem(f"{where}: tool {t.get('id')}: file parameter {p.get('name')!r} needs the 'files' permission")
exts = p.get("extensions", [])
if not isinstance(exts, list) or len(exts) > 16 or not all(isinstance(e, str) and EXTENSION_RE.fullmatch(e) for e in exts):
problem(f"{where}: tool {t.get('id')}: parameter {p.get('name')!r} has invalid extensions (letters and digits, no dot)")
def check_tab(m: dict, where: str) -> None:
"""Checks a manifest's own ribbon tab: its label and that every item names a command or tool.
Args:
m: The manifest.
where: Where it came from, for messages.
"""
tab = m.get("tab")
if tab is None:
return
if not isinstance(tab, dict):
problem(f"{where}: tab must be an object")
return
label = str(tab.get("label", "")).strip()
if not label or len(label) > 32 or "\n" in label:
problem(f"{where}: the tab's label must be one line of 1 to 32 characters")
if label.lower() in RESERVED_TABS:
problem(f"{where}: the tab can't be called '{label}', the name of one of RustGIS's tabs")
commands = {c.get("id") for c in m.get("commands", [])}
tools = {t.get("id") for t in m.get("tools", [])}
def entry(e: object) -> None:
ok = isinstance(e, str) and (
e[5:] in tools if e.startswith("tool:") else e in commands or (e == "panel" and isinstance(m.get("panel"), dict))
)
if not ok:
problem(f"{where}: the tab names {e!r}, which isn't one of the plugin's commands or tools (tool:<id>) or its panel")
groups = tab.get("groups") or []
if not 1 <= len(groups) <= 8:
problem(f"{where}: the tab needs 1 to 8 groups")
for g in groups:
items = g.get("items") or []
if not g.get("label") or not 1 <= len(items) <= 16:
problem(f"{where}: tab group {g.get('label')!r} needs a label and 1 to 16 items")
for item in items:
if isinstance(item, dict):
if not item.get("menu") or not 1 <= len(item.get("items") or []) <= 32:
problem(f"{where}: menu {item.get('menu')!r} needs a label and 1 to 32 items")
for e in item.get("items") or []:
entry(e)
else:
entry(item)
def check_panel(m: dict, where: str) -> None:
"""Checks a manifest's panel as RustGIS does when it loads the plugin (`PanelDecl::validate`):
its title, its widgets' kinds, ids, fields and slider ranges, and that the widgets and the
state name the plugin's own commands.
Args:
m: The manifest.
where: Where it came from, for messages.
"""
panel = m.get("panel")
if panel is None:
return
if not isinstance(panel, dict):
problem(f"{where}: panel must be an object")
return
title = panel.get("title")
if not isinstance(title, str) or not 1 <= len(title.strip()) <= PANEL_TITLE or "\n" in title.strip():
problem(f"{where}: the panel's title must be one line of 1 to {PANEL_TITLE} characters")
for key in ("help", "icon"):
if not isinstance(panel.get(key, ""), str) or len(panel.get(key, "")) > PANEL_DECLARED:
problem(f"{where}: the panel's {key} must be text of at most {PANEL_DECLARED} characters")
listed = m.get("commands", [])
commands = {c.get("id") for c in listed if isinstance(c, dict)} if isinstance(listed, list) else set()
if "panel" in commands:
problem(f"{where}: a plugin with a panel can't have a command called 'panel'")
if "state" in panel and not (isinstance(panel["state"], str) and panel["state"] in commands):
problem(f"{where}: the panel's state {panel['state']!r} isn't one of the plugin's commands")
items = panel.get("items")
if not isinstance(items, list) or not 1 <= len(items) <= 32:
problem(f"{where}: the panel needs 1 to 32 items")
return
seen: set[str] = set()
for item in items:
kind = item.get("kind") if isinstance(item, dict) else None
if not isinstance(kind, str) or kind not in PANEL_KINDS:
problem(f"{where}: panel item {item!r} has unknown kind {kind!r}")
continue
command = item.get("command")
if (kind == "button" or command is not None) and not (isinstance(command, str) and (command in commands or (kind == "form" and command == ""))):
problem(f"{where}: panel {kind} {item.get('id', command)!r} runs {command!r}, which isn't one of the plugin's commands")
continue
widget = item.get("id", command if kind == "button" else None)
if not isinstance(widget, str) or not (ID_RE.fullmatch(widget) if kind == "form" else ID_RE.match(widget)):
problem(f"{where}: panel {kind} {widget!r} needs a valid id")
elif widget in seen:
problem(f"{where}: two panel widgets have the id {widget!r} (a button's id is its command's unless it has one of its own)")
else:
seen.add(widget)
check_panel_item(item, kind, f"{where}: panel {kind} {widget!r}")
def whole(v: object) -> int | None:
"""A whole number from an integer or a float with no fraction, as RustGIS reads one."""
if isinstance(v, bool):
return None
if isinstance(v, int):
return v
if isinstance(v, float) and v.is_integer() and abs(v) <= SLIDER_LIMIT:
return int(v)
return None
def panel_date(s: object) -> bool:
"""Whether `s` is a real date written YYYY-MM-DD (years 1 to 9999), as RustGIS reads one."""
# ASCII digits only: `\d` would take other scripts' digits, which RustGIS refuses.
if not isinstance(s, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", s):
return False
y, m, d = int(s[:4]), int(s[5:7]), int(s[8:])
if y < 1 or not 1 <= m <= 12:
return False
leap = (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
days = [31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]
return 1 <= d <= days
def check_panel_item(item: dict, kind: str, where: str) -> None:
"""Checks a panel widget's fields: which kinds take which, a slider's or a range's ends and
default, a dropdown's options, a date's default, a tree's search and a pick's shape.
Args:
item: The widget, an object with a known `kind`.
kind: Its kind.
where: The widget, for messages.
"""
for key in ("label", "help", "text"):
if not isinstance(item.get(key, ""), str) or len(item.get(key, "")) > PANEL_DECLARED:
problem(f"{where}: {key} must be text of at most {PANEL_DECLARED} characters")
return
if kind == "form" and (not isinstance(item.get("shape", ""), str) or item.get("shape", "")):
problem(f"{where}: shape is for picks")
if kind == "form":
# Forms declare no static fields or defaults; fields arrive in command replies.
if "command" in item and not isinstance(item["command"], str):
problem(f"{where}: command must be text")
for key in ("min", "max"):
if type(item.get(key, 0)) is not int or item.get(key, 0) != 0:
problem(f"{where}: {key} must be zero for a form")
for key in ("steps", "search"):
if item.get(key, False) is not False:
problem(f"{where}: {key} must be false for a form")
if item.get("options", []) != [] or not isinstance(item.get("options", []), list):
problem(f"{where}: options are for dropdowns (choice)")
if item.get("default") is not None:
problem(f"{where}: a form has no declared default")
if item.get("text", ""):
problem(f"{where}: text is for texts")
return
if kind == "text" and item.get("command"):
problem(f"{where}: a text runs no command")
if kind == "checkbox" and not item.get("label", "").strip():
problem(f"{where}: a checkbox needs a label")
if kind == "pick" and not item.get("label", "").strip() and not item.get("command"):
problem(f"{where}: a pick needs a label or a command")
shape = item.get("shape", "")
if not isinstance(shape, str):
problem(f"{where}: shape is text, a pick's point or box")
elif kind == "pick" and shape and shape not in PICK_SHAPES:
problem(f"{where}: a pick's shape {shape!r} isn't point or box")
elif kind != "pick" and shape:
problem(f"{where}: shape is for picks")
if kind != "text" and item.get("text"):
problem(f"{where}: text is for texts")
if not isinstance(item.get("search", False), bool):
problem(f"{where}: search is true or false")
elif kind != "tree" and item.get("search", False):
problem(f"{where}: search is for trees")
options = item.get("options", [])
if kind != "choice" and "options" in item:
problem(f"{where}: options are for dropdowns (choice)")
ids: list[str] = []
if kind == "choice":
if not isinstance(options, list) or len(options) > PANEL_CHOICES:
problem(f"{where}: a dropdown's options are a list of at most {PANEL_CHOICES:,}")
return
for o in options:
oid = o.get("id") if isinstance(o, dict) else None
if not isinstance(oid, str) or not 1 <= len(oid) <= PANEL_OPTION_ID or oid in ids:
problem(f"{where}: each option is an object with a unique id of 1 to {PANEL_OPTION_ID} characters")
return
if not isinstance(o.get("label", ""), (str, type(None))):
problem(f"{where}: an option's label is text")
ids.append(oid)
lo, hi = item.get("min", 0), item.get("max", 0)
if kind not in ("slider", "range"):
if lo != 0 or hi != 0 or item.get("steps", False):
problem(f"{where}: min, max and steps are for sliders and ranges")
if "default" not in item:
return
default = item["default"]
if kind == "checkbox" and not isinstance(default, bool):
problem(f"{where}: a checkbox's default is true or false")
elif kind == "choice" and default not in ids:
problem(f"{where}: a dropdown's default is the id of one of its options")
elif kind == "date" and not panel_date(default):
problem(f"{where}: a date's default is a date written YYYY-MM-DD")
elif kind not in ("checkbox", "choice", "date"):
problem(f"{where}: only checkboxes, sliders, ranges, dropdowns and dates have a default")
return
if not isinstance(item.get("steps", False), bool):
problem(f"{where}: steps is true or false")
if isinstance(lo, bool) or isinstance(hi, bool) or not isinstance(lo, int) or not isinstance(hi, int):
problem(f"{where}: a slider's or a range's min and max are whole numbers")
return
if lo > hi or lo < -SLIDER_LIMIT or hi > SLIDER_LIMIT:
problem(f"{where}: a slider's or a range's min must not be above its max, both within ±{SLIDER_LIMIT:,}")
if "default" in item and kind == "slider":
v = whole(item["default"])
if v is None or not lo <= v <= hi:
problem(f"{where}: a slider's default is a whole number from min to max")
elif "default" in item:
d = item["default"]
pair = [whole(v) for v in d] if isinstance(d, list) and len(d) == 2 else None
if pair is None or None in pair or not lo <= pair[0] <= pair[1] <= hi:
problem(f"{where}: a range's default is [low, high], whole numbers from min to max, low first")
def check_module(wasm: bytes, where: str) -> None:
try:
exports, imports = wasm_interface(wasm)
except (ValueError, IndexError) as e:
problem(f"{where}: unreadable module: {e}")
return
for e in ("memory", "rustgis_alloc", "rustgis_call"):
if e not in exports:
problem(f"{where}: the module doesn't export '{e}' (build it with the rustgis-plugin SDK)")
for imp in imports:
if imp not in ("rustgis.call", "rustgis.result", "rustgis.log"):
problem(f"{where}: the module imports '{imp}', which RustGIS doesn't provide")
def package(manifest_path: Path, wasm: bytes) -> bytes:
"""A reproducible .rgplugin: plugin.json, the module and the README, in a fixed order."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z:
files = [("plugin.json", manifest_path.read_bytes())]
manifest = json.loads(files[0][1])
files.append((manifest.get("entry", "plugin.wasm"), wasm))
readme = manifest_path.parent / "README.md"
if readme.is_file():
files.append(("README.md", readme.read_bytes()))
for name, data in files:
info = zipfile.ZipInfo(name, ZIP_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
z.writestr(info, data)
return buf.getvalue()
def read_package(data: bytes, where: str) -> tuple[dict, bytes] | None:
try:
with zipfile.ZipFile(io.BytesIO(data)) as z:
names = z.namelist()
root = "" if "plugin.json" in names else next((n[: -len("plugin.json")] for n in names if n.endswith("/plugin.json")), None)
if root is None:
problem(f"{where}: the package has no plugin.json")
return None
# RustGIS reads at most 512 KiB of plugin.json (a dropdown's options can grow it).
if z.getinfo(root + "plugin.json").file_size > MANIFEST_MAX:
problem(f"{where}: plugin.json is larger than {MANIFEST_MAX // 1024} KiB, which RustGIS refuses")
return None
manifest = json.loads(z.read(root + "plugin.json"))
# A process plugin has no module: its files are checked by check_process().
if isinstance(manifest, dict) and manifest.get("runtime") == "process":
return manifest, b""
wasm = z.read(root + manifest.get("entry", "plugin.wasm"))
return manifest, wasm
except (zipfile.BadZipFile, KeyError, json.JSONDecodeError) as e:
problem(f"{where}: unreadable package: {e}")
return None
def valid_path(s: object) -> bool:
"""Whether `s` is a path inside a package as RustGIS takes one: relative, forward slashes, no `..`.
Args:
s: The path, from a manifest.
Returns:
True when it is one.
"""
return (
isinstance(s, str)
and 0 < len(s) <= 256
and not s.startswith("/")
and "\\" not in s
and ":" not in s
and all(seg not in ("", ".", "..") for seg in s.split("/"))
)
def executable(info: zipfile.ZipInfo) -> bool:
"""Whether a package file is executable once unpacked (RustGIS keeps Unix file modes).
Args:
info: The file's entry in the package.
Returns:
True when it was packed from Unix with an execute bit.
"""
return info.create_system == 3 and bool((info.external_attr >> 16) & 0o111)
def python_script(args: list[str]) -> str | None:
"""The script a Python interpreter is given in `args` (its arguments), if any.
Args:
args: The interpreter's arguments, from `run`.
Returns:
The first argument that isn't an option, or None when there is none or the interpreter
runs a module or a command instead (`-m`, `-c`, also in a cluster of short options).
"""
skip = False
for a in args:
if skip:
skip = False
elif a.startswith(("-W", "-X")) or a == "--check-hash-based-pycs":
# An option with a value, attached (`-Wignore`, `-Xutf8`) or next (`-W ignore`).
skip = a in ("-W", "-X", "--check-hash-based-pycs")
elif a.startswith("-") and not a.startswith("--") and ("m" in a or "c" in a):
# A module or a command (`-m pkg`, `-um pkg`, `-c code`), or a short option cluster
# that may hold one: nothing to check. (Long options, `--check-hash-based-pycs`, are
# skipped below.)
return None
elif a == "-" or not a.startswith("-"):
return None if a == "-" else a
return None
def check_process(data: bytes, m: dict, where: str) -> None:
"""Checks a process plugin's package: its files, its `run` and its `python` environment.
RustGIS unpacks the package and starts `run` in that folder, so a program named by a
relative path (and the script a Python interpreter is given) must be in the package, and
the requirements file of `python` too.
Args:
data: The package's bytes.
m: Its plugin.json.
where: Where it came from, for messages.
"""
try:
with zipfile.ZipFile(io.BytesIO(data)) as z:
infos = z.infolist()
except zipfile.BadZipFile as e:
problem(f"{where}: unreadable package: {e}")
return
if len(infos) > MAX_ENTRIES:
problem(f"{where}: the package has more than {MAX_ENTRIES} files")
if sum(i.file_size for i in infos) > MAX_UNPACKED:
problem(f"{where}: the package unpacks to more than {MAX_UNPACKED >> 20} MB")
for i in infos:
n = i.filename
if n.startswith("/") or re.match(r"^[A-Za-z]:", n) or ".." in n.replace("\\", "/").split("/"):
problem(f"{where}: the package has an unsafe path: {n}")
names = [i.filename for i in infos]
root = "" if "plugin.json" in names else next((n[: -len("plugin.json")] for n in names if n.endswith("/plugin.json")), "")
files = {i.filename[len(root) :]: i for i in infos if i.filename.startswith(root) and not i.is_dir()}
# Two entries by one name: which one RustGIS unpacks last isn't what a reviewer reads.
for n in sorted(n for n, k in Counter(names).items() if k > 1):
problem(f"{where}: the package holds {n} more than once")
run = m.get("run")
if isinstance(run, list):
argvs = {"": run}
elif isinstance(run, dict) and run and set(run) <= set(RUN_PLATFORMS):
argvs = dict(run)
else:
problem(f"{where}: a process plugin needs 'run': its program and arguments (a list of strings), or an object of them by platform ({', '.join(RUN_PLATFORMS)})")
argvs = {}
for platform, argv in argvs.items():
key = f"run.{platform}" if platform else "run"
if not isinstance(argv, list) or not argv or not all(isinstance(a, str) for a in argv) or not argv[0].strip():
problem(f"{where}: '{key}' must be a program and its arguments, a list of strings")
continue
if len(argv) > MAX_RUN_ARGS or any(len(a) > MAX_TEXT or "\0" in a for a in argv):
problem(f"{where}: '{key}' must be a program and at most {MAX_RUN_ARGS - 1} arguments of at most {MAX_TEXT} characters")
prog = argv[0]
if prog.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:", prog):
problem(f"{where}: '{key}' names '{prog}': a listed plugin runs a program in its package or one on PATH, not a full path")
elif "/" in prog or "\\" in prog:
# Relative to the plugin's folder, where RustGIS starts it: `./run.sh` is `run.sh`.
prog = prog.removeprefix("./")
if not valid_path(prog):
problem(f"{where}: '{key}' names '{prog}': a program in the package needs forward slashes and no '..'")
elif prog not in files:
problem(f"{where}: '{key}' runs {prog}, which isn't in the package")
elif platform != "windows" and not prog.lower().endswith((".exe", ".bat", ".cmd")) and not executable(files[prog]):
problem(f"{where}: {prog} isn't executable in the package (pack it with its Unix file mode, as zip does on Linux and macOS)")
elif prog in PYTHONS and (script := python_script(argv[1:])) is not None:
# The script the interpreter runs, in the plugin's folder.
if not valid_path(script.removeprefix("./")) or script.removeprefix("./") not in files:
problem(f"{where}: '{key}' runs {script}, which isn't in the package")
py = m.get("python")
if py is None:
return
if not isinstance(py, dict):
problem(f"{where}: python must be an object: {{\"version\": \"3.12\", \"requirements\": \"requirements.txt\"}}")
return
version = py.get("version", "3.12")
if not isinstance(version, str) or not PYTHON_VERSION_RE.fullmatch(version):
problem(f"{where}: python.version must look like 3.12 or 3.12.4")
req = py.get("requirements", "")
if not isinstance(req, str):
problem(f"{where}: python.requirements must be the name of a requirements file in the package")
elif req and (not valid_path(req) or req not in files):
problem(f"{where}: python.requirements names {req!r}, which isn't a file in the package")
# RustGIS runs the environment's interpreter in place of `python` in `run`, and only there.
if argvs and not any(isinstance(a, list) and a and a[0] in PYTHONS for a in argvs.values()):
problem(f"{where}: the plugin declares a Python environment but 'run' doesn't start python, its interpreter")
def package_file(pid: str, version: str, platform: str | None = None) -> str:
"""A package's file name in the bucket.
Args:
pid: The plugin's id.
version: Its version.
platform: The platform the package is for, or None for a plugin's only package.
Returns:
`<id>-<version>.rgplugin`, or `<id>-<version>-<platform>.rgplugin`.
"""
return f"{pid}-{version}-{platform}.rgplugin" if platform else f"{pid}-{version}.rgplugin"
def runs_on(manifest: dict, platform: str) -> bool:
"""Whether a process plugin's `run` gives a program for a platform.
Args:
manifest: The package's plugin.json.
platform: One of PACKAGE_PLATFORMS.
Returns:
True when `run` is one program for every platform, or names this one (or `default`).
"""
run = manifest.get("run")
return isinstance(run, list) or (isinstance(run, dict) and bool(run.get(platform) or run.get("default")))
def package_name(folder: Path) -> str:
"""The cargo package name of an in-repository plugin (for `cargo build -p`)."""
return tomllib.loads((folder / "Cargo.toml").read_text(encoding="utf-8"))["package"]["name"]
def crate_name(folder: Path) -> str:
"""The plugin's crate name, which names its .wasm file."""
return package_name(folder).replace("-", "_")
def download(url: str) -> bytes:
if not url.startswith("https://"):
raise ValueError("source urls must be https://")
req = urllib.request.Request(url, headers={"User-Agent": "rustgis-plugins-registry"})
with urllib.request.urlopen(req, timeout=120) as r:
data = r.read(MAX_PACKAGE + 1)
if len(data) > MAX_PACKAGE:
raise ValueError("the package is larger than 64 MB")
return data
# --------------------------------------------------------------------------------------------
def tree_hash(folder: Path) -> str:
"""Hashes an in-repository plugin's files (its source, manifest and README), so a change
without a version bump can be caught. Only the plugin's own folder counts: a change to the
shared SDK, the workspace lockfile or the toolchain doesn't republish existing versions.
Args:
folder: The plugin's folder.
Returns:
The lower-case hex SHA-256 over every file's relative path and contents.
"""
h = hashlib.sha256()
# The files git tracks (no build output, editor backups or links to elsewhere); every file
# when this isn't a git checkout.
try:
out = subprocess.run(["git", "ls-files", "-z", "--", "."], cwd=folder, capture_output=True, check=True).stdout
files = sorted(folder / f for f in out.decode().split("\0") if f)
except (OSError, subprocess.CalledProcessError):
files = sorted(p for p in folder.rglob("*") if p.is_file() and p.relative_to(folder).parts[0] != "target")
for f in files:
if not f.is_file() or f.is_symlink():
continue
h.update(f.relative_to(folder).as_posix().encode() + b"\0")
h.update(hashlib.sha256(f.read_bytes()).digest())
return h.hexdigest()
MAX_INDEX = 256 * 1024 * 1024
def load_index(source: str | None) -> dict:
"""Reads the previous deploy's package index.
Only a missing index (404: the first deploy) means "no index". Any other failure (network,
timeout, a truncated or malformed file) is a problem, because without the index the check
that in-repository plugins bumped their version can't run.
Args:
source: A URL or a file path, or None for no index.
Returns:
The index's plugins by id (empty when there is none or it can't be read).
"""
if not source:
return {}
try:
if source.startswith("https://"):
req = urllib.request.Request(f"{source}?{time.time_ns()}", headers={"User-Agent": "rustgis-plugins-registry", "Cache-Control": "no-cache"})
with urllib.request.urlopen(req, timeout=60) as r:
raw = r.read(MAX_INDEX + 1)
else:
raw = Path(source).read_bytes()
if len(raw) > MAX_INDEX:
raise ValueError(f"larger than {MAX_INDEX // (1024 * 1024)} MB")
data = json.loads(raw)
except urllib.error.HTTPError as e:
if e.code == 404:
print("note: no package index yet (first deploy); reusing packages already in the bucket", file=sys.stderr)
return {}
problem(f"the package index {source} couldn't be read ({e}); rerun once it is reachable")
return {}
except Exception as e: # noqa: BLE001 - any other failure stops a checked build
problem(f"the package index {source} couldn't be read ({e}); rerun once it is reachable")
return {}
return {p["id"]: p for p in data.get("plugins", []) if valid_cached(p)}
def valid_cached(p: object) -> bool:
"""Whether a package index entry has what reusing it needs; anything else is rebuilt.
Args:
p: An entry from the index.
Returns:
True when it can be reused.
"""
if not isinstance(p, dict):
return False
m = p.get("manifest")
def package(v: object) -> bool:
return isinstance(v, dict) and SHA_RE.match(str(v.get("sha256", ""))) is not None and isinstance(v.get("size"), int)
# One package, or one per platform.
platforms = p.get("platforms")
if platforms is None:
packaged = package(p)
else:
packaged = isinstance(platforms, dict) and bool(platforms) and set(platforms) <= set(PACKAGE_PLATFORMS) and all(map(package, platforms.values()))
return (
isinstance(p.get("id"), str)
and isinstance(p.get("version"), str)
and packaged
and isinstance(p.get("origin"), dict)
and isinstance(m, dict)
and m.get("id") == p["id"]
and m.get("version") == p["version"]
)
def published(url: str) -> bytes | None:
"""Downloads a package already in the bucket (bypassing caches, so a cached 404 isn't
believed).
Args:
url: The package's URL.
Returns:
Its bytes, or None when it isn't there.
Raises:
Exception: when the bucket can't be asked (anything but a 404).
"""
try:
return download(f"{url}?{time.time_ns()}")
except urllib.error.HTTPError as e:
if e.code == 404:
return None
raise
# What --inspect unpacks of a process plugin for review: its text files, up to these sizes.
MAX_REVIEW_FILE = 1024 * 1024
MAX_REVIEW = 16 * 1024 * 1024
def cell(value: object) -> str:
"""Package text for a cell of the review report's table: one line, with `|` escaped.
Args:
value: Text from a manifest.
Returns:
The cell's text.
"""
return " ".join(str(value).split()).replace("|", "\\|")
def unpack_for_review(data: bytes, dest: Path) -> list[str]:
"""Writes a process plugin's text files (its code) under `dest`, for review; never runs them.
Only files under the package's plugin.json, by paths inside the package (no `..`, nothing
absolute), that are UTF-8 text, at most MAX_REVIEW_FILE each and MAX_REVIEW in all. Every
file is listed (the first MAX_ENTRIES), with its size and whether it is executable, so
binaries show up too. At most twice MAX_REVIEW is decompressed, whatever the headers say.
Args:
data: The package's bytes.
dest: The folder to write to (`<out>/plugins/<id>/files`).
Returns:
The listing: one line per file in the package.
"""
lines, total = [], 0
with zipfile.ZipFile(io.BytesIO(data)) as z:
infos = [i for i in z.infolist() if not i.is_dir()]
names = [i.filename for i in infos]
root = "" if "plugin.json" in names else next((n[: -len("plugin.json")] for n in names if n.endswith("/plugin.json")), "")
seen: set[str] = set()
spent = 0 # bytes decompressed, kept or not
if len(infos) > MAX_ENTRIES:
lines.append(f"(the package holds {len(infos):,} files; only the first {MAX_ENTRIES:,} are listed)")
infos = infos[:MAX_ENTRIES]
for i in infos:
rel = i.filename[len(root) :] if i.filename.startswith(root) else None
# Names are the package's say-so: quoted, so one can't pass for lines of its own.
name = json.dumps(rel if rel is not None else i.filename, ensure_ascii=False)
link = i.create_system == 3 and (i.external_attr >> 16) & 0o170000 == 0o120000
how = ("a symbolic link in the zip (RustGIS unpacks it as a file holding its target), " if link else "")
how += ("executable, " if executable(i) else "") + f"{i.file_size:,} B"
if i.filename in seen:
lines.append(f"{name} ({how}): not unpacked (the package holds this name more than once)")
continue
seen.add(i.filename)
if rel is None or not valid_path(rel):
lines.append(f"{name} ({how}): not unpacked (outside the plugin's folder, or an unsafe path)")