-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetup
executable file
·921 lines (694 loc) · 29.2 KB
/
setup
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
#!/usr/bin/env sh
''':'
command -v python3 >/dev/null 2>&1 && exec python3 "$0" "$@"
command -v python >/dev/null 2>&1 && exec python "$0" "$@"
>&2 echo "error: python is not installed on this machine"
exit 1
'''
"""
Roam settings for shell rc files, Sublime Text etc.
"""
import argparse
import os
import shutil
import sys
from platform import system
P_LINUX = "linux"
P_MACOS = "darwin"
P_CYGWIN = "cygwin"
P_WINDOWS = "windows"
DEFAULT_ROAMING_SUBFOLER = "_"
PLATFORM_SYSTEM = system().lower()
if PLATFORM_SYSTEM.startswith("cygwin"):
PLATFORM_SYSTEM = P_CYGWIN
os.environ["CYGWIN"] = "winsymlinks:nativestrict"
if PLATFORM_SYSTEM in (P_WINDOWS, P_CYGWIN) and sys.version_info < (3, 0):
sys.exit("Python 3.0+ required on Windows (for proper symlink support)")
HOME = os.environ.get("HOME") or os.environ.get("APPDATA")
if not HOME:
sys.exit("Could not determine HOME folder, please check")
def get_roaming_root():
path = os.path.dirname(os.path.abspath(os.path.realpath(os.path.expanduser(__file__))))
wsl = "/mnt/c/users" # Can Windows Subsystem for Linux be better handled?
if path.lower().startswith(wsl):
p = os.path.join("/home", path[len(wsl)+1:])
if os.path.exists(p):
return p
return path
ROAMING_ROOT = get_roaming_root()
def _expanded_path(path):
if path and path.startswith("~"):
path = os.path.join(HOME, path[2:])
return path
def _join(*components):
""" Join path properly """
result = os.path.join(*components)
if PLATFORM_SYSTEM == P_CYGWIN and result.startswith("/cygdrive"):
result = result.replace("/cygdrive/c", "C:")
result = result.replace("/", "\\")
return result
def _roaming_path(*components):
""" Path in roaming folder for 'components' (relative) """
return _join(ROAMING_ROOT, *components)
def relative_path(path, anchor):
""" Relative path to anchor """
return os.path.relpath(path, os.path.dirname(anchor))
def _short_path(path):
""" Shortened 'path' if possible (replace expanded HOME with ~) """
return path.replace(HOME, "~")
def _get_description_from_file(fpath):
""" Return comment found on first line in 'fpath', if available """
res = ""
try:
with open(fpath) as fh:
line = fh.readline().strip()
if line.startswith("#"):
res = line[1:].strip()
except (IOError, OSError):
pass
if not res and fpath.endswith("default.cfg"):
res = "Default settings (applied when script ran without any arguments)"
return res
def _delete(report, path, commit):
""" Delete file/folder with 'path' """
if report.errors:
return report
if not os.path.exists(path) and not os.path.islink(path):
return report
if commit:
report.log("Deleting %s", path)
if os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
else:
try:
shutil.rmtree(path)
except Exception as e:
report.error("Can't delete [%s]: %s", path, e)
else:
report.log("Will delete %s", path)
return report
def _symlink(report, local, roaming, commit):
""" Create symlink local -> roaming """
if report.errors:
return report
if not os.path.exists(roaming) and commit:
return report.error("%s does not exist", roaming)
# Use relative path if roaming folder is under ~
if ROAMING_ROOT.startswith(HOME):
target = relative_path(roaming, local)
else:
target = roaming
if commit:
report.log("Creating symlink %s -> %s", local, target)
try:
os.symlink(target, local)
except Exception as e:
report.error("Can't symlink %s -> %s: %s", local, target, e)
else:
report.log("Will create symlink %s -> %s", local, target)
return report
def _copy(report, source, dest, commit):
""" Copy file/folder 'source' -> 'dest' """
if report.errors:
return report
if not os.path.exists(source):
return report.error("%s does not exist", source)
if commit:
report.log("Copying %s -> %s", source, dest)
parent = os.path.dirname(dest)
if not os.path.isdir(parent):
try:
os.makedirs(parent)
except Exception as e:
report.error("Can't create [%s]: %s", parent, e)
if os.path.isdir(source):
try:
shutil.copytree(source, dest, symlinks=False)
except Exception as e:
report.error("Can't copy [%s] -> [%s]: %s", source, dest, e)
else:
try:
shutil.copy(source, dest)
except Exception as e:
report.error("Can't copy [%s] -> [%s]: %s", source, dest, e)
try:
shutil.copystat(source, dest) # Make sure last modification time is preserved
except Exception as e:
report.error("Can't copy stats [%s] -> [%s]: %s", source, dest, e)
else:
report.log("Will copy %s -> %s", source, dest)
return report
class Report(object):
""" Simple reporting """
def __init__(self, title=""):
self.title = title
self.messages = []
self.errors = 0
self.infos = 0
self.logs = 0
def _log(self, msg, *args):
if args:
msg = msg % args
if self.title:
msg = self.title + ": " + msg
self.messages.append(_short_path(msg))
return self
def error(self, msg, *args):
self.errors += 1
return self._log(msg, *args)
def info(self, msg, *args):
self.infos += 1
return self._log(msg, *args)
def log(self, msg, *args):
self.logs += 1
return self._log(msg, *args)
def add(self, other):
assert other
self.errors += other.errors
self.infos += other.infos
self.logs += other.logs
for m in other.messages:
self.messages.append(m)
def __str__(self):
return "\n".join(self.messages)
class Spec(object):
""" File or folder roaming spec """
def __init__(self, section, name, local_path, doc, copy_only=False, optional=False):
"""
Args:
section (Section): Associated section, defines which roaming subfolder this should go under
name (str): Name of the file or folder roamed
local_path (str): Full path to local file (outside of roaming folder)
doc (str | None): Short explanation of what the file/folder is
copy_only (bool): Copy the file from roaming <-> local when True (instead of symlink local -> roaming)
optional (bool): If True, don't show that corresponding file isn't there
"""
self.section = section
self.name = name
self.local_path = _expanded_path(local_path)
self.roaming_path = section.computed_roaming_path(self)
self.doc = doc or ""
if copy_only:
self.doc = "[Copy] %s" % self.doc
short_local_path = _short_path(local_path)
if short_local_path not in self.doc:
self.doc = "%s (%s)" % (self.doc.strip(), short_local_path)
self.copy_only = copy_only
self.optional = optional
def __repr__(self):
source = _short_path(self.local_path)
dest = _short_path(self.roaming_path)
if self.copy_only:
return "%s <-> %s" % (source, dest)
return "%s -> %s" % (source, dest)
def is_match(self, name):
if not name:
return False
if name[0] == "~":
return _expanded_path(name) == self.local_path
return name.lower() == self.name.lower()
def setup(self, commit):
"""
Link 'self.local_path' to roaming correspondent,
if roaming correspondent does not exist, create it from the contents of 'self.local_path',
then delete self.local_path and link it to roaming
@param bool commit: Commit changes when true
@return Report: Report on how setup went, what was done or would be done if 'commit' was True
"""
report = Report(self.section.name)
if self.copy_only:
report.title += "+"
needs_copy = True
if not os.path.exists(self.roaming_path) and os.path.exists(self.local_path):
# First time we roam this copy_only file, seed the roaming folder with it
needs_copy = False
_copy(report, self.local_path, self.roaming_path, commit)
if os.path.islink(self.local_path):
# Local path shouldn't be a symlink, probably left-over from earlier mistaken roaming
# Example: macOS KeyBindings used to be symlinked but not anymore (sandbox-ed apps can't read it when symlinked)
needs_copy = True
_delete(report, self.local_path, commit)
elif os.path.islink(os.path.dirname(self.local_path)):
# Special case with previous symlink of KeyBindings by this very script...
# This script used to symlink ~/Library/KeyBindings -> roaming (instead of ~/Library/KeyBindings/DefaultKeyBinding.dict)
needs_copy = True
_delete(report, os.path.dirname(self.local_path), commit)
if not needs_copy:
# First copy took care of things, we don't need to continue
return report
if not os.path.exists(self.roaming_path):
return report.info("Skipping %s, no local and no roaming file", self.local_path)
if os.path.exists(self.local_path):
time_diff = os.path.getmtime(self.roaming_path) - os.path.getmtime(self.local_path)
if abs(time_diff) < 60:
report.info("OK %s <-> %s", self.local_path, self.roaming_path)
elif time_diff > 0:
# Roaming copy is younger
_copy(report, self.roaming_path, self.local_path, commit)
else:
# Local copy is younger
_copy(report, self.local_path, self.roaming_path, commit)
else:
# First roaming -> local copy
_copy(report, self.roaming_path, self.local_path, commit)
return report
if os.path.islink(self.local_path):
target = relative_path(self.roaming_path, self.local_path)
if os.readlink(self.local_path) == target or PLATFORM_SYSTEM in (P_CYGWIN, P_WINDOWS):
# FIXME: Need a good implementation for os.readlink on Windows
return report.info("OK %s -> %s", self.local_path, relative_path(self.roaming_path, self.local_path))
if not os.path.exists(self.roaming_path):
# Initialize self.roaming_path from self.local_path
if not os.path.exists(self.local_path):
if self.optional:
return report
r = _copy(report, self.local_path, self.roaming_path, commit)
if r.errors:
return r
elif not os.path.exists(self.local_path):
if self.optional and not os.path.islink(self.local_path):
return report
_delete(report, self.local_path, commit)
_symlink(report, self.local_path, self.roaming_path, commit)
return report
def help(self):
return "%-20s %s" % (self.name, self.doc)
class Section(object):
""" Roaming section """
def __init__(self):
self.platforms = [P_CYGWIN, P_LINUX, P_MACOS, P_WINDOWS]
self.name = self.__class__.__name__.lower().replace("section", "")
self.specs = [] # type: list[Spec]
def __repr__(self):
return "%s [%s] %s specs" % (self.name, " ".join(self.platforms), len(self.specs))
def computed_roaming_path(self, spec):
"""
Args:
spec (Spec): Associated spec
Returns:
(str): Roaming path
"""
x = _roaming_path(DEFAULT_ROAMING_SUBFOLER, spec.name)
rel_path = os.path.relpath(spec.local_path, HOME)
if rel_path.startswith("."):
rel_path = rel_path[1:]
y = _roaming_path(DEFAULT_ROAMING_SUBFOLER, rel_path)
assert (self.name in "shell ssh") or x == y
return y
def is_match(self, name):
return self.name == name.lower()
def get_roamable(self, name):
"""
@param str name: Name of roamable
@return: Corresponding section or spec?
"""
if self.is_match(name):
return self
for spec in self.specs:
if spec.is_match(name):
return spec
def add_spec(self, name, local_path, doc=None, copy_only=False, optional=False):
"""
Args:
name (str): Name of the file or folder roamed
local_path (str): Full path to local file (outside of roaming folder)
doc (str | None): Short explanation of what the file/folder is
copy_only (bool): Copy the file from roaming <-> local when True (instead of symlink local -> roaming)
optional (bool): If True, don't show that corresponding file isn't there
"""
spec = Spec(self, name, local_path, doc, copy_only, optional)
self.specs.append(spec)
def add_simple_file_spec(self, name, doc=None, local_path=None, copy_only=False, optional=True):
"""
Args:
name (str): Name of the file or folder roamed
doc (str | None): Short explanation of what the file/folder is
local_path (str | None): Full path to local file (outside of roaming folder), default ~/.<name>
copy_only (bool): Copy the file from roaming <-> local when True (instead of symlink local -> roaming)
optional (bool): If True, don't show that corresponding file isn't there
"""
if not local_path:
local_path = "~/.%s" % name
self.add_spec(name, local_path, doc, copy_only, optional)
def setup(self, settings, commit):
"""
@param Settings settings: What the user wants roamed
@param bool commit: Commit changes when true
@return Report: Report on how setup went, what was done or would be done if 'commit' was True
"""
rep = Report(self.name)
do_entire_section = self.name.lower() in settings.active
platform_supported = PLATFORM_SYSTEM in self.platforms
skipped = []
for spec in self.specs:
if not do_entire_section and not settings.is_active(spec.name):
continue
if spec.name in settings.exclude:
continue
if platform_supported:
rep.add(spec.setup(commit))
else:
skipped.append(spec)
if skipped:
return rep.info("Skipped on %s: %s", PLATFORM_SYSTEM, ", ".join(str(s) for s in skipped))
return rep
def help(self, platform):
res = ""
if platform and platform not in self.platforms:
return res
res += "%s (%s)\n" % (self.name, self.__doc__.strip())
for spec in self.specs:
res += " %s\n" % spec.help()
return res
class ShellSection(Section):
""" Shell specific settings """
def __init__(self):
super(ShellSection, self).__init__()
self.platforms = [P_CYGWIN, P_LINUX, P_MACOS]
self.add_simple_file_spec("bash_profile", "bash login settings")
self.add_simple_file_spec("bashrc", "bash session settings")
self.add_simple_file_spec("inputrc", "readline library configuration")
self.add_simple_file_spec("profile", "shell login settings")
self.add_simple_file_spec("starship.toml", "cross-shell prompt", local_path="~/.config/starship.toml")
self.add_simple_file_spec("zprofile", "zsh profile")
self.add_simple_file_spec("zshrc", "zsh settings")
class ToolsSection(Section):
""" Tool-specific settings """
def __init__(self):
super(ToolsSection, self).__init__()
self.add_simple_file_spec("agignore", "~/.agignore file")
self.add_simple_file_spec("bin", "~/bin folder", local_path="~/bin")
self.add_simple_file_spec("editorconfig", "See http://editorconfig.org/")
self.add_simple_file_spec("tmux.conf", "tmux configuration")
self.add_simple_file_spec("vimrc", "vim configuration")
class GitSection(Section):
""" Shell specific settings """
def __init__(self):
super(GitSection, self).__init__()
self.platforms = [P_CYGWIN, P_LINUX, P_MACOS]
self.add_simple_file_spec("gitconfig", "~/.gitconfig file")
self.add_simple_file_spec("gitignore_global", "~/.gitignore_global file (if you like to have a global git ignore)")
class SshSection(Section):
""" ssh settings """
def __init__(self):
super(SshSection, self).__init__()
self.platforms = [P_LINUX, P_MACOS]
self.add_ssh_file("config", "ssh configuration (~/.ssh/config)")
def add_ssh_file(self, name, doc=None, copy_only=False):
self.add_spec(name, _join("~/.ssh", name), doc, copy_only)
class MacOSSection(Section):
""" macOS specific settings """
def __init__(self):
super(MacOSSection, self).__init__()
self.platforms = [P_MACOS]
self.add_spec("DefaultKeyBinding.dict", "~/Library/KeyBindings/DefaultKeyBinding.dict", copy_only=True)
self.add_spec(
"com.googlecode.iterm2.plist", "~/Library/Preferences/com.googlecode.iterm2.plist", doc="iTerm2 settings", copy_only=True
)
def computed_roaming_path(self, spec):
return _roaming_path("macos", spec.name)
class STSection(Section):
""" Sublime Text settings """
def __init__(self):
super(STSection, self).__init__()
self.long_name = "Sublime Text"
local_path = None
self.base_folder = "config/sublime-text"
if PLATFORM_SYSTEM == P_LINUX:
local_path = "~/.%s" % self.base_folder
elif PLATFORM_SYSTEM == P_MACOS:
local_path = _join("~/Library", "Application Support", self.long_name)
elif PLATFORM_SYSTEM in (P_CYGWIN, P_WINDOWS):
local_path = "~/%s" % self.long_name
self.local_path = _expanded_path(local_path)
user_prefs = "Packages/User"
self.add_spec(user_prefs, _join(local_path, user_prefs), doc="Sublime Text user settings")
def computed_roaming_path(self, spec):
return _roaming_path(DEFAULT_ROAMING_SUBFOLER, self.base_folder, spec.name)
def setup(self, settings, commit):
"""
@param Settings settings: What the user wants roamed
@param bool commit: Commit changes when true
@return Report: Report on how setup went, what was done or would be done if 'commit' was True
"""
rep = Report(self.name)
if not settings.is_active(self.name):
return rep
if not self.local_path:
return rep.error("Can't determine where %s settings live on this platform" % self.name)
if not os.path.isdir(self.local_path):
rep.error("%s not found in %s", self.name, self.local_path)
return rep.error("Please install %s and run it at least once, then try this script again", self.long_name)
for spec in self.specs:
rep.add(spec.setup(commit))
return rep
class ST3Section(Section):
""" Sublime Text 3 settings """
def __init__(self):
super(ST3Section, self).__init__()
self.long_name = "Sublime Text 3"
local_path = None
self.base_folder = "config/sublime-text-3"
if PLATFORM_SYSTEM == P_LINUX:
local_path = "~/.%s" % self.base_folder
elif PLATFORM_SYSTEM == P_MACOS:
local_path = _join("~/Library", "Application Support", self.long_name)
elif PLATFORM_SYSTEM in (P_CYGWIN, P_WINDOWS):
local_path = "~/%s" % self.long_name
self.local_path = _expanded_path(local_path)
user_prefs = "Packages/User"
self.add_spec(user_prefs, _join(local_path, user_prefs), doc="ST3 user settings")
def computed_roaming_path(self, spec):
return _roaming_path(DEFAULT_ROAMING_SUBFOLER, self.base_folder, spec.name)
def setup(self, settings, commit):
"""
@param Settings settings: What the user wants roamed
@param bool commit: Commit changes when true
@return Report: Report on how setup went, what was done or would be done if 'commit' was True
"""
rep = Report(self.name)
if not settings.is_active(self.name):
return rep
if not self.local_path:
return rep.error("Can't determine where %s settings live on this platform" % self.name)
if not os.path.isdir(self.local_path):
rep.error("%s not found in %s", self.name, self.local_path)
return rep.error("Please install %s and run it at least once, then try this script again", self.long_name)
for spec in self.specs:
rep.add(spec.setup(commit))
return rep
class RoamingRunner(object):
def __init__(self):
self.sections = [] # type: list[Section]
self.adhoc_section = None
self.sections.append(ShellSection())
self.sections.append(ToolsSection())
self.sections.append(GitSection())
self.sections.append(STSection())
self.sections.append(ST3Section())
self.sections.append(SshSection())
self.sections.append(MacOSSection())
def __repr__(self):
return "%s sections" % len(self.sections)
def all_settings(self):
"""
@return Settings: Settings to roam everything we have
"""
settings = Settings("all")
for section in self.sections:
settings.add_active(section.name)
return settings
def setup(self, settings, commit):
"""
@param Settings settings: Settings specifying what to roam
@param bool commit: Commit changes when true
@return Report: Report on how setup went, what was done or would be done if 'commit' was True
"""
report = Report()
for section in self.sections:
report.add(section.setup(settings, commit))
return report
@staticmethod
def available_bundles():
res = ""
for fname in os.listdir(ROAMING_ROOT):
if fname.lower().endswith(".cfg"):
res += " %-20s %s\n" % (fname[:-4], _get_description_from_file(_roaming_path(fname)))
if res:
res = "Available .cfg bundles:\n%s" % res
return res
def help(self, platform=None):
""" List of roamable things for platform (if specified) """
res = ""
for section in self.sections:
sh = section.help(platform)
if sh:
res += sh + "\n"
res += self.available_bundles()
return res
def get_roamable(self, name):
"""
Args:
name (str): Name of roamable
Returns:
(Section | Spec | None): Corresponding section or spec, if available
"""
for section in self.sections:
roamable = section.get_roamable(name)
if roamable:
return roamable
def _add_adhoc(self, path):
if not self.adhoc_section:
self.adhoc_section = Section()
self.adhoc_section.name = "adhoc"
self.sections.append(self.adhoc_section)
if not self.get_roamable(path):
full_path = _expanded_path(path)
short_name = path[2:]
if short_name.startswith("."):
short_name = short_name[1:]
self.adhoc_section.add_simple_file_spec(short_name, path, full_path, optional=False)
def add_to_settings(self, settings, what):
"""
@param Settings settings: Settings to add to
@param str what: What to add to 'settings'
"""
if what == "osx":
msg = [
"Section 'osx' was renamed to 'macos'.",
"",
"Please rename your ./osx folder to ./macos",
"Don't forget to adapt corresponding apps if you used that folder for other things too (like Alfred or iTerm2).",
"",
"Sorry for the inconvenience, but it's probably best to adapt to the new name properly...",
]
_abort("\n********************************\n\n%s\n\n********************************\n" % "\n".join(msg))
if what.startswith("-"):
settings.add_exclude(what[1:])
return
if what.startswith("~/"):
self._add_adhoc(what)
roamable = self.get_roamable(what)
if roamable:
settings.add_active(roamable)
return
if what == "all":
s = self.all_settings()
else:
s = self.settings_from_file(what)
if s:
for name in s.active:
settings.add_active(name)
for name in s.exclude:
settings.add_exclude(name)
else:
_abort("Nothing corresponds to '%s' and no file '%s.cfg' found, typo?", what, what)
def settings_from_file(self, name):
"""
@param str name: File name containing the settings
@return Settings: Settings defined in file, if any
"""
if not name:
return None
fpath = _roaming_path(name)
if not os.path.exists(fpath):
if not name.endswith(".cfg"):
fpath = _roaming_path(name + ".cfg")
if not os.path.exists(fpath):
return None
try:
settings = Settings(name)
with open(fpath) as fh:
in_roam_section = False
for line in fh.readlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("["):
in_roam_section = line == "[roam]"
continue
if not in_roam_section:
continue
self.add_to_settings(settings, line)
return settings
except Exception as e:
print("Can't read file %s: %s" % (fpath, e))
return None
class Settings(object):
""" Settings specifying what to roam """
def __init__(self, name):
#: Name of setting file, if we got this object from
self.name = name
#: Active settings, to be roamed
self.active = []
#: Settings to skip
self.exclude = set()
def __repr__(self):
result = "(%s) %s" % (self.name, " ".join(self.active))
if self.exclude:
result = "%s [ex: %s]" % (result, " ".join(sorted(self.exclude)))
return result
def is_active(self, name):
return name.lower() in self.active
def add_active(self, name):
if isinstance(name, list):
for s in name:
self.add_active(s)
elif isinstance(name, Spec):
self.add_active(name.name)
elif isinstance(name, Section):
self.add_active(name.name)
else:
self.active.append(name.lower())
def add_exclude(self, name):
if isinstance(name, list):
for s in name:
self.add_exclude(s)
else:
self.exclude.add(name)
def _abort(message, *args):
if args:
message = message % args
print(message)
print("See --help and/or --list for instructions")
sys.exit(1)
def main():
runner = RoamingRunner()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-l", "--list", action="store_true", help="List what can be specified as what to roam.")
parser.add_argument("-c", "--commit", action="store_true", help="Commit changes.")
parser.add_argument("what", nargs="*", help="What to roam (see --list for what's available).")
args = parser.parse_args()
if args.list:
print(runner.help())
sys.exit(0)
if not ROAMING_ROOT.startswith(HOME):
print("Roaming root '%s' does not reside under HOME '%s'" % (ROAMING_ROOT, HOME))
# sys.exit(1)
if args.what:
settings = Settings("command line")
for what in args.what:
runner.add_to_settings(settings, what)
if not settings.active:
_abort("Couldn't figure out what to roam with '%s'", " ".join(args.what))
else:
settings = runner.settings_from_file("default")
if not settings:
print("Specify which settings to roam (see --help)")
print("You can also create a 'default.cfg' file in the roaming folder (%s)" % ROAMING_ROOT)
print("See 'bash.cfg' for an example of how to write a 'default.cfg' file")
sys.exit(1)
report = runner.setup(settings, args.commit)
if not report.messages:
_abort("Couldn't figure out what to roam with '%s'", " ".join(args.what))
print(report)
if not args.commit and report.logs and not report.errors:
print("Use -c to effectively perform these changes")
elif not report.logs and not report.errors:
print("All good")
if report.errors:
sys.exit(1)
if __name__ == "__main__":
if not HOME:
_abort("Could not determine HOME folder, please check this script")
main()