OLD | NEW |
| (Empty) |
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 """Gathers information about APKs.""" | |
6 | |
7 import collections | |
8 import logging | |
9 import os | |
10 import pickle | |
11 import re | |
12 | |
13 import cmd_helper | |
14 | |
15 # If you change the cached output of proguard, increment this number | |
16 PICKLE_FORMAT_VERSION = 1 | |
17 | |
18 def GetPackageNameForApk(apk_path): | |
19 """Returns the package name of the apk file.""" | |
20 aapt_output = cmd_helper.GetCmdOutput( | |
21 ['aapt', 'dump', 'badging', apk_path]).split('\n') | |
22 package_name_re = re.compile(r'package: .*name=\'(\S*)\'') | |
23 for line in aapt_output: | |
24 m = package_name_re.match(line) | |
25 if m: | |
26 return m.group(1) | |
27 raise Exception('Failed to determine package name of %s' % apk_path) | |
28 | |
29 | |
30 class ApkInfo(object): | |
31 """Helper class for inspecting APKs.""" | |
32 | |
33 def __init__(self, apk_path, jar_path): | |
34 self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_SDK_ROOT'], | |
35 'tools/proguard/bin/proguard.sh') | |
36 if not os.path.exists(self._PROGUARD_PATH): | |
37 self._PROGUARD_PATH = os.path.join(os.environ['ANDROID_BUILD_TOP'], | |
38 'external/proguard/bin/proguard.sh') | |
39 self._PROGUARD_CLASS_RE = re.compile(r'\s*?- Program class:\s*([\S]+)$') | |
40 self._PROGUARD_METHOD_RE = re.compile(r'\s*?- Method:\s*(\S*)[(].*$') | |
41 self._PROGUARD_ANNOTATION_RE = re.compile(r'\s*?- Annotation \[L(\S*);\]:$') | |
42 self._PROGUARD_ANNOTATION_CONST_RE = ( | |
43 re.compile(r'\s*?- Constant element value.*$')) | |
44 self._PROGUARD_ANNOTATION_VALUE_RE = re.compile(r'\s*?- \S+? \[(.*)\]$') | |
45 | |
46 if not os.path.exists(apk_path): | |
47 raise Exception('%s not found, please build it' % apk_path) | |
48 self._apk_path = apk_path | |
49 if not os.path.exists(jar_path): | |
50 raise Exception('%s not found, please build it' % jar_path) | |
51 self._jar_path = jar_path | |
52 self._annotation_map = collections.defaultdict(list) | |
53 self._pickled_proguard_name = self._jar_path + '-proguard.pickle' | |
54 self._test_methods = [] | |
55 self._Initialize() | |
56 | |
57 def _Initialize(self): | |
58 if not self._GetCachedProguardData(): | |
59 self._GetProguardData() | |
60 | |
61 def _GetCachedProguardData(self): | |
62 if (os.path.exists(self._pickled_proguard_name) and | |
63 (os.path.getmtime(self._pickled_proguard_name) > | |
64 os.path.getmtime(self._jar_path))): | |
65 logging.info('Loading cached proguard output from %s', | |
66 self._pickled_proguard_name) | |
67 try: | |
68 with open(self._pickled_proguard_name, 'r') as r: | |
69 d = pickle.loads(r.read()) | |
70 if d['VERSION'] == PICKLE_FORMAT_VERSION: | |
71 self._annotation_map = d['ANNOTATION_MAP'] | |
72 self._test_methods = d['TEST_METHODS'] | |
73 return True | |
74 except: | |
75 logging.warning('PICKLE_FORMAT_VERSION has changed, ignoring cache') | |
76 return False | |
77 | |
78 def _GetProguardData(self): | |
79 proguard_output = cmd_helper.GetCmdOutput([self._PROGUARD_PATH, | |
80 '-injars', self._jar_path, | |
81 '-dontshrink', | |
82 '-dontoptimize', | |
83 '-dontobfuscate', | |
84 '-dontpreverify', | |
85 '-dump', | |
86 ]).split('\n') | |
87 clazz = None | |
88 method = None | |
89 annotation = None | |
90 has_value = False | |
91 qualified_method = None | |
92 for line in proguard_output: | |
93 m = self._PROGUARD_CLASS_RE.match(line) | |
94 if m: | |
95 clazz = m.group(1).replace('/', '.') # Change package delim. | |
96 annotation = None | |
97 continue | |
98 | |
99 m = self._PROGUARD_METHOD_RE.match(line) | |
100 if m: | |
101 method = m.group(1) | |
102 annotation = None | |
103 qualified_method = clazz + '#' + method | |
104 if method.startswith('test') and clazz.endswith('Test'): | |
105 self._test_methods += [qualified_method] | |
106 continue | |
107 | |
108 if not qualified_method: | |
109 # Ignore non-method annotations. | |
110 continue | |
111 | |
112 m = self._PROGUARD_ANNOTATION_RE.match(line) | |
113 if m: | |
114 annotation = m.group(1).split('/')[-1] # Ignore the annotation package. | |
115 self._annotation_map[qualified_method].append(annotation) | |
116 has_value = False | |
117 continue | |
118 if annotation: | |
119 if not has_value: | |
120 m = self._PROGUARD_ANNOTATION_CONST_RE.match(line) | |
121 if m: | |
122 has_value = True | |
123 else: | |
124 m = self._PROGUARD_ANNOTATION_VALUE_RE.match(line) | |
125 if m: | |
126 value = m.group(1) | |
127 self._annotation_map[qualified_method].append( | |
128 annotation + ':' + value) | |
129 has_value = False | |
130 | |
131 logging.info('Storing proguard output to %s', self._pickled_proguard_name) | |
132 d = {'VERSION': PICKLE_FORMAT_VERSION, | |
133 'ANNOTATION_MAP': self._annotation_map, | |
134 'TEST_METHODS': self._test_methods} | |
135 with open(self._pickled_proguard_name, 'w') as f: | |
136 f.write(pickle.dumps(d)) | |
137 | |
138 def _GetAnnotationMap(self): | |
139 return self._annotation_map | |
140 | |
141 def _IsTestMethod(self, test): | |
142 class_name, method = test.split('#') | |
143 return class_name.endswith('Test') and method.startswith('test') | |
144 | |
145 def GetApkPath(self): | |
146 return self._apk_path | |
147 | |
148 def GetPackageName(self): | |
149 """Returns the package name of this APK.""" | |
150 return GetPackageNameForApk(self._apk_path) | |
151 | |
152 def GetTestAnnotations(self, test): | |
153 """Returns a list of all annotations for the given |test|. May be empty.""" | |
154 if not self._IsTestMethod(test): | |
155 return [] | |
156 return self._GetAnnotationMap()[test] | |
157 | |
158 def _AnnotationsMatchFilters(self, annotation_filter_list, annotations): | |
159 """Checks if annotations match any of the filters.""" | |
160 if not annotation_filter_list: | |
161 return True | |
162 for annotation_filter in annotation_filter_list: | |
163 filters = annotation_filter.split('=') | |
164 if len(filters) == 2: | |
165 key = filters[0] | |
166 value_list = filters[1].split(',') | |
167 for value in value_list: | |
168 if key + ':' + value in annotations: | |
169 return True | |
170 elif annotation_filter in annotations: | |
171 return True | |
172 return False | |
173 | |
174 def GetAnnotatedTests(self, annotation_filter_list): | |
175 """Returns a list of all tests that match the given annotation filters.""" | |
176 return [test for test, annotations in self._GetAnnotationMap().iteritems() | |
177 if self._IsTestMethod(test) and self._AnnotationsMatchFilters( | |
178 annotation_filter_list, annotations)] | |
179 | |
180 def GetTestMethods(self): | |
181 """Returns a list of all test methods in this apk as Class#testMethod.""" | |
182 return self._test_methods | |
183 | |
184 @staticmethod | |
185 def IsPythonDrivenTest(test): | |
186 return 'pythonDrivenTests' in test | |
OLD | NEW |