1 # Copyright (c) 2013 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.
5 """Module containing utilities for apk packages."""
10 from pylib import cmd_helper
11 from pylib import constants
14 _AAPT_PATH = os.path.join(constants.ANDROID_SDK_TOOLS, 'aapt')
15 _MANIFEST_ATTRIBUTE_RE = re.compile(
16 r'\s*A: ([^\(\)= ]*)\([^\(\)= ]*\)="(.*)" \(Raw: .*\)$')
17 _MANIFEST_ELEMENT_RE = re.compile(r'\s*(?:E|N): (\S*) .*$')
20 def GetPackageName(apk_path):
21 """Returns the package name of the apk."""
22 aapt_cmd = [_AAPT_PATH, 'dump', 'badging', apk_path]
23 aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
24 package_name_re = re.compile(r'package: .*name=\'(\S*)\'')
25 for line in aapt_output:
26 m = package_name_re.match(line)
29 raise Exception('Failed to determine package name of %s' % apk_path)
32 def _ParseManifestFromApk(apk_path):
33 aapt_cmd = [_AAPT_PATH, 'dump', 'xmltree', apk_path, 'AndroidManifest.xml']
34 aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
37 node_stack = [parsed_manifest]
40 for line in aapt_output[1:]:
45 while line[(len(indent) * indent_depth):].startswith(indent):
48 node_stack = node_stack[:indent_depth]
51 m = _MANIFEST_ELEMENT_RE.match(line[len(indent) * indent_depth:])
53 if not m.group(1) in node:
55 node_stack += [node[m.group(1)]]
58 m = _MANIFEST_ATTRIBUTE_RE.match(line[len(indent) * indent_depth:])
60 if not m.group(1) in node:
62 node[m.group(1)].append(m.group(2))
65 return parsed_manifest
68 def GetInstrumentationName(
69 apk_path, default='android.test.InstrumentationTestRunner'):
70 """Returns the name of the Instrumentation in the apk."""
73 manifest_info = _ParseManifestFromApk(apk_path)
74 return manifest_info['manifest']['instrumentation']['android:name'][0]