ext.shell_escape: Fixed escaping of tabs and unprintables
[ranger.git] / ranger / ext / shell_escape.py
blobb68afc333489d813eb7366f8bec616a3f9157bb7
1 # Copyright (C) 2009, 2010, 2011 Roman Zimbelmann <romanz@lavabit.com>
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """
17 Functions to escape metacharacters of arguments for shell commands.
18 """
20 META_CHARS = (' ', "'", '"', '`', '&', '|', ';',
21 '$', '!', '(', ')', '[', ']', '<', '>', '\t')
22 UNESCAPABLE = set(map(chr, list(range(9)) + list(range(10, 32)) \
23 + list(range(127, 256))))
24 META_DICT = dict([(mc, '\\' + mc) for mc in META_CHARS])
26 def shell_quote(string):
27 """Escapes by quoting"""
28 return "'" + str(string).replace("'", "'\\''") + "'"
30 def shell_escape(arg):
31 """Escapes by adding backslashes"""
32 arg = str(arg)
33 if UNESCAPABLE & set(arg):
34 return shell_quote(arg)
35 arg = arg.replace('\\', '\\\\') # make sure this comes at the start
36 for k, v in META_DICT.items():
37 arg = arg.replace(k, v)
38 return arg