1
1
import sys
2
+ import io
2
3
import os
3
4
import xml .etree .ElementTree as ET
4
5
import re
@@ -86,15 +87,32 @@ def add_new_string_tag(root, key, value):
86
87
# try to find the last tag in the
87
88
last_element_index = - 1
88
89
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 )
98
116
else :
99
117
new_tag .tail = "\n "
100
118
root .append (new_tag )
@@ -106,7 +124,7 @@ def save_translations(tree, file_path):
106
124
except AttributeError :
107
125
print ("Warning: ET.indent not available. Output formatting may not be ideal." )
108
126
109
- tree .write (file_path , encoding = 'utf-8' , xml_declaration = True )
127
+ tree .write (file_path , encoding = 'utf-8' , xml_declaration = False )
110
128
print (f"\n Saved changes to { file_path } " )
111
129
112
130
def main ():
@@ -115,6 +133,11 @@ def main():
115
133
print ("Usage: python utils/translate_helper.py <lang_id> [--check]" )
116
134
sys .exit (1 )
117
135
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
+
118
141
# get arguments
119
142
lang_id = sys .argv [1 ]
120
143
is_check_mode = len (sys .argv ) > 2 and sys .argv [2 ] == '--check'
0 commit comments