This repository has been archived by the owner on Oct 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
xtool
executable file
·1821 lines (1565 loc) · 56.5 KB
/
xtool
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 python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build script for XRTL.
This provides build, test, linting, and other utilities based on bazel.
All commands can be executed manually but are easier through this (in most
cases).
"""
import argparse
import difflib
import fnmatch
import hashlib
import json
import os
import re
import shutil
import string
import subprocess
import sys
self_path = os.path.dirname(os.path.abspath(__file__))
# Default config for the current host OS.
if (sys.platform == 'cygwin' or
sys.platform == 'win32'):
default_config = 'windows_x86_64'
elif sys.platform == 'darwin':
default_config = 'macos_x86_64'
else:
default_config = 'linux_x86_64'
top_level_packages = [
'//xrtl/base/...',
'//xrtl/examples/...',
'//xrtl/gfx/...',
'//xrtl/testing/...',
'//xrtl/tools/...',
'//xrtl/ui/...',
]
def main():
# Add self to the root search path.
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
# Check python version.
if not sys.version_info[:2] == (2, 7):
print('ERROR: Python 2.7 must be installed and on PATH')
return 1
# Check git exists.
if not has_bin('git'):
print('ERROR: git must be installed and on PATH.')
return 1
# Check bazel exists.
if not has_bin('bazel'):
print('ERROR: bazel must be installed and on PATH.')
return 1
# Grab Visual Studio version and execute shell to set up environment.
if sys.platform in ('cygwin', 'win32'):
vs_version = import_vs_environment()
if vs_version != 2017:
print('ERROR: Visual Studio 2017 not found!')
return 1
# Setup main argument parser and common arguments.
parser = argparse.ArgumentParser(prog='xtool')
# Grab all commands and populate the argument parser for each.
subparsers = parser.add_subparsers(title='subcommands',
dest='subcommand')
commands = discover_commands(subparsers)
# If the user passed no args, die nicely.
if len(sys.argv) == 1:
parser.print_help()
return 1
# Gather any arguments that we want to pass to child processes.
command_args = sys.argv[1:]
pass_args = []
try:
pass_index = command_args.index('--')
pass_args = command_args[pass_index + 1:]
command_args = command_args[:pass_index]
except:
pass
# Special case for bazel commands. This lets us pass everything we don't
# understand right to bazel.
allow_unknown_args = False
if len(command_args) and command_args[0] in ('clean', 'build', 'run', 'test',
'query', 'info', 'sln'):
allow_unknown_args = True
# Parse command name and dispatch.
if allow_unknown_args:
(known_args, unknown_args) = parser.parse_known_args(command_args)
args = vars(known_args)
pass_args = unknown_args + ['--'] + pass_args
else:
args = vars(parser.parse_args(command_args))
command_name = args['subcommand']
try:
command = commands[command_name]
return_code = command.execute(args, pass_args, os.getcwd())
except Exception as e:
raise
return_code = 1
return return_code
def query_reg_sz(key, value):
reg_binary = 'reg.exe'
p = subprocess.Popen([
reg_binary,
'query',
key,
'/v',
value,
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if not stderr:
for line in stdout.split('\n'):
line = line.strip()
if line.startswith(value) and line.find('REG_SZ') != -1:
return line[line.find('REG_SZ') + len('REG_SZ'):].strip()
return None
def import_vs_environment():
"""Finds the installed Visual Studio version and imports
interesting environment variables into os.environ.
Returns:
A version such as 2017 or None if no VS is found.
"""
# Pull the current paths, if specified. We'll use this to override our
# detection.
if 'BAZEL_VS' in os.environ and not 'BAZEL_VC' in os.environ:
os.environ['BAZEL_VC'] = os.environ['BAZEL_VS'] + "\\VC\\"
bazel_vc = os.environ.get('BAZEL_VC', '')
if not bazel_vc:
# Query first for VC++ tools, as we want to support non-VS installs. If it's
# not found we'll fall back to the VS directory.
vc7_dir = query_reg_sz(
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\SxS\\VC7',
'15.0')
vs7_dir = query_reg_sz(
'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\SxS\\VS7',
'15.0')
if vc7_dir and os.path.exists(vc7_dir):
bazel_vc = vc7_dir
elif vs7_dir and os.path.exists(vs7_dir):
bazel_vc = os.path.join(vs7_dir, 'VC')
os.environ['BAZEL_VC'] = bazel_vc
if not bazel_vc:
# Couldn't find any kind of VC++/VS install.
return None
vcvarsall_path = os.path.join(bazel_vc, 'Auxiliary\\Build\\vcvarsall.bat')
if not os.path.exists(vcvarsall_path):
print('ERROR: BAZEL_VC set to %s but no vcvarsall.bat found' % (bazel_vc))
return None
if sys.platform == 'cygwin':
args = ['tools\\/utils\\/echo_vcvarsall.bat']
envvars_to_save = (
'devenvdir',
'include',
'lib',
'libpath',
'pathext',
'systemroot',
'vcinstalldir',
'windowssdkdir',
)
else:
args = [vcvarsall_path, 'x64', '&&', 'set']
envvars_to_save = (
'devenvdir',
'include',
'lib',
'libpath',
'path',
'pathext',
'systemroot',
'temp',
'tmp',
'vcinstalldir',
'visualstudioversion',
'windowssdkdir',
)
popen = subprocess.Popen(
args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
variables, _ = popen.communicate()
for line in variables.splitlines():
for envvar in envvars_to_save:
if re.match(envvar + '=', line.lower()):
var, setting = line.split('=', 1)
if envvar == 'path':
setting = os.path.dirname(sys.executable) + os.pathsep + setting
os.environ[var.upper()] = setting
break
version = 0
if os.environ.get('VISUALSTUDIOVERSION', '') == '15.0':
version = 2017
os.environ['VSVERSION'] = str(version)
return version
def format_uuid(uuid):
"""Formats a dense hex UUID string into a dashed format.
Args:
uuid: input UUID as 'E90AFB8EA87B3B38903DC0A5B0928FDF'.
Returns:
UUID with dashes as 'E90AFB8E-A87B-3B38-903D-C0A5B0928FDF'.
"""
return '%s-%s-%s-%s-%s' % (uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20],
uuid[20:32])
def convert_path_cygwin_to_win32(cygwin_path):
"""Converts a /cygdrive/c/foo path to a C:\\foo path.
No-op on non-cygwin platforms.
Args:
cygwin_path: file path in cygwin format.
Returns:
File path in win32 format.
"""
# On Windows we want a Windows path (C:\foo). Convert here if
# we are under cygwin.
if sys.platform == 'cygwin' and cygwin_path.startswith('/'):
windows_path = cygwin_path.replace('/cygdrive/', '')
drive_name = '%s:\\\\' % (windows_path[0:1])
windows_path = windows_path[2:].replace('/', '\\\\')
windows_path = '%s%s' % (drive_name, windows_path)
elif sys.platform == 'cygwin' or sys.platform == 'win32':
windows_path = cygwin_path.replace('/', '\\')
else:
windows_path = cygwin_path
return windows_path
def has_bin(bin):
"""Checks whether the given binary is present.
Args:
bin: binary name (without .exe, etc).
Returns:
True if the binary exists.
"""
bin_path = get_bin(bin)
if not bin_path:
return False
return True
def get_bin(bin):
"""Checks whether the given binary is present and returns the path.
Args:
bin: binary name (without .exe, etc).
Returns:
Full path to the binary or None if not found.
"""
for path in os.environ['PATH'].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, bin)
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
exe_file = exe_file + '.exe'
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return None
def shell_call(command, throw_on_error=True, stdout_path=None):
"""Executes a shell command.
Args:
command: Command to execute, as a list of parameters.
throw_on_error: Whether to throw an error or return the status code.
stdout_path: File path to write stdout output to.
Returns:
If throw_on_error is False the status code of the call will be returned.
"""
stdout_file = None
if stdout_path:
stdout_file = open(stdout_path, 'w')
result = 0
try:
if throw_on_error:
result = 1
subprocess.check_call(command, shell=False, stdout=stdout_file)
result = 0
else:
result = subprocess.call(command, shell=False, stdout=stdout_file)
finally:
if stdout_file:
stdout_file.close()
return result
def _prepare_bazel_environ():
"""Ensures bazel environment variables are set.
This is not required but ensures the tools used by bazel match the ones we
select and also quiets bazel warnings about them being autoconfigured.
"""
if 'BAZEL_SH' not in os.environ:
os.environ['BAZEL_SH'] = get_bin('bash')
if 'BAZEL_PYTHON' not in os.environ:
os.environ['BAZEL_PYTHON'] = get_python_binary()
if 'BAZEL_VC' not in os.environ and 'VCINSTALLDIR' in os.environ:
os.environ['BAZEL_VC'] = os.environ['VCINSTALLDIR']
def invoke_bazel(command, args, output_base = None):
"""Invokes a bazel command.
Args:
command: the bazel command, such as 'build'.
args: a list of arguments to pass to bazel.
output_base: absolute path to dump bazel outputs.
Returns:
Exit value of bazel, 0 is success.
"""
_prepare_bazel_environ()
run_args = ['bazel']
run_args.append('--bazelrc=' + os.path.join(self_path, 'tools/bazel.rc'))
if output_base:
run_args.append('--output_base=%s' % (output_base))
run_args.append(command)
run_args.extend(args)
# When running under Visual Studio we need to launch bazel such that python
# allows exit while bazel is still running. This produces slightly worse
# output than just a normal call, so we prefer that unless we are in VS.
if '--tool_tag=vs' in args:
exit_code = 0
process = subprocess.Popen(run_args,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1)
linebuf = ''
while process.returncode is None:
for line in process.stdout.readline():
if not line.endswith('\n'):
linebuf += line
continue
complete_line = linebuf + line
linebuf = ''
sys.stdout.write(complete_line)
sys.stdout.flush()
process.poll()
(output, _) = process.communicate()
output = linebuf + output
for line in output.split('\n'):
sys.stdout.write(line)
sys.stdout.flush()
exit_code = process.returncode
else:
exit_code = subprocess.call(run_args, shell=False)
return exit_code
def bazel_info(key, config = default_config, output_base = None):
"""Gets a bazel info value.
Args:
key: bazel info key.
config: --config value (or platform default is unspecified).
output_base: absolute path to dump bazel outputs.
Returns:
Key value.
"""
# Memoize the lookup.
if not hasattr(bazel_info, 'cache'):
bazel_info.cache = {}
cache_key = '%s-%s' % (key, config)
if cache_key in bazel_info.cache:
return bazel_info.cache[cache_key]
_prepare_bazel_environ()
value = subprocess.check_output([
'bazel',
] + (['--output_base=%s' % (output_base),] if output_base else []) + [
'info',
'--config=%s' % (config),
key,
], cwd=self_path).decode('utf-8').rstrip()
# Add to cache.
bazel_info.cache[cache_key] = value
return value
def get_git_head_info():
"""Queries the current branch and commit checksum from git.
Returns:
(branch_name, commit, commit_short)
If the user is not on any branch the name will be 'detached'.
"""
p = subprocess.Popen([
'git',
'symbolic-ref',
'--short',
'-q',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
branch_name = stdout.strip() or 'detached'
p = subprocess.Popen([
'git',
'rev-parse',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
commit = stdout.strip() or 'unknown'
p = subprocess.Popen([
'git',
'rev-parse',
'--short',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
commit_short = stdout.strip() or 'unknown'
return (branch_name, commit, commit_short)
def git_submodule_update():
"""Runs a full recursive git submodule init and update.
"""
shell_call([
'git',
'submodule',
'update',
'--init',
'--recursive',
])
def get_python_binary():
"""Finds the python binary. Aborts if none is found.
Returns:
A path to the python binary. This may differ from sys.executable.
"""
python_exe = get_bin('python.exe')
if not python_exe:
python_exe = get_bin('python')
if not python_exe:
python_exe = sys.executable
python_exe = convert_path_cygwin_to_win32(python_exe)
return python_exe
def get_clang_format_binary():
"""Finds a clang-format binary. Aborts if none is found.
Returns:
A path to the clang-format executable.
"""
attempts = [
'C:\\Program Files\\LLVM\\bin\\clang-format.exe',
'C:\\Program Files (x86)\\LLVM\\bin\\clang-format.exe',
'clang-format-5.0',
'clang-format',
]
for binary in attempts:
if has_bin(binary):
return binary
print 'ERROR: clang-format is not on PATH'
print 'LLVM is available from http://llvm.org/releases/download.html'
print 'At least version 5.0 is required.'
sys.exit(1)
def get_git_clang_format_py():
"""Finds the git-clang-format python file. Aborts if none is found.
Returns:
A path to the git-clang-format executable.
"""
attempts = [
'C:\\Program Files\\LLVM\\bin\\git-clang-format',
'C:\\Program Files (x86)\\LLVM\\bin\\git-clang-format',
'git-clang-format-5.0',
'git-clang-format',
]
for py_path in attempts:
if has_bin(py_path):
return get_bin(py_path)
print 'ERROR: git-clang-format is not on PATH'
print 'LLVM is available from http://llvm.org/releases/download.html'
print 'At least version 5.0 is required.'
sys.exit(1)
def get_clang_tidy_binary():
"""Finds a clang-tidy binary.
Returns:
A path to the clang-tidy executable or empty string if not found.
"""
attempts = [
'C:\\Program Files\\LLVM\\bin\\clang-tidy.exe',
'C:\\Program Files (x86)\\LLVM\\bin\\clang-tidy.exe',
'clang-tidy-5.0',
'clang-tidy',
]
for binary in attempts:
if has_bin(binary):
return binary
print 'ERROR: clang-tidy is not on PATH'
print 'LLVM is available from http://llvm.org/releases/download.html'
print 'At least version 5.0 is required.'
sys.exit(1)
def write_if_changed(path, contents):
"""Writes file contents if they are different than what exists at the path.
This is useful for files that may be watched by other processes (such as
Visual Studio).
Args:
path: file path.
contents: file contents str.
"""
if os.path.exists(path):
# File exists - load contents and compare.
try:
with open(path, 'r') as file:
existing_contents = file.read()
if unicode(contents) == unicode(existing_contents):
# Contents are the same.
return
except: pass
with open(path, 'w') as file:
file.write(contents)
def discover_commands(subparsers):
"""Looks for all commands and returns a dictionary of them.
In the future commands could be discovered on disk.
Args:
subparsers: Argument subparsers parent used to add command parsers.
Returns:
A dictionary containing name-to-Command mappings.
"""
commands = {
'setup': SetupCommand(subparsers),
'pull': PullCommand(subparsers),
'clean': CleanCommand(subparsers),
'build': BuildCommand(subparsers),
'run': RunCommand(subparsers),
'test': TestCommand(subparsers),
'query': QueryCommand(subparsers),
'info': InfoCommand(subparsers),
'lint': LintCommand(subparsers),
'fix': FixCommand(subparsers),
'tidy': TidyCommand(subparsers),
'presubmit': PresubmitCommand(subparsers),
}
if sys.platform in ('cygwin', 'win32'):
commands['sln'] = GenerateSlnCommand(subparsers)
return commands
class Command(object):
"""Base type for commands.
"""
def __init__(self, subparsers, name, help_short=None, help_long=None,
*args, **kwargs):
"""Initializes a command.
Args:
subparsers: Argument subparsers parent used to add command parsers.
name: The name of the command exposed to the management script.
help_short: Help text printed alongside the command when queried.
help_long: Extended help text when viewing command help.
"""
self.name = name
self.help_short = help_short
self.help_long = help_long
if subparsers:
self.parser = subparsers.add_parser(name,
help=help_short,
description=help_long)
self.parser.set_defaults(command_handler=self)
else:
self.parser = None
def execute(self, args, pass_args, cwd):
"""Executes the command.
Args:
args: Arguments hash for the command.
pass_args: Arguments list to pass to child commands.
cwd: Current working directory.
Returns:
Return code of the command.
"""
return 1
class SetupCommand(Command):
"""'setup' command."""
def __init__(self, subparsers, *args, **kwargs):
super(SetupCommand, self).__init__(
subparsers,
name='setup',
help_short='Setup the build environment.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
print('Setting up the build environment...')
print('')
# Setup submodules.
print('- git submodule init / update...')
git_submodule_update()
print('')
# Install required python modules.
python_modules = []
try:
from google.protobuf import message
except:
python_modules.append('protobuf')
if python_modules:
return_code = 1
if has_bin('pip'):
print('- pip install %s' % (' '.join(python_modules)))
return_code = shell_call([
'pip',
'install',
'--user',
'--upgrade',
] + python_modules)
elif has_bin('easy_install'):
print('- easy_install %s' % (' '.join(python_modules)))
return_code = shell_call([
'easy_install',
] + python_modules)
if return_code:
print('ERROR: pip and easy_install not found or an error occurred!')
print('You\'ll need to install the following python modules:')
for python_module in python_modules:
print(' %s' % (python_module))
return return_code
print('')
# Install required go dependencies.
go_packages = [
'github.com/bazelbuild/buildtools/buildifier',
]
if go_packages:
if has_bin('go'):
print('- go get %s' % (' '.join(go_packages)))
return_code = shell_call([
'go',
'get',
] + go_packages)
else:
return_code = 1
if return_code:
print('ERROR: go not found or an error occurred!')
print('Ensure you have go installed and on your path.')
print('You\'ll need to install the following go packages:')
for go_package in go_packages:
print(' %s' % (go_package))
return 1
return 0
class PullCommand(Command):
"""'pull' command."""
def __init__(self, subparsers, *args, **kwargs):
super(PullCommand, self).__init__(
subparsers,
name='pull',
help_short='Pulls the repo and all dependencies and rebases changes.',
*args, **kwargs)
self.parser.add_argument('--merge', action='store_true',
help='Merges on master instead of rebasing.')
def execute(self, args, pass_args, cwd):
print('Pulling...')
print('')
print('- switching to master...')
shell_call([
'git',
'checkout',
'master',
])
print('')
print('- pulling self...')
if args['merge']:
shell_call([
'git',
'pull',
])
else:
shell_call([
'git',
'pull',
'--rebase',
])
print('')
print('- pulling dependencies...')
git_submodule_update()
print('')
# TODO(benvanik): run tulsi/sln/etc.
return 0
class BazelCommand(Command):
"""Base for commands that invoke bazel."""
def __init__(self, subparsers, *args, **kwargs):
super(BazelCommand, self).__init__(
subparsers,
*args, **kwargs)
self.parser.add_argument(
'--output_base',
help='Write bazel outputs to the given path.')
self.parser.add_argument(
'--all', action='store_true',
help='Performs the bazel action on all top-level packages.')
def execute(self, args, bazel_command, pass_args, cwd):
# Add --config set to default if none was specified.
has_config = False
for arg in pass_args:
if arg.startswith('--config='):
has_config = True
break
if not has_config:
pass_args = ['--config=%s' % (default_config)] + pass_args
if args['all']:
pass_args += top_level_packages
result = invoke_bazel(bazel_command, pass_args,
output_base = args['output_base'])
print('')
if result != 0:
print('ERROR: build failed with one or more errors.')
return result
return 0
class CleanCommand(BazelCommand):
"""'clean' command."""
def __init__(self, subparsers, *args, **kwargs):
super(CleanCommand, self).__init__(
subparsers,
name='clean',
help_short='Runs a bazel clean.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
# TODO(benvanik): build script.
result = super(CleanCommand, self).execute(args, 'clean', pass_args, cwd)
if not result:
print('Success!')
return result
class BuildCommand(BazelCommand):
"""'build' command."""
def __init__(self, subparsers, *args, **kwargs):
super(BuildCommand, self).__init__(
subparsers,
name='build',
help_short='Runs a bazel build.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
# TODO(benvanik): build script.
result = super(BuildCommand, self).execute(args, 'build', pass_args, cwd)
if not result:
print('Success!')
return result
class RunCommand(BazelCommand):
"""'run' command."""
def __init__(self, subparsers, *args, **kwargs):
super(RunCommand, self).__init__(
subparsers,
name='run',
help_short='Runs tests for several platforms at once.',
help_long='''
To pass arguments to the executables separate them with `--`.
$ xtool run //:target -- --some_test_arg
''',
*args, **kwargs)
# TODO(benvanik): configs for platforms to run tests on.
def execute(self, args, pass_args, cwd):
# TODO(benvanik): run script.
result = super(RunCommand, self).execute(args, 'run', pass_args, cwd)
if not result:
print('Success!')
return result
class TestCommand(BazelCommand):
"""'test' command."""
def __init__(self, subparsers, *args, **kwargs):
super(TestCommand, self).__init__(
subparsers,
name='test',
help_short='Runs a bazel test.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
# TODO(benvanik): test script.
result = super(TestCommand, self).execute(args, 'test', pass_args, cwd)
if not result:
print('Success!')
return result
class QueryCommand(BazelCommand):
"""'query' command."""
def __init__(self, subparsers, *args, **kwargs):
super(QueryCommand, self).__init__(
subparsers,
name='query',
help_short='Issues a bazel query.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
result = super(QueryCommand, self).execute(args, 'query', pass_args, cwd)
if not result:
print('Success!')
return result
class InfoCommand(BazelCommand):
"""'info' command."""
def __init__(self, subparsers, *args, **kwargs):
super(InfoCommand, self).__init__(
subparsers,
name='info',
help_short='Issues a bazel info.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
result = super(InfoCommand, self).execute(args, 'info', pass_args, cwd)
return result
def is_bazel_file(file_path):
"""
Args:
file_path: file path (like '.../foo.bzl').
Returns:
True if the file is considered a bazel BUILD/etc file.
"""
return file_path.endswith((
'BUILD',
'.bzl',
))
def is_source_file(file_path):
"""
Args:
file_path: file path (like '.../foo.cc').
Returns:
True if the file is considered a source file.
"""
return file_path.endswith((
'.cc',
'.c',
'.h',
'.inl',
'.mm',
'.m',
'.java',
'.py',
))
def find_xrtl_source_files(file_filter = is_source_file):
"""Gets all XRTL source files in the project.
Args:
file_filter: function that returns true if the file should be included.
Returns:
A list of file paths.
"""
all_files = [os.path.join(root, name)
for root, dirs, files in os.walk('xrtl')
for name in files
if file_filter(name)]
return [file_path.replace('\\', '/') for file_path in all_files]
def find_all_source_files(file_filter = is_source_file):
"""Gets all interesting source files in the project.
Args:
file_filter: function that returns true if the file should be included.
Returns:
A list of file paths.
"""
return find_xrtl_source_files(file_filter)
def find_changed_source_files(file_filter = is_source_file, diff_origin = False):
"""Gets all changed source files from the origin.
Args:
diff_origin: git diff against origin/master, not HEAD.
file_filter: function that returns true if the file should be included.
Returns:
A list of file paths.
"""
p = subprocess.Popen([
'git',
'diff',
'--name-only',
'%s' % ('origin/master' if diff_origin else 'HEAD')
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
changed_files = stdout.strip().split('\n')
changed_files = [file_path
for file_path in changed_files
if file_filter(file_path)]
return changed_files
def lint_check_files(check_all_files = False, diff_origin = False):
"""
Args:
check_all_files: True to run on all files, not just the git changes.
diff_origin: git diff against origin/master, not HEAD.