-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.gradle
More file actions
508 lines (469 loc) · 24.8 KB
/
Copy pathinit.gradle
File metadata and controls
508 lines (469 loc) · 24.8 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.UnknownDomainObjectException
import org.gradle.api.UnknownTaskException
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.internal.DefaultDomainObjectCollection
import org.gradle.api.internal.DefaultNamedDomainObjectCollection
import org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency
import org.gradle.plugins.ide.eclipse.model.EclipseModel
import org.gradle.plugins.ide.eclipse.model.SourceFolder
import org.gradle.plugins.ide.eclipse.model.ClasspathEntry
import org.gradle.plugins.ide.eclipse.model.Classpath
import org.gradle.plugins.ide.eclipse.model.Library
import org.gradle.plugins.ide.eclipse.model.internal.FileReferenceFactory
import org.gradle.util.GradleVersion
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.lang.Thread;
class JavaLanguageServerAndroidPlugin implements Plugin<Project> {
private static final String ANDROID_PROPERTY = "android"
// buildship indicator
private static final String ECLIPSE_PROPERTY = "eclipse"
private static final String DEFAULT_OUTPUT_MAIN = "bin/main"
private static final List<String> ANDROID_PLUGIN_IDS = Arrays.asList("com.android.application", "com.android.library")
private static final List<String> DEFAULT_SOURCE_SET_NAMES = Arrays.asList("main", "test", "androidTest")
private static final List<String> SUPPORTED_CONFIGURATION_KEYS = Arrays.asList("implementationConfigurationName", "apiConfigurationName", "compileConfigurationName", "compileOnlyConfigurationName", "runtimeOnlyConfigurationName")
private static final String OPTIONAL_ATTRIBUTE = "optional"
private static final String TEST_ATTRIBUTE = "test"
// using `./gradlew -I init.gradle -Dorg.gradle.daemon=false -Dorg.gradle.debug=true` eclipse to debug
// using `jdb -attach 5005 -sourcepath /` to attach, and then `cont`
private static int debugFlag = 0 // set to one to trap to forloop
void apply(Project project) {
if (!isSupportedAndroidProject(project)) {
println "[ACG]: not a android project"
return
}
if (!project.hasProperty(ECLIPSE_PROPERTY)) {
println "[ACG]: do not detect eclipse plugin"
return
}
File androidSDKFile = getAndroidSDKFile(project)
if (androidSDKFile == null) {
println "[ACG]: android.jar file not founded"
return
}
project.afterEvaluate {
// If you dont use ide and just using raw jdb to debug
// this snippet will help you founded out which thread to stop
if (debugFlag == 1) {
Thread currentThread = Thread.currentThread()
println "[AGP]: "+currentThread // using `threads` to findout which thread runing this script
// and then `suspend THREADID`, `where THREADID`
while(debugFlag) {
// jdb `set debugFlag = 1` to step out of this loop
}
}
// `stop at JavaLanguageServerAndroidPlugin$_apply_closure1:63`
List<Object> variants = getAndroidDebuggableVariants(project)
EclipseModel eclipseModel = (EclipseModel) project.property(ECLIPSE_PROPERTY)
// eclipseModel.synchronizationTasks() is available since Gradle 5.4
// see: https://www.eclipse.org/community/eclipse_newsletter/2019/june/buildship.php
if (GradleVersion.version(project.getGradle().getGradleVersion()) >= GradleVersion.version("5.4")) {
List<Object> synchronizationTasks = new ArrayList<>()
for (Object variant : variants) {
try {
synchronizationTasks.add(variant.properties.get("variantData").properties.get("taskContainer").properties.get("compileTask"))
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
eclipseModel.synchronizationTasks(synchronizationTasks)
}
List<Object> androidSourceSets = getAndroidSourceSets(project)
// Get project configurations from supported sourceSets names and configuration keys,
// and add them to eclipseModel.classpath.plusConfigurations
addPlusConfiguration(project, eclipseModel, androidSourceSets)
eclipseModel.classpath.setDownloadSources(true)
// Remove JDK container since android project should use embedded JDK types included in android.jar
List<String> containers = new ArrayList<>()
for (String containerName : eclipseModel.classpath.containers) {
if (containerName.contains("JavaSE")) {
// NOTE: this is a tradeoff, if this enabled, will report error in checkSystemLibrary
// Due to missing java.base in android.jar, which will cause decompiler not work
// Personally I would like to choice using incorrect java.* reference to make decompile work
// containers.add(containerName)
}
}
eclipseModel.classpath.containers.removeAll(containers)
// Add supported source sets to source folders of eclipse model
eclipseModel.classpath.file.whenMerged(new AddSourceFoldersAction(project, androidSourceSets))
// Add data binding files to source folders of eclipse model
eclipseModel.classpath.file.whenMerged(new AddDataBindingFilesAction(project, variants))
// Add R files to source folders of eclipse model
eclipseModel.classpath.file.whenMerged(new AddRFilesAction(project, variants))
// Add buildconfig files to source folders of eclipse model
eclipseModel.classpath.file.whenMerged(new AddBuildConfigFilesAction(project, variants))
// Add android.jar to project classpath of eclipse model
eclipseModel.classpath.file.whenMerged(new AddAndroidSDKAction(androidSDKFile))
// Add project dependencies to project classpath of eclipse model
// for aar dependencies, extract classes.jar and add them to project classpath
eclipseModel.classpath.file.whenMerged(new AddProjectDependenciesAction(project))
}
}
private static boolean isSupportedAndroidProject(Project project) {
for (String pluginId : ANDROID_PLUGIN_IDS) {
if (project.plugins.hasPlugin(pluginId)) {
return true
}
}
return false
}
private static File getAndroidSDKFile(Project project) {
Object android = project.property(ANDROID_PROPERTY)
try {
Object bootClasspathList = android.properties.get("bootClasspath")
if (bootClasspathList instanceof List) {
for (Object bootClasspath : ((List) bootClasspathList)) {
if (bootClasspath instanceof File) {
File file = (File) bootClasspath
if (file.getAbsolutePath().endsWith("android.jar") && file.exists()) {
return file
}
}
}
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
return null
}
private static void addPlusConfiguration(Project project, EclipseModel eclipseModel, List<Object> androidSourceSets) {
List<String> plusConfigurationNames = new ArrayList<>()
for (Object androidSourceSet : androidSourceSets) {
for (String key : SUPPORTED_CONFIGURATION_KEYS) {
if (androidSourceSet.properties.containsKey(key)) {
plusConfigurationNames.add(androidSourceSet.properties.get(key).toString())
}
}
}
SortedMap<String, Configuration> configurations = project.getConfigurations().getAsMap()
for (String config : plusConfigurationNames) {
if (configurations.containsKey(config)) {
Configuration configuration = configurations.get(config)
// set null target as default target
for (Dependency dependency : configuration.getDependencies()) {
if (dependency instanceof DefaultProjectDependency) {
if (((DefaultProjectDependency) dependency).getTargetConfiguration() == null) {
((DefaultProjectDependency) dependency).setTargetConfiguration("default")
}
}
}
configuration.setCanBeResolved(true)
eclipseModel.classpath.plusConfigurations.add(configuration)
}
}
}
private static List<Object> getAndroidDebuggableVariants(Project project) {
Object android = project.property(ANDROID_PROPERTY)
Object variants = null
if (project.plugins.hasPlugin("com.android.application")) {
// For android application, variants come from applicationVariants property
if (android.properties.containsKey("applicationVariants")) {
variants = android.properties.get("applicationVariants")
}
} else if (project.plugins.hasPlugin("com.android.library")) {
// For android library, variants come from libraryVariants property
if (android.properties.containsKey("libraryVariants")) {
variants = android.properties.get("libraryVariants")
}
}
if (variants instanceof DefaultDomainObjectCollection) {
List<Object> androidDebuggableVariants = new ArrayList<>()
for (Object variant : variants) {
try {
Object debuggable = variant.properties.get("buildType").properties.get("debuggable")
if (debuggable instanceof Boolean && ((Boolean) debuggable)) {
androidDebuggableVariants.add(variant)
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
return androidDebuggableVariants
}
return Collections.emptyList()
}
private static List<Object> getAndroidSourceSets(Project project) {
List<Object> androidSourceSets = new ArrayList<>()
Object android = project.property(ANDROID_PROPERTY)
if (android.properties.containsKey("sourceSets")) {
Object sourceSets = android.properties.get("sourceSets")
if (sourceSets instanceof DefaultNamedDomainObjectCollection) {
for (Object sourceSet : sourceSets) {
try {
Object javaDirectories = sourceSet.properties.get("javaDirectories")
if (javaDirectories instanceof Collection) {
for (Object javaDirectory : javaDirectories) {
if (javaDirectory instanceof File && ((File) javaDirectory).exists()) {
androidSourceSets.add(sourceSet)
}
}
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
// fallback to default sourceSets
if (androidSourceSets.size() == 0) {
for (String defaultName : DEFAULT_SOURCE_SET_NAMES) {
try {
androidSourceSets.add(((DefaultNamedDomainObjectCollection) sourceSets).getByName(defaultName))
} catch (UnknownDomainObjectException ignored) {
// Do nothing
}
}
}
}
}
return androidSourceSets
}
private static void addFolderToSourceFolder(Classpath classpath, Project project, File folder, String outputPath) {
if (!folder.exists()) {
if (!folder.mkdirs()) {
return
}
}
if (!folder.isDirectory()) {
return
}
SourceFolder sourceFolder = new SourceFolder(project.getProjectDir().toPath().relativize(folder.toPath()).toString(), outputPath)
// For Gradle version < 5.4, we add this attribute so that the folders can be recognized once the files are generated
// For Gradle version >= 5.4, we add the compile task to synchronization tasks so that this attribute is not necessary
if (GradleVersion.version(project.getGradle().getGradleVersion()) < GradleVersion.version("5.4")) {
sourceFolder.entryAttributes.put(OPTIONAL_ATTRIBUTE, "true")
}
// See: https://github.com/gradle/gradle/blob/dd350d3d50f7b7ea43f2a726739acb2c4645f30b/subprojects/ide/src/main/java/org/gradle/plugins/ide/eclipse/model/EclipseClasspath.java#L402-L406
if (outputPath.toLowerCase().contains("test")) {
sourceFolder.getEntryAttributes().put(TEST_ATTRIBUTE, "true")
}
classpath.entries.add(sourceFolder)
}
private static class AddSourceFoldersAction implements Action<Classpath> {
private final Project project
private final List<Object> androidSourceSets
AddSourceFoldersAction(Project project, List<Object> androidSourceSets) {
this.project = project
this.androidSourceSets = androidSourceSets
}
@Override
void execute(Classpath classpath) {
for (Object androidSourceSet : androidSourceSets) {
try {
Object javaDirectories = androidSourceSet.properties.get("javaDirectories")
String sourceSetName = androidSourceSet.properties.get("name")
if (javaDirectories instanceof Collection && sourceSetName instanceof String) {
for (Object javaDirectory : (Collection) javaDirectories) {
if (javaDirectory instanceof File) {
addFolderToSourceFolder(classpath, project, (File) javaDirectory, "bin/" + sourceSetName)
}
}
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
}
}
private static class AddDataBindingFilesAction implements Action<Classpath> {
private final Project project
private final FileReferenceFactory fileReferenceFactory
private final List<Object> variants
AddDataBindingFilesAction(Project project, List<Object> variants) {
this.project = project
this.fileReferenceFactory = new FileReferenceFactory()
this.variants = variants
}
@Override
void execute(Classpath classpath) {
for (Object variant : this.variants) {
try {
// TODO: get dataBinding task from variants?
String variantName = variant.properties.get("name")
String taskName = "dataBindingGenBaseClasses" + variantName.substring(0, 1).toUpperCase() + variantName.substring(1)
Task dataBindingGenTask = project.tasks.getByName(taskName)
Object outFolder = dataBindingGenTask.properties.get("sourceOutFolder").properties.get("orNull").properties.get("asFile")
if (outFolder instanceof File) {
addFolderToSourceFolder(classpath, project, (File) outFolder, DEFAULT_OUTPUT_MAIN)
}
} catch (NullPointerException | UnknownTaskException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
}
}
private static class AddRFilesAction implements Action<Classpath> {
private final Project project
private final FileReferenceFactory fileReferenceFactory
private final List<Object> variants
AddRFilesAction(Project project, List<Object> variants) {
this.project = project
this.fileReferenceFactory = new FileReferenceFactory()
this.variants = variants
}
@Override
void execute(Classpath classpath) {
for (Object variant : this.variants) {
try {
Object outputs = variant.properties.get("outputs")
if (outputs instanceof DefaultNamedDomainObjectCollection) {
for (Object output : outputs) {
// output.processResources.sourceOutputDir || output.processResources.RClassOutputJar
Object processResourcesTask = output.properties.get("processResources")
if (processResourcesTask.properties.containsKey("sourceOutputDir")) {
Object outputDir = processResourcesTask.properties.get("sourceOutputDir")
if (outputDir instanceof File) {
addRFileToClasspath(classpath, (File) outputDir)
continue
}
}
if (processResourcesTask.properties.containsKey("RClassOutputJar")) {
Object outputJar = processResourcesTask.properties.get("RClassOutputJar").properties.get("orNull").properties.get("asFile")
if (outputJar instanceof File) {
addRFileToClasspath(classpath, (File) outputJar)
}
}
}
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
}
private void addRFileToClasspath(Classpath classpath, File RFile) {
if (RFile.name.endsWith(".jar")) {
Library library = new Library(this.fileReferenceFactory.fromPath(project.getProjectDir().toPath().relativize(RFile.toPath()).toString()))
library.entryAttributes.put(OPTIONAL_ATTRIBUTE, "true")
classpath.entries.add(library)
} else {
addFolderToSourceFolder(classpath, this.project, RFile, DEFAULT_OUTPUT_MAIN)
}
}
}
private static class AddBuildConfigFilesAction implements Action<Classpath> {
private final Project project
private final List<Object> variants
AddBuildConfigFilesAction(Project project, List<Object> variants) {
this.project = project
this.variants = variants
}
@Override
void execute(Classpath classpath) {
for (Object variant : this.variants) {
try {
// for old AGP, the file instance can be directly got via variant.generateBuildConfig.sourceOutputDir
Object outputDir = variant.properties.get("generateBuildConfig").properties.get("sourceOutputDir")
if (outputDir instanceof File) {
addFolderToSourceFolder(classpath, this.project, (File) outputDir, DEFAULT_OUTPUT_MAIN)
} else {
// for newer AGP, the file instance can be got via variant.generateBuildConfig.sourceOutputDir.orNull.asFile
Object outputDirFile = outputDir.properties.get("orNull").properties.get("asFile")
if (outputDirFile instanceof File) {
addFolderToSourceFolder(classpath, this.project, (File) outputDirFile, DEFAULT_OUTPUT_MAIN)
}
}
} catch (NullPointerException ignored) {
// NPE occurs when the variant doesn't have related properties, we just skip these unsupported scenarios
}
}
}
}
private static class AddAndroidSDKAction implements Action<Classpath> {
private final FileReferenceFactory fileReferenceFactory
private final File androidSDKFile
AddAndroidSDKAction(File androidSDKFile) {
this.fileReferenceFactory = new FileReferenceFactory()
this.androidSDKFile = androidSDKFile
}
@Override
void execute(Classpath classpath) {
Library library = new Library(fileReferenceFactory.fromFile(androidSDKFile))
File platformsDir = androidSDKFile.getParentFile() // android-sdk/platforms/android-XX
String platformBasename = platformsDir.getName() // android-XX
File sourcesDir = new File(platformsDir.getParentFile().getParentFile(), "sources" + File.separator + platformBasename)
if (sourcesDir.exists() && sourcesDir.isDirectory()) {
library.setSourcePath(fileReferenceFactory.fromFile(sourcesDir))
}
classpath.entries.add(library)
}
}
private static class AddProjectDependenciesAction implements Action<Classpath> {
private static final String EXTRACT_AAR_RELATIVE_PATH = "aarLibraries"
private static final String AAR_EXTENSION = ".aar"
private static final String DEPENDENCY_ENTRY_NAME = "classes.jar"
private final Project project
private final FileReferenceFactory fileReferenceFactory
AddProjectDependenciesAction(Project project) {
this.project = project
this.fileReferenceFactory = new FileReferenceFactory()
}
@Override
void execute(Classpath classpath) {
List<ClasspathEntry> jarEntries = new ArrayList<>()
for (ClasspathEntry entry : classpath.entries) {
if (entry instanceof Library && ((Library) entry).path.endsWith(AAR_EXTENSION)) {
ClasspathEntry aarClasspathEntry = getClasspathEntryFromAAR((Library) entry)
if (aarClasspathEntry != null) {
jarEntries.add(aarClasspathEntry)
}
} else {
jarEntries.add(entry)
}
}
classpath.setEntries(jarEntries)
}
private ClasspathEntry getClasspathEntryFromAAR(Library aarLibrary) {
String libraryName = aarLibrary.getModuleVersion().toString().replaceAll(":", "-")
Path libraryFolderPath = Paths.get(project.buildDir.absolutePath, EXTRACT_AAR_RELATIVE_PATH)
File libraryFolder = libraryFolderPath.toFile()
if (!libraryFolder.exists()) {
if (!libraryFolder.mkdirs()) {
return null
}
}
Path libraryPath = libraryFolderPath.resolve(Paths.get(libraryName + ".jar"))
File libraryFile = libraryPath.toFile()
if (!libraryFile.exists()) {
ZipFile zipFile = null
try {
zipFile = new ZipFile(new File(aarLibrary.getPath()))
for (ZipEntry entry : zipFile.entries()) {
if (entry.name == DEPENDENCY_ENTRY_NAME) {
InputStream ins = zipFile.getInputStream(entry)
Files.copy(ins, libraryPath)
break
}
}
} catch (IOException | NullPointerException ignored) {
return null
} finally {
if (zipFile != null) {
zipFile.close()
}
}
}
if (libraryFile.exists()) {
Library library = new Library(fileReferenceFactory.fromFile(libraryFile))
library.setSourcePath(aarLibrary.getSourcePath())
return library
}
return null
}
}
}
allprojects {
apply plugin: 'eclipse'
// using workaround from
// https://github.com/eclipse-jdtls/eclipse.jdt.ls/issues/3284#issuecomment-2566480071
afterEvaluate {
afterEvaluate {
it.getPlugins().apply(JavaLanguageServerAndroidPlugin)
}
}
}