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
21from xml.dom import minidom
22
23from ninja_rsp import NinjaRspFileReader
24
25
26def check_action(check_type):
27  """
28  Returns an action that appends a tuple of check_type and the argument to the dest.
29  """
30  class CheckAction(argparse.Action):
31    def __init__(self, option_strings, dest, nargs=None, **kwargs):
32      if nargs is not None:
33        raise ValueError("nargs must be None, was %s" % nargs)
34      super(CheckAction, self).__init__(option_strings, dest, **kwargs)
35    def __call__(self, parser, namespace, values, option_string=None):
36      checks = getattr(namespace, self.dest, [])
37      checks.append((check_type, values))
38      setattr(namespace, self.dest, checks)
39  return CheckAction
40
41
42def parse_args():
43  """Parse commandline arguments."""
44
45  def convert_arg_line_to_args(arg_line):
46    for arg in arg_line.split():
47      if arg.startswith('#'):
48        return
49      if not arg.strip():
50        continue
51      yield arg
52
53  parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
54  parser.convert_arg_line_to_args = convert_arg_line_to_args
55  parser.add_argument('--project_out', dest='project_out',
56                      help='file to which the project.xml contents will be written.')
57  parser.add_argument('--config_out', dest='config_out',
58                      help='file to which the lint.xml contents will be written.')
59  parser.add_argument('--name', dest='name',
60                      help='name of the module.')
61  parser.add_argument('--srcs', dest='srcs', action='append', default=[],
62                      help='file containing whitespace separated list of source files.')
63  parser.add_argument('--generated_srcs', dest='generated_srcs', action='append', default=[],
64                      help='file containing whitespace separated list of generated source files.')
65  parser.add_argument('--resources', dest='resources', action='append', default=[],
66                      help='file containing whitespace separated list of resource files.')
67  parser.add_argument('--classes', dest='classes', action='append', default=[],
68                      help='file containing the module\'s classes.')
69  parser.add_argument('--classpath', dest='classpath', action='append', default=[],
70                      help='file containing classes from dependencies.')
71  parser.add_argument('--extra_checks_jar', dest='extra_checks_jars', action='append', default=[],
72                      help='file containing extra lint checks.')
73  parser.add_argument('--manifest', dest='manifest',
74                      help='file containing the module\'s manifest.')
75  parser.add_argument('--merged_manifest', dest='merged_manifest',
76                      help='file containing merged manifest for the module and its dependencies.')
77  parser.add_argument('--baseline', dest='baseline_path',
78                      help='file containing baseline lint issues.')
79  parser.add_argument('--library', dest='library', action='store_true',
80                      help='mark the module as a library.')
81  parser.add_argument('--test', dest='test', action='store_true',
82                      help='mark the module as a test.')
83  parser.add_argument('--cache_dir', dest='cache_dir',
84                      help='directory to use for cached file.')
85  parser.add_argument('--root_dir', dest='root_dir',
86                      help='directory to use for root dir.')
87  group = parser.add_argument_group('check arguments', 'later arguments override earlier ones.')
88  group.add_argument('--fatal_check', dest='checks', action=check_action('fatal'), default=[],
89                     help='treat a lint issue as a fatal error.')
90  group.add_argument('--error_check', dest='checks', action=check_action('error'), default=[],
91                     help='treat a lint issue as an error.')
92  group.add_argument('--warning_check', dest='checks', action=check_action('warning'), default=[],
93                     help='treat a lint issue as a warning.')
94  group.add_argument('--disable_check', dest='checks', action=check_action('ignore'), default=[],
95                     help='disable a lint issue.')
96  group.add_argument('--disallowed_issues', dest='disallowed_issues', default=[],
97                     help='lint issues disallowed in the baseline file')
98  return parser.parse_args()
99
100
101def write_project_xml(f, args):
102  test_attr = "test='true' " if args.test else ""
103
104  f.write("<?xml version='1.0' encoding='utf-8'?>\n")
105  f.write("<project>\n")
106  if args.root_dir:
107    f.write("  <root dir='%s' />\n" % args.root_dir)
108  f.write("  <module name='%s' android='true' %sdesugar='full' >\n" % (args.name, "library='true' " if args.library else ""))
109  if args.manifest:
110    f.write("    <manifest file='%s' %s/>\n" % (args.manifest, test_attr))
111  if args.merged_manifest:
112    f.write("    <merged-manifest file='%s' %s/>\n" % (args.merged_manifest, test_attr))
113  for src_file in args.srcs:
114    for src in NinjaRspFileReader(src_file):
115      f.write("    <src file='%s' %s/>\n" % (src, test_attr))
116  for src_file in args.generated_srcs:
117    for src in NinjaRspFileReader(src_file):
118      f.write("    <src file='%s' generated='true' %s/>\n" % (src, test_attr))
119  for res_file in args.resources:
120    for res in NinjaRspFileReader(res_file):
121      f.write("    <resource file='%s' %s/>\n" % (res, test_attr))
122  for classes in args.classes:
123    f.write("    <classes jar='%s' />\n" % classes)
124  for classpath in args.classpath:
125    f.write("    <classpath jar='%s' />\n" % classpath)
126  for extra in args.extra_checks_jars:
127    f.write("    <lint-checks jar='%s' />\n" % extra)
128  f.write("  </module>\n")
129  if args.cache_dir:
130    f.write("  <cache dir='%s'/>\n" % args.cache_dir)
131  f.write("</project>\n")
132
133
134def write_config_xml(f, args):
135  f.write("<?xml version='1.0' encoding='utf-8'?>\n")
136  f.write("<lint>\n")
137  for check in args.checks:
138    f.write("  <issue id='%s' severity='%s' />\n" % (check[1], check[0]))
139  f.write("</lint>\n")
140
141
142def check_baseline_for_disallowed_issues(baseline, forced_checks):
143  issues_element = baseline.documentElement
144  if issues_element.tagName != 'issues':
145    raise RuntimeError('expected issues tag at root')
146  issues = issues_element.getElementsByTagName('issue')
147  disallowed = set()
148  for issue in issues:
149    id = issue.getAttribute('id')
150    if id in forced_checks:
151      disallowed.add(id)
152  return disallowed
153
154
155def main():
156  """Program entry point."""
157  args = parse_args()
158
159  if args.baseline_path:
160    baseline = minidom.parse(args.baseline_path)
161    disallowed_issues = check_baseline_for_disallowed_issues(baseline, args.disallowed_issues)
162    if bool(disallowed_issues):
163      raise RuntimeError('disallowed issues %s found in lint baseline file %s for module %s'
164                         % (disallowed_issues, args.baseline_path, args.name))
165
166  if args.project_out:
167    with open(args.project_out, 'w') as f:
168      write_project_xml(f, args)
169
170  if args.config_out:
171    with open(args.config_out, 'w') as f:
172      write_config_xml(f, args)
173
174
175if __name__ == '__main__':
176  main()
177