forked from wookayin/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
executable file
·779 lines (669 loc) · 25.7 KB
/
Copy pathinstall.py
File metadata and controls
executable file
·779 lines (669 loc) · 25.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ruff: noqa: E402
"""
@kojunseo's
▓█████▄ ▒█████ ▄▄▄█████▓ ███████▓██▓ ▓█████ ██████
▒██▀ ██▒██▒ ██▓ ██▒ ▓▓██ ▓██▓██▒ ▓█ ▀▒██ ▒
░██ █▒██░ ██▒ ▓██░ ▒▒████ ▒██▒██░ ▒███ ░ ▓██▄
░▓█▄ ▒██ ██░ ▓██▓ ░░▓█▒ ░██▒██░ ▒▓█ ▄ ▒ ██▒
░▒████▓░ ████▓▒░ ▒██▒ ░░▒█░ ░██░██████░▒████▒██████▒▒
▒▒▓ ▒░ ▒░▒░▒░ ▒ ░░ ▒ ░ ░▓ ░ ▒░▓ ░░ ▒░ ▒ ▒▓▒ ▒ ░
░ ▒ ▒ ░ ▒ ▒░ ░ ░ ▒ ░ ░ ▒ ░░ ░ ░ ░▒ ░ ░
░ ░ ░░ ░ ░ ▒ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
"""
print(__doc__) # print logo.
import argparse
import os
import plistlib
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--force",
action="store_true",
default=False,
help="If set, it will override existing symbolic links",
)
parser.add_argument("--skip-vimplug", action="store_true", help="If set, do not update vim plugins.")
parser.add_argument("--skip-zplug", action="store_true", help="If set, skip update of zsh plugins.")
args = parser.parse_args()
################# BEGIN OF FIXME #################
IS_SSH = os.getenv("SSH_TTY", None) is not None
# Task Definition
# (path of target symlink) : (location of source file in the repository)
tasks = {
# SHELLS
"~/.bashrc": "bashrc",
"~/.screenrc": "screenrc",
# VIM
"~/.vimrc": "vim/vimrc",
"~/.vim": "vim",
"~/.vim/autoload/plug.vim": "vim/bundle/vim-plug/plug.vim",
# NeoVIM
"~/.config/nvim": "nvim",
# GIT
"~/.gitconfig": "git/gitconfig",
"~/.gitignore": "git/gitignore",
# ZSH
"~/.zsh": "zsh",
"~/.zlogin": "zsh/zlogin",
"~/.zlogout": "zsh/zlogout",
"~/.zpreztorc": "zsh/zpreztorc",
"~/.zprofile": "zsh/zprofile",
"~/.zshenv": "zsh/zshenv",
"~/.zshrc": "zsh/zshrc",
# Bins
"~/.local/bin/dotfiles": "bin/dotfiles",
"~/.local/bin/fasd": "zsh/fasd/fasd",
"~/.local/bin/fzf": dict(src="~/.fzf/bin/fzf", force=True),
# X
"~/.Xmodmap": "Xmodmap",
# GTK
"~/.gtkrc-2.0": "gtkrc-2.0",
# terminal emulators (kitty, alacritty, wezterm, ghostty)
"~/.config/kitty": dict(src="config/kitty", cond=not IS_SSH),
"~/.config/alacritty": dict(src="config/alacritty", cond=not IS_SSH),
"~/.config/wezterm": dict(src="config/wezterm", cond=not IS_SSH),
"~/.config/ghostty": dict(src="config/ghostty", cond=not IS_SSH),
# tmux
"~/.tmux": "tmux",
"~/.tmux.conf": "tmux/tmux.conf",
# herdr
"~/.config/herdr/config.toml": "config/herdr/config.toml",
# .config (XDG-style)
"~/.config/terminator": "config/terminator",
"~/.config/pudb/pudb.cfg": "config/pudb/pudb.cfg",
# pip and python
#'~/.pip/pip.conf' : 'pip/pip.conf',
"~/.pythonrc.py": "python/pythonrc.py",
"~/.pylintrc": "python/pylintrc",
"~/.condarc": "python/condarc",
"~/.config/pycodestyle": "python/pycodestyle",
"~/.ptpython/config.py": dict(action="remove"),
"~/.config/ptpython/config.py": "python/ptpython.config.py",
# codex instructions
"~/.codex/AGENTS.md": "codex/AGENTS.md",
}
import os
import platform
import shutil
# Make sure the CWD is the root of dotfiles.
__PATH__ = os.path.abspath(os.path.dirname(__file__))
os.chdir(__PATH__)
def _discover_codex_docs_tasks(base_source_dir="codex/docs", base_target_dir="~/.codex/docs"):
discovered = {}
source_root = os.path.join(__PATH__, base_source_dir)
if not os.path.isdir(source_root):
return discovered
for root, _, filenames in os.walk(source_root):
rel_root = os.path.relpath(root, source_root)
for filename in sorted(filenames):
source_relpath = os.path.join(base_source_dir, rel_root, filename)
target_path = os.path.join(base_target_dir, rel_root, filename)
source_relpath = source_relpath.replace("/./", "/")
target_path = target_path.replace("/./", "/")
discovered[target_path] = source_relpath
return discovered
tasks.update(_discover_codex_docs_tasks())
post_actions = []
# pyenv의 경우 이미 설치되어 있다면 건너뛰기
if not os.path.isdir(os.path.expanduser("~/.pyenv")):
post_actions += ["git clone https://github.com/pyenv/pyenv.git ~/.pyenv"]
post_actions += [ # Check symbolic link at $HOME
"""#!/bin/bash
# Check whether ~/.vim and ~/.zsh are well-configured
for f in ~/.vim ~/.zsh ~/.vimrc ~/.zshrc; do
if ! readlink $f >/dev/null; then
echo -e "\033[0;31m\
WARNING: $f is not a symbolic link to ~/.dotfiles.
Please remove your local folder/file $f and try again.\033[0m"
echo -n "(Press any key to continue) "; read user_confirm
exit 1;
else
echo "$f --> $(readlink $f)"
fi
done
"""
]
else:
post_actions += [
"""#!/bin/bash
echo -e "\033[0;33m\
Skipping pyenv installation since ~/.pyenv already exists.\033[0m"
"""
]
post_actions += [ # fzf
r"""#!/bin/bash
# Install junegunn/fzf
FZF_REPO="https://github.com/junegunn/fzf.git"
if [[ ! -d "$HOME/.fzf" ]]; then
git clone "$FZF_REPO" "$HOME/.fzf"
else
cd $HOME/.fzf && git fetch --tags
fi
cd $HOME/.fzf
# Checkout the latest release (tag)
tag=$(git ls-remote --tags --exit-code --refs "$FZF_REPO" \
| sed -E 's/^[[:xdigit:]]+[[:space:]]+refs\/tags\/(.+)/\1/g' \
| sort -V | tail -n1)
git checkout "$tag"
./install --all --no-update-rc
"""
]
post_actions += [ # GitHub CLI
r"""#!/bin/bash
if command -v gh >/dev/null 2>&1; then
echo "GitHub CLI already installed: $(gh --version | head -n1)"
exit 0
fi
if [[ "$(uname)" == "Darwin" ]]; then
if ! command -v brew >/dev/null 2>&1; then
echo "Homebrew is required to install GitHub CLI on macOS." >&2
exit 1
fi
brew install gh
else
bin/dotfiles install gh
fi
"""
]
post_actions += [ # Herdr
"etc/install-herdr.sh",
]
post_actions += [ # Leaf
r"""#!/bin/bash
# Install Leaf
if command -v leaf >/dev/null 2>&1 || [[ -x "$HOME/.local/bin/leaf" ]]; then
echo "Leaf already installed."
exit 0
fi
set -o pipefail
curl -fsSL https://leaf.rivolink.mg/install.sh | sh
"""
]
post_actions += [ # video2gif
"""#!/bin/bash
# Download command line scripts
mkdir -p "$HOME/.local/bin/"
_download() {
curl -L "$2" > "$1" && chmod +x "$1"
}
ret=0
set -v
_download "$HOME/.local/bin/video2gif" "https://raw.githubusercontent.com/wookayin/video2gif/master/video2gif" || ret=1
exit $ret;
"""
]
post_actions += [ # antidote (zsh plugins)
(
"""#!/bin/bash
# Update zsh bundles and cache (the init file)
zsh -c "
# source zsh plugin manager and list plugins
DOTFILES_UPDATE=1 __p9k_instant_prompt_disabled=1 source ${HOME}/.zshrc
if ! which antidote > /dev/null; then
echo -e '\033[0;31m\
ERROR: antidote not found. Double check the submodule exists, and you have a valid ~/.zshrc!\033[0m'
ls -alh ~/.zsh/antidote/
ls -alh ~/.zshrc
exit 1;
fi
antidote update
antidote reset
source ~/.zshrc
"
"""
if not args.skip_zplug
else "# zsh plugins update (Skipped)"
)
]
post_actions += [ # tmux plugins
# Install tmux plugins via tpm
"~/.tmux/plugins/tpm/bin/install_plugins",
r"""#!/bin/bash
# Check tmux version >= 2.3 (or use `dotfiles install tmux`)
_version_check() { # target_ver current_ver
[ "$1" = "$(echo -e "$1\n$2" | sort -s -t- -k 2,2n | sort -t. -s -k 1,1n -k 2,2n | head -n1)" ]
}
if [[ `uname` == "Linux" ]] && ! type tmux >/dev/null 2>&1; then
echo -e "\033[0;33mInstalling tmux because not installed globally.\033[0m"
bin/dotfiles install tmux
export PATH="$PATH:~/.local/bin"
elif ! _version_check "2.3" "$(tmux -V | cut -d' ' -f2)"; then
echo -en "\033[0;33m"
echo -e "$(tmux -V) is too old. Contact system administrator, or:"
echo -e " $ dotfiles install tmux \033[0m (installs to ~/.local/, if you don't have sudo)"
exit 1;
else
echo "$(which tmux): $(tmux -V)"
fi
""",
]
post_actions += (
[ # im-select (macOS)
r"""#!/bin/bash
# Install im-select to support forcing ABC input source on tmux prefix.
if [[ `uname` != "Darwin" ]]; then
echo "Skipping im-select installation on non-macOS."
exit 0
fi
if [[ -x /opt/homebrew/bin/im-select ]] || [[ -x /usr/local/bin/im-select ]] || type im-select >/dev/null 2>&1; then
echo -e "\033[0;32mim-select already installed.\033[0m"
exit 0
fi
if [[ "$(uname -m)" = "arm64" ]]; then
IM_SELECT_URL="https://raw.githubusercontent.com/daipeihust/im-select/master/macOS/out/apple/im-select"
else
IM_SELECT_URL="https://raw.githubusercontent.com/daipeihust/im-select/master/macOS/out/intel/im-select"
fi
IM_SELECT_DEST=""
for d in /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin"; do
mkdir -p "$d" 2>/dev/null || true
if [[ -d "$d" && -w "$d" ]]; then
IM_SELECT_DEST="$d/im-select"
break
fi
done
if [[ -z "$IM_SELECT_DEST" ]]; then
echo -e "\033[0;31mCould not find a writable destination for im-select.\033[0m"
exit 1
fi
echo -e "\033[0;33mInstalling im-select -> $IM_SELECT_DEST\033[0m"
curl -fLsS "$IM_SELECT_URL" -o "$IM_SELECT_DEST"
chmod 755 "$IM_SELECT_DEST"
echo -e "\033[0;32m✔ Successfully installed im-select -> $IM_SELECT_DEST\033[0m"
"""
]
if platform.system() == "Darwin"
else []
)
post_actions += [ # stat_dataset
r"""#!/bin/bash
# Install stat_dataset tool to /usr/local/bin
if command -v stat_dataset >/dev/null 2>&1; then
echo -e "\033[0;32mstat_dataset already installed at: $(command -v stat_dataset)\033[0m"
exit 0
fi
OS=$(uname)
if [[ "$OS" == "Darwin" ]] || [[ "$OS" == "Linux" ]]; then
STAT_DATASET_SRC="external/stat_dataset/bin/stat_dataset"
STAT_DATASET_DEST="/usr/local/bin/stat_dataset"
if [[ -f "$STAT_DATASET_SRC" ]]; then
echo -e "\033[0;33mInstalling stat_dataset to $STAT_DATASET_DEST...\033[0m"
if sudo cp "$STAT_DATASET_SRC" "$STAT_DATASET_DEST" 2>/dev/null; then
sudo chmod +x "$STAT_DATASET_DEST"
echo -e "\033[0;32m✔ Successfully installed stat_dataset → $STAT_DATASET_DEST\033[0m"
else
echo -e "\033[0;31m✗ Failed to install stat_dataset (sudo required)\033[0m"
echo -e "\033[0;33mTrying to install to ~/.local/bin instead...\033[0m"
mkdir -p "$HOME/.local/bin"
cp "$STAT_DATASET_SRC" "$HOME/.local/bin/stat_dataset"
chmod +x "$HOME/.local/bin/stat_dataset"
echo -e "\033[0;32m✔ Successfully installed stat_dataset → ~/.local/bin/stat_dataset\033[0m"
echo -e "\033[0;33mMake sure ~/.local/bin is in your PATH\033[0m"
fi
else
echo -e "\033[0;31m✗ stat_dataset source file not found at $STAT_DATASET_SRC\033[0m"
fi
else
echo -e "\033[0;33mstat_dataset installation skipped (unsupported OS: $OS)\033[0m"
fi
""",
]
post_actions += [ # pman / pqm
"""#!/bin/bash
bash "etc/install-pman.sh"
"""
]
post_actions += [ # summon
"""#!/bin/bash
bash "etc/install-summon.sh"
"""
]
post_actions += [ # granted(assume)
"""#!/bin/bash
bash "etc/install-granted.sh"
"""
]
post_actions += [ # default shell
r"""#!/bin/bash
# Change default shell to zsh
/bin/zsh --version >/dev/null || (\
echo -e "\033[0;31mError: /bin/zsh not found. Please install zsh.\033[0m"; exit 1)
if [[ ! "$SHELL" = *zsh ]]; then
echo -e '\033[0;33mPlease type your password if you wish to change the default shell to ZSH\e[m'
chsh -s /bin/zsh && echo -e 'Successfully changed the default shell, please re-login'
else
echo -e "\033[0;32m\$SHELL is already zsh.\033[0m $(zsh --version)"
fi
"""
]
post_actions += (
[ # install some essential packages (linux)
"""#!/bin/bash
# Install node, rg, fd locally
export PATH="$PATH:$HOME/.local/bin"
type node >/dev/null 2>&1 || bin/dotfiles install node
type rg >/dev/null 2>&1 || bin/dotfiles install ripgrep
type fd >/dev/null 2>&1 || bin/dotfiles install fd
"""
]
if platform.system() == "Linux"
else []
)
post_actions += [ # neovim
"""#!/bin/bash
bash "etc/install-neovim.sh"
"""
]
post_actions += [ # vim-plug
# Run vim-plug installation
{
"install": 'PATH="$PATH:~/.local/bin" nvim --headless +"Lazy! install" +qall',
"update": 'PATH="$PATH:~/.local/bin" nvim --headless +"Lazy! update" +qall',
"none": "# vim plugins: skipped",
}["update" if not args.skip_vimplug else "none"]
+ "\n"
+ r"""#!/bin/bash
if [[ -n "~/.vim/plugged/*.cloning(#qN)" ]]; then
echo "Cleaning up plugin installation artifacts..."
rm -fv ~/.vim/plugged/*.cloning
fi
"""
]
post_actions += [ # gitconfig.secret
r"""#!/bin/bash
# Create ~/.gitconfig.secret file and check user configuration
if [ ! -f ~/.gitconfig.secret ]; then
cat > ~/.gitconfig.secret <<EOL
# vim: set ft=gitconfig:
EOL
fi
if ! git config --file ~/.gitconfig.secret user.name 2>&1 > /dev/null || \
! git config --file ~/.gitconfig.secret user.email 2>&1 > /dev/null; then echo -ne '
\033[1;33m[!!!] Please configure git user name and email:
git config --file ~/.gitconfig.secret user.name "(YOUR NAME)"
git config --file ~/.gitconfig.secret user.email "(YOUR EMAIL)"
\033[0m'
echo -en '\n'
echo -en "(git config user.name) \033[0;33m Please input your name : \033[0m"; read git_username
echo -en "(git config user.email)\033[0;33m Please input your email : \033[0m"; read git_useremail
if [[ -n "$git_username" ]] && [[ -n "$git_useremail" ]]; then
git config --file ~/.gitconfig.secret user.name "$git_username"
git config --file ~/.gitconfig.secret user.email "$git_useremail"
else
exit 1; # error
fi
fi
# get the current config
echo -en '\033[0;32m';
echo -en 'user.name : '; git config --file ~/.gitconfig.secret user.name
echo -en 'user.email : '; git config --file ~/.gitconfig.secret user.email
echo -en '\033[0m';
"""
]
post_actions += [ # tmux reload
r"""#!/bin/bash
# Reload tmux config for running tmux server(s), if any.
if ! type tmux >/dev/null 2>&1; then
echo "Skipping tmux reload: tmux command not found."
exit 0
fi
if ! tmux ls >/dev/null 2>&1; then
echo "Skipping tmux reload: no running tmux server."
exit 0
fi
tmux source-file "$HOME/.tmux.conf"
echo -e "\033[0;32mReloaded tmux config: $HOME/.tmux.conf\033[0m"
"""
]
################# END OF FIXME #################
def _wrap_colors(ansicode):
return lambda msg: ansicode + str(msg) + "\033[0m"
GRAY = _wrap_colors("\033[0;37m")
WHITE = _wrap_colors("\033[1;37m")
RED = _wrap_colors("\033[0;31m")
GREEN = _wrap_colors("\033[0;32m")
YELLOW = _wrap_colors("\033[0;33m")
CYAN = _wrap_colors("\033[0;36m")
BLUE = _wrap_colors("\033[0;34m")
import os
import subprocess
import sys
from signal import SIG_DFL, SIGPIPE, signal
from sys import stderr
if sys.version_info[0] >= 3: # python3
unicode = lambda s, _: str(s)
from builtins import input
else: # python2
input = sys.modules["__builtin__"].raw_input
def log(msg, cr=True):
stderr.write(msg)
if cr:
stderr.write("\n")
def log_boxed(msg, color_fn=WHITE, use_bold=False, len_adjust=0):
import unicodedata
pad_msg = " " + msg + " "
l = sum(not unicodedata.combining(ch) for ch in unicode(pad_msg, "utf-8")) + len_adjust # noqa
if use_bold:
log(
color_fn("┏" + ("━" * l) + "┓\n" + "┃" + pad_msg + "┃\n" + "┗" + ("━" * l) + "┛\n"),
cr=False,
)
else:
log(
color_fn("┌" + ("─" * l) + "┐\n" + "│" + pad_msg + "│\n" + "└" + ("─" * l) + "┘\n"),
cr=False,
)
def makedirs(target, mode=511, exist_ok=False):
try:
os.makedirs(target, mode=mode)
except OSError as ex: # py2 has no exist_ok=True
import errno
if ex.errno == errno.EEXIST and exist_ok:
pass
else:
raise
def is_codex_managed_target(path):
codex_home = os.path.expanduser("~/.codex")
codex_docs = os.path.join(codex_home, "docs") + os.sep
return path == os.path.join(codex_home, "AGENTS.md") or path.startswith(codex_docs)
def cleanup_stale_codex_doc_symlinks():
source_root = os.path.realpath(os.path.join(current_dir, "codex/docs"))
target_root = os.path.expanduser("~/.codex/docs")
if not os.path.isdir(target_root):
return
for root, _, files in os.walk(target_root):
for name in files:
path = os.path.join(root, name)
if not os.path.islink(path):
continue
resolved = os.path.realpath(path)
if resolved.startswith(source_root + os.sep) and not os.path.exists(resolved):
os.unlink(path)
log("{:60s} : {}".format(BLUE(path), YELLOW("stale symlink removed")))
def _make_timestamped_backup_path(target_path):
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
backup_path = "{}.bak.{}".format(target_path, timestamp)
i = 1
while os.path.lexists(backup_path):
backup_path = "{}.bak.{}.{}".format(target_path, timestamp, i)
i += 1
return backup_path
def install_iterm2_preferences_copy_mode():
if platform.system() != "Darwin" or IS_SSH:
return 0
source = os.path.join(current_dir, "config/iTerm/com.googlecode.iterm2.plist")
target = os.path.expanduser("~/Library/Preferences/com.googlecode.iterm2.plist")
if not os.path.isfile(source):
log("{:60s} : {}".format(BLUE(target), RED("source plist not found: {}".format(source))))
return 1
target_dir = os.path.dirname(target)
if not os.path.isdir(target_dir):
makedirs(target_dir, exist_ok=True)
log(GREEN("Created directory : %s" % target_dir))
try:
with open(source, "rb") as source_file:
preferences = plistlib.load(source_file)
profiles = preferences.get("New Bookmarks")
if not isinstance(profiles, list) or not profiles:
raise ValueError("iTerm2 plist has no profiles in 'New Bookmarks'")
for profile in profiles:
if not isinstance(profile, dict):
raise ValueError("iTerm2 plist contains an invalid profile")
# Prevent terminal applications from enabling enhanced key reporting.
# It causes Ctrl chords to use Hangul codepoints instead of the
# physical QWERTY key while a Korean input source is active.
profile["Allow modifyOtherKeys"] = False
if os.path.lexists(target):
backup = _make_timestamped_backup_path(target)
shutil.move(target, backup)
log("{:60s} : {}".format(BLUE(backup), GREEN("backup created")))
with open(target, "wb") as target_file:
plistlib.dump(preferences, target_file, fmt=plistlib.FMT_BINARY, sort_keys=False)
shutil.copymode(source, target)
log(
"{:60s} : {}".format(
BLUE(target),
GREEN("copied from '{}' with enhanced key reporting disabled".format(source)),
)
)
return 0
except Exception as ex:
log("{:60s} : {}".format(BLUE(target), RED("failed to copy iTerm2 preferences: {}".format(ex))))
return 1
# get current directory (absolute path)
current_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(current_dir)
# check if git submodules are loaded properly
stat = subprocess.check_output("git submodule status --recursive", shell=True, universal_newlines=True)
submodule_issues = [(l.split()[1], l[0]) for l in stat.split("\n") if len(l) and l[0] != " "] # noqa
if submodule_issues:
stat_messages = {"+": "needs update", "-": "not initialized", "U": "conflict!"}
for submodule_name, submodule_stat in submodule_issues:
log(
RED(
"git submodule {name} : {status}".format(
name=submodule_name,
status=stat_messages.get(submodule_stat, "(Unknown)"),
)
)
)
log(YELLOW("Git submodules are not initialized.\n"))
update_submodule = True
if update_submodule:
git_submodule_update_cmd = "git submodule update --init --recursive"
# git 2.8+ supports parallel submodule fetching
try:
git_version = str(subprocess.check_output("""git --version | awk '{print $3}'""", shell=True))
if git_version >= "2.8":
git_submodule_update_cmd += " --jobs 8"
except Exception:
pass
log("Running: %s" % CYAN(git_submodule_update_cmd))
subprocess.call(git_submodule_update_cmd, shell=True)
else:
log(RED("Aborted."))
sys.exit(1)
log_boxed("Creating symbolic links", color_fn=CYAN)
cleanup_stale_codex_doc_symlinks()
for target, item in sorted(tasks.items()):
# normalize paths
if isinstance(item, str):
item = {"src": item}
source = item.get("src", None)
force = item.get("force", False)
fail_on_error = item.get("fail_on_error", False)
if not item.get("cond", True):
continue
if source:
source = os.path.join(current_dir, os.path.expanduser(source))
target = os.path.expanduser(target)
if item.get("action", None) == "remove":
try:
os.unlink(target)
except OSError: # FileNotFoundError
pass
continue
assert source is not None
# bad entry if source does not exists...
if force:
pass # Even if the source does not exist, always make a symlink
elif not os.path.lexists(source):
log(RED("source %s : does not exist" % source))
continue
# if --force option is given, delete and override the previous symlink
if os.path.lexists(target):
is_broken_link = os.path.islink(target) and not os.path.exists(os.readlink(target))
err = ""
if is_broken_link: # safe to remove
if os.path.islink(target):
os.unlink(target)
elif os.path.islink(target):
if args.force:
os.unlink(target)
else:
msg = GRAY("already exists, skipped")
log("{:60s} : {}".format(BLUE(target), msg))
elif fail_on_error:
err = RED("already exists, please remove " + target + " manually.")
else:
if is_codex_managed_target(target):
err = RED("exists, but is not a symbolic link. Skipped (codex-managed); remove manually.")
elif item.get("non_symlink_warning"):
err = RED(item["non_symlink_warning"])
elif args.force:
err = YELLOW("already exists but not a symbolic link; --force option ignored")
else:
err = YELLOW("exists, but not a symbolic link. Check by yourself!!")
if err:
log("{:60s} : {}".format(BLUE(target), err))
if fail_on_error:
sys.exit(1)
# make a symbolic link if available
if not os.path.lexists(target):
mkdir_target = os.path.split(target)[0]
if not os.path.isdir(mkdir_target):
makedirs(mkdir_target)
log(GREEN("Created directory : %s" % mkdir_target))
os.symlink(source, target)
log("{:60s} : {}".format(BLUE(target), GREEN("symlink created from '%s'" % source)))
errors = []
if platform.system() == "Darwin" and not IS_SSH:
action_title = "Apply iTerm2 preferences (backup + copy)"
log("\n", cr=False)
log_boxed("Executing: " + action_title, color_fn=CYAN)
ret = install_iterm2_preferences_copy_mode()
if ret:
errors.append(action_title)
for action in post_actions:
if not action:
continue
action_title = action.strip().split("\n")[0].strip()
if action_title == "#!/bin/bash":
action_title = action.strip().split("\n")[1].strip()
log("\n", cr=False)
log_boxed("Executing: " + action_title, color_fn=CYAN)
ret = subprocess.call(["bash", "-e", "-c", action], preexec_fn=lambda: signal(SIGPIPE, SIG_DFL))
if ret:
errors.append(action_title)
log("\n")
if errors:
log_boxed(
"You have %3d warnings or errors -- check the logs!" % len(errors),
color_fn=YELLOW,
use_bold=True,
)
for e in errors:
log(" " + YELLOW(e))
log("\n")
else:
log_boxed("✔ You are all set! ", color_fn=GREEN, use_bold=True)
log("- Please restart shell (e.g. " + CYAN("`exec zsh`") + ") if necessary.")
log("- To install some packages locally (e.g. neovim, tmux), try " + CYAN("`dotfiles install <package>`"))
log("- If you want to update dotfiles (or have any errors), try " + CYAN("`dotfiles update`"))
log("\n\n", cr=False)
sys.exit(len(errors))