forked from ManageIQ/integration_tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquote.py
58 lines (51 loc) · 1.37 KB
/
quote.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# -*- coding: utf-8 -*-
######################################################################
# Written by Kevin L. Sitze on 2006-12-03
# This code may be used pursuant to the MIT License.
######################################################################
# PEP8 applied and some things tweaked by Milan Falesnik
import re
__all__ = ('quote',)
_bash_reserved_words = {
'case',
'coproc',
'do',
'done',
'elif',
'else',
'esac',
'fi',
'for',
'function',
'if',
'in',
'select',
'then',
'until',
'while',
'time'
}
####
# _quote_re1 escapes double-quoted special characters.
# _quote_re2 escapes unquoted special characters.
_quote_re1 = re.compile(r"([\!\"\$\\\`])")
_quote_re2 = re.compile(r"([\t\ \!\"\#\$\&\'\(\)\*\:\;\<\>\?\@\[\\\]\^\`\{\|\}\~])")
def quote(*args):
"""Combine the arguments into a single string and escape any and
all shell special characters or (reserved) words. The shortest
possible string (correctly quoted suited to pass to a bash shell)
is returned.
"""
s = "".join(args)
if s in _bash_reserved_words:
return "\\" + s
elif s.find('\'') >= 0:
s1 = '"' + _quote_re1.sub(r"\\\1", s) + '"'
else:
s1 = "'" + s + "'"
s2 = _quote_re2.sub(r"\\\1", s)
if len(s1) <= len(s2):
return s1
else:
return s2