Skip to content

Commit af76dc8

Browse files
committed
feature: Insert new keys in alphabetical order when translating
1 parent a37d4f0 commit af76dc8

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

utils/translate_helper.py

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import sys
2+
import io
23
import os
34
import xml.etree.ElementTree as ET
45
import re
@@ -86,15 +87,32 @@ def add_new_string_tag(root, key, value):
8687
# try to find the last tag in the
8788
last_element_index = -1
8889
children = list(root)
89-
for i in range(len(children) - 1, -1, -1):
90-
if (children[i].tag == f"{{{X_NS}}}String" or
91-
children[i].tag == f"{{{XAML_NS}}}ResourceDictionary.MergedDictionaries"):
92-
last_element_index = i
93-
break
94-
95-
if last_element_index != -1:
96-
new_tag.tail = root[last_element_index].tail
97-
root.insert(last_element_index + 1, new_tag)
90+
91+
start = 0
92+
end = len(children) - 1
93+
middle = -1
94+
95+
# find the first String tag
96+
while (children[start].tag != f"{{{X_NS}}}String"):
97+
start = start + 1
98+
99+
# find where the insert the new tag
100+
# so it always keeps the alphabetical order
101+
while (end - start) > 1:
102+
middle = int((start + end) / 2)
103+
104+
if (children[middle].tag == f"{{{X_NS}}}String"):
105+
middle_key = children[middle].get(f"{{{X_NS}}}Key")
106+
107+
if key.lower() < middle_key.lower():
108+
end = middle
109+
else:
110+
start = middle
111+
112+
# insert after the middle or at the end
113+
if middle != -1:
114+
new_tag.tail = root[middle].tail
115+
root.insert(middle + 1, new_tag)
98116
else:
99117
new_tag.tail = "\n "
100118
root.append(new_tag)
@@ -106,7 +124,7 @@ def save_translations(tree, file_path):
106124
except AttributeError:
107125
print("Warning: ET.indent not available. Output formatting may not be ideal.")
108126

109-
tree.write(file_path, encoding='utf-8', xml_declaration=True)
127+
tree.write(file_path, encoding='utf-8', xml_declaration=False)
110128
print(f"\nSaved changes to {file_path}")
111129

112130
def main():
@@ -115,6 +133,11 @@ def main():
115133
print("Usage: python utils/translate_helper.py <lang_id> [--check]")
116134
sys.exit(1)
117135

136+
# Force sys.stdin to use UTF-8 decoding
137+
if sys.stdin.encoding.lower() != 'utf-8':
138+
print("Changin input encoding to UTF-8")
139+
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
140+
118141
# get arguments
119142
lang_id = sys.argv[1]
120143
is_check_mode = len(sys.argv) > 2 and sys.argv[2] == '--check'

0 commit comments

Comments
 (0)