|
4 | 4 | from .._utils import * |
5 | 5 |
|
6 | 6 |
|
| 7 | +def escape(txt): |
| 8 | + """apply FFmpeg single quote escaping |
| 9 | +
|
| 10 | + :param txt: Unescaped string |
| 11 | + :type txt: any stringifiable object |
| 12 | + :return: Escaped string |
| 13 | + :rtype: str |
| 14 | +
|
| 15 | + See https://ffmpeg.org/ffmpeg-utils.html#Quoting-and-escaping |
| 16 | + """ |
| 17 | + |
| 18 | + txt = str(txt) |
| 19 | + |
| 20 | + if re.search(r"\s", txt, re.MULTILINE): |
| 21 | + # quote if txt has any white space |
| 22 | + txt = txt.replace("'", r"'\''") |
| 23 | + return f"'{txt}'" |
| 24 | + else: |
| 25 | + # if not quoted, escape quotes and backslashes |
| 26 | + return re.sub(r"(['\\])", r"\\\1", txt) |
| 27 | + |
| 28 | + |
| 29 | +def unescape(txt): |
| 30 | + """undo FFmpeg single quote escaping |
| 31 | +
|
| 32 | + :param txt: Escaped string |
| 33 | + :type txt: str |
| 34 | + :return: Original string |
| 35 | + :rtype: str |
| 36 | +
|
| 37 | + See https://ffmpeg.org/ffmpeg-utils.html#Quoting-and-escaping |
| 38 | + """ |
| 39 | + |
| 40 | + n = len(txt) |
| 41 | + if not n: |
| 42 | + return txt |
| 43 | + |
| 44 | + re_start = re.compile(r"[^\\](?:\\\\)*'") |
| 45 | + re_sub = re.compile(r"\\([\\'])") |
| 46 | + |
| 47 | + blks = [] |
| 48 | + |
| 49 | + # look for a first quoted text block |
| 50 | + m = re.search(r"(?:^|[^\\])(?:\\\\)*'", txt) |
| 51 | + if m: |
| 52 | + i0 = m.end() |
| 53 | + if i0 > 1: |
| 54 | + # unescape the initial unquoted block |
| 55 | + blks.append(re_sub.sub(r"\1", txt[0 : i0 - 1])) |
| 56 | + else: |
| 57 | + # no quoted text block, unescape the whole string |
| 58 | + return re_sub.sub(r"\1", txt) |
| 59 | + |
| 60 | + # always starts with quoted block |
| 61 | + in_quote = True |
| 62 | + |
| 63 | + while i0 < n: |
| 64 | + |
| 65 | + if in_quote: |
| 66 | + # find the end quote |
| 67 | + i1 = txt.find("'", i0) |
| 68 | + if i1 < 0: |
| 69 | + raise ValueError("incorrectly escaped text: missing a closing quote.") |
| 70 | + blks.append(txt[i0:i1]) |
| 71 | + else: |
| 72 | + # find the next starting quote |
| 73 | + m = re_start.search(txt, i0 - 1) |
| 74 | + i1 = m.end() - 1 if m else n |
| 75 | + blks.append(re_sub.sub(r"\1", txt[i0:i1])) |
| 76 | + i0 = i1 + 1 |
| 77 | + in_quote = not in_quote |
| 78 | + |
| 79 | + return "".join(blks) |
| 80 | + |
| 81 | + |
7 | 82 | def parse_spec_stream(spec, file_index=False): |
8 | 83 | if isinstance(spec, str): |
9 | 84 | out = {} |
|
0 commit comments