Skip to content

Commit f668780

Browse files
Address review: specific caching reason, shared APK error text, shorter comments
- CopyFlutterApksTask: state why caching is disabled (local copy; a cache entry would duplicate the APKs) and build both errors through one transformedApkError helper. - Trim comments and KDoc added by this PR to what the code does not already say.
1 parent 33f3987 commit f668780

9 files changed

Lines changed: 74 additions & 171 deletions

File tree

‎packages/flutter_tools/gradle/src/main/kotlin/DslVersionCodes.kt‎

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,22 @@ package com.flutter.gradle
77
import com.android.build.api.dsl.ApplicationExtension
88

99
/**
10-
* The versionCodes an application project declares in its Android DSL, on `defaultConfig` and on
11-
* each product flavor.
10+
* The versionCodes declared on `defaultConfig` and on each product flavor.
1211
*
13-
* Flutter offsets the versionCode of each per-ABI APK from these values instead of reading
14-
* `VariantOutput.versionCode`. AGP disallows reading that property during configuration when its
15-
* compatibility mode (`android.compatibility.enableLegacyApi`) is off, and its lazy form would
16-
* make the property depend on itself. Create an instance with [from] in
17-
* `androidComponents.finalizeDsl`, where the DSL is complete and reading it is supported.
18-
* AGP runs `finalizeDsl` callbacks in registration order, so the snapshot does not see versionCode
19-
* changes made by a `finalizeDsl` callback registered after Flutter's, such as one in the app's
20-
* build script.
12+
* Flutter computes per-ABI versionCodes from these instead of reading `VariantOutput.versionCode`,
13+
* which AGP rejects during configuration when `android.compatibility.enableLegacyApi=false`.
14+
* Create it with [from] in `finalizeDsl`. It does not see changes made by `finalizeDsl` callbacks
15+
* registered after Flutter's.
2116
*
22-
* @property defaultConfigVersionCode the versionCode set on `defaultConfig`, or null if unset.
23-
* @property productFlavorVersionCodes the versionCode of each product flavor that sets one, keyed
24-
* by flavor name. Flavor names are unique across dimensions, so one map covers all of them.
17+
* @property productFlavorVersionCodes keyed by flavor name, which is unique across dimensions.
2518
*/
2619
internal data class DslVersionCodes(
2720
val defaultConfigVersionCode: Int?,
2821
val productFlavorVersionCodes: Map<String, Int>
2922
) {
3023
/**
31-
* Returns the versionCode AGP gives a variant built from [productFlavors], or null if neither
32-
* those flavors nor `defaultConfig` set one.
33-
*
34-
* Matches AGP's merge: the first flavor in [productFlavors] that sets a versionCode wins, and
35-
* `defaultConfig` is the fallback. When the DSL sets no versionCode, AGP reads it from the
36-
* merged manifest instead, which is not available at configuration time.
37-
*
38-
* @param productFlavors the variant's `(dimension, flavor name)` pairs in dimension priority
39-
* order, as returned by `ComponentIdentity.productFlavors`.
24+
* The versionCode AGP merges for a variant: the first of [productFlavors] (in dimension
25+
* priority order) that sets one, else `defaultConfig`. Null if none is set in the DSL.
4026
*/
4127
fun forVariant(productFlavors: List<Pair<String, String>>): Int? =
4228
productFlavors.firstNotNullOfOrNull { (_, flavorName) -> productFlavorVersionCodes[flavorName] }

‎packages/flutter_tools/gradle/src/main/kotlin/FlutterPlugin.kt‎

Lines changed: 12 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,7 @@ class FlutterPlugin : Plugin<Project> {
324324
// plugin instance that owns the resolved Flutter SDK and local engine paths.
325325
val flutterGradlePlugin = this
326326
val isApplicationProject = FlutterPluginUtils.isFlutterAppProject(projectToAddTasksTo)
327-
// AGP runs every finalizeDsl callback before any onVariants callback, so this is set
328-
// before the application branch below reads it.
327+
// Set in finalizeDsl, which AGP runs before any onVariants callback.
329328
var dslVersionCodes: DslVersionCodes? = null
330329
if (isApplicationProject) {
331330
val appExtension = FlutterPluginUtils.getAndroidApplicationExtension(projectToAddTasksTo)
@@ -345,8 +344,6 @@ class FlutterPlugin : Plugin<Project> {
345344
targetPlatforms
346345
)
347346
registerFlutterAssetTasks(projectToAddTasksTo, variant, compileTaskProvider)
348-
// An application project only has application variants, and only those have
349-
// the outputs (one per APK) that the versionCode and APK copy are configured on.
350347
check(variant is ApplicationVariant) {
351348
"Expected an application variant for '${variant.name}' in an application " +
352349
"project, but got ${variant::class.java.name}."
@@ -547,8 +544,7 @@ class FlutterPlugin : Plugin<Project> {
547544
}
548545

549546
/**
550-
* Whether `flutter assemble`, and the application wiring that depends on it (assets,
551-
* per-ABI versionCodes and the flutter-apk copy), should be configured for [variant].
547+
* Whether to configure `flutter assemble`, and everything that depends on it, for [variant].
552548
*
553549
* When a single `assemble<Variant>` task is named on the command line, Flutter is only
554550
* compiled for the variants that task can build. This keeps a release build from also
@@ -675,12 +671,7 @@ class FlutterPlugin : Plugin<Project> {
675671
}
676672
}
677673

678-
/**
679-
* The Flutter build mode ("debug", "profile" or "release") for [variant].
680-
*
681-
* Uses the public debuggable flag so that custom debuggable build types (e.g. `staging`)
682-
* map to the debug engine artifacts.
683-
*/
674+
/** "debug", "profile" or "release" for [variant]; debuggable custom build types are "debug". */
684675
private fun flutterBuildModeFor(variant: Variant): String {
685676
val variantBuildType =
686677
requireNotNull(variant.buildType) {
@@ -742,23 +733,13 @@ class FlutterPlugin : Plugin<Project> {
742733
}
743734

744735
/**
745-
* Sets the `versionCode` of each per-ABI output to
746-
* `ABI_VERSION[abi] * 1000 + baseVersionCode` for `--split-per-abi` builds, so every APK
747-
* gets a distinct versionCode. [FlutterPluginConstants.ABI_VERSION] holds the offsets.
748-
*
749-
* [baseVersionCode] is the versionCode the variant's DSL declares (see [DslVersionCodes]).
750-
* This never reads `output.versionCode`, which AGP disallows during configuration when its
751-
* compatibility mode is off. So a versionCode set only in the manifest is not offset, and
752-
* Flutter replaces a value that an `onVariants` callback running before its own has set.
736+
* For `--split-per-abi`, sets each output's versionCode to
737+
* `ABI_VERSION[abi] * 1000 + baseVersionCode`, where [baseVersionCode] comes from the DSL
738+
* (see [DslVersionCodes]). A versionCode set only in the manifest is not offset.
753739
*
754-
* Does nothing when `force-version-code-ignoring-abi` is set, and warns and does nothing
755-
* when [baseVersionCode] is null. Leaves an output unchanged if it has no ABI filter (a
756-
* universal APK) or if Flutter has no offset for its ABI.
757-
*
758-
* AGP runs `onVariants` callbacks in registration order. Flutter registers its callback
759-
* when the plugin is applied, so it normally runs before an `androidComponents.onVariants`
760-
* block in the app's build script: that block sees the offset value, and a value it sets
761-
* replaces Flutter's. See "Setting per-ABI or per-variant versionCode" in
740+
* Skipped with `force-version-code-ignoring-abi`. Outputs without an ABI filter are left
741+
* unchanged. An `onVariants` block in the app's build script runs after this one, so a
742+
* value it sets wins. See "Setting per-ABI or per-variant versionCode" in
762743
* docs/platforms/android/website-page-draft.md.
763744
*
764745
* TODO(reidbaker): Link to the docs.flutter.dev page once it is published.
@@ -791,11 +772,7 @@ class FlutterPlugin : Plugin<Project> {
791772
}
792773
}
793774

794-
/**
795-
* Registers the task that copies [variant]'s APKs into `build/outputs/flutter-apk/`,
796-
* where `flutter run` and `flutter build apk` look for them, and makes
797-
* `assemble<Variant>` run it.
798-
*/
775+
/** Registers the copy of [variant]'s APKs into flutter-apk, run by `assemble<Variant>`. */
799776
private fun registerCopyFlutterApksTask(
800777
project: Project,
801778
variant: ApplicationVariant
@@ -807,18 +784,13 @@ class FlutterPlugin : Plugin<Project> {
807784
) {
808785
apkDirectory.set(variant.artifacts.get(SingleArtifact.APK))
809786
builtArtifactsLoader.set(variant.artifacts.getBuiltArtifactsLoader())
810-
// The variant's outputs are the APKs AGP will build, so the copy declares
811-
// exactly the files it will write.
812787
outputAbis.set(variant.outputs.map { CopyFlutterApksTask.abiOf(it.filters) })
813788
flavorName.set(variant.flavorName?.takeIf { it.isNotEmpty() })
814789
buildMode.set(flutterBuildModeFor(variant))
815790
destinationDir.set(project.layout.buildDirectory.dir("outputs/flutter-apk"))
816791
}
817-
// The variant API has no provider for the assemble task, and AGP has not created that
818-
// task yet when onVariants runs, so the task has to be matched by name.
819-
// `configureEach` runs only when a task is realized, so this realizes no tasks. It is
820-
// used instead of `tasks.named(Spec)`, which is @Incubating in the Gradle API this
821-
// plugin compiles against.
792+
// The variant API has no provider for the assemble task, so match it by name.
793+
// `configureEach` realizes no tasks; `tasks.named(Spec)` is @Incubating in our API.
822794
val assembleTaskName = "assemble${FlutterPluginUtils.capitalize(variant.name)}"
823795
project.tasks.configureEach {
824796
if (name == assembleTaskName) {

‎packages/flutter_tools/gradle/src/main/kotlin/FlutterPluginUtils.kt‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,10 +349,8 @@ object FlutterPluginUtils {
349349
* Configuring only the variant named on the command line avoids that. Removing the check was
350350
* tried on AGP/Gradle 7.2.0/7.5 and still caused build failures.
351351
*
352-
* Callers gate the compile task registration in
353-
* [FlutterPlugin][com.flutter.gradle.FlutterPlugin] and the application wiring that depends
354-
* on it: the assets that `flutter assemble` produces, per-ABI versionCodes, and the
355-
* flutter-apk copy.
352+
* Callers in [FlutterPlugin][com.flutter.gradle.FlutterPlugin] gate the compile task and
353+
* everything that depends on it.
356354
*
357355
* TODO: Remove this AGP hack. https://github.com/flutter/flutter/issues/109560
358356
* That issue records the original rationale verbatim, the Gradle invocations that were

‎packages/flutter_tools/gradle/src/main/kotlin/tasks/CopyFlutterApksTask.kt‎

Lines changed: 38 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -26,48 +26,28 @@ import org.gradle.work.DisableCachingByDefault
2626
import javax.inject.Inject
2727

2828
/**
29-
* Copies the APKs that AGP built for one variant into the flutter-apk directory, where
30-
* `flutter run` and `flutter build apk` look for them, under the names the Flutter tool expects
31-
* (see [apkFileName]).
29+
* Copies one variant's APKs into the flutter-apk directory, renamed to what the Flutter tool
30+
* expects (see [apkFileName]).
3231
*
33-
* Every variant copies into the same flutter-apk directory, so declaring that directory as an
34-
* output would make the variants' outputs overlap. The task declares the individual
35-
* [outputApks] instead. Those and the files the copy writes are both named by [apkFileName] from
36-
* the same inputs, so the declared outputs cannot drift from what the task produces.
32+
* Every variant writes into the same directory, so the task declares the individual
33+
* [outputApks] as outputs rather than the directory.
3734
*
38-
* The task only copies files, so like Gradle's own `Copy` and `Sync` tasks, which carry the same
39-
* annotation and reason, it is not cached.
40-
*
41-
* The task fails, and names the APK artifact (`SingleArtifact.APK`) in its error, when another
42-
* plugin or build script transforms that artifact so that either:
43-
* - the directory has no `output-metadata.json`. A transform registered with `toTransformMany`
44-
* and `ArtifactTransformationRequest` gets the file written by AGP. A transform registered with
45-
* `toTransform` must write it with `BuiltArtifacts.save`.
46-
* - an APK has an ABI filter that none of the variant's outputs has.
47-
*
48-
* The task cannot fix either case, so the errors point at the plugin that did the transform, not
49-
* at Flutter. Plugins that only read the APK artifact, or that write extra APKs after `assemble`
50-
* (as channel-packaging plugins do), do not cause either failure.
35+
* Fails if another plugin transforms `SingleArtifact.APK` without writing `output-metadata.json`,
36+
* or into APKs whose ABI filters differ from the variant outputs. Flutter cannot fix either, so
37+
* the error points at that plugin.
5138
*/
52-
@DisableCachingByDefault(because = "Not worth caching")
39+
@DisableCachingByDefault(because = "Copies local APKs; a cache entry would only duplicate them")
5340
abstract class CopyFlutterApksTask : DefaultTask() {
5441
/** The variant's `SingleArtifact.APK` directory: the APKs and AGP's metadata file. */
5542
@get:InputDirectory
5643
@get:PathSensitive(PathSensitivity.RELATIVE)
5744
abstract val apkDirectory: DirectoryProperty
5845

59-
/**
60-
* Reads the metadata in [apkDirectory]. Not an input itself, because [apkDirectory] already
61-
* covers every file it reads.
62-
*/
46+
/** Reads the metadata in [apkDirectory], which already covers its inputs. */
6347
@get:Internal
6448
abstract val builtArtifactsLoader: Property<BuiltArtifactsLoader>
6549

66-
/**
67-
* The ABI of each APK the variant produces, taken from the ABI filters of the variant's
68-
* outputs. An output without an ABI filter is listed as [NO_ABI]: the single APK of a build
69-
* without ABI splits, or a universal APK.
70-
*/
50+
/** The ABI of each variant output, or [NO_ABI] for an output without an ABI filter. */
7151
@get:Input
7252
abstract val outputAbis: ListProperty<String>
7353

@@ -80,10 +60,7 @@ abstract class CopyFlutterApksTask : DefaultTask() {
8060
@get:Input
8161
abstract val buildMode: Property<String>
8262

83-
/**
84-
* The flutter-apk directory. Shared by every variant's copy task, so it is not declared as an
85-
* output; [outputApks] are the declared outputs.
86-
*/
63+
/** The flutter-apk directory, shared by every variant, so not an output itself. */
8764
@get:Internal
8865
abstract val destinationDir: DirectoryProperty
8966

@@ -101,37 +78,28 @@ abstract class CopyFlutterApksTask : DefaultTask() {
10178
@TaskAction
10279
fun copyApks() {
10380
val apkDir = apkDirectory.get()
104-
// `load` returns null only when the directory has no `output-metadata.json`. AGP's
105-
// packaging task always writes one. A plugin that transforms the APK artifact with
106-
// `toTransformMany` and `ArtifactTransformationRequest` gets one written by AGP. So this
107-
// means another plugin or build script replaced the artifact with `toTransform` and did
108-
// not call `BuiltArtifacts.save`. An unreadable or malformed file throws instead.
81+
// `load` returns null only when `output-metadata.json` is missing.
10982
val builtArtifacts =
11083
builtArtifactsLoader.get().load(apkDir)
111-
?: throw GradleException(
112-
"Flutter could not read the APK metadata in $apkDir (no output-metadata.json), " +
113-
"so it cannot copy the APKs to ${destinationDir.get()}. Another Gradle " +
114-
"plugin or build script in this project replaced the APK artifact " +
115-
"(SingleArtifact.APK) without writing output-metadata.json. Find the " +
116-
"plugin or script that transforms SingleArtifact.APK, and ask its " +
117-
"maintainer to write the metadata, for example with " +
118-
"ArtifactTransformationRequest or BuiltArtifacts.save()."
84+
?: throw transformedApkError(
85+
problem =
86+
"Flutter could not read the APK metadata in $apkDir " +
87+
"(no output-metadata.json), so it cannot copy the APKs to " +
88+
"${destinationDir.get()}.",
89+
fix =
90+
"write output-metadata.json, for example with " +
91+
"ArtifactTransformationRequest or BuiltArtifacts.save()"
11992
)
12093
val declaredAbis = outputAbis.get()
12194
builtArtifacts.elements.forEach { artifact ->
12295
val abi = abiOf(artifact.filters)
123-
// AGP writes one APK per variant output, and the declared ABIs come from those same
124-
// outputs, so with AGP alone they always match. They differ only if another plugin
125-
// or build script transforms the APK artifact into APKs with different ABI filters.
126-
// Fail rather than write a file that Gradle does not track.
96+
// With AGP alone this always matches, because both come from the variant outputs.
12797
if (abi !in declaredAbis) {
128-
throw GradleException(
129-
"Flutter expected APKs for the ABIs $declaredAbis, but the APK metadata in " +
130-
"$apkDir lists ${artifact.outputFile} for ABI '$abi'. Another Gradle " +
131-
"plugin or build script in this project changed the APK artifact " +
132-
"(SingleArtifact.APK). Find the plugin or script that transforms " +
133-
"SingleArtifact.APK, and ask its maintainer to keep one APK per variant " +
134-
"output with the same ABI filters."
98+
throw transformedApkError(
99+
problem =
100+
"Flutter expected APKs for the ABIs $declaredAbis, but the APK metadata " +
101+
"in $apkDir lists ${artifact.outputFile} for ABI '$abi'.",
102+
fix = "keep one APK per variant output, with the same ABI filters"
135103
)
136104
}
137105
val fileName = apkFileName(abi, flavorName.orNull, buildMode.get())
@@ -147,22 +115,14 @@ abstract class CopyFlutterApksTask : DefaultTask() {
147115
/** The [outputAbis] entry for an APK that has no ABI filter. */
148116
const val NO_ABI: String = ""
149117

150-
/**
151-
* The ABI that [filters] select, or [NO_ABI] if they have no ABI filter.
152-
*
153-
* Used both for the variant outputs at configuration time and for the built APKs at
154-
* execution time, so the two always agree on what "no ABI" means.
155-
*/
118+
/** The ABI that [filters] select, or [NO_ABI] if they have no ABI filter. */
156119
internal fun abiOf(filters: Collection<FilterConfiguration>): String =
157120
filters.find { it.filterType == FilterConfiguration.FilterType.ABI }?.identifier ?: NO_ABI
158121

159122
/**
160-
* The file name the Flutter tool expects for an APK:
161123
* `app[-<abi>][-<flavor>]-<build mode>.apk`, with the flavor in lower case.
162124
*
163-
* Must stay in sync with `listApkPaths` in
164-
* `packages/flutter_tools/lib/src/android/gradle.dart`, which is how the Flutter tool
165-
* finds these files.
125+
* Must match `listApkPaths` in `packages/flutter_tools/lib/src/android/gradle.dart`.
166126
*/
167127
internal fun apkFileName(
168128
abi: String,
@@ -173,5 +133,15 @@ abstract class CopyFlutterApksTask : DefaultTask() {
173133
val flavorPart = if (flavorName.isNullOrEmpty()) "" else "-${flavorName.lowercase()}"
174134
return "app$abiPart$flavorPart-$buildMode.apk"
175135
}
136+
137+
private fun transformedApkError(
138+
problem: String,
139+
fix: String
140+
): GradleException =
141+
GradleException(
142+
"$problem Another Gradle plugin or build script in this project transforms the " +
143+
"APK artifact (SingleArtifact.APK). Find the plugin or script that transforms " +
144+
"SingleArtifact.APK, and ask its maintainer to $fix."
145+
)
176146
}
177147
}

0 commit comments

Comments
 (0)