Skip to content

Commit 4f5a63b

Browse files
authored
Use shlex.join. NFC (#24111)
We bumped the minimum python version to 3.8 in #23417. I guess I overlooked this change at the time.
1 parent de8b02c commit 4f5a63b

13 files changed

+38
-44
lines changed

emcc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,7 @@ def run(args):
526526
args += shlex.split(EMCC_CFLAGS)
527527

528528
if DEBUG:
529-
logger.warning(f'invocation: {shared.shlex_join(args)} (in {os.getcwd()})')
529+
logger.warning(f'invocation: {shlex.join(args)} (in {os.getcwd()})')
530530

531531
# Strip args[0] (program name)
532532
args = args[1:]
@@ -596,7 +596,7 @@ def run(args):
596596
exit_with_error(f'unable to parse output of `{cmd}`:\n{proc.stderr}')
597597
parts = shlex.split(lines[0].replace('\\', '\\\\'))
598598
parts = [x for x in parts if x not in ['-c', '-o', '-v', '-emit-llvm'] and input_file not in x and temp_target not in x]
599-
print(shared.shlex_join(parts[1:]))
599+
print(shlex.join(parts[1:]))
600600
return 0
601601

602602
if '-dumpmachine' in args or '-print-target-triple' in args or '--print-target-triple' in args:

emcmake.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
# found in the LICENSE file.
66

77
import os
8+
import shlex
89
import shutil
910
import sys
1011
from tools import shared
@@ -56,7 +57,7 @@ def has_substr(args, substr):
5657
print('emcmake: no compatible cmake generator found; Please install ninja or mingw32-make, or specify a generator explicitly using -G', file=sys.stderr)
5758
return 1
5859

59-
print('configure: ' + shared.shlex_join(args), file=sys.stderr)
60+
print(f'configure: {shlex.join(args)}', file=sys.stderr)
6061
try:
6162
shared.check_call(args)
6263
return 0

emconfigure.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
tests will work properly.
1717
"""
1818

19+
import shlex
1920
import sys
2021
from tools import building
2122
from tools import shared
@@ -47,7 +48,7 @@ def run():
4748
# compilation with emcc, but instead do builds natively with Clang. This
4849
# is a heuristic emulation that may or may not work.
4950
env['EMMAKEN_JUST_CONFIGURE'] = '1'
50-
print('configure: ' + shared.shlex_join(args), file=sys.stderr)
51+
print(f'configure: {shlex.join(args)}', file=sys.stderr)
5152
try:
5253
shared.check_call(args, env=env)
5354
return 0

test/common.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
EMCMAKE = shared.bat_suffix(path_from_root('emcmake'))
8989
EMCONFIGURE = shared.bat_suffix(path_from_root('emconfigure'))
9090
EMRUN = shared.bat_suffix(shared.path_from_root('emrun'))
91-
WASM_DIS = Path(building.get_binaryen_bin(), 'wasm-dis')
91+
WASM_DIS = os.path.join(building.get_binaryen_bin(), 'wasm-dis')
9292
LLVM_OBJDUMP = os.path.expanduser(shared.build_llvm_tool_path(shared.exe_suffix('llvm-objdump')))
9393
PYTHON = sys.executable
9494
if not config.NODE_JS_TEST:
@@ -1406,7 +1406,7 @@ def build(self, filename, libraries=None, includes=None, force_c=False, emcc_arg
14061406
output = output_basename + output_suffix
14071407
else:
14081408
output = shared.unsuffixed_basename(filename) + output_suffix
1409-
cmd = compiler + [filename, '-o', output] + all_emcc_args
1409+
cmd = compiler + [str(filename), '-o', output] + all_emcc_args
14101410
if libraries:
14111411
cmd += libraries
14121412
if includes:
@@ -1755,7 +1755,7 @@ def run_process(self, cmd, check=True, **args):
17551755
if check and e.returncode != 0:
17561756
print(e.stdout)
17571757
print(e.stderr)
1758-
self.fail(f'subprocess exited with non-zero return code({e.returncode}): `{shared.shlex_join(cmd)}`')
1758+
self.fail(f'subprocess exited with non-zero return code({e.returncode}): `{shlex.join(cmd)}`')
17591759

17601760
def emcc(self, filename, args=[], output_filename=None, **kwargs): # noqa
17611761
compile_only = '-c' in args or '-sSIDE_MODULE' in args

test/jsrun.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import common
77
import logging
88
import os
9+
import shlex
910
import subprocess
1011
import sys
1112
from subprocess import PIPE, CalledProcessError
@@ -97,7 +98,7 @@ def run_js(filename, engine, args=None,
9798

9899
command = make_command(os.path.abspath(filename), engine, args)
99100
if common.EMTEST_VERBOSE:
100-
print(f"Running: '{shared.shlex_join(command)}'")
101+
print(f"Running: '{shlex.join(command)}'")
101102
try:
102103
proc = subprocess.run(
103104
command,

test/test_browser.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1399,7 +1399,7 @@ def test_fs_workerfs_package(self):
13991399
create_file('file1.txt', 'first')
14001400
ensure_dir('sub')
14011401
create_file('sub/file2.txt', 'second')
1402-
self.run_process([FILE_PACKAGER, 'files.data', '--preload', 'file1.txt', Path('sub/file2.txt'), '--separate-metadata', '--js-output=files.js'])
1402+
self.run_process([FILE_PACKAGER, 'files.data', '--preload', 'file1.txt', 'sub/file2.txt', '--separate-metadata', '--js-output=files.js'])
14031403
self.btest(Path('fs/test_workerfs_package.cpp'), '1', emcc_args=['-lworkerfs.js', '--proxy-to-worker', '-lworkerfs.js'])
14041404

14051405
def test_fs_lz4fs_package(self):
@@ -1415,7 +1415,7 @@ def test_fs_lz4fs_package(self):
14151415
print('emcc-normal')
14161416
self.set_setting('DEFAULT_LIBRARY_FUNCS_TO_INCLUDE', '$ccall')
14171417
self.btest_exit(Path('fs/test_lz4fs.cpp'), 2, emcc_args=['-sLZ4', '--preload-file', 'file1.txt', '--preload-file', 'subdir/file2.txt', '--preload-file', 'file3.txt'])
1418-
assert os.path.getsize('file1.txt') + os.path.getsize(Path('subdir/file2.txt')) + os.path.getsize('file3.txt') == 3 * 1024 * 128 * 10 + 1
1418+
assert os.path.getsize('file1.txt') + os.path.getsize('subdir/file2.txt') + os.path.getsize('file3.txt') == 3 * 1024 * 128 * 10 + 1
14191419
assert os.path.getsize('test.data') < (3 * 1024 * 128 * 10) / 2 # over half is gone
14201420
print(' emcc-opts')
14211421
self.btest_exit(Path('fs/test_lz4fs.cpp'), 2, emcc_args=['-sLZ4', '--preload-file', 'file1.txt', '--preload-file', 'subdir/file2.txt', '--preload-file', 'file3.txt', '-O2'])
@@ -5696,7 +5696,7 @@ def test_emrun(self):
56965696
['--dump_out_directory=foo_bar', '--port', '6942'],
56975697
]:
56985698
args = args_base + args + [self.in_dir('test_emrun.html'), '--', '1', '2', '--3', 'escaped space', 'with_underscore']
5699-
print(shared.shlex_join(args))
5699+
print(shlex.join(args))
57005700
proc = self.run_process(args, check=False)
57015701
self.assertEqual(proc.returncode, 100)
57025702
dump_dir = 'dump_out'

test/test_core.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7841,7 +7841,7 @@ def get_dwarf_addr(line, col):
78417841
self.assertLess(get_dwarf_addr(7, 3), get_dwarf_addr(8, 3))
78427842

78437843
# Get the wat, printing with -g which has binary offsets
7844-
wat = self.run_process([Path(building.get_binaryen_bin(), 'wasm-opt'),
7844+
wat = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'),
78457845
wasm_filename, '-g', '--print', '-all'], stdout=PIPE).stdout
78467846

78477847
# We expect to see a pattern like this in optimized builds (there isn't
@@ -8352,7 +8352,7 @@ def break_wasm(name):
83528352
return False
83538353
create_file('wat.wat', wat)
83548354
shutil.move(name, name + '.orig')
8355-
self.run_process([Path(building.get_binaryen_bin(), 'wasm-as'), 'wat.wat', '-o', name, '-g', '--all-features'])
8355+
self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-as'), 'wat.wat', '-o', name, '-g', '--all-features'])
83568356
return True
83578357

83588358
def verify_working(args):

test/test_other.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11814,7 +11814,7 @@ def print_percent(actual, expected):
1181411814
raise
1181511815

1181611816
args = [compiler_for(sources[0]), '-o', 'a.html'] + args + sources
11817-
print(shared.shlex_join(args))
11817+
print(shlex.join(args))
1181811818
self.run_process(args)
1181911819

1182011820
# For certain tests, don't just check the output size but check

test/test_sanity.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -743,18 +743,24 @@ def test_embuilder_with_use_port_syntax(self):
743743
self.assertExists(os.path.join(config.CACHE, 'sysroot', 'lib', 'wasm32-emscripten', 'libSDL2_image-jpg-png.a'))
744744
self.assertContained('error building port `sdl2_image:formats=invalid` | invalid is not a supported format', self.do([EMBUILDER, 'build', 'sdl2_image:formats=invalid', '--force']))
745745

746-
def test_embuilder_external_ports(self):
746+
def test_embuilder_external_ports_simple(self):
747747
restore_and_set_up()
748748
simple_port_path = test_file("other/ports/simple.py")
749749
# embuilder handles external port target that ends with .py
750750
self.run_process([EMBUILDER, 'build', f'{simple_port_path}', '--force'])
751751
self.assertExists(os.path.join(config.CACHE, 'sysroot', 'lib', 'wasm32-emscripten', 'lib_simple.a'))
752+
753+
def test_embuilder_external_ports(self):
752754
# embuilder handles external port target that contains port options
755+
restore_and_set_up()
753756
external_port_path = test_file("other/ports/external.py")
754757
self.run_process([EMBUILDER, 'build', f'{external_port_path}:value1=12:value2=36', '--force'])
755758
self.assertExists(os.path.join(config.CACHE, 'sysroot', 'lib', 'wasm32-emscripten', 'lib_external.a'))
759+
760+
def test_embuilder_external_ports_options(self):
756761
# embuilder handles external port target that contains port options (influences library name,
757762
# like sdl2_image:formats=png)
763+
restore_and_set_up()
758764
external_port_path = test_file("other/ports/external.py")
759765
self.run_process([EMBUILDER, 'build', f'{external_port_path}:dependency=sdl2', '--force'])
760766
self.assertExists(os.path.join(config.CACHE, 'sysroot', 'lib', 'wasm32-emscripten', 'lib_external-sdl2.a'))

tools/building.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ def get_command_with_possible_response_file(cmd):
314314
# subprocess can still run into the Command Line Too Long error.
315315
# Reduce the limit by ~1K for now to be on the safe side, but we might need to
316316
# adjust this in the future if it turns out not to be enough.
317-
if (len(shared.shlex_join(cmd)) <= 7000 and force_response_files != '1') or force_response_files == '0':
317+
if (len(shlex.join(cmd)) <= 7000 and force_response_files != '1') or force_response_files == '0':
318318
return cmd
319319

320320
logger.debug('using response file for %s' % cmd[0])
@@ -473,12 +473,12 @@ def check_closure_compiler(cmd, args, env, allowed_to_fail):
473473
if isinstance(e, subprocess.CalledProcessError):
474474
sys.stderr.write(e.stdout)
475475
sys.stderr.write(str(e) + '\n')
476-
exit_with_error('closure compiler (%s) did not execute properly!' % shared.shlex_join(cmd))
476+
exit_with_error('closure compiler (%s) did not execute properly!' % shlex.join(cmd))
477477

478478
if 'Version:' not in output:
479479
if allowed_to_fail:
480480
return False
481-
exit_with_error('unrecognized closure compiler --version output (%s):\n%s' % (shared.shlex_join(cmd), output))
481+
exit_with_error('unrecognized closure compiler --version output (%s):\n%s' % (shlex.join(cmd), output))
482482

483483
return True
484484

@@ -685,7 +685,7 @@ def move_to_safe_7bit_ascii_filename(filename):
685685
logger.error(proc.stderr) # print list of errors (possibly long wall of text if input was minified)
686686

687687
# Exit and print final hint to get clearer output
688-
msg = f'closure compiler failed (rc: {proc.returncode}): {shared.shlex_join(cmd)}'
688+
msg = f'closure compiler failed (rc: {proc.returncode}): {shlex.join(cmd)}'
689689
if settings.MINIFY_WHITESPACE:
690690
msg += ' the error message may be clearer with -g1 and EMCC_DEBUG=2 set'
691691
exit_with_error(msg)

tools/gen_struct_info.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
import json
6262
import argparse
6363
import tempfile
64+
import shlex
6465
import subprocess
6566

6667
__scriptdir__ = os.path.dirname(os.path.abspath(__file__))
@@ -268,7 +269,7 @@ def generate_cmd(js_file_path, src_file_path, cflags):
268269
# TODO(sbc): Remove this one we remove the test_em_config_env_var test
269270
cmd += ['-Wno-deprecated']
270271

271-
show(shared.shlex_join(cmd))
272+
show(shlex.join(cmd))
272273
return cmd
273274

274275

tools/link.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -469,9 +469,9 @@ def make_js_executable(script):
469469
# Using -S (--split-string) here means that arguments to the executable are
470470
# correctly parsed. We don't do this by default because old versions of env
471471
# don't support -S.
472-
cmd = '/usr/bin/env -S ' + shared.shlex_join(cmd)
472+
cmd = '/usr/bin/env -S ' + shlex.join(cmd)
473473
else:
474-
cmd = shared.shlex_join(cmd)
474+
cmd = shlex.join(cmd)
475475
logger.debug('adding `#!` to JavaScript file: %s' % cmd)
476476
# add shebang
477477
with open(script, 'w') as f:

tools/shared.py

+6-22
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import os
1313
import re
1414
import shutil
15+
import shlex
1516
import subprocess
1617
import signal
1718
import stat
@@ -95,23 +96,6 @@
9596
diagnostics.add_warning('closure', enabled=False)
9697

9798

98-
# TODO(sbc): Investigate switching to shlex.quote
99-
def shlex_quote(arg):
100-
arg = os.fspath(arg)
101-
if ' ' in arg and (not (arg.startswith('"') and arg.endswith('"'))) and (not (arg.startswith("'") and arg.endswith("'"))):
102-
return '"' + arg.replace('"', '\\"') + '"'
103-
104-
return arg
105-
106-
107-
# Switch to shlex.join once we can depend on python 3.8:
108-
# https://docs.python.org/3/library/shlex.html#shlex.join
109-
def shlex_join(cmd):
110-
if type(cmd) is str:
111-
return cmd
112-
return ' '.join(shlex_quote(x) for x in cmd)
113-
114-
11599
def run_process(cmd, check=True, input=None, *args, **kw):
116100
"""Runs a subprocess returning the exit code.
117101
@@ -127,7 +111,7 @@ def run_process(cmd, check=True, input=None, *args, **kw):
127111
kw.setdefault('text', True)
128112
kw.setdefault('encoding', 'utf-8')
129113
ret = subprocess.run(cmd, check=check, input=input, *args, **kw)
130-
debug_text = '%sexecuted %s' % ('successfully ' if check else '', shlex_join(cmd))
114+
debug_text = '%sexecuted %s' % ('successfully ' if check else '', shlex.join(cmd))
131115
logger.debug(debug_text)
132116
return ret
133117

@@ -218,7 +202,7 @@ def get_finished_process():
218202
idx = get_finished_process()
219203
finished_process = processes.pop(idx)
220204
if finished_process.returncode != 0:
221-
exit_with_error('subprocess %d/%d failed (%s)! (cmdline: %s)' % (idx + 1, len(commands), returncode_to_str(finished_process.returncode), shlex_join(commands[idx])))
205+
exit_with_error('subprocess %d/%d failed (%s)! (cmdline: %s)' % (idx + 1, len(commands), returncode_to_str(finished_process.returncode), shlex.join(commands[idx])))
222206
num_completed += 1
223207

224208
if route_stdout_to_temp_files_suffix:
@@ -235,9 +219,9 @@ def check_call(cmd, *args, **kw):
235219
try:
236220
return run_process(cmd, *args, **kw)
237221
except subprocess.CalledProcessError as e:
238-
exit_with_error("'%s' failed (%s)", shlex_join(cmd), returncode_to_str(e.returncode))
222+
exit_with_error("'%s' failed (%s)", shlex.join(cmd), returncode_to_str(e.returncode))
239223
except OSError as e:
240-
exit_with_error("'%s' failed: %s", shlex_join(cmd), str(e))
224+
exit_with_error("'%s' failed: %s", shlex.join(cmd), str(e))
241225

242226

243227
def exec_process(cmd):
@@ -638,7 +622,7 @@ def maybe_quote(arg):
638622
print(' ' + ' '.join([maybe_quote(a) for a in cmd]), file=sys.stderr)
639623
sys.stderr.flush()
640624
elif PRINT_SUBPROCS:
641-
print(' %s %s' % (maybe_quote(cmd[0]), shlex_join(cmd[1:])), file=sys.stderr)
625+
print(' %s %s' % (maybe_quote(cmd[0]), shlex.join(cmd[1:])), file=sys.stderr)
642626
sys.stderr.flush()
643627

644628

0 commit comments

Comments
 (0)