Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/shell.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 # You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import re
6
7 SHELL_QUOTE_RE = re.compile(r"[\\\t\r\n \'\"#<>&|`(){}$;\*\?]")
8
9
10 def _quote(s):
11 """Given a string, returns a version that can be used literally on a shell
12 command line, enclosing it with single quotes if necessary.
13
14 As a special case, if given an int, returns a string containing the int,
15 not enclosed in quotes.
16 """
17 if isinstance(s, int):
18 return f"{s}"
19
20 # Empty strings need to be quoted to have any significance
21 if s and not SHELL_QUOTE_RE.search(s) and not s.startswith("~"):
22 return s
23
24 # Single quoted strings can contain any characters unescaped except the
25 # single quote itself, which can't even be escaped, so the string needs to
26 # be closed, an escaped single quote added, and reopened.
27 t = type(s)
28 return t("'%s'") % s.replace(t("'"), t("'\\''"))
29
30
31 def quote(*strings):
32 """Given one or more strings, returns a quoted string that can be used
33 literally on a shell command line.
34
35 >>> quote('a', 'b')
36 "a b"
37 >>> quote('a b', 'c')
38 "'a b' c"
39 """
40 return " ".join(_quote(s) for s in strings)