| 1 |
|
| 2 |
|
| 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 |
|
| 32 |
if "'" in text: |
| 33 |
|
| 34 |
|
| 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 |
|
| 44 |
if "'" in text: |
| 45 |
return f'"{_escape_for_double_quotes(text)}"' |
| 46 |
else: |
| 47 |
return f"'{text}'" |