diff --git a/packages/flutterfire_cli/lib/src/commands/reconfigure.dart b/packages/flutterfire_cli/lib/src/commands/reconfigure.dart index a1c6a8cf..b69a4913 100644 --- a/packages/flutterfire_cli/lib/src/commands/reconfigure.dart +++ b/packages/flutterfire_cli/lib/src/commands/reconfigure.dart @@ -409,7 +409,7 @@ class Reconfigure extends FlutterFireCommand { final androidBuildConfigurationsExist = doesNestedMapExist(firebaseJsonMap, buildConfigurationKeys); - await gradleContentUpdates(flutterApp!); + await gradleContentUpdates(flutterApp!, logger: logger); if (androidBuildConfigurationsExist) { final buildConfigurations = diff --git a/packages/flutterfire_cli/lib/src/firebase/firebase_android_writes.dart b/packages/flutterfire_cli/lib/src/firebase/firebase_android_writes.dart index 56ef7a8a..3ac7b15d 100644 --- a/packages/flutterfire_cli/lib/src/firebase/firebase_android_writes.dart +++ b/packages/flutterfire_cli/lib/src/firebase/firebase_android_writes.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'package:cli_util/cli_logging.dart'; @@ -92,6 +93,146 @@ final kotlinGoogleServicesPluginPattern = RegExp( "id\\(([\"']com\\.google\\.gms\\.google-services[\"'])\\) version\\(([\"']\\d+\\.\\d+\\.\\d+[\"'])\\) apply false", ); +// A `com.google.gms.google-services` declaration in the Groovy DSL, written as +// `id "..."`, `id '...'` or `id("...")`. Groups 1 and 2 are the quote and the +// text of the version literal (`version "..."` or `version("...")`) when the +// declaration has one on the same line. +final _googleServicesPluginDeclarationPattern = RegExp( + r'''\bid[ \t]*\(?[ \t]*['"]com\.google\.gms\.google-services['"][ \t]*\)?(?:[ \t]*\.?[ \t]*version[ \t]*\(?[ \t]*(['"])([^'"\r\n]*)\1)?''', +); + +// The same declaration in the Kotlin DSL, where `id(...)` needs parentheses. +final _kotlinGoogleServicesPluginDeclarationPattern = RegExp( + r'''\bid[ \t]*\([ \t]*['"]com\.google\.gms\.google-services['"][ \t]*\)(?:[ \t]*\.?[ \t]*version[ \t]*\(?[ \t]*(['"])([^'"\r\n]*)\1)?''', +); + +/// Replaces every comment in a Gradle file with whitespace of the same length, +/// so offsets into the result are also valid for [source]. +/// +/// String literals are left alone, which keeps a `//` inside one (a repository +/// URL, for example) from being read as the start of a comment. +String _maskGradleComments(String source) { + final buffer = StringBuffer(); + String? quote; + var index = 0; + + while (index < source.length) { + final char = source[index]; + final next = index + 1 < source.length ? source[index + 1] : ''; + + if (quote != null) { + buffer.write(char); + if (char == r'\' && next.isNotEmpty) { + buffer.write(next); + index += 2; + continue; + } + if (char == quote || char == '\n') quote = null; + index++; + } else if (char == '"' || char == "'") { + quote = char; + buffer.write(char); + index++; + } else if (char == '/' && next == '/') { + while (index < source.length && source[index] != '\n') { + buffer.write(' '); + index++; + } + } else if (char == '/' && next == '*') { + final close = source.indexOf('*/', index + 2); + final end = close == -1 ? source.length : close + 2; + for (; index < end; index++) { + final commentChar = source[index]; + final isLineBreak = commentChar == '\n' || commentChar == '\r'; + buffer.write(isLineBreak ? commentChar : ' '); + } + } else { + buffer.write(char); + index++; + } + } + + return buffer.toString(); +} + +String _lineContaining(String source, int offset) { + final start = source.lastIndexOf('\n', offset) + 1; + final end = source.indexOf('\n', offset); + return source.substring(start, end == -1 ? source.length : end).trim(); +} + +/// Upgrades an existing `com.google.gms.google-services` plugin declaration in +/// `android/settings.gradle` (Groovy DSL) or `android/settings.gradle.kts` +/// (Kotlin DSL, when [kotlin] is `true`) to [targetVersion]. +/// +/// `flutter pub upgrade` bumps the Firebase Android BoM but never touches the +/// Gradle settings file, so projects configured with an older FlutterFire CLI +/// keep the Google Services plugin version that was current at that time +/// (e.g. `4.3.15`). Build-time features such as seamless App Check debug +/// tokens ship in newer plugin versions, so re-running `flutterfire configure` +/// must move the pin forward. +/// +/// A declaration is left untouched when it is commented out or already at or +/// above [targetVersion]. Only the text of the version literal is rewritten, +/// so the quoting style and the rest of the declaration are preserved. +/// +/// [onUnsupportedDeclaration] is called with the source line of each +/// declaration whose version is missing or is not a semantic version literal +/// (a version catalog reference, for example). Those are left untouched too. +String upgradeGoogleServicesPluginVersion( + String settingsContents, + String targetVersion, { + bool kotlin = false, + void Function(String declaration)? onUnsupportedDeclaration, +}) { + final Version target; + try { + target = Version.parse(targetVersion); + } on FormatException { + return settingsContents; + } + + final pattern = kotlin + ? _kotlinGoogleServicesPluginDeclarationPattern + : _googleServicesPluginDeclarationPattern; + + final buffer = StringBuffer(); + var copiedUpTo = 0; + + for (final match + in pattern.allMatches(_maskGradleComments(settingsContents))) { + final currentVersion = match.group(2); + + Version? current; + if (currentVersion != null) { + try { + current = Version.parse(currentVersion); + } on FormatException { + current = null; + } + } + + if (currentVersion == null || current == null) { + onUnsupportedDeclaration?.call( + _lineContaining(settingsContents, match.start), + ); + continue; + } + if (current >= target) continue; + + // The match ends with the closing quote of the version literal. + final versionEnd = match.end - 1; + final versionStart = versionEnd - currentVersion.length; + buffer + ..write(settingsContents.substring(copiedUpTo, versionStart)) + ..write(targetVersion); + copiedUpTo = versionEnd; + } + + buffer.write(settingsContents.substring(copiedUpTo)); + return buffer.toString(); +} + String _applyGradleSettingsDependency( String dependency, String version, { @@ -221,15 +362,16 @@ class FirebaseAndroidWrites { Future apply() async { await _writeAndroidGoogleServicesJsonFile(); - await gradleContentUpdates(flutterApp); + await gradleContentUpdates(flutterApp, logger: logger); return _firebaseJsonWrites(); } } Future gradleContentUpdates( - FlutterApp flutterApp, -) async { + FlutterApp flutterApp, { + Logger? logger, +}) async { final androidBuildGradleFile = File( path.join( flutterApp.androidDirectory.path, @@ -238,7 +380,7 @@ Future gradleContentUpdates( ); if (androidBuildGradleFile.existsSync()) { - return _gradleContentUpdates(flutterApp); + return _gradleContentUpdates(flutterApp, logger); } final androidBuildGradleKtsFile = File( @@ -249,7 +391,7 @@ Future gradleContentUpdates( ); if (androidBuildGradleKtsFile.existsSync()) { - return _gradleKtsContentUpdates(flutterApp); + return _gradleKtsContentUpdates(flutterApp, logger); } throw UnimplementedError( @@ -259,6 +401,7 @@ Future gradleContentUpdates( Future _gradleContentUpdates( FlutterApp flutterApp, + Logger? logger, ) async { final androidBuildGradleFile = File( path.join( @@ -286,7 +429,13 @@ Future _gradleContentUpdates( ), ); - final firebaseCorePubSpec = await getFirebaseCorePubSpec(); + // Prefer the versions declared by the `firebase_core` this app resolves. The + // pub cache lookup can return a version that only another project uses, so + // it is kept for adding missing declarations and never rewrites a pin. + final resolvedFirebaseCorePubSpec = + await getResolvedFirebaseCorePubSpec(flutterApp.package.path); + final firebaseCorePubSpec = + resolvedFirebaseCorePubSpec ?? await getFirebaseCorePubSpec(); final androidGradleSettingsFileContents = androidGradleSettingsFile.readAsStringSync(); @@ -359,6 +508,14 @@ Future _gradleContentUpdates( // We check if plugins block containing "id "com.android.application"" is present in the android/settings.gradle file if (androidGradleSettingsFileContents .contains('id "com.android.application"')) { + if (resolvedFirebaseCorePubSpec != null) { + content = _upgradeGoogleServicesPluginPin( + content, + resolvedFirebaseCorePubSpec.googleServicesGradlePluginVersion, + settingsFile: androidGradleSettingsFile, + logger: logger, + ); + } content = _applyGoogleServicesPlugin( flutterApp, content, @@ -393,6 +550,39 @@ Future _gradleContentUpdates( ); } +/// Moves an existing Google Services plugin pin in the settings file forward +/// to [targetVersion]. +/// +/// This is separate from applying the plugin, which returns early when +/// `android/app/build.gradle(.kts)` already references the plugin (a legacy +/// `classpath` declaration, for example) and would leave the pin behind. +AndroidGradleContents _upgradeGoogleServicesPluginPin( + AndroidGradleContents content, + String targetVersion, { + required File settingsFile, + bool kotlin = false, + Logger? logger, +}) { + return AndroidGradleContents( + buildGradleContent: content.buildGradleContent, + appBuildGradleContent: content.appBuildGradleContent, + gradleSettingsContent: upgradeGoogleServicesPluginVersion( + content.gradleSettingsContent, + targetVersion, + kotlin: kotlin, + onUnsupportedDeclaration: (declaration) { + final message = 'Could not read the Google Services plugin version in ' + '${settingsFile.path}, so it was left unchanged: $declaration'; + if (logger != null) { + logger.stderr(message); + } else { + stderr.writeln(message); + } + }, + ), + ); +} + AndroidGradleContents _legacyUpdateAndroidBuildGradle( AndroidGradleContents content, String googleServicesGradlePluginVersion, @@ -681,6 +871,7 @@ AndroidGradleContents _applyFirebaseAndroidPlugin({ // i.e., build.gradle.kts, app/build.gradle.kts and settings.gradle.kts files Future _gradleKtsContentUpdates( FlutterApp flutterApp, + Logger? logger, ) async { final androidBuildGradleKtsFile = File( path.join( @@ -708,7 +899,13 @@ Future _gradleKtsContentUpdates( ), ); - final firebaseCorePubSpec = await getFirebaseCorePubSpec(); + // Prefer the versions declared by the `firebase_core` this app resolves. The + // pub cache lookup can return a version that only another project uses, so + // it is kept for adding missing declarations and never rewrites a pin. + final resolvedFirebaseCorePubSpec = + await getResolvedFirebaseCorePubSpec(flutterApp.package.path); + final firebaseCorePubSpec = + resolvedFirebaseCorePubSpec ?? await getFirebaseCorePubSpec(); final androidGradleSettingsKtsFileContents = androidGradleSettingsKtsFile.readAsStringSync(); @@ -781,6 +978,15 @@ Future _gradleKtsContentUpdates( // We check if plugins block containing "id "com.android.application"" is present in the android/settings.gradle.kts file if (androidGradleSettingsKtsFileContents .contains('id("com.android.application")')) { + if (resolvedFirebaseCorePubSpec != null) { + content = _upgradeGoogleServicesPluginPin( + content, + resolvedFirebaseCorePubSpec.googleServicesGradlePluginVersion, + settingsFile: androidGradleSettingsKtsFile, + kotlin: true, + logger: logger, + ); + } content = _applyGoogleServicesPluginKts( flutterApp, content, @@ -1104,6 +1310,86 @@ AndroidGradleContents _applyFirebaseAndroidPluginKts({ ); } +/// The `package_config.json` covering [flutterAppPath], or null if there is +/// none. +/// +/// In a pub workspace the file lives at the workspace root rather than next to +/// the app's own `pubspec.yaml`, so parent directories are searched too. +File? _packageConfigFile(String flutterAppPath) { + var directory = Directory(path.normalize(path.absolute(flutterAppPath))); + + while (true) { + final packageConfigFile = File( + path.join(directory.path, '.dart_tool', 'package_config.json'), + ); + if (packageConfigFile.existsSync()) return packageConfigFile; + + final parent = directory.parent; + if (parent.path == directory.path) return null; + directory = parent; + } +} + +/// Reads the `firebase` section of the `pubspec.yaml` in [packageDirectory], +/// or returns null if the package does not have one. +Future _firebasePubSpecOfPackage( + Directory packageDirectory, +) async { + final content = + await File(pubspecPathForDirectory(packageDirectory)).readAsString(); + final yamlMap = loadYaml(content) as YamlMap; + final unparsedJson = yamlMap['firebase'] as YamlMap?; + if (unparsedJson == null) return null; + + return FirebasePubSpecModel.fromJson(unparsedJson.cast()); +} + +/// Reads the Gradle plugin versions declared by the `firebase_core` package +/// that the app at [flutterAppPath] resolves to, according to its +/// `.dart_tool/package_config.json`. +/// +/// Returns null when the app's dependencies have not been resolved yet, it +/// does not depend on `firebase_core`, or the resolved package does not +/// declare the versions. +Future getResolvedFirebaseCorePubSpec( + String flutterAppPath, +) async { + try { + final packageConfigFile = _packageConfigFile(flutterAppPath); + if (packageConfigFile == null) return null; + + final packageConfig = + jsonDecode(await packageConfigFile.readAsString()) as Map; + final packages = packageConfig['packages'] as List; + + final firebaseCore = packages.firstWhere( + (dynamic package) => package is Map && package['name'] == 'firebase_core', + orElse: () => null, + ); + if (firebaseCore == null) return null; + + // "rootUri" is either absolute or relative to the ".dart_tool" directory. + final rootUri = Uri.parse((firebaseCore as Map)['rootUri'] as String); + final packageRoot = rootUri.isAbsolute + ? rootUri.toFilePath() + : path.normalize( + path.join( + path.dirname(packageConfigFile.path), + rootUri.toFilePath(), + ), + ); + + return await _firebasePubSpecOfPackage(Directory(packageRoot)); + } catch (_) { + return null; + } +} + +/// Reads the Gradle plugin versions declared by the highest `firebase_core` +/// version in the pub cache. +/// +/// That is not necessarily the version the app being configured uses, so +/// prefer [getResolvedFirebaseCorePubSpec] and keep this as its fallback. Future getFirebaseCorePubSpec() async { try { const packageName = 'firebase_core-'; @@ -1140,17 +1426,9 @@ Future getFirebaseCorePubSpec() async { }, ); - final firebaseCoreDirectory = firebaseCoreItems.last; - final firebaseCorePubspecFile = - pubspecPathForDirectory(firebaseCoreDirectory); - final content = await File(firebaseCorePubspecFile).readAsString(); - final yamlMap = loadYaml(content) as YamlMap; - final unparsedJson = yamlMap['firebase'] as YamlMap?; - if (unparsedJson != null) { - return FirebasePubSpecModel.fromJson( - unparsedJson.cast(), - ); - } + final firebaseCorePubSpec = + await _firebasePubSpecOfPackage(firebaseCoreItems.last); + if (firebaseCorePubSpec != null) return firebaseCorePubSpec; } catch (_) { // If we cannot find the firebase_core package, we return the fallback versions } diff --git a/packages/flutterfire_cli/test/firebase_android_writes_test.dart b/packages/flutterfire_cli/test/firebase_android_writes_test.dart index 7607c39f..fc37c08e 100644 --- a/packages/flutterfire_cli/test/firebase_android_writes_test.dart +++ b/packages/flutterfire_cli/test/firebase_android_writes_test.dart @@ -1,6 +1,85 @@ +import 'dart:convert'; +import 'dart:io'; + import 'package:flutterfire_cli/src/firebase/firebase_android_writes.dart'; +import 'package:flutterfire_cli/src/flutter_app.dart'; +import 'package:path/path.dart' as path; import 'package:test/test.dart'; +/// Writes a `firebase_core` package into [pubCache], declaring +/// [googleServicesVersion] as its Google Services Gradle plugin version. +Directory _writeFirebaseCore( + Directory pubCache, { + required String version, + required String googleServicesVersion, +}) { + final directory = Directory( + path.join(pubCache.path, 'firebase_core-$version'), + )..createSync(recursive: true); + File(path.join(directory.path, 'pubspec.yaml')).writeAsStringSync(''' +name: firebase_core +version: $version +firebase: + google_services_gradle_plugin_version: '$googleServicesVersion' + crashlytics_gradle_plugin_version: '3.0.3' + performance_gradle_plugin_version: '1.4.2' +'''); + return directory; +} + +/// Writes the `package_config.json` of [appDirectory], resolving +/// `firebase_core` to [firebaseCoreRootUri]. +void _writePackageConfig( + Directory appDirectory, { + required String firebaseCoreRootUri, +}) { + final dartTool = Directory(path.join(appDirectory.path, '.dart_tool')) + ..createSync(recursive: true); + File(path.join(dartTool.path, 'package_config.json')).writeAsStringSync( + jsonEncode({ + 'configVersion': 2, + 'packages': [ + { + 'name': 'firebase_core', + 'rootUri': firebaseCoreRootUri, + 'packageUri': 'lib/', + }, + ], + }), + ); +} + +/// Creates a Flutter app in [appDirectory] with the given Android Gradle +/// files, written in the Kotlin DSL when [kotlin] is true. +Future _createAndroidApp( + Directory appDirectory, { + required String settings, + required String appBuildGradle, + bool kotlin = false, +}) async { + final extension = kotlin ? '.kts' : ''; + final androidApp = Directory(path.join(appDirectory.path, 'android', 'app')) + ..createSync(recursive: true); + + File(path.join(appDirectory.path, 'pubspec.yaml')).writeAsStringSync(''' +name: test_app +environment: + sdk: ">=3.0.0 <4.0.0" +dependencies: + flutter: + sdk: flutter + firebase_core: ^3.10.0 +'''); + File(path.join(appDirectory.path, 'android', 'build.gradle$extension')) + .writeAsStringSync('// Top-level build file\n'); + File(path.join(appDirectory.path, 'android', 'settings.gradle$extension')) + .writeAsStringSync(settings); + File(path.join(androidApp.path, 'build.gradle$extension')) + .writeAsStringSync(appBuildGradle); + + return (await FlutterApp.load(appDirectory))!; +} + void main() { group('Firebase Android Writes - Regex Pattern Tests', () { group('Android Application Pattern Tests', () { @@ -316,4 +395,540 @@ plugins { }); }); }); + + group('upgradeGoogleServicesPluginVersion', () { + const groovySettings = ''' +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.3.0" apply false + // START: FlutterFire Configuration + id "com.google.gms.google-services" version "4.3.15" apply false + // END: FlutterFire Configuration + id "org.jetbrains.kotlin.android" version "2.3.0" apply false +} + +include ":app" +'''; + + const ktsSettings = ''' +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.3.0" apply false + // START: FlutterFire Configuration + id("com.google.gms.google-services") version("4.4.4") apply false + // END: FlutterFire Configuration + id("org.jetbrains.kotlin.android") version "2.3.0" apply false +} + +include(":app") +'''; + + const ktsInfixSettings = ''' +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.3.0" apply false + // START: FlutterFire Configuration + id("com.google.gms.google-services") version "4.4.4" apply false + // END: FlutterFire Configuration + id("org.jetbrains.kotlin.android") version "2.3.0" apply false +} + +include(":app") +'''; + + test('upgrades an older Groovy DSL pin (4.3.15 -> 4.7.0)', () { + final result = + upgradeGoogleServicesPluginVersion(groovySettings, '4.7.0'); + + expect( + result, + contains( + 'id "com.google.gms.google-services" version "4.7.0" apply false', + ), + ); + expect(result, isNot(contains('4.3.15'))); + expect( + result.replaceFirst('4.7.0', '4.3.15'), + equals(groovySettings), + ); + }); + + test('upgrades an older Kotlin DSL pin (4.4.4 -> 4.7.0)', () { + final result = upgradeGoogleServicesPluginVersion( + ktsSettings, + '4.7.0', + kotlin: true, + ); + + expect( + result, + contains( + 'id("com.google.gms.google-services") version("4.7.0") apply false', + ), + ); + expect(result, isNot(contains('4.4.4'))); + expect(result.replaceFirst('4.7.0', '4.4.4'), equals(ktsSettings)); + }); + + test('upgrades an older Kotlin DSL infix pin (4.4.4 -> 4.7.0)', () { + final result = upgradeGoogleServicesPluginVersion( + ktsInfixSettings, + '4.7.0', + kotlin: true, + ); + + expect( + result, + contains( + 'id("com.google.gms.google-services") version "4.7.0" apply false', + ), + ); + expect(result, isNot(contains('4.4.4'))); + expect(result.replaceFirst('4.7.0', '4.4.4'), equals(ktsInfixSettings)); + }); + + test('preserves single-quote style when upgrading', () { + const settings = + "id 'com.google.gms.google-services' version '4.3.15' apply false"; + + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + + expect( + result, + equals( + "id 'com.google.gms.google-services' version '4.7.0' apply false", + ), + ); + }); + + test('is a no-op when the pin is already at the target version', () { + final result = + upgradeGoogleServicesPluginVersion(groovySettings, '4.3.15'); + expect(result, equals(groovySettings)); + }); + + test('never downgrades a newer pin', () { + final result = + upgradeGoogleServicesPluginVersion(groovySettings, '4.3.0'); + expect(result, equals(groovySettings)); + }); + + test('is a no-op when the plugin is not declared', () { + const settings = ''' +plugins { + id "com.android.application" version "8.3.0" apply false +} +'''; + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + expect(result, equals(settings)); + }); + + test('is a no-op for an unparseable target version', () { + final result = + upgradeGoogleServicesPluginVersion(groovySettings, 'not-a-version'); + expect(result, equals(groovySettings)); + }); + + test('is idempotent across repeated configure runs', () { + final once = upgradeGoogleServicesPluginVersion(groovySettings, '4.7.0'); + final twice = upgradeGoogleServicesPluginVersion(once, '4.7.0'); + expect(twice, equals(once)); + }); + + test('does not touch the Groovy pin when asked to upgrade Kotlin DSL', () { + final result = upgradeGoogleServicesPluginVersion( + groovySettings, + '4.7.0', + kotlin: true, + ); + expect(result, equals(groovySettings)); + }); + + test('upgrades the declaration below a commented-out one', () { + const settings = ''' +plugins { + // id "com.google.gms.google-services" version "4.7.0" apply false + id "com.google.gms.google-services" version "4.3.15" apply false +} +'''; + + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + + expect( + result, + equals(''' +plugins { + // id "com.google.gms.google-services" version "4.7.0" apply false + id "com.google.gms.google-services" version "4.7.0" apply false +} +'''), + ); + }); + + test('does not rewrite a commented-out declaration', () { + const settings = ''' +plugins { + // id("com.google.gms.google-services") version "4.3.15" apply false + /* + id("com.google.gms.google-services") version "4.4.0" apply false + */ + id("com.google.gms.google-services") version "4.4.4" apply false // pinned +} +'''; + + final result = upgradeGoogleServicesPluginVersion( + settings, + '4.7.0', + kotlin: true, + ); + + expect( + result, + equals(''' +plugins { + // id("com.google.gms.google-services") version "4.3.15" apply false + /* + id("com.google.gms.google-services") version "4.4.0" apply false + */ + id("com.google.gms.google-services") version "4.7.0" apply false // pinned +} +'''), + ); + }); + + test('does not treat "//" inside a string as a comment', () { + const settings = ''' +pluginManagement { + repositories { maven { url "https://maven.google.com" } } +} +plugins { id "com.google.gms.google-services" version "4.3.15" apply false } +'''; + + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + + expect(result, equals(settings.replaceFirst('4.3.15', '4.7.0'))); + }); + + test('upgrades a Kotlin DSL declaration that uses "apply(false)"', () { + const settings = + 'id("com.google.gms.google-services") version "4.3.15" apply(false)'; + + final result = upgradeGoogleServicesPluginVersion( + settings, + '4.7.0', + kotlin: true, + ); + + expect( + result, + equals( + 'id("com.google.gms.google-services") version "4.7.0" apply(false)', + ), + ); + }); + + test('upgrades a Groovy declaration with extra whitespace', () { + const settings = + 'id "com.google.gms.google-services"\tversion "4.3.15" apply\tfalse'; + + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + + expect( + result, + equals( + 'id "com.google.gms.google-services"\tversion "4.7.0" apply\tfalse', + ), + ); + }); + + test('upgrades a Groovy declaration written with parentheses', () { + const settings = + "id('com.google.gms.google-services') version('4.3.15') apply false"; + + final result = upgradeGoogleServicesPluginVersion(settings, '4.7.0'); + + expect( + result, + equals( + "id('com.google.gms.google-services') version('4.7.0') apply false", + ), + ); + }); + + test('reports declarations whose version cannot be read', () { + const settings = ''' +plugins { + // id("com.google.gms.google-services") version "not-a-version" + id("com.google.gms.google-services") version libs.versions.gms apply false + id("com.google.gms.google-services") version "4.4" apply false +} +'''; + final unsupported = []; + + final result = upgradeGoogleServicesPluginVersion( + settings, + '4.7.0', + kotlin: true, + onUnsupportedDeclaration: unsupported.add, + ); + + expect(result, equals(settings)); + expect( + unsupported, + equals([ + 'id("com.google.gms.google-services") version libs.versions.gms apply false', + 'id("com.google.gms.google-services") version "4.4" apply false', + ]), + ); + }); + + test('does not report a declaration it can read', () { + final unsupported = []; + + upgradeGoogleServicesPluginVersion( + groovySettings, + '4.7.0', + onUnsupportedDeclaration: unsupported.add, + ); + upgradeGoogleServicesPluginVersion( + groovySettings, + '4.3.0', + onUnsupportedDeclaration: unsupported.add, + ); + + expect(unsupported, isEmpty); + }); + }); + + group('getResolvedFirebaseCorePubSpec', () { + late Directory tempDirectory; + late Directory pubCache; + + setUp(() { + tempDirectory = + Directory.systemTemp.createTempSync('flutterfire_cli_android'); + pubCache = Directory( + path.join(tempDirectory.path, 'pub-cache', 'hosted', 'pub.dev'), + ); + }); + + tearDown(() { + tempDirectory.deleteSync(recursive: true); + }); + + test( + 'reads the firebase_core the app resolves to, not the highest version ' + 'in the pub cache', () async { + final resolved = _writeFirebaseCore( + pubCache, + version: '3.10.0', + googleServicesVersion: '4.4.2', + ); + _writeFirebaseCore( + pubCache, + version: '3.15.0', + googleServicesVersion: '4.7.0', + ); + final appDirectory = Directory(path.join(tempDirectory.path, 'app')); + _writePackageConfig( + appDirectory, + firebaseCoreRootUri: resolved.uri.toString(), + ); + + final pubSpec = await getResolvedFirebaseCorePubSpec(appDirectory.path); + + expect(pubSpec?.googleServicesGradlePluginVersion, equals('4.4.2')); + expect(pubSpec?.crashlyticsGradlePluginVersion, equals('3.0.3')); + expect(pubSpec?.performanceGradlePluginVersion, equals('1.4.2')); + }); + + test('follows a root URI relative to the ".dart_tool" directory', () async { + _writeFirebaseCore( + pubCache, + version: '3.10.0', + googleServicesVersion: '4.4.2', + ); + final appDirectory = Directory(path.join(tempDirectory.path, 'app')); + _writePackageConfig( + appDirectory, + firebaseCoreRootUri: + '../../pub-cache/hosted/pub.dev/firebase_core-3.10.0', + ); + + final pubSpec = await getResolvedFirebaseCorePubSpec(appDirectory.path); + + expect(pubSpec?.googleServicesGradlePluginVersion, equals('4.4.2')); + }); + + test('finds the package_config.json of a pub workspace', () async { + final resolved = _writeFirebaseCore( + pubCache, + version: '3.10.0', + googleServicesVersion: '4.4.2', + ); + final workspace = Directory(path.join(tempDirectory.path, 'workspace')); + _writePackageConfig( + workspace, + firebaseCoreRootUri: resolved.uri.toString(), + ); + final appDirectory = Directory( + path.join(workspace.path, 'packages', 'app'), + )..createSync(recursive: true); + + final pubSpec = await getResolvedFirebaseCorePubSpec(appDirectory.path); + + expect(pubSpec?.googleServicesGradlePluginVersion, equals('4.4.2')); + }); + + test('returns null when the dependencies are not resolved', () async { + final appDirectory = Directory(path.join(tempDirectory.path, 'app')) + ..createSync(recursive: true); + + expect(await getResolvedFirebaseCorePubSpec(appDirectory.path), isNull); + }); + }); + + group('gradleContentUpdates', () { + const groovySettings = ''' +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.3.0" apply false + id "com.google.gms.google-services" version "4.3.15" apply false +} + +include ":app" +'''; + const groovyLegacyAppBuildGradle = ''' +buildscript { + dependencies { + classpath 'com.google.gms:google-services:4.3.15' + } +} + +plugins { + id "com.android.application" +} +'''; + const ktsSettings = ''' +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.3.0" apply false + id("com.google.gms.google-services") version "4.3.15" apply(false) +} + +include(":app") +'''; + const ktsLegacyAppBuildGradle = ''' +buildscript { + dependencies { + classpath("com.google.gms:google-services:4.3.15") + } +} + +plugins { + id("com.android.application") +} +'''; + + late Directory tempDirectory; + late Directory appDirectory; + + setUp(() { + tempDirectory = + Directory.systemTemp.createTempSync('flutterfire_cli_android'); + appDirectory = Directory(path.join(tempDirectory.path, 'app')); + }); + + tearDown(() { + tempDirectory.deleteSync(recursive: true); + }); + + void resolveFirebaseCore({required String googleServicesVersion}) { + final firebaseCore = _writeFirebaseCore( + Directory(path.join(tempDirectory.path, 'pub-cache')), + version: '3.10.0', + googleServicesVersion: googleServicesVersion, + ); + _writePackageConfig( + appDirectory, + firebaseCoreRootUri: firebaseCore.uri.toString(), + ); + } + + String readAndroidFile(String relativePath) { + return File(path.join(appDirectory.path, 'android', relativePath)) + .readAsStringSync(); + } + + test( + 'upgrades the settings.gradle pin when app/build.gradle has the ' + 'legacy classpath declaration', () async { + final flutterApp = await _createAndroidApp( + appDirectory, + settings: groovySettings, + appBuildGradle: groovyLegacyAppBuildGradle, + ); + resolveFirebaseCore(googleServicesVersion: '4.4.2'); + + await gradleContentUpdates(flutterApp); + + expect( + readAndroidFile('settings.gradle'), + equals(groovySettings.replaceFirst('4.3.15', '4.4.2')), + ); + expect( + readAndroidFile(path.join('app', 'build.gradle')), + equals(groovyLegacyAppBuildGradle), + ); + }); + + test( + 'upgrades the settings.gradle.kts pin when app/build.gradle.kts has ' + 'the legacy classpath declaration', () async { + final flutterApp = await _createAndroidApp( + appDirectory, + settings: ktsSettings, + appBuildGradle: ktsLegacyAppBuildGradle, + kotlin: true, + ); + resolveFirebaseCore(googleServicesVersion: '4.4.2'); + + await gradleContentUpdates(flutterApp); + + expect( + readAndroidFile('settings.gradle.kts'), + equals(ktsSettings.replaceFirst('4.3.15', '4.4.2')), + ); + expect( + readAndroidFile(path.join('app', 'build.gradle.kts')), + equals(ktsLegacyAppBuildGradle), + ); + }); + + test('never downgrades a pin that is newer than the resolved firebase_core', + () async { + final flutterApp = await _createAndroidApp( + appDirectory, + settings: groovySettings, + appBuildGradle: groovyLegacyAppBuildGradle, + ); + resolveFirebaseCore(googleServicesVersion: '4.3.0'); + + await gradleContentUpdates(flutterApp); + + expect(readAndroidFile('settings.gradle'), equals(groovySettings)); + }); + + test('leaves the pin alone when firebase_core is not resolved', () async { + final flutterApp = await _createAndroidApp( + appDirectory, + settings: groovySettings, + appBuildGradle: groovyLegacyAppBuildGradle, + ); + + await gradleContentUpdates(flutterApp); + + expect(readAndroidFile('settings.gradle'), equals(groovySettings)); + }); + }); }