-
Notifications
You must be signed in to change notification settings - Fork 28.1k
/
Copy pathflutter.groovy
1794 lines (1638 loc) · 81.7 KB
/
flutter.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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* groovylint-disable LineLength, UnnecessaryGString, UnnecessaryGetter */
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import com.android.build.OutputFile
import com.flutter.gradle.BaseApplicationNameHandler
import com.flutter.gradle.Deeplink
import com.flutter.gradle.DependencyVersionChecker
import com.flutter.gradle.IntentFilterCheck
import com.flutter.gradle.VersionUtils
import groovy.json.JsonGenerator
import groovy.xml.QName
import java.nio.file.Paths
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.Task
import org.gradle.api.UnknownTaskException
import org.gradle.api.file.CopySpec
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.LogLevel
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Jar
import org.gradle.internal.os.OperatingSystem
/**
* For apps only. Provides the flutter extension used in the app-level Gradle
* build file (app/build.gradle or app/build.gradle.kts).
*
* The versions specified here should match the values in
* packages/flutter_tools/lib/src/android/gradle_utils.dart, so when bumping,
* make sure to update the versions specified there.
*
* Learn more about extensions in Gradle:
* * https://docs.gradle.org/8.0.2/userguide/custom_plugins.html#sec:getting_input_from_the_build
*/
class FlutterExtension {
/** Sets the compileSdkVersion used by default in Flutter app projects. */
public final int compileSdkVersion = 35
/** Sets the minSdkVersion used by default in Flutter app projects. */
public final int minSdkVersion = 21
/**
* Sets the targetSdkVersion used by default in Flutter app projects.
* targetSdkVersion should always be the latest available stable version.
*
* See https://developer.android.com/guide/topics/manifest/uses-sdk-element.
*/
public final int targetSdkVersion = 35
/**
* Sets the ndkVersion used by default in Flutter app projects.
* Chosen as default version of the AGP version below as found in
* https://developer.android.com/studio/projects/install-ndk#default-ndk-per-agp.
*/
public final String ndkVersion = "26.3.11579264"
/**
* Specifies the relative directory to the Flutter project directory.
* In an app project, this is ../.. since the app's Gradle build file is under android/app.
*/
String source = "../.."
/** Allows to override the target file. Otherwise, the target is lib/main.dart. */
String target
/** The versionCode that was read from app's local.properties. */
public String flutterVersionCode = null
/** The versionName that was read from app's local.properties. */
public String flutterVersionName = null
/** Returns flutterVersionCode as an integer with error handling. */
Integer getVersionCode() {
if (flutterVersionCode == null) {
throw new GradleException("flutterVersionCode must not be null.")
}
if (!flutterVersionCode.isNumber()) {
throw new GradleException("flutterVersionCode must be an integer.")
}
return flutterVersionCode.toInteger()
}
/** Returns flutterVersionName with error handling. */
String getVersionName() {
if (flutterVersionName == null) {
throw new GradleException("flutterVersionName must not be null.")
}
return flutterVersionName
}
}
class FlutterPlugin implements Plugin<Project> {
private static final String DEFAULT_MAVEN_HOST = "https://storage.googleapis.com"
/** The platforms that can be passed to the `--Ptarget-platform` flag. */
private static final String PLATFORM_ARM32 = "android-arm"
private static final String PLATFORM_ARM64 = "android-arm64"
private static final String PLATFORM_X86 = "android-x86"
private static final String PLATFORM_X86_64 = "android-x64"
/** The ABI architectures supported by Flutter. */
private static final String ARCH_ARM32 = "armeabi-v7a"
private static final String ARCH_ARM64 = "arm64-v8a"
private static final String ARCH_X86 = "x86"
private static final String ARCH_X86_64 = "x86_64"
private static final String INTERMEDIATES_DIR = "intermediates"
/** Maps platforms to ABI architectures. */
private static final Map PLATFORM_ARCH_MAP = [
(PLATFORM_ARM32) : ARCH_ARM32,
(PLATFORM_ARM64) : ARCH_ARM64,
(PLATFORM_X86) : ARCH_X86,
(PLATFORM_X86_64) : ARCH_X86_64,
]
/**
* The version code that gives each ABI a value.
* For each APK variant, use the following versions to override the version of the Universal APK.
* Otherwise, the Play Store will complain that the APK variants have the same version.
*/
private static final Map<String, Integer> ABI_VERSION = [
(ARCH_ARM32) : 1,
(ARCH_ARM64) : 2,
(ARCH_X86) : 3,
(ARCH_X86_64) : 4,
]
/** When split is enabled, multiple APKs are generated per each ABI. */
private static final List DEFAULT_PLATFORMS = [
PLATFORM_ARM32,
PLATFORM_ARM64,
PLATFORM_X86_64,
]
private final static String propLocalEngineRepo = "local-engine-repo"
private final static String propProcessResourcesProvider = "processResourcesProvider"
/**
* The name prefix for flutter builds. This is used to identify gradle tasks
* where we expect the flutter tool to provide any error output, and skip the
* standard Gradle error output in the FlutterEventLogger. If you change this,
* be sure to change any instances of this string in symbols in the code below
* to match.
*/
static final String FLUTTER_BUILD_PREFIX = "flutterBuild"
private Project project
private File flutterRoot
private File flutterExecutable
private String localEngine
private String localEngineHost
private String localEngineSrcPath
private Properties localProperties
private String engineVersion
private String engineRealm
private List<Map<String, Object>> pluginList
private List<Map<String, Object>> pluginDependencies
/**
* Flutter Docs Website URLs for help messages.
*/
private final String kWebsiteDeploymentAndroidBuildConfig = "https://flutter.dev/to/review-gradle-config"
@Override
void apply(Project project) {
this.project = project
Project rootProject = project.rootProject
if (isFlutterAppProject()) {
rootProject.tasks.register("generateLockfiles") {
doLast {
rootProject.subprojects.each { subproject ->
String gradlew = (OperatingSystem.current().isWindows()) ?
"${rootProject.projectDir}/gradlew.bat" : "${rootProject.projectDir}/gradlew"
rootProject.exec {
workingDir(rootProject.projectDir)
executable(gradlew)
args(":${subproject.name}:dependencies", "--write-locks")
}
}
}
}
}
String flutterRootPath = resolveProperty("flutter.sdk", System.getenv("FLUTTER_ROOT"))
if (flutterRootPath == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file or with a FLUTTER_ROOT environment variable.")
}
flutterRoot = project.file(flutterRootPath)
if (!flutterRoot.isDirectory()) {
throw new GradleException("flutter.sdk must point to the Flutter SDK directory")
}
engineVersion = useLocalEngine()
? "+" // Match any version since there's only one.
: "1.0.0-" + Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.version").toFile().text.trim()
engineRealm = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.realm").toFile().text.trim()
if (engineRealm) {
engineRealm += "/"
}
// Configure the Maven repository.
String hostedRepository = System.getenv("FLUTTER_STORAGE_BASE_URL") ?: DEFAULT_MAVEN_HOST
String repository = useLocalEngine()
? project.property(propLocalEngineRepo)
: "$hostedRepository/${engineRealm}download.flutter.io"
rootProject.allprojects {
repositories {
maven {
url(repository)
}
}
}
// Load shared gradle functions
project.apply from: Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools", "gradle", "src", "main", "groovy", "native_plugin_loader.groovy")
FlutterExtension extension = project.extensions.create("flutter", FlutterExtension)
Properties localProperties = new Properties()
File localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader("UTF-8") { reader ->
localProperties.load(reader)
}
}
extension.flutterVersionCode = localProperties.getProperty("flutter.versionCode", "1")
extension.flutterVersionName = localProperties.getProperty("flutter.versionName", "1.0")
this.addFlutterTasks(project)
forceNdkDownload(project, flutterRootPath)
// By default, assembling APKs generates fat APKs if multiple platforms are passed.
// Configuring split per ABI allows to generate separate APKs for each abi.
// This is a noop when building a bundle.
if (shouldSplitPerAbi()) {
project.android {
splits {
abi {
// Enables building multiple APKs per ABI.
enable(true)
// Resets the list of ABIs that Gradle should create APKs for to none.
reset()
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk(false)
}
}
}
}
final String propDeferredComponentNames = "deferred-component-names"
if (project.hasProperty(propDeferredComponentNames)) {
String[] componentNames = project.property(propDeferredComponentNames).split(",").collect {":${it}"}
project.android {
dynamicFeatures = componentNames
}
}
getTargetPlatforms().each { targetArch ->
String abiValue = PLATFORM_ARCH_MAP[targetArch]
project.android {
if (shouldSplitPerAbi()) {
splits {
abi {
include(abiValue)
}
}
}
}
}
String flutterExecutableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "flutter.bat" : "flutter"
flutterExecutable = Paths.get(flutterRoot.absolutePath, "bin", flutterExecutableName).toFile()
// Validate that the provided Gradle, Java, AGP, and KGP versions are all within our
// supported range.
// TODO(gmackall) Dependency version checking is currently implemented as an additional
// Gradle plugin because we can't import it from Groovy code. As part of the Groovy
// -> Kotlin migration, we should remove this complexity and perform the checks inside
// of the main Flutter Gradle Plugin.
// See https://github.com/flutter/flutter/issues/121541#issuecomment-1920363687.
final Boolean shouldSkipDependencyChecks = project.hasProperty("skipDependencyChecks") && project.getProperty("skipDependencyChecks")
if (!shouldSkipDependencyChecks) {
try {
DependencyVersionChecker.checkDependencyVersions(project)
} catch (Exception e) {
if (!project.hasProperty("usesUnsupportedDependencyVersions") || !project.usesUnsupportedDependencyVersions) {
// Possible bug in dependency checking code - warn and do not block build.
project.logger.error("Warning: Flutter was unable to detect project Gradle, Java, " +
"AGP, and KGP versions. Skipping dependency version checking. Error was: "
+ e)
}
else {
// If usesUnsupportedDependencyVersions is set, the exception was thrown by us
// in the dependency version checker plugin so re-throw it here.
throw e
}
}
}
// Use Kotlin source to handle baseApplicationName logic due to Groovy dynamic dispatch bug.
BaseApplicationNameHandler.setBaseName(project)
String flutterProguardRules = Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools",
"gradle", "flutter_proguard_rules.pro")
project.android.buildTypes {
// Add profile build type.
profile {
initWith(debug)
if (it.hasProperty("matchingFallbacks")) {
matchingFallbacks = ["debug", "release"]
}
}
// TODO(garyq): Shrinking is only false for multi apk split aot builds, where shrinking is not allowed yet.
// This limitation has been removed experimentally in gradle plugin version 4.2, so we can remove
// this check when we upgrade to 4.2+ gradle. Currently, deferred components apps may see
// increased app size due to this.
if (shouldShrinkResources(project)) {
release {
// Enables code shrinking, obfuscation, and optimization for only
// your project's release build type.
minifyEnabled(true)
// Enables resource shrinking, which is performed by the Android Gradle plugin.
// The resource shrinker can't be used for libraries.
shrinkResources(isBuiltAsApp(project))
// Fallback to `android/app/proguard-rules.pro`.
// This way, custom Proguard rules can be configured as needed.
proguardFiles(project.android.getDefaultProguardFile("proguard-android-optimize.txt"), flutterProguardRules, "proguard-rules.pro")
}
}
}
if (useLocalEngine()) {
// This is required to pass the local engine to flutter build aot.
String engineOutPath = project.property("local-engine-out")
File engineOut = project.file(engineOutPath)
if (!engineOut.isDirectory()) {
throw new GradleException("local-engine-out must point to a local engine build")
}
localEngine = engineOut.name
localEngineSrcPath = engineOut.parentFile.parent
String engineHostOutPath = project.property("local-engine-host-out")
File engineHostOut = project.file(engineHostOutPath)
if (!engineHostOut.isDirectory()) {
throw new GradleException("local-engine-host-out must point to a local engine host build")
}
localEngineHost = engineHostOut.name
}
project.android.buildTypes.all(this.&addFlutterDependencies)
}
private static Boolean shouldShrinkResources(Project project) {
final String propShrink = "shrink"
if (project.hasProperty(propShrink)) {
return project.property(propShrink).toBoolean()
}
return true
}
private static String toCamelCase(List<String> parts) {
if (parts.empty) {
return ""
}
return "${parts[0]}${parts[1..-1].collect { it.capitalize() }.join('')}"
}
private static Properties readPropertiesIfExist(File propertiesFile) {
Properties result = new Properties()
if (propertiesFile.exists()) {
propertiesFile.withReader("UTF-8") { reader -> result.load(reader) }
}
return result
}
private static Boolean isBuiltAsApp(Project project) {
// Projects are built as applications when the they use the `com.android.application`
// plugin.
return project.plugins.hasPlugin("com.android.application")
}
private static void addApiDependencies(Project project, String variantName, Object dependency, Closure config = null) {
String configuration
// `compile` dependencies are now `api` dependencies.
try{
project.getConfigurations().named("api")
configuration = "${variantName}Api"
} catch(UnknownTaskException ignored) {
configuration = "${variantName}Compile"
}
project.dependencies.add(configuration, dependency, config)
}
// Add a task that can be called on flutter projects that prints the Java version used in Gradle.
//
// Format of the output of this task can be used in debugging what version of Java Gradle is using.
// Not recommended for use in time sensitive commands like `flutter run` or `flutter build` as
// Gradle is slower than we want. Particularly in light of https://github.com/flutter/flutter/issues/119196.
private static void addTaskForJavaVersion(Project project) {
// Warning: the name of this task is used by other code. Change with caution.
project.tasks.register("javaVersion") {
description "Print the current java version used by gradle. "
"see: https://docs.gradle.org/current/javadoc/org/gradle/api/JavaVersion.html"
doLast {
println(JavaVersion.current())
}
}
}
// Add a task that can be called on Flutter projects that prints the available build variants
// in Gradle.
//
// This task prints variants in this format:
//
// BuildVariant: debug
// BuildVariant: release
// BuildVariant: profile
//
// Format of the output of this task is used by `AndroidProject.getBuildVariants`.
private static void addTaskForPrintBuildVariants(Project project) {
// Warning: The name of this task is used by `AndroidProject.getBuildVariants`.
project.tasks.register("printBuildVariants") {
description "Prints out all build variants for this Android project"
doLast {
project.android.applicationVariants.all { variant ->
println "BuildVariant: ${variant.name}"
}
}
}
}
// Add a task that can be called on Flutter projects that outputs app link related project
// settings into a json file.
//
// See https://developer.android.com/training/app-links/ for more information about app link.
//
// The json will be saved in path stored in outputPath parameter.
//
// An example json:
// {
// applicationId: "com.example.app",
// deeplinks: [
// {"scheme":"http", "host":"example.com", "path":".*"},
// {"scheme":"https","host":"example.com","path":".*"}
// ]
// }
//
// The output file is parsed and used by devtool.
private static void addTasksForOutputsAppLinkSettings(Project project) {
project.android.applicationVariants.all { variant ->
// Warning: The name of this task is used by AndroidBuilder.outputsAppLinkSettings
project.tasks.register("output${variant.name.capitalize()}AppLinkSettings") {
description "stores app links settings for the given build variant of this Android project into a json file."
variant.outputs.configureEach { output ->
// Deeplinks are defined in AndroidManifest.xml and is only available after
// `processResourcesProvider`.
Object processResources = output.hasProperty(propProcessResourcesProvider) ?
output.processResourcesProvider.get() : output.processResources
dependsOn processResources.name
}
doLast {
AppLinkSettings appLinkSettings = new AppLinkSettings()
appLinkSettings.applicationId = variant.applicationId
appLinkSettings.deeplinks = [] as Set<Deeplink>
variant.outputs.configureEach { output ->
Object processResources = output.hasProperty(propProcessResourcesProvider) ?
output.processResourcesProvider.get() : output.processResources
def manifest = new XmlParser().parse(processResources.manifestFile)
manifest.application.activity.each { activity ->
activity."meta-data".each { metadata ->
boolean nameAttribute = metadata.attributes().find { it.key == 'android:name' }?.value == 'flutter_deeplinking_enabled'
boolean valueAttribute = metadata.attributes().find { it.key == 'android:value' }?.value == 'true'
if (nameAttribute && valueAttribute) {
appLinkSettings.deeplinkingFlagEnabled = true
}
}
activity."intent-filter".each { appLinkIntent ->
// Print out the host attributes in data tags.
Set<String> schemes = [] as Set<String>
Set<String> hosts = [] as Set<String>
Set<String> paths = [] as Set<String>
IntentFilterCheck intentFilterCheck = new IntentFilterCheck()
if (appLinkIntent.attributes().find { it.key == 'android:autoVerify' }?.value == 'true') {
intentFilterCheck.hasAutoVerify = true
}
appLinkIntent.'action'.each { action ->
if (action.attributes().find { it.key == 'android:name' }?.value == 'android.intent.action.VIEW') {
intentFilterCheck.hasActionView = true
}
}
appLinkIntent.'category'.each { category ->
if (category.attributes().find { it.key == 'android:name' }?.value == 'android.intent.category.DEFAULT') {
intentFilterCheck.hasDefaultCategory = true
}
if (category.attributes().find { it.key == 'android:name' }?.value == 'android.intent.category.BROWSABLE') {
intentFilterCheck.hasBrowsableCategory = true
}
}
appLinkIntent.data.each { data ->
data.attributes().each { entry ->
if (entry.key instanceof QName) {
switch (entry.key.getLocalPart()) {
case "scheme":
schemes.add(entry.value)
break
case "host":
hosts.add(entry.value)
break
case "pathAdvancedPattern":
case "pathPattern":
case "path":
paths.add(entry.value)
break
case "pathPrefix":
paths.add("${entry.value}.*")
break
case "pathSuffix":
paths.add(".*${entry.value}")
break
}
}
}
}
if(!hosts.isEmpty() || !paths.isEmpty()){
if(schemes.isEmpty()){schemes.add(null)}
if(hosts.isEmpty()){hosts.add(null)}
if(paths.isEmpty()){paths.add('.*')}
schemes.each { scheme ->
hosts.each { host ->
paths.each { path ->
appLinkSettings.deeplinks.add(new Deeplink(scheme, host, path, intentFilterCheck))
}
}
}
}
}
}
}
JsonGenerator generator = new JsonGenerator.Options().build()
new File(project.getProperty("outputPath")).write(generator.toJson(appLinkSettings))
}
}
}
}
/**
* Returns a Flutter build mode suitable for the specified Android buildType.
*
* The BuildType DSL type is not public, and is therefore omitted from the signature.
*
* @return "debug", "profile", or "release" (fall-back).
*/
private static String buildModeFor(buildType) {
if (buildType.name == "profile") {
return "profile"
} else if (buildType.debuggable) {
return "debug"
}
return "release"
}
/**
* Adds the dependencies required by the Flutter project.
* This includes:
* 1. The embedding
* 2. libflutter.so
*/
void addFlutterDependencies(buildType) {
String flutterBuildMode = buildModeFor(buildType)
if (!supportsBuildMode(flutterBuildMode)) {
return
}
// The embedding is set as an API dependency in a Flutter plugin.
// Therefore, don't make the app project depend on the embedding if there are Flutter
// plugin dependencies. In release mode, dev dependencies are stripped, so we do not
// consider those in the check.
// This prevents duplicated classes when using custom build types. That is, a custom build
// type like profile is used, and the plugin and app projects have API dependencies on the
// embedding.
List<Map<String, Object>> pluginsThatIncludeFlutterEmbeddingAsTransitiveDependency = flutterBuildMode == "release" ? getPluginListWithoutDevDependencies(project) : getPluginList(project);
if (!isFlutterAppProject() || pluginsThatIncludeFlutterEmbeddingAsTransitiveDependency.size() == 0) {
addApiDependencies(project, buildType.name,
"io.flutter:flutter_embedding_$flutterBuildMode:$engineVersion")
}
List<String> platforms = getTargetPlatforms().collect()
platforms.each { platform ->
String arch = PLATFORM_ARCH_MAP[platform].replace("-", "_")
// Add the `libflutter.so` dependency.
addApiDependencies(project, buildType.name,
"io.flutter:${arch}_$flutterBuildMode:$engineVersion")
}
}
/**
* Configures the Flutter plugin dependencies.
*
* The plugins are added to pubspec.yaml. Then, upon running `flutter pub get`,
* the tool generates a `.flutter-plugins-dependencies` file, which contains a map to each plugin location.
* Finally, the project's `settings.gradle` loads each plugin's android directory as a subproject.
*/
private void configurePlugins(Project project) {
configureLegacyPluginEachProjects(project)
getPluginList(project).each(this.&configurePluginProject)
getPluginList(project).each(this.&configurePluginDependencies)
}
// TODO(54566, 48918): Can remove once the issues are resolved.
// This means all references to `.flutter-plugins` are then removed and
// apps only depend exclusively on the `plugins` property in `.flutter-plugins-dependencies`.
/**
* Workaround to load non-native plugins for developers who may still use an
* old `settings.gradle` which includes all the plugins from the
* `.flutter-plugins` file, even if not made for Android.
* The settings.gradle then:
* 1) tries to add the android plugin implementation, which does not
* exist at all, but is also not included successfully
* (which does not throw an error and therefore isn't a problem), or
* 2) includes the plugin successfully as a valid android plugin
* directory exists, even if the surrounding flutter package does not
* support the android platform (see e.g. apple_maps_flutter: 1.0.1).
* So as it's included successfully it expects to be added as API.
* This is only possible by taking all plugins into account, which
* only appear on the `dependencyGraph` and in the `.flutter-plugins` file.
* So in summary the plugins are currently selected from the `dependencyGraph`
* and filtered then with the [doesSupportAndroidPlatform] method instead of
* just using the `plugins.android` list.
*/
private void configureLegacyPluginEachProjects(Project project) {
try {
// Read the contents of the settings.gradle file.
// Remove block/line comments
String settingsText = settingsGradleFile(project).text
settingsText = settingsText.replaceAll(/(?s)\/\*.*?\*\//, '').replaceAll(/(?m)\/\/.*$/, '')
if (!settingsText.contains("'.flutter-plugins'")) {
return
}
} catch (FileNotFoundException ignored) {
throw new GradleException("settings.gradle/settings.gradle.kts does not exist: ${settingsGradleFile(project).absolutePath}")
}
// TODO(matanlurey): https://github.com/flutter/flutter/issues/48918.
project.logger.quiet("Warning: This project is still reading the deprecated '.flutter-plugins. file.")
project.logger.quiet("In an upcoming stable release support for this file will be completely removed and your build will fail.")
project.logger.quiet("See https:/flutter.dev/to/flutter-plugins-configuration.")
List<Map<String, Object>> deps = getPluginDependencies(project)
List<String> plugins = getPluginList(project).collect { it.name as String }
deps.removeIf { plugins.contains(it.name) }
deps.each {
Project pluginProject = project.rootProject.findProject(":${it.name}")
if (pluginProject == null) {
// Plugin was not included in `settings.gradle`, but is listed in `.flutter-plugins`.
project.logger.error("Plugin project :${it.name} listed, but not found. Please fix your settings.gradle/settings.gradle.kts.")
} else if (pluginSupportsAndroidPlatform(pluginProject)) {
// Plugin has a functioning `android` folder and is included successfully, although it's not supported.
// It must be configured nonetheless, to not throw an "Unresolved reference" exception.
configurePluginProject(it)
/* groovylint-disable-next-line EmptyElseBlock */
} else {
// Plugin has no or an empty `android` folder. No action required.
}
}
}
// TODO(54566): Can remove this function and its call sites once resolved.
/**
* Returns `true` if the given project is a plugin project having an `android` directory
* containing a `build.gradle` or `build.gradle.kts` file.
*/
private static Boolean pluginSupportsAndroidPlatform(Project project) {
File buildGradle = new File(project.projectDir.parentFile, "android" + File.separator + "build.gradle")
File buildGradleKts = new File(project.projectDir.parentFile, "android" + File.separator + "build.gradle.kts")
return buildGradle.exists() || buildGradleKts.exists()
}
/**
* Returns the Gradle build script for the build. When both Groovy and
* Kotlin variants exist, then Groovy (build.gradle) is preferred over
* Kotlin (build.gradle.kts). This is the same behavior as Gradle 8.5.
*/
private static File buildGradleFile(Project project) {
File buildGradle = new File(project.projectDir.parentFile, "app" + File.separator + "build.gradle")
File buildGradleKts = new File(project.projectDir.parentFile, "app" + File.separator + "build.gradle.kts")
if (buildGradle.exists() && buildGradleKts.exists()) {
project.logger.error(
"Both build.gradle and build.gradle.kts exist, so " +
"build.gradle.kts is ignored. This is likely a mistake."
)
}
return buildGradle.exists() ? buildGradle : buildGradleKts
}
/**
* Returns the Gradle settings script for the build. When both Groovy and
* Kotlin variants exist, then Groovy (settings.gradle) is preferred over
* Kotlin (settings.gradle.kts). This is the same behavior as Gradle 8.5.
*/
private static File settingsGradleFile(Project project) {
File settingsGradle = new File(project.projectDir.parentFile, "settings.gradle")
File settingsGradleKts = new File(project.projectDir.parentFile, "settings.gradle.kts")
if (settingsGradle.exists() && settingsGradleKts.exists()) {
project.logger.error(
"Both settings.gradle and settings.gradle.kts exist, so " +
"settings.gradle.kts is ignored. This is likely a mistake."
)
}
return settingsGradle.exists() ? settingsGradle : settingsGradleKts
}
/** Adds the plugin project dependency to the app project. */
private void configurePluginProject(Map<String, Object> pluginObject) {
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
// Apply the "flutter" Gradle extension to plugins so that they can use it's vended
// compile/target/min sdk values.
pluginProject.extensions.create("flutter", FlutterExtension)
// Add plugin dependency to the app project. We only want to add dependency
// for dev dependencies in non-release builds.
project.afterEvaluate {
project.android.buildTypes.all { buildType ->
if (!pluginObject.dev_dependency || buildType.name != 'release') {
project.dependencies.add("${buildType.name}Api", pluginProject)
}
}
}
Closure addEmbeddingDependencyToPlugin = { buildType ->
String flutterBuildMode = buildModeFor(buildType)
// In AGP 3.5, the embedding must be added as an API implementation,
// so java8 features are desugared against the runtime classpath.
// For more, see https://github.com/flutter/flutter/issues/40126
if (!supportsBuildMode(flutterBuildMode)) {
return
}
if (!pluginProject.hasProperty("android")) {
return
}
// Copy build types from the app to the plugin.
// This allows to build apps with plugins and custom build types or flavors.
pluginProject.android.buildTypes {
"${buildType.name}" {}
}
// The embedding is API dependency of the plugin, so the AGP is able to desugar
// default method implementations when the interface is implemented by a plugin.
//
// See https://issuetracker.google.com/139821726, and
// https://github.com/flutter/flutter/issues/72185 for more details.
addApiDependencies(
pluginProject,
buildType.name,
"io.flutter:flutter_embedding_$flutterBuildMode:$engineVersion"
)
}
// Wait until the Android plugin loaded.
pluginProject.afterEvaluate {
// Checks if there is a mismatch between the plugin compileSdkVersion and the project compileSdkVersion.
if (pluginProject.android.compileSdkVersion > project.android.compileSdkVersion) {
project.logger.quiet("Warning: The plugin ${pluginObject.name} requires Android SDK version ${getCompileSdkFromProject(pluginProject)} or higher.")
project.logger.quiet("For more information about build configuration, see $kWebsiteDeploymentAndroidBuildConfig.")
}
project.android.buildTypes.all(addEmbeddingDependencyToPlugin)
}
}
private void forceNdkDownload(Project gradleProject, String flutterSdkRootPath) {
// If the project is already configuring a native build, we don't need to do anything.
Boolean forcingNotRequired = gradleProject.android.externalNativeBuild.cmake.path != null
if (forcingNotRequired) {
return
}
// Otherwise, point to an empty CMakeLists.txt, and ignore associated warnings.
gradleProject.android {
externalNativeBuild {
cmake {
// Respect the existing configuration if it exists - the NDK will already be
// downloaded in this case.
path = flutterSdkRootPath + "/packages/flutter_tools/gradle/src/main/groovy/CMakeLists.txt"
}
}
defaultConfig {
externalNativeBuild {
cmake {
// CMake will print warnings when you try to build an empty project.
// These arguments silence the warnings - our project is intentionally
// empty.
arguments("-Wno-dev", "--no-warn-unused-cli")
}
}
}
}
}
/** Prints error message and fix for any plugin compileSdkVersion or ndkVersion that are higher than the project. */
private void detectLowCompileSdkVersionOrNdkVersion() {
project.afterEvaluate {
// Default to int max if using a preview version to skip the sdk check.
int projectCompileSdkVersion = Integer.MAX_VALUE
// Stable versions use ints, legacy preview uses string.
if (getCompileSdkFromProject(project).isInteger()) {
projectCompileSdkVersion = getCompileSdkFromProject(project) as int
}
int maxPluginCompileSdkVersion = projectCompileSdkVersion
String ndkVersionIfUnspecified = "21.1.6352462" /* The default for AGP 4.1.0 used in old templates. */
String projectNdkVersion = project.android.ndkVersion ?: ndkVersionIfUnspecified
String maxPluginNdkVersion = projectNdkVersion
int numProcessedPlugins = getPluginList(project).size()
List<Tuple2<String, String>> pluginsWithHigherSdkVersion = []
List<Tuple2<String, String>> pluginsWithDifferentNdkVersion = []
getPluginList(project).each { pluginObject ->
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
pluginProject.afterEvaluate {
// Default to int min if using a preview version to skip the sdk check.
int pluginCompileSdkVersion = Integer.MIN_VALUE
// Stable versions use ints, legacy preview uses string.
if (getCompileSdkFromProject(pluginProject).isInteger()) {
pluginCompileSdkVersion = getCompileSdkFromProject(pluginProject) as int
}
maxPluginCompileSdkVersion = Math.max(pluginCompileSdkVersion, maxPluginCompileSdkVersion)
if (pluginCompileSdkVersion > projectCompileSdkVersion) {
pluginsWithHigherSdkVersion.add(new Tuple(pluginProject.name, pluginCompileSdkVersion))
}
String pluginNdkVersion = pluginProject.android.ndkVersion ?: ndkVersionIfUnspecified
maxPluginNdkVersion = VersionUtils.mostRecentSemanticVersion(pluginNdkVersion, maxPluginNdkVersion)
if (pluginNdkVersion != projectNdkVersion) {
pluginsWithDifferentNdkVersion.add(new Tuple(pluginProject.name, pluginNdkVersion))
}
numProcessedPlugins--
if (numProcessedPlugins == 0) {
if (maxPluginCompileSdkVersion > projectCompileSdkVersion) {
project.logger.error("Your project is configured to compile against Android SDK $projectCompileSdkVersion, but the following plugin(s) require to be compiled against a higher Android SDK version:")
for (Tuple2<String, String> pluginToCompileSdkVersion : pluginsWithHigherSdkVersion) {
project.logger.error("- ${pluginToCompileSdkVersion.v1} compiles against Android SDK ${pluginToCompileSdkVersion.v2}")
}
project.logger.error("""\
Fix this issue by compiling against the highest Android SDK version (they are backward compatible).
Add the following to ${buildGradleFile(project).path}:
android {
compileSdk = ${maxPluginCompileSdkVersion}
...
}
""".stripIndent())
}
if (maxPluginNdkVersion != projectNdkVersion) {
project.logger.error("Your project is configured with Android NDK $projectNdkVersion, but the following plugin(s) depend on a different Android NDK version:")
for (Tuple2<String, String> pluginToNdkVersion : pluginsWithDifferentNdkVersion) {
project.logger.error("- ${pluginToNdkVersion.v1} requires Android NDK ${pluginToNdkVersion.v2}")
}
project.logger.error("""\
Fix this issue by using the highest Android NDK version (they are backward compatible).
Add the following to ${buildGradleFile(project).path}:
android {
ndkVersion = \"${maxPluginNdkVersion}\"
...
}
""".stripIndent())
}
}
}
}
}
}
/**
* Returns the portion of the compileSdkVersion string that corresponds to either the numeric
* or string version.
*/
private static String getCompileSdkFromProject(Project gradleProject) {
return gradleProject.android.compileSdkVersion.substring(8)
}
/**
* Add the dependencies on other plugin projects to the plugin project.
* A plugin A can depend on plugin B. As a result, this dependency must be surfaced by
* making the Gradle plugin project A depend on the Gradle plugin project B.
*/
private void configurePluginDependencies(Map<String, Object> pluginObject) {
assert(pluginObject.name instanceof String)
Project pluginProject = project.rootProject.findProject(":${pluginObject.name}")
if (pluginProject == null) {
return
}
project.android.buildTypes.each { buildType ->
String flutterBuildMode = buildModeFor(buildType)
if (flutterBuildMode == "release" && pluginObject.dev_dependency) {
// This plugin is a dev dependency will not be included in the
// release build, so no need to add its dependencies.
return
}
def dependencies = pluginObject.dependencies
assert(dependencies instanceof List<String>)
dependencies.each { pluginDependencyName ->
if (pluginDependencyName.empty) {
return
}
Project dependencyProject = project.rootProject.findProject(":$pluginDependencyName")
if (dependencyProject == null) {
return
}
// Wait for the Android plugin to load and add the dependency to the plugin project.
pluginProject.afterEvaluate {
pluginProject.dependencies {
implementation(dependencyProject)
}
}
}
}
}
/**
* Gets the list of plugins (as map) that support the Android platform.
*
* The map value contains either the plugins `name` (String),
* its `path` (String), or its `dependencies` (List<String>).
* See [NativePluginLoader#getPlugins] in packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy
*/
private List<Map<String, Object>> getPluginList(Project project) {
if (pluginList == null) {
pluginList = project.ext.nativePluginLoader.getPlugins(getFlutterSourceDirectory())
}
return pluginList
}
/**
* Gets the list of plugins (as map) that support the Android platform and are dependencies of the
* Android project excluding dev dependencies.
*
* The map value contains either the plugins `name` (String),
* its `path` (String), or its `dependencies` (List<String>).
* See [NativePluginLoader#getPlugins] in packages/flutter_tools/gradle/src/main/groovy/native_plugin_loader.groovy
*/
private List<Map<String, Object>> getPluginListWithoutDevDependencies(Project project) {
List<Map<String, Object>> pluginListWithoutDevDependencies = []
for (Map<String, Object> plugin in getPluginList(project)) {
if (!plugin.dev_dependency) {
pluginListWithoutDevDependencies += plugin
}
}
return pluginListWithoutDevDependencies
}
// TODO(54566, 48918): Remove in favor of [getPluginList] only, see also
// https://github.com/flutter/flutter/blob/1c90ed8b64d9ed8ce2431afad8bc6e6d9acc4556/packages/flutter_tools/lib/src/flutter_plugins.dart#L212
/** Gets the plugins dependencies from `.flutter-plugins-dependencies`. */
private List<Map<String, Object>> getPluginDependencies(Project project) {
if (pluginDependencies == null) {
Map meta = project.ext.nativePluginLoader.getDependenciesMetadata(getFlutterSourceDirectory())
if (meta == null) {
pluginDependencies = []
} else {
assert(meta.dependencyGraph instanceof List<Map>)
pluginDependencies = meta.dependencyGraph as List<Map<String, Object>>
}
}
return pluginDependencies
}
private String resolveProperty(String name, String defaultValue) {
if (localProperties == null) {
localProperties = readPropertiesIfExist(new File(project.projectDir.parentFile, "local.properties"))