• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
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
18"""This file generates project.xml and lint.xml files used to drive the Android Lint CLI tool."""
19
20import argparse
21
22
23def check_action(check_type):
24  """
25  Returns an action that appends a tuple of check_type and the argument to the dest.
26  """
27  class CheckAction(argparse.Action):
28    def __init__(self, option_strings, dest, nargs=None, **kwargs):
29      if nargs is not None:
30        raise ValueError("nargs must be None, was %s" % nargs)
31      super(CheckAction, self).__init__(option_strings, dest, **kwargs)
32    def __call__(self, parser, namespace, values, option_string=None):
33      checks = getattr(namespace, self.dest, [])
34      checks.append((check_type, values))
35      setattr(namespace, self.dest, checks)
36  return CheckAction
37
38
39def parse_args():
40  """Parse commandline arguments."""
41
42  def convert_arg_line_to_args(arg_line):
43    for arg in arg_line.split():
44      if arg.startswith('#'):
45        return
46      if not arg.strip():
47        continue
48      yield arg
49
50  parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
51  parser.convert_arg_line_to_args = convert_arg_line_to_args
52  parser.add_argument('--project_out', dest='project_out',
53                      help='file to which the project.xml contents will be written.')
54  parser.add_argument('--config_out', dest='config_out',
55                      help='file to which the lint.xml contents will be written.')
56  parser.add_argument('--name', dest='name',
57                      help='name of the module.')
58  parser.add_argument('--srcs', dest='srcs', action='append', default=[],
59                      help='file containing whitespace separated list of source files.')
60  parser.add_argument('--generated_srcs', dest='generated_srcs', action='append', default=[],
61                      help='file containing whitespace separated list of generated source files.')
62  parser.add_argument('--resources', dest='resources', action='append', default=[],
63                      help='file containing whitespace separated list of resource files.')
64  parser.add_argument('--classes', dest='classes', action='append', default=[],
65                      help='file containing the module\'s classes.')
66  parser.add_argument('--classpath', dest='classpath', action='append', default=[],
67                      help='file containing classes from dependencies.')
68  parser.add_argument('--extra_checks_jar', dest='extra_checks_jars', action='append', default=[],
69                      help='file containing extra lint checks.')
70  parser.add_argument('--manifest', dest='manifest',
71                      help='file containing the module\'s manifest.')
72  parser.add_argument('--merged_manifest', dest='merged_manifest',
73                      help='file containing merged manifest for the module and its dependencies.')
74  parser.add_argument('--library', dest='library', action='store_true',
75                      help='mark the module as a library.')
76  parser.add_argument('--test', dest='test', action='store_true',
77                      help='mark the module as a test.')
78  parser.add_argument('--cache_dir', dest='cache_dir',
79                      help='directory to use for cached file.')
80  parser.add_argument('--root_dir', dest='root_dir',
81                      help='directory to use for root dir.')
82  group = parser.add_argument_group('check arguments', 'later arguments override earlier ones.')
83  group.add_argument('--fatal_check', dest='checks', action=check_action('fatal'), default=[],
84                     help='treat a lint issue as a fatal error.')
85  group.add_argument('--error_check', dest='checks', action=check_action('error'), default=[],
86                     help='treat a lint issue as an error.')
87  group.add_argument('--warning_check', dest='checks', action=check_action('warning'), default=[],
88                     help='treat a lint issue as a warning.')
89  group.add_argument('--disable_check', dest='checks', action=check_action('ignore'), default=[],
90                     help='disable a lint issue.')
91  return parser.parse_args()
92
93
94class NinjaRspFileReader:
95  """
96  Reads entries from a Ninja rsp file.  Ninja escapes any entries in the file that contain a
97  non-standard character by surrounding the whole entry with single quotes, and then replacing
98  any single quotes in the entry with the escape sequence '\''.
99  """
100
101  def __init__(self, filename):
102    self.f = open(filename, 'r')
103    self.r = self.character_reader(self.f)
104
105  def __iter__(self):
106    return self
107
108  def character_reader(self, f):
109    """Turns a file into a generator that returns one character at a time."""
110    while True:
111      c = f.read(1)
112      if c:
113        yield c
114      else:
115        return
116
117  def __next__(self):
118    entry = self.read_entry()
119    if entry:
120      return entry
121    else:
122      raise StopIteration
123
124  def read_entry(self):
125    c = next(self.r, "")
126    if not c:
127      return ""
128    elif c == "'":
129      return self.read_quoted_entry()
130    else:
131      entry = c
132      for c in self.r:
133        if c == " " or c == "\n":
134          break
135        entry += c
136      return entry
137
138  def read_quoted_entry(self):
139    entry = ""
140    for c in self.r:
141      if c == "'":
142        # Either the end of the quoted entry, or the beginning of an escape sequence, read the next
143        # character to find out.
144        c = next(self.r)
145        if not c or c == " " or c == "\n":
146          # End of the item
147          return entry
148        elif c == "\\":
149          # Escape sequence, expect a '
150          c = next(self.r)
151          if c != "'":
152            # Malformed escape sequence
153            raise "malformed escape sequence %s'\\%s" % (entry, c)
154          entry += "'"
155        else:
156          raise "malformed escape sequence %s'%s" % (entry, c)
157      else:
158        entry += c
159    raise "unterminated quoted entry %s" % entry
160
161
162def write_project_xml(f, args):
163  test_attr = "test='true' " if args.test else ""
164
165  f.write("<?xml version='1.0' encoding='utf-8'?>\n")
166  f.write("<project>\n")
167  if args.root_dir:
168    f.write("  <root dir='%s' />\n" % args.root_dir)
169  f.write("  <module name='%s' android='true' %sdesugar='full' >\n" % (args.name, "library='true' " if args.library else ""))
170  if args.manifest:
171    f.write("    <manifest file='%s' %s/>\n" % (args.manifest, test_attr))
172  if args.merged_manifest:
173    f.write("    <merged-manifest file='%s' %s/>\n" % (args.merged_manifest, test_attr))
174  for src_file in args.srcs:
175    for src in NinjaRspFileReader(src_file):
176      f.write("    <src file='%s' %s/>\n" % (src, test_attr))
177  for src_file in args.generated_srcs:
178    for src in NinjaRspFileReader(src_file):
179      f.write("    <src file='%s' generated='true' %s/>\n" % (src, test_attr))
180  for res_file in args.resources:
181    for res in NinjaRspFileReader(res_file):
182      f.write("    <resource file='%s' %s/>\n" % (res, test_attr))
183  for classes in args.classes:
184    f.write("    <classes jar='%s' />\n" % classes)
185  for classpath in args.classpath:
186    f.write("    <classpath jar='%s' />\n" % classpath)
187  for extra in args.extra_checks_jars:
188    f.write("    <lint-checks jar='%s' />\n" % extra)
189  f.write("  </module>\n")
190  if args.cache_dir:
191    f.write("  <cache dir='%s'/>\n" % args.cache_dir)
192  f.write("</project>\n")
193
194
195def write_config_xml(f, args):
196  f.write("<?xml version='1.0' encoding='utf-8'?>\n")
197  f.write("<lint>\n")
198  for check in args.checks:
199    f.write("  <issue id='%s' severity='%s' />\n" % (check[1], check[0]))
200  f.write("</lint>\n")
201
202
203def main():
204  """Program entry point."""
205  args = parse_args()
206
207  if args.project_out:
208    with open(args.project_out, 'w') as f:
209      write_project_xml(f, args)
210
211  if args.config_out:
212    with open(args.config_out, 'w') as f:
213      write_config_xml(f, args)
214
215
216if __name__ == '__main__':
217  main()
218