sbang: use utf-8 for encoding when patching (#13490)

This fixes a UnicodeDecodeError in the sbang patching function.
This commit is contained in:
Gregory Lee 2019-11-01 03:39:45 -07:00 committed by Todd Gamblin
parent eb286bb80f
commit 2a9d6b9fbf
No known key found for this signature in database
GPG key ID: 66B24B9050FDD0B8

View file

@ -6,6 +6,7 @@
import os import os
import stat import stat
import re import re
import sys
import llnl.util.tty as tty import llnl.util.tty as tty
@ -33,8 +34,12 @@ def shebang_too_long(path):
def filter_shebang(path): def filter_shebang(path):
"""Adds a second shebang line, using sbang, at the beginning of a file.""" """Adds a second shebang line, using sbang, at the beginning of a file."""
with open(path, 'r') as original_file: with open(path, 'rb') as original_file:
original = original_file.read() original = original_file.read()
if sys.version_info >= (2, 7):
original = original.decode(encoding='UTF-8')
else:
original = original.decode('UTF-8')
# This line will be prepended to file # This line will be prepended to file
new_sbang_line = '#!/bin/bash %s/bin/sbang\n' % spack.paths.prefix new_sbang_line = '#!/bin/bash %s/bin/sbang\n' % spack.paths.prefix
@ -61,9 +66,13 @@ def filter_shebang(path):
saved_mode = st.st_mode saved_mode = st.st_mode
os.chmod(path, saved_mode | stat.S_IWRITE) os.chmod(path, saved_mode | stat.S_IWRITE)
with open(path, 'w') as new_file: with open(path, 'wb') as new_file:
new_file.write(new_sbang_line) if sys.version_info >= (2, 7):
new_file.write(original) new_file.write(new_sbang_line.encode(encoding='UTF-8'))
new_file.write(original.encode(encoding='UTF-8'))
else:
new_file.write(new_sbang_line.encode('UTF-8'))
new_file.write(original.encode('UTF-8'))
# Restore original permissions. # Restore original permissions.
if saved_mode is not None: if saved_mode is not None: