slang-i18n / slang

Type-safe i18n for Dart and Flutter
https://pub.dev/packages/slang
MIT License
459 stars 39 forks source link

slang clean fails when analyze output for unused translations has empty map for a locale #189

Closed arianneorpilla closed 8 months ago

arianneorpilla commented 8 months ago

Describe the bug I'm trying to run dart run slang clean with namespaces: false. I have multiple locales in the project, all with a filename akin to strings_en-US.i18n.json. For some reason, dart run slang analyze --full gives me only results in the base locale for unused translations, i.e.

  "en-US": {"loremIpsum":  "loremIpsum"},
  "de-DE": {},

If I run dart run slang clean, this results to an error if the _unused_translations.json has an empty map for a non-base locale.

To Reproduce Not quite able to provide exact reproduction steps as the project I'm working on is closed source, but I was able to work out a solution:

To do this successfully, I had to do the following, dart run slang analyze --full --split-unused. Remove the unsplit translation file _unused_translations.json. In clean.dart:

Instead of:

if (fileMap.isEmpty) {
      throw 'No file found for locale <$locale>';
    }

final file = fileMap.values.first;
...

Use:

if (fileMap.isNotEmpty) {
      final file = fileMap.values.first;
      final map = outputMap.values.first;
      MapUtils.clearEmptyMaps(map);

      FileUtils.writeFileOfType(
        fileType: config.fileType,
        path: file.path,
        content: map,
      );
    }

This allows me to clear the unused translations for the base locale. Another run of the analyze command now detects unused translations of the non-base locale. This now allows me to clear the unused translations for non-base locales.

The unused translations for base and non-base locales have been cleared, which is the expected behaviour.

Expected behavior dart run slang clean will take the input of _unused_translations.json (or not even require it), and clear unused translations for base and non-base locales.

(Unless I'm misunderstanding the purpose of the command here)

Additional context Error message otherwise without the change,

No file found for locale <I18nLocale(de-DE)>
#0      _deleteEntriesForLocale (package:slang/src/runner/clean.dart:123:7)
#1      runClean (package:slang/src/runner/clean.dart:50:11)
<asynchronous suspension>
#2      main (file:///Users/xxxxx/.pub-cache/hosted/pub.dev/slang-3.25.0/bin/slang.dart:163:7)
<asynchronous suspension>

I can make a pull request if the change I made is desired, though not sure if this behaviour/the use case I want aligns with what is desired by the author

Tienisto commented 8 months ago

Thank you. I added a fix in 7a50769cc0e4ec2186bd203e1dbbcb0b5a82ebb8