summaryrefslogtreecommitdiffstats
path: root/build/android/pylib/utils/apk_helper.py
blob: 6dd209e3dc17960691937220c68c4f1cbadd28ff (plain)
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
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Module containing utilities for apk packages."""

import os.path
import re

from pylib import cmd_helper
from pylib import constants


_AAPT_PATH = os.path.join(constants.ANDROID_SDK_TOOLS, 'aapt')
_MANIFEST_ATTRIBUTE_RE = re.compile(
    r'\s*A: ([^\(\)= ]*)\([^\(\)= ]*\)="(.*)" \(Raw: .*\)$')
_MANIFEST_ELEMENT_RE = re.compile(r'\s*(?:E|N): (\S*) .*$')


def GetPackageName(apk_path):
  """Returns the package name of the apk."""
  return ApkHelper(apk_path).GetPackageName()


# TODO(jbudorick): Deprecate and remove this function once callers have been
# converted to ApkHelper.GetInstrumentationName
def GetInstrumentationName(apk_path):
  """Returns the name of the Instrumentation in the apk."""
  return ApkHelper(apk_path).GetInstrumentationName()


def _ParseManifestFromApk(apk_path):
  aapt_cmd = [_AAPT_PATH, 'dump', 'xmltree', apk_path, 'AndroidManifest.xml']
  aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')

  parsed_manifest = {}
  node_stack = [parsed_manifest]
  indent = '  '

  for line in aapt_output[1:]:
    if len(line) == 0:
      continue

    indent_depth = 0
    while line[(len(indent) * indent_depth):].startswith(indent):
      indent_depth += 1

    node_stack = node_stack[:indent_depth]
    node = node_stack[-1]

    m = _MANIFEST_ELEMENT_RE.match(line[len(indent) * indent_depth:])
    if m:
      if not m.group(1) in node:
        node[m.group(1)] = {}
      node_stack += [node[m.group(1)]]
      continue

    m = _MANIFEST_ATTRIBUTE_RE.match(line[len(indent) * indent_depth:])
    if m:
      if not m.group(1) in node:
        node[m.group(1)] = []
      node[m.group(1)].append(m.group(2))
      continue

  return parsed_manifest


class ApkHelper(object):
  def __init__(self, apk_path):
    self._apk_path = apk_path
    self._manifest = None
    self._package_name = None

  def GetActivityName(self):
    """Returns the name of the Activity in the apk."""
    manifest_info = self._GetManifest()
    try:
      activity = (
          manifest_info['manifest']['application']['activity']
              ['android:name'][0])
    except KeyError:
      return None
    if '.' not in activity:
      activity = '%s.%s' % (self.GetPackageName(), activity)
    elif activity.startswith('.'):
      activity = '%s%s' % (self.GetPackageName(), activity)
    return activity

  def GetInstrumentationName(
      self, default='android.test.InstrumentationTestRunner'):
    """Returns the name of the Instrumentation in the apk."""
    manifest_info = self._GetManifest()
    try:
      return manifest_info['manifest']['instrumentation']['android:name'][0]
    except KeyError:
      return default

  def GetPackageName(self):
    """Returns the package name of the apk."""
    if self._package_name:
      return self._package_name

    aapt_cmd = [_AAPT_PATH, 'dump', 'badging', self._apk_path]
    aapt_output = cmd_helper.GetCmdOutput(aapt_cmd).split('\n')
    package_name_re = re.compile(r'package: .*name=\'(\S*)\'')
    for line in aapt_output:
      m = package_name_re.match(line)
      if m:
        self._package_name = m.group(1)
        return self._package_name
    raise Exception('Failed to determine package name of %s' % self._apk_path)

  def _GetManifest(self):
    if not self._manifest:
      self._manifest = _ParseManifestFromApk(self._apk_path)
    return self._manifest