-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathstring_format.py
More file actions
181 lines (161 loc) · 6.92 KB
/
string_format.py
File metadata and controls
181 lines (161 loc) · 6.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# Copyright 2023-2025 Buf Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# type: ignore
# TODO(#257): Fully test and fix types in this file.
from decimal import Decimal
import celpy
from celpy import celtypes
QUOTE_TRANS = str.maketrans(
{
"\a": r"\a",
"\b": r"\b",
"\f": r"\f",
"\n": r"\n",
"\r": r"\r",
"\t": r"\t",
"\v": r"\v",
"\\": r"\\",
'"': r"\"",
}
)
def quote(s: str) -> str:
return '"' + s.translate(QUOTE_TRANS) + '"'
class StringFormat:
"""An implementation of string.format() in CEL."""
def __init__(self, locale: str):
self.locale = locale
def format(self, fmt: celtypes.Value, args: celtypes.Value) -> celpy.Result:
if not isinstance(fmt, celtypes.StringType):
return celpy.CELEvalError("format() requires a string as the first argument")
if not isinstance(args, celtypes.ListType):
return celpy.CELEvalError("format() requires a list as the second argument")
# printf style formatting
i = 0
j = 0
result = ""
while i < len(fmt):
if fmt[i] != "%":
result += fmt[i]
i += 1
continue
if i + 1 < len(fmt) and fmt[i + 1] == "%":
result += "%"
i += 2
continue
if j >= len(args):
return celpy.CELEvalError("format() not enough arguments for format string")
arg = args[j]
j += 1
i += 1
if i >= len(fmt):
return celpy.CELEvalError("format() incomplete format specifier")
precision = 6
if fmt[i] == ".":
i += 1
precision = 0
while i < len(fmt) and fmt[i].isdigit():
precision = precision * 10 + int(fmt[i])
i += 1
if i >= len(fmt):
return celpy.CELEvalError("format() incomplete format specifier")
if fmt[i] == "f":
result += self.format_float(arg, precision)
if fmt[i] == "e":
result += self.format_exponential(arg, precision)
elif fmt[i] == "d":
result += self.format_int(arg)
elif fmt[i] == "s":
result += self.format_string(arg)
elif fmt[i] == "x":
result += self.format_hex(arg)
elif fmt[i] == "X":
result += self.format_hex(arg).upper()
elif fmt[i] == "o":
result += self.format_oct(arg)
elif fmt[i] == "b":
result += self.format_bin(arg)
else:
return celpy.CELEvalError("format() unknown format specifier: " + fmt[i])
i += 1
if j < len(args):
return celpy.CELEvalError("format() too many arguments for format string")
return celtypes.StringType(result)
def format_float(self, arg: celtypes.Value, precision: int) -> celpy.Result:
if isinstance(arg, celtypes.DoubleType):
return celtypes.StringType(f"{arg:.{precision}f}")
return self.format_int(arg)
def format_exponential(self, arg: celtypes.Value, precision: int) -> celpy.Result:
if isinstance(arg, celtypes.DoubleType):
return celtypes.StringType(f"{arg:.{precision}e}")
return self.format_int(arg)
def format_int(self, arg: celtypes.Value) -> celpy.Result:
if isinstance(arg, celtypes.IntType):
return celtypes.StringType(arg)
if isinstance(arg, celtypes.UintType):
return celtypes.StringType(arg)
return celpy.CELEvalError("format_int() requires an integer argument")
def format_hex(self, arg: celtypes.Value) -> celpy.Result:
if isinstance(arg, celtypes.IntType):
return celtypes.StringType(f"{arg:x}")
if isinstance(arg, celtypes.UintType):
return celtypes.StringType(f"{arg:x}")
if isinstance(arg, celtypes.BytesType):
return celtypes.StringType(arg.hex())
if isinstance(arg, celtypes.StringType):
return celtypes.StringType(arg.encode("utf-8").hex())
return celpy.CELEvalError("format_hex() requires an integer, string, or binary argument")
def format_oct(self, arg: celtypes.Value) -> celpy.Result:
if isinstance(arg, celtypes.IntType):
return celtypes.StringType(f"{arg:o}")
if isinstance(arg, celtypes.UintType):
return celtypes.StringType(f"{arg:o}")
return celpy.CELEvalError("format_oct() requires an integer argument")
def format_bin(self, arg: celtypes.Value) -> celpy.Result:
if isinstance(arg, celtypes.IntType):
return celtypes.StringType(f"{arg:b}")
if isinstance(arg, celtypes.UintType):
return celtypes.StringType(f"{arg:b}")
if isinstance(arg, celtypes.BoolType):
return celtypes.StringType(f"{arg:b}")
return celpy.CELEvalError("format_bin() requires an integer argument")
def format_string(self, arg: celtypes.Value) -> celpy.Result:
if isinstance(arg, celtypes.StringType):
return arg
if isinstance(arg, celtypes.BytesType):
return celtypes.StringType(arg)
if isinstance(arg, celtypes.ListType):
return self.format_list(arg)
if isinstance(arg, celtypes.BoolType):
# True -> true
return celtypes.StringType(str(arg).lower())
if isinstance(arg, celtypes.DoubleType):
return celtypes.StringType(f"{arg:g}")
if isinstance(arg, celtypes.DurationType):
return celtypes.StringType(self._format_duration(arg))
if isinstance(arg, celtypes.TimestampType):
base = arg.isoformat()
if arg.getMilliseconds() != 0:
base = arg.isoformat(timespec="milliseconds")
return celtypes.StringType(base.removesuffix("+00:00") + "Z")
return celtypes.StringType(arg)
def format_list(self, arg: celtypes.ListType) -> celpy.Result:
result = "["
for i in range(len(arg)):
if i > 0:
result += ", "
result += self.format_string(arg[i])
result += "]"
return celtypes.StringType(result)
def _format_duration(self, arg: celtypes.DurationType) -> celpy.Result:
return f"{arg.seconds + Decimal(arg.microseconds) / Decimal(1_000_000):f}s"