-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathbrew-file
executable file
·3488 lines (3117 loc) · 134 KB
/
brew-file
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
# -*- coding: utf-8 -*-
"""
Brew-file: Manager for packages of Homebrew
https://github.com/rcmdnk/homebrew-file
requirement: Python 3.7 or later
"""
import argparse
import copy
import getpass
import glob
import json
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
from io import StringIO
from urllib.parse import quote
__prog__ = os.path.basename(__file__)
__description__ = __doc__
__author__ = "rcmdnk"
__copyright__ = "Copyright (c) 2013 rcmdnk"
__credits__ = ["rcmdnk"]
__license__ = "MIT"
__version__ = "v8.0.5"
__date__ = "14/Sep/2020"
__maintainer__ = "rcmdnk"
__email__ = "[email protected]"
__status__ = "Prototype"
def is_mac():
if platform.system() == "Darwin":
return True
return False
def open_output_file(name, mode="w"):
"""Helper function to open a file even if it doesn't exist."""
if os.path.dirname(name) != "" and \
not os.path.exists(os.path.dirname(name)):
os.makedirs(os.path.dirname(name))
return open(name, mode)
def to_bool(val):
if isinstance(val, bool):
return val
if isinstance(val, int) or (isinstance(val, str) and val.isdigit()):
return bool(int(val))
if isinstance(val, str):
if val.lower() == "true":
return True
return False
def to_num(val):
if isinstance(val, bool):
return int(val)
if isinstance(val, int) or (isinstance(val, str) and val.isdigit()):
return int(val)
if isinstance(val, str):
if val.lower() == "true":
return 1
return 0
def expandpath(val):
f = os.path.expandvars(os.path.expanduser(val))
for h in ('$HOSTNAME', '${HOSTNAME}'):
f = f.replace(h, os.uname()[1])
return f
class Tee:
"""Module to write out in two ways at once."""
def __init__(self, out1, out2=sys.stdout, use2=True):
"""__init__"""
if isinstance(out1, str):
self.out1name = out1
self.out1 = StringIO()
else:
self.out1name = ""
self.out1 = out1
self.use2 = use2
if self.use2:
if isinstance(out2, str):
self.out2name = out2
self.out2 = StringIO()
else:
self.out2name = ""
self.out2 = out2
def __del__(self):
"""__del__"""
if self.out1name != "":
self.out1.close()
if self.use2:
if self.out2name != "":
self.out2.close()
def write(self, text):
"""Write w/o line break."""
self.out1.write(text)
if self.use2:
self.out2.write(text)
def writeln(self, text):
"""Write w/ line break."""
self.out1.write(text + "\n")
if self.use2:
self.out2.write(text + "\n")
def flush(self):
"""Flush the output"""
self.out1.flush()
if self.use2:
self.out2.flush()
def close(self):
"""Close output files."""
if self.out1name != "":
f = open_output_file(self.out1name, "w")
f.write(self.out1.getvalue())
f.close()
if self.use2:
if self.out2name != "":
f = open(self.out2name, "w")
f.write(self.out2.getvalue())
f.close()
self.__del__()
class BrewHelper:
"""Helper functions for BrewFile."""
def __init__(self, opt):
self.opt = opt
self.colors = {"black": "30", "red": "31", "green": "32",
"yellow": "33", "blue": "34", "magenta": "35",
"lightblue": 36, "white": 37}
def readstdout(self, proc):
while True:
line = proc.stdout.readline().decode().rstrip()
code = proc.poll()
if line == '':
if code is not None:
break
continue
yield line
def proc(self, cmd, print_cmd=True, print_out=True,
exit_on_err=True, separate_err=False, print_err=True,
verbose=1, env={}):
""" Get process output."""
if not isinstance(cmd, list):
cmd = shlex.split(cmd)
cmd_orig = " ".join(["$"] + cmd)
if cmd[0] == "brew":
cmd[0] = self.opt["brew_cmd"]
if print_cmd:
self.info(cmd_orig, verbose)
all_env = os.environ.copy()
for k, v in env.items():
all_env[k] = v
lines = []
try:
if separate_err:
if print_err:
stderr = None
else:
stderr = open(os.devnull, 'w')
else:
stderr = subprocess.STDOUT
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr,
env=all_env)
if separate_err and not print_err:
stderr.close()
for line in self.readstdout(p):
lines.append(line)
if print_out:
self.info(line, verbose)
ret = p.wait()
except OSError as e:
if print_out:
lines = [" ".join(cmd) + ": " + str(e)]
self.info(lines[0].strip(), verbose)
ret = -1
if exit_on_err and ret != 0:
if not (print_out and self.opt["verbose"] >= verbose):
print("\n".join(lines))
self.err("Failed at command: " + " ".join(cmd))
sys.exit(ret)
return ret, lines
def out(self, text, verbose=100, color=""):
if self.opt["verbose"] < verbose:
return
pre = post = ""
if color != "" and sys.stdout.isatty():
if color in self.colors:
pre = "\033[" + self.colors[color] + ";1m"
post = "\033[m"
print(pre + text + post)
def info(self, text, verbose=2):
self.out(text, verbose)
def warn(self, text, verbose=1):
self.out("[WARNING]: " + text, verbose, "yellow")
def err(self, text, verbose=0):
self.out("[ERROR]: " + text, verbose, "red")
def banner(self, text, verbose=1):
width = 0
for line in text.split("\n"):
if width < len(line):
width = len(line)
self.out("\n" + "#" * width + "\n" + text + "\n" + "#" * width + "\n",
verbose)
def brew_val(self, name):
if name not in self.opt:
self.opt[name] = self.proc("brew --" + name, False, False)[1][0]
return self.opt[name]
class BrewInfo:
"""Homebrew information storage."""
def __init__(self, helper, filename=""):
self.brew_input_opt = {}
self.pip_input_opt = {}
self.gem_input_opt = {}
self.brew_input = []
self.tap_input = []
self.cask_input = []
self.pip_input = []
self.gem_input = []
self.appstore_input = []
self.file_input = []
self.before_input = []
self.after_input = []
self.cmd_input = []
self.brew_list_opt = {}
self.pip_list_opt = {}
self.gem_list_opt = {}
self.brew_list = []
self.brew_full_list = []
self.tap_list = []
self.cask_list = []
self.pip_list = []
self.gem_list = []
self.appstore_list = []
self.file_list = []
self.cask_nocask_list = []
self.list_dic = {
"brew_input_opt": self.brew_input_opt,
"pip_input_opt": self.pip_input_opt,
"gem_input_opt": self.gem_input_opt,
"brew_input": self.brew_input,
"tap_input": self.tap_input,
"cask_input": self.cask_input,
"pip_input": self.pip_input,
"gem_input": self.gem_input,
"appstore_input": self.appstore_input,
"file_input": self.file_input,
"before_input": self.before_input,
"after_input": self.after_input,
"cmd_input": self.cmd_input,
"brew_list_opt": self.brew_list_opt,
"pip_list_opt": self.pip_list_opt,
"gem_list_opt": self.gem_list_opt,
"brew_list": self.brew_list,
"brew_full_list": self.brew_full_list,
"tap_list": self.tap_list,
"cask_list": self.cask_list,
"cask_nocask_list": self.cask_nocask_list,
"pip_list": self.pip_list,
"gem_list": self.gem_list,
"appstore_list": self.appstore_list,
"file_list": self.file_list,
}
self.filename = filename
self.helper = helper
def set_file(self, filename):
self.filename = filename
def get_file(self):
return self.filename
def get_dir(self):
return os.path.dirname(self.filename)
def check_file(self):
if os.path.exists(self.filename):
return True
return False
def check_dir(self):
if os.path.exists(self.get_dir()):
return True
return False
def clear(self):
self.clear_input()
self.clear_list()
def clear_input(self):
self.brew_input_opt.clear()
self.pip_input_opt.clear()
self.gem_input_opt.clear()
del self.brew_input[:]
del self.tap_input[:]
del self.cask_input[:]
del self.pip_input[:]
del self.gem_input[:]
del self.appstore_input[:]
del self.file_input[:]
del self.before_input[:]
del self.after_input[:]
del self.cmd_input[:]
def clear_list(self):
self.brew_list_opt.clear()
self.pip_list_opt.clear()
self.gem_list_opt.clear()
del self.brew_list[:]
del self.brew_full_list[:]
del self.tap_list[:]
del self.cask_list[:]
del self.cask_nocask_list[:]
del self.pip_list[:]
del self.gem_list[:]
del self.appstore_list[:]
del self.file_list[:]
def input_to_list(self):
self.clear_list()
self.brew_list.extend(self.brew_input)
self.brew_list_opt.update(self.brew_input_opt)
self.pip_list_opt.update(self.pip_input_opt)
self.gem_list_opt.update(self.gem_input_opt)
self.tap_list.extend(self.tap_input)
self.cask_list.extend(self.cask_input)
self.pip_list.extend(self.pip_input)
self.gem_list.extend(self.gem_input)
self.appstore_list.extend(self.appstore_input)
self.file_list.extend(self.file_input)
def sort(self):
core_tap = []
cask_tap = []
brew_taps = []
other_taps = []
for t in self.tap_list:
if t == "homebrew/core":
core_tap.append(t)
elif t == self.helper.opt["cask_repo"]:
cask_tap.append(t)
elif t.startswith("homebrew/"):
brew_taps.append(t)
else:
other_taps.append(t)
brew_taps.sort()
other_taps.sort()
self.tap_list = core_tap + brew_taps + cask_tap + other_taps
self.brew_list.sort()
self.brew_full_list.sort()
self.cask_list.sort()
self.pip_list.sort()
self.gem_list.sort()
self.file_list.sort()
self.cask_nocask_list.sort()
self.appstore_list.sort(
key=lambda x: x.split()[1].lower() if len(x.split()) > 1
else x.split()[0])
def get(self, name):
return copy.deepcopy(self.list_dic[name])
def remove(self, name, package):
if isinstance(self.list_dic[name], list):
self.list_dic[name].remove(package)
elif isinstance(self.list_dic[name], dict):
del self.list_dic[name][package]
def set_val(self, name, val):
if isinstance(self.list_dic[name], list):
del self.list_dic[name][:]
self.list_dic[name].extend(val)
elif isinstance(self.list_dic[name], dict):
self.list_dic[name].clear()
self.list_dic[name].update(val)
def add(self, name, val):
if isinstance(self.list_dic[name], list):
self.list_dic[name].extend(val)
elif isinstance(self.list_dic[name], dict):
self.list_dic[name].update(val)
def read(self, filename=""):
self.clear_input()
try:
if filename == "":
f = open(self.filename, "r")
else:
f = open(filename, "r")
except IOError:
return False
lines = f.readlines()
f.close()
is_ignore = False
self.tap_input.append("direct")
for line in lines:
if re.match("# *BREWFILE_ENDIGNORE", line):
is_ignore = False
if re.match("# *BREWFILE_IGNORE", line):
is_ignore = True
if is_ignore:
continue
if re.match(" *$", line) is not None or\
re.match(" *#", line) is not None:
continue
args = line.replace("'", "").replace('"', "").\
replace(",", " ").replace("[", "").replace("]", "").split()
cmd = args[0]
p = args[1] if len(args) > 1 else ""
if len(args) > 2 and p in ["tap", "cask", "pip", "gem"]:
args.pop(0)
cmd = args[0]
p = args[1]
if self.helper.opt["form"] == "none":
self.helper.opt["form"] = "cmd"
if len(args) > 2 and cmd in ["brew", "cask", "gem"] and \
p == "install":
args.pop(1)
p = args[1]
if self.helper.opt["form"] == "none":
self.helper.opt["form"] = "cmd"
if len(args) > 2:
if args[2] == "args:":
opt = " " + " ".join(["--" + x for x in args[3:]]).strip()
if self.helper.opt["form"] == "none":
self.helper.opt["form"] = "bundle"
else:
opt = " " + " ".join(args[2:]).strip()
else:
opt = ""
excmd = " ".join(line.split()[1:]).strip()
if self.helper.opt["form"] == "none":
if cmd in ["brew", "tap", "tapall", "pip", "gem"]:
if '"' in line or "'" in line:
self.helper.opt["form"] = "bundle"
if cmd in ("brew", "install"):
self.brew_input.append(p)
self.brew_input_opt[p] = (opt)
elif cmd == "tap":
self.tap_input.append(p)
elif cmd == "tapall":
self.tap_input.append(p)
for tp in self.get_tap_packs(p):
self.brew_input.append(tp)
self.brew_input_opt[tp] = ""
for tp in self.get_tap_casks(p):
self.cask_input.append(tp)
elif cmd == "cask":
self.cask_input.append(p)
elif cmd == "pip":
self.pip_input.append(p)
self.pip_input_opt[p] = (opt)
elif cmd == "gem":
self.gem_input.append(p)
self.gem_input_opt[p] = (opt)
elif cmd == "mas" and line.find(',') != -1:
if self.helper.opt["form"] == "none":
self.helper.opt["form"] = "bundle"
p = line.split()[1].strip(",").strip("'").strip('"')
pid = line.split()[3]
self.appstore_input.append(pid + ' ' + p)
elif cmd in ("appstore", "mas"):
self.appstore_input.append(re.sub("^ *appstore *", "", line).
strip().strip("'").strip('"'))
elif cmd == "file" or cmd.lower() == "brewfile":
self.file_input.append(p)
elif cmd == "before":
self.before_input.append(excmd)
elif cmd == "after":
self.after_input.append(excmd)
else:
self.cmd_input.append(line.strip())
def get_tap_path(self, tap):
"""Get tap path"""
if tap == "direct":
return self.helper.brew_val("cache") + "/Formula"
tap_user = os.path.dirname(tap)
tap_repo = os.path.basename(tap)
return self.helper.brew_val("repository") + "/Library/Taps" +\
"/" + tap_user + "/homebrew-" + tap_repo
def get_tap_packs(self, tap):
"""Helper for tap configuration file"""
packs = []
tap_path = self.get_tap_path(tap)
if not os.path.isdir(tap_path):
return packs
packs = list(map(lambda x: x.replace(".rb", ""),
filter(lambda y: y.endswith(".rb"),
os.listdir(tap_path))))
path = tap_path + "/Formula"
if os.path.isdir(path):
packs += list(map(lambda x: x.replace(".rb", ""),
filter(lambda y: y.endswith(".rb"),
os.listdir(path))))
return sorted(packs)
def get_tap_casks(self, tap):
"""Helper for tap configuration file"""
tap_path = self.get_tap_path(tap)
casks = []
if not os.path.isdir(tap_path):
return casks
path = tap_path + "/Casks"
if os.path.isdir(path):
casks = list(map(lambda x: x.replace(".rb", ""),
filter(lambda y: y.endswith(".rb"),
os.listdir(tap_path + "/Casks"))))
return sorted(casks)
def get_leaves(self):
leavestmp = self.helper.proc("brew leaves", False, False)[1]
leaves = []
for line in leavestmp:
leaves.append(line.split("/")[-1])
return leaves
def get_info(self, package=""):
if package == "":
package = "--installed"
infotmp = json.loads(
self.helper.proc("brew info --json=v1 " + package, print_cmd=False,
print_out=False, exit_on_err=True,
separate_err=True)[1][0])
info = {}
for i in infotmp:
info[i["name"]] = i
return info
def get_installed(self, package, package_info=""):
"""get installed version of brew package"""
if not isinstance(package_info, dict):
package_info = self.get_info(package)[package]
installed = package_info["installed"][0]
version = ""
if package_info["linked_keg"] is None:
version = self.helper.proc(
"ls -l " + self.helper.brew_val("prefix") + "/opt/" + package,
print_cmd=False, print_out=False, exit_on_err=False,
separate_err=False)[1][0]
version = version.split("/")[-1]
if "No such file or directory" in version:
version = ""
else:
version = package_info["linked_keg"]
if version != "":
for i in package_info["installed"]:
if i["version"].replace(".reinstall", "") == version:
installed = i
break
return installed
def get_option(self, package, package_info=""):
"""get install options from brew info"""
# Get options for build
if not isinstance(package_info, dict):
package_info = self.get_info(package)[package]
opt = ""
installed = self.get_installed(package, package_info)
if installed["used_options"]:
opt = " " + " ".join(installed["used_options"])
for k, v in package_info["versions"].items():
if installed["version"] == v and k != "stable":
if k == "head":
opt += " --HEAD"
else:
opt += " --" + k
return opt
def convert_option(self, opt):
if opt != "" and self.helper.opt["form"] in ["brewdler", "bundle"]:
opt = ", args: [" + ", ".join(
["'" + re.sub("^--", "", x) + "'" for x in opt.split()]) + "]"
return opt
def packout(self, pack):
if self.helper.opt["form"] in ["brewdler", "bundle"]:
return "'" + pack + "'"
return pack
def mas_pack(self, pack):
if self.helper.opt["form"] in ["brewdler", "bundle"]:
pack_split = pack.split()
pid = pack_split[0]
name = pack_split[1:]
return "'" + ' '.join(name) + "', id: " + pid
return pack
def write(self):
output_prefix = ""
output = ""
# commands for each format
if self.helper.opt["form"] in ["file", "none"]:
cmd_before = "before "
cmd_after = "after "
cmd_other = ""
cmd_install = "brew "
cmd_tap = "tap "
cmd_cask = "cask "
cmd_pip = "pip "
cmd_gem = "gem "
cmd_cask_nocask = "#cask "
cmd_appstore = "appstore "
cmd_file = "file "
elif self.helper.opt["form"] in ["brewdler", "bundle"]:
cmd_before = "#before "
cmd_after = "#after "
cmd_other = "#"
cmd_install = "brew "
cmd_tap = "tap "
cmd_cask = "cask "
cmd_pip = "#pip "
cmd_gem = "#gem "
cmd_cask_nocask = "#cask "
cmd_appstore = "mas "
cmd_file = "#file "
elif self.helper.opt["form"] in ["command", "cmd"]:
# Shebang for command format
output_prefix += """#!/usr/bin/env bash
#BREWFILE_IGNORE
if ! which brew >& /dev/null;then
brew_installed=0
echo Homebrew is not installed!
echo Install now...
echo /bin/bash -c \\\"\\$\\(curl -fsSL
https://raw.githubusercontent.com/Homebrew/
install/master/install.sh\\)\\\
/bin/bash -c \"$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/
install/master/install.sh)\
echo
fi
#BREWFILE_ENDIGNORE
"""
cmd_before = ""
cmd_after = ""
cmd_other = ""
cmd_install = "brew install "
cmd_tap = "brew tap "
cmd_cask = "brew cask install "
cmd_pip = "brew pip "
cmd_gem = "brew gem install "
cmd_cask_nocask = "#brew cask install "
cmd_appstore = "mas install "
cmd_file = "#file "
# sort
self.sort()
# Before commands
if self.before_input:
output += "# Before commands\n"
for c in self.before_input:
output += cmd_before + c + "\n"
# Taps
if self.tap_list:
isfirst = True
def first_tap_pack_write(isfirst, direct_first, isfirst_pack, tap,
cmd_tap):
output = ""
if isfirst:
output += "\n# tap repositories and their packages\n"
if not direct_first and isfirst_pack:
output += "\n" + cmd_tap + self.packout(tap) + "\n"
return output
for t in self.tap_list:
isfirst_pack = True
direct_first = False
tap_packs = self.get_tap_packs(t)
if t == "direct":
if not tap_packs:
continue
direct_first = True
if not self.helper.opt["caskonly"]:
output += first_tap_pack_write(isfirst, direct_first,
isfirst_pack, t, cmd_tap)
isfirst = isfirst_pack = False
for p in self.brew_list[:]:
if p.split("/")[-1].replace(
".rb", "") in tap_packs:
if direct_first:
direct_first = False
output += "\n## " + "Direct install\n"
pack = self.packout(p) +\
self.convert_option(self.brew_list_opt[p])
output += cmd_install + pack + "\n"
self.brew_list.remove(p)
del self.brew_list_opt[p]
if not is_mac():
continue
tap_casks = self.get_tap_casks(t)
for p in self.cask_list[:]:
if p in tap_casks:
output += first_tap_pack_write(
isfirst, False,isfirst_pack, t, cmd_tap)
isfirst = isfirst_pack = False
output += cmd_cask + self.packout(p) + "\n"
self.cask_list.remove(p)
# Brew packages
if not self.helper.opt["caskonly"] and self.brew_list:
output += "\n# Other Homebrew packages\n"
for p in self.brew_list:
pack = self.packout(p) +\
self.convert_option(self.brew_list_opt[p])
output += cmd_install + pack + "\n"
# pip packages
if not self.helper.opt["caskonly"] and self.pip_list:
output += "\n# Other pip packages\n"
for p in self.pip_list:
pack = self.packout(p)
if len(self.pip_list_opt[p]) == 1:
pack = pack + "=" + self.pip_list_opt[p][0].strip()
output += cmd_pip + pack + "\n"
# gem packages
if not self.helper.opt["caskonly"] and self.gem_list:
output += "\n# Other gem packages\n"
for p in self.gem_list:
pack = self.packout(p) + self.gem_list_opt[p]
output += cmd_gem + pack + "\n"
# Casks
if is_mac() and self.cask_list:
output += "\n# Other Cask applications\n"
for c in self.cask_list:
output += cmd_cask + self.packout(c) + "\n"
# Installed by cask, but cask files were not found...
if is_mac() and self.cask_nocask_list:
output += "\n# Below applications were installed by Cask,\n"
output += "# but do not have corresponding casks.\n\n"
for c in self.cask_nocask_list:
output += cmd_cask_nocask + self.packout(c) + "\n"
# App Store applications
if is_mac() and self.helper.opt["appstore"] \
and self.appstore_list:
output += "\n# App Store applications\n"
for a in self.appstore_list:
output += cmd_appstore + self.mas_pack(a) + "\n"
# Additional files
if self.file_list:
output += "\n# Additional files\n"
for f in self.file_list:
output += cmd_file + self.packout(f) + "\n"
# Other commands
if self.cmd_input:
output += "\n# Other commands\n"
for c in self.cmd_input:
output += cmd_other + c + "\n"
# After commands
if self.after_input:
output += "\n# After commands\n"
for c in self.after_input:
output += cmd_after + c + "\n"
# Write to Brewfile
if output:
output = output_prefix + output
out = Tee(self.get_file(), sys.stdout,
self.helper.opt["verbose"] > 1)
out.write(output)
out.close()
# Change permission for exe/normal file
if self.helper.opt["form"] in ["command", "cmd"]:
self.helper.proc(
"chmod 755 %s" % self.get_file(), print_cmd=False,
print_out=False, exit_on_err=False)
else:
self.helper.proc(
"chmod 644 %s" % self.get_file(), print_cmd=False,
print_out=False, exit_on_err=False)
class BrewFile:
"""Main class of Brew-file."""
def __init__(self):
"""initialization."""
# Set default values
self.opt = {}
# Prepare helper, need verbose first
self.opt["verbose"] = int(
os.environ.get("HOMEBREW_BRWEFILE_VERBOSE", 1))
self.helper = BrewHelper(self.opt)
# Other default values
self.opt["command"] = ""
self.opt["input"] = os.environ.get("HOMEBREW_BREWFILE", "")
brewfile_config = os.environ["HOME"] + "/.config/brewfile/Brewfile"
brewfile_home = os.environ["HOME"] + "/.brewfile/Brewfile"
if self.opt["input"] == "":
if not os.path.isfile(brewfile_config) and\
os.path.isfile(brewfile_home):
self.opt["input"] = brewfile_home
else:
self.opt["input"] = brewfile_config
self.opt["backup"] = os.environ.get("HOMEBREW_BREWFILE_BACKUP", "")
self.opt["leaves"] = to_bool(
os.environ.get("HOMEBREW_BREWFILE_LEAVES", False))
self.opt["on_request"] = to_bool(
os.environ.get("HOMEBREW_BREWFILE_ON_REQUEST", False))
self.opt["top_packages"] = os.environ.get(
"HOMEBREW_BREWFILE_TOP_PACKAGES", "")
self.opt["form"] = "none"
self.opt["repo"] = ""
self.opt["noupgradeatupdate"] = False
self.opt["link"] = True
self.opt["caskonly"] = False
self.opt["dryrun"] = True
self.opt["initialized"] = False
self.opt["cask_repo"] = "homebrew/cask"
self.opt["reattach_formula"] = "reattach-to-user-namespace"
self.opt["mas_formula"] = "mas"
self.opt["pip_pack"] = "brew-pip"
self.opt["gem_pack"] = "brew-gem"
self.opt["my_editor"] = os.environ.get("EDITOR", "vim")
self.opt["is_brew_cmd"] = False
self.opt["brew_cmd"] = ""
self.opt["is_cask_cmd"] = False
self.opt["cask_cmd_installed"] = False
self.opt["mas_cmd"] = "mas"
self.opt["is_mas_cmd"] = 0
self.opt["mas_cmd_installed"] = False
self.opt["reattach_cmd_installed"] = False
self.opt["is_pip_cmd"] = False
self.opt["pip_cmd_installed"] = False
self.opt["is_gem_cmd"] = False
self.opt["gem_cmd_installed"] = False
self.opt["args"] = []
self.opt["yn"] = False
self.opt["brew_packages"] = ""
self.opt["homebrew_ruby"] = False
# Check Homebrew
self.check_brew_cmd()
# Check Homebrew variables
cask_opts = self.parse_env_opts(
"HOMEBREW_CASK_OPTS", {"--appdir": "", "--fontdir": ""})
if not os.path.isdir(self.brew_val("prefix") + "/Caskroom") and\
os.path.isdir("/opt/homebrew-cask/Caskroom"):
self.opt["caskroom"] = "/opt/homebrew-cask/Caskroom"
else:
self.opt["caskroom"] =\
self.brew_val("prefix") + "/Caskroom"
self.opt["appdir"] = cask_opts["--appdir"].rstrip("/") \
if cask_opts["--appdir"] != ""\
else os.environ["HOME"] + "/Applications"
self.opt["appdirlist"] = ["/Applications",
os.environ["HOME"] + "/Applications"]
if self.opt["appdir"].rstrip("/") not in self.opt["appdirlist"]:
self.opt["appdirlist"].append(self.opt["appdir"])
self.opt["appdirlist"] += [x.rstrip("/") + "/Utilities"
for x in self.opt["appdirlist"]]
self.opt["appdirlist"] = [x for x in self.opt["appdirlist"]
if os.path.isdir(x)]
# fontdir may be used for application search, too
self.opt["fontdir"] = cask_opts["--fontdir"]
self.opt["appstore"] = to_num(
os.environ.get("HOMEBREW_BREWFILE_APPSTORE", -1))
self.opt["no_appstore"] = to_num(
os.environ.get("HOMEBREW_BREWFILE_APPSTORE", 1))
gem_opts = self.parse_env_opts("HOMEBREW_GEM_OPTS")
if "--homebrew-ruby" in gem_opts:
self.opt["homebrew_ruby"] = True
self.int_opts = ["verbose"]
self.float_opts = []
self.brewinfo = BrewInfo(self.helper, self.opt["input"])
self.brewinfo_ext = []
self.opt["read"] = False
self.pack_deps = {}
self.top_packs = []
self.editor = ""
def parse_env_opts(self, env_var, base_opts=None):
"""Returns a dictionary parsed from an environment variable"""
if base_opts is not None:
opts = base_opts.copy()
else:
opts = {}
env_var = env_var.upper()
env_opts = os.environ.get(env_var, None)
if env_opts:
# these can be flags ("--flag") or values ("--key=value")
# but not weirdness ("--foo=bar=baz")
user_opts = {key.lower(): value for (key, value) in
[pair.partition("=")[::2] for pair in env_opts.split()
if pair.count("=") < 2]}
if user_opts:
opts.update(user_opts)
else:
self.warn("%s: \"%s\" is not a proper format." %
(env_var, env_opts), 0)
self.warn("Ignoring the value.\n", 0)
return opts
def set_args(self, **kw):
"""Set arguments."""
for k, v in kw.items():
self.opt[k] = v
for k in self.int_opts:
self.opt[k] = int(self.opt[k])
for k in self.float_opts:
self.opt[k] = float(self.opt[k])