codekingpro/portable-devtools
115k
1import re2 3import pyparsing4 5# TODO: There is a lot of work to be done here.6# The current implementation is written in a way that _any_ input is valid,7# which does not make sense once things get more complex.8 9PartialQuotedString = pyparsing.Regex(10 re.compile(11 r"""12 "[^"]*(?:"|$) # double-quoted string that ends with double quote or EOF13 |14 '[^']*(?:'|$) # single-quoted string that ends with double quote or EOF15 """,16 re.VERBOSE,17 )18)19 20expr = pyparsing.ZeroOrMore(21 PartialQuotedString22 | pyparsing.Word(" \r\n\t")23 | pyparsing.CharsNotIn("""'" \r\n\t""")24).leaveWhitespace()25 26 27def quote(val: str) -> str:28 if val and all(char not in val for char in "'\" \r\n\t"):29 return val30 if '"' not in val:31 return f'"{val}"'32 if "'" not in val:33 return f"'{val}'"34 return '"' + val.replace('"', r"\x22") + '"'35 36 37def unquote(x: str) -> str:38 if len(x) > 1 and x[0] in "'\"" and x[0] == x[-1]:39 return x[1:-1]40 else:41 return x42 