-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
setup
executable file
·2020 lines (1715 loc) · 62.7 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
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
# vim: set ft=python ts=4 sw=4 sts=4 et :
# -*- coding: utf-8 -*-
# setup.py --- Qubes Builder Configuration Utility
#
# Copyright (C) 2015 Jason Mehring
#
# License: GPL-2+
# ------------------------------------------------------------------------------
# Install 'dialog' program if it does not yet exist
# ------------------------------------------------------------------------------
# pylint: disable=E1101,W1401
import argparse
import codecs
import collections
import collections.abc
import copy
import locale
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
import tty
import types
import configparser
from subprocess import (Popen, STDOUT)
from textwrap import dedent, wrap
# Globals
DIALOG = 'dialog'
DEVELOPMENT_MODE = False
# Global file locations
BASE_DIR = os.getcwd()
CONFIG_DIR = 'example-configs'
OVERRIDE_CONF = 'override.conf'
OVERRIDE_DATA = 'override.data'
MASTER_TEMPLATE = 'templates.conf'
BUILDER_CONF = 'builder.conf'
BACKUP_EXTENSION = '.bak'
QUBES_DEVELOPERS_KEYS = 'qubes-developers-keys.asc'
GNUPGHOME = os.path.join(os.path.abspath(BASE_DIR), 'keyrings/git')
# Add 'qubes-builder/libs' directory to sys.path
LIBS_DIR = os.path.join(BASE_DIR, 'libs')
if os.path.exists(LIBS_DIR) and os.path.isdir(LIBS_DIR):
if LIBS_DIR not in sys.path:
sys.path.insert(1, LIBS_DIR)
# Import ANSIColor after LIBS_DIR is added to path
from ansi import ANSIColor
locale.setlocale(locale.LC_ALL, '')
def exit(*varargs, **kwargs): # pylint: disable=W0622
"""Function to exit. Maybe restoring some files before exiting.
"""
kwargs['title'] = 'System Exit!'
kwargs['width'] = 80
kwargs['height'] = 0 # Auto height
try:
DefaultUI.ui.infobox(*varargs, **kwargs)
except AttributeError:
pass
# Restore original template.conf
try:
config = Config(None)
if os.path.exists(config.conf_builder + BACKUP_EXTENSION):
shutil.move(
config.conf_builder + BACKUP_EXTENSION, config.conf_builder
)
except NameError:
pass
sys.exit()
def getchar():
try:
import termios
except ImportError:
import msvcrt
return msvcrt.getchar()
def _getchar():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
char = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return char
return _getchar()
def get_builder_deps():
"""Install qubes-builder depends if they are not already installed.
"""
env = os.environ.copy()
if not os.path.exists(BUILDER_CONF):
env['BUILDERCONF'] = MASTER_TEMPLATE
try:
env['GET_VAR'] = 'DEPENDENCIES'
dependencies = subprocess.check_output(
['make', '--always-make', '--quiet', 'get-var'],
env=env
).strip()
env.pop('GET_VAR')
except subprocess.CalledProcessError:
print(
'\nAn error occurred trying to determine dependencies and therefore setup must now exit')
print('Exiting!')
exit()
return dependencies.decode('utf-8').split(' ')
def install_deps(packages=None):
"""Call qubes-builder make-deps to install packages if they are not already installed.
The DEPENDENCIES env variable will contain any packages to update.
"""
packages = packages or []
try:
from subprocess import DEVNULL # py3k
except ImportError:
DEVNULL = open(os.devnull, 'wb')
ansi = ANSIColor()
dependencies = set()
packages += get_builder_deps()
# Only add packages to dependency list if they are not installed
for package in packages:
proc = Popen(['rpm', '-q', '--whatprovides', package], stdout=DEVNULL,
stderr=DEVNULL)
proc.wait()
if proc.returncode:
dependencies.add(package)
if dependencies:
env = os.environ.copy()
dependencies = ' '.join(list(dependencies))
# Prompt and confirm installation of dependencies
os.system('clear')
message = 'The following dependencies have not been met:\n'
print('{ansi[blue]}{0}{ansi[red]}{1}{ansi[normal]}\r\r'.format(
message,
dependencies,
ansi=ansi
))
print(
'\nEnter \'Y\' to install {ansi[red]}ALL{ansi[normal]} dependencies now, or anything else to quit [YyNnQq]: '.format(
ansi=ansi
))
char = getchar()
if char.lower() != 'y':
print(
'\nYou selected not to install the dependencies and therefore setup must now exit'.format(
ansi=ansi
))
print('Exiting!')
exit()
# User confirmed installation of dependencies
os.system('clear')
sys.stdout.write(
'Waiting for {ansi[red]}{0}{ansi[normal]} to install\n'.format(
dependencies,
ansi=ansi
)
)
sys.stdout.flush()
env['DEPENDENCIES'] = dependencies
proc = Popen(
['make', 'install-deps'],
stdout=DEVNULL,
stderr=STDOUT,
env=env
)
while proc.poll() is None:
sys.stdout.write('{ansi[red]}.{ansi[normal]}'.format(ansi=ansi))
sys.stdout.flush()
time.sleep(1)
print("")
if proc.returncode:
print(
'\nThere was an error installing dependencies!{ansi[blue]}{ansi[normal]} and therefore setup must now exit'.format(
ansi=ansi
))
print('Exiting!')
exit()
def write_file(filename, text):
try:
with codecs.open(filename, 'w', 'utf8') as outfile:
outfile.write(dedent(text))
except IOError as err:
exit(err)
def parse_parentheses(text):
"""A very simple lexer to parse round parentheses.
"""
ansi = ANSIColor()
lexer = shlex.shlex(text)
lexer.whitespace = '\t\r\n'
text = ''
raw = ''
count = 0
for token in lexer:
chars = token
if chars[0] in '\'"' and chars[-1] in '\'"':
new_chars = parse_parentheses(chars[1:-1])
text += chars[0] + new_chars + chars[-1]
continue
if token == '(':
count += 1
if raw and raw[-1] == '$':
chars = '{ansi[blue]}{0}'.format(chars, ansi=ansi)
elif token == ')':
if count == 1:
chars = '{0}{ansi[normal]}'.format(chars, ansi=ansi)
count -= 1
elif count:
if raw and raw[-1] != '(':
chars = '{ansi[black]}{0}'.format(chars, ansi=ansi)
raw += token
text += chars
return text
def display_configuration(filename):
"""Display the configuration file.
"""
ansi = ANSIColor()
print('{ansi[bold]}{ansi[black]}{0}:{ansi[normal]}'.format(
filename,
ansi=ansi
))
try:
with codecs.open(filename, 'r', 'utf8') as infile:
for line in infile:
match = re.match(
r'(?P<text>.*?(?=#)|.*)(?P<comment>([#]+.*)|)',
line.rstrip()
)
if match:
line = ''
text = match.groupdict()['text']
comment = match.groupdict()['comment']
if match.groupdict()['text']:
var = re.match(r'(?P<var>.*)(?P<text>[?:]?=.*)', text)
target = re.match(
r'(?P<target>.*[:]+)(?P<text>.*)', text
)
text = parse_parentheses(text)
if var:
line += '{ansi[blue]}{d[var]}{ansi[normal]}{d[text]}'.format(
d=var.groupdict(),
ansi=ansi
)
elif target:
line += '{ansi[red]}{d[target]}{ansi[normal]}{d[text]}'.format(
d=target.groupdict(),
ansi=ansi
)
else:
line += '{ansi[black]}{0}{ansi[normal]}'.format(
text,
ansi=ansi
)
if comment:
line += '{ansi[green]}{0}{ansi[normal]}'.format(
comment,
ansi=ansi
)
print(line)
except IOError as err:
exit(err)
def is_linkable(source, target, replace_file=False, replace_link=False):
"""Return True if target can be linked to source.
"""
# Source does not exist or is a broken link
if not source or not os.path.exists(source):
return False
# Target does not exist or is a broken link
if target and not os.path.exists(target):
return True
# Source and target are same as indicated by device and i-node
# number
if os.path.samefile(source, target):
return False
# Target is a regular file and 'replace_file' is False
if not replace_file:
if os.path.exists(target) and not os.path.islink(target):
return False
# Target is a link and 'replace_link' is True
if replace_link and os.path.islink(target):
return True
# Most likely target is a link and 'replace_link' is False
return False
def soft_link(source, target, replace_file=False, replace_link=False):
"""Attempt to soft-link a file. Exit with message on failure.
"""
if is_linkable(source, target, replace_file, replace_link):
try:
if os.path.lexists(target):
os.remove(target)
os.symlink(source, target)
except OSError as err:
exit(
'Error linking:\n{0} to {1}\n\n{2}.'.format(
target, source, err.strerror
)
)
else:
message = 'Unable to link target file to source.'
exit(
'Error linking:\n{0} to {1}\n\n{2}'.format(
target, source, message
)
)
class DefaultUI(object):
"""Default UI contains pointer to selected UI.
"""
ui = None
@classmethod
def __init__(cls, ui):
cls.ui = ui
class DialogUI(DefaultUI):
"""UI Interface to `dialog` API.
"""
from dialog import (Dialog, ExecutableNotFound)
try:
from textwrap import indent
except ImportError:
@staticmethod
def indent(text, prefix, predicate=None):
l = []
for line in text.splitlines(True):
if (callable(predicate) and predicate(line)) \
or (not callable(predicate) and predicate) \
or (predicate is None and line.strip()):
line = prefix + line
l.append(line)
return ''.join(l)
# Initialize a dialog.Dialog instance
try:
dialog = Dialog(dialog=DIALOG, pass_args_via_file=False)
except ExecutableNotFound:
install_deps(['dialog'])
dialog = Dialog(dialog=DIALOG, pass_args_via_file=False)
@classmethod
def __init__(cls):
cls.dialog.set_background_title("Qubes Builder Configuration Utility")
super(DialogUI, cls).__init__(cls)
@classmethod
def _auto_height(cls, width, text):
_max = max(8, 5 + len(wrap(text, width=width))) # Min of 8 rows
_min = min(22, _max) # Max of 22 rows
return _min
@classmethod
def yesno(cls, **info):
"""YesNo dialog.
"""
default = {'colors': True, 'width': 60, 'height': 8, }
default.update(info)
code = cls.dialog.yesno(**default)
if code == cls.dialog.OK:
return True
elif code == cls.dialog.CANCEL:
return False
elif code == cls.dialog.ESC:
exit('Escape key pressed. Exiting.')
@classmethod
def msgbox(cls, *varargs, **info):
"""Msgbox dialog.
Only displays if text is provided. Text can be provided in varargs
"""
default = {
'colors': True,
'title': 'Qubes Setup Information.',
'width': 72,
'height': 8,
'text': ''
}
default.update(info)
if varargs:
default['text'] = ' '.join(varargs)
if not default['height']:
default['height'] = cls._auto_height(
default['width'], default['text']
)
if default['text']:
cls.dialog.msgbox(**default)
@classmethod
def infobox(cls, *varargs, **info):
"""Infobox dialog.
Only displays if text is provided. Text can be provided in varargs
"""
default = {
'colors': True,
'title': 'Qubes Setup Information.',
'width': 72,
'height': 8,
'text': ''
}
default.update(info)
if varargs:
default['text'] = ' '.join(varargs)
if not default['height']:
default['height'] = cls._auto_height(
default['width'], default['text']
)
if default['text']:
cls.dialog.infobox(**default)
@classmethod
def list_done(cls, code, tag, helper=None):
if not helper:
helper = {}
no_help = "You asked for help about something called '{0}'. Sorry, but I am quite incompetent in this matter."
if code == 'help':
cls.msgbox(
helper.get(tag[0], no_help.format(tag[0])),
height=0,
width=60
)
return False
elif code == cls.dialog.CANCEL:
exit('User aborted setup.')
elif code == cls.dialog.ESC:
exit('User aborted setup.')
else:
return True
@classmethod
def checklist(cls, **info):
"""Checklist dialog.
"""
default = {
'colors': True,
'height': 0,
'width': 0,
'list_height': 0,
'choices': [],
'title': '',
'help_button': False,
'item_help': False,
'help_tags': False,
'help_status': False,
'text': '',
}
default.update(info)
helper = default.pop('helper', {})
while True:
code, tag = cls.dialog.checklist(**default)
if cls.list_done(code, tag, helper):
break
return tag
@classmethod
def radiolist(cls, **info):
"""Radiolist dialog.
"""
default = {
'colors': True,
'height': 0,
'width': 0,
'list_height': 0,
'choices': [],
'title': '',
'help_button': False,
'item_help': False,
'help_tags': False,
'help_status': False,
'text': '',
}
default.update(info)
helper = default.pop('helper', {})
while True:
code, tag = cls.dialog.radiolist(**default)
if cls.list_done(code, tag, helper):
break
return tag
@classmethod
def release(cls, **info):
"""Display `select release` dialog of Qubes release version to build.
"""
return cls.radiolist(**info)
@classmethod
def override(cls, **info):
"""Display use override confirmation.
"""
return cls.yesno(**info)
@classmethod
def repo(cls, **info):
"""Display `choose repo` dialog.
"""
return cls.radiolist(**info)
@classmethod
def ssh_access(cls, **info):
"""Display ssh-access dialog.
"""
return cls.yesno(**info)
@classmethod
def template_only(cls, **info):
"""Display dialog choice of building only templates.
"""
return cls.yesno(**info)
@classmethod
def git_clone_fast(cls, **info):
"""Display dialog choice of git clone method.
"""
return cls.yesno(**info)
@classmethod
def dists(cls, **info):
"""Display DISTS_VM's for selection.
"""
return cls.checklist(**info)
@classmethod
def builders(cls, **info):
"""Display BUILDER_PLUGINS's for selection.
"""
return cls.checklist(**info)
@classmethod
def verify_keys(cls, **info):
"""Display `verify keys` confirmation dialog.
"""
default = {'height': 12, }
default.update(info)
return cls.yesno(**default)
@classmethod
def get_sources(cls, **info):
"""Display get-sources dialog.
"""
result = cls.yesno(**info)
get_sources = 1 if result else 0
# Download sources
if get_sources:
try:
# py3k
from subprocess import DEVNULL # pylint: disable=W0404
except ImportError:
DEVNULL = open(os.devnull, 'wb')
args = ['make', 'get-sources', 'NO_COLOR=1']
p = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=DEVNULL,
close_fds=True,
)
default = {
# 'colors': True,
# 'scrollbar': True,
'height': 40,
'width': 120,
}
cls.dialog.programbox(
fd=p.stdout.fileno(),
text="Get sources",
**default
)
retcode = p.wait()
# Context manager support for subprocess.Popen objects requires
# Python 3.2 or later.
p.stdout.close()
return retcode
class Config(object):
"""Configuration objects holds all config data.
Provides provides methods to read and write the data
"""
MARKER = object()
_makefile_vars = {
'about': '',
'release': '',
'ssh_access': 0,
'template_only': 0,
'git_baseurl': '',
'git_prefix': '',
'git_prefix_default': '',
'use_qubes_repo_version': '',
'use_qubes_repo_testing': '',
'dist_dom0_selected': '',
'dists_vm_all': [],
'dists_vm_selected': [],
'builders_selected': [],
'template_aliases_reversed': [],
'template_labels': [],
'template_labels_reversed': [],
}
_defaults_builder = {
'id': '',
'type': '',
'description': '',
'optional': [],
'require': [],
'require_in': [],
'development': False,
}
_defaults_key = {
'id': '',
'type': '',
'key': '',
'owner': '',
'fingerprint': None,
'verify': '',
'url': '',
}
_defaults_repo = {'type': '', 'description': '', 'prefix': '', }
def __init__(self, filename, **options):
"""Init.
filename is the name of the main configuration file to load which
is typically .salt.conf and is configurable with command-line option
'-c'
"""
self.filename = filename
self.options = options
self.dir_builder = self.options.get('dir_builder') or os.path.abspath(
os.path.curdir
)
self.dir_configurations = os.path.join(self.dir_builder, CONFIG_DIR)
# Override configuration filename will override and merge into .setup.data
self.conf_override_data = os.path.join(self.dir_builder, OVERRIDE_DATA)
self.parser = configparser.RawConfigParser(
dict_type=collections.OrderedDict
)
self.parser.add_section('makefile')
self.sections = []
self.releases = collections.OrderedDict()
self.keys = collections.OrderedDict()
self.repos = collections.OrderedDict()
self.builders = collections.OrderedDict()
self._init_makefile_vars()
self.conf_template = os.path.join(
self.dir_configurations, MASTER_TEMPLATE
)
self.conf_override = os.path.join(self.dir_builder, OVERRIDE_CONF)
self.conf_builder = os.path.join(self.dir_builder, BUILDER_CONF)
# Copy example-configs/template.conf to builder.conf if
# the configuration file does not yet exist
self._create_builder_conf(force=False)
# Parse Makefiles
self._parse_makefiles()
# Set up any branch specific override configurations
self._overrides()
# Load .setup.data
if filename and os.path.exists(filename):
self._load()
if os.path.exists(self.conf_override_data):
self._load(self.conf_override_data)
def _init_makefile_vars(self):
for key, value in self._makefile_vars.items():
setattr(self, key, value)
def _create_builder_conf(self, force=False):
"""Copies example-configs/template.conf to builder.conf
"""
if not os.path.exists(self.conf_builder) or force:
try:
if os.path.exists(self.conf_builder) and force:
os.remove(self.conf_builder)
shutil.copy2(self.conf_template, self.conf_builder)
# ABOUT
replace = ReplaceInplace(self.conf_builder)
replace.add(
**{
'replace': r'@echo "{0}"'.format(MASTER_TEMPLATE),
'text': r'@echo "{0}"'.format(BUILDER_CONF),
}
)
replace.start()
except IOError as err:
exit(err)
# def __getattribute__(self, name):
# return super(Config, self).__getattribute__(name)
@staticmethod
def _coerce_value(default, value):
if type(value) != type(default):
try:
if isinstance(default, bool):
value = bool(value)
elif isinstance(default, int):
value = int(value)
elif isinstance(default, float):
value = float(value)
elif isinstance(default, list):
if isinstance(value, str):
if value.strip().lower() in ['none', 'null']:
value = []
else:
value = value.strip().split()
elif default is None:
value = None
except ValueError:
value = default
return value
def _coerce_values(self, defaults, values):
if not isinstance(defaults, collections.abc.Mapping):
return values
if isinstance(values, collections.abc.Mapping):
for key, value in values.items():
if key in defaults:
values[key] = self._coerce_value(defaults[key], value)
return values
def __setattr__(self, name, value):
if name in self._makefile_vars:
default = self._makefile_vars[name]
value = self._coerce_value(default, value)
self.parser.set('makefile', name, value)
return super(Config, self).__setattr__(name, value)
def _get_section(self, section_name):
adict = collections.OrderedDict()
options = self.parser.options(section_name)
for option in options:
try:
adict[option] = self.parser.get(section_name, option)
# if adict[option] == -1:
# adict.pop(option, None)
except (configparser.Error, TypeError):
adict[option] = None
return adict
def _load(self, filename=None):
if not filename:
filename = self.filename
self.parser.read_file(codecs.open(filename, 'r', 'utf8'))
for section_name in self.parser.sections():
section = self._get_section(section_name)
if not section:
continue
section_type = section.get('type', section_name)
if section_type == 'gpg':
config = copy.deepcopy(self._defaults_key)
section['id'] = section_name
config.update(section)
self.keys[section_name] = config
elif section_type == 'repo':
config = copy.deepcopy(self._defaults_repo)
config.update(section)
self.repos[section_name] = config
elif section_type == 'builder':
config = copy.deepcopy(self._defaults_builder)
config.update(section)
self.builders[section_name] = self._coerce_values(
self._defaults_builder, config
)
elif section_type == 'releases':
self.releases = section
def _overrides(self):
"""Set up any branch specific override configurations.
"""
# See if a branch specific override configuration file exists
branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
override_path = None
# Skip if overrides already exists and is a regular file
if not (
os.path.exists(self.conf_override) and
not os.path.islink(self.conf_override)
):
directory = self.dir_configurations
override = os.path.basename(self.conf_override)
patterns = []
# Example: example-configs/r3-feature_branch-override.conf
# example-configs/r3-master-override.conf
patterns.append(
'{0}/r{1}-{2}-{3}'.format(
directory, self.release, branch, override
)
)
# Example: example-configs/feature_branch-override.conf
# example-configs/master-override.conf
patterns.append('{0}/{1}-{2}'.format(directory, branch, override))
# Example: example-configs/override.conf
patterns.append('{0}/{1}'.format(directory, override))
for pattern in patterns:
if os.path.exists(pattern):
override_path = pattern
break
if is_linkable(
override_path,
self.conf_override,
replace_link=True
):
info = {
'title':
'Use Branch Specific Override Configuration File?',
'default_button': 'yes',
'text': dedent(
"""\
A branch specific configuration file was found in your personal directory:
{0}.
Would you like to use and override the other provided repos?
""".format(override_path)
),
}
# Link if user confirmed override
if DefaultUI.ui.override(**info):
soft_link(
override_path,
self.conf_override,
replace_link=True
)
# Re-parse Makefiles
self._parse_makefiles()
def _parse_makefiles(self):
"""
"""
from sh import make # pylint: disable=E0611
env = os.environ.copy()
make = make.bake(
'--always-make',
'--quiet',
'get-var',
directory=self.dir_builder,
_env=env
)
# Get variables from Makefile
try:
env['GET_VAR'] = 'RELEASE'
self.release = make().strip()
env['GET_VAR'] = 'SSH_ACCESS'
self.ssh_access = make().strip()
env['GET_VAR'] = 'TEMPLATE_ONLY'
self.template_only = make().strip()
env['GET_VAR'] = 'BUILDER_PLUGINS_ALL'
self.builders_selected = make().strip()
env['GET_VAR'] = 'GIT_BASEURL'
self.git_baseurl = make().strip()
env['GET_VAR'] = 'GIT_PREFIX'
self.git_prefix = make().strip()
self.git_prefix_default = self.git_prefix
env['GET_VAR'] = 'GIT_CLONE_FAST'
self.git_clone_fast = make().strip()
env['GET_VAR'] = 'USE_QUBES_REPO_VERSION'
self.use_qubes_repo_version = make().strip()
env['GET_VAR'] = 'USE_QUBES_REPO_TESTING'
self.use_qubes_repo_testing = make().strip()
env['GET_VAR'] = 'DISTS_VM'
self.dists_vm_selected = make().strip().split()
env['GET_VAR'] = 'DIST_DOM0'
self.dist_dom0_selected = make().strip().split()
env['SETUP_MODE'] = '1'
env['GET_VAR'] = 'DISTS_VM'
self.dists_vm_all = make().strip().split()
env['GET_VAR'] = 'TEMPLATE_ALIAS'
aliases = make().strip().split()
self.template_aliases = dict(
[
(item.split(':')) for item in aliases
]
)
self.template_aliases_reversed = dict(
[
(
value, key
) for key, value in self.template_aliases.items()
]
)
env['GET_VAR'] = 'TEMPLATE_LABEL'
labels = make().strip().split()
self.template_labels = dict([item.split(':') for item in labels])
self.template_labels_reversed = dict(
[
(
value, key
) for key, value in self.template_labels.items()