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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
// 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 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'package:xml/xml.dart';
import '../artifacts.dart';
import '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/deferred_component.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/net.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../base/project_migrator.dart';
import '../base/terminal.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../cache.dart';
import '../convert.dart';
import '../flutter_manifest.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../reporting/reporting.dart';
import 'android_builder.dart';
import 'android_studio.dart';
import 'gradle_errors.dart';
import 'gradle_utils.dart';
import 'java.dart';
import 'migrations/android_studio_java_gradle_conflict_migration.dart';
import 'migrations/min_sdk_version_migration.dart';
import 'migrations/top_level_gradle_build_file_migration.dart';
import 'multidex.dart';
/// The regex to grab variant names from printBuildVariants gradle task
///
/// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy
///
/// The expected output from the task should be similar to:
///
/// BuildVariant: debug
/// BuildVariant: release
/// BuildVariant: profile
final RegExp _kBuildVariantRegex = RegExp('^BuildVariant: (?<$_kBuildVariantRegexGroupName>.*)\$');
const String _kBuildVariantRegexGroupName = 'variant';
const String _kBuildVariantTaskName = 'printBuildVariants';
/// The regex to grab variant names from print${BuildVariant}ApplicationId gradle task
///
/// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy
///
/// The expected output from the task should be similar to:
///
/// ApplicationId: com.example.my_id
final RegExp _kApplicationIdRegex = RegExp('^ApplicationId: (?<$_kApplicationIdRegexGroupName>.*)\$');
const String _kApplicationIdRegexGroupName = 'applicationId';
String _getPrintApplicationIdTaskFor(String buildVariant) {
return _taskForBuildVariant('print', buildVariant, 'ApplicationId');
}
/// The regex to grab app link domains from print${BuildVariant}AppLinkDomains gradle task
///
/// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy
///
/// The expected output from the task should be similar to:
///
/// Domain: domain.com
/// Domain: another-domain.dev
final RegExp _kAppLinkDomainsRegex = RegExp('^Domain: (?<$_kAppLinkDomainsGroupName>.*)\$');
const String _kAppLinkDomainsGroupName = 'domain';
String _getPrintAppLinkDomainsTaskFor(String buildVariant) {
return _taskForBuildVariant('print', buildVariant, 'AppLinkDomains');
}
/// The directory where the APK artifact is generated.
Directory getApkDirectory(FlutterProject project) {
return project.isModule
? project.android.buildDirectory
.childDirectory('host')
.childDirectory('outputs')
.childDirectory('apk')
: project.android.buildDirectory
.childDirectory('app')
.childDirectory('outputs')
.childDirectory('flutter-apk');
}
/// The directory where the app bundle artifact is generated.
@visibleForTesting
Directory getBundleDirectory(FlutterProject project) {
return project.isModule
? project.android.buildDirectory
.childDirectory('host')
.childDirectory('outputs')
.childDirectory('bundle')
: project.android.buildDirectory
.childDirectory('app')
.childDirectory('outputs')
.childDirectory('bundle');
}
/// The directory where the repo is generated.
/// Only applicable to AARs.
Directory getRepoDirectory(Directory buildDirectory) {
return buildDirectory
.childDirectory('outputs')
.childDirectory('repo');
}
/// Returns the name of Gradle task that starts with [prefix].
String _taskFor(String prefix, BuildInfo buildInfo) {
final String buildType = camelCase(buildInfo.modeName);
final String productFlavor = buildInfo.flavor ?? '';
return _taskForBuildVariant(prefix, '$productFlavor${sentenceCase(buildType)}');
}
String _taskForBuildVariant(String prefix, String buildVariant, [String suffix = '']) {
return '$prefix${sentenceCase(buildVariant)}$suffix';
}
/// Returns the task to build an APK.
@visibleForTesting
String getAssembleTaskFor(BuildInfo buildInfo) {
return _taskFor('assemble', buildInfo);
}
/// Returns the task to build an AAB.
@visibleForTesting
String getBundleTaskFor(BuildInfo buildInfo) {
return _taskFor('bundle', buildInfo);
}
/// Returns the task to build an AAR.
@visibleForTesting
String getAarTaskFor(BuildInfo buildInfo) {
return _taskFor('assembleAar', buildInfo);
}
/// Returns the output APK file names for a given [AndroidBuildInfo].
///
/// For example, when [splitPerAbi] is true, multiple APKs are created.
Iterable<String> _apkFilesFor(AndroidBuildInfo androidBuildInfo) {
final String buildType = camelCase(androidBuildInfo.buildInfo.modeName);
final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? '';
final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor';
if (androidBuildInfo.splitPerAbi) {
return androidBuildInfo.targetArchs.map<String>((AndroidArch arch) {
final String abi = arch.archName;
return 'app$flavorString-$abi-$buildType.apk';
});
}
return <String>['app$flavorString-$buildType.apk'];
}
// The maximum time to wait before the tool retries a Gradle build.
const Duration kMaxRetryTime = Duration(seconds: 10);
/// An implementation of the [AndroidBuilder] that delegates to gradle.
class AndroidGradleBuilder implements AndroidBuilder {
AndroidGradleBuilder({
required Java? java,
required Logger logger,
required ProcessManager processManager,
required FileSystem fileSystem,
required Artifacts artifacts,
required Usage usage,
required GradleUtils gradleUtils,
required Platform platform,
required AndroidStudio? androidStudio,
}) : _java = java,
_logger = logger,
_fileSystem = fileSystem,
_artifacts = artifacts,
_usage = usage,
_gradleUtils = gradleUtils,
_androidStudio = androidStudio,
_fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform),
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
final Java? _java;
final Logger _logger;
final ProcessUtils _processUtils;
final FileSystem _fileSystem;
final Artifacts _artifacts;
final Usage _usage;
final GradleUtils _gradleUtils;
final FileSystemUtils _fileSystemUtils;
final AndroidStudio? _androidStudio;
/// Builds the AAR and POM files for the current Flutter module or plugin.
@override
Future<void> buildAar({
required FlutterProject project,
required Set<AndroidBuildInfo> androidBuildInfo,
required String target,
String? outputDirectoryPath,
required String buildNumber,
}) async {
Directory outputDirectory =
_fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory);
if (project.isModule) {
// Module projects artifacts are located in `build/host`.
outputDirectory = outputDirectory.childDirectory('host');
}
for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) {
await buildGradleAar(
project: project,
androidBuildInfo: androidBuildInfo,
target: target,
outputDirectory: outputDirectory,
buildNumber: buildNumber,
);
}
printHowToConsumeAar(
buildModes: androidBuildInfo
.map<String>((AndroidBuildInfo androidBuildInfo) {
return androidBuildInfo.buildInfo.modeName;
}).toSet(),
androidPackage: project.manifest.androidPackage,
repoDirectory: getRepoDirectory(outputDirectory),
buildNumber: buildNumber,
logger: _logger,
fileSystem: _fileSystem,
);
}
/// Builds the APK.
@override
Future<void> buildApk({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
bool configOnly = false,
}) async {
await buildGradleApp(
project: project,
androidBuildInfo: androidBuildInfo,
target: target,
isBuildingBundle: false,
localGradleErrors: gradleErrors,
configOnly: configOnly,
maxRetries: 1,
);
}
/// Builds the App Bundle.
@override
Future<void> buildAab({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
bool configOnly = false,
}) async {
await buildGradleApp(
project: project,
androidBuildInfo: androidBuildInfo,
target: target,
isBuildingBundle: true,
localGradleErrors: gradleErrors,
validateDeferredComponents: validateDeferredComponents,
deferredComponentsEnabled: deferredComponentsEnabled,
configOnly: configOnly,
maxRetries: 1,
);
}
Future<RunResult> _runGradleTask(
String taskName, {
List<String> options = const <String>[],
required FlutterProject project
}) async {
final Status status = _logger.startProgress(
"Running Gradle task '$taskName'...",
);
final List<String> command = <String>[
_gradleUtils.getExecutable(project),
...options, // suppresses gradle output.
taskName,
];
RunResult result;
try {
result = await _processUtils.run(
command,
workingDirectory: project.android.hostAppGradleRoot.path,
allowReentrantFlutter: true,
environment: _java?.environment,
);
} finally {
status.stop();
}
return result;
}
/// Builds an app.
///
/// * [project] is typically [FlutterProject.current()].
/// * [androidBuildInfo] is the build configuration.
/// * [target] is the target dart entry point. Typically, `lib/main.dart`.
/// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`,
/// otherwise the output artifact is an `*.apk`.
/// * [maxRetries] If not `null`, this is the max number of build retries in case a retry is triggered.
Future<void> buildGradleApp({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
required bool isBuildingBundle,
required List<GradleHandledError> localGradleErrors,
required bool configOnly,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
int retry = 0,
@visibleForTesting int? maxRetries,
}) async {
if (!project.android.isSupportedVersion) {
_exitWithUnsupportedProjectMessage(_usage, _logger.terminal);
}
final List<ProjectMigrator> migrators = <ProjectMigrator>[
TopLevelGradleBuildFileMigration(project.android, _logger),
AndroidStudioJavaGradleConflictMigration(_logger,
project: project.android,
androidStudio: _androidStudio,
java: globals.java),
MinSdkVersionMigration(project.android, _logger),
];
final ProjectMigration migration = ProjectMigration(migrators);
migration.run();
final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot);
if (usesAndroidX) {
BuildEvent('app-using-android-x', type: 'gradle', flutterUsage: _usage).send();
} else if (!usesAndroidX) {
BuildEvent('app-not-using-android-x', type: 'gradle', flutterUsage: _usage).send();
_logger.printStatus("${_logger.terminal.warningMark} Your app isn't using AndroidX.", emphasis: true);
_logger.printStatus(
'To avoid potential build failures, you can quickly migrate your app '
'by following the steps on https://goo.gl/CP92wY .',
indent: 4,
);
}
// The default Gradle script reads the version name and number
// from the local.properties file.
updateLocalProperties(
project: project, buildInfo: androidBuildInfo.buildInfo);
final List<String> command = <String>[
// This does more than get gradlewrapper. It creates the file, ensures it
// exists and verifies the file is executable.
_gradleUtils.getExecutable(project),
];
// All automatically created files should exist.
if (configOnly) {
_logger.printStatus('Config complete.');
return;
}
// Assembly work starts here.
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
final String assembleTask = isBuildingBundle
? getBundleTaskFor(buildInfo)
: getAssembleTaskFor(buildInfo);
final Status status = _logger.startProgress(
"Running Gradle task '$assembleTask'...",
);
if (_logger.isVerbose) {
command.add('--full-stacktrace');
command.add('--info');
command.add('-Pverbose=true');
} else {
command.add('-q');
}
if (!buildInfo.androidGradleDaemon) {
command.add('--no-daemon');
}
final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo;
if (localEngineInfo != null) {
final Directory localEngineRepo = _getLocalEngineRepo(
engineOutPath: localEngineInfo.engineOutPath,
androidBuildInfo: androidBuildInfo,
fileSystem: _fileSystem,
);
_logger.printTrace(
'Using local engine: ${localEngineInfo.engineOutPath}\n'
'Local Maven repo: ${localEngineRepo.path}'
);
command.add('-Plocal-engine-repo=${localEngineRepo.path}');
command.add('-Plocal-engine-build-mode=${buildInfo.modeName}');
command.add('-Plocal-engine-out=${localEngineInfo.engineOutPath}');
command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath(
localEngineInfo.engineOutPath)}');
} else if (androidBuildInfo.targetArchs.isNotEmpty) {
final String targetPlatforms = androidBuildInfo
.targetArchs
.map((AndroidArch e) => e.platformName).join(',');
command.add('-Ptarget-platform=$targetPlatforms');
}
command.add('-Ptarget=$target');
// Only attempt adding multidex support if all the flutter generated files exist.
// If the files do not exist and it was unintentional, the app will fail to build
// and prompt the developer if they wish Flutter to add the files again via gradle_error.dart.
if (androidBuildInfo.multidexEnabled &&
multiDexApplicationExists(project.directory) &&
androidManifestHasNameVariable(project.directory)) {
command.add('-Pmultidex-enabled=true');
ensureMultiDexApplicationExists(project.directory);
_logger.printStatus('Building with Flutter multidex support enabled.');
}
// If using v1 embedding, we want to use FlutterApplication as the base app.
final String baseApplicationName =
project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ?
'android.app.Application' :
'io.flutter.app.FlutterApplication';
command.add('-Pbase-application-name=$baseApplicationName');
final List<DeferredComponent>? deferredComponents = project.manifest.deferredComponents;
if (deferredComponents != null) {
if (deferredComponentsEnabled) {
command.add('-Pdeferred-components=true');
androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents');
}
// Pass in deferred components regardless of building split aot to satisfy
// android dynamic features registry in build.gradle.
final List<String> componentNames = <String>[];
for (final DeferredComponent component in deferredComponents) {
componentNames.add(component.name);
}
if (componentNames.isNotEmpty) {
command.add('-Pdeferred-component-names=${componentNames.join(',')}');
// Multi-apk applications cannot use shrinking. This is only relevant when using
// android dynamic feature modules.
_logger.printStatus(
'Shrinking has been disabled for this build due to deferred components. Shrinking is '
'not available for multi-apk applications. This limitation is expected to be removed '
'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow);
command.add('-Pshrink=false');
}
}
command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
if (buildInfo.fileSystemRoots.isNotEmpty) {
command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}');
}
if (buildInfo.fileSystemScheme != null) {
command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}');
}
if (androidBuildInfo.splitPerAbi) {
command.add('-Psplit-per-abi=true');
}
if (androidBuildInfo.fastStart) {
command.add('-Pfast-start=true');
}
command.add(assembleTask);
GradleHandledError? detectedGradleError;
String? detectedGradleErrorLine;
String? consumeLog(String line) {
if (detectedGradleError != null) {
// Pipe stdout/stderr from Gradle.
return line;
}
for (final GradleHandledError gradleError in localGradleErrors) {
if (gradleError.test(line)) {
detectedGradleErrorLine = line;
detectedGradleError = gradleError;
// The first error match wins.
break;
}
}
// Pipe stdout/stderr from Gradle.
return line;
}
final Stopwatch sw = Stopwatch()
..start();
int exitCode = 1;
try {
exitCode = await _processUtils.stream(
command,
workingDirectory: project.android.hostAppGradleRoot.path,
allowReentrantFlutter: true,
environment: _java?.environment,
mapFunction: consumeLog,
);
} on ProcessException catch (exception) {
consumeLog(exception.toString());
// Rethrow the exception if the error isn't handled by any of the
// `localGradleErrors`.
if (detectedGradleError == null) {
rethrow;
}
} finally {
status.stop();
}
_usage.sendTiming('build', 'gradle', sw.elapsed);
if (exitCode != 0) {
if (detectedGradleError == null) {
BuildEvent('gradle-unknown-failure', type: 'gradle', flutterUsage: _usage).send();
throwToolExit(
'Gradle task $assembleTask failed with exit code $exitCode',
exitCode: exitCode,
);
}
final GradleBuildStatus status = await detectedGradleError!.handler(
line: detectedGradleErrorLine!,
project: project,
usesAndroidX: usesAndroidX,
multidexEnabled: androidBuildInfo.multidexEnabled,
);
if (maxRetries == null || retry < maxRetries) {
switch (status) {
case GradleBuildStatus.retry:
// Use binary exponential backoff before retriggering the build.
// The expected wait times are: 100ms, 200ms, 400ms, and so on...
final int waitTime = min(pow(2, retry).toInt() * 100, kMaxRetryTime.inMicroseconds);
retry += 1;
_logger.printStatus('Retrying Gradle Build: #$retry, wait time: ${waitTime}ms');
await Future<void>.delayed(Duration(milliseconds: waitTime));
await buildGradleApp(
project: project,
androidBuildInfo: androidBuildInfo,
target: target,
isBuildingBundle: isBuildingBundle,
localGradleErrors: localGradleErrors,
retry: retry,
maxRetries: maxRetries,
configOnly: configOnly,
);
final String successEventLabel = 'gradle-${detectedGradleError!.eventLabel}-success';
BuildEvent(successEventLabel, type: 'gradle', flutterUsage: _usage).send();
return;
case GradleBuildStatus.exit:
// Continue and throw tool exit.
}
}
BuildEvent('gradle-${detectedGradleError?.eventLabel}-failure', type: 'gradle', flutterUsage: _usage).send();
throwToolExit(
'Gradle task $assembleTask failed with exit code $exitCode',
exitCode: exitCode,
);
}
if (isBuildingBundle) {
final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage);
final String appSize = (buildInfo.mode == BuildMode.debug)
? '' // Don't display the size when building a debug variant.
: ' (${getSizeAsMB(bundleFile.lengthSync())})';
if (buildInfo.codeSizeDirectory != null) {
await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo);
}
_logger.printStatus(
'${_logger.terminal.successMark} Built ${_fileSystem.path.relative(bundleFile.path)}$appSize.',
color: TerminalColor.green,
);
return;
}
// Gradle produced APKs.
final Iterable<String> apkFilesPaths = project.isModule
? findApkFilesModule(project, androidBuildInfo, _logger, _usage)
: listApkPaths(androidBuildInfo);
final Directory apkDirectory = getApkDirectory(project);
// Generate sha1 for every generated APKs.
for (final File apkFile in apkFilesPaths.map(apkDirectory.childFile)) {
if (!apkFile.existsSync()) {
_exitWithExpectedFileNotFound(
project: project,
fileExtension: '.apk',
logger: _logger,
usage: _usage,
);
}
final String filename = apkFile.basename;
_logger.printTrace('Calculate SHA1: $apkDirectory/$filename');
final File apkShaFile = apkDirectory.childFile('$filename.sha1');
apkShaFile.writeAsStringSync(_calculateSha(apkFile));
final String appSize = (buildInfo.mode == BuildMode.debug)
? '' // Don't display the size when building a debug variant.
: ' (${getSizeAsMB(apkFile.lengthSync())})';
_logger.printStatus(
'${_logger.terminal.successMark} Built ${_fileSystem.path.relative(apkFile.path)}$appSize.',
color: TerminalColor.green,
);
if (buildInfo.codeSizeDirectory != null) {
await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo);
}
}
}
Future<void> _performCodeSizeAnalysis(String kind,
File zipFile,
AndroidBuildInfo androidBuildInfo,) async {
final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
fileSystem: _fileSystem,
logger: _logger,
flutterUsage: _usage,
);
final String archName = androidBuildInfo.targetArchs.single.archName;
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory)
.childFile('snapshot.$archName.json');
final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory)
.childFile('trace.$archName.json');
final Map<String, Object?> output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot(
zipFile: zipFile,
aotSnapshot: aotSnapshot,
precompilerTrace: precompilerTrace,
kind: kind,
);
final File outputFile = _fileSystemUtils.getUniqueFile(
_fileSystem
.directory(_fileSystemUtils.homeDirPath)
.childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json',
)
..writeAsStringSync(jsonEncode(output));
// This message is used as a sentinel in analyze_apk_size_test.dart
_logger.printStatus(
'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}',
);
// DevTools expects a file path relative to the .flutter-devtools/ dir.
final String relativeAppSizePath = outputFile.path
.split('.flutter-devtools/')
.last
.trim();
_logger.printStatus(
'\nTo analyze your app size in Dart DevTools, run the following command:\n'
'dart devtools --appSizeBase=$relativeAppSizePath'
);
}
/// Builds AAR and POM files.
///
/// * [project] is typically [FlutterProject.current()].
/// * [androidBuildInfo] is the build configuration.
/// * [outputDir] is the destination of the artifacts,
/// * [buildNumber] is the build number of the output aar,
Future<void> buildGradleAar({
required FlutterProject project,
required AndroidBuildInfo androidBuildInfo,
required String target,
required Directory outputDirectory,
required String buildNumber,
}) async {
final FlutterManifest manifest = project.manifest;
if (!manifest.isModule && !manifest.isPlugin) {
throwToolExit('AARs can only be built for plugin or module projects.');
}
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
final String aarTask = getAarTaskFor(buildInfo);
final Status status = _logger.startProgress(
"Running Gradle task '$aarTask'...",
);
final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot!);
final String initScript = _fileSystem.path.join(
flutterRoot,
'packages',
'flutter_tools',
'gradle',
'aar_init_script.gradle',
);
final List<String> command = <String>[
_gradleUtils.getExecutable(project),
'-I=$initScript',
'-Pflutter-root=$flutterRoot',
'-Poutput-dir=${outputDirectory.path}',
'-Pis-plugin=${manifest.isPlugin}',
'-PbuildNumber=$buildNumber',
];
if (_logger.isVerbose) {
command.add('--full-stacktrace');
command.add('--info');
command.add('-Pverbose=true');
} else {
command.add('-q');
}
if (!buildInfo.androidGradleDaemon) {
command.add('--no-daemon');
}
if (target.isNotEmpty) {
command.add('-Ptarget=$target');
}
command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) {
_logger.printStatus(
'Dart obfuscation is not supported in ${sentenceCase(buildInfo.friendlyModeName)}'
' mode, building as un-obfuscated.',
);
}
final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo;
if (localEngineInfo != null) {
final Directory localEngineRepo = _getLocalEngineRepo(
engineOutPath: localEngineInfo.engineOutPath,
androidBuildInfo: androidBuildInfo,
fileSystem: _fileSystem,
);
_logger.printTrace(
'Using local engine: ${localEngineInfo.engineOutPath}\n'
'Local Maven repo: ${localEngineRepo.path}'
);
command.add('-Plocal-engine-repo=${localEngineRepo.path}');
command.add('-Plocal-engine-build-mode=${buildInfo.modeName}');
command.add('-Plocal-engine-out=${localEngineInfo.engineOutPath}');
// Copy the local engine repo in the output directory.
try {
copyDirectory(
localEngineRepo,
getRepoDirectory(outputDirectory),
);
} on FileSystemException catch (error, st) {
throwToolExit(
'Failed to copy the local engine ${localEngineRepo.path} repo '
'in ${outputDirectory.path}: $error, $st'
);
}
command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath(
localEngineInfo.engineOutPath)}');
} else if (androidBuildInfo.targetArchs.isNotEmpty) {
final String targetPlatforms = androidBuildInfo.targetArchs
.map((AndroidArch e) => e.platformName).join(',');
command.add('-Ptarget-platform=$targetPlatforms');
}
command.add(aarTask);
final Stopwatch sw = Stopwatch()
..start();
RunResult result;
try {
result = await _processUtils.run(
command,
workingDirectory: project.android.hostAppGradleRoot.path,
allowReentrantFlutter: true,
environment: _java?.environment,
);
} finally {
status.stop();
}
_usage.sendTiming('build', 'gradle-aar', sw.elapsed);
if (result.exitCode != 0) {
_logger.printStatus(result.stdout, wrap: false);
_logger.printError(result.stderr, wrap: false);
throwToolExit(
'Gradle task $aarTask failed with exit code ${result.exitCode}.',
exitCode: result.exitCode,
);
}
final Directory repoDirectory = getRepoDirectory(outputDirectory);
if (!repoDirectory.existsSync()) {
_logger.printStatus(result.stdout, wrap: false);
_logger.printError(result.stderr, wrap: false);
throwToolExit(
'Gradle task $aarTask failed to produce $repoDirectory.',
exitCode: exitCode,
);
}
_logger.printStatus(
'${_logger.terminal.successMark} Built ${_fileSystem.path.relative(repoDirectory.path)}.',
color: TerminalColor.green,
);
}
@override
Future<List<String>> getBuildVariants({required FlutterProject project}) async {
final Stopwatch sw = Stopwatch()
..start();
final RunResult result = await _runGradleTask(
_kBuildVariantTaskName,
options: const <String>['-q'],
project: project,
);
_usage.sendTiming('print', 'android build variants', sw.elapsed);
if (result.exitCode != 0) {
_logger.printStatus(result.stdout, wrap: false);
_logger.printError(result.stderr, wrap: false);
return const <String>[];
}
final List<String> options = <String>[];
for (final String line in LineSplitter.split(result.stdout)) {
final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line);
if (match != null) {
options.add(match.namedGroup(_kBuildVariantRegexGroupName)!);
}
}
return options;
}
@override
Future<String> getApplicationIdForVariant(
String buildVariant, {
required FlutterProject project,
}) async {
final String taskName = _getPrintApplicationIdTaskFor(buildVariant);
final Stopwatch sw = Stopwatch()
..start();
final RunResult result = await _runGradleTask(
taskName,
options: const <String>['-q'],
project: project,
);
_usage.sendTiming('print', 'application id', sw.elapsed);
if (result.exitCode != 0) {
_logger.printStatus(result.stdout, wrap: false);
_logger.printError(result.stderr, wrap: false);
return '';
}
for (final String line in LineSplitter.split(result.stdout)) {
final RegExpMatch? match = _kApplicationIdRegex.firstMatch(line);
if (match != null) {
return match.namedGroup(_kApplicationIdRegexGroupName)!;
}
}
return '';
}
@override
Future<List<String>> getAppLinkDomainsForVariant(
String buildVariant, {
required FlutterProject project,
}) async {
final String taskName = _getPrintAppLinkDomainsTaskFor(buildVariant);
final Stopwatch sw = Stopwatch()
..start();
final RunResult result = await _runGradleTask(
taskName,
options: const <String>['-q'],
project: project,
);
_usage.sendTiming('print', 'application id', sw.elapsed);
if (result.exitCode != 0) {
_logger.printStatus(result.stdout, wrap: false);
_logger.printError(result.stderr, wrap: false);
return const <String>[];
}
final List<String> domains = <String>[];
for (final String line in LineSplitter.split(result.stdout)) {
final RegExpMatch? match = _kAppLinkDomainsRegex.firstMatch(line);
if (match != null) {
domains.add(match.namedGroup(_kAppLinkDomainsGroupName)!);
}
}
return domains;
}
}
/// Prints how to consume the AAR from a host app.
void printHowToConsumeAar({
required Set<String> buildModes,
String? androidPackage = 'unknown',
required Directory repoDirectory,
required Logger logger,
required FileSystem fileSystem,
String? buildNumber,
}) {
assert(buildModes.isNotEmpty);
buildNumber ??= '1.0';
logger.printStatus('\nConsuming the Module', emphasis: true);
logger.printStatus('''
1. Open ${fileSystem.path.join('<host>', 'app', 'build.gradle')}
2. Ensure you have the repositories configured, otherwise add them:
String storageUrl = System.env.$kFlutterStorageBaseUrl ?: "https://storage.googleapis.com"
repositories {
maven {
url '${repoDirectory.path}'
}
maven {
url "\$storageUrl/download.flutter.io"
}
}
3. Make the host app depend on the Flutter module:
dependencies {''');
for (final String buildMode in buildModes) {
logger.printStatus("""
${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'""");
}
logger.printStatus('''
}
''');
if (buildModes.contains('profile')) {
logger.printStatus('''
4. Add the `profile` build type:
android {
buildTypes {
profile {
initWith debug
}
}
}
''');
}
logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar');
}
String _hex(List<int> bytes) {
final StringBuffer result = StringBuffer();
for (final int part in bytes) {
result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
}
return result.toString();
}
String _calculateSha(File file) {
final List<int> bytes = file.readAsBytesSync();
return _hex(sha1.convert(bytes).bytes);
}
void _exitWithUnsupportedProjectMessage(Usage usage, Terminal terminal) {
BuildEvent('unsupported-project', type: 'gradle', eventError: 'gradle-plugin', flutterUsage: usage).send();
throwToolExit(
'${terminal.warningMark} Your app is using an unsupported Gradle project. '
'To fix this problem, create a new project by running `flutter create -t app <app-directory>` '
'and then move the dart code, assets and pubspec.yaml to the new project.',
);
}
/// Returns [true] if the current app uses AndroidX.
// TODO(egarciad): https://github.com/flutter/flutter/issues/40800
// Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`.
bool isAppUsingAndroidX(Directory androidDirectory) {
final File properties = androidDirectory.childFile('gradle.properties');
if (!properties.existsSync()) {
return false;
}
return properties.readAsStringSync().contains('android.useAndroidX=true');
}
/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].
@visibleForTesting
Iterable<String> findApkFilesModule(
FlutterProject project,
AndroidBuildInfo androidBuildInfo,
Logger logger,
Usage usage,
) {
final Iterable<String> apkFileNames = _apkFilesFor(androidBuildInfo);
final Directory apkDirectory = getApkDirectory(project);
final Iterable<File> apks = apkFileNames.expand<File>((String apkFileName) {
File apkFile = apkDirectory.childFile(apkFileName);
if (apkFile.existsSync()) {
return <File>[apkFile];
}
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
final String modeName = camelCase(buildInfo.modeName);
apkFile = apkDirectory
.childDirectory(modeName)
.childFile(apkFileName);
if (apkFile.existsSync()) {
return <File>[apkFile];
}
final String? flavor = buildInfo.flavor;
if (flavor != null) {
// Android Studio Gradle plugin v3 adds flavor to path.
apkFile = apkDirectory
.childDirectory(flavor)
.childDirectory(modeName)
.childFile(apkFileName);
if (apkFile.existsSync()) {
return <File>[apkFile];
}
}
return const <File>[];
});
if (apks.isEmpty) {
_exitWithExpectedFileNotFound(
project: project,
fileExtension: '.apk',
logger: logger,
usage: usage,
);
}
return apks.map((File file) => file.path);
}
/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].
///
/// The flutter.gradle plugin will copy APK outputs into:
/// `$buildDir/app/outputs/flutter-apk/app-<abi>-<flavor-flag>-<build-mode-flag>.apk`
@visibleForTesting
Iterable<String> listApkPaths(
AndroidBuildInfo androidBuildInfo,
) {
final String buildType = camelCase(androidBuildInfo.buildInfo.modeName);
final List<String> apkPartialName = <String>[
if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false)
androidBuildInfo.buildInfo.lowerCasedFlavor!,
'$buildType.apk',
];
if (androidBuildInfo.splitPerAbi) {
return <String>[
for (final AndroidArch androidArch in androidBuildInfo.targetArchs)
<String>[
'app',
androidArch.archName,
...apkPartialName,
].join('-'),
];
}
return <String>[
<String>[
'app',
...apkPartialName,
].join('-'),
];
}
@visibleForTesting
File findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage) {
final List<File> fileCandidates = <File>[
getBundleDirectory(project)
.childDirectory(camelCase(buildInfo.modeName))
.childFile('app.aab'),
getBundleDirectory(project)
.childDirectory(camelCase(buildInfo.modeName))
.childFile('app-${buildInfo.modeName}.aab'),
];
if (buildInfo.flavor != null) {
// The Android Gradle plugin 3.0.0 adds the flavor name to the path.
// For example: In release mode, if the flavor name is `foo_bar`, then
// the directory name is `foo_barRelease`.
fileCandidates.add(
getBundleDirectory(project)
.childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}')
.childFile('app.aab'));
// The Android Gradle plugin 3.5.0 adds the flavor name to file name.
// For example: In release mode, if the flavor name is `foo_bar`, then
// the file name is `app-foo_bar-release.aab`.
fileCandidates.add(
getBundleDirectory(project)
.childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}')
.childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab'));
// The Android Gradle plugin 4.1.0 does only lowercase the first character of flavor name.
fileCandidates.add(getBundleDirectory(project)
.childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}')
.childFile('app-${buildInfo.uncapitalizedFlavor}-${buildInfo.modeName}.aab'));
// The Android Gradle plugin uses kebab-case and lowercases the first character of the flavor name
// when multiple flavor dimensions are used:
// e.g.
// flavorDimensions "dimension1","dimension2"
// productFlavors {
// foo {
// dimension "dimension1"
// }
// bar {
// dimension "dimension2"
// }
// }
fileCandidates.add(getBundleDirectory(project)
.childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}')
.childFile('app-${kebabCase(buildInfo.uncapitalizedFlavor!)}-${buildInfo.modeName}.aab'));
}
for (final File bundleFile in fileCandidates) {
if (bundleFile.existsSync()) {
return bundleFile;
}
}
_exitWithExpectedFileNotFound(
project: project,
fileExtension: '.aab',
logger: logger,
usage: usage,
);
}
/// Throws a [ToolExit] exception and logs the event.
Never _exitWithExpectedFileNotFound({
required FlutterProject project,
required String fileExtension,
required Logger logger,
required Usage usage,
}) {
final String androidGradlePluginVersion =
getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger);
BuildEvent('gradle-expected-file-not-found',
type: 'gradle',
settings:
'androidGradlePluginVersion: $androidGradlePluginVersion, '
'fileExtension: $fileExtension',
flutterUsage: usage,
).send();
throwToolExit(
'Gradle build failed to produce an $fileExtension file. '
"It's likely that this file was generated under ${project.android.buildDirectory.path}, "
"but the tool couldn't find it."
);
}
void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) {
final File targetFile = fileSystem.file(targetPath);
if (!targetFile.existsSync()) {
throwToolExit("The file $targetPath wasn't found in the local engine out directory.");
}
final File linkFile = fileSystem.file(linkPath);
final Link symlink = linkFile.parent.childLink(linkFile.basename);
try {
symlink.createSync(targetPath, recursive: true);
} on FileSystemException catch (exception) {
throwToolExit(
'Failed to create the symlink $linkPath->$targetPath: $exception'
);
}
}
String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) {
final File pomFile = fileSystem.file(pomPath);
if (!pomFile.existsSync()) {
throwToolExit("The file $pomPath wasn't found in the local engine out directory.");
}
XmlDocument document;
try {
document = XmlDocument.parse(pomFile.readAsStringSync());
} on XmlException {
throwToolExit(
'Error parsing $pomPath. Please ensure that this is a valid XML document.'
);
} on FileSystemException {
throwToolExit(
'Error reading $pomPath. Please ensure that you have read permission to this '
'file and try again.');
}
final Iterable<XmlElement> project = document.findElements('project');
assert(project.isNotEmpty);
for (final XmlElement versionElement in document.findAllElements('version')) {
if (versionElement.parent == project.first) {
return versionElement.innerText;
}
}
throwToolExit('Error while parsing the <version> element from $pomPath');
}
/// Returns the local Maven repository for a local engine build.
/// For example, if the engine is built locally at <home>/engine/src/out/android_release_unopt
/// This method generates symlinks in the temp directory to the engine artifacts
/// following the convention specified on https://maven.apache.org/pom.html#Repositories
Directory _getLocalEngineRepo({
required String engineOutPath,
required AndroidBuildInfo androidBuildInfo,
required FileSystem fileSystem,
}) {
final String abi = _getAbiByLocalEnginePath(engineOutPath);
final Directory localEngineRepo = fileSystem.systemTempDirectory
.createTempSync('flutter_tool_local_engine_repo.');
final String buildMode = androidBuildInfo.buildInfo.modeName;
final String artifactVersion = _getLocalArtifactVersion(
fileSystem.path.join(
engineOutPath,
'flutter_embedding_$buildMode.pom',
),
fileSystem,
);
for (final String artifact in const <String>['pom', 'jar']) {
// The Android embedding artifacts.
_createSymlink(
fileSystem.path.join(
engineOutPath,
'flutter_embedding_$buildMode.$artifact',
),
fileSystem.path.join(
localEngineRepo.path,
'io',
'flutter',
'flutter_embedding_$buildMode',
artifactVersion,
'flutter_embedding_$buildMode-$artifactVersion.$artifact',
),
fileSystem,
);
// The engine artifacts (libflutter.so).
_createSymlink(
fileSystem.path.join(
engineOutPath,
'${abi}_$buildMode.$artifact',
),
fileSystem.path.join(
localEngineRepo.path,
'io',
'flutter',
'${abi}_$buildMode',
artifactVersion,
'${abi}_$buildMode-$artifactVersion.$artifact',
),
fileSystem,
);
}
for (final String artifact in <String>['flutter_embedding_$buildMode', '${abi}_$buildMode']) {
_createSymlink(
fileSystem.path.join(
engineOutPath,
'$artifact.maven-metadata.xml',
),
fileSystem.path.join(
localEngineRepo.path,
'io',
'flutter',
artifact,
'maven-metadata.xml',
),
fileSystem,
);
}
return localEngineRepo;
}
String _getAbiByLocalEnginePath(String engineOutPath) {
String result = 'armeabi_v7a';
if (engineOutPath.contains('x86')) {
result = 'x86';
} else if (engineOutPath.contains('x64')) {
result = 'x86_64';
} else if (engineOutPath.contains('arm64')) {
result = 'arm64_v8a';
}
return result;
}
String _getTargetPlatformByLocalEnginePath(String engineOutPath) {
String result = 'android-arm';
if (engineOutPath.contains('x86')) {
result = 'android-x86';
} else if (engineOutPath.contains('x64')) {
result = 'android-x64';
} else if (engineOutPath.contains('arm64')) {
result = 'android-arm64';
}
return result;
}