readNewEntriesFromFile function

void readNewEntriesFromFile(
  1. String packagePath
)

Implementation

void readNewEntriesFromFile(String packagePath) async {
  // Specify the path to the user's text file containing new entries
  String userTxtFilePath = './new_language_entries.txt';

  // Check if the file exists, and create it if it doesn't
  final file = File(userTxtFilePath);
  if (!file.existsSync()) {
    stdout.write(
        "File 'new_language_entries.txt' does not exist. Creating it...");
    await file.create();
  }

  // Read the user's text file line by line
  final lines = await file.readAsLines();

  // Create a map to store entries and their corresponding hash keys
  Map<String, String> entriesWithHashKeys = {};

  // Iterate through each line (entry) in the text file
  for (String entry in lines) {
    // Generate the hash key for the entry
    final hashKeyEntry = HashKey.getHashKey(entry);

    // Store the entry and its hash key in the map
    entriesWithHashKeys[hashKeyEntry] = entry;
  }

  // Add the new entries with their hash keys to each language JSON file
  Directory(p.join(packagePath, 'lib', 'language_json'))
      .listSync()
      .where((element) =>
          element is File && !element.path.endsWith('strings.g.dart'))
      .forEach((jsonFile) {
    // Explicitly cast FileSystemEntity to File
    File file = jsonFile as File;

    try {
      // Read the existing JSON file
      Map<String, dynamic> jsonContent = json.decode(file.readAsStringSync());

      // Add the new entries with their hash keys without overwriting existing entries
      entriesWithHashKeys.forEach((key, value) {
        jsonContent.putIfAbsent(key, () => value);
      });

      // Create a JsonEncoder with indentation for pretty printing
      JsonEncoder encoder = const JsonEncoder.withIndent('  ');

      // Write the updated content back to the JSON file
      file.writeAsStringSync(encoder.convert(jsonContent));
      stdout.write("\nSuccessfully added new entries to ${file.path}");
    } catch (e) {
      stdout.write(
          "\nFailed to add new entries to ${file.path}: ${e.toString()}");
    }
  });
}