Skip to content

Commit d117fe4

Browse files
style: split complex regexes across multiple lines and add comments
1 parent 3addc27 commit d117fe4

1 file changed

Lines changed: 30 additions & 2 deletions

File tree

juju/constraints.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,21 @@ def normalize_list_value(value: str) -> List[ParsedValue]:
151151

152152

153153
STORAGE = re.compile(
154-
'(?:(?:^|(?<=,))(?:|(?P<pool>[a-zA-Z]+[-?a-zA-Z0-9]*)|(?P<count>-?[0-9]+)|(?:(?P<size>-?[0-9]+(?:\\.[0-9]+)?)(?P<size_exp>[MGTPEZY])(?:i?B)?))(?:$|,))')
154+
# original regex:
155+
# '(?:(?:^|(?<=,))(?:|(?P<pool>[a-zA-Z]+[-?a-zA-Z0-9]*)|(?P<count>-?[0-9]+)|(?:(?P<size>-?[0-9]+(?:\\.[0-9]+)?)(?P<size_exp>[MGTPEZY])(?:i?B)?))(?:$|,))'
156+
# with formatting and explanation -- note that this regex is used with re.finditer:
157+
'(?:(?:^|(?<=,))' # start of string or previous match ends with ','
158+
'(?:' # match one of the following:
159+
'|(?P<pool>[a-zA-Z]+[-?a-zA-Z0-9]*)' # pool: a sequence starting with a letter, ending with a letter or number,
160+
# -- and including letters, numbers and hyphens (no more than one in a row)
161+
'|(?P<count>-?[0-9]+)' # count: an optional minus sign followed by one or more digits
162+
'|(?:' # size (number) and size_exp (units):
163+
'(?P<size>-?[0-9]+(?:\\.[0-9]+)?)' # an optional minus sign followed by one or more digits, optionally with decimal point and more digits
164+
'(?P<size_exp>[MGTPEZY])(?:i?B)?' # one of MGTPEZY, optionally followed by iB or B, for example 1M or 2.0MB or -3.3MiB
165+
')'
166+
')'
167+
'(?:$|,))' # end of string or ','
168+
)
155169

156170

157171
class StorageConstraintDict(TypedDict):
@@ -179,7 +193,21 @@ def parse_storage_constraint(constraint: str) -> StorageConstraintDict:
179193

180194

181195
DEVICE = re.compile(
182-
'^(?P<count>[0-9]+)?(?:^|,)(?P<type>[^,]+)(?:$|,(?!$))(?P<attrs>(?:[^=]+=[^;]+)+)*$')
196+
# original regex:
197+
# '^(?P<count>[0-9]+)?(?:^|,)(?P<type>[^,]+)(?:$|,(?!$))(?P<attrs>(?:[^=]+=[^;]+)+)*$'
198+
# with formatting and explanation:
199+
'^' # start of string
200+
'(?P<count>[0-9]+)?' # count is 1+ digits, and is optional
201+
'(?:^|,)' # match start of string or a comma
202+
# -- so type can be at the start or comma separated from count
203+
'(?P<type>[^,]+)' # type is 1+ anything not a comma (including digits), and is required
204+
'(?:$|,(?!$))' # match end of string | or a non-trailing comma
205+
# -- so type can be at the end or followed by attrs
206+
'(?P<attrs>(?:[^=]+=[^;]+)+)*' # attrs is any number of semicolon separated key=value items
207+
# -- value can have spare '=' inside, possible not intended
208+
# -- attrs will be matched with ATTR.finditer afterwards in parse_device_constraint
209+
'$' # end of string
210+
)
183211
ATTR = re.compile(';?(?P<key>[^=]+)=(?P<value>[^;]+)')
184212

185213

0 commit comments

Comments
 (0)