updateBuildGradle method

Future<void> updateBuildGradle()

Updates the build.gradle file with flavor configurations.

Implementation

Future<void> updateBuildGradle() async {
  final buildGradleFile = File(androidAppBuildGradlePath);
  final pubspecFile = File('pubspec.yaml');

  if (!await buildGradleFile.exists()) {
    logger.e('build.gradle file not found.');
    return;
  }

  final buildGradleLines = await buildGradleFile.readAsLines();

  // Check if the flavor configuration section already exists.
  bool flavorConfigExists = false;
  for (var i = 0; i < buildGradleLines.length; i++) {
    if (buildGradleLines[i].contains('flavorDimensions') &&
        buildGradleLines[i + 2].contains('productFlavors {')) {
      flavorConfigExists = true;
      break;
    }
  }

  if (!flavorConfigExists) {
    // Find the application ID in build.gradle.
    String? applicationId;

    for (var line in buildGradleLines) {
      if (line.contains('namespace')) {
        final parts = line.split('"');
        if (parts.length >= 2) {
          applicationId = parts[1];
          break;
        }
      }
    }

    final pubspecContent = await pubspecFile.readAsString();
    final pubspecYaml = loadYaml(pubspecContent);

    final resValueString = pubspecYaml['name'] as String?;

    // Add the new flavor configuration section.
    final flavorConfigurations = '''
    flavorDimensions  'app'

    productFlavors {
        dev {
            dimension "app"
            resValue "string", "app_name", "$resValueString Dev"
            versionNameSuffix "-dev"
            applicationId "$applicationId.dev"
        }
        staging {
            dimension "app"
            resValue "string", "app_name", "$resValueString Staging "
            versionNameSuffix "-stg"
            applicationId "$applicationId.staging"
        }
        prod {
            dimension "app"
            resValue "string", "app_name", "$resValueString"
            applicationId "$applicationId"
        }
    }
    ''';

    // Find the location to insert flavor configurations.
    int insertIndex = -1;
    for (var i = 0; i < buildGradleLines.length; i++) {
      if (buildGradleLines[i].contains('defaultConfig {')) {
        insertIndex = i;
        break;
      }
    }

    if (insertIndex == -1) {
      logger.e('Could not find defaultConfig section in build.gradle.');
      return;
    }

    // Insert the new flavor configurations.
    buildGradleLines.insertAll(insertIndex, flavorConfigurations.split('\n'));

    await buildGradleFile.writeAsString(buildGradleLines.join('\n'));
  } else {
    logger.i('Flavor configuration already exists in build.gradle.');
  }
}