OILS / data_lang / j8_lite.py View on Github | oils.pub

57 lines, 17 significant
1"""j8_lite.py: Low dependency library
2
3For ASDL circular dep involving prebuilt/
4"""
5
6import fastfunc # Skip pyj8 and fastlex
7
8
9def EncodeString(s, unquoted_ok=False):
10 # type: (str, bool) -> str
11 """Convenience API that doesn't require instance of j8.Printer()
12
13 This is the same logic as j8.Printer.EncodeString(), which reuses a
14 BufWriter.
15
16 If you have to create many strings, it may generate less garbage to use
17 that method, then call BufWriter.clear() in between.
18
19 Note: true false null are quoted, even when unquoted_ok=True
20 """
21 if unquoted_ok and fastfunc.CanOmitQuotes(s):
22 return s
23
24 return fastfunc.J8EncodeString(s, 1) # j8_fallback is true
25
26
27def YshEncodeString(s):
28 # type: (str) -> str
29
30 # Possibilities:
31 # - '' then b'' - simplest logic
32 return fastfunc.ShellEncodeString(s, 1) # ysh_fallback
33
34
35def MaybeShellEncode(s):
36 # type: (str) -> str
37 """
38 This is like ShellEncode(s, unquoted_ok=True)
39 But it's common, so we give it a shorter name.
40 """
41 if fastfunc.CanOmitQuotes(s):
42 return s
43
44 return fastfunc.ShellEncodeString(s, 0) # no ysh_fallback
45
46
47def ShellEncode(s):
48 # type: (str) -> str
49 return fastfunc.ShellEncodeString(s, 0) # no ysh_fallback
50
51
52def YshEncode(s, unquoted_ok=False):
53 # type: (str, bool) -> str
54 if unquoted_ok and fastfunc.CanOmitQuotes(s):
55 return s
56
57 return fastfunc.ShellEncodeString(s, 1) # ysh_fallback