extract_locales.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Extracts localizable strings from a set of source files and writes them to JSON files.
  2. // This script can create new translations or update existing ones.
  3. // Usage:
  4. // `../make --js extract_locales.js <locale code>`
  5. // Generates a `base/assets/locale/<locale code>.json` file
  6. let locale = scriptArgs[4];
  7. if (!locale) {
  8. console.log("Locale code not set!");
  9. std.exit();
  10. }
  11. let locale_path = "./base/assets/locale/" + locale + ".json";
  12. let out = {};
  13. let old = {};
  14. if (fs_exists(locale_path)) {
  15. old = JSON.parse(fs_readfile(locale_path).toString());
  16. }
  17. let source_paths = [
  18. "base/sources", "base/sources/nodes",
  19. "paint/sources", "paint/sources/nodes",
  20. "lab/sources", "lab/sources/nodes",
  21. "forge/sources", "forge/sources/nodes"
  22. ];
  23. for (let path of source_paths) {
  24. if (!fs_exists(path)) {
  25. continue;
  26. }
  27. let files = fs_readdir(path);
  28. for (let file of files) {
  29. if (!file.endsWith(".ts")) {
  30. continue;
  31. }
  32. let data = fs_readfile(path + "/" + file).toString();
  33. let start = 0;
  34. while (true) {
  35. start = data.indexOf('tr("', start);
  36. if (start == -1) {
  37. break;
  38. }
  39. start += 4; // tr("
  40. let end_a = data.indexOf('")', start);
  41. let end_b = data.indexOf('",', start);
  42. if (end_a == -1) {
  43. end_a = end_b;
  44. }
  45. if (end_b == -1) {
  46. end_b = end_a;
  47. }
  48. let end = end_a < end_b ? end_a : end_b;
  49. let val = data.substring(start, end);
  50. val = val.replaceAll("\\n", "\n");
  51. if (old.hasOwnProperty(val)) {
  52. out[val] = old[val];
  53. }
  54. else {
  55. out[val] = "";
  56. }
  57. start = end;
  58. }
  59. }
  60. }
  61. fs_writefile(locale_path, JSON.stringify(out, Object.keys(out).sort(), 4));