blob: 7ab4f01503d0687947de81f69db9f3730b53db7d [file] [log] [blame]
Colin Cross014489c2020-06-02 20:09:13 -07001#!/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 group = parser.add_argument_group('check arguments', 'later arguments override earlier ones.')
81 group.add_argument('--fatal_check', dest='checks', action=check_action('fatal'), default=[],
82 help='treat a lint issue as a fatal error.')
83 group.add_argument('--error_check', dest='checks', action=check_action('error'), default=[],
84 help='treat a lint issue as an error.')
85 group.add_argument('--warning_check', dest='checks', action=check_action('warning'), default=[],
86 help='treat a lint issue as a warning.')
87 group.add_argument('--disable_check', dest='checks', action=check_action('ignore'), default=[],
88 help='disable a lint issue.')
89 return parser.parse_args()
90
91
92class NinjaRspFileReader:
93 """
94 Reads entries from a Ninja rsp file. Ninja escapes any entries in the file that contain a
95 non-standard character by surrounding the whole entry with single quotes, and then replacing
96 any single quotes in the entry with the escape sequence '\''.
97 """
98
99 def __init__(self, filename):
100 self.f = open(filename, 'r')
101 self.r = self.character_reader(self.f)
102
103 def __iter__(self):
104 return self
105
106 def character_reader(self, f):
107 """Turns a file into a generator that returns one character at a time."""
108 while True:
109 c = f.read(1)
110 if c:
111 yield c
112 else:
113 return
114
115 def __next__(self):
116 entry = self.read_entry()
117 if entry:
118 return entry
119 else:
120 raise StopIteration
121
122 def read_entry(self):
123 c = next(self.r, "")
124 if not c:
125 return ""
126 elif c == "'":
127 return self.read_quoted_entry()
128 else:
129 entry = c
130 for c in self.r:
131 if c == " " or c == "\n":
132 break
133 entry += c
134 return entry
135
136 def read_quoted_entry(self):
137 entry = ""
138 for c in self.r:
139 if c == "'":
140 # Either the end of the quoted entry, or the beginning of an escape sequence, read the next
141 # character to find out.
142 c = next(self.r)
143 if not c or c == " " or c == "\n":
144 # End of the item
145 return entry
146 elif c == "\\":
147 # Escape sequence, expect a '
148 c = next(self.r)
149 if c != "'":
150 # Malformed escape sequence
151 raise "malformed escape sequence %s'\\%s" % (entry, c)
152 entry += "'"
153 else:
154 raise "malformed escape sequence %s'%s" % (entry, c)
155 else:
156 entry += c
157 raise "unterminated quoted entry %s" % entry
158
159
160def write_project_xml(f, args):
161 test_attr = "test='true' " if args.test else ""
162
163 f.write("<?xml version='1.0' encoding='utf-8'?>\n")
164 f.write("<project>\n")
165 f.write(" <module name='%s' android='true' %sdesugar='full' >\n" % (args.name, "library='true' " if args.library else ""))
166 if args.manifest:
167 f.write(" <manifest file='%s' %s/>\n" % (args.manifest, test_attr))
168 if args.merged_manifest:
169 f.write(" <merged-manifest file='%s' %s/>\n" % (args.merged_manifest, test_attr))
170 for src_file in args.srcs:
171 for src in NinjaRspFileReader(src_file):
172 f.write(" <src file='%s' %s/>\n" % (src, test_attr))
173 for src_file in args.generated_srcs:
174 for src in NinjaRspFileReader(src_file):
175 f.write(" <src file='%s' generated='true' %s/>\n" % (src, test_attr))
176 for res_file in args.resources:
177 for res in NinjaRspFileReader(res_file):
178 f.write(" <resource file='%s' %s/>\n" % (res, test_attr))
179 for classes in args.classes:
180 f.write(" <classes jar='%s' />\n" % classes)
181 for classpath in args.classpath:
182 f.write(" <classpath jar='%s' />\n" % classpath)
183 for extra in args.extra_checks_jars:
184 f.write(" <lint-checks jar='%s' />\n" % extra)
185 f.write(" </module>\n")
186 if args.cache_dir:
187 f.write(" <cache dir='%s'/>\n" % args.cache_dir)
188 f.write("</project>\n")
189
190
191def write_config_xml(f, args):
192 f.write("<?xml version='1.0' encoding='utf-8'?>\n")
193 f.write("<lint>\n")
194 for check in args.checks:
195 f.write(" <issue id='%s' severity='%s' />\n" % (check[1], check[0]))
196 f.write("</lint>\n")
197
198
199def main():
200 """Program entry point."""
201 args = parse_args()
202
203 if args.project_out:
204 with open(args.project_out, 'w') as f:
205 write_project_xml(f, args)
206
207 if args.config_out:
208 with open(args.config_out, 'w') as f:
209 write_config_xml(f, args)
210
211
212if __name__ == '__main__':
213 main()