Skip to content

Commit 435b877

Browse files
committed
shlex: Support parsing byte streams
for posix=False or whitespace_split=True
1 parent 5b6dd1e commit 435b877

2 files changed

Lines changed: 102 additions & 52 deletions

File tree

‎Lib/shlex.py‎

Lines changed: 83 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# changes to tokenize more like Posix shells by Vinay Sajip, July 2016.
99

1010
import sys
11-
from io import StringIO
11+
from io import StringIO, BytesIO
1212

1313
__all__ = ["shlex", "split", "quote", "join"]
1414

@@ -20,48 +20,63 @@ def __init__(self, instream=None, infile=None, posix=False,
2020

2121
if isinstance(instream, str):
2222
instream = StringIO(instream)
23+
if isinstance(instream, bytes):
24+
instream = BytesIO(instream)
2325
if instream is not None:
2426
self.instream = instream
2527
self.infile = infile
2628
else:
2729
self.instream = sys.stdin
2830
self.infile = None
31+
self.binary = isinstance(self.instream.read(0), bytes)
32+
self.empty = b'' if self.binary else ''
2933
self.posix = posix
3034
if posix:
3135
self.eof = None
3236
else:
33-
self.eof = ''
34-
self.commenters = '#'
35-
self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
37+
self.eof = self.empty
38+
self.commenters = b'#' if self.binary else '#'
39+
self.wordchars = (b'abcdfeghijklmnopqrstuvwxyz'
40+
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
41+
if self.binary else
42+
'abcdfeghijklmnopqrstuvwxyz'
3643
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
3744
if self.posix:
3845
self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
3946
'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
40-
self.whitespace = ' \t\r\n'
47+
self.whitespace = b' \t\r\n' if self.binary else ' \t\r\n'
4148
self.whitespace_split = False
42-
self.quotes = '\'"'
43-
self.escape = '\\'
44-
self.escapedquotes = '"'
45-
self.state = ' '
49+
self.quotes = b'\'"' if self.binary else '\'"'
50+
self.escape = b'\\' if self.binary else '\\'
51+
self.escapedquotes = b'"' if self.binary else '"'
52+
self.includequote = self.escapedquotes
53+
self.space = b' ' if self.binary else ' '
54+
self.A = b'a' if self.binary else 'a'
55+
self.C = b'c' if self.binary else 'c'
56+
self.state = self.space
4657
self.pushback = deque()
4758
self.lineno = 1
4859
self.debug = 0
49-
self.token = ''
60+
self.token = self.empty
61+
self.newline = b'\n' if self.binary else '\n'
5062
self.filestack = deque()
5163
self.source = None
5264
if not punctuation_chars:
53-
punctuation_chars = ''
65+
punctuation_chars = self.empty
5466
elif punctuation_chars is True:
55-
punctuation_chars = '();<>|&'
67+
punctuation_chars = b'();<>|&' if self.binary else '();<>|&'
5668
self._punctuation_chars = punctuation_chars
5769
if punctuation_chars:
5870
# _pushback_chars is a push back queue used by lookahead logic
5971
self._pushback_chars = deque()
6072
# these chars added because allowed in file names, args, wildcards
61-
self.wordchars += '~-./*?='
73+
self.wordchars += b'~-./*?=' if self.binary else '~-./*?='
6274
#remove any punctuation chars from wordchars
63-
t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars))
64-
self.wordchars = self.wordchars.translate(t)
75+
if self.binary:
76+
self.wordchars = self.wordchars.translate(None, delete = punctuation_chars)
77+
else:
78+
t = self.wordchars.maketrans(dict.fromkeys(punctuation_chars))
79+
self.wordchars = self.wordchars.translate(t)
6580

6681
@property
6782
def punctuation_chars(self):
@@ -77,6 +92,11 @@ def push_source(self, newstream, newfile=None):
7792
"Push an input source onto the lexer's input source stack."
7893
if isinstance(newstream, str):
7994
newstream = StringIO(newstream)
95+
if isinstance(newstream, bytes):
96+
newstream = BytesIO(newstream)
97+
binary = isinstance(newstream.read(0), bytes)
98+
if binary != self.binary:
99+
raise TypeError("Cannot append %s to %s" % (type(self.instream).__name__, type(newstream).__name__))
80100
self.filestack.appendleft((self.infile, self.instream, self.lineno))
81101
self.infile = newfile
82102
self.instream = newstream
@@ -94,7 +114,7 @@ def pop_source(self):
94114
if self.debug:
95115
print('shlex: popping to %s, line %d' \
96116
% (self.instream, self.lineno))
97-
self.state = ' '
117+
self.state = self.space
98118

99119
def get_token(self):
100120
"Get a token from the input stream (or from stack if it's nonempty)"
@@ -129,24 +149,26 @@ def get_token(self):
129149
return raw
130150

131151
def read_token(self):
152+
if self.posix and self.binary and not self.whitespace_split:
153+
raise ValueError('POSIX word characters not supported with byte streams')
132154
quoted = False
133-
escapedstate = ' '
155+
escapedstate = self.space
134156
while True:
135157
if self.punctuation_chars and self._pushback_chars:
136158
nextchar = self._pushback_chars.pop()
137159
else:
138160
nextchar = self.instream.read(1)
139-
if nextchar == '\n':
161+
if nextchar == self.newline:
140162
self.lineno += 1
141163
if self.debug >= 3:
142164
print("shlex: in state %r I see character: %r" % (self.state,
143165
nextchar))
144166
if self.state is None:
145-
self.token = '' # past end of file
167+
self.token = self.empty # past end of file
146168
break
147-
elif self.state == ' ':
169+
elif self.state == self.space:
148170
if not nextchar:
149-
self.state = None # end of file
171+
self.state = None # end of file
150172
break
151173
elif nextchar in self.whitespace:
152174
if self.debug >= 2:
@@ -159,21 +181,21 @@ def read_token(self):
159181
self.instream.readline()
160182
self.lineno += 1
161183
elif self.posix and nextchar in self.escape:
162-
escapedstate = 'a'
184+
escapedstate = self.A
163185
self.state = nextchar
164186
elif nextchar in self.wordchars:
165187
self.token = nextchar
166-
self.state = 'a'
188+
self.state = self.A
167189
elif nextchar in self.punctuation_chars:
168190
self.token = nextchar
169-
self.state = 'c'
191+
self.state = self.C
170192
elif nextchar in self.quotes:
171193
if not self.posix:
172194
self.token = nextchar
173195
self.state = nextchar
174196
elif self.whitespace_split:
175197
self.token = nextchar
176-
self.state = 'a'
198+
self.state = self.A
177199
else:
178200
self.token = nextchar
179201
if self.token or (self.posix and quoted):
@@ -190,10 +212,10 @@ def read_token(self):
190212
if nextchar == self.state:
191213
if not self.posix:
192214
self.token += nextchar
193-
self.state = ' '
215+
self.state = self.space
194216
break
195217
else:
196-
self.state = 'a'
218+
self.state = self.A
197219
elif (self.posix and nextchar in self.escape and self.state
198220
in self.escapedquotes):
199221
escapedstate = self.state
@@ -213,14 +235,14 @@ def read_token(self):
213235
self.token += self.state
214236
self.token += nextchar
215237
self.state = escapedstate
216-
elif self.state in ('a', 'c'):
238+
elif self.state in (self.A, self.C):
217239
if not nextchar:
218240
self.state = None # end of file
219241
break
220242
elif nextchar in self.whitespace:
221243
if self.debug >= 2:
222244
print("shlex: I see whitespace in word state")
223-
self.state = ' '
245+
self.state = self.space
224246
if self.token or (self.posix and quoted):
225247
break # emit current token
226248
else:
@@ -229,23 +251,23 @@ def read_token(self):
229251
self.instream.readline()
230252
self.lineno += 1
231253
if self.posix:
232-
self.state = ' '
254+
self.state = self.space
233255
if self.token or (self.posix and quoted):
234256
break # emit current token
235257
else:
236258
continue
237-
elif self.state == 'c':
259+
elif self.state == self.C:
238260
if nextchar in self.punctuation_chars:
239261
self.token += nextchar
240262
else:
241263
if nextchar not in self.whitespace:
242264
self._pushback_chars.append(nextchar)
243-
self.state = ' '
265+
self.state = self.space
244266
break
245267
elif self.posix and nextchar in self.quotes:
246268
self.state = nextchar
247269
elif self.posix and nextchar in self.escape:
248-
escapedstate = 'a'
270+
escapedstate = self.A
249271
self.state = nextchar
250272
elif (nextchar in self.wordchars or nextchar in self.quotes
251273
or (self.whitespace_split and
@@ -258,14 +280,14 @@ def read_token(self):
258280
self.pushback.appendleft(nextchar)
259281
if self.debug >= 2:
260282
print("shlex: I see punctuation in word state")
261-
self.state = ' '
283+
self.state = self.space
262284
if self.token or (self.posix and quoted):
263285
break # emit current token
264286
else:
265287
continue
266288
result = self.token
267-
self.token = ''
268-
if self.posix and not quoted and result == '':
289+
self.token = self.empty
290+
if self.posix and not quoted and result == self.empty:
269291
result = None
270292
if self.debug > 1:
271293
if result:
@@ -277,20 +299,26 @@ def read_token(self):
277299
def sourcehook(self, newfile):
278300
"Hook called on a filename to be sourced."
279301
import os.path
280-
if newfile[0] == '"':
302+
if newfile[0] == self.includequote:
281303
newfile = newfile[1:-1]
304+
infile = self.infile
282305
# This implements cpp-like semantics for relative-path inclusion.
283-
if isinstance(self.infile, str) and not os.path.isabs(newfile):
284-
newfile = os.path.join(os.path.dirname(self.infile), newfile)
285-
return (newfile, open(newfile, "r"))
306+
if (isinstance(infile, str) or isinstance(infile, bytes)) and not os.path.isabs(newfile):
307+
if isinstance(infile, bytes) != isinstance(newfile, bytes):
308+
if not isinstance(infile, bytes):
309+
infile = infile.encode()
310+
else:
311+
newfile = newfile.encode()
312+
newfile = os.path.join(os.path.dirname(infile), newfile)
313+
return (newfile, open(newfile, 'rb' if self.binary else 'r'))
286314

287315
def error_leader(self, infile=None, lineno=None):
288316
"Emit a C-compiler-like, Emacs-friendly error-message leader."
289317
if infile is None:
290318
infile = self.infile
291319
if lineno is None:
292320
lineno = self.lineno
293-
return "\"%s\", line %d: " % (infile, lineno)
321+
return "%r, line %d: " % (infile, lineno)
294322

295323
def __iter__(self):
296324
return self
@@ -302,19 +330,21 @@ def __next__(self):
302330
return token
303331

304332
def split(s, comments=False, posix=True):
305-
"""Split the string *s* using shell-like syntax."""
333+
"""Split the string or byte array *s* using shell-like syntax."""
306334
if s is None:
307335
raise ValueError("s argument must not be None")
308336
lex = shlex(s, posix=posix)
309337
lex.whitespace_split = True
310338
if not comments:
311-
lex.commenters = ''
339+
lex.commenters = lex.empty
312340
return list(lex)
313341

314342

315343
def join(split_command):
316344
"""Return a shell-escaped string from *split_command*."""
317-
return ' '.join(quote(arg) for arg in split_command)
345+
split_command = list(split_command)
346+
space = b' ' if split_command and isinstance(split_command[0], bytes) else ' '
347+
return space.join(quote(arg) for arg in split_command)
318348

319349

320350
def quote(s, *, force=False):
@@ -323,11 +353,12 @@ def quote(s, *, force=False):
323353
If *force* is *True*, then *s* is unconditionally quoted,
324354
even if it is already safe for a shell without being quoted.
325355
"""
356+
is_bytes = isinstance(s, bytes)
326357
if not s:
327-
return "''"
358+
return b"''" if is_bytes else "''"
328359

329-
if not isinstance(s, str):
330-
raise TypeError(f"expected string object, got {type(s).__name__!r}")
360+
if not isinstance(s, str) and not isinstance(s, bytes):
361+
raise TypeError(f"expected string or byte array object, got {type(s).__name__!r}")
331362

332363
# Use bytes.translate() for performance
333364
safe_chars = (b'%+,-./0123456789:=@'
@@ -336,12 +367,15 @@ def quote(s, *, force=False):
336367
# No quoting is needed if we are not forcing quoting
337368
# and `s` is an ASCII string consisting only of `safe_chars`.
338369
if (not force
339-
and s.isascii() and not s.encode().translate(None, delete=safe_chars)):
370+
and s.isascii() and
371+
not (s if is_bytes else s.encode()).translate(None, delete=safe_chars)):
340372
return s
341373

342374
# use single quotes, and put single quotes into double quotes
343375
# the string $'b is then quoted as '$'"'"'b'
344-
return "'" + s.replace("'", "'\"'\"'") + "'"
376+
quote = b"'" if is_bytes else "'"
377+
replace = b"'\"'\"'" if is_bytes else "'\"'\"'"
378+
return quote + s.replace(quote, replace) + quote
345379

346380

347381
def _print_tokens(lexer):

‎Lib/test/test_shlex.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,18 @@ def testPunctuationWithWhitespaceSplit(self):
294294
# white space
295295
self.assertEqual(list(s), ['a', '&&', 'b', '||', 'c'])
296296

297+
def testPunctuationWithWhitespaceSplitBytes(self):
298+
"""Test that with whitespace_split, behaviour is as expected with bytes"""
299+
s = shlex.shlex(b'a && b || c', punctuation_chars=b'&')
300+
# whitespace_split is False, so splitting will be based on
301+
# punctuation_chars
302+
self.assertEqual(list(s), [b'a', b'&&', b'b', b'|', b'|', b'c'])
303+
s = shlex.shlex(b'a && b || c', punctuation_chars=b'&')
304+
s.whitespace_split = True
305+
# whitespace_split is True, so splitting will be based on
306+
# white space
307+
self.assertEqual(list(s), [b'a', b'&&', b'b', b'||', b'c'])
308+
297309
def testPunctuationWithPosix(self):
298310
"""Test that punctuation_chars and posix behave correctly together."""
299311
# see Issue #29132
@@ -333,17 +345,21 @@ def testQuote(self):
333345
unsafe = '"`$\\!' + unicode_sample
334346

335347
self.assertEqual(shlex.quote(''), "''")
348+
self.assertEqual(shlex.quote(b''), b"''")
336349
self.assertEqual(shlex.quote(None), "''")
337350
self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
351+
self.assertEqual(shlex.quote(safeunquoted.encode()), safeunquoted.encode())
338352
self.assertEqual(shlex.quote('test file name'), "'test file name'")
353+
self.assertEqual(shlex.quote(b'test file name'), b"'test file name'")
339354
for u in unsafe:
340355
self.assertEqual(shlex.quote('test%sname' % u),
341356
"'test%sname'" % u)
357+
self.assertEqual(shlex.quote(b'test%sname' % u.encode()),
358+
b"'test%sname'" % u.encode())
342359
for u in unsafe:
343360
self.assertEqual(shlex.quote("test%s'name'" % u),
344361
"'test%s'\"'\"'name'\"'\"''" % u)
345362
self.assertRaises(TypeError, shlex.quote, 42)
346-
self.assertRaises(TypeError, shlex.quote, b"abc")
347363

348364
def testForceQuote(self):
349365
self.assertEqual(shlex.quote("spam"), "spam")
@@ -457,14 +473,14 @@ def testErrorLeaderTracksPosition(self):
457473
s = shlex.shlex("line 1\nline 2", infile=infile_label)
458474
list(s)
459475
result = s.error_leader()
460-
self.assertEqual(result, f'"{infile_label}", line 2: ')
476+
self.assertEqual(result, f"'{infile_label}', line 2: ")
461477

462478
def testErrorLeaderOverrides(self):
463479
s = shlex.shlex("foo", infile="original.sh")
464480
infile_label_override = "override.sh"
465481
lineno_override = 42
466482
result = s.error_leader(infile=infile_label_override, lineno=lineno_override)
467-
self.assertEqual(result, f'"{infile_label_override}", line {lineno_override}: ')
483+
self.assertEqual(result, f"'{infile_label_override}', line {lineno_override}: ")
468484

469485
def testNoClosingQuotation(self):
470486
s = shlex.shlex('"foo')

0 commit comments

Comments
 (0)