Debian Codegraph @

git_delete_merged_branches/_shell.py

raw symbols SCIP
1 # Copyright (C) 2020 Sebastian Pipping <[email protected]>
2 # Licensed under GPL v3 or later
3
4 _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES = set('!`"$\\')
5 _NEED_ESCAPING_WITHOUT_QUOTES = _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES | set("' {}()?*&<>;#")
6
7
8 def _escape_for_double_quotes(text: str) -> str:
9 escape = {c: f"\\{c}" for c in _NEED_ESCAPING_INSIDE_DOUBLE_QUOTES}
10 escaped = "".join(escape.get(c, c) for c in text)
11 return escaped
12
13
14 def escape_for_shell_display(text: str) -> str:
15 """
16 Format text for display as part of a shell command
17 close to what a human would write and expect to read.
18
19 In detail, the requirements are:
20 1. Do not escape spaces but rather surround by quotes,
21 single or double.
22 2. Do not surround by any quotes if the string does not
23 contain spaces and is not the empty string.
24 3. Prefer single quotes over double quotes, i.e. use double
25 quotes only when single quotes are already present.
26 """
27 if not text:
28 return "''"
29
30 if " " in text:
31 # Is surrounding by single quotes an option?
32 if "'" in text:
33 # Surrounding by single quotes is not an option;
34 # so escape for use inside double quotes
35 return f'"{_escape_for_double_quotes(text)}"'
36 else:
37 return f"'{text}'"
38
39 needs_escaping = any((c in _NEED_ESCAPING_WITHOUT_QUOTES) for c in text)
40 if not needs_escaping:
41 return text
42
43 # Is surrounding by single quotes an option?
44 if "'" in text:
45 return f'"{_escape_for_double_quotes(text)}"'
46 else:
47 return f"'{text}'"