-
Notifications
You must be signed in to change notification settings - Fork 9
/
AnimalSniffer.groovy
263 lines (238 loc) · 9.56 KB
/
AnimalSniffer.groovy
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
package ru.vyarus.gradle.plugin.animalsniffer
import groovy.transform.CompileStatic
import groovy.transform.TypeCheckingMode
import org.apache.tools.ant.BuildListener
import org.gradle.api.Action
import org.gradle.api.GradleException
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileTree
import org.gradle.api.internal.CollectionCallbackActionDecorator
import org.gradle.api.internal.project.IsolatedAntBuilder
import org.gradle.api.reporting.Report
import org.gradle.api.reporting.Reporting
import org.gradle.api.tasks.*
import org.gradle.internal.reflect.Instantiator
import org.gradle.util.ClosureBackedAction
import org.gradle.util.GUtil
import org.gradle.util.GradleVersion
import ru.vyarus.gradle.plugin.animalsniffer.report.AnimalSnifferReports
import ru.vyarus.gradle.plugin.animalsniffer.report.AnimalSnifferReportsImpl
import ru.vyarus.gradle.plugin.animalsniffer.report.ReportCollector
import javax.inject.Inject
import java.lang.reflect.Proxy
/**
* AnimalSniffer task is created for each registered source set.
* <p>
* Task is SourceTask, but with root in compile classes dir of current source set. This means that include/exclude
* may be used, but they wil be applied to compiled classes and not sources.
*
* @author Vyacheslav Rusakov
* @since 14.12.2015
*/
@SuppressWarnings('UnnecessaryGetter')
@CompileStatic
@CacheableTask
class AnimalSniffer extends SourceTask implements VerificationTask, Reporting<AnimalSnifferReports> {
/**
* The class path containing the Animal Sniffer library to be used.
*/
@Classpath
@InputFiles
FileCollection animalsnifferClasspath
/**
* Signature files used for checks.
*/
@SkipWhenEmpty
@Classpath
@InputFiles
FileCollection animalsnifferSignatures
/**
* Classpath used for compilation (if not included in signature)
*/
@CompileClasspath
@InputFiles
@Optional
FileCollection classpath
/**
* Source directories
*/
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
Set<File> sourcesDirs
/**
* Annotation class name to avoid check
*/
@Input
@Optional
String annotation
/**
* Extra allowed classes, not mentioned in signature, but allowed for usage.
* Most commonly, when some classes target newer jdk version.
* <p>
* See <a href="http://www.mojohaus.org/animal-sniffer/animal-sniffer-ant-tasks/examples/checking-signatures.html
* #Ignoring_classes_not_in_the_signature">
* docs</a> for more info.
*/
@Input
@Optional
Iterable<String> ignoreClasses = []
/**
* Whether or not the build should break when the verifications performed by this task fail.
*/
@Console
boolean ignoreFailures
private final AnimalSnifferReportsImpl reports
/**
* Due to many classloaders used by AntBuilder, have to avoid ant classes in custom listener.
* Use jdk proxy to register custom listener.
*
* @param project ant project
* @param handler proxy handler
*/
@CompileStatic(TypeCheckingMode.SKIP)
static void replaceBuildListener(Object project, ReportCollector handler) {
// use original to redirect other ant tasks output (not expected, but just in case)
handler.originalListener = project.buildListeners.first()
// cleanup default gradle listener listener to avoid console output
project.buildListeners.each { project.removeBuildListener(it) }
ClassLoader cl = project.class.classLoader
Object listener = Proxy.newProxyInstance(cl, [cl.loadClass(BuildListener.name)] as Class[], handler)
project.addBuildListener(listener)
}
/**
* Recover original listener after execution.
*
* @param project ant project
* @param original original listener
*/
@CompileStatic(TypeCheckingMode.SKIP)
static void recoverOriginalListener(Object project, Object original) {
if (original != null) {
project.buildListeners.each { project.removeBuildListener(it) }
project.addBuildListener(original)
}
}
@SuppressWarnings('ThisReferenceEscapesConstructor')
AnimalSniffer() {
reports = instantiator.newInstance(AnimalSnifferReportsImpl, this, getCallbackActionDecorator())
}
@Inject
Instantiator getInstantiator() {
throw new UnsupportedOperationException()
}
@Inject
CollectionCallbackActionDecorator getCallbackActionDecorator() {
throw new UnsupportedOperationException()
}
@Inject
IsolatedAntBuilder getAntBuilder() {
throw new UnsupportedOperationException()
}
@TaskAction
@SuppressWarnings('CatchException')
@CompileStatic(TypeCheckingMode.SKIP)
void run() {
antBuilder.withClasspath(getAnimalsnifferClasspath()).execute {
ant.taskdef(name: 'animalsniffer', classname: 'org.codehaus.mojo.animal_sniffer.ant.CheckSignatureTask')
ReportCollector collector = new ReportCollector(getSourcesDirs())
replaceBuildListener(project, collector)
String sortedPath = preparePath(getSource())
getAnimalsnifferSignatures().each { signature ->
try {
collector.contextSignature(signature.name)
ant.animalsniffer(signature: signature.absolutePath, classpath: getClasspath()?.asPath) {
// the same as getSource().asPath, but have to apply sorting because otherwise
// enclosing class could be parsed after inlined and so ignoring annotation on enclosing class
// would be ignored (actually, this problem appears only on windows)
path(path: sortedPath)
getSourcesDirs().each {
sourcepath(path: it.absoluteFile)
}
annotation(className: 'org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement')
if (getAnnotation()) {
annotation(className: getAnnotation())
}
getIgnoreClasses().each { ignore(className: it) }
}
} catch (Exception ex) {
// rethrow not expected ant exceptions
if (!ex.message.startsWith('Signature errors found')) {
throw ex
}
}
}
collector.printSignatureNames = getAnimalsnifferSignatures().size() > 1
processErrors(collector)
// it should be useless as completely custom ant used for execution, but just in case
recoverOriginalListener(project, collector.originalListener)
}
}
/**
* Returns the reports to be generated by this task.
*/
@Nested
@Override
AnimalSnifferReports getReports() {
return reports
}
@Override
@SuppressWarnings('ConfusingMethodName')
AnimalSnifferReports reports(
@DelegatesTo(value = AnimalSnifferReports, strategy = Closure.DELEGATE_FIRST) Closure closure) {
reports(new ClosureBackedAction<AnimalSnifferReports>(closure))
}
@Override
@SuppressWarnings('ConfusingMethodName')
AnimalSnifferReports reports(Action<? super AnimalSnifferReports> action) {
action.execute(reports)
return reports
}
@Override
@PathSensitive(PathSensitivity.RELATIVE)
FileTree getSource() {
return super.getSource()
}
void processErrors(ReportCollector collector) {
if (collector.errorsCnt() > 0) {
String message = "${collector.errorsCnt()} AnimalSniffer violations were found " +
"in ${collector.filesCnt()} files."
Report report = reports.firstEnabled
if (report) {
File target = GradleVersion.current() < GradleVersion.version('7.0')
? report.destination : report.outputLocation.get().asFile
collector.writeToFile(target)
String reportUrl = "file:///${target.canonicalPath.replaceAll('\\\\', '/')}"
message += " See the report at: $reportUrl"
}
if (getIgnoreFailures()) {
String nl = String.format('%n')
logger.error(nl + message + nl)
collector.writeToConsole(logger)
} else {
logger.error('')
collector.writeToConsole(logger)
throw new GradleException(message)
}
}
}
@SuppressWarnings(['Indentation', 'UnnecessaryCollectCall', 'UnnecessarySubstring'])
private static String preparePath(FileTree source) {
int clsExtSize = '.class'.length()
String innerIndicator = '$'
List<String> sortedPath = source
.collect { it.toString() }
.toSorted { a, b ->
if (a.contains(innerIndicator) || b.contains(innerIndicator)) {
String a1 = a.substring(0, a.length() - clsExtSize) // - .class
String b1 = b.substring(0, b.length() - clsExtSize)
// trick is to compare names without extension, so inner class would
// become longer and go last automatically;
// compare: Some.class < Some$1.class, but Some > Some$1
return a1 <=> b1
}
return a <=> b
}
// lambda case (Some$$Lambda$1). Ant removes every odd $ in a row
return GUtil.asPath(sortedPath).replace('$$', '$$$')
}
}