Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
executable file
·1199 lines (1066 loc) · 41.9 KB
/
Copy pathinstall.py
File metadata and controls
executable file
·1199 lines (1066 loc) · 41.9 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
"""Install box-rpg on the system.
Checks that the system is Linux with Python 3.14+ and pip, then installs the
selected distributions at user level: the box-rpg CLI with its shell
completions, and the box-rpg-maker GTK GUI with its desktop entry and icons.
No sudo is needed. By default it only verifies the prerequisites,
reports the installed / repo versions and shows the exact commands; pass
--install to actually run them (with a confirmation prompt) and --yes to skip
the prompt. Pass --uninstall to remove the selected packages and their files.
Pass --target {cli,gui,all} to select which distributions to manage.
"""
from __future__ import annotations
import argparse
import contextlib
import gettext
import json
import os
import re
import shlex
import shutil
import site
import stat
import subprocess
import sys
import tempfile
import uuid
from collections.abc import Callable, Generator, Sequence
from ctypes.util import find_library
from pathlib import Path
from typing import cast
REPO_ROOT = Path(__file__).resolve().parent
CLI_ROOT = REPO_ROOT / "box-rpg"
GUI_ROOT = REPO_ROOT / "box-gui"
PACKAGE = "box-rpg"
GUI_PACKAGE = "box-rpg-maker"
PACKAGES = (PACKAGE, GUI_PACKAGE)
DESKTOP_FILE_NAME = "io.gitlab.christvh.BoxRpgApp.desktop"
BWRAP = Path("/usr/bin/bwrap")
GPG = Path("/usr/bin/gpg")
# Managed shell completions are always published from the current checkout:
# install overwrites any existing file and uninstall removes it. Symlinks are
# never followed and raced replacements are preserved, never overwritten.
# update_managed_file serves every managed file (completions, desktop entry,
# icons) through this same protected path.
# Run only under -I: load trusted pip before exposing user metadata. The
# path-entry finder blocks ALL imports from user-site, including lazy imports.
# Unlike addsitedir(), this never processes .pth files or sitecustomize.
USER_PIP_BOOTSTRAP = """
import json, os, site, sys
from pathlib import Path
from importlib import metadata
from pip._internal.cli.main import main
home = Path.home().resolve()
user_site = Path(site.getusersitepackages()).resolve()
if (not home.is_absolute() or not user_site.is_absolute()
or user_site == home or not user_site.is_relative_to(home)
or '..' in user_site.parts):
raise SystemExit('error: user-site must be inside the user home')
descriptor = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
current = Path('/')
for component in user_site.parts[1:]:
current /= component
try:
child = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
dir_fd=descriptor)
except FileNotFoundError:
break
os.close(descriptor)
descriptor = child
entry = os.fstat(descriptor)
if current.is_relative_to(home) and (
entry.st_uid != os.getuid() or entry.st_mode & 0o022
):
raise SystemExit('error: user-site ancestors must be user-owned without group/other write')
finally:
os.close(descriptor)
class MetadataOnlyFinder:
def find_spec(self, fullname, target=None):
return None
sys.path_importer_cache[str(user_site)] = MetadataOnlyFinder()
sys.path.insert(0, str(user_site))
# Permit pip's explicit --user scheme, not Python's site initialization.
site.ENABLE_USER_SITE = True
if sys.argv[1] in ('--verify-user-distribution', 'uninstall'):
distribution = metadata.distribution('__PACKAGE__')
location = Path(distribution.locate_file('')).resolve()
if location != user_site:
raise SystemExit('error: refusing a non-user-site distribution')
if sys.argv[1] == '--verify-user-distribution':
print(json.dumps([str(location), str(user_site)]))
raise SystemExit(0)
raise SystemExit(main(['--isolated', *sys.argv[1:]]))
"""
def _languages() -> tuple[str, ...] | None:
"""Return locale candidates for the standalone installer."""
language = os.environ.get("LANGUAGE")
if language:
return tuple(value for value in language.split(":") if value)
for name in ("LC_ALL", "LC_MESSAGES", "LANG"):
value = os.environ.get(name)
if value:
return (value,)
return None
_ = gettext.NullTranslations().gettext
def _configure_translation() -> None:
"""Load the standalone installer's catalog for the current environment."""
global _
_ = gettext.translation(
"box",
localedir=CLI_ROOT / "src/box/locale",
languages=_languages(),
fallback=True,
).gettext
argparse._ = _ # pyright: ignore[reportAttributeAccessIssue]
# User-level completion dirs (no root required); the parent dirs are created
# on demand during install / uninstall.
COMPLETION_TARGETS = [
(
CLI_ROOT / "res/completions/box-rpg.bash",
Path.home() / ".local/share/bash-completion/completions/box-rpg",
),
(
CLI_ROOT / "res/completions/box-rpg.fish",
Path.home() / ".config/fish/completions/box-rpg.fish",
),
(
CLI_ROOT / "res/completions/_box-rpg",
Path.home() / ".local/share/zsh/site-functions/_box-rpg",
),
]
def _default_gui_targets() -> list[tuple[Path, Path]]:
"""Resolve the GUI desktop entry plus every currently bundled icon."""
targets = [
(
GUI_ROOT / "res" / DESKTOP_FILE_NAME,
Path.home() / ".local/share/applications" / DESKTOP_FILE_NAME,
)
]
icons_dir = GUI_ROOT / "res" / "icons"
if icons_dir.is_dir():
for icon in sorted(icons_dir.glob("*.svg")):
targets.append(
(
icon,
Path.home() / ".local/share/icons/hicolor/scalable/apps" / icon.name,
)
)
return targets
# Managed GUI files are always published from the current checkout, like
# completions: install overwrites any existing file and uninstall removes it.
# Icon names are never hardcoded; they follow whatever res/icons/ ships.
GUI_TARGETS = _default_gui_targets()
def selected_packages(target: str) -> tuple[str, ...]:
"""Return the distributions covered by an install/uninstall target."""
if target == "cli":
return (PACKAGE,)
if target == "gui":
return (GUI_PACKAGE,)
return PACKAGES
def is_linux() -> bool:
"""Return whether the active Python interpreter runs on Linux."""
return sys.platform.startswith("linux")
def _check_python_version() -> bool:
return sys.version_info >= (3, 14)
def _versioning_helpers() -> tuple[Callable[[Path], str], Callable[[Path, str], None]] | None:
"""Load (compute_version, write_version_file) from the monorepo tools.
Tries the ``tools`` package first (normal ``./install.py`` runs from the
repo root) then the top-level ``versioning`` module (contexts like the
test suite that put ``tools/`` itself on ``sys.path``). Returns None
when neither is importable. The declared return type keeps strict
type-checking exact at the call sites.
"""
try:
from tools.versioning import compute_version, write_version_file
return compute_version, write_version_file
except ImportError:
pass
try:
from versioning import compute_version as _compute # type: ignore[no-redef]
from versioning import write_version_file as _write # type: ignore[no-redef]
return cast(
"tuple[Callable[[Path], str], Callable[[Path, str], None]]",
(_compute, _write),
)
except ImportError:
return None
def _dynamic_repo_version() -> str:
"""Return the checkout version computed from git history.
Never reads installed metadata: callers compare Repo against Installed
to detect updates, so both sides must stay independent. Returns
``"unknown"`` outside a git checkout.
"""
helpers = _versioning_helpers()
if helpers is None:
return "unknown"
compute_version, _ = helpers
try:
return compute_version(REPO_ROOT)
except Exception:
return "unknown"
def repo_version() -> str:
"""Return the checkout version for the box-rpg distribution."""
return _dynamic_repo_version()
def gui_repo_version() -> str:
"""Return the checkout version for the box-rpg-maker distribution."""
return _dynamic_repo_version()
def installed_version(package: str = PACKAGE) -> str | None:
"""Return the installed distribution version, or None if not installed.
The user site-packages are checked explicitly so the detection works
even when this script runs from inside a virtualenv (whose pip cannot
do --user installs and whose site-packages hide the user ones).
"""
user_site = Path(site.getusersitepackages())
try:
from importlib import metadata
return next(
distribution.version
for distribution in metadata.distributions(path=[str(user_site)])
if distribution.metadata["Name"] == package
)
except Exception: # PackageNotFoundError / import errors
return None
def _version_tuple(version: str) -> tuple[int, ...]:
parts = re.findall(r"\d+", version)
return tuple(int(p) for p in parts)
def compare_versions(a: str, b: str) -> int:
"""Compare two dotted versions numerically; -1 if a < b, 0 equal, 1 if a > b."""
ta, tb = _version_tuple(a), _version_tuple(b)
width = max(len(ta), len(tb))
ta = ta + (0,) * (width - len(ta))
tb = tb + (0,) * (width - len(tb))
return (ta > tb) - (ta < tb)
def _command_environment() -> dict[str, str]:
"""Sanitize the environment for installer subprocesses.
Loader injection variables must not reach venv/pip children, and PATH is
pinned because every installer command uses absolute interpreter paths.
"""
environment = {
key: value
for key, value in os.environ.items()
if not key.startswith(("PIP_", "PYTHON", "LD_", "DYLD_")) and key != "VIRTUAL_ENV"
}
environment["PATH"] = "/usr/bin:/bin"
environment["PIP_CONFIG_FILE"] = os.devnull
return environment
def run(args: list[str]) -> int:
"""Run a command, streaming output, returning its exit code."""
proc = subprocess.run(args, check=False, env=_command_environment())
return proc.returncode
def system_python() -> str:
"""Return the system (non-venv) python, since --user installs need it."""
base = Path(sys.base_exec_prefix) / "bin" / "python3"
if base.is_file():
return str(base)
return sys.executable
def has_pip() -> bool:
"""Return whether the system Python can invoke pip."""
try:
result = subprocess.run(
[system_python(), "-I", "-m", "pip", "--version"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=_command_environment(),
)
except OSError:
return False
return result.returncode == 0
def _tool_runs(command: list[str]) -> bool:
"""Return whether a helper tool executes successfully."""
try:
result = subprocess.run(
command,
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env=_command_environment(),
)
except OSError:
return False
return result.returncode == 0
def bwrap_problem() -> str | None:
"""Return None when Bubblewrap can launch games, else a short reason."""
if not (BWRAP.is_file() and os.access(BWRAP, os.X_OK)):
return "missing"
if not _tool_runs([str(BWRAP), "--version"]):
return "broken"
# Reproduce the namespaces every launch needs; library binds are required
# or the probe binary cannot even start (misleading exec failure).
if not _tool_runs(
[
str(BWRAP),
"--unshare-user",
"--unshare-pid",
"--unshare-ipc",
"--unshare-uts",
"--ro-bind",
"/usr",
"/usr",
"--ro-bind",
"/lib",
"/lib",
"--ro-bind",
"/lib64",
"/lib64",
"--",
"/usr/bin/true",
]
):
return "userns"
return None
def gpg_problem() -> str | None:
"""Return None when GnuPG can verify runtimes, else a short reason."""
if not (GPG.is_file() and os.access(GPG, os.X_OK)):
return "missing"
if not _tool_runs([str(GPG), "--version"]):
return "broken"
return None
def gtk_problem() -> str | None:
"""Return None when the GTK4/libadwaita typelibs resolve, else a reason."""
probe = (
"import gi; gi.require_version('Gtk', '4.0'); gi.require_version('Adw', '1'); "
"from gi.repository import Gtk, Adw"
)
if not _tool_runs([system_python(), "-I", "-c", probe]):
return "missing"
return None
def fuse3_problem() -> str | None:
"""Return None when the case-insensitive mount backend is usable, else a reason."""
try:
found = find_library("fuse3")
except Exception:
return "missing"
if found is None:
return "missing"
if not Path("/dev/fuse").exists():
return "no-device"
return None
def icoextract_problem() -> str | None:
"""Return None when game icon extraction is available, else a reason."""
if not _tool_runs([system_python(), "-I", "-c", "import icoextract"]):
return "missing"
return None
allow_system_packages = False
force_reinstall = False
def _break_system_packages_args() -> list[str]:
"""Override PEP 668 only with separate, explicit consent."""
return ["--break-system-packages"] if allow_system_packages else []
@contextlib.contextmanager
def open_directory(path: Path, *, create: bool = False) -> Generator[int]:
"""Open every absolute path component without following symbolic links."""
if not path.is_absolute() or ".." in path.parts:
raise PermissionError(path)
descriptor = os.open("/", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
for component in path.parts[1:]:
if create:
with contextlib.suppress(FileExistsError):
os.mkdir(component, mode=0o700, dir_fd=descriptor)
child = os.open(
component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=descriptor
)
os.close(descriptor)
descriptor = child
yield descriptor
finally:
os.close(descriptor)
def read_regular(parent: int, name: str) -> bytes:
"""Read a regular file, never a symlink, FIFO or device."""
descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
with os.fdopen(descriptor, "rb") as stream:
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
raise PermissionError(name)
return stream.read()
def remove_matching(parent: int, name: str, expected: bytes) -> None:
"""Capture before checking ownership; never unlink a raced replacement.
A conflicting replacement is retained in the private recovery directory if
its original name is occupied. No existing name is overwritten on recovery.
"""
recovery = f".box-rpg-recovery-{uuid.uuid4().hex}"
os.mkdir(recovery, mode=0o700, dir_fd=parent)
with contextlib.ExitStack() as stack:
descriptor = os.open(recovery, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
stack.callback(os.close, descriptor)
captured = False
try:
os.rename(name, "entry", src_dir_fd=parent, dst_dir_fd=descriptor)
captured = True
if read_regular(descriptor, "entry") != expected:
raise PermissionError(f"Modified or unowned file: {name}")
os.unlink("entry", dir_fd=descriptor)
captured = False
finally:
if captured:
try:
os.link(
"entry",
name,
src_dir_fd=descriptor,
dst_dir_fd=parent,
follow_symlinks=False,
)
except OSError as exc:
raise PermissionError(f"File preserved in {recovery}/entry") from exc
os.unlink("entry", dir_fd=descriptor)
os.rmdir(recovery, dir_fd=parent)
def update_managed_file(source: Path, target: Path, *, uninstall: bool = False) -> None:
"""Publish the current managed file, replacing any existing file on install."""
home = Path.home()
if target == home or not target.is_relative_to(home) or ".." in target.parts:
raise PermissionError(f"Managed file outside home: {target}")
with open_directory(source.parent) as source_parent:
expected = read_regular(source_parent, source.name)
try:
with open_directory(target.parent, create=not uninstall) as parent:
try:
existing = read_regular(parent, target.name)
except FileNotFoundError:
if uninstall:
return
else:
if uninstall or existing != expected:
remove_matching(parent, target.name, existing)
if uninstall or existing == expected:
return
temporary = f".box-rpg-{uuid.uuid4().hex}"
descriptor = os.open(
temporary,
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
0o600,
dir_fd=parent,
)
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(expected)
os.link(temporary, target.name, src_dir_fd=parent, dst_dir_fd=parent)
finally:
os.unlink(temporary, dir_fd=parent)
except FileNotFoundError:
if not uninstall:
raise
def _user_distribution_verified(package: str = PACKAGE) -> bool:
"""Verify what the base interpreter (and therefore pip) will select."""
try:
result = subprocess.run(
[*_user_pip_args(package), "--verify-user-distribution"],
check=False,
capture_output=True,
text=True,
env=_command_environment(),
)
payload: object = json.loads(result.stdout)
if not isinstance(payload, list):
return False
locations = cast(list[object], payload)
return (
result.returncode == 0
and len(locations) == 2
and isinstance(locations[0], str)
and locations[0] == locations[1]
and Path(locations[0]).is_relative_to(Path.home().resolve())
)
except OSError, ValueError:
return False
def _user_pip_args(package: str = PACKAGE) -> list[str]:
return [system_python(), "-I", "-c", USER_PIP_BOOTSTRAP.replace("__PACKAGE__", package)]
def _pip_install_args(
wheel: Path, *, with_dependencies: bool = False, extra_wheels: Sequence[Path] = ()
) -> list[str]:
args = [
*_user_pip_args(),
"install",
"--user",
]
if not with_dependencies:
# The CLI ships zero runtime dependencies; the GUI wheel installs its
# real dependencies (PyGObject, pycairo, icoextract) instead, with the
# backend pinned to the just-built local wheel rather than PyPI.
args += ["--no-deps", "--no-index"]
args += [
str(wheel),
*(str(extra) for extra in extra_wheels),
"--no-input",
"--no-warn-script-location",
"--disable-pip-version-check",
]
if force_reinstall:
args.append("--force-reinstall")
return [*args, *_break_system_packages_args()]
def user_bin_without_path() -> Path | None:
"""Return the user script directory when it is missing from PATH."""
user_bin = Path(site.getusersitepackages()).parents[2] / "bin"
if str(user_bin) not in os.environ.get("PATH", "").split(os.pathsep):
return user_bin
return None
def _staged_version_file(destination: Path, project_dir: Path | None) -> Path:
"""Return where the generated _version.py lives in staged build sources."""
if (CLI_ROOT if project_dir is None else project_dir) == GUI_ROOT:
return destination / "src/box_gui/_version.py"
return destination / "src/box/_version.py"
def copy_build_source(destination: Path, project_dir: Path | None = None) -> None:
"""Stage the trusted checkout without venvs or previous build artifacts."""
source_root = (
CLI_ROOT if project_dir is None else project_dir
) # Nested workspaces (e.g. the GUI build stages cli/ and gui/ side by
# side) may not exist yet; still refuse to reuse an existing destination.
destination.mkdir(parents=True)
for name in ("pyproject.toml", "README.md"):
shutil.copyfile(source_root / name, destination / name)
# The license lives once at the monorepo root but ships in both wheels.
shutil.copyfile(REPO_ROOT / "LICENSE", destination / "LICENSE")
for name in ("src", "res"):
shutil.copytree(
source_root / name,
destination / name,
ignore=shutil.ignore_patterns("__pycache__", "*.egg-info"),
)
if source_root == GUI_ROOT:
# The GUI project ships no separate requirements lock by design; its
# wheel build reuses the shared locked build environment, so stage the
# backend build lock where _build_commands expects it.
requirements = destination / "res" / "requirements" / "build.txt"
requirements.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(CLI_ROOT / "res/requirements/build.txt", requirements)
else:
# Backend docs live outside the backend project directory in the
# monorepo; stage them back under docs/ for the share/doc data files.
monorepo_docs = REPO_ROOT / "docs" / "box-rpg"
if monorepo_docs.is_dir():
shutil.copytree(
monorepo_docs,
destination / "docs",
ignore=shutil.ignore_patterns("__pycache__", "*.egg-info"),
)
# Dynamic versions resolve from a generated _version.py that never lives
# in git: stamp the staged copy so isolated wheel builds (which ship no
# tools/) work from a fresh clone without a manual stamping step first.
helpers = _versioning_helpers()
if helpers is None:
raise RuntimeError("cannot stamp _version.py: tools/versioning.py is unavailable")
_compute_version, _write_version_file = helpers
_write_version_file(
_staged_version_file(destination, project_dir),
_compute_version(REPO_ROOT),
)
def _wheel_args(python: Path, workspace: Path) -> list[str]:
return [
str(python),
"-I",
"-m",
"pip",
"--isolated",
"wheel",
"--no-build-isolation",
"--no-deps",
"--no-index",
"--no-input",
"--disable-pip-version-check",
"--wheel-dir",
str(workspace / "wheels"),
str(workspace / "source"),
]
def _build_commands(workspace: Path) -> list[list[str]]:
python = workspace / "venv/bin/python"
return [
[sys.executable, "-I", "-m", "venv", str(workspace / "venv")],
[
str(python),
"-I",
"-m",
"pip",
"--isolated",
"install",
"--require-hashes",
"--only-binary=:all:",
"--force-reinstall",
"--index-url",
"https://pypi.org/simple",
"--no-input",
"--disable-pip-version-check",
"-r",
str(workspace / "source/res/requirements/build.txt"),
],
_wheel_args(python, workspace),
]
def build_wheel(
workspace: Path,
project_dir: Path | None = None,
*,
wheel_glob: str = "box_rpg-*.whl",
label: str = PACKAGE,
) -> Path:
"""Build with hash-checked tools in a private, disposable environment."""
copy_build_source(workspace / "source", project_dir)
for command in _build_commands(workspace):
if run(command) != 0:
raise RuntimeError("locked wheel build failed")
wheels = list((workspace / "wheels").glob(wheel_glob))
if len(wheels) != 1 or not wheels[0].is_file() or wheels[0].is_symlink():
raise RuntimeError(f"expected exactly one {label} wheel")
return wheels[0]
def _pip_uninstall_args(package: str = PACKAGE) -> list[str]:
"""Build pip's user-level uninstall command."""
args = [*_user_pip_args(package), "uninstall", "-y", package]
return [*args, *_break_system_packages_args()]
def install_commands(target: str = "all") -> list[str]:
workspace = Path("<private-temporary-directory>")
cmds: list[str] = []
if target in ("cli", "all"):
cmds.append(
"stage trusted checkout in private temporary directory; "
+ " && ".join(shlex.join(command) for command in _build_commands(workspace))
+ " && "
+ shlex.join(_pip_install_args(workspace / "wheels/box_rpg-<version>-py3-none-any.whl"))
+ "; clean up temporary directory"
)
for source, destination in COMPLETION_TARGETS:
cmds.append(
f"safe completion install: {shlex.quote(str(source))}"
f" -> {shlex.quote(str(destination))}"
)
if target in ("gui", "all"):
cmds.append(
"stage trusted GUI checkout in private temporary directory; "
+ " && ".join(shlex.join(command) for command in _build_commands(workspace))
+ " && "
+ shlex.join(
_pip_install_args(
workspace / "wheels/box_rpg_maker-<version>-py3-none-any.whl",
extra_wheels=(workspace / "wheels/box_rpg-<version>-py3-none-any.whl",),
with_dependencies=True,
)
)
+ "; clean up temporary directory"
)
for source, destination in GUI_TARGETS:
cmds.append(
f"safe GUI file install: {shlex.quote(str(source))}"
f" -> {shlex.quote(str(destination))}"
)
return cmds
def run_install(target: str = "all") -> bool:
if os.geteuid() == 0:
print(_("error: refusing to run as root"), file=sys.stderr)
return False
ok = True
if target in ("cli", "all"):
try:
with tempfile.TemporaryDirectory(prefix="box-rpg-build-") as directory:
wheel = build_wheel(Path(directory))
if run(_pip_install_args(wheel)) != 0:
raise RuntimeError("pip install failed")
except (OSError, RuntimeError) as exc:
print(f"error: {exc}", file=sys.stderr)
return False
done = 0
for source, destination in COMPLETION_TARGETS:
if not source.exists():
print(
_("warning: completion source missing: {source}").format(source=source),
file=sys.stderr,
)
continue
try:
update_managed_file(source, destination)
except OSError as exc:
print(
_("error: cannot install completion {target}: {error}").format(
target=destination, error=exc
),
file=sys.stderr,
)
ok = False
continue
done += 1
print(_("installed {count} shell completions").format(count=done))
if target in ("gui", "all"):
try:
with tempfile.TemporaryDirectory(prefix="box-rpg-maker-build-") as directory:
base = Path(directory)
# The GUI depends on the backend, so pin it to the just-built
# local wheel in the same pip invocation instead of PyPI.
cli_wheel = build_wheel(base / "cli")
gui_wheel = build_wheel(
base / "gui",
GUI_ROOT,
wheel_glob="box_rpg_maker-*.whl",
label=GUI_PACKAGE,
)
if (
run(
_pip_install_args(
gui_wheel, extra_wheels=(cli_wheel,), with_dependencies=True
)
)
!= 0
):
raise RuntimeError("pip install failed")
except (OSError, RuntimeError) as exc:
print(f"error: {exc}", file=sys.stderr)
return False
done = 0
for source, destination in GUI_TARGETS:
if not source.exists():
print(
_("warning: GUI source missing: {source}").format(source=source),
file=sys.stderr,
)
continue
try:
update_managed_file(source, destination)
except OSError as exc:
print(
_("error: cannot install GUI file {target}: {error}").format(
target=destination, error=exc
),
file=sys.stderr,
)
ok = False
continue
done += 1
print(_("installed {count} GUI files").format(count=done))
return ok
def uninstall_commands(target: str = "all") -> list[str]:
cmds: list[str] = []
if target in ("cli", "all"):
cmds.append(shlex.join(_pip_uninstall_args()))
for _source, destination in COMPLETION_TARGETS:
cmds.append(f"safe completion removal: {shlex.quote(str(destination))}")
if target in ("gui", "all"):
cmds.append(shlex.join(_pip_uninstall_args(GUI_PACKAGE)))
for _source, destination in GUI_TARGETS:
cmds.append(f"safe GUI file removal: {shlex.quote(str(destination))}")
return cmds
def run_uninstall(target: str = "all") -> bool:
if os.geteuid() == 0:
print(
_("error: uninstall requires a verified user-site package and a non-root user"),
file=sys.stderr,
)
return False
ok = True
for package in selected_packages(target):
if installed_version(package) is None:
continue
if not _user_distribution_verified(package):
print(
_("error: uninstall requires a verified user-site package and a non-root user"),
file=sys.stderr,
)
return False
if run(_pip_uninstall_args(package)) != 0:
print(_("error: pip uninstall failed"), file=sys.stderr)
ok = False
managed: list[tuple[Path, Path]] = []
if target in ("cli", "all"):
managed += COMPLETION_TARGETS
if target in ("gui", "all"):
managed += GUI_TARGETS
done = 0
for source, destination in managed:
try:
update_managed_file(source, destination, uninstall=True)
except OSError as exc:
print(
_("error: failed to remove managed file {target}: {error}").format(
target=destination, error=exc
),
file=sys.stderr,
)
ok = False
else:
done += 1
print(_("removed {count} managed files").format(count=done))
return ok
def print_commands(title: str, cmds: list[str]) -> None:
print(f"\n{title}")
for cmd in cmds:
print(f" {cmd}")
def _prompt(prompt: str) -> str | None:
"""Read one interactive response, treating end-of-input as cancellation."""
try:
return input(prompt).strip().lower()
except EOFError:
print(_("Aborted."))
return None
def main() -> int:
global allow_system_packages, force_reinstall
_configure_translation()
parser = argparse.ArgumentParser(
description=_(
"""Install box-rpg on the system.
Checks that the system is Linux with Python 3.14+ and pip, then installs the
selected distributions at user level: the box-rpg CLI with its shell
completions, and the box-rpg-maker GTK GUI with its desktop entry and icons.
No sudo is needed. By default it only verifies prerequisites,
reports installed / repo versions and shows the exact commands; pass --install
to actually run them (with a confirmation prompt) and --yes to skip the
prompt. Pass --uninstall to remove the selected packages and their files.
Pass --target {cli,gui,all} to select which distributions to manage."""
)
)
parser.add_argument(
"--install",
action="store_true",
help=_("actually install (default is a dry run)"),
)
parser.add_argument(
"--uninstall",
action="store_true",
help=_("uninstall the selected packages and their files"),
)
parser.add_argument(
"--yes",
action="store_true",
help=_("skip the confirmation prompts"),
)
parser.add_argument(
"--break-system-packages",
action="store_true",
help="explicitly allow pip to override PEP 668 (not implied by --yes)",
)
parser.add_argument(
"--force-reinstall",
action="store_true",
help=_("reinstall the package even when the same version is installed"),
)
parser.add_argument(
"--target",
choices=("cli", "gui", "all"),
default="all",
help=_("select which distributions to manage: cli, gui, or all"),
)
parser.add_argument(
"--verbose",
action="store_true",
help=_("show the exact commands that would run"),
)
args = parser.parse_args()
allow_system_packages = args.break_system_packages
force_reinstall = args.force_reinstall
if args.install and args.uninstall:
print(_("error: --install and --uninstall are mutually exclusive"), file=sys.stderr)
return 1
if not is_linux():
print(_("error: this script requires Linux"), file=sys.stderr)
return 1
print(_("OK: Linux system detected."))
if not _check_python_version():
print(
_("error: Python 3.14+ required, found {major}.{minor}").format(
major=sys.version_info.major, minor=sys.version_info.minor
),
file=sys.stderr,
)
return 1
print(
_("OK: Python {major}.{minor} found.").format(
major=sys.version_info.major, minor=sys.version_info.minor
)
)
if not has_pip():
print(_("error: pip is required for the system Python"), file=sys.stderr)
return 1
print(_("OK: pip found for the system Python."))
installed = {package: installed_version(package) for package in selected_packages(args.target)}
if args.target in ("cli", "all"):
print(_("\nInstalled: {installed}").format(installed=installed[PACKAGE] or "none"))
print(_("Repo: {repo}").format(repo=repo_version()))
if args.target in ("gui", "all"):
print(_("\nInstalled GUI: {installed}").format(installed=installed[GUI_PACKAGE] or "none"))
print(_("Repo GUI: {repo}").format(repo=gui_repo_version()))
if args.uninstall:
if all(version is None for version in installed.values()):
names = ", ".join(selected_packages(args.target))
print(_("error: {package} is not installed").format(package=names), file=sys.stderr)
return 1