• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Parses a input care_map.txt in plain text format; converts it into the proto
19buf message; and writes the result to the output file.
20
21"""
22
23import argparse
24import logging
25import sys
26
27import care_map_pb2
28
29
30def GenerateCareMapProtoFromLegacyFormat(lines, fingerprint_enabled):
31  """Constructs a care map proto message from the lines of the input file."""
32
33  # Expected format of the legacy care_map.txt:
34  # system
35  # system's care_map ranges
36  # [system's fingerprint property id]
37  # [system's fingerprint]
38  # [vendor]
39  # [vendor's care_map ranges]
40  # [vendor's fingerprint property id]
41  # [vendor's fingerprint]
42  # ...
43
44  step = 4 if fingerprint_enabled else 2
45  assert len(lines) % step == 0, \
46      "line count must be multiple of {}: {}".format(step, len(lines))
47
48  care_map_proto = care_map_pb2.CareMap()
49  for index in range(0, len(lines), step):
50    info = care_map_proto.partitions.add()
51    info.name = lines[index]
52    info.ranges = lines[index + 1]
53    if fingerprint_enabled:
54      info.id = lines[index + 2]
55      info.fingerprint = lines[index + 3]
56    logging.info("Care map info: name %s, ranges %s, id %s, fingerprint %s",
57                 info.name, info.ranges, info.id, info.fingerprint)
58
59  return care_map_proto
60
61
62def ParseProtoMessage(message, fingerprint_enabled):
63  """Parses the care_map proto message and returns its text representation.
64  Args:
65    message: Care_map in protobuf format.
66    fingerprint_enabled: Input protobuf message contains the fields 'id' and
67        'fingerprint'.
68
69  Returns:
70     A string of the care_map information, similar to the care_map legacy
71     format.
72  """
73  care_map_proto = care_map_pb2.CareMap()
74  care_map_proto.MergeFromString(message)
75
76  info_list = []
77  for info in care_map_proto.partitions:
78    assert info.name, "partition name is required in care_map"
79    assert info.ranges, "source range is required in care_map"
80    info_list += [info.name, info.ranges]
81    if fingerprint_enabled:
82      assert info.id, "property id is required in care_map"
83      assert info.fingerprint, "fingerprint is required in care_map"
84      info_list += [info.id, info.fingerprint]
85
86  return '\n'.join(info_list)
87
88
89def main(argv):
90  parser = argparse.ArgumentParser(
91      description=__doc__,
92      formatter_class=argparse.RawDescriptionHelpFormatter)
93  parser.add_argument("input_care_map",
94                      help="Path to the legacy care_map file (or path to"
95                           " care_map in protobuf format if --parse_proto is"
96                           " specified).")
97  parser.add_argument("output_file",
98                      help="Path to output file to write the result.")
99  parser.add_argument("--no_fingerprint", action="store_false",
100                      dest="fingerprint_enabled",
101                      help="The 'id' and 'fingerprint' fields are disabled in"
102                           " the caremap.")
103  parser.add_argument("--parse_proto", "-p", action="store_true",
104                      help="Parses the input as proto message, and outputs"
105                           " the care_map in plain text.")
106  parser.add_argument("--verbose", "-v", action="store_true")
107
108  args = parser.parse_args(argv)
109
110  logging_format = '%(filename)s %(levelname)s: %(message)s'
111  logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
112                      format=logging_format)
113
114  with open(args.input_care_map, 'r') as input_care_map:
115    content = input_care_map.read()
116
117  if args.parse_proto:
118    result = ParseProtoMessage(content, args.fingerprint_enabled)
119  else:
120    care_map_proto = GenerateCareMapProtoFromLegacyFormat(
121        content.rstrip().splitlines(), args.fingerprint_enabled)
122    result = care_map_proto.SerializeToString()
123
124  with open(args.output_file, 'w') as output:
125    output.write(result)
126
127
128if __name__ == '__main__':
129  main(sys.argv[1:])
130