forked from skywind3000/emake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emake.py
3405 lines (3195 loc) · 93.6 KB
/
emake.py
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 python2
# -*- coding: utf-8 -*-
#======================================================================
#
# emake.py - emake version 3.6.9
#
# history of this file:
# 2009.08.20 skywind create this file
# 2009.11.14 skywind new install() method
# 2009.12.22 skywind implementation execute interface
# 2010.01.18 skywind new project info
# 2010.03.14 skywind fixed source lex bug
# 2010.11.03 skywind new 'import' to import config section
# 2010.11.04 skywind new 'export' to export .def, .lib for windll
# 2010.11.27 skywind fixed link sequence with -Xlink -( -)
# 2012.03.26 skywind multiprocess building system, speed up
# 2012.08.18 skywind new 'flnk' to project
# 2012.09.09 skywind new system condition config, optimized
# 2013.12.19 skywind new $(target) config
# 2014.02.09 skywind new build-event and environ
# 2014.04.15 skywind new 'arglink' and 'argcc' config
# 2015.09.03 skywind new replace in config.parameters()
# 2016.01.14 skywind new compile flags with different source file
# 2016.04.27 skywind exit non-zero when error occurs
# 2016.09.01 skywind new lib composite method
# 2016.09.02 skywind more environ variables rather than $(target)
# 2017.08.16 skywind new: cflag, cxxflag, sflag, mflag, mmflag
# 2017.12.20 skywind new: --abs=1 to tell gcc to print fullpath
#
#======================================================================
import sys, time, os
import ConfigParser
#----------------------------------------------------------------------
# preprocessor: C/C++/Java 预处理器
#----------------------------------------------------------------------
class preprocessor(object):
# 初始化预编译器
def __init__ (self):
self.reset()
# 生成正文映射,将所有字符串及注释用 "$"和 "`"代替,排除分析干扰
def preprocess (self, text):
content = text
spaces = (' ', '\n', '\t', '\r')
import cStringIO
srctext = cStringIO.StringIO()
srctext.write(text)
srctext.seek(0)
memo = 0
i = 0
length = len(content)
output = srctext.write
while i < length:
char = content[i]
word = content[i : i + 2]
if memo == 0: # 正文中
if word == '/*':
output('``')
i += 2
memo = 1
continue
if word == '//':
output('``')
i += 2
while (i < len(content)) and (content[i] != '\n'):
if content[i] in spaces:
output(content[i])
i = i + 1
continue
output('`')
i = i + 1
continue
if char == '\"':
output('\"')
i += 1
memo = 2
continue
if char == '\'':
output('\'')
i += 1
memo = 3
continue
output(char)
elif memo == 1: # 注释中
if word == '*/':
output('``')
i += 2
memo = 0
continue
if char in spaces:
output(content[i])
i += 1
continue
output('`')
elif memo == 2: # 字符串中
if word == '\\\"':
output('$$')
i += 2
continue
if word == '\\\\':
output('$$')
i += 2
continue
if char == '\"':
output('\"')
i += 1
memo = 0
continue
if char in spaces:
output(char)
i += 1
continue
output('$')
elif memo == 3: # 字符中
if word == '\\\'':
output('$$')
i += 2
continue
if word == '\\\\':
output('$$')
i += 2
continue
if char == '\'':
output('\'')
i += 1
memo = 0
continue
if char in spaces:
output(char)
i += 1
continue
output('$')
i += 1
srctext.truncate()
return srctext.getvalue()
# 查找单一文件的头文件引用情况
def search_reference(self, source, heads):
content = ''
del heads[:]
try:
fp = open(source, "r")
except:
return ''
content = '\n'.join([ line.strip('\r\n') for line in fp ])
fp.close()
srctext = self.preprocess(content)
length = len(srctext)
start = 0
endup =-1
number = 0
while (start >= 0) and (start < length):
start = endup + 1
endup = srctext.find('\n', start)
if (endup < 0):
endup = length
number = number + 1
offset1 = srctext.find('#', start, endup)
if offset1 < 0: continue
offset2 = srctext.find('include', offset1, endup)
if offset2 < 0: continue
offset3 = srctext.find('\"', offset2, endup)
if offset3 < 0: continue
offset4 = srctext.find('\"', offset3 + 1, endup)
if offset4 < 0: continue
check_range = [ i for i in xrange(start, offset1) ]
check_range += [ i for i in xrange(offset1 + 1, offset2) ]
check_range += [ i for i in xrange(offset2 + 7, offset3) ]
check = 1
for i in check_range:
if not (srctext[i] in (' ', '`')):
check = 0
break
if check != 1:
continue
name = content[offset3 + 1 : offset4]
heads.append([name, offset1, offset4, number])
return content
# 合并引用的所有头文件,并返回文件依赖,及找不到的头文件
def parse_source(self, filename, history_headers, lost_headers):
headers = []
filename = os.path.abspath(filename)
import cStringIO
outtext = cStringIO.StringIO()
if not os.path.exists(filename):
sys.stderr.write('can not open %s\n'%(filename))
return outtext.getvalue()
if filename in self._references:
content, headers = self._references[filename]
else:
content = self.search_reference(filename, headers)
self._references[filename] = content, headers
save_cwd = os.getcwd()
file_cwd = os.path.dirname(filename)
if file_cwd == '':
file_cwd = '.'
os.chdir(file_cwd)
available = []
for head in headers:
if os.path.exists(head[0]):
available.append(head)
headers = available
offset = 0
for head in headers:
name = os.path.abspath(os.path.normcase(head[0]))
if not (name in history_headers):
history_headers.append(name)
position = len(history_headers) - 1
text = self.parse_source(name, history_headers, lost_headers)
del history_headers[position]
history_headers.append(name)
outtext.write(content[offset:head[1]] + '\n')
outtext.write('/*:: <%s> ::*/\n'%(head[0]))
outtext.write(text + '\n/*:: </:%s> ::*/\n'%(head[0]))
offset = head[2] + 1
else:
outtext.write(content[offset:head[1]] + '\n')
outtext.write('/*:: skip including "%s" ::*/\n'%(head[0]))
offset = head[2] + 1
outtext.write(content[offset:])
os.chdir(save_cwd)
return outtext.getvalue()
# 过滤代码注释
def cleanup_memo (self, text):
content = text
outtext = ''
srctext = self.preprocess(content)
space = ( ' ', '\t', '`' )
start = 0
endup = -1
sized = len(srctext)
while (start >= 0) and (start < sized):
start = endup + 1
endup = srctext.find('\n', start)
if endup < 0:
endup = sized
empty = 1
memod = 0
for i in xrange(start, endup):
if not (srctext[i] in space):
empty = 0
if srctext[i] == '`':
memod = 1
if empty and memod:
continue
for i in xrange(start, endup):
if srctext[i] != '`':
outtext = outtext + content[i]
outtext = outtext + '\n'
return outtext
# 复位依赖关系
def reset (self):
self._references = {}
return 0
# 直接返回依赖
def dependence (self, filename, reset = False):
head = []
lost = []
if reset: self.reset()
text = self.parse_source(filename, head, lost)
return head, lost, text
# 查询 Java的信息,返回:(package, imports, classname)
def java_preprocess (self, text):
text = self.preprocess(text)
content = text.replace('\r', '')
p1 = content.find('{')
p2 = content.rfind('}')
if p1 >= 0:
if p2 < 0:
p2 = len(content)
content = content[:p1] + ';\n' + content[p2 + 1:]
content = self.cleanup_memo(content).rstrip() + '\n'
info = { 'package': None, 'import': [], 'class': None }
for line in content.split(';'):
line = line.replace('\n', ' ').strip()
data = [ n.strip() for n in line.split() ]
if len(data) < 2: continue
name = data[0]
if name == 'package':
info['package'] = ''.join(data[1:])
elif name == 'import':
info['import'] += [''.join(data[1:])]
elif 'class' in data or 'interface' in data:
if 'extends' in data:
p = data.index('extends')
data = data[:p]
if 'implements' in data:
p = data.index('implements')
data = data[:p]
info['class'] = data[-1]
return info['package'], info['import'], info['class']
# returns: (package, imports, classname, srcpath)
def java_parse (self, filename):
try:
text = open(filename).read()
except:
return None, None, None, None
package, imports, classname = self.java_preprocess(text)
if package is None:
path = os.path.dirname(filename)
return None, imports, classname, os.path.abspath(path)
path = os.path.abspath(os.path.dirname(filename))
if sys.platform[:3] == 'win':
path = path.replace('\\', '/')
names = package.split('.')
root = path
srcpath = None
if sys.platform[:3] == 'win':
root = root.lower()
names = [n.lower() for n in names]
while 1:
part = os.path.split(root)
name = names[-1]
names = names[:-1]
if name != part[1]:
break
if len(names) == 0:
srcpath = part[0]
break
if root == part[0]:
break
root = part[0]
return package, imports, classname, srcpath
#----------------------------------------------------------------------
# execute and capture
#----------------------------------------------------------------------
def execute(args, shell = False, capture = False):
import sys, os
parameters = []
if type(args) in (type(''), type(u'')):
import shlex
cmd = args
if sys.platform[:3] == 'win':
ucs = False
if type(cmd) == type(u''):
cmd = cmd.encode('utf-8')
ucs = True
args = shlex.split(cmd.replace('\\', '\x00'))
args = [ n.replace('\x00', '\\') for n in args ]
if ucs:
args = [ n.decode('utf-8') for n in args ]
else:
args = shlex.split(cmd)
for n in args:
if sys.platform[:3] != 'win':
replace = { ' ':'\\ ', '\\':'\\\\', '\"':'\\\"', '\t':'\\t', \
'\n':'\\n', '\r':'\\r' }
text = ''.join([ replace.get(ch, ch) for ch in n ])
parameters.append(text)
else:
if (' ' in n) or ('\t' in n) or ('"' in n):
parameters.append('"%s"'%(n.replace('"', ' ')))
else:
parameters.append(n)
cmd = ' '.join(parameters)
if sys.platform[:3] == 'win' and len(cmd) > 255:
shell = False
if shell and (not capture):
os.system(cmd)
return ''
elif (not shell) and (not capture):
import subprocess
if 'call' in subprocess.__dict__:
subprocess.call(args)
return ''
import subprocess
if 'Popen' in subprocess.__dict__:
if sys.platform[:3] != 'win' and shell:
p = None
stdin, stdouterr = os.popen4(cmd)
else:
p = subprocess.Popen(args, shell = shell,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.STDOUT)
stdin, stdouterr = (p.stdin, p.stdout)
else:
p = None
stdin, stdouterr = os.popen4(cmd)
text = stdouterr.read()
stdin.close()
stdouterr.close()
if p: p.wait()
if not capture:
sys.stdout.write(text)
sys.stdout.flush()
return ''
return text
#----------------------------------------------------------------------
# Default CFG File
#----------------------------------------------------------------------
ININAME = ''
INIPATH = ''
CFG = {'abspath':False, 'verbose':False, 'silent':False}
#----------------------------------------------------------------------
# configure: 确定gcc位置并从配置读出默认设置
#----------------------------------------------------------------------
class configure(object):
# 构造函数
def __init__ (self, ininame = ''):
self.dirpath = os.path.split(os.path.abspath(__file__))[0]
self.current = os.getcwd()
if not ininame:
ininame = ININAME and ININAME or 'emake.ini'
self.ininame = ininame
self.inipath = os.path.join(self.dirpath, self.ininame)
self.haveini = False
self.dirhome = ''
self.target = ''
self.config = {}
self.cp = ConfigParser.ConfigParser()
self.unix = 1
self.xlink = 1
self.searchdirs = None
self.environ = {}
self.exename = {}
self.replace = {}
self.cygwin = ''
for n in os.environ:
self.environ[n] = os.environ[n]
if sys.platform[:3] == 'win':
self.unix = 0
self.GetShortPathName = None
if sys.platform[:6] == 'darwin':
self.xlink = 0
if sys.platform[:3] == 'aix':
self.xlink = 0
self.cpus = 0
self.inited = False
self.fpic = 0
self.name = {}
ext = ('.c', '.cpp', '.c', '.cc', '.cxx', '.s', '.asm', '.m', '.mm')
self.extnames = ext
self.__jdk_home = None
self.reset()
# 配置信息复位
def reset (self):
self.inc = {} # include路径
self.lib = {} # lib 路径
self.flag = {} # 编译参数
self.pdef = {} # 预定义宏
self.link = {} # 连接库
self.flnk = {} # 连接参数
self.wlnk = {} # 连接传递
self.cond = {} # 条件参数
self.param_build = ''
self.param_compile = ''
return 0
# 初始化工具环境
def _cmdline_init (self, envname, exename):
if not envname in self.config:
return -1
config = self._env_config(envname)
PATH = []
EXEC = ''
sep = self.unix and ':' or ';'
envpath = config.get('PATH', '') + sep + self.environ.get('PATH', '')
condition = False
if os.path.exists(exename):
EXEC = exename
for path in envpath.split(sep):
if path.strip('\r\n\t ') == '':
continue
path = os.path.abspath(path)
if os.path.exists(path):
if not path in PATH:
PATH.append(path)
if not EXEC:
name = os.path.join(path, exename)
if os.path.exists(name):
EXEC = name
if not EXEC:
return -2
config['PATH'] = sep.join(PATH)
for n in config:
v = config[n]
if not n in ('PATH',):
os.environ[n] = v
os.environ['PATH'] = config['PATH']
if not self.unix:
EXEC = self.pathshort(EXEC)
return EXEC
# 工具加载
def _env_config (self, section):
config = {}
if section in self.config:
for n in self.config[section]:
config[n.upper()] = self.config[section][n]
for n in config:
config[n] = config[n].replace('$(INIROOT)', os.path.dirname(self.iniload))
for n in config:
config[n] = self._expand(config, self.environ, n)
return config
# 展开配置宏
def _expand (self, section, environ, item, d = 0):
if not environ: environ = {}
if not section: section = {}
text = ''
if item in environ:
text = environ[item]
if item in section:
text = section[item]
if d >= 20: return text
names = {}
index = 0
# print 'expanding', item
while 1:
index = text.find('$(', index)
if index < 0: break
p2 = text.find(')', index)
if p2 < 0: break
name = text[index + 2:p2]
index = p2 + 1
names[name] = name.upper()
for name in names:
if name != item:
value = self._expand(section, environ, name.upper(), d + 1)
elif name in environ:
value = environ[name]
else:
value = ''
text = text.replace('$(' + name + ')', value)
names[name] = value
# print '>', text
return text
# 取得短文件名
def pathshort (self, path):
path = os.path.abspath(path)
if self.unix:
return path
if not self.GetShortPathName:
self.kernel32 = None
self.textdata = None
try:
import ctypes
self.kernel32 = ctypes.windll.LoadLibrary("kernel32.dll")
self.textdata = ctypes.create_string_buffer('\000' * 1024)
self.GetShortPathName = self.kernel32.GetShortPathNameA
args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int ]
self.GetShortPathName.argtypes = args
self.GetShortPathName.restype = ctypes.c_uint32
except: pass
if not self.GetShortPathName:
return path
retval = self.GetShortPathName(path, self.textdata, 1024)
shortpath = self.textdata.value
if retval <= 0:
return ''
return shortpath
# 读取ini文件
def _readini (self, inipath):
self.cp = ConfigParser.ConfigParser()
if self.unix and '~' in inipath:
inipath = os.path.expanduser(inipath)
if os.path.exists(inipath):
self.iniload = os.path.abspath(inipath)
config = {}
try: self.cp.read(inipath)
except: pass
for sect in self.cp.sections():
for key, val in self.cp.items(sect):
lowsect, lowkey = sect.lower(), key.lower()
self.config.setdefault(lowsect, {})[lowkey] = val
config.setdefault(lowsect, {})[lowkey] = val
self.config['default'] = self.config.get('default', {})
config['default'] = config.get('default', {})
inihome = os.path.abspath(os.path.split(inipath)[0])
dirhome = config['default'].get('home', '')
if dirhome:
dirhome = os.path.join(inihome, dirhome)
if not os.path.exists(dirhome):
sys.stderr.write('error: %s: %s not exists\n'%(inipath, dirhome))
sys.stderr.flush()
else:
self.config['default']['home'] = dirhome
for exename in ('gcc', 'ld', 'ar', 'as', 'nasm', 'yasm', 'dllwrap'):
if not exename in config['default']:
continue
self.exename[exename] = config['default'][exename]
for bp in ('include', 'lib'):
if not bp in config['default']:
continue
data = []
for n in config['default'][bp].replace(';', ',').split(','):
n = os.path.normpath(os.path.join(inihome, self.pathconf(n)))
if not self.unix: n = n.replace('\\', '/')
data.append("'" + n + "'")
text = ','.join(data)
config['default'][bp] = text
self.config['default'][bp] = text
java = config['default'].get('java', '')
if java:
java = os.path.join(inihome, java)
if not os.path.exists(java):
sys.stderr.write('error: %s: %s not exists\n'%(inipath, java))
sys.stderr.flush()
else:
self.config['default']['java'] = os.path.abspath(java)
self.haveini = True
return 0
# 检查 dirhome
def check (self):
if not self.dirhome:
sys.stderr.write('error: cannot find gcc home in config\n')
sys.stderr.flush()
sys.exit(1)
return 0
# 初始化
def init (self):
if self.inited:
return 0
self.config = {}
self.reset()
fn = INIPATH
self.iniload = os.path.abspath(self.inipath)
if fn:
if os.path.exists(fn):
self._readini(fn)
self.iniload = os.path.abspath(fn)
else:
sys.stderr.write('error: cannot open %s\n'%fn)
sys.stderr.flush()
sys.exit(1)
else:
if self.unix:
self._readini('/etc/%s'%self.ininame)
self._readini('/usr/local/etc/%s'%self.ininame)
self._readini('~/.config/%s'%self.ininame)
self._readini(self.inipath)
self.dirhome = self._getitem('default', 'home', '')
cfghome = self.dirhome
if not self.haveini:
#sys.stderr.write('warning: %s cannot be open\n'%(self.ininame))
sys.stderr.flush()
defined = self.exename.get('gcc', None) and True or False
for name in ('gcc', 'ar', 'ld', 'as', 'nasm', 'yasm', 'dllwrap'):
exename = self.exename.get(name, name)
if not self.unix:
elements = list(os.path.splitext(exename)) + ['', '']
if not elements[1]: exename = elements[0] + '.exe'
self.exename[name] = exename
gcc = self.exename['gcc']
p1 = os.path.join(self.dirhome, '%s.exe'%gcc)
p2 = os.path.join(self.dirhome, '%s'%gcc)
if (not os.path.exists(p1)) and (not os.path.exists(p2)):
self.dirhome = ''
if sys.platform[:3] != 'win':
if self.dirhome[1:2] == ':':
self.dirhome = ''
if (not self.dirhome) and (not cfghome):
self.dirhome = self.__search_gcc()
if (not self.dirhome) and (not defined):
gcc = 'clang'
self.exename['gcc'] = gcc
self.dirhome = self.__search_gcc()
if self.dirhome:
self.dirhome = os.path.abspath(self.dirhome)
try:
cpus = self._getitem('default', 'cpu', '')
intval = int(cpus)
self.cpus = intval
except:
pass
cygwin = self._getitem('default', 'cygwin')
self.cygwin = ''
if cygwin and (not self.unix):
if os.path.exists(cygwin):
cygwin = os.path.abspath(cygwin)
bash = os.path.join(cygwin, 'bin/bash.exe')
if os.path.exists(bash):
self.cygwin = cygwin
self.name = {}
self.name[sys.platform.lower()] = 1
if sys.platform[:3] == 'win':
self.name['win'] = 1
if sys.platform[:7] == 'freebsd':
self.name['freebsd'] = 1
self.name['unix'] = 1
if sys.platform[:5] == 'linux':
self.name['linux'] = 1
self.name['unix'] = 1
if sys.platform[:6] == 'darwin':
self.name['darwin'] = 1
self.name['unix'] = 1
if sys.platform == 'cygwin':
self.name['unix'] = 1
if sys.platform[:5] == 'sunos':
self.name['sunos'] = 1
if os.name == 'posix':
self.name['unix'] = 1
if os.name == 'nt':
self.name['win'] = 1
if 'win' in self.name:
self.name['nt'] = 1
self.target = self._getitem('default', 'target')
names = self._getitem('default', 'name')
if names:
self.name = {}
for name in names.replace(';', ',').split(','):
name = name.strip('\r\n\t ').lower()
if not name: continue
self.name[name] = 1
if not self.target:
self.target = name
if not self.target:
self.target = sys.platform
self.target = self.target.strip('\r\n\t ')
if sys.platform[:3] in ('win', 'cyg'):
self.fpic = False
else:
self.fpic = True
#self.__python_config()
self.replace = {}
self.replace['home'] = self.dirhome
self.replace['emake'] = self.dirpath
self.replace['inihome'] = os.path.dirname(self.iniload)
self.replace['inipath'] = self.inipath
self.replace['target'] = self.target
self.inited = True
return 0
# 读取配置
def _getitem (self, sect, key, default = ''):
return self.config.get(sect, {}).get(key, default)
# 取得替换了$(HOME)变量的路径
def path (self, path):
path = path.replace('$(HOME)', self.dirhome).replace('\\', '/')
path = self.cygpath(path)
text = ''
issep = False
for n in path:
if n == '/':
if issep == False: text += n
issep = True
else:
text += n
issep = False
return os.path.abspath(text)
# 取得可用于参数的文本路径
def pathtext (self, name):
name = os.path.normpath(name)
name = self.cygpath(name)
name = name.replace('"', '""')
if ' ' in name:
return '"%s"'%(name)
if self.unix:
name = name.replace('\\', '/')
return name
# 取得短路径:当前路径的相对路径
def relpath (self, name, start = None):
name = os.path.abspath(name)
if not start:
start = os.getcwd()
if 'relpath' in os.path.__dict__:
try:
return os.path.relpath(name, start)
except:
pass
current = start.replace('\\', '/')
if len(current) > 0:
if current[-1] != '/':
current += '/'
name = self.path(name).replace('\\', '/')
size = len(current)
if self.unix:
if name[:size] == current:
name = name[size:]
else:
if name[:size].lower() == current.lower():
name = name[size:]
return name
# 取得短路径:当前路径的相对路径
def pathrel (self, name, start = None):
return self.pathtext(self.relpath(name, start))
# 转换到cygwin路径
def cygpath (self, path):
if self.unix and path[1:2] == ':':
path = '/cygdrive/%s%s'%(path[0], path[2:].replace('\\', '/'))
return path
# 转换到cygwin路径
def win2cyg (self, path):
path = os.path.abspath(path)
return '/cygdrive/%s%s'%(path[0], path[2:].replace('\\', '/'))
# 转换回cygwin路径
def cyg2win (self, path):
if path[1:2] == ':':
return os.path.abspath(path)
if path.lower().startswith('/cygdrive/'):
path = path[10] + ':' + path[11:]
return os.path.abspath(path)
if not path.startswith('/'):
raise Exception('cannot convert path: %s'%path)
if not self.cygwin:
raise Exception('cannot find cygwin root')
return os.path.abspath(os.path.join(self.cygwin, path[1:]))
# 添加头文件目录
def push_inc (self, inc):
path = self.path(inc)
if not os.path.exists(path):
sys.stderr.write('warning: ignore invalid path %s\n'%path)
return -1
path = self.pathtext(path)
self.inc[path] = 1
return 0
# 添加库文件目录
def push_lib (self, lib):
path = self.path(lib)
if not os.path.exists(path):
sys.stderr.write('warning: ignore invalid path %s\n'%path)
return -1
path = self.pathtext(path)
self.lib[path] = 1
return 0
# 添加参数
def push_flag (self, flag):
if not flag in self.flag:
self.flag[flag] = len(self.flag)
return 0
# 添加链接库
def push_link (self, link):
if link[-2:].lower() in ('.o', '.a'):
link = self.pathtext(self.path(link))
else:
link = '-l%s'%link.replace(' ', '_')
if not link in self.link:
self.link[link] = len(self.link)
#print 'push: ' + link
return 0
# 添加预定义
def push_pdef (self, define):
self.pdef[define] = 1
# 添加连接参数
def push_flnk (self, flnk):
if not flnk in self.flnk:
self.flnk[flnk] = len(self.flnk)
return 0
# 添加链接传递
def push_wlnk (self, wlnk):
if not wlnk in self.wlnk:
self.wlnk[wlnk] = len(self.wlnk)
return 0
# 添加条件参数
def push_cond (self, flag, condition):
key = (flag, condition)
if not key in self.cond:
self.cond[key] = len(self.cond)
return 0
# 搜索gcc
def __search_gcc (self):
dirpath = self.dirpath
gcc = self.exename['gcc']
splitter = self.unix and ':' or ';'
if os.path.exists(os.path.join(dirpath, '%s'%gcc)):
return os.path.abspath(dirpath)
if os.path.exists(os.path.join(dirpath, 'bin/%s'%gcc)):
return os.path.abspath(os.path.join(dirpath, 'bin'))
for d in os.environ.get('PATH', '').split(splitter):
n = os.path.abspath(os.path.join(d, '%s'%gcc))
if os.path.exists(n): return os.path.abspath(d)
if self.unix:
if os.path.exists('/bin/%s'%gcc):
return '/bin'
if os.path.exists('/usr/bin/%s'%gcc):
return '/usr/bin'
if os.path.exists('/usr/local/bin/%s'%gcc):
return '/usr/local/bin'
if os.path.exists('/opt/bin/%s'%gcc):
return '/opt/bin'
if os.path.exists('/opt/usr/bin/%s'%gcc):
return '/opt/usr/bin'
if os.path.exists('/opt/usr/local/bin/%s'%gcc):
return '/opt/usr/local/bin'
return ''
# 写默认的配置文件
def _write_default_ini (self):
default = ''' [default]
include=$(HOME)/include
lib=$(HOME)/lib
'''
text = '\n'.join([ n.strip('\t\r\n ') for n in default.split('\n') ])
if os.path.exists(self.inipath):
return -1
fp = open(self.inipath, 'w')
fp.write(text)
fp.close()
return 0
# 配置路径
def pathconf (self, path):
path = path.strip(' \t\r\n')
if path[:1] == '\'' and path[-1:] == '\'': path = path[1:-1]
if path[:1] == '\"' and path[-1:] == '\"': path = path[1:-1]
return path.strip(' \r\n\t')
# 刷新配置
def loadcfg (self, sect = 'default', reset = True):
self.init()
if reset: self.reset()
f1 = lambda n: (n[:1] != '\'' or n[-1:] != '\'') and n
config = lambda n: self._getitem(sect, n, '')
for path in config('include').replace(';', ',').split(','):
path = self.pathconf(path)
if not path: continue
self.push_inc(path)
for path in config('lib').replace(';', ',').split(','):
path = self.pathconf(path)
if not path: continue
self.push_lib(path)
for link in config('link').replace(';', ',').split(','):
link = self.pathconf(link)
if not link: continue
self.push_link(link)
for flag in config('flag').replace(';', ',').split(','):
flag = flag.strip(' \t\r\n')
if not flag: continue
self.push_flag(flag)
for pdef in config('define').replace(';', ',').split(','):
pdef = pdef.strip(' \t\r\n')
if not pdef: continue
self.push_pdef(pdef.replace(' ', '_'))
for flnk in config('flnk').replace(';', ',').split(','):
flnk = flnk.strip(' \t\r\n')
if not flnk: continue
self.push_flnk(flnk)
for wlnk in config('wlnk').replace(';', ',').split(','):
wlnk = wlnk.strip(' \t\r\n')
if not wlnk: continue
self.push_wlnk(wlnk)
for name in ('cflag', 'cxxflag', 'mflag', 'mmflag', 'sflag'):
for flag in config(name).replace(';', ',').split(','):
flag = flag.strip(' \t\r\n')
if not flag: continue
self.push_cond(flag, name)
self.parameters()
return 0
# 按字典值顺序取出配置
def sequence (self, data):
x = [ (n, k) for (k, n) in data.items() ]
x.sort()
y = [ n for (k, n) in x ]
return y
# 替换字符串
def __replace_key (self, text):
for key in self.replace:
value = self.replace[key]
check = '$(' + key + ')'
if check in text: