forked from Timeszoro/LayoutCast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcast.py
1057 lines (913 loc) · 37.9 KB
/
cast.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/python
from sys import stderr
from re import match
__author__ = 'mmin18'
__version__ = '1.51927'
__plugin__ = '1'
import argparse
from distutils.version import LooseVersion
import io
import json
import os
import re
import shutil
from subprocess import Popen, PIPE
import sys
import time
import zipfile
# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
def which(program):
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def cexec_fail_exit(args, code, stdout, stderr):
if code != 0:
print('Fail to exec %s' % args)
print(stdout)
print(stderr)
exit(code)
def cexec(args, callback=cexec_fail_exit, addPath=None, exitcode=1):
env = None
if addPath:
import copy
env = copy.copy(os.environ)
env['PATH'] = addPath + os.path.pathsep + env['PATH']
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env)
output, err = p.communicate()
code = p.returncode
if code and exitcode:
code = exitcode
if callback:
callback(args, code, output, err)
return output
def curl(url, body=None, ignoreError=False, exitcode=1):
try:
if sys.version_info >= (3, 0):
import urllib.request
return urllib.request.urlopen(url, data=body).read().decode('utf-8').strip()
else:
import urllib2
return urllib2.urlopen(url, data=body).read().decode('utf-8').strip()
except Exception as e:
if ignoreError:
return None
else:
print(e)
exit(exitcode)
def open_as_text(path):
if not path or not os.path.isfile(path):
return ''
with io.open(path, 'r', errors='replace') as f:
data = f.read()
return data
print('fail to open %s' % path)
return ''
def is_gradle_project(directory):
return os.path.isfile(os.path.join(directory, 'build.gradle'))
def parse_properties(path):
return os.path.isfile(path) and dict(line.strip().split('=') for line in open(path) if ('=' in line and not line.startswith('#'))) or {}
def balanced_braces(arg):
if '{' not in arg:
return ''
chars = []
n = 0
for c in arg:
if c == '{':
if n > 0:
chars.append(c)
n += 1
elif c == '}':
n -= 1
if n > 0:
chars.append(c)
elif n == 0:
return ''.join(chars).lstrip().rstrip()
elif n > 0:
chars.append(c)
return ''
def remove_comments(code):
# remove comments in groovy
return re.sub(r'''(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)''', '', code)
def __deps_list_eclipse(a_list, project):
prop = parse_properties(os.path.join(project, 'project.properties'))
for i in range(1, 100):
dep = prop.get('android.library.reference.%d' % i)
if dep:
absdep = os.path.abspath(os.path.join(project, dep))
__deps_list_eclipse(a_list, absdep)
if not absdep in a_list:
a_list.append(absdep)
def __deps_list_gradle(a_list, project):
sFile = open_as_text(os.path.join(project, 'build.gradle'))
sFile = remove_comments(sFile)
ideps = []
# for depends in re.findall(r'dependencies\s*\{.*?\}', str, re.DOTALL | re.MULTILINE):
for m in re.finditer(r'dependencies\s*\{', sFile):
depends = balanced_braces(sFile[m.start():])
for proj in re.findall(r'''compile\s+project\s*\(.*['"]:(.+)['"].*\)''', depends):
ideps.append(proj.replace(':', os.path.sep))
if len(ideps) == 0:
return
# get the real path
ex_libs = {}
par = os.path.abspath(os.path.join(project, os.pardir))
if os.path.isfile(os.path.join(par, 'settings.gradle')):
data = open_as_text(os.path.join(par, 'settings.gradle'))
for proj in re.findall(r'''project\(\'\:(.+)\'\)\.projectDir\s*\=\s*new\s*File\(.*['"](.+)['"]\)''', data):
ex_libs[proj[0]] = proj[1]
deptmp = []
for dep in ideps:
if dep in ex_libs:
deptmp.append(ex_libs[dep])
else:
deptmp.append(dep)
ideps = deptmp
path = project
for i in range(1, 3):
path = os.path.abspath(os.path.join(path, os.path.pardir))
pathtmp = path
b = True
deps = []
for idep in ideps:
for par in re.findall(r'.*(\.\.\/).+', idep):
pathtmp = os.path.abspath(os.path.join(path, os.path.pardir))
idep = idep.replace('../', '')
dep = os.path.join(pathtmp, idep)
if not os.path.isdir(dep):
b = False
break
deps.append(dep)
if b:
for dep in deps:
__deps_list_gradle(a_list, dep)
if not dep in a_list:
a_list.append(dep)
break
def deps_list(directory):
if is_gradle_project(directory):
a_list = []
__deps_list_gradle(a_list, directory)
return a_list
else:
a_list = []
__deps_list_eclipse(a_list, directory)
return a_list
def manifest_path(directory):
if os.path.isfile(os.path.join(directory, 'AndroidManifest.xml')):
return os.path.join(directory, 'AndroidManifest.xml')
if os.path.isfile(os.path.join(directory, 'src', 'main', 'AndroidManifest.xml')):
return os.path.join(directory, 'src', 'main', 'AndroidManifest.xml')
def package_name(directory):
path = manifest_path(directory)
data = open_as_text(path)
for pn in re.findall('package=\"([\w\d_\.]+)\"', data):
return pn
def get_apk_path(directory):
if not is_gradle_project(directory):
apkpath = os.path.join(directory, 'bin')
else:
apkpath = os.path.join(directory, 'build', 'outputs', 'apk')
# Get the lastmodified *.apk file
maxt = 0
maxd = None
for dirpath, dirnames, files in os.walk(apkpath):
for fn in files:
if fn.endswith('.apk') and not fn.endswith('-unaligned.apk') and not fn.endswith('-unsigned.apk'):
lastModified = os.path.getmtime(os.path.join(dirpath, fn))
if lastModified > maxt:
maxt = lastModified
maxd = os.path.join(dirpath, fn)
return maxd
def package_name_fromapk(directory, sdkdir):
# Get the package name from maxd
aaptpath = get_aapt(sdkdir)
if aaptpath:
apkpath = get_apk_path(directory)
if apkpath:
aaptargs = [aaptpath, 'dump', 'badging', apkpath]
output = cexec(aaptargs, callback=None)
for pn in re.findall('package: name=\'([^\']+)\'', output):
return pn
return package_name(directory)
def get_latest_packagename(dirlist, sdkdir):
maxt = 0
maxd = None
for directory in dirlist:
if directory:
apkfile = get_apk_path(directory)
if apkfile:
lastModified = os.path.getmtime(apkfile)
if lastModified > maxt:
maxt = lastModified
maxd = directory
if maxd:
return package_name_fromapk(maxd, sdkdir)
def isRes_Name(name):
if name == 'drawable' or name.startswith('drawable-'):
return 2
if name == 'layout' or name.startswith('layout-'):
return 2
if name == 'values' or name.startswith('values-'):
return 2
if name == 'anim' or name.startswith('anim-'):
return 1
if name == 'color' or name.startswith('color-'):
return 1
if name == 'menu' or name.startswith('menu-'):
return 1
if name == 'raw' or name.startswith('raw-'):
return 1
if name == 'xml' or name.startswith('xml-'):
return 1
if name == 'mipmap' or name.startswith('mipmap-'):
return 1
if name == 'animator' or name.startswith('animator-'):
return 1
return 0
def count_Res_Dir(directory):
c = 0
d = 0
if os.path.isdir(directory):
for subd in os.listdir(directory):
v = isRes_Name(subd)
if v > 1:
d += 1
if v > 0:
c += 1
if d == 0:
return 0
return c
def count_Asset_Dir(directory):
a = 0
if os.path.isdir(directory):
for subd in os.listdir(directory):
if not subd.startswith('.'):
a += 1
return a
def res_dir(directory):
dir1 = os.path.join(directory, 'res')
dir2 = os.path.join(directory, 'src', 'main', 'res')
a = count_Res_Dir(dir1)
b = count_Res_Dir(dir2)
if b == 0 and a == 0:
return None
elif b > a:
return dir2
else:
return dir1
def asset_dir(directory):
dir1 = os.path.join(directory, 'assets')
dir2 = os.path.join(directory, 'src', 'main', 'assets')
a = count_Asset_Dir(dir1)
b = count_Asset_Dir(dir2)
if b == 0 and a == 0:
return None
elif b > a:
return dir2
else:
return dir1
def get_asset_from_apk(apk_filename, dest_dir):
with zipfile.ZipFile(apk_filename) as zf:
for member in zf.infolist():
path = dest_dir
if member.filename.startswith('assets/'):
zf.extract(member, path)
def count_Src_Dir2(directory, lastBuild=0, a_list=None):
count = 0
lastModified = 0
for dirpath, dirnames, files in os.walk(directory):
if re.findall(r'[/\\+]androidTest[/\\+]', dirpath) or '/.' in dirpath:
continue
for fn in files:
if fn.endswith('.java'):
count += 1
mt = os.path.getmtime(os.path.join(dirpath, fn))
lastModified = max(lastModified, mt)
if a_list != None and mt > lastBuild:
a_list.append(os.path.join(dirpath, fn))
return (count, lastModified)
def src_dir2(directory, lastBuild=0, alist=None):
for srcdir in [os.path.join(directory, 'src', 'main', 'java'), os.path.join(directory, 'src')]:
olist = None
if alist != None:
olist = []
(count, lastModified) = count_Src_Dir2(srcdir, lastBuild=lastBuild, a_list=olist)
if count > 0:
if alist != None:
alist.extend(olist)
return (srcdir, count, lastModified)
return (None, 0, 0)
def lib_dir(directory):
ddir = os.path.join(directory, 'libs')
if os.path.isdir(ddir):
return ddir
else:
return None
def is_launchable_project(directory):
if is_gradle_project(directory):
data = open_as_text(os.path.join(directory, 'build.gradle'))
data = remove_comments(data)
if re.findall(r'''apply\s+plugin:\s*['"]com.android.application['"]''', data, re.MULTILINE):
return True
elif os.path.isfile(os.path.join(directory, 'project.properties')):
data = open_as_text(os.path.join(directory, 'project.properties'))
if re.findall(r'''^\s*target\s*=.*$''', data, re.MULTILINE) and not re.findall(r'''^\s*android.library\s*=\s*true\s*$''', data, re.MULTILINE):
return True
return False
def __append_project(a_list, directory, depth):
if package_name(directory):
a_list.append(directory)
elif depth > 0:
for cname in os.listdir(directory):
if cname == 'build' or cname == 'bin':
continue
cdir = os.path.join(directory, cname)
if os.path.isdir(cdir):
__append_project(a_list, cdir, depth - 1)
def list_projects(directory):
a_list = []
if os.path.isfile(os.path.join(directory, 'settings.gradle')):
data = open_as_text(os.path.join(directory, 'settings.gradle'))
for line in re.findall(r'''include\s*(.+)''', data):
for proj in re.findall(r'''[\s,]+['"](.*?)['"]''', ',' + line):
dproj = (proj.startswith(':') and proj[1:] or proj).replace(':', os.path.sep)
cdir = os.path.join(directory, dproj)
if package_name(cdir):
a_list.append(cdir)
else:
__append_project(a_list, directory, 2)
return a_list
def list_aar_projects(directory, deps):
pnlist = [package_name(i) for i in deps]
pnlist.append(package_name(directory))
list1 = []
if os.path.isdir(os.path.join(directory, 'build', 'intermediates', 'incremental', 'mergeResources')):
for dirpath, dirnames, files in os.walk(os.path.join(directory, 'build', 'intermediates', 'incremental', 'mergeResources')):
if re.findall(r'[/\\+]androidTest[/\\+]', dirpath):
continue
for fn in files:
if fn == 'merger.xml':
data = open_as_text(os.path.join(dirpath, fn))
for s in re.findall(r'''path="([^"]+)"''', data):
(parent, child) = os.path.split(s)
if child.endswith('.xml') or child.endswith('.png') or child.endswith('.jpg'):
(parent, child) = os.path.split(parent)
if isRes_Name(child) and not parent in list1:
list1.append(parent)
elif os.path.isdir(s) and not s in list1 and count_Res_Dir(s) > 0:
list1.append(s)
# if os.path.isdir(os.path.join(directory, 'build', 'intermediates', 'exploded-aar')):
# for dirpath, dirnames, files in os.walk(os.path.join(directory, 'build', 'intermediates', 'exploded-aar')):
# if 'res' in dirnames:
# list1.append(os.path.join(dirpath,'res'))
list2 = []
for ppath in list1:
parpath = os.path.abspath(os.path.join(ppath, os.pardir))
pn = package_name(parpath)
if pn and not pn in pnlist:
list2.append(ppath)
return list2
def get_android_jar(path):
if not os.path.isdir(path):
return None
platforms = os.path.join(path, 'platforms')
if not os.path.isdir(platforms):
return None
api = 0
result = []
for pd in os.listdir(platforms):
pd = os.path.join(platforms, pd)
if os.path.isdir(pd) and os.path.isfile(os.path.join(pd, 'source.properties')) and os.path.isfile(os.path.join(pd, 'android.jar')):
s = open_as_text(os.path.join(pd, 'source.properties'))
m = re.search(r'^AndroidVersion.ApiLevel\s*[=:]\s*(.*)$', s, re.MULTILINE)
if m:
a = int(m.group(1))
if a > api:
api = a
result.append(os.path.join(pd, 'android.jar'))
api = 0
for pd in os.listdir(platforms):
pd = os.path.join(platforms, pd)
if os.path.isdir(pd) and os.path.isfile(os.path.join(pd, 'source.properties')) and os.path.isfile(os.path.join(pd, 'android.jar')):
s = open_as_text(os.path.join(pd, 'source.properties'))
m = re.search(r'^AndroidVersion.ApiLevel\s*[=:]\s*(.*)$', s, re.MULTILINE)
if m:
a = int(m.group(1))
if a > api and a < 23:
api = a
result.append(os.path.join(pd, 'android.jar'))
return result
def get_adb(path):
execname = os.name == 'nt' and 'adb.exe' or 'adb'
if os.path.isdir(path) and is_exe(os.path.join(path, 'platform-tools', execname)):
return os.path.join(path, 'platform-tools', execname)
def get_aapt(path):
execname = os.name == 'nt' and 'aapt.exe' or 'aapt'
if path and os.path.isdir(path) and os.path.isdir(os.path.join(path, 'build-tools')):
btpath = os.path.join(path, 'build-tools')
minv = LooseVersion('0')
minp = None
for pn in os.listdir(btpath):
if is_exe(os.path.join(btpath, pn, execname)):
if LooseVersion(pn) > minv:
minv = LooseVersion(pn)
minp = os.path.join(btpath, pn, execname)
return minp
def get_dx(path):
execname = os.name == 'nt' and 'dx.bat' or 'dx'
if os.path.isdir(path) and os.path.isdir(os.path.join(path, 'build-tools')):
btpath = os.path.join(path, 'build-tools')
minv = LooseVersion('0')
minp = None
for pn in os.listdir(btpath):
if is_exe(os.path.join(btpath, pn, execname)):
if LooseVersion(pn) > minv:
minv = LooseVersion(pn)
minp = os.path.join(btpath, pn, execname)
return minp
def get_android_sdk(directory, condf=get_android_jar):
s = open_as_text(os.path.join(directory, 'local.properties'))
m = re.search(r'^sdk.directory\s*[=:]\s*(.*)$', s, re.MULTILINE)
if m:
val = m.group(1).replace('\\:', ':').replace('\\=', '=').replace('\\\\', '\\')
if os.path.isdir(val) and condf(val):
return val
path = os.getenv('ANDROID_HOME')
if path and os.path.isdir(path) and condf(path):
return path
path = os.getenv('ANDROID_SDK')
if path and os.path.isdir(path) and condf(path):
return path
# mac
path = os.path.expanduser('~/Library/Android/sdk')
if path and os.path.isdir(path) and condf(path):
return path
# windows
path = os.path.expanduser('~/AppData/Local/Android/sdk')
if path and os.path.isdir(path) and condf(path):
return path
def get_javac(directory):
execname = os.name == 'nt' and 'javac.exe' or 'javac'
if directory and os.path.isfile(os.path.join(directory, 'bin', execname)):
return os.path.join(directory, 'bin', execname)
wpath = which(execname)
if wpath:
return wpath
path = os.getenv('JAVA_HOME')
if path and is_exe(os.path.join(path, 'bin', execname)):
return os.path.join(path, 'bin', execname)
if os.name == 'nt':
btpath = 'C:\\Program Files\\Java'
if os.path.isdir(btpath):
minv = ''
minp = None
for pn in os.listdir(btpath):
path = os.path.join(btpath, pn, 'bin', execname)
if is_exe(path):
if pn > minv:
minv = pn
minp = path
return minp
else:
for btpath in ['/Library/Java/JavaVirtualMachines', '/System/Library/Java/JavaVirtualMachines']:
if os.path.isdir(btpath):
minv = ''
minp = None
for pn in os.listdir(btpath):
path = os.path.join(btpath, pn, 'Contents', 'Home', 'bin', execname)
if is_exe(path):
if pn > minv:
minv = pn
minp = path
if minp:
return minp
def search_path(directory, filename):
dir0 = filename
if os.path.sep in filename:
dir0 = filename[0:filename.index(os.path.sep)]
a_list = []
parpath = None
for dirpath, dirnames, files in os.walk(directory):
if re.findall(r'[/\\+]androidTest[/\\+]', dirpath) or '/.' in dirpath:
continue
if dir0 in dirnames:
parpath = dirpath
break;
if parpath:
for dirpath, dirnames, files in os.walk(parpath):
if 'R.class' in files:
print parpath
a_list.append(parpath)
break;
if len(a_list) == 1:
return a_list[0]
elif len(a_list) > 1:
maxt = 0
maxd = None
for ddir in a_list:
lastModified = 0
for dirpath, dirnames, files in os.walk(directory):
for fn in files:
if fn.endswith('.class'):
lastModified = os.path.getmtime(os.path.join(dirpath, fn))
if lastModified > maxt:
maxt = lastModified
maxd = ddir
return maxd
else:
if os.path.sep in filename:
filename_pre = filename[0:filename.rfind(os.path.sep)]
print filename_pre
return os.path.join(directory, 'debug')
def get_maven_libs(projs):
maven_deps = []
for proj in projs:
sFile = open_as_text(os.path.join(proj, 'build.gradle'))
sFile = remove_comments(sFile)
for m in re.finditer(r'dependencies\s*\{', sFile):
depends = balanced_braces(sFile[m.start():])
for mvndep in re.findall(r'''compile\s+['"](.+:.+:.+)(?:@*)?['"]''', depends):
mvndeps = mvndep.split(':')
if not mvndeps in maven_deps:
maven_deps.append(mvndeps)
return maven_deps
def get_maven_jars(libs):
if not libs:
return []
jars = []
maven_path_prefix = []
# ~/.gralde/caches
gradle_home = os.path.join(os.path.expanduser('~'), '.gradle', 'caches')
for dirpath, dirnames, files in os.walk(gradle_home):
# search in ~/.gradle/**/GROUP_ID/ARTIFACT_ID/VERSION/**/*.jar
for mvndeps in libs:
if mvndeps[0] in dirnames:
dir1 = os.path.join(dirpath, mvndeps[0], mvndeps[1])
if os.path.isdir(dir1):
dir2 = os.path.join(dir1, mvndeps[2])
if os.path.isdir(dir2):
maven_path_prefix.append(dir2)
else:
prefix = mvndeps[2]
if '+' in prefix:
prefix = prefix[0:prefix.index('+')]
maxdir = ''
for subd in os.listdir(dir1):
if subd.startswith(prefix) and subd > maxdir:
maxdir = subd
if maxdir:
maven_path_prefix.append(os.path.join(dir1, maxdir))
for dirprefix in maven_path_prefix:
if dirpath.startswith(dirprefix):
for fn in files:
if fn.endswith('.jar') and not fn.startswith('.') and not fn.endswith('-sources.jar') and not fn.endswith('-javadoc.jar'):
jars.append(os.path.join(dirpath, fn))
break
return jars
def get_resource_xml(content):
if content:
mathrul = "attr|iD|style|string|dimen|color|array|drawable|layout|anim|integer|animator|interpolator|transition|raw"
output = re.finditer(r'resource (0x7f[0-f]{6}).*(' + mathrul + ')\/(.+)\:.*', content)
idsnum = []
publicxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<resources>\n"
idsxml = publicxml
for match in output:
iD = str(match.group(1))
if iD not in idsnum:
idsnum.append(iD)
publicinfo = " <public type=\"" + str(match.group(2)) + "\" name=\"" + str(match.group(3)) + "\" iD=\"" + str(match.group(1)) + "\" />\n"
publicxml += publicinfo
if str(match.group(2)) == "iD":
idinfo = " <item type=\"iD\" name=\"" + str(match.group(3)) + "\" />\n"
idsxml += idinfo
publicxml += "</resources>"
idsxml += "</resources>"
return (publicxml, idsxml)
def scan_port(adbpath, pnlist, projlist):
port = 0
prodir = None
packagename = None
for i in range(0, 10):
cexec([adbpath, 'forward', 'tcp:%d' % (41128 + i), 'tcp:%d' % (41128 + i)])
output = curl('http://127.0.0.1:%d/packagename' % (41128 + i), ignoreError=True)
if output and output in pnlist:
index = pnlist.index(output) # index of this app in projlist
state = curl('http://127.0.0.1:%d/appstate' % (41128 + i), ignoreError=True)
if state and int(state) >= 2:
port = 41128 + i
prodir = projlist[index]
packagename = output
break
for i in range(0, 10):
if (41128 + i) != port:
cexec([adbpath, 'forward', '--remove', 'tcp:%d' % (41128 + i)], callback=None)
return port, prodir, packagename
# Get only the resources that exists in the local project
# Fix for the "appcompat like" libs
def filter_public_xml(args, code, stdout, stderr):
if code != 0 and re.search(r"declared here is not defined.", stderr):
listMatches = re.findall(r"(?<=error: Public symbol ).+(?= declared here is not defined)", stderr)
if os.path.exists(os.path.join(binresdir, "values", "public.xml")):
publicXml = open(os.path.join(binresdir, "values", "public.xml"), "r")
tempStr = ""
listMatchesSplitted = []
for mt in listMatches:
listMatchesSplitted.append(mt.split("/"))
for line in publicXml.readlines():
isMatch = True
for mt in listMatchesSplitted:
if line.find(mt[0]) > -1 and line.find(mt[1]) > -1:
isMatch = False
break
if isMatch:
tempStr += line
publicXml = open(os.path.join(binresdir, "values", "public.xml"), "w")
publicXml.write(tempStr)
publicXml.close()
cexec(args, cexec_fail_exit, exitcode=18)
else:
cexec_fail_exit(args, code, stdout, stderr)
if __name__ == "__main__":
directory = '.'
sdkdir = None
jdkdir = None
starttime = time.time()
if len(sys.argv) > 1:
parser = argparse.ArgumentParser()
parser.add_argument('--sdk', help='specify Android SDK path')
parser.add_argument('--jdk', help='specify JDK path')
parser.add_argument('project')
args = parser.parse_args()
if args.sdk:
sdkdir = args.sdk
if args.jdk:
jdkdir = args.jdk
if args.project:
directory = args.project
projlist = [i for i in list_projects(directory) if is_launchable_project(i)]
if not sdkdir:
sdkdir = get_android_sdk(directory)
if not sdkdir:
print('android sdk not found, specify in local.properties or export ANDROID_HOME')
exit(2)
if not projlist:
print('no valid android project found in ' + os.path.abspath(directory))
exit(3)
pnlist = [package_name_fromapk(i, sdkdir) for i in projlist]
portlist = [0 for i in pnlist]
adbpath = get_adb(sdkdir)
if not adbpath:
print('adb not found in %s/platform-tools' % sdkdir)
exit(4)
port, directory, packagename = scan_port(adbpath, pnlist, projlist)
if port == 0:
# launch app
latest_package = get_latest_packagename(projlist, sdkdir)
if latest_package:
cexec([adbpath, 'shell', 'monkey', '-p', latest_package, '-c', 'android.intent.category.LAUNCHER', '1'], callback=None)
for i in range(0, 6):
# try 6 times to wait the application launches
port, directory, packagename = scan_port(adbpath, pnlist, projlist)
if port:
break
time.sleep(0.25)
if port == 0:
print('package %s not found, make sure your project is properly setup and running' % (len(pnlist) == 1 and pnlist[0] or pnlist))
exit(5)
is_gradle = is_gradle_project(directory)
android_jar = get_android_jar(sdkdir)
if not android_jar:
print('android.jar not found !!!\nUse local.properties or set ANDROID_HOME env')
exit(7)
deps = deps_list(directory)
bindir = is_gradle and os.path.join(directory, 'build', 'lcast') or os.path.join(directory, 'bin', 'lcast')
if not os.path.exists(os.path.join(bindir, "lastBuildSrc")): # just to initiate files if not exists
open(os.path.join(bindir, "lastBuildSrc"), "w").write("0")
# check if the /res and /src has changed
lastBuild = 0
rdir = is_gradle and os.path.join(directory, 'build', 'outputs', 'apk') or os.path.join(directory, 'bin')
if os.path.isdir(rdir):
for fn in os.listdir(rdir):
if fn.endswith('.apk') and not '-androidTest' in fn:
fpath = os.path.join(rdir, fn)
lastBuild = max(lastBuild, os.path.getmtime(fpath))
adeps = []
adeps.extend(deps)
adeps.append(directory)
latestResModified = 0
latestSrcModified = 0
srcs = []
msrclist = []
assetdirs = []
for dep in adeps:
adir = asset_dir(dep)
if adir:
latestModified = os.path.getmtime(adir)
for dirpath, dirnames, files in os.walk(adir):
for dirname in dirnames:
if not dirname.startswith('.'):
latestModified = max(latestModified, os.path.getmtime(os.path.join(dirpath, dirname)))
for fn in files:
if not fn.startswith('.'):
fpath = os.path.join(dirpath, fn)
latestModified = max(latestModified, os.path.getmtime(fpath))
latestResModified = max(latestResModified, latestModified)
if latestModified > lastBuild:
assetdirs.append(adir)
rdir = res_dir(dep)
if rdir:
for subd in os.listdir(rdir):
if os.path.isdir(os.path.join(rdir, subd)) and isRes_Name(subd):
for fn in os.listdir(os.path.join(rdir, subd)):
fpath = os.path.join(rdir, subd, fn)
if os.path.isfile(fpath) and not fn.startswith('.'):
latestResModified = max(latestResModified, os.path.getmtime(fpath))
(sdir, scount, smt) = src_dir2(dep, lastBuild=lastBuild, alist=msrclist)
if sdir:
srcs.append(sdir)
latestSrcModified = max(latestSrcModified, smt)
resModified = latestResModified > lastBuild
srcModified = latestSrcModified > lastBuild and round(latestSrcModified * 100) > round(float(open(os.path.join(bindir, "lastBuildSrc"), "r").read()) * 100)
targets = ''
if resModified and srcModified:
targets = 'both /res and /src'
open(os.path.join(bindir, "lastBuildSrc"), "w").write(str(latestSrcModified))
elif resModified:
targets = '/res'
elif srcModified:
targets = '/src'
open(os.path.join(bindir, "lastBuildSrc"), "w").write(str(latestSrcModified))
else:
print('%s has no /res or /src changes' % (packagename))
open(os.path.join(bindir, "lastBuildSrc"), "w").write("0")
exit(0)
if is_gradle:
print('cast %s:%d as gradle project with %s changed (v%s)' % (packagename, port, targets, __version__))
else:
print('cast %s:%d as eclipse project with %s changed (v%s)' % (packagename, port, targets, __version__))
# prepare to reset
if srcModified:
curl('http://127.0.0.1:%d/pcast' % port, ignoreError=True)
if resModified:
binresdir = os.path.join(bindir, 'res')
if not os.path.exists(os.path.join(binresdir, 'values')):
os.makedirs(os.path.join(binresdir, 'values'))
data = curl('http://127.0.0.1:%d/ids.xml' % port, exitcode=8)
with open(os.path.join(binresdir, 'values/ids.xml'), 'w') as fp:
fp.write(data)
data = curl('http://127.0.0.1:%d/public.xml' % port, exitcode=9)
with open(os.path.join(binresdir, 'values/public.xml'), 'w') as fp:
fp.write(data)
# Get the assets path
apk_path = get_apk_path(directory)
if apk_path:
assets_path = os.path.join(bindir, "assets")
if os.path.isdir(assets_path):
shutil.rmtree(assets_path)
get_asset_from_apk(apk_path, bindir)
aaptpath = get_aapt(sdkdir)
if not aaptpath:
print('aapt not found in %s/build-tools' % sdkdir)
exit(10)
aaptargs = [aaptpath, 'package', '-f', '--auto-add-overlay', '-F', os.path.join(bindir, 'res.zip')]
aaptargs.append('-S')
aaptargs.append(binresdir)
rdir = res_dir(directory)
if rdir:
aaptargs.append('-S')
aaptargs.append(rdir)
for dep in reversed(deps):
rdir = res_dir(dep)
if rdir:
aaptargs.append('-S')
aaptargs.append(rdir)
if is_gradle:
for dep in reversed(list_aar_projects(directory, deps)):
aaptargs.append('-S')
aaptargs.append(dep)
for asset_dir in assetdirs:
aaptargs.append('-A')
aaptargs.append(asset_dir)
if os.path.isdir(assets_path):
aaptargs.append('-A')
aaptargs.append(assets_path)
aaptargs.append('-M')
aaptargs.append(manifest_path(directory))
for andr_jar in android_jar:
aaptargs.append('-I')
aaptargs.append(andr_jar)
cexec(aaptargs, filter_public_xml, exitcode=18)
with open(os.path.join(bindir, 'res.zip'), 'rb') as fp:
curl('http://127.0.0.1:%d/pushres' % port, body=fp.read(), exitcode=11)
if srcModified:
vmversion = curl('http://127.0.0.1:%d/vmversion' % port, ignoreError=True)
if vmversion == None:
vmversion = ''
if vmversion.startswith('1') or vmversion.startswith('2'):
javac = get_javac(jdkdir)
if not javac:
print('javac is required to compile java code, config your PATH to include javac')
exit(12)
launcher = curl('http://127.0.0.1:%d/launcher' % port, exitcode=13)
classpath = android_jar
for dep in adeps:
dlib = lib_dir(dep)
if dlib:
for fjar in os.listdir(dlib):
if fjar.endswith('.jar'):
classpath.append(os.path.join(dlib, fjar))
if is_gradle:
# jars from maven cache
maven_libs = get_maven_libs(adeps)
maven_libs_cache_file = os.path.join(bindir, 'cache-javac-maven.json')
maven_libs_cache = {}
if os.path.isfile(maven_libs_cache_file):
try:
with open(maven_libs_cache_file, 'r') as fp:
maven_libs_cache = json.load(fp)
except:
pass
if maven_libs_cache.get('version') != 1 or not maven_libs_cache.get('from') or sorted(maven_libs_cache['from']) != sorted(maven_libs):
if os.path.isfile(maven_libs_cache_file):
os.remove(maven_libs_cache_file)
maven_libs_cache = {}
maven_jars = []
if maven_libs_cache:
maven_jars = maven_libs_cache.get('jars')
elif maven_libs:
maven_jars = get_maven_jars(maven_libs)
cache = {'version': 1, 'from': maven_libs, 'jars': maven_jars}
try:
with open(maven_libs_cache_file, 'w') as fp:
json.dump(cache, fp)
except:
pass
if maven_jars:
classpath.extend(maven_jars)
# aars from exploded-aar
darr = os.path.join(directory, 'build', 'intermediates', 'exploded-aar')
# TODO: use the max version
for dirpath, dirnames, files in os.walk(darr):
if re.findall(r'[/\\+]androidTest[/\\+]', dirpath) or '/.' in dirpath:
continue
for fn in files:
if fn.endswith('.jar'):
classpath.append(os.path.join(dirpath, fn))
# R.class
classesdir = search_path(os.path.join(directory, 'build', 'intermediates', 'classes'), launcher and launcher.replace('.', os.path.sep) + '.class' or '$')
classpath.append(classesdir)