Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor convert_xcstrings_to_jsons.py for Improved File Handling and Error Management #58

Merged
38 changes: 30 additions & 8 deletions Scribe-i18n/scripts/iOS/convert_xcstrings_to_jsons.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,35 @@
import os

directory = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
file = open(os.path.join(directory, "Localizable.xcstrings"), "r").read()
dir_list = os.listdir(directory)

# Ensure the "jsons" folder exists inside the directory.
jsons_folder = os.path.join(directory, "jsons")
if not os.path.exists(jsons_folder):
os.makedirs(jsons_folder)

# Read the Localizable.xcstrings file.
try:
with open(os.path.join(directory, "Localizable.xcstrings"), "r") as f:
file = f.read()

except FileNotFoundError:
print("Error: Localizable.xcstrings file not found.")
exit(1)

dir_list = os.listdir(jsons_folder)
languages = [file.replace(".json", "") for file in dir_list if file.endswith(".json")]

for lang in languages:
dest = open(f"{directory}/{lang}.json", "w")
if lang == "en-US":
lang = "en"
lang = "en" if lang == "en-US" else lang

# Attempt to load the JSON data.
try:
json_file = json.loads(file)

except json.JSONDecodeError:
print("Error: The Localizable.xcstrings file is not valid JSON.")
exit(1)

json_file = json.loads(file)
strings = json_file["strings"]

data = {}
Expand All @@ -38,8 +57,11 @@

data[key] = translation

json.dump(data, dest, indent=2, ensure_ascii=False)
dest.write("\n")
lang = "en-US" if lang == "en" else lang
# Write to the destination JSON file using a context manager.
with open(f"{jsons_folder}/{lang}.json", "w") as dest:
json.dump(data, dest, indent=2, ensure_ascii=False)
dest.write("\n")

print(
"Scribe-i18n Localizable.xcstrings file successfully converted to the localization JSON files."
Expand Down