run method

  1. @override
void run()
override

Runs this command.

The return value is wrapped in a Future if necessary and returned by CommandRunner.runCommand.

Implementation

@override
void run() async {
  final supportedLocales = argResults?['locales'] as List<String>;

  final libDir = Directory('lib');
  final partialsDir = Directory('lib/l10n/partials');

  if (!libDir.existsSync()) {
    print('Error: lib directory does not exist.');
    return;
  }

  if (!partialsDir.existsSync()) {
    partialsDir.createSync(recursive: true);
  }

  // Step 1: Detect all entity names
  final entityNames = _getEntityNames(partialsDir);
  print('Detected entity names: $entityNames');

  final keysByEntity = <String, Set<String>>{};

  // Step 2: Scan Dart files in lib directory for keys
  await for (var entityFile in libDir.list(recursive: true)) {
    if (entityFile is File && entityFile.path.endsWith('.dart')) {
      final content = await entityFile.readAsString();
      final matches = RegExp(r'App(Localizations|Locale)\.of\(context\)\.(\w+)').allMatches(content);

      for (var match in matches) {
        final key = match.group(2);
        if (key != null) {
          // Step 3: Match the key with entity names
          final matchedEntity =
              entityNames.firstWhere((entity) => key.startsWith(entity), orElse: () => 'miscellaneous');

          keysByEntity.putIfAbsent(matchedEntity, () => {}).add(key);
        }
      }
    }
  }

  // Step 4: Write keys to corresponding .arb files
  for (var entity in keysByEntity.keys) {
    for (var locale in supportedLocales) {
      final arbFile = File(path.join(partialsDir.path, '${entity}_$locale.arb'));
      final existingKeys = _getExistingKeys(arbFile);

      final combinedKeys = existingKeys.union(keysByEntity[entity]!);
      final outputContent = _generateArbContent(combinedKeys);

      arbFile.writeAsStringSync(outputContent);
      print('Keys extracted and saved to ${arbFile.path}');
    }
  }

  print('Extraction operation completed.');
}