-
Notifications
You must be signed in to change notification settings - Fork 180
/
build
executable file
·1496 lines (1107 loc) · 44.7 KB
/
build
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 (c) 2008-2024 the MRtrix3 contributors.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Covered Software is provided under this License on an "as is"
# basis, without warranty of any kind, either expressed, implied, or
# statutory, including, without limitation, warranties that the
# Covered Software is free of defects, merchantable, fit for a
# particular purpose or non-infringing.
# See the Mozilla Public License v. 2.0 for more details.
#
# For more details, see http://www.mrtrix.org/.
# pylint: disable=redefined-outer-name,invalid-name
# note: deal with these warnings properly when we drop support for Python 2:
# pylint: disable=unspecified-encoding,consider-using-dict-items,unused-variable,consider-using-f-string
usage_string = '''
USAGE
./build [-verbose] [-showdep[=target|all]] [target ...]
DESCRIPTION
This script will compile and link the MRtrix3 source tree. It relies on the
configuration file produced by ./configure - please ensure you have run
this first.
In most cases, a simple invocation is all that is required:
$ ./build
If no targets are provided, the command will default to building all
applications by scanning through the cmd/ folder.
The target executables will be located in the bin/ folder, and the shared
library (if requested - the default) will be located in the lib/ folder (or
in bin/ on Windows). All intermediate temporary files will be located
within the tmp/ folder.
SPECIAL TARGETS
clean
used to remove all compiler-generated files, including objects,
executables, and shared libraries.
bash
used to update the bash completion script. Note that automatic updating
of this script can be enabled at the configure stage, by running
'./configure -dev' prior to invoking './build'.
doc
used to update the command documentation, so that any modifications to
the inline documentation in commands can be propagated through to the
user documentation site.
select name
used to switch between configs / builds. This stores the current config
and all compiler-generated files in a folder (called "build.oldname"),
and restores the config in "build.name". If the named config does not
already exist, an empty one is created. If "name" is not given the
currently active config name is reported.
PARALLELISED BUILD
By default, 'build' will use all available cores to run a parallel build.
In some instances, this can cause problems (notably out of RAM errors). You
can control how many jobs 'build' will run concurrently using the
NUMBER_OF_PROCESSORS environment variable. For example:
$ NUMBER_OF_PROCESSORS=1 ./build
OPTIONS
-verbose
print each command as it is being invoked
-nowarnings
do not print out non-fatal compiler messages (warnings, etc)
-dryrun
do not actually execute the compiler and linking commands (used for testing)
-showdep[=target|all]
print the list of dependencies for every target (with -showdep=target;
the default) or for all files
-tree
[only used with -showdep] print full dependency tree for each file
-persistent
keep trying to build regardless of failures, until none of the remaining
jobs succeed.
-timings
write compile times out to timings.log file.
-nopaginate
do not feed error log to the paginator, even if running in a TTY
'''
############################################################################
# COMMON DEFINITIONS #
############################################################################
import atexit, codecs, copy, glob, os, platform, re, shutil, subprocess, sys, tempfile, time, threading
from timeit import default_timer as timer
# on Windows, need to use MSYS2 version of python - not MinGW version:
if sys.executable[0].isalpha() and sys.executable[1] == ':':
python_cmd = subprocess.check_output ([ 'cygpath.exe', '-w', '/usr/bin/python' ]).decode(errors='ignore').splitlines()[0].strip()
sys.exit (subprocess.call ([ python_cmd ] + sys.argv))
bin_dir = 'bin'
cmd_dir = 'cmd'
lib_dir = 'core'
misc_dir = 'src'
script_dir = os.path.join('lib', 'mrtrix3')
tmp_dir = 'tmp'
cpp_suffix = '.cpp'
h_suffix = '.h'
libname = 'mrtrix'
include_paths = [ misc_dir ]
config_file = None
system = None
dependencies = 0
dep_recursive = False
verbose = False
dryrun = False
persistent = False
nowarnings = False
paginate = True
targets = []
todo, headers, object_deps, file_flags = {}, {}, {}, {}
formatstr=''
lock = threading.Lock()
print_lock = threading.Lock()
index_lock = threading.Lock()
stop = False
error_stream = None
todo_index = 0
logfile = open ('build.log', 'wb') #pylint: disable=consider-using-with
timingfile = None
bcolors = {
"candidate" : '\033[94m',
"no known conversion" : '\033[94m',
"expected" : '\033[93m',
"^" : '\033[91m',
"static assertion" : '\033[91m',
"Linking" : '\033[01;32m',
"In function" : '\033[01;32m',
"WARNING" : '\033[95m',
"Warning" : '\033[95m',
"warning" : '\033[95m',
"required from" : '\033[94m',
"In instantiation of" : '\033[01;32m',
"In member" : '\033[01;32m',
"ERROR" : '\033[01;95m',
"error" : '\033[01;31m',
"failed" : '\033[91m',
"note" : '\033[94m'}
def colorize(s):
out = ''
for l in s.splitlines():
for st in bcolors:
if st in l:
l = l.replace (st, bcolors[st] + st) + '\033[0m'
break
out += l + '\n'
return out
def pipe_errors_to_less_handler():
if error_stream:
with tempfile.NamedTemporaryFile() as tf:
tf.write (colorize(error_stream).encode (errors='ignore'))
tf.flush()
os.system ("less -RX " + tf.name)
def disp (msg):
with print_lock:
logfile.write (msg.encode (errors='ignore'))
sys.stdout.write (msg)
sys.stdout.flush()
def log (msg):
with print_lock:
logfile.write (msg.encode (errors='ignore'))
if verbose:
sys.stdout.write (msg)
sys.stdout.flush()
def logtime (msg):
with print_lock:
timingfile.write (msg.encode (errors='ignore'))
timingfile.flush()
def error (msg):
global error_stream
with print_lock:
logfile.write (msg.encode (errors='ignore'))
if error_stream is not None:
error_stream += msg
else:
sys.stdout.write (msg)
sys.stdout.flush()
def fail (msg):
with print_lock:
logfile.write (msg.encode (errors='ignore'))
sys.stdout.write (msg)
sys.stdout.flush()
sys.exit (1)
def split_path (path):
return path.replace ('\\', '/').split ('/')
def get_real_name (path):
if os.path.islink (path):
return os.readlink (path)
return path
def _get_expected_bin_filenames (exe_suffix, cmd_directory=cmd_dir):
binary_apps = { 'mrtrix3.pyc' }
if exe_suffix:
binary_apps.add('mrtrix.dll')
for entry in os.listdir(cmd_directory):
if entry.endswith(cpp_suffix):
binary_apps.add (entry[:-len(cpp_suffix)] + exe_suffix)
return binary_apps
def list_expected_bin_files (exe_suffix, cmd_directory=cmd_dir, bin_directory=bin_dir):
bin_files = []
binary_apps = _get_expected_bin_filenames(exe_suffix, cmd_directory=cmd_directory)
for app in sorted(binary_apps):
if os.path.isfile(os.path.join(bin_directory, app)):
bin_files.append(os.path.join(bin_directory, app))
return bin_files
def list_unexpected_bin_files (exe_suffix, cmd_directory=cmd_dir, bin_directory=bin_dir):
unexpected = []
if os.path.isdir(bin_directory):
binary_apps = _get_expected_bin_filenames(exe_suffix, cmd_directory=cmd_directory)
for filename in sorted(os.listdir(bin_directory)):
filepath = os.path.normpath(os.path.join(bin_directory, filename))
if os.path.isfile(filepath) and filename not in binary_apps and not is_likely_text(filepath):
unexpected.append(filepath)
return unexpected
def list_untracked_bin_files (directory = '.'):
process = subprocess.Popen ([ 'git', '-C', directory, 'ls-files', '-x', '.*', '-o', bin_dir ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) #pylint: disable=consider-using-with
filelist = process.communicate()[0]
if process.returncode == 0:
return filelist.decode(errors='ignore').splitlines()
return []
def is_likely_text(filename, nbytes=1024):
""" detects if file has a shebang or is utf-8 encoded, empty file is deemed non-text
:arg filename
:arg nbytes sample size to analyse
"""
chunk = b''
try:
with open(filename, 'rb') as f:
chunk = f.read(nbytes)
except IOError as e:
log('could not read file ' + filename + '\n' + str(e) + '\n')
if chunk:
if chunk.startswith(b'\x23\x21'): # starts with shebang '#!'
log('is_likely_text: ' + filename + ': starts with shebang \n')
return True
try:
chunk.decode('utf-8')
log('is_likely_text: ' + filename + ': utf-8 encoded \n')
return True
except UnicodeDecodeError:
pass
return False
def modify_path (name, tmp=False, strip=None, add=None):
if strip is not None:
name = name[:-len(strip)]
if add is not None:
name = name + add
for project_dir in mrtrix_dir:
relname = os.path.normpath (os.path.relpath (name, project_dir))
if relname.startswith ('.'):
continue
if tmp:
relname = os.path.join (tmp_dir, relname)
elif not os.path.relpath (relname, tmp_dir).startswith ('.'):
relname = os.sep.join (split_path (relname)[1:])
name = os.path.normpath (os.path.join (project_dir, relname))
return name
############################################################################
# COMMAND-LINE PARSING #
############################################################################
command_doc = False
bash_completion = False
for arg in sys.argv[1:]:
if '-help'.startswith(arg):
sys.stdout.write (usage_string)
sys.exit (0)
elif '-verbose'.startswith(arg):
verbose = True
elif '-dryrun'.startswith(arg):
dryrun = True
elif '-persistent'.startswith(arg):
persistent = True
elif '-nowarnings'.startswith(arg):
nowarnings = True
elif '-showdep'.startswith(arg):
dependencies = 1
elif arg.startswith ('-showdep='):
if arg[9:] == 'target':
dependencies = 1
elif arg[9:] == 'all':
dependencies = 2
else:
fail ('invalid specified for option "-showdep" (expected target, all)')
elif '-tree'.startswith(arg):
dep_recursive = True
elif '-timings'.startswith(arg):
timingfile = open ('timings.log', 'wb') #pylint: disable=consider-using-with
elif '-nopaginate'.startswith(arg):
paginate = False
elif arg[0] == '-':
fail ('unknown command-line option "' + arg + '"')
elif arg == 'bash':
bash_completion = True
elif arg == 'doc':
command_doc = True
elif arg == 'clean':
targets = [ 'clean' ]
else:
targets.append(arg)
if paginate and sys.stdout.isatty():
error_stream = ''
atexit.register (pipe_errors_to_less_handler)
############################################################################
# PROJECT DETECTION #
############################################################################
mrtrix_dir = [ '.' ]
build_script = sys.argv[0]
separate_project = False
while os.path.abspath (os.path.dirname (get_real_name (build_script))) != os.path.abspath (mrtrix_dir[-1]):
if not separate_project:
log ('compiling separate project against:' + os.linesep)
separate_project = True
build_script = os.path.normpath (os.path.join (mrtrix_dir[-1], get_real_name (build_script)))
project_dir = os.path.dirname (build_script)
mrtrix_dir += [ project_dir ]
include_paths += [ os.path.join (project_dir, misc_dir) ]
log (' ' + project_dir + os.linesep + os.linesep)
############################################################################
# CONFIG HANDLING #
############################################################################
class ConfigException (Exception):
pass
def get_active_build (directory):
active_configs = glob.glob (os.path.join (directory, 'build.*.active'))
if len (active_configs) > 1:
fail ('ERROR: more than one config is currently marked as active!')
if active_configs:
name = active_configs[0]
if not os.path.isdir (name):
raise ConfigException ('ERROR: active config (' + name + ') is not a directory')
if os.listdir (name):
raise ConfigException ('ERROR: active config directory (' + name + ') is not empty')
return name[:-len('.active')]
os.mkdir (os.path.join (directory, 'build.default.active'))
return os.path.join (directory, 'build.default')
def store_current_build (directory = '.'):
stored_config = get_active_build (directory)
os.rename (stored_config + '.active', stored_config)
disp ('in "' + directory + '": storing "' + stored_config + '"...\n')
for f in [ tmp_dir, 'config' ] + list_untracked_bin_files (directory) + glob.glob ('lib/libmrtrix*'):
if os.path.exists (os.path.join (directory, f)):
os.renames (os.path.join (directory, f), os.path.join (stored_config, f))
def restore_build (config_name, directory = '.'):
stored_path = os.path.join (directory, 'build.' + config_name)
active_path = stored_path + '.active'
if os.path.isdir (stored_path):
disp ('in "' + directory + '": restoring "' + stored_path + '"...\n')
os.rename (stored_path, active_path)
for root, dirs, files in os.walk(active_path, topdown=False):
for name in files:
os.renames (os.path.join (root, name), os.path.join (directory, os.path.relpath (root, active_path), name))
for name in dirs:
if os.path.isdir (os.path.join (root, name)):
os.rmdir (os.path.join(root, name))
else:
if os.path.exists (stored_path):
raise ConfigException ('ERROR config to be restored (' + stored_path + ') is not a directory')
disp ('in "' + directory + '": creating empty "' + stored_path + '"...\n')
if not os.path.isdir (active_path):
os.mkdir (active_path)
def activate_build (name, directories):
for directory in directories:
config = get_active_build (directory)
if os.path.realpath (config) == os.path.realpath (os.path.join (directory, 'build.' + name)):
continue
store_current_build (directory)
restore_build (name, directory)
if targets and targets[0] == 'select':
if len(targets) == 1:
active_config = os.path.basename (get_active_build ('.'))
disp ('current config is "' + active_config + '"\n')
for entry in mrtrix_dir[1:]:
other_config = os.path.basename (get_active_build (entry))
if active_config != other_config:
disp ('WARNING: directory "' + entry + '" contains config "' + other_config + '"\n')
sys.exit (0)
if len(targets) != 2:
fail ('ERROR: select target expects a single configuration name\n')
activate_build (targets[1], mrtrix_dir)
sys.exit (0)
active_config = os.path.basename (get_active_build ('.'))[6:]
log ('active config is ' + active_config + '\n\n')
active_config_core = os.path.basename (get_active_build (mrtrix_dir[-1]))[6:]
if active_config_core != active_config:
disp ('active config differs from core - switching to core active config\n')
activate_build (active_config_core, mrtrix_dir)
############################################################################
# LOAD CONFIGURATION FILE #
############################################################################
if config_file is None:
config_file = os.path.normpath (os.path.join (mrtrix_dir[-1], 'config'))
# prevent pylint from generating undefined variable / non-iterable / membership test warnings
PATH = obj_suffix = exe_suffix = lib_prefix = lib_suffix = None
runpath = ld_enabled = moc = rcc = nogui = None
cpp = cpp_flags = ld = ld_flags = ld_lib = ld_lib_flags = eigen_cflags = qt_cflags = qt_ldflags = [ ]
try:
log ('reading configuration from "' + config_file + '"...' + os.linesep)
with codecs.open (config_file, mode='r', encoding='utf-8') as f:
exec (f.read()) # pylint: disable=exec-used
except IOError:
fail ('''no configuration file found!
please run "./configure" prior to invoking this script
''')
# renamed internal string substitutions
if 'LDFLAGS' in ld or 'LDLIB_FLAGS' in ld_lib:
fail ('''configuration file is out of date!
please run "./configure" prior to invoking this script
''')
if separate_project:
cpp_flags += [ '-DMRTRIX_PROJECT' ]
environ = os.environ.copy()
environ.update ({ 'PATH': PATH })
target_bin_dir = os.path.join (mrtrix_dir[0], bin_dir)
purged_bin_dir = os.path.join (target_bin_dir, 'purged_files')
system = platform.system().lower()
if system.startswith('mingw') or system.startswith('msys'):
target_lib_dir = os.path.join (mrtrix_dir[-1], bin_dir)
else:
target_lib_dir = os.path.join (mrtrix_dir[-1], 'lib')
lib_dir = os.path.join (mrtrix_dir[-1], lib_dir)
if ld_enabled and runpath:
ld_flags += [ runpath+os.path.relpath (target_lib_dir,target_bin_dir) ]
############################################################################
# BUILD CLEAN #
############################################################################
if 'clean' in targets:
for f in [ tmp_dir, 'dev' ]:
if not os.path.isdir (f):
continue
for root, dirs, files in os.walk(f, topdown=False):
for entry in files:
filename = os.path.join(root, entry)
disp ('delete file: ' + filename + '\n')
try:
os.remove (filename)
except OSError as excp:
disp ('error deleting file "' + filename + '": ' + os.strerror (excp.errno))
for entry in dirs:
dirname = os.path.join(root, entry)
disp ('delete directory: ' + dirname + '\n')
try:
os.rmdir (dirname)
except OSError as excp:
disp ('error deleting folder "' + dirname + '": ' + os.strerror (excp.errno))
disp ('delete directory: ' + f + '\n')
try:
os.rmdir (f)
except OSError as excp:
disp ('error deleting folder "' + f + '": ' + os.strerror (excp.errno))
for filename in list_expected_bin_files(exe_suffix):
disp ('delete file: ' + filename + '\n')
try:
os.remove (filename)
except OSError as excp:
disp ('error deleting file "' + filename + '": ' + os.strerror (excp.errno))
for filepath in list_unexpected_bin_files(exe_suffix):
if not os.path.exists(purged_bin_dir):
os.makedirs(purged_bin_dir)
move_to = os.path.join(purged_bin_dir, os.path.split(filepath)[1])
while os.path.isfile(move_to):
move_to = move_to + '_'
disp ('WARNING: moving unexpected file ' + filepath + ' to ' + move_to + '\n')
try:
shutil.move(filepath, move_to)
except OSError as excp:
disp ('error moving file "' + filepath + '": ' + os.strerror (excp.errno))
for filename in glob.glob (os.path.join ('lib', 'libmrtrix*')):
if os.path.isfile (filename):
disp ('delete file: ' + filename + '\n')
try:
os.remove (filename)
except OSError as excp:
disp ('error deleting file "' + filename + '": ' + os.strerror (excp.errno))
sys.exit (0)
############################################################################
# GET VERSION INFORMATION #
############################################################################
if ld_enabled:
ld_flags.insert(0, '-l' + libname)
libname = lib_prefix + libname + lib_suffix
# other settings:
include_paths += [ lib_dir, cmd_dir ]
cpp_flags += [ '-I' + entry for entry in include_paths ]
ld_flags += [ '-L' + target_lib_dir ]
moc_cpp_suffix = '_moc' + cpp_suffix
moc_obj_suffix = '_moc' + obj_suffix
# remove any files that might have been left over from older installations in
# different locations:
if os.path.isdir ('release'):
disp ('WARNING: removing \'release/\' folder - most likely left over from a previous installation\n')
shutil.rmtree ('release')
for entry in glob.glob (os.path.normpath (os.path.join (target_lib_dir, '*' + lib_suffix))):
if os.path.basename (entry) != libname:
disp ('WARNING: removing "' + entry + '" - most likely left over from a previous installation\n')
os.remove (entry)
# move unexpected binary files out of the target bin directory:
for filepath in list_unexpected_bin_files(exe_suffix):
if not os.path.exists(purged_bin_dir):
os.makedirs(purged_bin_dir)
move_to = os.path.join(purged_bin_dir, os.path.split(filepath)[1])
while os.path.isfile(move_to):
move_to = move_to + '_'
disp ('WARNING: moving unexpected binary file ' + filepath + ' to ' + move_to + '\n')
try:
shutil.move(filepath, move_to)
except OSError as excp:
disp ('error moving file "' + filepath + '": ' + os.strerror (excp.errno))
###########################################################################
# TO-DO LIST ENTRY #
###########################################################################
class TargetException (Exception):
pass
def next_index ():
global todo_index
with index_lock:
todo_index+=1
return todo_index
class Entry(object):
def __init__ (self, name):
name = os.path.normpath (name)
if name in todo:
return
todo[name] = self
self.name = name
self.cmd = []
self.deps = set()
self.action = '--'
self.timestamp = mtime (self.name)
self.dep_timestamp = self.timestamp
self.currently_being_processed = False
if is_executable (self.name):
self.set_executable()
elif is_icon (self.name):
self.set_icon()
elif is_object (self.name):
self.set_object()
elif is_library (self.name):
self.set_library()
elif is_moc (self.name):
self.set_moc()
elif not os.path.exists (self.name):
raise TargetException ('unknown target "' + self.name + '"')
[ Entry(item) for item in self.deps ] # pylint: disable=expression-not-assigned
dep_timestamp = [ todo[item].timestamp for item in todo if item in self.deps and not is_library(item) ]
dep_timestamp += [ todo[item].dep_timestamp for item in todo if item in self.deps and not is_library(item) ]
if dep_timestamp:
self.dep_timestamp = max(dep_timestamp)
def execute (self):
folder = os.path.dirname (self.name)
try:
os.makedirs (folder)
except OSError as excp:
if not os.path.isdir (folder):
fail ('ERROR: can''t create target folder "' + folder + '": ' + os.strerror (excp.errno))
if self.action == 'RCC':
with codecs.open (self.cmd[1], mode='w', encoding='utf-8') as fd:
fd.write ('<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n')
for entry in self.deps:
entry = os.path.basename (entry)
if not entry.startswith ('config'):
fd.write ('<file>' + entry + '</file>\n')
fd.write ('</qresource>\n</RCC>\n')
if self.cmd:
return execute (formatstr.format (next_index(), self.action, self.name), self.cmd)
return None
def set_executable (self):
self.action = 'LB'
if exe_suffix and self.name.endswith(exe_suffix):
cc_file = self.name[:-len(exe_suffix)]
else:
cc_file = self.name
cc_file = modify_path (os.path.join (cmd_dir, os.sep.join (split_path(cc_file)[1:])), add=cpp_suffix)
self.deps = list_cmd_deps(cc_file)
if separate_project:
self.deps = self.deps.union ([ os.path.join (tmp_dir, misc_dir, 'project_version' + obj_suffix) ])
skip = False
flags = []
if 'Q' in file_flags[cc_file]:
flags += qt_ldflags
if not skip:
if not ld_enabled:
self.deps = self.deps.union (list_lib_deps())
self.cmd = fillin (ld, {
'LINKFLAGS': [ s.replace ('LIBNAME', os.path.basename (self.name)) for s in ld_flags ] + flags,
'OBJECTS': list(self.deps),
'EXECUTABLE': [ self.name ] })
try:
if ld_use_shell:
self.cmd = [ 'sh', '-c', ' '.join(self.cmd) ]
except NameError:
pass
if ld_enabled:
self.deps.add (os.path.normpath (os.path.join (target_lib_dir, libname)))
def set_object (self):
self.action = 'CC'
cc_file = self.name[:-len(obj_suffix)] + cpp_suffix
flags = copy.copy (eigen_cflags)
if is_moc (cc_file):
src_header = modify_path (cc_file, strip=moc_cpp_suffix, add=h_suffix)
list_headers (src_header)
file_flags[cc_file] = file_flags[src_header]
elif is_icon (cc_file):
src_header = modify_path (cc_file, strip=cpp_suffix, add=h_suffix)
list_headers (src_header)
file_flags[cc_file] = file_flags[src_header]
else:
cc_file = modify_path (cc_file, tmp=False)
self.deps = self.deps.union (list_headers (cc_file))
self.deps.add (config_file)
self.deps.add( cc_file )
skip = False
if 'Q' in file_flags[cc_file]:
flags += qt_cflags
if not skip:
self.cmd = fillin (cpp, {
'CFLAGS': cpp_flags + flags,
'OBJECT': [ self.name ],
'SRC': [ cc_file ] })
def set_moc (self):
self.action = 'MOC'
src_file = modify_path (self.name, strip=moc_cpp_suffix, add=h_suffix)
self.deps = set([ src_file ])
self.deps = self.deps.union (list_headers (src_file))
self.deps.add (config_file)
self.cmd = [ moc ]
self.cmd += [ src_file, '-o', self.name ]
def set_library (self):
if not ld_enabled:
fail ('ERROR: shared library generation is disabled in this configuration')
self.action = 'LD'
self.deps = list_lib_deps()
self.cmd = fillin (ld_lib, {
'LINKLIB_FLAGS': [ s.replace ('LIBNAME', os.path.basename (self.name)) for s in ld_lib_flags ],
'OBJECTS': self.deps,
'LIB': [ self.name ] })
try:
if ld_use_shell:
self.cmd = [ 'sh', '-c', ' '.join(self.cmd) ]
except NameError:
pass
def set_icon (self):
self.action = 'RCC'
with codecs.open (modify_path (self.name, strip=cpp_suffix, add=h_suffix), mode='r', encoding='utf-8') as fd:
for line in fd:
if line.startswith ('//RCC:'):
for entry in line[6:].strip().split():
self.deps = self.deps.union (glob.glob (os.path.normpath (os.path.join (mrtrix_dir[-1], 'icons', entry))))
self.deps.add (config_file)
qrc_file = os.path.normpath (os.path.join (mrtrix_dir[-1], 'icons', os.path.basename (os.path.dirname(self.name)) + '.qrc'))
self.cmd = [ rcc, qrc_file, '-o', self.name ]
def need_rebuild (self):
return self.timestamp == float("inf") or self.timestamp < self.dep_timestamp
def display (self, indent=''):
show_rebuild = lambda x: x+' [REBUILD]' if todo[x].need_rebuild() else x
msg = indent + '[' + self.action + '] ' + show_rebuild (self.name) + ':\n'
msg += indent + ' timestamp: ' + str(self.timestamp)
if self.deps:
msg += ', dep timestamp: ' + str(self.dep_timestamp) + ', diff: ' + str(self.timestamp-self.dep_timestamp)
msg += '\n'
if self.cmd:
msg += indent + ' command: ' + ' '.join(self.cmd) + '\n'
if self.deps:
msg += indent + ' deps: '
if dep_recursive:
disp (msg + '\n')
for x in self.deps:
todo[x].display (indent + ' ')
else:
disp (msg + (indent+'\n ').join([ show_rebuild(x) for x in self.deps ]) + '\n')
###########################################################################
# FUNCTION DEFINITIONS #
###########################################################################
def default_targets():
if not os.path.isdir (cmd_dir):
fail ('ERROR: no "cmd" folder - unable to determine default targets' + os.linesep)
for entry in os.listdir (cmd_dir):
if entry.endswith(cpp_suffix):
targets.append (os.path.normpath (os.path.join (target_bin_dir, entry[:-len(cpp_suffix)] + exe_suffix)))
return targets
def is_executable (target):
return os.path.normpath (split_path (target)[0]) == os.path.normpath (bin_dir) and not is_moc (target) and not is_library (target)
def is_library (target):
return target.endswith (lib_suffix) and split_path(target)[-1].startswith (lib_prefix)
def is_object (target):
return target.endswith (obj_suffix)
def is_moc (target):
return target.endswith (moc_cpp_suffix)
def is_icon (target):
return os.path.basename (target) == 'icons'+cpp_suffix
def mtime (target):
if not os.path.exists (target):
return float('inf')
return os.stat(target).st_mtime
def fillin (template, keyvalue):
cmd = []
for item in template:
if item in keyvalue:
cmd += keyvalue[item]
else:
cmd += [ item ]
return cmd
def execute (message, cmd, working_dir=None):
disp (message + os.linesep)
log (' '.join(cmd) + os.linesep)
if dryrun:
return 0
try:
start = timer()
process = subprocess.Popen (cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ, cwd=working_dir) #pylint: disable=consider-using-with
( stdout, stderr ) = process.communicate()
end = timer()
if timingfile is not None:
logtime ('[{:>8.3f}s] '.format(end-start) + message + os.linesep)
if process.returncode != 0:
error ('\nERROR: ' + message + '\n\n' + ' '.join(cmd) + '\n\nfailed with output\n\n' + stderr.decode (errors='ignore'))
return 1
errstr = None
if stdout or stderr:
errstr = '\n' + ' '.join(cmd) + ':\n\n'
if stdout:
errstr += stdout.decode (errors='ignore') + '\n\n'
if stderr:
errstr += stderr.decode (errors='ignore') + '\n\n'
if errstr and not nowarnings:
disp (errstr)
except OSError:
disp (cmd[0] + ': command not found')
return 1
return None
def print_deps (current_file, indent=''):
current_file = os.path.normpath (current_file)
msg = indent + current_file
if current_file in file_flags:
if file_flags[current_file]:
msg += ' [' + file_flags[current_file] + ']'
msg += os.linesep
disp (msg)
for entry in todo[current_file].deps:
print_deps (entry, indent + ' ')
def is_GUI_target (current_file):
if 'gui' in split_path (current_file):
return True
if current_file in file_flags:
if 'Q' in file_flags[current_file]:
return True
if todo[current_file].deps:
for entry in todo[current_file].deps:
if is_GUI_target (entry):
return True
return False