File: list_java_targets.py

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (311 lines) | stat: -rwxr-xr-x 10,380 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python3
# Copyright 2020 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Lint as: python3
"""Prints out available java targets.

Examples:
# List GN target for bundles:
build/android/list_java_targets.py -C out/Default --type android_app_bundle \
--gn-labels

# List all android targets with types:
build/android/list_java_targets.py -C out/Default --print-types

# Build all apk targets:
build/android/list_java_targets.py -C out/Default --type android_apk | xargs \
autoninja -C out/Default

# Show how many of each target type exist:
build/android/list_java_targets.py -C out/Default --stats

"""

import argparse
import collections
import json
import logging
import os
import shlex
import subprocess
import sys

_SRC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..',
                                          '..'))
sys.path.append(os.path.join(_SRC_ROOT, 'build'))
import gn_helpers

sys.path.append(os.path.join(_SRC_ROOT, 'build', 'android'))
from pylib import constants

_VALID_TYPES = (
    'android_apk',
    'android_app_bundle',
    'android_app_bundle_module',
    'android_assets',
    'android_resources',
    'dist_aar',
    'dist_jar',
    'group',
    'java_annotation_processor',
    'java_binary',
    'java_library',
    'robolectric_binary',
    'system_java_library',
)


def _compile(output_dir, args, quiet=False):
  cmd = gn_helpers.CreateBuildCommand(output_dir) + args
  logging.info('Running: %s', shlex.join(cmd))
  if quiet:
    subprocess.run(cmd, check=True, capture_output=True)
  else:
    subprocess.run(cmd, check=True, stdout=sys.stderr)


def _query_for_build_config_targets(output_dir):
  # Query ninja rather than GN since it's faster.
  cmd = [
      os.path.join(_SRC_ROOT, 'third_party', 'siso', 'cipd', 'siso'), 'query',
      'targets', '-C', output_dir
  ]
  logging.info('Running: %r', cmd)
  try:
    query_output = subprocess.run(cmd,
                                  check=True,
                                  capture_output=True,
                                  encoding='ascii').stdout
  except subprocess.CalledProcessError as e:
    sys.stderr.write('Command output:\n' + e.stdout + e.stderr)
    raise

  ret = []
  SUFFIX = '__build_config_crbug_908819'
  SUFFIX_LEN = len(SUFFIX)
  for line in query_output.splitlines():
    ninja_target = line.rsplit(':', 1)[0]
    # Ignore root aliases by ensuring a : exists.
    if ':' in ninja_target and ninja_target.endswith(SUFFIX):
      ret.append(f'//{ninja_target[:-SUFFIX_LEN]}')
  return ret


def _query_json(*, json_dict: dict, query: str, path: str):
  """Traverses through the json dictionary according to the query.

  If at any point a key does not exist, return the empty string, but raise an
  error if a key exists but is the wrong type.

  This is roughly equivalent to returning
  json_dict[queries[0]]?[queries[1]]?...[queries[N]]? where the ? means that if
  the key doesn't exist, the empty string is returned.

  Example:
  Given json_dict = {'a': {'b': 'c'}}
  - If queries = ['a', 'b']
    Return: 'c'
  - If queries = ['a', 'd']
    Return ''
  - If queries = ['x']
    Return ''
  - If queries = ['a', 'b', 'x']
    Raise an error since json_dict['a']['b'] is the string 'c' instead of an
    expected dict that can be indexed into.

  Returns the final result after exhausting all the queries.
  """
  queries = query.split('.')
  value = json_dict
  try:
    for key in queries:
      value = value.get(key)
      if value is None:
        return ''
  except AttributeError as e:
    raise Exception(
        f'Failed when attempting to get {queries} from {path}') from e
  return value


class _TargetEntry:

  def __init__(self, gn_target):
    assert gn_target.startswith('//'), f'{gn_target} does not start with //'
    assert ':' in gn_target, f'Non-root {gn_target} required'
    self.gn_target = gn_target
    self._build_config = None

  @property
  def ninja_target(self):
    return self.gn_target[2:]

  @property
  def ninja_build_config_target(self):
    return self.ninja_target + '__build_config_crbug_908819'

  @property
  def build_config_path(self):
    """Returns the filepath of the project's .build_config.json."""
    ninja_target = self.ninja_target
    # Support targets at the root level. e.g. //:foo
    if ninja_target[0] == ':':
      ninja_target = ninja_target[1:]
    subpath = ninja_target.replace(':', os.path.sep) + '.build_config.json'
    return os.path.relpath(
        os.path.join(constants.GetOutDirectory(), 'gen', subpath))

  @property
  def params_path(self):
    """Returns the filepath of the project's .params.json."""
    return self.build_config_path.replace('.build_config.json', '.params.json')

  def build_config(self):
    """Reads and returns the project's .build_config.json JSON."""
    if not self._build_config:
      with open(self.params_path) as f:
        config = json.load(f)
      with open(self.build_config_path) as f:
        config.update(json.load(f))
      self._build_config = config
    return self._build_config

  def get_type(self):
    """Returns the target type from its .build_config.json."""
    return self.build_config()['type']

  def proguard_enabled(self):
    """Returns whether proguard runs for this target."""
    # Modules set proguard_enabled, but the proguarding happens only once at the
    # bundle level.
    if self.get_type() == 'android_app_bundle_module':
      return False
    return self.build_config().get('proguard_enabled', False)


def main():
  parser = argparse.ArgumentParser(
      description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  parser.add_argument('-C',
                      '--output-directory',
                      help='If outdir is not provided, will attempt to guess.')
  parser.add_argument('--gn-labels',
                      action='store_true',
                      help='Print GN labels rather than ninja targets')
  parser.add_argument('--omit-targets',
                      action='store_true',
                      help='Do not print the target / gn label')
  parser.add_argument(
      '--nested',
      action='store_true',
      help='Do not convert nested targets to their top-level equivalents. '
      'E.g. Without this, foo_test__apk -> foo_test')
  parser.add_argument('--print-types',
                      action='store_true',
                      help='Print type of each target')
  parser.add_argument(
      '--print-build-config-paths',
      action='store_true',
      help='Print path to the .build_config.json of each target')
  parser.add_argument('--print-params-paths',
                      action='store_true',
                      help='Print path to the .params.json of each target')
  parser.add_argument('--build',
                      action='store_true',
                      help='Build all .build_config.json files.')
  parser.add_argument('--type',
                      action='append',
                      help='Restrict to targets of given type',
                      choices=_VALID_TYPES)
  parser.add_argument('--stats',
                      action='store_true',
                      help='Print counts of each target type.')
  parser.add_argument('--proguard-enabled',
                      action='store_true',
                      help='Restrict to targets that have proguard enabled.')
  parser.add_argument('--query',
                      help='A dot separated string specifying a query for a '
                      'build config json value of each target. Example: Use '
                      '--query unprocessed_jar_path to show a list '
                      'of all targets that have a non-empty '
                      '"unprocessed_jar_path" value in that dict.')
  parser.add_argument('-v', '--verbose', default=0, action='count')
  parser.add_argument('-q', '--quiet', default=0, action='count')
  args = parser.parse_args()

  args.build |= bool(args.type or args.proguard_enabled or args.print_types
                     or args.stats or args.query)

  logging.basicConfig(level=logging.WARNING + 10 * (args.quiet - args.verbose),
                      format='%(levelname).1s %(relativeCreated)6d %(message)s')

  if args.output_directory:
    constants.SetOutputDirectory(args.output_directory)
  constants.CheckOutputDirectory()
  output_dir = constants.GetOutDirectory()

  if args.build:
    _compile(output_dir, ['build.ninja'])

  # Query ninja for all __build_config_crbug_908819 targets.
  targets = _query_for_build_config_targets(output_dir)
  entries = [_TargetEntry(t) for t in targets]

  if not entries:
    logging.warning('No targets found. Run with --build')
    sys.exit(1)

  if args.build:
    logging.warning('Building %d .build_config.json files...', len(entries))
    _compile(output_dir, [e.ninja_build_config_target for e in entries],
             quiet=args.quiet)

  if args.type:
    entries = [e for e in entries if e.get_type() in args.type]

  if args.proguard_enabled:
    entries = [e for e in entries if e.proguard_enabled()]

  if args.stats:
    counts = collections.Counter(e.get_type() for e in entries)
    for entry_type, count in sorted(counts.items()):
      print(f'{entry_type}: {count}')
  else:
    for e in entries:
      if args.omit_targets:
        target_part = ''
      else:
        if args.gn_labels:
          target_part = e.gn_target
        else:
          target_part = e.ninja_target

        # Convert to top-level target
        if not args.nested:
          target_part = target_part.replace('__test_apk',
                                            '').replace('__apk', '')

      type_part = ''
      if args.print_types:
        type_part = e.get_type()
      elif args.print_build_config_paths:
        type_part = e.build_config_path
      elif args.print_params_paths:
        type_part = e.params_path
      elif args.query:
        type_part = _query_json(json_dict=e.build_config(),
                                query=args.query,
                                path=e.build_config_path)
        if not type_part:
          continue

      if target_part and type_part:
        print(f'{target_part}: {type_part}')
      elif target_part or type_part:
        print(target_part or type_part)


if __name__ == '__main__':
  main()