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.
4
5"""Module containing utilities for apk packages."""
6
7import os.path
8import re
9
10from pylib import cmd_helper
11from pylib import constants
12
13
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*) .*$')
18
19
20def 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)
27    if m:
28      return m.group(1)
29  raise Exception('Failed to determine package name of %s' % apk_path)
30
31
32def _ParseManifestFromApk(apk_path):
33  aapt_cmd = [_AAPT_PATH, 'dump', 'xmltree', apk_path, 'AndroidManifest.xml']
34  aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
35
36  parsed_manifest = {}
37  node_stack = [parsed_manifest]
38  indent = '  '
39
40  for line in aapt_output[1:]:
41    if len(line) == 0:
42      continue
43
44    indent_depth = 0
45    while line[(len(indent) * indent_depth):].startswith(indent):
46      indent_depth += 1
47
48    node_stack = node_stack[:indent_depth]
49    node = node_stack[-1]
50
51    m = _MANIFEST_ELEMENT_RE.match(line[len(indent) * indent_depth:])
52    if m:
53      if not m.group(1) in node:
54        node[m.group(1)] = {}
55      node_stack += [node[m.group(1)]]
56      continue
57
58    m = _MANIFEST_ATTRIBUTE_RE.match(line[len(indent) * indent_depth:])
59    if m:
60      if not m.group(1) in node:
61        node[m.group(1)] = []
62      node[m.group(1)].append(m.group(2))
63      continue
64
65  return parsed_manifest
66
67
68def GetInstrumentationName(
69    apk_path, default='android.test.InstrumentationTestRunner'):
70  """Returns the name of the Instrumentation in the apk."""
71
72  try:
73    manifest_info = _ParseManifestFromApk(apk_path)
74    return manifest_info['manifest']['instrumentation']['android:name'][0]
75  except KeyError:
76    return default
77