updateCompileSdkVersion function

void updateCompileSdkVersion(
  1. String directoryPath
)

Implementation

void updateCompileSdkVersion(String directoryPath) {
  // Possible file names
  const List<String> fileNames = ['build.gradle', 'build.gradle.kts'];
  String? filePath;

  // Detect the existing file
  for (final fileName in fileNames) {
    final file = File('$directoryPath/$fileName');
    if (file.existsSync()) {
      filePath = file.path;
      break;
    }
  }

  if (filePath == null) {
    print("Error: Neither build.gradle nor build.gradle.kts exists in the directory: $directoryPath");
    return;
  }

  final file = File(filePath);
  final bool isKts = filePath.endsWith('.kts');
  List<String> lines;

  try {
    lines = file.readAsLinesSync();
  } catch (e) {
    print("Error reading file: $e");
    return;
  }

  bool updated = false;

  // Update compileSdk line
  for (int i = 0; i < lines.length; i++) {
    if (lines[i].trim().startsWith(isKts ? "compileSdk = " : "compileSdk")) {
      lines[i] = isKts ? "    compileSdk = 35" : "    compileSdk 35";
      updated = true;
      print("Updated compileSdk to 35 in ${file.path}.");
      break;
    }
  }

  if (!updated) {
    print("Error: Could not find the compileSdk declaration in ${file.path}.");
    return;
  }

  // Write updated content back to the file
  try {
    file.writeAsStringSync(lines.join('\n'));
    print("File updated successfully: ${file.path}");
  } catch (e) {
    print("Error writing to file: $e");
  }
}