qutebrowser/qutebrowser/misc/split.py

212 lines
6.5 KiB
Python
Raw Normal View History

2014-11-03 21:27:07 +01:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2016-01-04 07:12:39 +01:00
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
2014-11-03 21:27:07 +01:00
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Our own fork of shlex.split with some added and removed features."""
import re
2014-11-04 20:06:58 +01:00
from qutebrowser.utils import log
2014-11-03 21:27:07 +01:00
class ShellLexer:
2014-11-03 21:43:34 +01:00
"""A lexical analyzer class for simple shell-like syntaxes.
Based on Python's shlex, but cleaned up, removed some features, and added
some features useful for qutebrowser.
Attributes:
FIXME
"""
def __init__(self, s):
2014-11-06 09:02:21 +01:00
self.string = s
2014-11-05 21:44:52 +01:00
self.whitespace = ' \t\r'
2014-11-03 21:27:07 +01:00
self.quotes = '\'"'
self.escape = '\\'
self.escapedquotes = '"'
2014-11-05 07:41:17 +01:00
self.keep = False
2014-11-09 22:15:44 +01:00
self.quoted = None
self.escapedstate = None
self.token = None
self.state = None
self.reset()
2014-11-03 21:27:07 +01:00
2014-11-06 06:44:23 +01:00
def reset(self):
2015-03-31 20:49:29 +02:00
"""Reset the state machine state to the defaults."""
2014-11-06 06:44:23 +01:00
self.quoted = False
self.escapedstate = ' '
self.token = ''
self.state = ' '
def __iter__(self): # pragma: no mccabe
2014-11-03 21:43:34 +01:00
"""Read a raw token from the input stream."""
2014-11-09 22:15:44 +01:00
# pylint: disable=too-many-branches,too-many-statements
2014-11-06 07:13:58 +01:00
self.reset()
2014-11-06 09:02:21 +01:00
for nextchar in self.string:
2014-11-06 07:13:58 +01:00
if self.state == ' ':
if self.keep:
self.token += nextchar
2014-11-06 06:44:23 +01:00
if nextchar in self.whitespace:
if self.token or self.quoted:
yield self.token
self.reset()
2014-11-03 21:35:47 +01:00
elif nextchar in self.escape:
2014-11-06 06:44:23 +01:00
self.escapedstate = 'a'
self.state = nextchar
2014-11-03 21:27:07 +01:00
elif nextchar in self.quotes:
2014-11-06 06:44:23 +01:00
self.state = nextchar
2014-11-03 21:27:07 +01:00
else:
2014-11-06 06:44:23 +01:00
self.token = nextchar
self.state = 'a'
elif self.state in self.quotes:
self.quoted = True
if nextchar == self.state:
2014-11-05 07:41:17 +01:00
if self.keep:
2014-11-06 06:44:23 +01:00
self.token += nextchar
self.state = 'a'
2014-11-03 21:35:47 +01:00
elif (nextchar in self.escape and
2016-04-27 18:30:54 +02:00
self.state in self.escapedquotes):
2014-11-05 07:41:17 +01:00
if self.keep:
2014-11-06 06:44:23 +01:00
self.token += nextchar
self.escapedstate = self.state
self.state = nextchar
2014-11-03 21:27:07 +01:00
else:
2014-11-06 06:44:23 +01:00
self.token += nextchar
elif self.state in self.escape:
2014-11-03 21:27:07 +01:00
# In posix shells, only the quote itself or the escape
# character may be escaped within quotes.
2014-11-06 06:44:23 +01:00
if (self.escapedstate in self.quotes and
nextchar != self.state and
nextchar != self.escapedstate and not self.keep):
self.token += self.state
self.token += nextchar
self.state = self.escapedstate
elif self.state == 'a':
if nextchar in self.whitespace:
self.state = ' '
2015-08-02 13:05:19 +02:00
assert self.token or self.quoted
yield self.token
self.reset()
if self.keep:
yield nextchar
2014-11-03 21:35:47 +01:00
elif nextchar in self.quotes:
2014-11-05 07:41:17 +01:00
if self.keep:
2014-11-06 06:44:23 +01:00
self.token += nextchar
self.state = nextchar
2014-11-03 21:35:47 +01:00
elif nextchar in self.escape:
2014-11-05 07:41:17 +01:00
if self.keep:
2014-11-06 06:44:23 +01:00
self.token += nextchar
self.escapedstate = 'a'
self.state = nextchar
2014-11-03 21:27:07 +01:00
else:
2014-11-06 06:44:23 +01:00
self.token += nextchar
else:
raise AssertionError("Invalid state {!r}!".format(self.state))
2014-11-06 09:02:21 +01:00
if self.state in self.escape and not self.keep:
self.token += self.state
if self.token or self.quoted:
yield self.token
2014-11-03 21:27:07 +01:00
2014-11-05 07:41:17 +01:00
def split(s, keep=False):
"""Split a string via ShellLexer.
Args:
2015-04-09 23:47:25 +02:00
keep: Whether to keep special chars in the split output.
2014-11-05 07:41:17 +01:00
"""
lexer = ShellLexer(s)
2014-11-05 07:41:17 +01:00
lexer.keep = keep
2014-11-05 21:42:27 +01:00
tokens = list(lexer)
2014-11-06 06:44:23 +01:00
if not tokens:
return []
2014-11-05 21:42:27 +01:00
out = []
spaces = ""
log.shlexer.vdebug("{!r} -> {!r}".format(s, tokens))
2014-11-05 21:42:27 +01:00
for t in tokens:
if t.isspace():
spaces += t
2014-11-05 21:42:27 +01:00
else:
out.append(spaces + t)
spaces = ""
2014-11-06 08:25:46 +01:00
if spaces:
out.append(spaces)
2014-11-05 21:42:27 +01:00
return out
2014-11-10 23:02:34 +01:00
def _combine_ws(parts, whitespace):
"""Combine whitespace in a list with the element following it.
Args:
parts: A list of strings.
whitespace: A string containing what's considered whitespace.
Return:
The modified list.
"""
out = []
ws = ''
for part in parts:
if not part:
continue
elif part in whitespace:
ws += part
else:
out.append(ws + part)
ws = ''
if ws:
out.append(ws)
return out
def simple_split(s, keep=False, maxsplit=None):
"""Split a string on whitespace, optionally keeping the whitespace.
Args:
s: The string to split.
keep: Whether to keep whitespace.
maxsplit: The maximum count of splits.
Return:
A list of split strings.
"""
whitespace = '\n\t '
if maxsplit == 0:
# re.split with maxsplit=0 splits everything, while str.split splits
2015-03-31 20:49:29 +02:00
# nothing (which is the behavior we want).
if keep:
return [s]
else:
return [s.strip(whitespace)]
elif maxsplit is None:
maxsplit = 0
if keep:
pattern = '([' + whitespace + '])'
2014-11-10 23:02:34 +01:00
parts = re.split(pattern, s, maxsplit)
return _combine_ws(parts, whitespace)
else:
pattern = '[' + whitespace + ']'
2014-11-10 23:02:34 +01:00
parts = re.split(pattern, s, maxsplit)
parts[-1] = parts[-1].rstrip()
2014-11-10 23:02:34 +01:00
return [p for p in parts if p]