-
Notifications
You must be signed in to change notification settings - Fork 273
/
Output.java
411 lines (351 loc) · 12.7 KB
/
Output.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
Copyright 2014 Immutables Authors and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.immutables.generator;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.processing.Filer;
import javax.annotation.processing.FilerException;
import javax.annotation.processing.Messager;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import org.immutables.generator.Templates.Invokable;
import org.immutables.generator.Templates.Invokation;
import static com.google.common.base.Preconditions.*;
public final class Output {
public final Templates.Invokable error = new Templates.Invokable() {
@Override
@Nullable
public Invokable invoke(Invokation invokation, Object... parameters) {
String message = CharMatcher.WHITESPACE.trimFrom(parameters[0].toString());
StaticEnvironment.processing().getMessager().printMessage(Diagnostic.Kind.ERROR, message);
return null;
}
@Override
public int arity() {
return 1;
}
};
public final Templates.Invokable system = new Templates.Invokable() {
@Override
@Nullable
public Invokable invoke(Invokation invokation, Object... parameters) {
String message = CharMatcher.WHITESPACE.trimFrom(parameters[0].toString());
System.out.println(message);
return null;
}
@Override
public int arity() {
return 1;
}
};
private static abstract class OutputFilter extends Templates.Fragment {
public OutputFilter() {
super(1);
}
abstract void apply(Invokation invokation, CharSequence content, @Nullable Templates.Invokable original);
@Override
public final void run(Invokation invokation) {
Object param = invokation.param(0);
Invokable original = param instanceof Templates.Invokable
? (Templates.Invokable) param
: null;
apply(invokation, toCharSequence(param), original);
}
private CharSequence toCharSequence(Object param) {
checkNotNull(param);
// Is it worthwhile optimization?
if (param instanceof Templates.Fragment) {
return ((Templates.Fragment) param).toCharSequence();
}
return param.toString();
}
}
public final Templates.Invokable trim = new OutputFilter() {
@Override
void apply(Invokation invokation, CharSequence content, @Nullable Templates.Invokable original) {
invokation.out(CharMatcher.WHITESPACE.trimFrom(content));
}
};
public final Templates.Invokable linesShortable = new OutputFilter() {
private static final int LIMIT = 100;
@Override
void apply(Invokation invokation, CharSequence content, @Nullable Templates.Invokable original) {
String collapsed = CharMatcher.WHITESPACE.trimAndCollapseFrom(content, ' ');
int estimatedLimitOnThisLine = LIMIT - invokation.getCurrentIndentation().length();
if (collapsed.length() < estimatedLimitOnThisLine) {
invokation.out(collapsed);
} else {
if (original != null) {
original.invoke(invokation);
} else {
invokation.out(content);
}
}
}
};
public final Templates.Invokable collapsible = new OutputFilter() {
@Override
void apply(Invokation invokation, CharSequence content, @Nullable Templates.Invokable original) {
boolean hasNonWhitespace = !CharMatcher.WHITESPACE.matchesAllOf(content);
if (hasNonWhitespace) {
if (original != null) {
original.invoke(invokation);
} else {
invokation.out(content);
}
}
}
};
public final Templates.Invokable java = new Templates.Invokable() {
@Override
public Invokable invoke(Invokation invokation, Object... parameters) {
String packageName = parameters[0].toString();
String simpleName = parameters[1].toString();
Invokable body = (Invokable) parameters[2];
ResourceKey key = new ResourceKey(packageName, simpleName);
SourceFile javaFile = getFiles().sourceFiles.get(key);
body.invoke(new Invokation(javaFile.consumer));
javaFile.complete();
return null;
}
@Override
public int arity() {
return 3;
}
};
public final Templates.Invokable service = new Templates.Invokable() {
private static final String META_INF_SERVICES = "META-INF/services/";
@Override
public Invokable invoke(Invokation invokation, Object... parameters) {
String interfaceName = parameters[0].toString();
Invokable body = (Invokable) parameters[1];
ResourceKey key = new ResourceKey("", META_INF_SERVICES + interfaceName);
AppendServiceFile servicesFile = getFiles().appendResourceFiles.get(key);
body.invoke(new Invokation(servicesFile.consumer));
return null;
}
@Override
public int arity() {
return 3;
}
};
private final static class ResourceKey {
private static Joiner PACKAGE_RESOURCE_JOINER = Joiner.on('.').skipNulls();
final String packageName;
final String relativeName;
ResourceKey(String packageName, String simpleName) {
this.packageName = checkNotNull(packageName);
this.relativeName = checkNotNull(simpleName);
}
@Override
public String toString() {
return PACKAGE_RESOURCE_JOINER.join(Strings.emptyToNull(packageName), relativeName);
}
@Override
public int hashCode() {
return Objects.hash(packageName, relativeName);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ResourceKey) {
ResourceKey other = (ResourceKey) obj;
return this.packageName.equals(other.packageName)
|| this.relativeName.equals(other.relativeName);
}
return false;
}
}
private static class AppendServiceFile {
private static final Pattern SERVICE_FILE_COMMENT_LINE = Pattern.compile("^\\#.*");
final ResourceKey key;
final Templates.CharConsumer consumer = new Templates.CharConsumer();
AppendServiceFile(ResourceKey key) {
this.key = key;
}
void complete() {
try {
writeFile();
} catch (FilerException ex) {
throw Throwables.propagate(ex);
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}
private void writeFile() throws IOException {
LinkedHashSet<String> services = Sets.newLinkedHashSet();
readExistingEntriesInto(services);
copyNewMetaservicesInto(services);
removeBlankLinesIn(services);
writeLinesFrom(services);
}
private void readExistingEntriesInto(Collection<String> services) {
try {
FileObject existing = getFiler().getResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName);
FluentIterable.from(CharStreams.readLines(existing.openReader(true)))
.filter(Predicates.not(Predicates.contains(SERVICE_FILE_COMMENT_LINE)))
.copyInto(services);
} catch (Exception ex) {
// unable to read existing file
}
}
private void writeLinesFrom(Iterable<String> services) throws IOException {
new CharSink() {
@Override
public Writer openStream() throws IOException {
return getFiler()
.createResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName)
.openWriter();
}
}.writeLines(services, "\n");
}
private void removeBlankLinesIn(Iterable<String> services) {
Iterables.removeIf(services, Predicates.equalTo(""));
}
private void copyNewMetaservicesInto(Collection<String> services) {
FluentIterable.from(Splitter.on("\n").split(consumer.asCharSequence()))
.copyInto(services);
}
}
private static class SourceFile {
final ResourceKey key;
final Templates.CharConsumer consumer = new Templates.CharConsumer();
SourceFile(ResourceKey key) {
this.key = key;
}
void complete() {
CharSequence sourceCode = extractSourceCode();
try {
try (Writer writer = getFiler().createSourceFile(key.toString()).openWriter()) {
writer.append(sourceCode);
}
} catch (FilerException ex) {
if (identicalFileIsAlreadyGenerated(sourceCode)) {
getMessager().printMessage(Kind.MANDATORY_WARNING, "Regenerated file with the same content: " + key);
} else {
getMessager().printMessage(Kind.ERROR, String.format(
"Generated source file name collission. Attempt to overwrite already generated file: %s, %s",
key, ex));
}
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}
private boolean identicalFileIsAlreadyGenerated(CharSequence sourceCode) {
try {
String existingContent = new CharSource() {
final String packagePath = !key.packageName.isEmpty() ? (key.packageName.replace('.', '/') + '/') : "";
final String filename = key.relativeName + ".java";
@Override
public Reader openStream() throws IOException {
return getFiler()
.getResource(StandardLocation.SOURCE_OUTPUT,
"", packagePath + filename)
.openReader(true);
}
}.read();
if (existingContent.contentEquals(sourceCode)) {
// We are ok, for some reason the same file is already generated,
// happens in Eclipse for example.
return true;
}
} catch (Exception ignoredAttemptToGetExistingFile) {
// we have some other problem, not an existing file
}
return false;
}
private CharSequence extractSourceCode() {
return PostprocessingMachine.rewrite(consumer.asCharSequence());
}
}
private static Filer getFiler() {
return StaticEnvironment.processing().getFiler();
}
private static Messager getMessager() {
return StaticEnvironment.processing().getMessager();
}
private static Files getFiles() {
return StaticEnvironment.getInstance(Files.class, FilesSupplier.INSTANCE);
}
private enum FilesSupplier implements Supplier<Files> {
INSTANCE;
@Override
public Files get() {
return new Files();
}
}
// Do not use guava cache to slim down minimized jar
@NotThreadSafe
private static abstract class Cache<K, V> {
private final Map<K, V> map = new HashMap<>();
protected abstract V load(K key) throws Exception;
final V get(K key) {
@Nullable V value = map.get(key);
if (value == null) {
try {
value = load(key);
} catch (Exception ex) {
throw Throwables.propagate(ex);
}
map.put(key, value);
}
return value;
}
public Map<K, V> asMap() {
return map;
}
}
private static class Files implements StaticEnvironment.Completable {
final Cache<ResourceKey, SourceFile> sourceFiles = new Cache<ResourceKey, SourceFile>() {
@Override
public SourceFile load(ResourceKey key) throws Exception {
return new SourceFile(key);
}
};
final Cache<ResourceKey, AppendServiceFile> appendResourceFiles = new Cache<ResourceKey, AppendServiceFile>() {
@Override
public AppendServiceFile load(ResourceKey key) throws Exception {
return new AppendServiceFile(key);
}
};
@Override
public void complete() {
for (AppendServiceFile file : appendResourceFiles.asMap().values()) {
file.complete();
}
}
}
}