-
Notifications
You must be signed in to change notification settings - Fork 114
/
emake.py
3974 lines (3730 loc) · 138 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 python3
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 tw=0 et :
#======================================================================
#
# emake.py - emake version 3.7.6
#
# 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
# 2022.04.03 changning new: update to Python3
# 2023.09.20 skywind new: --profile=debug/release options
# 2023.10.08 skywind new: try "flag@debug: -g"
# 2023.12.07 skywind new: "PATH" item in 'default' section
# 2024.05.06 skywind new: "pkg: xxx" to import pkg-config packages
#
#======================================================================
from __future__ import unicode_literals, print_function
import sys
import time
import os
if sys.version_info.major == 2:
import ConfigParser as configparser
import cStringIO as cio
# pylint: disable=undefined-variable
range = xrange # noqa: F821
else:
import configparser
import io as cio
unicode = str
#----------------------------------------------------------------------
# version info
#----------------------------------------------------------------------
EMAKE_VERSION = '3.7.6'
EMAKE_DATE = 'Sep.12 2024'
#----------------------------------------------------------------------
# posix shell tools
#----------------------------------------------------------------------
class posix (object):
@staticmethod
def load_file_content (filename, mode = 'r'):
if hasattr(filename, 'read'):
try: content = filename.read()
except: pass
return content
try:
fp = open(filename, mode)
content = fp.read()
fp.close()
except:
content = None
return content
# load file and guess encoding
@staticmethod
def load_file_text (filename, encoding = None):
content = posix.load_file_content(filename, 'rb')
if content is None:
return None
if content[:3] == b'\xef\xbb\xbf':
text = content[3:].decode('utf-8')
elif encoding is not None:
text = content.decode(encoding, 'ignore')
else:
text = None
guess = [sys.getdefaultencoding(), 'utf-8']
if sys.stdout and sys.stdout.encoding:
guess.append(sys.stdout.encoding)
try:
import locale
guess.append(locale.getpreferredencoding())
except:
pass
visit = {}
for name in guess + ['gbk', 'ascii', 'latin1']:
if name in visit:
continue
visit[name] = 1
try:
text = content.decode(name)
break
except:
pass
if text is None:
text = content.decode('utf-8', 'ignore')
return text
@staticmethod
def load_ini (filename, encoding = None):
text = posix.load_file_text(filename, encoding)
config = {}
sect = 'default'
if text is None:
return None
for line in text.split('\n'):
line = line.strip('\r\n\t ')
if not line:
continue
elif line[:1] in ('#', ';'):
continue
elif line.startswith('['):
if line.endswith(']'):
sect = line[1:-1].strip('\r\n\t ')
if sect not in config:
config[sect] = {}
else:
pos = line.find('=')
if pos >= 0:
key = line[:pos].rstrip('\r\n\t ')
val = line[pos + 1:].lstrip('\r\n\t ')
if sect not in config:
config[sect] = {}
config[sect][key] = val
return config
@staticmethod
def decode_string (text, encoding = None):
hr = ''
if sys.version_info[0] >= 3:
if isinstance(text, str):
return text
else:
# pylint: disable-next=else-if-used
if isinstance(text, unicode): # noqa
return text
if encoding is not None:
return text.decode(encoding, errors = 'ignore')
guess = [sys.getdefaultencoding(), 'utf-8']
if sys.stdout and sys.stdout.encoding:
guess.append(sys.stdout.encoding)
try:
import locale
guess.append(locale.getpreferredencoding())
except:
pass
guess.reverse()
guess += ['gbk', 'ascii', 'latin1']
visit = {}
for name in guess:
if name in visit:
continue
visit[name] = 1
try:
hr = text.decode(name)
return hr
break
except:
pass
hr = text.decode('utf-8', errors = 'ignore')
return hr
#----------------------------------------------------------------------
# preprocessor: C/C++/Java 预处理器
#----------------------------------------------------------------------
class preprocessor(object):
# 初始化预编译器
def __init__ (self):
self.reset()
# 生成正文映射,将所有字符串及注释用 "$"和 "`"代替,排除分析干扰
def preprocess (self, text):
content = text
spaces = (' ', '\n', '\t', '\r')
srctext = cio.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:
content = posix.load_file_text(source)
except:
return ''
content = '\n'.join([ line.strip('\r\n') for line in content.split("\n") ])
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 range(start, offset1) ]
check_range += [ i for i in range(offset1 + 1, offset2) ]
check_range += [ i for i in range(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)
outtext = cio.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 range(start, endup):
if not (srctext[i] in space):
empty = 0
if srctext[i] == '`':
memod = 1
if empty and memod:
continue
for i in range(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 = []
cmd = None
os.shell_return = -1
if not isinstance(args, list):
import shlex
cmd = args
if sys.platform[:3] == 'win':
ucs = False
if sys.version_info[0] < 3:
if not isinstance(cmd, str):
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)
if cmd is None:
cmd = ' '.join(parameters)
if sys.platform[:3] == 'win' and len(cmd) > 255:
shell = False
if shell and (not capture):
os.shell_return = os.system(cmd)
return b''
elif (not shell) and (not capture):
import subprocess
if 'call' in subprocess.__dict__:
os.shell_return = subprocess.call(args)
return b''
import subprocess
if 'Popen' in subprocess.__dict__:
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)
stdin.close()
text = stdouterr.read()
stdouterr.close()
if p: p.wait()
os.shell_return = -1
if 'returncode' in p.__dict__:
os.shell_return = p.returncode
if not capture:
sys.stdout.write(text)
sys.stdout.flush()
return b''
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:
# pylint: disable=simplify-boolean-expression
ininame = ININAME and ININAME or 'emake.ini'
self.ininame = ininame
self.inipath = os.path.join(self.dirpath, self.ininame)
self.iniload = ''
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.profile = None
self.reset()
# reset all configure
def reset (self):
self.inc = {} # include paths
self.lib = {} # lib paths
self.flag = {} # compile flags
self.pdef = {} # predefined macros
self.link = {} # libraries
self.flnk = {} # link flags
self.wlnk = {} # link pass
self.cond = {} # condition flags
self.param_build = ''
self.param_compile = ''
return 0
# initialize environment for command tool
def _cmdline_init (self, envname):
config = self._env_config('environ:' + envname)
# print('config', config)
output = []
sep = self.unix and ':' or ';'
PATH = config.get('PATH', '').strip().replace(';', ',')
if self.unix:
PATH = PATH.replace(':', ',')
envpath = PATH + sep + self.environ.get('PATH', '')
for path in envpath.split(sep):
if path.strip('\r\n\t ') == '':
continue
path = os.path.abspath(path)
if os.path.exists(path):
if path not in output:
output.append(path)
config['PATH'] = sep.join(output)
for n in config:
v = config[n]
if n.strip():
os.environ[n] = v
os.environ['PATH'] = config['PATH']
return 0
# environment configuration for cmdline tool
def _env_config (self, section):
config = {}
if section in self.config:
for n in self.config[section]:
config[n.upper()] = self.config[section][n]
replace = {}
replace['$(INIROOT)'] = os.path.dirname(self.iniload)
replace['$(INIPATH)'] = os.path.abspath(self.iniload)
replace['$(TARGET)'] = self.target
for n in config:
text = config[n]
for key in replace:
text = text.replace(key, replace[key])
config[n] = text
for n in config:
config[n] = self._expand(config, self.environ, n)
return config
# expand macro
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
# calculate short path name
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
# read ini files
def _readini (self, inipath):
if '~' in inipath:
inipath = os.path.expanduser(inipath)
if os.path.exists(inipath):
self.iniload = os.path.abspath(inipath)
config = {}
self.cp = posix.load_ini(inipath)
if self.cp:
for sect in self.cp:
for key, val in self.cp[sect].items():
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 exename not in config['default']:
continue
self.exename[exename] = config['default'][exename]
for exename in ('pkg-config', 'pkgconfig'):
if exename not in config['default']:
continue
self.exename['pkgconfig'] = config['default'][exename]
for bp in ('include', 'lib'):
if bp not 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
# check 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
# init configure
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').strip()
if not self.target:
self.target = sys.platform
self.name[self.target] = 1
names = self._getitem('default', 'name').strip()
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 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.replace['profile'] = self.profile
self._reset_path()
self._reset_environ()
self.inited = True
return 0
# read configuration
def _getitem (self, sect, key, default = ''):
return self.config.get(sect, {}).get(key, default)
# reset $PATH
def _reset_path (self):
PATH = self._getitem('default', 'path', '').strip()
if not PATH:
return -1
sep = self.unix and ':' or ';'
pathout = []
PATH = PATH.replace(';', ',')
if self.unix:
PATH = PATH.replace(':', ',')
for path in PATH.split(','):
if os.path.isabs(path):
pathout.append(path)
elif os.path.exists(self.inipath):
inihome = os.path.dirname(os.path.abspath(self.inipath))
t = os.path.join(inihome, path)
pathout.append(t)
if 'PATH' not in CFG:
CFG['PATH'] = os.environ.get('PATH', '')
self._origin_os_path = CFG['PATH']
finalize = []
for path in pathout:
finalize.append(path)
t = sep.join(finalize)
self._new_os_path = t + sep + os.environ.get('PATH', '')
os.environ['PATH'] = self._new_os_path
return 0
# reset environment variables
def _reset_environ (self):
PKG_CONFIG_PATH = self._getitem('default', 'pcpath', '').strip()
if PKG_CONFIG_PATH:
os.environ['PKG_CONFIG_PATH'] = PKG_CONFIG_PATH
ENVIRON = self._getitem('default', 'environ', '').strip()
if ENVIRON:
for item in ENVIRON.split(','):
if not item: continue
name, value = (item.split('=') + ['', ''])[:2]
name, value = name.strip(), value.strip()
if name:
os.environ[name] = value
return 0
# 取得替换了$(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 is 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:]