-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpymake
executable file
·1448 lines (1224 loc) · 60.6 KB
/
pymake
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
# pymake
# Copyright (C) 2001 Pascal Vincent
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. The name of the authors may not be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This file is part of the PLearn library. For more information on the PLearn
# library, go to the PLearn Web site at www.plearn.org
import os, sys, re, string, glob, socket, time, whrandom, select, shutil, fnmatch,math
from stat import *
from types import *
from popen2 import *
print "pymake 2.0 [ (C) 2001, Pascal Vincent. This is free software distributed under a BSD type license. Report problems to [email protected] ]"
# initialise a few variables from the environment
platform = sys.platform
if platform=='linux2':
linux_type = os.uname()[4]
if linux_type == 'ppc':
platform = 'linux-ppc'
elif linux_type =='x86_64':
platform = 'linux-x86_64'
else:
platform = 'linux-i386'
homedir = os.environ['HOME']
if platform=='win32':
homedir = 'R:/'
myhostname = socket.gethostname()
pos = string.find(myhostname,'.')
if pos>=0:
myhostname = myhostname[0:pos]
# QT specific stuff. If this is true, then qt's include dir and library are added for compilation and linkage
useqt = 0
qtdir=''
# get the option arguments
args = sys.argv[:]
del args[0] # ignore program name
# initialize a few variables to their default values...
# these may be overridden by the config file
default_compiler = 'g++'
default_linker = 'g++'
sourcedirs = []
mandatory_includedirs = []
linkeroptions_tail = '-lstdc++ -lm'
options_choices = []
nprocesses_per_processor = 1
rshcommand = 'rsh '
compileflags = ''
#objspolicy=1 -> for dir/truc.cc object file in dir/platform_opt/truc.o (objects file are in a directory corresponding to the cc file directory)
#objspolicy=2 -> for dir/truc.cc object file in objsdir/platform_opt/truc.o (all objects file are in the same directory)
objspolicy=1
objsdir=''
# some variables used when creating a dll...
default_wrapper = 'dllwrap'
dllwrap_basic_options = '--driver-name=c++ --add-stdcall-alias'
# nice default command and value
nice_command = 'env nice -n'
nice_value = '10'
verbose=3
# a few useful functions
def convertWinToLinux(path):
"""in windows, replace all directory separator \\ by / (for use in MinGW)"""
if platform=='win32':
return string.replace(path,"\\","/")
else:
return path
def join(dir,file,file2="",file3=""):
"""simply call os.path.join and convertWinToLinux"""
if file2=='':
res = convertWinToLinux(os.path.join(dir, file))
elif file3=='':
res = convertWinToLinux(os.path.join(dir, file, file2))
else:
res = convertWinToLinux(os.path.join(dir, file, file2, file3))
return res
def abspath(mypath):
"""returns the absolute path of the file, with a hack to remove the leading /export/ that causes problems at DIRO"""
p = convertWinToLinux(os.path.abspath(mypath)) # python 5.1 does not have abspath
rmprefix = '/export/'
lenprefix = len(rmprefix)
if len(p)>lenprefix:
if p[0:lenprefix]==rmprefix :
p = '/'+p[lenprefix:]
return p
def lsdirs(basedir):
"""returns the recursive list of all subdirectories of the given directory,
excluding OBJS and CVS directories and those whose name starts with a dot.
The first element of the returned list is the basedir"""
if not os.path.isdir(basedir):
return []
dirs = [ basedir ]
for dname in os.listdir(basedir):
if dname!='CVS' and dname!='.svn' and dname!='OBJS' and dname[0]!='.':
dname = join(basedir,dname)
if os.path.isdir(dname):
dirs.append(dname)
dirs.extend(lsdirs(dname))
return dirs
def appendunique(l, l2):
"""appends the elements of list l2 to list l, but only those that are not already in l"""
for e in l2:
if e not in l:
l.append(e)
def unique(l):
"""returns the elements of l but without duplicates"""
lfilt = []
for e in l:
if e not in lfilt:
lfilt.append(e)
return lfilt
# This is used for buffering mtime calls
mtime_map = {}
def forget_mtime(filepath):
del mtime_map[filepath]
def mtime(filepath):
"a buffered os.path.getmtime"
"returns 0 if the file does not exist"
if not mtime_map.has_key(filepath):
if os.path.exists(filepath):
mtime_map[filepath] = os.path.getmtime(filepath)
else:
mtime_map[filepath] = 0
return mtime_map[filepath]
# preparing to read config file
pymake_options_defs = {}
class PymakeOption:
def __init__(self, name, description, compiler, compileroptions, linker, linkeroptions):
self.name = name
self.description = description
self.compiler = compiler
self.compileroptions = compileroptions
self.linker = linker
self.linkeroptions = linkeroptions
# adds a posible option to the pymake_options_defs
def pymakeOption( name, description, compiler='', compileroptions='', linker='', linkeroptions='' ):
pymake_options_defs[name] = PymakeOption(name, description, compiler, compileroptions, linker, linkeroptions)
optional_libraries_defs = []
class OptionalLibrary:
def __init__(self, name, includedirs, triggers, linkeroptions, compileroptions ):
self.name = name
self.includedirs = includedirs
self.triggers = triggers
self.linkeroptions = linkeroptions
self.compileroptions = compileroptions
def is_triggered_by(self, include):
"""returns true if this particular include command is supposed to trigger this library"""
for trigger in self.triggers:
if fnmatch.fnmatch(include,trigger):
# print 'OPTIONAL LIBRARY: ' + self.name + ' TRIGGERED BY TRIGGER ' + trigger
return 1
if include[0]!='/': # look for it in includedirs
for incldir in self.includedirs:
if os.path.isfile(join(incldir,include)):
# print 'file exists!: ' + join(incldir,include)
# print 'INCLUDE ' + include + ' TRIGGERED BY INCDIR ' + incldir
return 1
return 0
# adds a library to the optional_libraries_defs
def optionalLibrary( name, linkeroptions, includedirs=[], triggers='', compileroptions='' ):
if type(includedirs) != ListType:
includedirs = [ includedirs ]
if type(triggers) != ListType:
triggers = [ triggers ]
optional_libraries_defs.append( OptionalLibrary(name, includedirs, triggers, linkeroptions, compileroptions) )
default_config_text = r"""
# List of directories in which to look for .h includes and corresponding .cc files to compile and link with your program
# (no need to include the current directory, it is implicit)
#sourcedirs = []
# directories other than those in sourcedirs, that will be added as list of includes (-I...) to all compilations
#mandatory_includedirs = []
# Add available external libraries In the order in which the linkeroptions
# must appear on the linker command line (typically most basic libraries
# last) If you do not give any specific triggers, any included .h file
# found in the specified includedirs will trigger the library Triggers can
# be a list of includes that will trigger the use of the library, and they
# can have wildcards (such as ['GreatLibInc/*.h','Magick*.h'] for instance)
# optionalLibrary( name = 'lapack',
# triggers = 'Lapackincl/*.h',
# linkeroptions = '-llapack' )
# What linker options to put always after those from the optional libraries
#linkeroptions_tail = '-lstdc++ -lm'
# List of lists of mutually exclusive pymake options.
# First option that appears in each group is the default, and is assumed if you don't specify any option from that group
#options_choices = [
# [ 'g++', 'CC'],
# [ 'dbg', 'opt']
#]
# Description of options, and associated settings
# name and description are mandatory (description will appear in usage display of pymake)
# you can then specify any one or more of compiler, compileroptions, linker, linkeroptions
#pymakeOption( name = 'g++',
# description = 'use g++ compiler and linker',
# compiler = 'g++',
# compileroptions = '-pedantic-errors',
# linker = 'g++' )
#pymakeOption( name = 'CC',
# description = 'use CC compiler and linker',
# compiler = 'CC',
# linker = 'CC' )
#pymakeOption( name = 'dbg',
# description = 'debug mode (defines BOUNDCHECK)',
# compileroptions = '-Wall -g -DBOUNDCHECK' )
#pymakeOption( name = 'opt',
# description = 'optimized mode',
# compileroptions = '-Wall -O9 -funroll-loops -finline -fomit-frame-pointer -fstrength-reduce -ffast-math -fPIC' )
"""
def locateconfigfile(file,configdir,config_text=''):
# first look in the current directory then look in its parents
directory = convertWinToLinux(configdir)
while os.path.isdir(directory) and os.access(directory,os.W_OK) and directory!='/':
fpath = join(directory,'.pymake',file);
modelpath = join(directory,'pymake.'+file+'.model')
if os.path.isfile(modelpath) and mtime(modelpath)>mtime(fpath):
print '*****************************************************'
if os.path.isfile(fpath):
print '* FOUND A MORE RECENT MODEL FILE: ' + modelpath + ' ***'
print '* SAVING PREVIOUS CONFIG FILE AS: ' + fpath+'.bak '
os.rename(fpath, fpath+'.bak')
print '* COPYING MODEL FILE ' + modelpath + ' TO ' + fpath
print '* PLEASE ADAPT THE CONFIGURATION TO YOUR NEEDS'
print '*****************************************************'
try: os.makedirs(join(directory,'.pymake'))
except: pass
shutil.copyfile(modelpath,fpath)
if os.path.isfile(fpath):
return fpath
directory = abspath(join(directory,'..'))
# nothing was found in current directory or its parents, let's look in the homedir
fpath = join(homedir,'.pymake',file)
if os.path.isfile(fpath):
return fpath
else:
if config_text:
print '*****************************************************'
print '* COULD NOT LOCATE ANY PYMAKE '+file+' CONFIGURATION FILE.'
print '* CREATING A DEFAULT CONFIG FILE IN ' + fpath
print '* PLEASE ADAPT THE CONFIGURATION TO YOUR NEEDS'
print '*****************************************************'
try: os.makedirs(join(homedir,'.pymake'))
except: pass
f = open(fpath,'w')
f.write(config_text)
f.close()
return fpath
return ''
def printusage():
print 'Usage: pymake [options] <list of targets, files or directories>'
print 'Where targets are .cc file names or base names or directories'
print 'And options are a combination of the following: '
for choice in options_choices:
print ' * One of ' + string.join(map(lambda s: '-'+s, choice),', ') + ' (default is -' + choice[0] + ') where:'
for item in choice:
print ' -'+item + ': ' + pymake_options_defs[item].description
print
print 'Other possible options are:'
print " -graph: if this is given, targets won't be compiled or linked. Instead their"
print " dependency graph will be generated in targetname.dot and targetname.ps files."
print ' -force: forces recompilation of all necessary files, even if they are up to date.'
print ' -local: don\'t use parallel compilation, even if there is a .pymake/<platform>.hosts file.'
print ' -clean: removes all OBJS subrdirectories recursively in all given directories'
print ' -checkobj: will report all source files that don\'t have *any* correponding .o in OBJS.'
print ' This processes recursively from given directories and is typically called'
print ' after a pymake -clean, and a pymake . to get the list of files that failed to compile.'
print ' -so: create a shared object (.so) instead of an executable file.'
print ' -dll: create a dll instead of an executable file.'
print ' It probably works ONLY on Windows with MinGW installed.'
print
print """The configuration file 'config' for pymake is searched for
first in the .pymake subdirectory of the current directory, then similarly
in the .pymake subdirectory of parent directories of the current directory,
and as last resort in the .pymake subdirectory of your homedir. Also, if
there is a pymake.config.model in the directory from which a .pymake/config
is searched, and the pymake.config.model is more recent than the
.pymake/config (or the .pymake/config does not exist) then that 'model'
will be copied to the .pymake/config file.
In adition to the 'config' file, your .pymake directories can contain files
that list machines (one per line) for launching parallel
compilations. Those files are to be called <platform>.hosts, where
<platform> indicates the architecture and system of the machines it
lists. A good place for this file is in the .pymake of your home directory,
as these are likely to be comon to all projects.
Note that you can easily override the compileroptions (defined in your
config file) for a particular <target>.cc file. Just create a
.<target>.override_compile_options file (along your <target>.cc file) in
which you put a python dictionary defining what options to override and
how.
Ex: If a non time-critical file takes too long to compile in optimized mode
(or bugs), you can override its optimized flags by writing the following in
a corresponding .<target>.override_compile_options file:
{ 'opt': '-Wall -g',
'opt_boundcheck': '-Wall -g -DBOUNDCHECK' }
"""
if len(args)==0:
printusage()
sys.exit()
#######################################################
# special calling options, that don't actually compile anything
#######################################################
def rmOBJS(arg, dirpath, names):
if os.path.basename(dirpath) == 'OBJS':
print 'Removing', dirpath
shutil.rmtree(dirpath)
def reportMissingObj(arg, dirpath, names):
if 'OBJS' in names: names.remove('OBJS')
if 'CVS' in names: names.remove('CVS')
for fname in names:
fpath = join(dirpath,fname)
if os.path.isfile(fpath):
basename, ext = os.path.splitext(fname)
if ext in ['.cc','.c','.C','.cpp','.CC']:
foundobj = 0 # found the .o file?
for f in glob.glob(join(dirpath,'OBJS','*',basename+'.o')):
if os.path.isfile(f): foundobj = 1
if not foundobj:
print fpath
######## Regular pymake processing
optionargs = [] # will contain all the -... options, with the leading '-' removed
otherargs = [] # will contain all other arguments to pymake (should be file or directory names)
#JF
#for arg in args:
# if arg[0]=='-':
# optionargs.append(arg[1:])
# else:
# otherargs.append(arg)
i=0
linkname = ''
while i < len(args):
if args[i] == '-o':
linkname = args[i+1]
i = i + 1
elif args[i][0]=='-':
optionargs.append(args[i][1:])
else:
otherargs.append(args[i])
i = i + 1
#/JF
print '*** Current platform is: ' + platform
print
if 'link' in optionargs:
force_link = 1;
optionargs.remove('link')
else:
force_link = 0;
if 'clean' in optionargs:
if len(optionargs)!=1 or len(otherargs)==0:
print 'BAD ARGUMENTS: with -clean, specify one or more directories to clean, but no other -option'
else:
print '>> Removing the following OBJS directories: '
for dirname in otherargs:
os.path.walk(dirname,rmOBJS,'')
sys.exit()
if 'checkobj' in optionargs: # report .cc files without any corresponding .o file in OBJS
if len(optionargs)!=1 or len(otherargs)==0:
print 'BAD ARGUMENTS: with -checkobj, specify one or more directories to check, but no other -option'
else:
print '>> The following files do not have *any* corresponding .o in OBJS:'
for dirname in otherargs:
os.path.walk(abspath(dirname),reportMissingObj, '')
sys.exit()
force_recompilation = 0 # force recompilation of everything?
if 'force' in optionargs:
force_recompilation = 1
optionargs.remove('force')
SPC = 0
if 'spc' in optionargs :
SPC = 1
plearndir = os.environ.get('PLEARNDIR')
if not plearndir:
print 'Error: First set the PLEARNDIR environnement variable in order to get the pyfreemachines script'
sys.exit();
else:
try: os.makedirs(join(homedir,'.pymake'))
except: pass
print '*** Running pymake using Smart Parallel Compilation'
cmd=plearndir+'/scripts/pyfreemachines '+join(homedir,'.pymake','SPC.hosts');
# print cmd
os.system(cmd)
optionargs.remove('spc')
local_compilation = 0 # do we want to do everything locally?
if platform=='win32':
local_compilation = 1 # in windows, we ALWAYS work locally
if 'local' in optionargs:
local_compilation = 1
optionargs.remove('local')
create_so = 0 # do we want to create a .so instead of an executable file
if 'so' in optionargs:
create_so = 1
optionargs.remove('so')
create_dll = 0 # do we want to create a dll instead of an executable file
if 'dll' in optionargs:
create_dll = 1
optionargs.remove('dll')
if create_so and create_dll:
print 'Error: cannot create a DLL and a Shared Object at the same time. Remove "-dll" or "-so" option.'
sys.exit()
#if options_choices[0][0] == 'icc'
if 'icc' in optionargs:
usingIntelCompiler = 1
#optionargs.remove('icc')
else:
usingIntelCompiler = 0
temp_objs=0
if 'tmp' in optionargs:
objspolicy = 2
temp_objs=1
local_compilation = 1
objsdir = '/tmp/OBJS'
optionargs.remove('tmp')
else:
temp_objs = 0
# fill the list of options from the optionargs, adding necessary default options (if no option of a group choice was specified)
def getOptions(options_choices,optionargs):
options = []
for choice in options_choices:
nmatches = 0
for item in choice:
if item in optionargs:
optionargs.remove(item)
if nmatches<1:
options.append(item)
else:
print 'PROBLEM: options ' + item + ' and ' + options[-1] + ' are mutually exclusive. Ignoring ' + item
nmatches = nmatches+1
if nmatches<1:
options.append(choice[0])
if optionargs: # there are remaining optionargs
print 'Invalid options: ' + string.join(map(lambda s: '-'+s, optionargs))
printusage()
sys.exit()
return options
list_of_hosts = []
if local_compilation:
list_of_hosts = ['localhost']
else:
if SPC:
hostspath = locateconfigfile('SPC.hosts',homedir,'localhost');
else:
hostspath = locateconfigfile(platform+'.hosts',os.getcwd(),'localhost')
if hostspath:
print '*** Parallel compilation using list of hosts from file: ' + hostspath
f = open(hostspath,'r')
list_of_hosts = filter(lambda s: s and s[0]!='#', map(string.strip,f.readlines()))
f.close()
else:
list_of_hosts = ['localhost']
print '*** No hosts file found: no parallel compilation, using localhost'
print ' (create a '+platform + '.hosts file in your .pymake directory to list hosts for parallel compilation.)'
# We could just do random.shuffle(list) but that's not in Python 1.5.2
def shuffle(list):
l = len(list)
for i in range(0,l-1):
j = whrandom.randint(i+1,l-1)
list[i], list[j] = list[j], list[i]
# randomize order of list_of_hosts
shuffle(list_of_hosts)
# replicate list nprocesses_per_processor times
list_of_hosts = nprocesses_per_processor * list_of_hosts
# rmccomment_regexp = re.compile(r'([^/])\/\*([^\*]|\*(?!\/))*\*\/',re.M)
rmcppcomment_regexp = re.compile(r'//[^\n]*\n',re.M)
def remove_c_comments(text):
result = ''
prevpos = 0
while 1:
pos = string.find(text,'/*',prevpos)
if pos<0:
result = result + text[prevpos:]
break
result = result + text[prevpos:pos]
prevpos = string.find(text,'*/',pos+2)
if prevpos<0:
result = result + text[pos:]
break
prevpos = prevpos + 2
return result;
def remove_comments(text):
text = rmcppcomment_regexp.sub('\n',text)
text = remove_c_comments(text)
return text
class FileInfo:
"""
This class is specifically designed to hold all useful information about .cc and .h files.
Contains the following fields:
- mtime: last modification time of this file
- filepath: full absolute path of file
- filedir: dirtectory part of filepath
- filebase: file basename part of filepath
- fileext: file extension
- is_ccfile: true if this file has a .cc or similar extension, false if it has a .h or similar extension
- includes_from_sourcedirs: list of FileInfo of the files that this one includes found in the sourcedirs
- triggered_libraries: list of OptionalLibrary objects triggered by this file's includes
QT specific:
- isqt : (for .cc files) true if this file is the brother .cc of a .h that 'hasqobject==true', or if for this .cc 'hasqobject==true'
- hasqobject : true if file contains a Q_OBJECT declaration (in which case we need to preprocess it with moc)
- mocfilename : the name of the associated moc file, if appropriate, that is, if hasqobject is true
- corresponding_moc_cc : the fileinfo of the .cc generated by moc'ing the file
.h files will also have the following fields:
- corresponding_ccfile: FileInfo of corresponding .cc file if any, 0 otherwise
.cc files will also have the following fields
- corresponding_ofile: full path of corresponding .o file
- hasmain: true if the sourcefile has a main function
If hasmain is true, then the following field will also be set:
- corresponding_output: full path of corresponding executable (in the same directory as the obj)
If create_dll is true, then the following fields will be set:
- corresponding_output: full path of corresponding dll file (in the same directory as the source file)
- corresponding_def_file: full path of corresponding def file (in the same directory as the source file)
If create_so is true, then the following field will be set:
- corresponding_output: full path of corresponding .so file (in the same directory as the source obj)
These attributes should not be accessed directly, but through their get method
- depmtime (optionally built by a call to get_depmtime())
- ccfiles_to_link list containing the FileInfos of all .cc files whose .o must be linked to produce the executable
When launching a compilation, the following are also set:
- hostname: name of host on which the compilation has been launched
- launched: a Popen3 object for the launched process
- errormsgs: a list of error messages taken from the launched process' stdout
- warningmsgs: a list of warning messages taken from the launched process' stderr
"""
# static patterns useful for parsing the file
include_regexp = re.compile(r'^\s*#include\s*(?:"|<)([^\s\"\>]+)(?:"|>)',re.M)
qobject_regexp = re.compile(r'\bQ\_OBJECT\b',re.M)
#hasmain_regexp = re.compile(r'\b(main|mpi_master_main)\s*\(',re.M)
hasmain_regexp = re.compile(r'\b(main|IMPLEMENT_APP)\s*\(',re.M)
def __init__(self,filepath):
if not os.path.exists(filepath):
raise "Couldn't find file " + filepath
self.filepath = filepath
def parse_file(self):
""" Parses the file, and sets self.includes_from_sourcedirs, self.triggered_libraries and self.hasmain"""
#print "Parsing " + self.filepath
f = open(self.filepath,"r")
text = f.read()
f.close()
text = remove_comments(text)
self.includes_from_sourcedirs = []
self.triggered_libraries = []
for includefile in FileInfo.include_regexp.findall(text):
#print 'Considering include ' + includefile
for optlib in optional_libraries_defs:
if optlib.is_triggered_by(includefile) and not optlib in self.triggered_libraries:
self.triggered_libraries.append(optlib)
# print optlib.name + ' TRIGGERED BY INCLUDE ' + includefile + ' IN ' + self.filepath
fullpath = join(self.filedir, includefile)
if os.path.isfile(fullpath):
self.includes_from_sourcedirs.append(abspath(fullpath))
else:
for srcdir in mandatory_includedirs:
fullpath = join(srcdir, includefile)
if os.path.isfile(fullpath):
self.includes_from_sourcedirs.append(abspath(fullpath))
self.hasmain = FileInfo.hasmain_regexp.search(text)
if platform!='win32':
self.hasqobject = FileInfo.qobject_regexp.search(text)
else:
self.hasqobject = False
self.mocfilename = "moc_"+self.filebase+".cpp"
def mocFile(self):
"""QT specific : if moc_'filename'.cpp is older than 'filename'.h,
then moc 'filename'.h (generates) moc_'filename'.cpp"""
if qtdir == '':
print """\nError : The qtdir variable is unset but the file """+self.filepath+""" seems to use QT (a Q_OBJECT declaration was found). In your .pymake/config file, assign the qtdir variable to the path to Trolltech's QT installation. Example : qtdir = '/usr/lib/qt3/'"""
sys.exit()
if (os.path.isfile(self.mocfilename)) and self.get_depmtime() <= os.path.getmtime(self.mocfilename):
return 0
os.system(qtdir+"bin/moc "+self.filepath+" -o "+self.mocfilename)
def analyseFile(self):
global useqt
self.mtime = os.path.getmtime(self.filepath)
self.filedir, fname = os.path.split(self.filepath)
self.filebase, self.fileext = os.path.splitext(fname)
# Parse the file to get includes and check if there's a main()
self.parse_file()
# transform the list of includes from a list of file names to a list of correspondinf FileInfo
self.includes_from_sourcedirs = map(file_info,self.includes_from_sourcedirs)
if self.fileext in ['.h','.H','.hpp']:
self.is_ccfile = 0
# get the corresponding .cc file's FileInfo (if there is such a file)
self.corresponding_ccfile = 0
for newext in ['.cc','.c','.C','.cpp','.CC']:
ccpath = join(self.filedir, self.filebase + newext)
if mtime(ccpath):
self.corresponding_ccfile = file_info(ccpath)
break
elif self.fileext in ['.cc','.c','.C','.cpp','.CC']:
self.is_ccfile = 1
if objspolicy == 1:
self.corresponding_ofile = join(self.filedir, objsdir, self.filebase+'.o')
elif objspolicy == 2:
self.corresponding_ofile = join(objsdir, self.filebase+'.o')
#print self.corresponding_ofile
if self.hasmain:
self.corresponding_output = join(self.filedir, objsdir, self.filebase)
if create_dll:
self.corresponding_output = join(self.filedir, self.filebase+'.dll')
self.corresponding_def_file = join(self.filedir, self.filebase+'.def')
if create_so:
self.corresponding_output = join(self.filedir, objsdir, 'lib'+self.filebase+'.so')
elif self.fileext in ['.xpm']:
self.is_ccfile = 0
self.corresponding_ccfile = 0
else:
raise 'Attempting to build a FileInfo from a file that is not a .cc or .h or similar file : '+self.filedir+"/"+self.filebase+self.fileext
if self.hasqobject:
useqt = 1
self.mocFile()
self.corresponding_moc_cc = file_info(self.mocfilename)
def collect_ccfiles_to_link(self, ccfiles_to_link, visited_hfiles):
"""completes the ccfiles_to_link list by appending the FileInfo
for all .cc files related to this file through includes and .cc
files corresponding to .h files"""
if self.is_ccfile:
if self not in ccfiles_to_link:
ccfiles_to_link.append(self)
# print self.filebase,self.fileext
for include in self.includes_from_sourcedirs:
#print self.filebase
include.collect_ccfiles_to_link(ccfiles_to_link, visited_hfiles)
else: # it's a .h file
if self not in visited_hfiles:
visited_hfiles.append(self)
if self.corresponding_ccfile:
self.corresponding_ccfile.collect_ccfiles_to_link(ccfiles_to_link, visited_hfiles)
if self.hasqobject:
self.corresponding_moc_cc.collect_ccfiles_to_link(ccfiles_to_link, visited_hfiles)
for include in self.includes_from_sourcedirs:
include.collect_ccfiles_to_link(ccfiles_to_link, visited_hfiles)
def get_ccfiles_to_link(self):
"""returns the list of FileInfos of all .cc files that need to be linked together to produce the corresponding_output"""
if not hasattr(self,"ccfiles_to_link"):
#if not self.hasmain or not self.is_ccfile:
if (not self.hasmain and not create_dll and not create_so) or not self.is_ccfile:
raise "called get_ccfiles_to_link on a file that is not a .cc file or that does not contain a main()"
self.ccfiles_to_link = []
visited_hfiles = []
self.collect_ccfiles_to_link(self.ccfiles_to_link,visited_hfiles)
return self.ccfiles_to_link
def collect_optional_libraries(self, optlibs, visited_files):
# print 'collecting optional libraries for file', self.filebase+self.fileext
if self not in visited_files:
# print 'ENTERING'
visited_files.append(self)
if hasattr(self,'optional_libraries'):
# print 'hasattr: ', map(lambda(x): x.name, self.optional_libraries)
appendunique(optlibs, self.optional_libraries)
else:
# print 'appending triggered libraries'
appendunique(optlibs, self.triggered_libraries)
for include in self.includes_from_sourcedirs:
# print 'lookin up include', include.filebase+include.fileext
include.collect_optional_libraries(optlibs, visited_files)
def get_optional_libraries(self):
"""returns the list of all OptionalLibrary that this file triggers directly or indirectly"""
if not hasattr(self,'optional_libraries'):
optlibs = []
self.collect_optional_libraries(optlibs, [])
self.optional_libraries = optlibs
return self.optional_libraries
def get_all_optional_libraries_to_link(self):
"""returns the list of all optional libraries to link with this .cc"""
# reorder self.optional_libraries in the order in which they appear in optional_libraries_defs
# self.optional_libraries = [ x for x in optional_libraries_defs if x in self.optional_libraries ]
# old-fashioned python that will work on troll (xsm):
optlibs = []
for ccfile in self.get_ccfiles_to_link():
appendunique(optlibs, ccfile.get_optional_libraries())
sol= []
for x in optional_libraries_defs:
if x in optlibs:
sol = sol + [x]
return sol
# def get_optional_libraries(self):
# """returns the list of *all* OptionalLibrary that need to be linked with any program that uses this file, in the right order"""
# print "go(",self.filebase+self.fileext,")"
# if not hasattr(self,'optional_libraries'):
# self.optional_libraries = []
# appendunique(self.optional_libraries, self.triggered_libraries)
# if not self.is_ccfile and self.corresponding_ccfile:
# print self.filebase+self.fileext, " moving into corresponding .cc file"
# appendunique(self.optional_libraries, self.corresponding_ccfile.get_optional_libraries())
# print self.filebase+self.fileext, " moving into INCLUDES: ", map( lambda(x): x.filebase, self.includes_from_sourcedirs)
# for include in self.includes_from_sourcedirs:
# appendunique(self.optional_libraries, include.get_optional_libraries())
# # reorder self.optional_libraries in the order in which they appear in optional_libraries_defs
# # self.optional_libraries = [ x for x in optional_libraries_defs if x in self.optional_libraries ]
# # old-fashioned python that will work on troll (xsm):
# sol= []
# for x in optional_libraries_defs:
# if x in self.optional_libraries:
# sol = sol + [x]
# self.optional_libraries = sol
# print "optlib(",self.filebase+self.fileext, " = ", map(lambda(x): x.name, self.optional_libraries)
# return self.optional_libraries
def get_optional_libraries_compileroptions(self):
compopts = []
for optlib in self.get_optional_libraries():
compopts.append(optlib.compileroptions)
# print '+> ', optlib.name, optlib.compileroptions
return compopts
def get_optional_libraries_includedirs(self):
incldirs = []
for optlib in self.get_optional_libraries():
appendunique(incldirs, optlib.includedirs)
# print '+> ', optlib.name, optlib.includedirs
if useqt:
appendunique(incldirs, [ qtdir+"include/" ] )
return incldirs
def get_optional_libraries_linkeroptions(self):
linkeroptions = ''
for optlib in self.get_all_optional_libraries_to_link():
linkeroptions = linkeroptions + optlib.linkeroptions + ' '
if useqt:
if os.path.exists(qtdir + 'lib/libqt.so'):
linkeroptions = linkeroptions + '-L'+qtdir + 'lib/ -lqt'
else:
linkeroptions = linkeroptions + '-L'+qtdir + 'lib/ -lqt-mt'
return linkeroptions
# as of date 09/07/2004
# no need to -lXi -lXext -lX11 to compile PLearn
# removing following code to speed up linking
# if needed, this should go in an option in pymake.config.model
# Martin
# if platform=='win32':
# return linkeroptions
# else:
# return linkeroptions + ' -L/usr/X11R6/lib/ -lXi -lXext -lX11'
def get_depmtime(self):
"returns the single latest last modification time of"
"this file and all its .h dependencies through includes"
if not hasattr(self,"depmtime"):
# YB DEBUGGING
self.mtime = os.path.getmtime(self.filepath)
#
self.depmtime = self.mtime
for includefile in self.includes_from_sourcedirs:
depmtime = includefile.get_depmtime()
if depmtime>self.depmtime:
self.depmtime = depmtime
#print "time of ",includefile.filepath," = ",depmtime
return self.depmtime
def corresponding_ofile_is_up_to_date(self):
"""returns true if the corresponding .o file is up to date,
false if it needs recompiling."""
try:
if not os.path.exists(self.corresponding_ofile):
# print "path of ",self.corresponding_ofile," does not exist!"
return 0
else:
t1 = self.get_depmtime()
t2 = os.path.getmtime(self.corresponding_ofile)
#print "t1 = source of ",self.filepath," time = ",t1
#print "t2 = object ",self.corresponding_ofile," time = ",t2
return t1 <= t2
except OSError: # OSError: [Errno 116] Stale NFS file handle
print "OSError... (probably NFS latency); Will be retrying"
return 0
def corresponding_output_is_up_to_date(self):
"""returns true if the corresponding executable is up to date, false if it needs rebuilding"""
if not os.path.exists(self.corresponding_output):
return 0
else:
exec_mtime = os.path.getmtime(self.corresponding_output)
ccfilelist = self.get_ccfiles_to_link()
for ccfile in ccfilelist:
if not os.path.exists(ccfile.corresponding_ofile):
return 0
ofile_mtime = os.path.getmtime(ccfile.corresponding_ofile)
if ccfile.get_depmtime()>ofile_mtime or ofile_mtime>exec_mtime:
return 0
return 1
def nfs_wait_for_corresponding_ofile(self):
"""wait until nfs catches up...."""
while not self.corresponding_ofile_is_up_to_date():
time.sleep(0.1) #no active wait (was 'pass') -xsm
def nfs_wait_for_all_linkable_ofiles(self):
for ccfile in self.get_ccfiles_to_link():
ccfile.nfs_wait_for_corresponding_ofile()
def make_objs_dir(self):
""" makes the OBJS dir and subdirectory if they don't already exist,
to hold the corresponding_ofile and corresponding_output """
odir = join(self.filedir, objsdir)
if not os.path.isdir(odir): # make sure the OBJS dir exists, otherwise the command will fail
os.makedirs(odir)
def make_symbolic_link(self, linkname):
""" recreates the symbolic link in filedir pointing to the executable in subdirectory objsdir """
#If the second argument, which is the user defined path and name for the symbolic link,
#is specified then the symbolic link will have this path and name, and the object files will be
#placed in the OBJS subdirectory of the directory where the source file is.
if linkname == '':
symlinktarget = join(self.filedir,self.filebase)
else:
symlinktarget = linkname
if os.path.islink(symlinktarget) or os.path.exists(symlinktarget):
os.remove(symlinktarget)
if linkname == '':
os.symlink(join(objsdir,self.filebase),symlinktarget)
else:
os.symlink(join(self.filedir+"/"+objsdir,self.filebase),symlinktarget)
def compile_command(self):
"""returns the command line necessary to compile this .cc file"""
fname = join(self.filedir,'.'+self.filebase+'.override_compile_options')
options_override = {}
if os.path.isfile(fname):
f = open(fname,'r')
options_override = eval(f.read())
f.close()
compiler = default_compiler
compileroptions = ""
for opt in options:
optdef = pymake_options_defs[opt]
if options_override.has_key(opt):
compileroptions = compileroptions+ ' ' + options_override[opt]
else:
compileroptions = compileroptions + ' ' + optdef.compileroptions
if optdef.compiler:
compiler = optdef.compiler
optlib_compopt = self.get_optional_libraries_compileroptions();
# print optlib_compopt
if platform == 'win32' or nice_value == '0':
nice = ''
else:
nice = nice_command + nice_value + ' '
command = nice + compiler + ' ' + compileflags + ' ' + compileroptions + ' ' + string.join(optlib_compopt, ' ')
includedirs = [] + mandatory_includedirs + self.get_optional_libraries_includedirs()
if includedirs: