Skip to content

Commit e46e39d

Browse files
fix: update regex code to work with binary
1 parent 1d69a02 commit e46e39d

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

synthtool/transforms.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -224,17 +224,28 @@ def move(
224224

225225

226226
def _replace_in_file(path, expr, replacement):
227-
with path.open("r+") as fh:
228-
content = fh.read()
229-
content, count = expr.subn(replacement, content)
230-
231-
# Don't bother writing the file if we didn't change
232-
# anything.
233-
if count:
234-
fh.seek(0)
235-
fh.write(content)
236-
fh.truncate()
237-
return count
227+
try:
228+
with path.open("r+") as fh:
229+
return _replace_in_file_handle(fh, expr, replacement)
230+
except UnicodeDecodeError:
231+
pass # It's a binary file. Try again with a binary regular expression.
232+
flags = expr.flags & ~re.UNICODE
233+
expr = re.compile(expr.pattern.encode(), flags)
234+
with path.open("rb+") as fh:
235+
return _replace_in_file_handle(fh, expr, replacement.encode())
236+
237+
238+
def _replace_in_file_handle(fh, expr, replacement):
239+
content = fh.read()
240+
content, count = expr.subn(replacement, content)
241+
242+
# Don't bother writing the file if we didn't change
243+
# anything.
244+
if count:
245+
fh.seek(0)
246+
fh.write(content)
247+
fh.truncate()
248+
return count
238249

239250

240251
def replace(

0 commit comments

Comments
 (0)