forked from Western-parotia/EaseLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAndroidLintAnalysisTask.kt
455 lines (403 loc) · 17.4 KB
/
AndroidLintAnalysisTask.kt
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
* Copyright (C) 2021 The Android Open Source Project
*
* 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 com.android.build.gradle.internal.lint
import com.android.Version
import com.android.build.api.artifact.impl.ArtifactsImpl
import com.android.build.api.dsl.Lint
import com.android.build.gradle.internal.SdkComponentsBuildService
import com.android.build.gradle.internal.component.ComponentCreationConfig
import com.android.build.gradle.internal.component.VariantCreationConfig
import com.android.build.gradle.internal.profile.AnalyticsService
import com.android.build.gradle.internal.publishing.AndroidArtifacts
import com.android.build.gradle.internal.scope.InternalArtifactType
import com.android.build.gradle.internal.services.TaskCreationServices
import com.android.build.gradle.internal.services.getBuildService
import com.android.build.gradle.internal.services.getLintParallelBuildService
import com.android.build.gradle.internal.tasks.BuildAnalyzer
import com.android.build.gradle.internal.tasks.NonIncrementalTask
import com.android.build.gradle.internal.tasks.factory.VariantTaskCreationAction
import com.android.build.gradle.internal.utils.fromDisallowChanges
import com.android.build.gradle.internal.utils.getDesugaredMethods
import com.android.build.gradle.internal.utils.setDisallowChanges
import com.android.build.gradle.internal.tasks.TaskCategory
import com.android.ide.common.repository.GradleVersion
import com.android.tools.lint.model.LintModelSerialization
import com.android.utils.FileUtils
import com.buildsrc.lint.ArtifactsImplProxy
import com.buildsrc.lint.LintHook
import com.google.common.annotations.VisibleForTesting
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.configuration.ShowStacktrace
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskProvider
import java.io.File
import java.util.Collections
/** Task to invoke lint with the --analyze-only flag, producing partial results. */
@CacheableTask
@BuildAnalyzer(primaryTaskCategory = TaskCategory.LINT)
abstract class AndroidLintAnalysisTask : NonIncrementalTask() {
@get:Nested
abstract val lintTool: LintTool
@get:Internal
abstract val lintModelDirectory: DirectoryProperty
@get:OutputDirectory
abstract val partialResultsDirectory: DirectoryProperty
@get:Internal
abstract val androidSdkHome: Property<String>
@get:Input
abstract val androidGradlePluginVersion: Property<String>
@get:Input
abstract val offline: Property<Boolean>
@get:Input
abstract val android: Property<Boolean>
@get:Input
abstract val fatalOnly: Property<Boolean>
@get:Input
abstract val checkOnly: ListProperty<String>
@get:Classpath
abstract val lintRuleJars: ConfigurableFileCollection
@get:Nested
abstract val projectInputs: ProjectInputs
@get:Nested
abstract val variantInputs: VariantInputs
@get:Input
abstract val printStackTrace: Property<Boolean>
@get:Nested
abstract val systemPropertyInputs: SystemPropertyInputs
@get:Nested
abstract val environmentVariableInputs: EnvironmentVariableInputs
@get:InputFiles
@get:PathSensitive(PathSensitivity.NONE)
@get:Optional
abstract val desugaredMethodsFiles: ConfigurableFileCollection
override fun doTaskAction() {
println("----------- AndroidLintAnalysisTask has been cover by EaseLint -----------")
LintHook().loadHookFile(lintTool,project)
lintTool.lintClassLoaderBuildService.get().shouldDispose = true
writeLintModelFile()
var arguments = generateCommandLineArguments(true)
lintTool.submit(
mainClass = "com.android.tools.lint.Main",
workerExecutor = workerExecutor,
arguments = arguments,
android = android.get(),
fatalOnly = fatalOnly.get(),
await = false,
lintMode = LintMode.ANALYSIS
)
}
private fun writeLintModelFile() {
val module = ProjectInputsProxy.convertToLintModelModule(projectInputs)
val variant =
variantInputs.toLintModel(
module,
partialResultsDirectory.get().asFile,
desugaredMethodsFiles.files
)
val destination = lintModelDirectory.get().asFile.also { FileUtils.cleanOutputDir(it) }
LintModelSerialization.writeModule(
module = module,
destination = destination,
writeVariants = listOf(variant),
writeDependencies = true
)
}
@VisibleForTesting
internal fun generateCommandLineArguments(addModel: Boolean = true): List<String> {
val arguments = mutableListOf<String>()
arguments += "--analyze-only"
if (fatalOnly.get()) {
arguments += "--fatalOnly"
}
arguments += listOf("--jdk-home", systemPropertyInputs.javaHome.get())
androidSdkHome.orNull?.let { arguments.add("--sdk-home", it) }
if (addModel) {
arguments += "--lint-model"
arguments += listOf(lintModelDirectory.get().asFile.absolutePath).asLintPaths()
}
for (check in checkOnly.get()) {
arguments += listOf("--check", check)
}
val rules = lintRuleJars.files.filter { it.isFile }.map { it.absolutePath }
if (rules.isNotEmpty()) {
arguments += "--lint-rule-jars"
arguments += rules.asLintPaths()
}
if (printStackTrace.get()) {
arguments += "--stacktrace"
}
arguments += lintTool.initializeLintCacheDir()
// Pass information to lint using the --client-id, --client-name, and --client-version flags
// so that lint can apply gradle-specific and version-specific behaviors.
arguments.add("--client-id", "gradle")
arguments.add("--client-name", "AGP")
arguments.add("--client-version", Version.ANDROID_GRADLE_PLUGIN_VERSION)
// Pass --offline flag only if lint version is 30.3.0-beta01 or higher because earlier
// versions of lint don't accept that flag.
if (offline.get()
&& GradleVersion.tryParse(lintTool.version.get())
?.isAtLeast(30, 3, 0, "beta", 1, false) == true
) {
arguments += "--offline"
}
// arguments.add("/Volumes/D/CodeProject/AndroidProject/EaseLint-7.0/AndroidLint-7.4.2/lint-gradle-api/app/src/main/java/com/easelint/gradle/SubModuleKotlinPrint.kt")
return Collections.unmodifiableList(arguments)
}
// See LintUtils.splitPath: Using `;` as a suffix to avoid triggering the path that uses `:`,
// even if there is only one path.
private fun Collection<String>.asLintPaths() = joinToString(separator = ";", postfix = ";")
private fun MutableList<String>.add(arg: String, value: String) {
add(arg)
add(value)
}
/**
* Creates the lintAnalyzeVariant Task. Linting a variant also includes looking at the tests for
* that variant.
*/
class SingleVariantCreationAction(variant: VariantWithTests) : VariantCreationAction(variant) {
override val name = creationConfig.computeTaskName("lintAnalyze")
override val fatalOnly = false
override val description = "Run lint analysis on the ${creationConfig.name} variant"
override fun handleProvider(taskProvider: TaskProvider<AndroidLintAnalysisTask>) {
registerOutputArtifacts(
taskProvider,
InternalArtifactType.LINT_PARTIAL_RESULTS,
creationConfig.artifacts
)
}
}
/**
* CreationAction for the lintVitalAnalyzeVariant task. Does not use the variant with tests
*/
class LintVitalCreationAction(variant: VariantCreationConfig) :
VariantCreationAction(
VariantWithTests(
variant,
androidTest = null,
unitTest = null,
testFixtures = null
)
) {
override val name = creationConfig.computeTaskName("lintVitalAnalyze")
override val fatalOnly = true
override val description =
"Run lint analysis with only the fatal issues enabled on the ${creationConfig.name} variant"
override fun handleProvider(taskProvider: TaskProvider<AndroidLintAnalysisTask>) {
registerOutputArtifacts(
taskProvider,
InternalArtifactType.LINT_VITAL_PARTIAL_RESULTS,
creationConfig.artifacts
)
}
}
abstract class VariantCreationAction(val variant: VariantWithTests) :
VariantTaskCreationAction<AndroidLintAnalysisTask,
ComponentCreationConfig>(variant.main) {
final override val type: Class<AndroidLintAnalysisTask>
get() = AndroidLintAnalysisTask::class.java
abstract val fatalOnly: Boolean
abstract val description: String
final override fun configure(task: AndroidLintAnalysisTask) {
super.configure(task)
task.group = JavaBasePlugin.VERIFICATION_GROUP
task.description = description
task.initializeGlobalInputs(
services = variant.main.services,
isAndroid = true
)
task.lintModelDirectory.set(variant.main.paths.getIncrementalDir(task.name))
task.lintRuleJars.from(creationConfig.global.localCustomLintChecks)
task.lintRuleJars.from(
creationConfig
.variantDependencies
.getArtifactFileCollection(
AndroidArtifacts.ConsumedConfigType.RUNTIME_CLASSPATH,
AndroidArtifacts.ArtifactScope.ALL,
AndroidArtifacts.ArtifactType.LINT
)
)
task.lintRuleJars.from(
creationConfig
.variantDependencies
.getArtifactFileCollection(
AndroidArtifacts.ConsumedConfigType.COMPILE_CLASSPATH,
AndroidArtifacts.ArtifactScope.ALL,
AndroidArtifacts.ArtifactType.LINT
)
)
task.lintRuleJars.disallowChanges()
task.fatalOnly.setDisallowChanges(fatalOnly)
task.checkOnly.set(
creationConfig.services.provider {
creationConfig.global.lintOptions.checkOnly
}
)
ProjectInputsProxy.initialize(task.projectInputs, variant, LintMode.ANALYSIS)
task.variantInputs.initialize(
variant,
checkDependencies = false,
warnIfProjectTreatedAsExternalDependency = false,
LintMode.ANALYSIS
)
task.lintTool.initialize(creationConfig.services)
task.desugaredMethodsFiles.from(
getDesugaredMethods(
creationConfig.services,
creationConfig.global.compileOptions.isCoreLibraryDesugaringEnabled,
creationConfig.minSdkVersion,
creationConfig.global.compileSdkHashString,
creationConfig.global.bootClasspath
)
)
task.desugaredMethodsFiles.disallowChanges()
}
}
private fun initializeGlobalInputs(
services: TaskCreationServices,
isAndroid: Boolean
) {
val buildServiceRegistry = services.buildServiceRegistry
this.androidGradlePluginVersion.setDisallowChanges(Version.ANDROID_GRADLE_PLUGIN_VERSION)
val sdkComponentsBuildService =
getBuildService(buildServiceRegistry, SdkComponentsBuildService::class.java)
this.android.setDisallowChanges(isAndroid)
if (isAndroid) {
this.androidSdkHome.set(
sdkComponentsBuildService.flatMap { it.sdkDirectoryProvider }
.map { it.asFile.absolutePath }
)
}
this.androidSdkHome.disallowChanges()
this.offline.setDisallowChanges(project.gradle.startParameter.isOffline)
// Include Lint jars set via the environment variable ANDROID_LINT_JARS
val globalLintJarsFromEnvVariable: Provider<List<String>> =
project.providers.environmentVariable(ANDROID_LINT_JARS_ENVIRONMENT_VARIABLE)
.orElse("")
.map { it.split(File.pathSeparator).filter(String::isNotEmpty) }
this.lintRuleJars.from(globalLintJarsFromEnvVariable)
if (project.gradle.startParameter.showStacktrace != ShowStacktrace.INTERNAL_EXCEPTIONS) {
printStackTrace.setDisallowChanges(true)
} else {
printStackTrace.setDisallowChanges(
project.providers
.environmentVariable(LINT_PRINT_STACKTRACE_ENVIRONMENT_VARIABLE)
.map { it.equals("true", ignoreCase = true) }
.orElse(false)
)
}
systemPropertyInputs.initialize(project.providers, LintMode.ANALYSIS)
environmentVariableInputs.initialize(project.providers, LintMode.ANALYSIS)
this.usesService(
services.buildServiceRegistry.getLintParallelBuildService(services.projectOptions)
)
}
fun configureForStandalone(
taskCreationServices: TaskCreationServices,
javaPluginExtension: JavaPluginExtension,
customLintChecksConfig: FileCollection,
lintOptions: Lint,
fatalOnly: Boolean = false
) {
initializeGlobalInputs(
services = taskCreationServices,
isAndroid = false
)
this.group = JavaBasePlugin.VERIFICATION_GROUP
this.variantName = ""
// this.analyticsService.setDisallowChanges(getBuildService(taskCreationServices.buildServiceRegistry))
this.analyticsService.setDisallowChanges(
getBuildService(
taskCreationServices.buildServiceRegistry,
AnalyticsService::class.java
)
)
this.fatalOnly.setDisallowChanges(fatalOnly)
this.checkOnly.setDisallowChanges(lintOptions.checkOnly)
this.lintTool.initialize(taskCreationServices)
ProjectInputsProxy.initializeForStandalone(
this.projectInputs,
project,
javaPluginExtension,
lintOptions,
LintMode.ANALYSIS
)
// .initializeForStandalone(
// project,
// javaPluginExtension,
// lintOptions,
// LintMode.ANALYSIS
// )
VariantInputsProxy.initializeForStandalone(
this.variantInputs,
project,
javaPluginExtension,
taskCreationServices.projectOptions,
fatalOnly,
checkDependencies = false,
LintMode.ANALYSIS
)
// this.variantInputs.initializeForStandalone(
// project,
// javaPluginExtension,
// taskCreationServices.projectOptions,
// fatalOnly,
// checkDependencies = false,
// LintMode.ANALYSIS
// )
this.lintRuleJars.fromDisallowChanges(customLintChecksConfig)
this.lintModelDirectory
.setDisallowChanges(
project.layout.buildDirectory.dir("intermediates/${this.name}/android-lint-model")
)
}
companion object {
private const val LINT_PRINT_STACKTRACE_ENVIRONMENT_VARIABLE = "LINT_PRINT_STACKTRACE"
private const val ANDROID_LINT_JARS_ENVIRONMENT_VARIABLE = "ANDROID_LINT_JARS"
const val PARTIAL_RESULTS_DIR_NAME = "out"
fun registerOutputArtifacts(
taskProvider: TaskProvider<AndroidLintAnalysisTask>,
internalArtifactType: InternalArtifactType<Directory>,
artifacts: ArtifactsImpl
) {
ArtifactsImplProxy().proxy(
taskProvider, AndroidLintAnalysisTask::partialResultsDirectory,
artifacts,
internalArtifactType
)
// artifacts
// .setInitialProvider(taskProvider, AndroidLintAnalysisTask::partialResultsDirectory)
// .withName(PARTIAL_RESULTS_DIR_NAME)
// .on(internalArtifactType)
}
}
}