Debian Codegraph @

src/com/google/javascript/jscomp/WhitelistWarningsGuard.java

raw symbols SCIP
1 /*
2 * Copyright 2011 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Charsets;
20 import com.google.common.base.Joiner;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Splitter;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.collect.Iterables;
26 import com.google.common.collect.Multimap;
27 import com.google.common.collect.Sets;
28 import com.google.common.collect.TreeMultimap;
29 import com.google.common.io.CharStreams;
30 import com.google.common.io.Files;
31 import com.google.common.io.InputSupplier;
32 import com.google.javascript.jscomp.CheckLevel;
33
34 import java.io.File;
35 import java.io.IOException;
36 import java.io.PrintStream;
37 import java.io.Reader;
38 import java.util.List;
39 import java.util.Set;
40 import java.util.regex.Pattern;
41
42 /**
43 * An extension of {@code WarningsGuard} that provides functionality to maintain
44 * a list of warnings (white-list). It is subclasses' responsibility to decide
45 * what to do with the white-list by implementing the {@code level} function.
46 * Warnings are defined by the name of the JS file and the first line of
47 * warnings description.
48 *
49 * @author [email protected] (Anatol Pomazau)
50 * @author [email protected] (Bashir Sadjad)
51 */
52 public class WhitelistWarningsGuard extends WarningsGuard {
53 private static final Splitter LINE_SPLITTER = Splitter.on("\n");
54
55 /** The set of white-listed warnings, same format as {@code formatWarning}. */
56 private final Set<String> whitelist;
57
58 /** Pattern to match line number in error descriptions. */
59 private static final Pattern LINE_NUMBER = Pattern.compile(":-?\\d+");
60
61 /**
62 * This class depends on an input set that contains the white-list. The format
63 * of each white-list string is:
64 * <file-name>:<line-number>? <warning-description>
65 * # <optional-comment>
66 *
67 * @param whitelist The set of JS-warnings that are white-listed. This is
68 * expected to have similar format as {@code formatWarning(JSError)}.
69 */
70 public WhitelistWarningsGuard(Set<String> whitelist) {
71 Preconditions.checkNotNull(whitelist);
72 this.whitelist = normalizeWhitelist(whitelist);
73 }
74
75 /**
76 * Loads legacy warnings list from the set of strings. During development line
77 * numbers are changed very often - we just cut them and compare without ones.
78 *
79 * @return known legacy warnings without line numbers.
80 */
81 private static Set<String> normalizeWhitelist(Set<String> whitelist) {
82 Set<String> result = Sets.newHashSet();
83 for (String line : whitelist) {
84 String trimmed = line.trim();
85 if (trimmed.isEmpty() || trimmed.charAt(0) == '#') {
86 // strip out empty lines and comments.
87 continue;
88 }
89
90 // Strip line number for matching.
91 result.add(LINE_NUMBER.matcher(trimmed).replaceFirst(":"));
92 }
93 return ImmutableSet.copyOf(result);
94 }
95
96 @Override
97 public CheckLevel level(JSError error) {
98 if (containWarning(formatWarning(error))) {
99 // If the message matches the guard we use WARNING, so that it
100 // - Shows up on stderr, and
101 // - Gets caught by the WhitelistBuilder downstream in the pipeline
102 return CheckLevel.WARNING;
103 }
104
105 return null;
106 }
107
108 /**
109 * Determines whether a given warning is included in the white-list.
110 *
111 * @param formattedWarning the warning formatted by {@code formatWarning}
112 * @return whether the given warning is white-listed or not.
113 */
114 protected boolean containWarning(String formattedWarning) {
115 return whitelist.contains(formattedWarning);
116 }
117
118 @Override
119 public int getPriority() {
120 return WarningsGuard.Priority.SUPPRESS_BY_WHITELIST.getValue();
121 }
122
123 /** Creates a warnings guard from a file. */
124 public static WhitelistWarningsGuard fromFile(File file) {
125 return new WhitelistWarningsGuard(loadWhitelistedJsWarnings(file));
126 }
127
128 /**
129 * Loads legacy warnings list from the file.
130 * @return The lines of the file.
131 */
132 public static Set<String> loadWhitelistedJsWarnings(File file) {
133 return loadWhitelistedJsWarnings(
134 Files.newReaderSupplier(file, Charsets.UTF_8));
135 }
136
137 /**
138 * Loads legacy warnings list from the file.
139 * @return The lines of the file.
140 */
141 protected static Set<String> loadWhitelistedJsWarnings(
142 InputSupplier<? extends Reader> supplier) {
143 try {
144 return loadWhitelistedJsWarnings(supplier.getInput());
145 } catch (IOException e) {
146 throw new RuntimeException(e);
147 }
148 }
149
150 /**
151 * Loads legacy warnings list from the file.
152 * @return The lines of the file.
153 */
154 // TODO(nicksantos): This is a weird API.
155 static Set<String> loadWhitelistedJsWarnings(Reader reader)
156 throws IOException {
157 Preconditions.checkNotNull(reader);
158 Set<String> result = Sets.newHashSet();
159
160 for (String line : CharStreams.readLines(reader)) {
161 result.add(line);
162 }
163
164 return result;
165 }
166
167 public static String formatWarning(JSError error) {
168 return formatWarning(error, false);
169 }
170
171 /**
172 * @param withMetaData If true, include metadata that's useful to humans
173 * This metadata won't be used for matching the warning.
174 */
175 public static String formatWarning(JSError error, boolean withMetaData) {
176 StringBuilder sb = new StringBuilder();
177 sb.append(error.sourceName).append(":");
178 if (withMetaData) {
179 sb.append(error.lineNumber);
180 }
181 List<String> lines = ImmutableList.copyOf(
182 LINE_SPLITTER.split(error.description));
183 sb.append(" ").append(lines.get(0));
184
185 // Add the rest of the message as a comment.
186 if (withMetaData) {
187 for (int i = 1; i < lines.size(); i++) {
188 sb.append("\n# ").append(lines.get(i));
189 }
190 sb.append("\n");
191 }
192
193 return sb.toString();
194 }
195
196 public static String getFirstLine(String warning) {
197 int lineLength = warning.indexOf('\n');
198 if (lineLength > 0) {
199 warning = warning.substring(0, lineLength);
200 }
201 return warning;
202 }
203
204 public static class WhitelistBuilder implements ErrorHandler {
205 private final Set<JSError> warnings = Sets.newLinkedHashSet();
206 private String productName = null;
207 private String generatorTarget = null;
208 private String headerNote = null;
209
210 /** Fill in your product name to get a fun message! */
211 public WhitelistBuilder setProductName(String name) {
212 this.productName = name;
213 return this;
214 }
215
216 /** Fill in instructions on how to generate this whitelist. */
217 public WhitelistBuilder setGeneratorTarget(String name) {
218 this.generatorTarget = name;
219 return this;
220 }
221
222 /** A note to include at the top of the whitelist file. */
223 public WhitelistBuilder setNote(String note) {
224 this.headerNote = note;
225 return this;
226 }
227
228 /** We now always record the line number. */
229 @Deprecated
230 public WhitelistBuilder setWithLineNumber(boolean line) {
231 return this;
232 }
233
234 @Override
235 public void report(CheckLevel level, JSError error) {
236 warnings.add(error);
237 }
238
239 /**
240 * Writes the warnings collected in a format that the WhitelistWarningsGuard
241 * can read back later.
242 */
243 public void writeWhitelist(File out) throws IOException {
244 PrintStream stream = new PrintStream(out);
245 appendWhitelist(stream);
246 stream.close();
247 }
248
249 /**
250 * Writes the warnings collected in a format that the WhitelistWarningsGuard
251 * can read back later.
252 */
253 public void appendWhitelist(PrintStream out) {
254 out.append(
255 "# This is a list of legacy warnings that have yet to be fixed.\n");
256
257 if (productName != null) {
258 out.append("# Please find some time and fix at least one of them "
259 + "and it will be the happiest day for " + productName + ".\n");
260 }
261
262 if (generatorTarget != null) {
263 out.append("# When you fix any of these warnings, run "
264 + generatorTarget + " task.\n");
265 }
266
267 if (headerNote != null) {
268 out.append("#"
269 + Joiner.on("\n# ").join(Splitter.on("\n").split(headerNote))
270 + "\n");
271 }
272
273 Multimap<DiagnosticType, String> warningsByType = TreeMultimap.create();
274 for (JSError warning : warnings) {
275 warningsByType.put(
276 warning.getType(),
277 formatWarning(warning, true /* withLineNumber */));
278 }
279
280 for (DiagnosticType type : warningsByType.keySet()) {
281 out.append("\n# Warning ")
282 .append(type.key)
283 .append(": ")
284 .println(Iterables.get(
285 LINE_SPLITTER.split(type.format.toPattern()), 0));
286
287 for (String warning : warningsByType.get(type)) {
288 out.println(warning);
289 }
290 }
291 out.flush();
292 }
293 }
294 }