1# Copyright 2018 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
5import os
6
7# Utilities to read and write .jar.info files.
8#
9# A .jar.info file contains a simple mapping from fully-qualified Java class
10# names to the source file that actually defines it.
11#
12# For APKs, the .jar.info maps the class names to the .jar file that which
13# contains its .class definition instead.
14
15
16def ReadAarSourceInfo(info_path):
17  """Returns the source= path from an .aar's source.info file."""
18  # The .info looks like: "source=path/to/.aar\n".
19  with open(info_path) as f:
20    return f.read().rstrip().split('=', 1)[1]
21
22
23def ParseJarInfoFile(info_path):
24  """Parse a given .jar.info file as a dictionary.
25
26  Args:
27    info_path: input .jar.info file path.
28  Returns:
29    A new dictionary mapping fully-qualified Java class names to file paths.
30  """
31  info_data = dict()
32  if os.path.exists(info_path):
33    with open(info_path, 'r') as info_file:
34      for line in info_file:
35        line = line.strip()
36        if line:
37          fully_qualified_name, path = line.split(',', 1)
38          info_data[fully_qualified_name] = path
39  return info_data
40
41
42def WriteJarInfoFile(output_obj, info_data, source_file_map=None):
43  """Generate a .jar.info file from a given dictionary.
44
45  Args:
46    output_obj: output file object.
47    info_data: a mapping of fully qualified Java class names to filepaths.
48    source_file_map: an optional mapping from java source file paths to the
49      corresponding source .srcjar. This is because info_data may contain the
50      path of Java source files that where extracted from an .srcjar into a
51      temporary location.
52  """
53  for fully_qualified_name, path in sorted(info_data.iteritems()):
54    if source_file_map and path in source_file_map:
55      path = source_file_map[path]
56      assert not path.startswith('/tmp'), (
57          'Java file path should not be in temp dir: {}'.format(path))
58    output_obj.write('{},{}\n'.format(fully_qualified_name, path))
59