-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathn2build
executable file
·2401 lines (2276 loc) · 82.7 KB
/
n2build
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
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import getopt, os, os.path, shelve, ConfigParser, hashlib, commands, string, codecs, shutil, datetime, re, zipfile, binascii, time, zlib, signal, subprocess
import socket, threading, base64, json, struct, multiprocessing
from xml.dom import minidom
# 判断必备模块
try:
import watchdog, watchdog.observers, watchdog.events
except Exception, err:
print '请先使用 sudo pip install watchdog 安装模块'
sys.exit(0)
try:
import lxml
except Exception, err:
print '请先使用 sudo pip install lxml 安装模块'
sys.exit(0)
try:
import openpyxl
except Exception, err:
print '请先使用 sudo pip install openpyxl 安装模块'
sys.exit(0)
if len(commands.getoutput('which npm')) == 0:
print '请先使用 sudo port install npm 安装node.js环境'
sys.exit(0)
if len(commands.getoutput('which tsc')) == 0:
print '请先使用 sudo npm install -g typescript 安装Typescript环境'
sys.exit(0)
if len(commands.getoutput('which md5sum')) == 0:
print '请显示用 sudo port install md5sha1sum 安装必要工具'
sys.exit(0)
if len(commands.getoutput('which wget')) == 0:
print '请显示用 sudo port install wget 安装必要工具'
sys.exit(0)
cfgdb = None
version = '1.0.0'
HOMEDIR = os.getenv("HOME") + '/'
if not os.path.isdir('.n2~'):
os.mkdir('.n2~')
def usage():
print """
n2build <-ht> <debug|publish|config|dpack|api file> \n
-h 帮助
-t 不启动service
debug \t 调试模式,默认
publish \t 发布模式,版本号使用config定义
dist <debug> \t 打包模式,除了publish的功能,额外会把publish/resource的目录压缩一遍
clean \t 清空
config \t 使用引导来配置当前项目
dpack \t diff-package 增量打包项目版本
api file \t 编译 file 文件,产出 api.proto 和 api.ts
depto <module> \t 使用ResDepto来修改子模块的资源配置文件
service <list|stop> \t 控制n2build的服务
skin <preview> \t 皮肤相关的操作 preview:生成皮肤预览[很长时间]
developer \t 启动开发服务
genres \t 生成res.json文件
pubres \t 发布resource到publish中
checkout \t 切换分支
debugindex \t 生成debugindex(windows编译出来的index.html中的文件顺序不对的时候需要在mac上生成debug.html)
"""
# 跨进程锁实现
try:
import fcntl
LOCK_EX = fcntl.LOCK_EX
except ImportError:
# windows平台下没有fcntl模块
fcntl = None
import win32con
import win32file
import pywintypes
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
overlapped = pywintypes.OVERLAPPED()
class GlobalLock:
def __init__(self, name):
self.name = '.n2~/' + name + '.locker~'
self.handle = open(self.name, 'w')
def acquire(self):
try:
if fcntl:
fcntl.flock(self.handle, LOCK_EX | fcntl.LOCK_NB)
else:
hfile = win32file._get_osfhandle(self.handle.fileno())
win32file.LockFileEx(hfile, LOCK_EX, 0, -0x10000, overlapped)
ret = True
except Exception, err:
ret = False
return ret
def release(self):
try:
if fcntl:
fcntl.flock(self.handle, fcntl.LOCK_UN)
else:
hfile = win32file._get_osfhandle(self.handle.fileno())
win32file.UnlockFileEx(hfile, 0, -0x10000, overlapped)
except Exception, err:
pass
def __del__(self):
#try:
# self.handle.close()
# os.remove(self.name)
#except:
# pass
pass #会干扰n2build的挂进程svc服务,造成重复启动
# 使用md5散列文件
def hashfile(file):
# with open(file, 'rb') as fh:
# m = hashlib.md5()
# while True:
# data = fh.read(8192)
# if not data:
# break
# m.update(data)
# return m.hexdigest()
res = commands.getoutput('md5sum ' + file).split(" ")
return res[0]
def filesize(file):
st = os.stat(file)
return st.st_size
# 高性能的简单散列
def simplehashfile(file):
st = os.stat(file)
d = ':'.join([str(st.st_size),
str(st.st_mtime),
str(st.st_ctime)])
return hashstring(d)
# 简单获取服务相关的临时文件名
_tmpfilecounter = 0;
def tempfilename():
global _tmpfilecounter
_tmpfilecounter = _tmpfilecounter + 1
return str(_tmpfilecounter)
def hashstring(str):
return hashlib.md5(str).hexdigest()
def isImage(file):
reximg = re.compile(r'(\.png$)|(\.jpg$)')
return reximg.search(file) != None
def makeconfig(recfg):
"""使用引导来生成项目的构建配置文件 .n2.cfg"""
cfg = ConfigParser.SafeConfigParser()
if recfg:
cfg.read('.n2.cfg')
def input(s, k, h):
if not cfg.has_section(s):
cfg.add_section(s)
if cfg.has_option(s, k):
t = cfg.get(s, k)
else:
t = ''
v = raw_input(h + [' 当前(' + t + ')', ''][not t] + ':') or t
cfg.set(s, k, v)
input('app', 'name', '游戏名称')
input('app', 'icon', 'ICON的路径')
input('app', 'background', '背景')
input('app', 'background-color', '背景颜色')
input('app', 'orientation', '方向 [h]ov/[v]ec')
input('app', 'resource', '资源的模式 [d]ebug/[p]ublish]')
input('app', 'version', '版本号')
input('dev', 'genresdb', '自动生成资源数据 [y]es/[n]o')
input('dev', 'automerge', '自动合并资源 [y]es/[n]o')
cfg.write(open('.n2.cfg', 'w'))
def checkconfig():
"""检查决策此次工作的配置"""
if not os.path.isfile('.n2.cfg'):
makeconfig(False)
if not cfgdb.has_key('uuid'):
import uuid
cfgdb['uuid'] = str(uuid.uuid4())
# 比对是否n2build升版
if not cfgdb.has_key('bver') or cfgdb['bver'] != version:
return True
# 比对配置文件是否修改过
cfghash = hashfile('.n2.cfg')
if not cfgdb.has_key('cfghash') or cfgdb['cfghash'] != cfghash:
cfgdb['cfghash'] = cfghash
return True
# 比对n2build是否修改过
n2bhash = hashfile('n2build')
if not cfgdb.has_key('n2bhash') or cfgdb['n2bhash'] != n2bhash:
cfgdb['n2bhash'] = n2bhash
return True
# 比对egretProp是否修改过
egprj = hashfile('egretProperties.json')
if not cfgdb.has_key('egprjhash') or cfgdb['egprjhash'] != egprj:
cfgdb['egprjhash'] = egprj
return True
return False
def egret_makerequire():
"""生成egret需要的文件"""
# egret3.0.5后,必须准备好native_require.js文件,否则编译报错
if not os.path.isfile('template/runtime/native_require.js'):
cnt = string.Template(TPL_NATIVE_REQUIRE).substitute()
open('template/runtime/native_require.js', 'w').write(cnt)
# 提取app.html中引用独立定义的加载样式
def apphtmlinfo(debug):
r = {'APPSTYLE':"",
'APPLAUNCH':"",
'APPSCRIPT':""}
# 如果直接返回r则代表不使用app.html
if not os.path.exists("src/app/app.html"):
return r
cfg = ConfigParser.ConfigParser()
cfg.read('.n2.cfg')
from lxml import etree
content = readfile("src/app/app.html")
# 替换掉assets形式的定义
if debug == True:
content = content.replace('assets://', 'resource/assets/')
else:
content = content.replace('assets://', 'resource_' + cfg.get('app', 'version') + '/assets/')
html = etree.HTML(content)
node = html.find('body').find('style')
if node != None:
r['APPSTYLE'] = etree.tostring(node, encoding='utf-8', method='html')
node = html.find('body').find('div')
if node != None:
r['APPLAUNCH'] = etree.tostring(node, encoding='utf-8', method='html')
node = html.find('body').find('script')
if node != None:
r['APPSCRIPT'] = etree.tostring(node, encoding='utf-8', method='html')
return r
def pdindex():
"""生成调试用的index相关文件"""
print "生成debug的index.html"
cfg = ConfigParser.ConfigParser()
cfg.read('.n2.cfg')
bkg = cfg.get('app', 'background')
bkgcolor = cfg.get('app', 'background-color')
if bkg.startswith('assets://'):
bkg = bkg.replace('assets://', 'resource/assets/')
appinfo = apphtmlinfo(True)
index = string.Template(TPL_INDEX_DEBUG).substitute({
'APPNAME': cfg.get('app', 'name'),
'APPORI': ['portrait', 'landscape'][cfg.get('app', 'orientation') == 'h'],
'APPANGLE': ['0', '90'][cfg.get('app', 'orientation') == 'h'],
'APPCONTENT': 'version=0.0.1, debug, verbose' + ['', ', publish'][cfg.get('app', 'resource') == 'p'],
'BACKGROUND': bkg,
'BACKGROUNDCOLOR': bkgcolor,
'APPSTYLE': appinfo['APPSTYLE'],
'APPLAUNCH': appinfo['APPLAUNCH'],
'APPSCRIPT': appinfo['APPSCRIPT']
})
open('index.html', 'w').write(index)
# 为了支持插件调试模式,需要描述一下当前项目的信息
open('src/app/~debug.js', 'w').write(string.Template("""
var app = {};
app.debug = {
PATH:"${PATH}",
UUID:"${UUID}",
CONFIG:${CONFIG},
BUILDDATE:${BUILDDATE}
};
""").substitute({
'PATH': os.getcwd(),
'UUID': cfgdb['uuid'],
'CONFIG': ['false', 'true'][os.path.exists('~debug.json')],
'BUILDDATE': int(time.time())
}))
def prindex():
# 处理最新的文件
print "生成release版的index.html"
if not os.path.isdir('publish'):
os.mkdir('publish')
"""生成发布版本的index相关文件"""
cfg = ConfigParser.ConfigParser()
cfg.read('.n2.cfg')
bkg = cfg.get('app', 'background')
bkgcolor = cfg.get('app', 'background-color')
if bkg.startswith('assets://'):
if cfg.get('app', 'resource') == 'p':
bkg = bkg.replace('assets://', 'resource_' + cfg.get('app', 'version') + '/assets/')
else:
bkg = bkg.replace('assets://', 'resource/assets/')
appinfo = apphtmlinfo(False)
index = string.Template(TPL_INDEX_RELEASE).safe_substitute({
'APPNAME': cfg.get('app', 'name'),
'APPORI': ['portrait', 'landscape'][cfg.get('app', 'orientation') == 'h'],
'APPANGLE': ['0', '90'][cfg.get('app', 'orientation') == 'h'],
'APPCONTENT': 'version=' + cfg.get('app', 'version') + ['', ', publish'][cfg.get('app', 'resource') == 'p'],
'APPVERSION': cfg.get('app', 'version'),
'APPICON': cfg.get('app', 'icon'),
'BACKGROUND': bkg,
'BACKGROUNDCOLOR' : bkgcolor,
'APPSTYLE': appinfo['APPSTYLE'],
'APPLAUNCH': appinfo['APPLAUNCH'],
'APPSCRIPT': appinfo['APPSCRIPT']
})
open('publish/index.html', 'w').write(index)
def readfile(file):
return ''.join(open(file).readlines())
def combinefiles(files, dest):
cnt = []
for file in files:
cnt.append(readfile(file))
open(dest, 'w').write('\n'.join(cnt))
def prebuildsrc():
# 处理 tsd 文件
if not os.path.exists('src/app/~tsc'):
os.mkdir('src/app/~tsc')
# 查找所有的tsd, 保存hash到对照表
tscdb = shelve.open('src/app/~tsc/.db')
# 处理所有的tsc文件
files = listfiles('src/app/data', whitelist=[re.compile(r'\.tsc$')])
for file in files:
hash = simplehashfile(file)
key = file.replace('/', '_')
if not tscdb.has_key(key) or tscdb[key] != hash:
prebuild_tsc(file, key)
tscdb[key] = hash
# 处理所有的excel文件
files = listfiles('src/app/data', whitelist=[re.compile(r'\.xlsx$'),re.compile(r'\.xls$')])
for file in files:
if os.path.basename(file).startswith('~'):
continue
hash = simplehashfile(file)
key = file.replace('/', '_')
if not tscdb.has_key(key) or tscdb[key] != hash:
prebuild_xls(file, key)
tscdb[key] = hash
tscdb.close()
# 合并处理过的所有文件到resource中,形成一个唯一的js
files = listfiles('src/app/~tsc', whitelist=[re.compile(r'\.js$')])
combinefiles(files, 'resource/default.data.js')
def prebuild_tsc(file, key):
print '处理 ' + file
shutil.copyfile(file, 'src/app/~tsc/doing.ts')
# 生成 d.ts 文件
commands.getoutput('tsc -d -t es5 --outDir src/app/~tsc src/app/~tsc/doing.ts')
shutil.move('src/app/~tsc/doing.d.ts', 'src/app/~tsc/' + key + '.d.ts')
shutil.move('src/app/~tsc/doing.js', 'src/app/~tsc/' + key + '.js')
os.unlink('src/app/~tsc/doing.ts')
def prebuild_xls(file, key):
print '处理 ' + file
d = openpyxl.reader.excel.load_workbook(file)
for e in d.sheetnames:
prebuild_xls_sheet(d, e, key + '_' + e.lower())
def prebuild_xls_sheet(xls, name, key):
sh = xls.get_sheet_by_name(name)
data = {}
# 第一行是说明,第二行是id会变成property,其他行是数据
# 查找id位于的colid
colids = []
colnames = []
idxid = None
for col in range(sh.max_column):
cell = sh.cell(row=2, column=col+1)
val = cell.value
if val != None:
colids.append(col+1)
colnames.append(val)
if val == 'id':
idxid = col+1
# 根据第一行的数据类型生成基础的类型定义
props = []
for i in range(len(colids)):
col = colids[i]
cell = sh.cell(row=3, column=col)
val = cell.value
valtype = 'number'
if val == None:
valtype = 'string'
elif isinstance(val, str) or isinstance(val, unicode):
valtype = 'string'
prop = string.Template("""
get ${NAME}():${TYPE} { return this._obj[${INDEX}]; }
static ${NAME}Index = ${INDEX};
"""
).substitute({
'NAME':colnames[i],
'TYPE':valtype,
'INDEX':i
})
props.append(prop)
# 拼装所有行数据
rowdatas = []
rowids = []
for row in range(3, sh.max_row+1):
rowid = row - 3
if idxid != None:
rowid = sh.cell(row=row, column=idxid).value
rowdata = []
for i in range(len(colids)):
col = colids[i]
val = sh.cell(row=row, column=col).value
rowdata.append(val)
rowids.append(rowid)
rowdatas.append(rowdata)
# 输出
output_xlsdata_tots(name, rowids, rowdatas, props, key)
def output_xlsdata_tots(name, ids, datas, props, key):
# 转换datas到对应的jsobj结构的数据
jsobjs = []
for i in range(len(ids)):
jsobjs.append('"' + str(ids[i]) + '":' + name.lower() + 'Cfgs[' + str(i) + ']')
# 输出成ts再使用tsc变异成dts和对应js文件,降低性能影响
cnt = string.Template("""module Data {
export var ${NAME}Cfgs:any[] = ${CFGS};
export var ${NAME}s:any = ${DATA};
export class ${CLASS} {
constructor(obj) { this._obj = obj; }
private _obj:any;
${PROPERTIES}
}
export function get${CLASS}(id:any):${CLASS} { return new ${CLASS}(${NAME}s[id]); }
}""").substitute({
'NAME':name.lower(),
'CLASS':name[0].upper() + name[1:],
'CFGS':json.dumps(datas, indent=4),
'DATA':'{' + ','.join(jsobjs) + '}',
'PROPERTIES':''.join(props)
}).decode("unicode-escape")
codecs.open('src/app/~tsc/doing.ts', 'w', 'utf-8').write(cnt)
# 输出js
commands.getoutput('tsc -d -t es5 --outDir src/app/~tsc src/app/~tsc/doing.ts')
shutil.move('src/app/~tsc/doing.d.ts', 'src/app/~tsc/' + key + '.d.ts')
shutil.move('src/app/~tsc/doing.js', 'src/app/~tsc/' + key + '.js')
os.unlink('src/app/~tsc/doing.ts')
def builddebug(rebuild):
if rebuild:
print "重新编译debug版本"
else:
print "编译debug版本"
# 预处理工程代码
egret_makerequire()
prebuildsrc()
# 去除publish引起的egret混乱
shutil.rmtree('publish', True)
# 判断使用何种编译
if rebuild:
egret_cmd('clean')
print egret_cmd('build -e')
else:
print egret_cmd('build')
def copydebugtopublish():
print "拷贝debug文件到publish"
if not os.path.isdir('publish'):
os.mkdir('publish')
shutil.copytree('tools', 'publish/tools')
shutil.copytree('libs', 'publish/libs')
shutil.copytree('src/app/~tsc', 'publish/src/app/~tsc')
shutil.copytree('bin-debug', 'publish/bin-debug')
shutil.copytree('resource', 'publish/resource')
shutil.copy('src/app/~debug.js', 'publish/src/app/')
shutil.copy('index.html', 'publish/')
shutil.copy('app.json', 'publish/')
# 判断是否需要合并
cfg = ConfigParser.ConfigParser()
cfg.read('.n2.cfg')
if cfg.get('dev', 'automerge') == 'y':
print "合并图片"
processdirs('publish/resource/assets', automergeimages, blacklist=GENRES_BLACKS, depth=2)
genresdbdirectory('publish')
def lines_between(lines, begin, end):
ret = []
match = False
rexbeg = re.compile(begin)
rexend = re.compile(end)
for line in lines:
if not match:
if rexbeg.search(line):
match = True
continue
if rexend.search(line):
break
ret.append(line)
return ret
def lines_replace(lines, begin, end, reps):
match = False
rexbeg = re.compile(begin)
rexend = re.compile(end)
idxbeg = -1
idxend = -1
idx = -1
for line in lines:
idx += 1
if not match:
if rexbeg.search(line):
match = True
idxbeg = idx
continue
if rexend.search(line):
idxend = idx
break
if idxbeg == -1 or idxend == -1:
return lines
l = lines[:idxbeg+1]
r = lines[idxend:]
return l + reps + r
def lines_insert(lines, find, inserts):
rex = re.compile(find)
idx = -1
for line in lines:
idx += 1
if rex.search(line):
break;
if idx == -1:
return lines
l = lines[:idx+1]
r = lines[idx+1:]
return l + inserts + r
def safeInt(str, d = 0):
r = d
try:
r = int(str)
except:
pass
return r
# 下载 closure-compiler
def downloadccompiler():
if not os.path.isfile(".n2~/jscompiler"):
os.system("wget http://7xlcco.com1.z0.glb.clouddn.com/closure-compiler.jar -O " + ".n2~/jscompiler")
# 下载 euibooster
def downloadeuib():
if not os.path.isfile(".n2~/euibooster"):
commands.getoutput("wget https://raw.githubusercontent.com/wybosys/n2egret/master/tools/euibooster.js -O " + ".n2~/euibooster.js")
commands.getoutput("wget https://raw.githubusercontent.com/wybosys/n2egret/master/tools/euibooster -O " + ".n2~/euibooster")
commands.getoutput("chmod +x .n2~/euibooster")
PATTERN_HTML_SCRIPT_SRC = re.compile('src="(.+)"')
def buildrelease():
print "编译release版本"
# 判断是否使用eui
if os.path.exists('resource/eui_skins'):
if len(commands.getoutput('which euibooster')) == 0:
print '请先使用 sudo npm install -g cli-eui-new 安装模块'
sys.exit(0)
else:
downloadeuib()
# 预处理代码
egret_makerequire()
prebuildsrc()
# 重新编译工程
egret_cmd('build -e')
# 读取配置
cfg = ConfigParser.ConfigParser()
cfg.read('.n2.cfg')
# 清理binrelease
if os.path.isdir("bin-release"):
shutil.rmtree("bin-release")
print 'publish版本' + egret_cmd('publish --compressjson')
dir = str(max(map(safeInt, os.listdir('bin-release/web'))))
# 自动合并release下面的图片
if cfg.get('dev', 'automerge') == 'y':
print "自动合并图片"
processdirs('bin-release/web/' + dir + '/resource/assets/', automergeimages, blacklist=GENRES_BLACKS, depth=2)
# 因为自动合并图片,需要刷新下bin-release下面的res.json
genresdbdirectory('bin-release/web/' + dir)
# 后处理
print "拷贝release版本到publish"
shutil.move('bin-release/web/' + dir + '/resource', 'publish/resource')
shutil.copyfile('bin-release/web/' + dir + '/main.min.js', 'publish/main.min.js')
# 压缩eui
if os.path.exists('resource/eui_skins'):
print '编译 eui-skins'
shutil.copyfile('publish/resource/default.thm.json', 'publish/resource/default.thm')
os.system('.n2~/euibooster ' + os.getcwd() + ' publish')
files = []
# 提取标准打包出来的数据
html = open('bin-release/web/' + dir + '/index.html').readlines()
libfiles = lines_between(html, '<!--modules_files_start-->', '<!--modules_files_end-->')
# 打包基础的库文件
libscnt = []
for file in libfiles:
file = PATTERN_HTML_SCRIPT_SRC.findall(file)[0]
libscnt.append(readfile(file))
open("publish/engine.min.js", "w").write('\n'.join(libscnt))
files.append('<script src="engine.min.js?v=' + cfg.get('app', 'version') + '"></script>\n')
# 打包进自定义生成的数据文件
if os.path.isdir("src/app/~tsc"):
downloadccompiler()
# 保存一下原始的
shutil.move('publish/resource/default.data.js', '.n2~/default.data.js')
# 使用cc来压缩js
os.system("java -jar .n2~/jscompiler --charset utf8 --language_out ECMASCRIPT5 --js .n2~/default.data.js --js_output_file publish/resource/default.data.js")
# 需要给js上加上版本标记
files.append('<script src="main.min.js?v=' + cfg.get('app', 'version') + '"></script>\n')
html = string.Template(''.join(open('publish/index.html').readlines()))
open('publish/index.html', 'w').write(html.safe_substitute({
'FILESLIST': ''.join(files)
}))
# 数据库
def db_get(file, val={}):
s = shelve.open(file)
for e in s.keys():
val[e] = s[e]
return val
def db_set(obj, file):
s = shelve.open(file)
for e in obj.keys():
s[e] = obj[e]
s.close()
# 打包资源文件
def distfile(q, sem, file, func, db, prg):
idx = prg[0]
sum = prg[1]
key = hashstring(file)
if db.has_key(key):
# 如果大小不同,再比对hash,加速
hash = hashfile(file)
if hash == db[key]:
print 'COPY %d/%d' %(idx,sum), file
shutil.copyfile('.n2~/dist/' + key, file)
sem.release()
return
db[key] = hash
oldsz = filesize(file)
func(file)
newsz = float(filesize(file))
print 'RECOMPRESS %d/%d' %(idx,sum), file, '%d%%' %(newsz/oldsz*100), '%dK' %(newsz/1024)
shutil.copyfile(file, '.n2~/dist/' + key)
sem.release()
return
hash = hashfile(file)
db[key] = hash
oldsz = filesize(file)
func(file)
newsz = float(filesize(file))
print 'COMPRESS %d/%d' %(idx,sum), file, '%d%%' %(newsz/oldsz*100), '%dK' %(newsz/1024)
shutil.copyfile(file, '.n2~/dist/' + key)
sem.release()
def distpng(file):
os.system("pngquant --ext .png --force --speed 1 " + file)
def distjpg(file):
os.system("jpegoptim -m30 " + file)
def distresources():
# .n2~ 中建立一个数据库,保存历史中的文件优化信息,并保存文件版本,该版本会当目标文件变化时更新,因为.n2~会随着n2build clean清除,所以一定程度上可以忽视image文件大量积压问题
db = db_get('.n2~/dist.db', multiprocessing.Manager().dict())
if not os.path.isdir('.n2~/dist'):
os.mkdir('.n2~/dist')
# 针对png和jpg分别处理
pngs = listfiles("publish/resource", whitelist=[re.compile(r'(\.png$)')])
jpgs = listfiles("publish/resource", whitelist=[re.compile(r'(\.jpg$)')])
idx = 0
sum = len(pngs) + len(jpgs)
# 多进程处理
sem = multiprocessing.Semaphore(8)
for png in pngs:
sem.acquire()
idx += 1
q = multiprocessing.Queue()
p = multiprocessing.Process(target=distfile, args=(q, sem, png, distpng, db, (idx,sum)))
p.start()
for jpg in jpgs:
sem.acquire()
idx += 1
# 启动进程
q = multiprocessing.Queue()
p = multiprocessing.Process(target=distfile, args=(q, sem, jpg, distjpg, db, (idx,sum)))
p.start()
# 额外做一下等待
time.sleep(10)
db_set(db, '.n2~/dist.db')
def explorer(path):
commands.getstatusoutput("terminal-notifier -title N2BUILD -sound default -message 发布成功 " + "-execute \"open " + path + "\"")
def egret_cmd(cmd):
s, ot = commands.getstatusoutput('egret ' + cmd)
return ot.decode('utf-8')
SRV_DEBUG_RUN = True
WS_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
WS_HANDSHAKE_STRING = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade:websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: {1}\r\n" \
"WebSocket-Location: ws://{2}/chat\r\n" \
"WebSocket-Protocol:chat\r\n\r\n"
class WS_SERVICE(threading.Thread):
def __init__(self, connection):
threading.Thread.__init__(self)
self.con = connection
self.workers = {}
def run(self):
while True:
try:
rec = self.recv_data(9216)
if type(rec) == str:
m = json.loads(unicode(rec, "utf-8"))
cmd = m[u'cmd']
if self.workers.has_key(cmd):
worker = self.workers[cmd]
if worker(m):
# 发送成功
m['rsp'] = True
self.send_data(json.dumps(m))
else:
print '服务器不支持该命令 ' + cmd
except Exception, err:
print '处理收到的数据失败', err
self.con.close()
def work(self, cmd, worker):
self.workers[cmd] = worker
def recv_data(self, num):
try:
all_data = self.con.recv(num)
if not len(all_data):
return False
except:
return False
else:
code_len = ord(all_data[1]) & 127
if code_len == 126:
masks = all_data[4:8]
data = all_data[8:]
elif code_len == 127:
masks = all_data[10:14]
data = all_data[14:]
else:
masks = all_data[2:6]
data = all_data[6:]
raw_str = ""
i = 0
for d in data:
raw_str += chr(ord(d) ^ ord(masks[i % 4]))
i += 1
return raw_str
def send_data(self, data):
if data:
data = str(data)
else:
return False
token = "\x81"
length = len(data)
if length < 126:
token += struct.pack("B", length)
elif length <= 0xFFFF:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
data = '%s%s' % (token, data)
self.con.send(data)
return True
def ws_handshake(con):
headers = {}
shake = con.recv(1024)
if not len(shake):
return False
header, data = shake.split('\r\n\r\n', 1)
for line in header.split('\r\n')[1:]:
key, val = line.split(': ', 1)
headers[key] = val
if 'Sec-WebSocket-Key' not in headers:
return False
sec_key = headers['Sec-WebSocket-Key']
res_key = base64.b64encode(hashlib.sha1(sec_key + WS_MAGIC_STRING).digest())
str_handshake = WS_HANDSHAKE_STRING.replace('{1}', res_key).replace('{2}', 'localhost:59000')
con.send(str_handshake)
return True
# 运行守护进程
def start_deamon():
pid = os.fork()
if pid != 0:
open(HOMEDIR + "/.n2.builder.deamons", 'a').write(str(pid) + '\n')
return pid == 0
def stop_deamons():
if not os.path.exists(HOMEDIR + "/.n2.builder.deamons"):
return
for pid in get_deamons():
try:
os.kill(pid, signal.SIGKILL)
except:
pass
os.unlink(HOMEDIR + "/.n2.builder.deamons")
def get_deamons():
r = []
if not os.path.exists(HOMEDIR + "/.n2.builder.deamons"):
return []
for line in open(HOMEDIR + "/.n2.builder.deamons", 'r').readlines():
try:
r.append(int(line))
except:
pass
return r
# 启动标准的ws服务
def wswrk_launch(port, wrkidr, wrkfun):
# 如果已经运行,则跳过
lck = GlobalLock(wrkidr.replace(':', '_'))
if lck.acquire() == False:
return
lck.release()
# 子进程
if start_deamon():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', int(port)))
sock.listen(1000)
#print wrkidr + ' 启动成功 localhost:' + port
except Exception,err:
print err
return
lck = GlobalLock(wrkidr.replace(':', '_'))
lck.acquire()
while SRV_DEBUG_RUN:
connector, addr = sock.accept()
if addr[0] != '127.0.0.1':
connector.close()
continue
if ws_handshake(connector):
try:
svc = WS_SERVICE(connector)
svc.work(wrkidr, wrkfun)
svc.start()
except:
connector.close()
lck.release()
# 监听文件变动
def watchfilesystem(name, path, handler):
lck = GlobalLock(name)
if lck.acquire() == False:
#print 'fswatcher:' + name + ' 已经运行'
return False
#print 'fswatcher:即将启动 ' + name
lck.release()
# 创建工作进程
#wfs_worker(name, path, handler)
#return
if start_deamon():
wfs_worker(name, path, handler)
return True
def wfs_worker(name, path, handler):
lck = GlobalLock(name)
lck.acquire()
try:
obs = watchdog.observers.Observer()
obs.schedule(handler, path, recursive=True)
obs.start()
#print 'fswatcher:' + name + '启动成功'
try:
while True:
time.sleep(1)
#print 'fswatcher:' + name + '轮询'
except KeyboardInterrupt:
obs.stop()
obs.join()
except Exception, err:
#print 'fswatcher:' + name + '启动失败'
print err
lck.release()
# ----------------------------------- 控制 wing 的状态
def egret_wing_usefile(file, dir):
hex = """\n\x0b\x01\x1blayoutDefault\n\x01;MainView.WorkSpace.Programmer\x06\x8e${SIZE}<BoxElement width="1886" height="955" id="6">\n <BoxElement isVertical="true" width="272" height="955" id="2">\n <TabGroup selectedIndex="0" width="272" height="478" id="0">\n <TabPanel content="packagePanel"/>\n </TabGroup>\n <TabGroup selectedIndex="0" width="272" height="478" id="1">\n <TabPanel content="outlinePanel"/>\n </TabGroup>\n </BoxElement>\n <BoxElement isVertical="true" width="1615" height="955" id="5">\n <Document width="1615" height="955" id="3">\n <TabGroup selectedIndex="0" width="1615" height="955" id="7">\n <TabPanel path="${FILE}"/>\n </TabGroup>\n </Document>\n <TabGroup selectedIndex="0" minimized="true" id="4">\n <TabPanel content="consolePanel"/>\n <TabPanel content="progressPanel"/>\n <TabPanel content="searchResultPanel"/>\n <TabPanel content="errorPanel"/>\n </TabGroup>\n </BoxElement>\n</BoxElement>\x01\x0fcurrent\n\x01\tname\x06\x02\ttype\x06\x0fdefault\x01\x01"""
layout = HOMEDIR + "Library/Application Support/EgretWing/Local Store/layout.amf"
cnt = string.Template(hex).substitute({
'SIZE':chr(len(dir) + (len(file) + 1)*2),
'FILE':dir + '/' + file
})
open(layout, 'w').write(egret_compress(cnt))
def egret_wing_openwing(file, dir, fun = None):
layout = HOMEDIR + "Library/Application Support/EgretWing/Local Store/layout.amf"
# 保存老的
shutil.copyfile(layout, layout + ".bak")
egret_wing_usefile(file, dir)
# 打开wing
app = subprocess.Popen("/Applications/EgretWing.app/Contents/MacOS/EgretWing", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if fun != None:
# 需要等待20s当wing启动正常后再处理
time.sleep(20)
fun()
# 关闭
app.kill()
# 退出后恢复
app.wait()
shutil.move(layout + ".bak", layout)
def egret_wing_captureskin(file, dir, to):
try:
import pyscreeze
except:
print '请使用 sudo pip install pyscreeze 安装模块'
sys.exit(0)
print "即将生成 " + file + " 的预览"
def captureskin():
img = pyscreeze.screenshot(region=(700, 160, 780, 900))
img.save(to)
egret_wing_openwing(file, dir, captureskin)
def preview_skins():
skins = listfiles('resource/eui_skins/app', whitelist=[re.compile(r'\.exml$')])
if not os.path.exists('preview'):
os.mkdir('preview')
dir = os.getcwd()
for skin in skins:
name = skin[23:].replace('/', '_') + '.jpg'
egret_wing_captureskin(skin, dir, 'preview/' + name)
# ----------------------------------- 生成子资源模块 ---------------------------
def svc_subresmaker():
suc = watchfilesystem("resmaker", "resource/assets", hdl_resmaker())
# 每次第一次打开,自动重建一下索引
if suc:
resmaker_rebuild()
class hdl_resmaker(watchdog.events.FileSystemEventHandler):
def getinfo(self, e):
p = e.src_path
if os.path.isdir(p):
return None
res = re.compile(r'resource/assets/(0-9a-zA-Z]+)/(.+)').findall(p)
if len(res) == 0:
return None
res = res[0]
mod = res[0]
path = mod + '/' + res[1]
return (mod, path)
def rebuild(self, e):
info = self.getinfo(e)
if info != None:
resmaker_buildmod('resource/assets/' + info[0])
def on_created(self, e):
self.rebuild(e)
def on_deleted(self, e):
self.rebuild(e)
def on_moved(self, e):
self.rebuild(e)
def resmaker_rebuild():
# 刷新资源的索引,默认 resource 下面每一个文件夹都代表一个res-module,里面按照jsonobj保存资源的name-path
for each in listdirs("resource/assets", depth=1):
resmaker_buildmod(each)
RESMAKER_BLACKS = [
re.compile(r'module\.res\.json$'),
re.compile(r'\.swf$'),
re.compile(r'\.fla$'),
re.compile(r'^\.')
];
def resmaker_buildmod(dir):
files = listfiles(dir, blacklist=RESMAKER_BLACKS)
# 做成keyvalue
dict = {}
for file in files:
fns = os.path.splitext(os.path.basename(file))
dict[fns[0] + fns[1]] = {'p':file.replace('resource/assets/', '')}
# 使用增量的方式可以避免通过工具设置的其它参数被冲掉
resf = dir + '/module.res.json'
if os.path.exists(resf):
try:
predict = json.loads(''.join(open(resf).readlines()))
except: