Reland: "Fix how Gradle resolves Android plugin" (#137115)

Relands #97823

When the tool migrated to `.flutter-plugins-dependencies`, the Gradle plugin was never changed.
Until now, the plugin had the heuristic that a plugin with a `android/build.gradle` file supported the Android platform.

Also applies schema of `getPluginDependencies` to `getPluginList` which uses a `List` of Object instead of `Properties`.

Fixes #97729
Cause of the error: 5f105a6ca7/packages/flutter_tools/gradle/flutter.gradle (L421C25-L421C25)

Fixes #98048
The deprecated line `include ":$name"` in `settings.gradle` (pluginEach) in old projects causes the `project.rootProject.findProject` to also find the plugin "project", so it is not failing on the `afterEvaluate` method. But the plugin shouldn't be included in the first place as it fails with `Could not find method implementation() for arguments` error in special cases.

Related to #48918, see [_writeFlutterPluginsListLegacy](27bc1cf61a/packages/flutter_tools/lib/src/flutter_plugins.dart (L248)).

Co-authored-by: Emmanuel Garcia <egarciad@google.com>
This commit is contained in:
Gustl22
2023-12-21 17:55:04 +01:00
committed by GitHub
parent 430254e13b
commit f5ac225c8d
7 changed files with 618 additions and 127 deletions

View File

@@ -0,0 +1,208 @@
// 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 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/cache.dart';
import '../src/common.dart';
import 'test_data/plugin_each_settings_gradle_project.dart';
import 'test_data/plugin_project.dart';
import 'test_data/project.dart';
import 'test_utils.dart';
void main() {
late Directory tempDir;
setUp(() {
Cache.flutterRoot = getFlutterRoot();
tempDir = createResolvedTempDirectorySync('flutter_plugin_test.');
});
tearDown(() async {
tryToDelete(tempDir);
});
// Regression test for https://github.com/flutter/flutter/issues/97729 (#137115).
/// Creates a project which uses a plugin, which is not supported on Android.
/// This means it has no entry in pubspec.yaml for:
/// flutter -> plugin -> platforms -> android
///
/// [createAndroidPluginFolder] indicates that the plugin can additionally
/// have a functioning `android` folder.
Future<ProcessResult> testUnsupportedPlugin({
required Project project,
required bool createAndroidPluginFolder,
}) async {
final String flutterBin = fileSystem.path.join(
getFlutterRoot(),
'bin',
'flutter',
);
// Create dummy plugin that supports iOS and optionally Android.
processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'create',
'--template=plugin',
'--platforms=ios${createAndroidPluginFolder ? ',android' : ''}',
'test_plugin',
], workingDirectory: tempDir.path);
final Directory pluginAppDir = tempDir.childDirectory('test_plugin');
final File pubspecFile = pluginAppDir.childFile('pubspec.yaml');
String pubspecYamlSrc =
pubspecFile.readAsStringSync().replaceAll('\r\n', '\n');
if (createAndroidPluginFolder) {
// Override pubspec to drop support for the Android implementation.
pubspecYamlSrc = pubspecYamlSrc
.replaceFirst(
RegExp(r'name:.*\n'),
'name: test_plugin\n',
)
.replaceFirst('''
android:
package: com.example.test_plugin
pluginClass: TestPlugin
''', '''
# android:
# package: com.example.test_plugin
# pluginClass: TestPlugin
''');
pubspecFile.writeAsStringSync(pubspecYamlSrc);
// Check the android directory and the build.gradle file within.
final File pluginGradleFile =
pluginAppDir.childDirectory('android').childFile('build.gradle');
expect(pluginGradleFile, exists);
} else {
expect(pubspecYamlSrc, isNot(contains('android:')));
}
// Create a project which includes the plugin to test against
final Directory pluginExampleAppDir =
pluginAppDir.childDirectory('example');
await project.setUpIn(pluginExampleAppDir);
// Run flutter build apk to build plugin example project.
return processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
'apk',
'--debug',
], workingDirectory: pluginExampleAppDir.path);
}
test('skip plugin if it does not support the Android platform', () async {
final Project project = PluginWithPathAndroidProject();
final ProcessResult buildApkResult = await testUnsupportedPlugin(
project: project, createAndroidPluginFolder: false);
expect(buildApkResult.stderr.toString(),
isNot(contains('Please fix your settings.gradle.')));
expect(buildApkResult, const ProcessResultMatcher());
});
test(
'skip plugin with android folder if it does not support the Android platform',
() async {
final Project project = PluginWithPathAndroidProject();
final ProcessResult buildApkResult = await testUnsupportedPlugin(
project: project, createAndroidPluginFolder: true);
expect(buildApkResult.stderr.toString(),
isNot(contains('Please fix your settings.gradle.')));
expect(buildApkResult, const ProcessResultMatcher());
});
// TODO(54566): Remove test when issue is resolved.
/// Test project with a `settings.gradle` (PluginEach) that apps were created
/// with until Flutter v1.22.0.
/// It uses the `.flutter-plugins` file to load EACH plugin.
test(
'skip plugin if it does not support the Android platform with a _plugin.each_ settings.gradle',
() async {
final Project project = PluginEachWithPathAndroidProject();
final ProcessResult buildApkResult = await testUnsupportedPlugin(
project: project, createAndroidPluginFolder: false);
expect(buildApkResult.stderr.toString(),
isNot(contains('Please fix your settings.gradle.')));
expect(buildApkResult, const ProcessResultMatcher());
});
// TODO(54566): Remove test when issue is resolved.
/// Test project with a `settings.gradle` (PluginEach) that apps were created
/// with until Flutter v1.22.0.
/// It uses the `.flutter-plugins` file to load EACH plugin.
/// The plugin includes a functional 'android' folder.
test(
'skip plugin with android folder if it does not support the Android platform with a _plugin.each_ settings.gradle',
() async {
final Project project = PluginEachWithPathAndroidProject();
final ProcessResult buildApkResult = await testUnsupportedPlugin(
project: project, createAndroidPluginFolder: true);
expect(buildApkResult.stderr.toString(),
isNot(contains('Please fix your settings.gradle.')));
expect(buildApkResult, const ProcessResultMatcher());
});
// TODO(54566): Remove test when issue is resolved.
/// Test project with a `settings.gradle` (PluginEach) that apps were created
/// with until Flutter v1.22.0.
/// It is compromised by removing the 'include' statement of the plugins.
/// As the "'.flutter-plugins'" keyword is still present, the framework
/// assumes that all plugins are included, which is not the case.
/// Therefore it should throw an error.
test(
'skip plugin if it does not support the Android platform with a compromised _plugin.each_ settings.gradle',
() async {
final Project project = PluginCompromisedEachWithPathAndroidProject();
final ProcessResult buildApkResult = await testUnsupportedPlugin(
project: project, createAndroidPluginFolder: true);
expect(
buildApkResult,
const ProcessResultMatcher(
stderrPattern: 'Please fix your settings.gradle.'),
);
});
}
const String pubspecWithPluginPath = r'''
name: test
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
flutter:
sdk: flutter
test_plugin:
path: ../
''';
/// Project that load's a plugin from the specified path.
class PluginWithPathAndroidProject extends PluginProject {
@override
String get pubspec => pubspecWithPluginPath;
}
// TODO(54566): Remove class when issue is resolved.
/// [PluginEachSettingsGradleProject] that load's a plugin from the specified
/// path.
class PluginEachWithPathAndroidProject extends PluginEachSettingsGradleProject {
@override
String get pubspec => pubspecWithPluginPath;
}
// TODO(54566): Remove class when issue is resolved.
/// [PluginCompromisedEachSettingsGradleProject] that load's a plugin from the
/// specified path.
class PluginCompromisedEachWithPathAndroidProject
extends PluginCompromisedEachSettingsGradleProject {
@override
String get pubspec => pubspecWithPluginPath;
}

View File

@@ -0,0 +1,60 @@
// 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.
// TODO(54566): Remove this file when issue is resolved.
import 'deferred_components_config.dart';
import 'plugin_project.dart';
/// Project to test the deprecated `settings.gradle` (PluginEach) that apps were
/// created with until Flutter v1.22.0.
/// It uses the `.flutter-plugins` file to load EACH plugin.
class PluginEachSettingsGradleProject extends PluginProject {
@override
DeferredComponentsConfig get deferredComponents =>
PluginEachSettingsGradleDeferredComponentsConfig();
}
class PluginEachSettingsGradleDeferredComponentsConfig
extends PluginDeferredComponentsConfig {
@override
String get androidSettings => r'''
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
''';
}
/// Project to test the deprecated `settings.gradle` (PluginEach) that apps were
/// created with until Flutter v1.22.0.
/// It uses the `.flutter-plugins` file to get EACH plugin.
/// It is compromised by removing the 'include' statement of the plugins.
class PluginCompromisedEachSettingsGradleProject extends PluginProject {
@override
DeferredComponentsConfig get deferredComponents =>
PluginCompromisedEachSettingsGradleDeferredComponentsConfig();
}
class PluginCompromisedEachSettingsGradleDeferredComponentsConfig
extends PluginDeferredComponentsConfig {
@override
String get androidSettings => r'''
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
''';
}

View File

@@ -0,0 +1,99 @@
// 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 'basic_project.dart';
import 'deferred_components_config.dart';
import 'deferred_components_project.dart';
/// Project which can load native plugins
class PluginProject extends BasicProject {
@override
final DeferredComponentsConfig? deferredComponents =
PluginDeferredComponentsConfig();
}
class PluginDeferredComponentsConfig extends BasicDeferredComponentsConfig {
@override
String get androidBuild => r'''
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
configurations.classpath {
resolutionStrategy.activateDependencyLocking()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
dependencyLocking {
ignoredDependencies.add('io.flutter:*')
lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile")
if (!project.hasProperty('local-engine-repo')) {
lockAllConfigurations()
}
}
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
''';
@override
String get androidSettings => r'''
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
''';
@override
String get appManifest => r'''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourcompany.flavors">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:name="${applicationName}"
android:label="flavors">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
''';
}