sort_strings.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/python3
  2. import re
  3. import pathlib
  4. # add your files here
  5. strings_files = [
  6. "ffupdater/src/main/res/values-pt-rBR/strings.xml",
  7. "ffupdater/src/main/res/values-pl/strings.xml",
  8. "ffupdater/src/main/res/values-ru/strings.xml",
  9. "ffupdater/src/main/res/values-fr/strings.xml",
  10. "ffupdater/src/main/res/values-de/strings.xml",
  11. "ffupdater/src/main/res/values-uk/strings.xml",
  12. "ffupdater/src/main/res/values/strings.xml",
  13. "ffupdater/src/main/res/values-bg/strings.xml",
  14. "ffupdater/src/main/res/values-ja/strings.xml",
  15. "ffupdater/src/main/res/values-cs/strings.xml",
  16. "ffupdater/src/main/res/values-it/strings.xml",
  17. "ffupdater/src/main/res/values-nb-rNO/strings.xml",
  18. "ffupdater/src/main/res/values-tr/strings.xml",
  19. "ffupdater/src/main/res/values-zh-rCN/strings.xml",
  20. "ffupdater/src/main/res/values-es/strings.xml",
  21. "ffupdater/src/main/res/values-hu/strings.xml",
  22. ]
  23. # 1. transform the strings.xml file to a dict
  24. # 2. sort the dict
  25. # 3. transform the dict to a strings.xml file
  26. def sort_strings_xml_file(path_to_file: str):
  27. entries = dict()
  28. current_entry_name = None
  29. # read entries from strings.xml file
  30. with open(path_to_file, "r") as file:
  31. for line in file.readlines():
  32. # a new entry was found in the strings.xml file
  33. if line.strip().startswith("<string ") or line.strip().startswith("<plurals "):
  34. current_entry_name = re.search(r'name="(.+)"', line).group(1)
  35. entries[current_entry_name] = ""
  36. # store content for the current entry
  37. if current_entry_name is not None:
  38. entries[current_entry_name] += line
  39. # stop recording for the current entry
  40. if line.strip().endswith("</string>") or line.strip().endswith("</plurals>"):
  41. current_entry_name = None
  42. entries = dict(sorted(entries.items()))
  43. # write results back to the strings.xml file
  44. with open(path_to_file, "w") as file:
  45. file.write(('<?xml version="1.0" encoding="utf-8"?>'
  46. '<resources>'
  47. f'{"".join(entries.values())}</resources>'))
  48. print(f"{path_to_file} was sorted")
  49. for strings_file in strings_files:
  50. strings_file = f"{(pathlib.Path(__file__).parent.parent.absolute())}/{strings_file}"
  51. sort_strings_xml_file(strings_file)