-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
executable file
·1356 lines (1200 loc) · 45.7 KB
/
Copy pathinstall.py
File metadata and controls
executable file
·1356 lines (1200 loc) · 45.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
#!/usr/bin/env python3
import argparse
import importlib.util
import io
import logging
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import zipfile
from datetime import datetime
from typing import List, Set, Tuple, Union
from urllib.parse import unquote
SCRIPT_DIR = Path(__file__).resolve().parent
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
HOME_DIR = Path.home().resolve()
BACKUP_DIR = HOME_DIR / ".dotfiles-backup" / timestamp
INSTALLER_VENV_DIR = HOME_DIR / ".local" / "share" / "dotfiles-installer" / "venv"
INSTALLER_REQUIRED_PACKAGES = {"requests"}
DOTFILES = {
".bashrc",
".config/",
".gitconfig",
".local/bin/",
".p10k.zsh",
".profile",
".tmux.conf",
".zprofile",
".zsh/",
".zshrc",
}
PATHS_IGNORED_IN_DOCKER = {".gitconfig"}
# Packages needed for a working zsh environment.
# Used both on the host and inside containers.
APT_ZSH_PACKAGES = {
"autojump",
"fzf",
"jq",
"luajit",
"tmux",
"zsh",
}
# Packages only needed on the host (already in company base image or
# irrelevant inside a container).
APT_HOST_PACKAGES = {
"curl",
"eza",
"fonts-firacode",
"fonts-powerline",
"git",
"git-lfs",
"gnupg",
"golang",
"libsecret-tools",
"pipx",
"python-is-python3",
"python3-venv",
"wget",
}
APT_PACKAGES = APT_ZSH_PACKAGES | APT_HOST_PACKAGES
# UI-dependent packages that should be skipped in headless mode
UI_PACKAGES = {
"flameshot",
"gnome-shell-extension-gpaste",
"gnome-shell-extension-manager",
"gnome-shell-extension-prefs",
"gnome-shell-extensions-gpaste",
"guake",
"guake-indicator",
}
def _module_available(module_name: str) -> bool:
return importlib.util.find_spec(module_name) is not None
def _installer_venv_python() -> Path:
return INSTALLER_VENV_DIR / "bin" / "python3"
def _format_subprocess_error(cpe: subprocess.CalledProcessError) -> str:
stderr = (cpe.stderr or "").strip()
stdout = (cpe.stdout or "").strip()
output = stderr or stdout or "<no output>"
return f"exit code {cpe.returncode}; output: {output}"
def _reset_installer_venv_dir() -> None:
if INSTALLER_VENV_DIR.exists():
try:
shutil.rmtree(INSTALLER_VENV_DIR)
except OSError as exc:
print(
"Failed to clean existing installer venv directory at "
f"'{INSTALLER_VENV_DIR}'.\nDetails: {exc}",
file=sys.stderr,
)
sys.exit(1)
def _try_install_python_bootstrap_with_apt() -> bool:
apt_get = shutil.which("apt-get")
if apt_get is None:
return False
if os.geteuid() == 0:
update_command = [apt_get, "update"]
install_command = [apt_get, "install", "-y", "python3-venv", "python3-pip"]
else:
sudo = shutil.which("sudo")
if sudo is None:
print(
"python3-venv/python3-pip are required but 'sudo' is not available for apt install.",
file=sys.stderr,
)
return False
update_command = [sudo, apt_get, "update"]
install_command = [
sudo,
apt_get,
"install",
"-y",
"python3-venv",
"python3-pip",
]
try:
subprocess.run(
update_command,
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
subprocess.run(
install_command,
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
return True
except subprocess.CalledProcessError as cpe:
print(
"Automatic apt install of python bootstrap packages failed.\n"
f"Details: {_format_subprocess_error(cpe)}",
file=sys.stderr,
)
return False
def _venv_has_pip(venv_python: Path) -> bool:
try:
subprocess.run(
[str(venv_python), "-m", "pip", "--version"],
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
return True
except subprocess.CalledProcessError:
return False
def ensure_runtime_environment() -> None:
"""Run installer from dedicated venv and ensure required Python deps exist.
Many modern distros block system/user pip installs (PEP 668). To keep setup
reproducible we bootstrap a private venv and re-exec the installer there.
"""
in_bootstrap = os.environ.get("DOTFILES_INSTALLER_VENV_ACTIVE") == "1"
missing_packages = [
pkg for pkg in INSTALLER_REQUIRED_PACKAGES if not _module_available(pkg)
]
if not missing_packages and in_bootstrap:
return
venv_python = _installer_venv_python()
if not venv_python.exists():
_reset_installer_venv_dir()
venv_creation_error: Union[subprocess.CalledProcessError, None] = None
try:
subprocess.run(
[sys.executable, "-m", "venv", str(INSTALLER_VENV_DIR)],
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
except subprocess.CalledProcessError as cpe:
venv_creation_error = cpe
if venv_creation_error is not None:
print(
"Initial venv creation failed. Trying apt install for python3-venv/python3-pip.",
file=sys.stderr,
)
if _try_install_python_bootstrap_with_apt():
_reset_installer_venv_dir()
try:
subprocess.run(
[sys.executable, "-m", "venv", str(INSTALLER_VENV_DIR)],
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
venv_creation_error = None
except subprocess.CalledProcessError as cpe:
venv_creation_error = cpe
if venv_creation_error is not None:
print(
"Failed to create installer venv at "
f"'{INSTALLER_VENV_DIR}'.\n"
"Install 'python3-venv' and 'python3-pip' (apt), then retry.\n"
f"Details: {_format_subprocess_error(venv_creation_error)}",
file=sys.stderr,
)
sys.exit(1)
if not venv_python.exists():
print(
f"Installer venv python not found at '{venv_python}'.",
file=sys.stderr,
)
sys.exit(1)
if not _venv_has_pip(venv_python):
print(
"pip is missing in installer venv. Trying apt install for python3-venv/python3-pip and recreating venv.",
file=sys.stderr,
)
if _try_install_python_bootstrap_with_apt():
_reset_installer_venv_dir()
try:
subprocess.run(
[sys.executable, "-m", "venv", str(INSTALLER_VENV_DIR)],
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
except subprocess.CalledProcessError as cpe:
print(
"Failed to recreate installer venv after apt bootstrap install.\n"
f"Details: {_format_subprocess_error(cpe)}",
file=sys.stderr,
)
sys.exit(1)
venv_python = _installer_venv_python()
if not _venv_has_pip(venv_python):
print(
"Failed to bootstrap pip in installer venv.\n"
"Install 'python3-venv' and 'python3-pip' via apt, then retry.",
file=sys.stderr,
)
sys.exit(1)
try:
subprocess.run(
[str(venv_python), "-m", "pip", "install", "--upgrade", "pip"],
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
subprocess.run(
[str(venv_python), "-m", "pip", "install"]
+ list(INSTALLER_REQUIRED_PACKAGES),
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
except subprocess.CalledProcessError as cpe:
print(
"Failed to install installer dependencies in venv.\n"
f"Details: {_format_subprocess_error(cpe)}",
file=sys.stderr,
)
sys.exit(1)
# Re-exec under dedicated installer interpreter exactly once.
if not in_bootstrap or missing_packages:
env = os.environ.copy()
env["DOTFILES_INSTALLER_VENV_ACTIVE"] = "1"
result = subprocess.run([str(venv_python), __file__, *sys.argv[1:]], env=env)
sys.exit(result.returncode)
def get_dotfiles_path(relative_path: Union[str, Path]) -> Path:
return SCRIPT_DIR / relative_path
def get_home_path(relative_path: Union[str, Path]) -> Path:
return HOME_DIR / relative_path
def verify_dotfiles_exist() -> None:
logging.debug("Verifying dotfiles to be installed")
missing_files = [
dotfile for dotfile in DOTFILES if not get_dotfiles_path(dotfile).exists()
]
if missing_files:
logging.error(
"The following dotfiles are missing in the repository: %s",
", ".join(missing_files),
)
sys.exit(1)
logging.info("All required dotfiles are present")
def setup_dotfile_links(
use_symlink: bool = True,
backup: bool = True,
dry_run: bool = False,
force: bool = False,
) -> None:
logging.debug("Setting up links for dotfiles in %s/", HOME_DIR)
links_created = {}
used_directory_symlink_fallback = False
if is_running_in_docker():
for ignored_path in PATHS_IGNORED_IN_DOCKER:
DOTFILES.remove(ignored_path)
for dotfile in DOTFILES:
dotfile_path = get_dotfiles_path(dotfile)
target_path = get_home_path(dotfile)
if dotfile_path.is_dir():
# For directories in the repo, create links for individual files
# inside the directory instead of linking the directory itself.
#
# If the home-side target is a directory-level symlink pointing
# into the repo (left over from an old install), remove it first
# so that per-file linking can take over cleanly.
if target_path.is_symlink() and target_path.is_dir():
target_resolved = target_path.resolve()
dotfile_resolved = dotfile_path.resolve()
if target_resolved == dotfile_resolved:
msg = (
"Removing stale directory symlink '%s' "
"(pointed into repo; switching to per-file links)" % target_path
)
if dry_run:
logging.debug(
"Dry-run:: would remove stale directory symlink '%s' "
"(pointed into repo; switching to per-file links)",
target_path,
)
else:
logging.info(msg)
target_path.unlink()
logging.debug(
"Creating links for files inside directory '%s'", dotfile_path
)
try:
result = create_links_for_directory(
dotfile_path, use_symlink, backup, dry_run, force
)
if result:
links_created.update(result)
except Exception as exc: # pragma: no cover - defensive logging
logging.error(
"Failed to create links for directory '%s': %s",
dotfile_path,
exc,
)
continue
result = create_link_for_file(
target_path, dotfile_path, use_symlink, backup, dry_run, force
)
if result:
links_created.update(result)
mode_label = "sym" if use_symlink else "hard"
if used_directory_symlink_fallback:
mode_label = "hard (directory entries as sym)"
logging.info(
"Successfully set up %d %s-links for dotfiles in %s",
len(links_created),
mode_label,
HOME_DIR,
)
def create_links_for_directory(
dotfile_dir: Path,
use_symlink: bool,
backup: bool,
dry_run: bool,
force: bool,
) -> dict:
links_created = {}
repo_root = SCRIPT_DIR
# Resolve the dotfile_dir to its real path on disk. If the entry in the
# repo is itself a symlink (e.g. from a previous directory-level install
# that pointed ~/.config -> dotfiles/.config), resolve it so that we are
# always walking the canonical repo directory and never following the link
# out into the live home directory.
real_dotfile_dir = dotfile_dir.resolve()
if not str(real_dotfile_dir).startswith(str(repo_root.resolve())):
logging.error(
"Directory '%s' resolves to '%s' which is outside the repository "
"root '%s'. The repo must not contain symlinks pointing outside "
"itself. Remove the offending symlink and re-run.",
dotfile_dir,
real_dotfile_dir,
repo_root,
)
sys.exit(1)
# followlinks=False so we never accidentally walk into symlinked subtrees
# inside the repo directory.
for root, _, files in os.walk(real_dotfile_dir, followlinks=False):
logging.debug("Setting up link for files in folder '%s'", root)
for name in files:
# Compute path relative to repository root so get_dotfiles_path
# and get_home_path produce the correct targets.
root_path = Path(root)
try:
rel = root_path.relative_to(repo_root.resolve())
except ValueError:
logging.warning(
"Cannot compute relative path for '%s'; skipping.", root_path
)
continue
relative_path = rel / name
dotfile_path = get_dotfiles_path(relative_path)
target_path = get_home_path(relative_path)
logging.debug(
"Setting up link for file in folder: Target '%s' -> Dotfile '%s'",
target_path,
dotfile_path,
)
result = create_link_for_file(
target_path, dotfile_path, use_symlink, backup, dry_run, force
)
if result:
links_created.update(result)
return links_created
def _existing_link_correct(
target_path: Path, dotfile_path: Path, use_symlink: bool
) -> bool:
if use_symlink:
if target_path.is_symlink() and target_path.resolve() == dotfile_path.resolve():
logging.debug(
"'%s' is already a symlink to '%s'", target_path, dotfile_path
)
return True
else:
if (
target_path.is_file()
and not target_path.is_symlink()
and target_path.samefile(dotfile_path)
):
logging.debug(
"'%s' is already a hard link to '%s'", target_path, dotfile_path
)
return True
return False
def create_link_for_file(
target_path: Path,
dotfile_path: Path,
use_symlink: bool,
backup: bool,
dry_run: bool,
force: bool,
) -> dict:
if not dry_run:
if dotfile_path.absolute() == target_path.absolute():
logging.error(
"Dotfile path and target path are the same: '%s'. "
"This should never happen — check your DOTFILES entries and "
"that the repo is not checked out inside HOME in a conflicting way.",
dotfile_path,
)
sys.exit(1)
if dotfile_path.resolve() == target_path.resolve():
# The target already resolves to the exact same file as the
# dotfile (e.g. because a parent directory is a symlink pointing
# into the repo). Nothing to do and nothing to back up.
logging.debug(
"Dotfile and target resolve to the same file; skipping: '%s'",
dotfile_path,
)
return {}
target_abs_path = target_path.absolute()
if target_abs_path.exists() or target_abs_path.is_symlink():
# STEP 1: Backup regular files/dirs (not symlinks) to BACKUP_DIR before linking.
# Symlinks are NOT backed up — they were created by a previous dotfiles run.
# Guard: skip if backup_path already exists.
if backup and target_abs_path.exists() and not target_abs_path.is_symlink():
try:
rel_path = target_abs_path.relative_to(HOME_DIR)
except ValueError:
logging.warning(
"Cannot backup '%s' — outside HOME directory",
target_abs_path,
)
else:
backup_path = BACKUP_DIR / rel_path
if backup_path.exists():
logging.debug(
"Backup already exists at '%s', skipping inline backup of '%s'",
backup_path,
target_abs_path,
)
else:
if dry_run:
logging.info(
"Dry-run:: would back up file '%s' to '%s'",
target_abs_path,
backup_path,
)
else:
backup_path.parent.mkdir(parents=True, exist_ok=True)
logging.info(
"Backing up file '%s' to '%s'",
target_abs_path,
backup_path,
)
shutil.move(str(target_abs_path), str(backup_path))
# After move, target no longer exists, fall through to link creation
# STEP 2: If force=True, remove whatever remains (symlinks, broken links) to force recreation.
if force and (target_abs_path.exists() or target_abs_path.is_symlink()):
if target_abs_path.is_dir() and not target_abs_path.is_symlink():
message = "Force removing directory '%s'" % target_abs_path
else:
message = "Force removing link '%s'" % target_abs_path
if dry_run:
logging.debug("Dry-run:: " + message)
else:
logging.debug(message)
if target_abs_path.is_dir() and not target_abs_path.is_symlink():
shutil.rmtree(target_abs_path)
else:
os.remove(target_abs_path)
# STEP 3: If not force, check if we can skip or need to fix an incorrect link.
elif not force:
if _existing_link_correct(target_path, dotfile_path, use_symlink):
logging.info("Correct link already exists: '%s'", target_abs_path)
return None
# Incorrect target (wrong symlink or leftover regular file): remove it.
if target_abs_path.exists() or target_abs_path.is_symlink():
if target_abs_path.is_dir() and not target_abs_path.is_symlink():
message = "Removing incorrect directory '%s'" % target_abs_path
else:
message = "Removing incorrect link '%s'" % target_abs_path
if dry_run:
logging.debug("Dry-run:: " + message)
else:
logging.debug(message)
if target_abs_path.is_dir() and not target_abs_path.is_symlink():
shutil.rmtree(target_abs_path)
else:
os.remove(target_abs_path)
# Verify target was removed successfully (unless dry_run)
if not dry_run and (target_abs_path.exists() or target_abs_path.is_symlink()):
raise FileExistsError(
f"Failed to remove target '{target_abs_path}' before creating link"
)
else:
logging.debug("Link '%s' does not exist yet", target_abs_path)
if not dry_run:
target_path.parent.mkdir(parents=True, exist_ok=True)
if use_symlink:
# Note: failed trying to get relative path using pathlib
relative_link = Path(os.path.relpath(dotfile_path, target_abs_path.parent))
message = f"Creating symlink: Target '{target_path}' -> Link '{relative_link}'"
if dry_run:
logging.debug("Dry-run:: " + message)
else:
logging.debug(message)
target_path.absolute().symlink_to(relative_link)
else:
message = f"Creating hard link: Target '{target_path}' -> Link '{dotfile_path}'"
if dry_run:
logging.debug("Dry-run:: " + message)
else:
logging.debug(message)
target_path.absolute().hardlink_to(dotfile_path)
return {str(target_path): str(dotfile_path)}
def install_apt_packages(dry_run: bool = False, ui: bool = False) -> None:
if shutil.which("apt-get") is None:
logging.info("apt-get not found. Skipping apt package installation.")
return
packages = APT_PACKAGES.copy()
# Add UI packages if not headless mode
if ui:
packages.extend(UI_PACKAGES)
else:
logging.info("Not installing UI packages.")
logging.info("Installing apt packages: %s", ", ".join(packages))
update_command = ["sudo", "apt-get", "update"]
try:
if not dry_run:
subprocess.run(
update_command,
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
(
available_packages,
unavailable_packages,
already_installed_packages,
) = classify_apt_packages(packages)
if not available_packages and not unavailable_packages:
logging.info("All packages are already installed")
return
if unavailable_packages:
logging.warning(
"Packages not found in apt repositories (skipped): %s",
", ".join(unavailable_packages),
)
if available_packages:
logging.info(
"The following packages will be installed: %s",
", ".join(available_packages),
)
else:
if already_installed_packages:
logging.info(
"All available packages are already installed. Nothing to do."
)
else:
logging.warning(
"No installable apt packages left after availability check."
)
return
install_command = ["sudo", "apt-get", "install", "-y"] + available_packages
if not dry_run:
result = subprocess.run(
install_command,
check=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
encoding="utf-8",
)
logging.debug(result.stdout)
except subprocess.CalledProcessError as cpe:
logging.error("Failed to install apt packages: %s", cpe.stderr)
sys.exit(1)
logging.info("Successfully installed apt packages")
def classify_apt_packages(
packages: List[str],
) -> Tuple[List[str], List[str], List[str]]:
"""
Return (available_and_missing, unavailable, already_installed).
"""
if shutil.which("apt-cache") is None:
logging.info(
"apt-cache not found. Missing packages cannot be verified and will be skipped."
)
available = []
unavailable = []
already_installed = []
for package in packages:
if (
subprocess.run(
["dpkg", "-s", package],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
).returncode
== 0
):
already_installed.append(package)
else:
# Availability cannot be verified without apt-cache.
# Keep behavior conservative and skip unverified packages.
unavailable.append(package)
return available, unavailable, already_installed
available = []
unavailable = []
already_installed = []
for package in packages:
if (
subprocess.run(
["dpkg", "-s", package], stdout=subprocess.PIPE, stderr=subprocess.PIPE
).returncode
== 0
):
already_installed.append(package)
continue
result = subprocess.run(
["apt-cache", "show", package],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
if result.returncode == 0 and result.stdout.strip():
available.append(package)
else:
unavailable.append(package)
return available, unavailable, already_installed
def get_installed_font_families() -> Set[str]:
if shutil.which("fc-list") is None:
logging.debug("fc-list not found; font presence checks are disabled.")
return set()
result = subprocess.run(
["fc-list", ":", "family"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
if result.returncode != 0:
logging.debug("fc-list failed: %s", result.stderr.strip())
return set()
families: Set[str] = set()
for line in result.stdout.splitlines():
for entry in line.split(","):
family = entry.strip().lower()
if family:
families.add(family)
return families
def _normalize_font_token(value: str) -> str:
return "".join(ch for ch in value.lower() if ch.isalnum())
def _has_font_family(
installed_families: Set[str], family_hints: Union[str, List[str]]
) -> bool:
hints = [family_hints] if isinstance(family_hints, str) else family_hints
normalized_hints = {
_normalize_font_token(hint) for hint in hints if _normalize_font_token(hint)
}
normalized_families = {
_normalize_font_token(family)
for family in installed_families
if _normalize_font_token(family)
}
# fc-list often reports extended family names like "robotomono nerd font";
# treat a family as present when any normalized hint is contained in it.
for hint in normalized_hints:
for family in normalized_families:
if hint == family or hint in family:
return True
return False
def setup_fonts(dry_run: bool = False) -> None:
import requests
font_zips = [
(
["firacode", "fira code"],
"https://github.com/ryanoasis/nerd-fonts/releases/download/v2.3.3/FiraCode.zip",
),
(
["robotomono", "roboto mono"],
"https://github.com/ryanoasis/nerd-fonts/releases/download/v2.3.3/RobotoMono.zip",
),
(
["sourcecodepro", "source code pro", "saucecodepro"],
"https://github.com/ryanoasis/nerd-fonts/releases/download/v2.3.3/SourceCodePro.zip",
),
(
["hack"],
"https://github.com/ryanoasis/nerd-fonts/releases/download/v2.3.3/Hack.zip",
),
(
["meslolgs", "meslo lgs"],
"https://github.com/ryanoasis/nerd-fonts/releases/download/v2.3.3/Meslo.zip",
),
]
font_files = [
"https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf",
"https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf",
"https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf",
"https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf",
]
# Initial snapshot; during this run we update in-memory hints instead of
# repeatedly calling fc-list (which is comparatively expensive).
installed_families = set() if dry_run else get_installed_font_families()
logging.info("Downloading and installing fonts from zip files")
for idx, (family_hints, zip_url) in enumerate(font_zips, start=1):
if _has_font_family(installed_families, family_hints):
logging.info(
"[%d/%d] Skipping %s zip (already installed)",
idx,
len(font_zips),
family_hints[0],
)
continue
if dry_run:
logging.info(
"[%d/%d] Dry-run:: would download and install %s",
idx,
len(font_zips),
zip_url,
)
continue
logging.info("[%d/%d] Downloading %s", idx, len(font_zips), zip_url)
request = requests.get(zip_url, allow_redirects=True, timeout=(10, 180))
request.raise_for_status()
zip_file = zipfile.ZipFile(io.BytesIO(request.content))
with tempfile.TemporaryDirectory() as tmp_dir:
zip_file.extractall(tmp_dir)
copy_fonts_to_directory(Path(tmp_dir), dry_run=dry_run)
for family_hint in family_hints:
installed_families.add(family_hint.lower())
logging.info("Downloading and installing individual font files")
for idx, file_url in enumerate(font_files, start=1):
filename = os.path.basename(unquote(file_url))
target_file = HOME_DIR / ".local" / "share" / "fonts" / filename
if target_file.exists():
logging.info(
"[%d/%d] Skipping %s (already installed)",
idx,
len(font_files),
filename,
)
continue
if dry_run:
logging.info(
"[%d/%d] Dry-run:: would download and install %s",
idx,
len(font_files),
filename,
)
continue
logging.info("[%d/%d] Downloading %s", idx, len(font_files), filename)
request = requests.get(file_url, allow_redirects=True, timeout=(10, 120))
request.raise_for_status()
with tempfile.TemporaryDirectory() as tmp_dir:
filepath = Path(tmp_dir) / filename
with open(filepath, "wb") as file:
file.write(request.content)
copy_fonts_to_directory(filepath, dry_run=dry_run)
command = "fc-cache -f"
logging.info("Rebuilding font cache with command: '%s'", command)
if not dry_run:
result = subprocess.run(
["fc-cache", "-f"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
logging.debug(result.stdout)
logging.info(
"Remember to configure 'MesloLGS NF' as the default font "
+ "(see https://github.com/romkatv/powerlevel10k/blob/master/font.md)"
)
def copy_fonts_to_directory(source: Path, dry_run: bool = False) -> None:
font_dir = HOME_DIR / ".local" / "share" / "fonts"
if not dry_run:
font_dir.mkdir(parents=True, exist_ok=True)
if source.is_file():
destination = font_dir / source.name
logging.debug("Moving font file '%s' to '%s'", source, font_dir)
if not dry_run:
shutil.move(str(source), str(destination))
return
logging.debug("Moving all font files from directory '%s' to '%s'", source, font_dir)
for file in source.iterdir():
if file.suffix in (".ttf", ".otf", ".ttc"):
destination = font_dir / file.name
logging.debug("Moving file '%s' to '%s'", file, destination)
if not dry_run:
shutil.move(str(file), str(destination))
else:
logging.debug("Skipping non-font file '%s'", file)
def _install_zsh_packages() -> None:
"""Install zsh dependencies inside the container via apt (idempotent).
Skips entirely if all packages are already installed.
The /var/cache/apt/archives/ volume used by alias caches .deb files across --rm runs.
"""
missing: list[str] = []
for pkg in APT_ZSH_PACKAGES:
result = subprocess.run(
["dpkg", "-s", pkg],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode != 0:
missing.append(pkg)
if not missing:
logging.info("All container zsh packages already installed")
return
logging.info("Installing container zsh packages: %s", ", ".join(missing))
try:
subprocess.run(
["sudo", "apt-get", "update", "-qq"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
subprocess.run(
["sudo", "apt-get", "install", "-y", "--no-install-recommends"] + missing,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
logging.info("Container zsh packages installed successfully")
except subprocess.CalledProcessError as exc:
logging.warning("Failed to install container zsh packages: %s", exc.stderr)
def run_additional_setup_in_container() -> None:
logging.info("Running additional setup in container")
# 1. Install zsh apt dependencies (idempotent, cached debs)
_install_zsh_packages()
# 2. Seed zinit cache from host mount into named volume (first run only)
zinit_cache_path = Path(".local") / "share" / "zinit"
host_home_mount_path = Path("/mnt/host_home")
host_zinit_cache = host_home_mount_path / zinit_cache_path
container_zinit_cache = HOME_DIR / zinit_cache_path
if host_zinit_cache.exists() and not container_zinit_cache.exists():
logging.info(
"Copying zinit cache from '%s' to '%s'",
host_zinit_cache,
container_zinit_cache,
)
container_zinit_cache.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(host_zinit_cache, container_zinit_cache)
else:
logging.debug(
"Zinit cache not copied: source exists: %s, destination exists: %s",
host_zinit_cache.exists(),
container_zinit_cache.exists(),
)
# 3. Run optional extension scripts
script_path_from_env = os.environ.get("DOTFILES_CONTAINER_EXTENSION_SCRIPT")
if script_path_from_env:
extension_scripts = [Path(script_path_from_env)]
else: