Skip to content

Commit bd9a0e4

Browse files
authored
Formatting Cleanup (#569)
- Convert all s-string into f-string - Remove mode "r" from `load` function, as it is the default value - Write sets using brackets instead of `Set` constructor
1 parent 6e3b8e8 commit bd9a0e4

18 files changed

Lines changed: 69 additions & 85 deletions

File tree

lobster/common/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __init__(self, message, data=None):
2828
self.data = data
2929

3030
def dump(self):
31-
print("LOBSTER Error: %s" % self.message)
31+
print(f"LOBSTER Error: {self.message}")
3232
if self.data:
3333
print("-" * 60)
3434
pprint(self.data)

lobster/common/io.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def lobster_read(
6565
loc = File_Reference(filename)
6666

6767
# Read and validate JSON
68-
with open(filename, "r", encoding="UTF-8") as fd:
68+
with open(filename, encoding="UTF-8") as fd:
6969
try:
7070
data = json.load(fd)
7171
except json.decoder.JSONDecodeError as err:
@@ -80,7 +80,7 @@ def lobster_read(
8080

8181
for rkey in ("schema", "version", "generator", "data"):
8282
if rkey not in data:
83-
mh.error(loc, "required top-level key %s not present" % rkey)
83+
mh.error(loc, f"required top-level key {rkey} not present")
8484
if rkey == "data":
8585
if not isinstance(data[rkey], list):
8686
mh.error(loc, "data is not an array")
@@ -89,16 +89,16 @@ def lobster_read(
8989
mh.error(loc, "version is not an integer")
9090
else:
9191
if not isinstance(data[rkey], str):
92-
mh.error(loc, "%s is not a string" % rkey)
92+
mh.error(loc, f"{rkey} is not a string")
9393

9494
# Validate indicated schema
9595
supported_schema = {
96-
"lobster-req-trace" : set([3, 4]),
97-
"lobster-imp-trace" : set([3]),
98-
"lobster-act-trace" : set([3]),
96+
"lobster-req-trace" : {3, 4},
97+
"lobster-imp-trace" : {3},
98+
"lobster-act-trace" : {3},
9999
}
100100
if data["schema"] not in supported_schema:
101-
mh.error(loc, "unknown schema kind %s" % data["schema"])
101+
mh.error(loc, f"unknown schema kind {data['schema']}")
102102
if data["version"] not in supported_schema[data["schema"]]:
103103
mh.error(loc,
104104
"version %u for schema %s is not supported" %

lobster/common/items.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,9 @@ def __init__(
4343
self.hash_val = None
4444

4545
def __str__(self):
46-
rv = "%s %s" % (self.namespace,
47-
self.tag)
46+
rv = f"{self.namespace} {self.tag}"
4847
if self.version:
49-
rv += "@%s" % str(self.version)
48+
rv += f"@{self.version}"
5049
return rv
5150

5251
def key(self) -> str:

lobster/common/lexer.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ def value(self):
3636
return self.text
3737

3838
def __repr__(self):
39-
return "Token(%s, %s, %s)" % (self.kind,
40-
self.text,
41-
self.loc)
39+
return f"Token({self.kind}, {self.text}, {self.loc})"
4240

4341

4442
class Lexer:
@@ -50,7 +48,7 @@ def __init__(self, mh, file_name):
5048
self.file_name = file_name
5149
self.mh = mh
5250

53-
with open(file_name, "r", encoding="UTF-8") as fd:
51+
with open(file_name, encoding="UTF-8") as fd:
5452
self.content = fd.read()
5553
self.length = len(self.content)
5654

@@ -114,7 +112,7 @@ def token(self):
114112
while self.nc.isalpha() or self.nc == "_":
115113
self.advance()
116114
else:
117-
self.error("unexpected character: '%s'" % self.cc)
115+
self.error(f"unexpected character: '{self.cc}'")
118116

119117
t_end = self.lexpos
120118

lobster/common/parser.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,13 @@ def match(self, kind, value=None):
6060
elif self.nt is None:
6161
self.error(
6262
location.File_Reference(filename = self.lexer.file_name),
63-
"expected %s, found EOF" % kind)
63+
f"expected {kind}, found EOF")
6464
elif value is None:
6565
self.error(self.nt.loc,
66-
"expected %s, found %s %s" % (kind,
67-
self.nt.kind,
68-
self.nt.value()))
66+
f"expected {kind}, found {self.nt.kind} {self.nt.value()}")
6967
else:
7068
self.error(self.nt.loc,
71-
"expected %s, found %s" % (value, self.nt.value()))
69+
f"expected {value}, found {self.nt.value()}")
7270

7371
def warning(self, loc, message):
7472
self.lexer.mh.warning(loc, message)
@@ -117,7 +115,7 @@ def parse_level_declaration(self):
117115
}
118116
if not os.path.isfile(source_info["file"]):
119117
self.error(self.ct.loc,
120-
"cannot find file %s" % source_info["file"])
118+
f"cannot find file {source_info['file']}")
121119
item.source.append(source_info)
122120

123121
if self.peek("KEYWORD", "with"):
@@ -135,7 +133,7 @@ def parse_level_declaration(self):
135133
"cannot trace to yourself")
136134
elif self.ct.value() not in self.levels:
137135
self.error(self.ct.loc,
138-
"unknown item %s" % self.ct.value())
136+
f"unknown item {self.ct.value()}")
139137
else:
140138
self.levels[self.ct.value()].needs_tracing_down = True
141139
item.traces.append(self.ct.value())
@@ -163,7 +161,7 @@ def parse_level_declaration(self):
163161

164162
else:
165163
self.error(self.nt.loc,
166-
"unexpected directive %s" % self.nt.value())
164+
f"unexpected directive {self.nt.value()}")
167165

168166
self.match("C_KET")
169167

@@ -180,12 +178,10 @@ def load(mh, file_name):
180178
new_chain = []
181179
for tok in chain:
182180
if tok.value() not in ast:
183-
mh.error(tok.loc, "unknown level %s" % tok.value())
181+
mh.error(tok.loc, f"unknown level {tok.value()}")
184182
if item.name not in ast[tok.value()].traces:
185183
mh.error(tok.loc,
186-
"%s cannot trace to %s items" %
187-
(tok.value(),
188-
item.name))
184+
f"{tok.value()} cannot trace to {item.name} items")
189185
new_chain.append(tok.value())
190186
item.breakdown_requirements.append(new_chain)
191187
else:

lobster/common/report.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def resolve_references_for_items(self):
8080
while src_item.unresolved_references:
8181
dst_tag = src_item.unresolved_references.pop()
8282
if dst_tag.key() not in self.items:
83-
src_item.error("unknown tracing target %s" % dst_tag.key())
83+
src_item.error(f"unknown tracing target {dst_tag.key()}")
8484
continue
8585
dst_item = self.items[dst_tag.key()]
8686
# TODO: Check if policy allows this link
@@ -151,7 +151,7 @@ def load_report(self, filename):
151151
loc = File_Reference(filename)
152152

153153
# Read and validate JSON
154-
with open(filename, "r", encoding="UTF-8") as fd:
154+
with open(filename, encoding="UTF-8") as fd:
155155
try:
156156
data = json.load(fd)
157157
except json.decoder.JSONDecodeError as err:
@@ -231,10 +231,10 @@ def validate_indicated_schema(self, data, loc):
231231
232232
"""
233233
supported_schema = {
234-
"lobster-report": set([2]),
234+
"lobster-report": {2},
235235
}
236236
if data["schema"] not in supported_schema:
237-
self.mh.error(loc, "unknown schema kind %s" % data["schema"])
237+
self.mh.error(loc, f"unknown schema kind {data['schema']}")
238238
if data["version"] not in supported_schema[data["schema"]]:
239239
self.mh.error(loc,
240240
"version %u for schema %s is not supported" %
@@ -262,6 +262,6 @@ def validate_basic_structure_of_lobster_file(self, data, loc):
262262
dict: "an object"}
263263
for rkey, rvalue in rkey_dict.items():
264264
if rkey not in data:
265-
self.mh.error(loc, "required top-level key %s not present" % rkey)
265+
self.mh.error(loc, f"required top-level key {rkey} not present")
266266
if not isinstance(data[rkey], rvalue):
267-
self.mh.error(loc, "%s is not %s." % (rkey, type_dict[rvalue]))
267+
self.mh.error(loc, f"{rkey} is not {type_dict[rvalue]}.")

lobster/common/version.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
VERSION_SUFFIX = "dev"
2222

2323
LOBSTER_VERSION = ".".join(str(x) for x in VERSION_TUPLE) + (
24-
"-%s" % VERSION_SUFFIX if VERSION_SUFFIX else ""
24+
f"-{VERSION_SUFFIX}" if VERSION_SUFFIX else ""
2525
)
2626

27-
FULL_NAME = "LOBSTER %s" % LOBSTER_VERSION
27+
FULL_NAME = f"LOBSTER {LOBSTER_VERSION}"

lobster/htmldoc/htmldoc.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ def __init__(self, title, subtitle):
235235
"h2" : {
236236
"padding" : "0.5em",
237237
"margin" : "0",
238-
"border-bottom" : "0.25em solid %s" % self.primary_color,
238+
"border-bottom" : f"0.25em solid {self.primary_color}",
239239
"text-align" : "right",
240240
},
241241
".content" : {
@@ -298,13 +298,13 @@ def render(self):
298298
"<html>",
299299
"<head>",
300300
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>",
301-
"<title>%s</title>" % html.escape(self.title),
301+
f"<title>{html.escape(self.title)}</title>",
302302
"<style>"
303303
]
304304
for elem, style in self.style.items():
305305
rv.append("%s {" % elem)
306306
for attr, value in style.items():
307-
rv.append(" %s: %s;" % (attr, value))
307+
rv.append(f" {attr}: {value};")
308308
rv.append("}")
309309

310310
# add css files that are appended to self.files
@@ -315,9 +315,8 @@ def render(self):
315315
rv.append("<body>")
316316

317317
rv.append('<div class="title">')
318-
rv.append("<h1>%s</h1>" % html.escape(self.title))
319-
rv.append('<div class="subtitle">%s</div>' %
320-
html.escape(self.subtitle))
318+
rv.append(f"<h1>{html.escape(self.title)}</h1>")
319+
rv.append(f'<div class="subtitle">{html.escape(self.subtitle)}</div>')
321320
rv.append('</div>')
322321

323322
rv += navbar_content

lobster/tools/codebeamer/codebeamer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ def load_config(file_name: str) -> Config:
492492
FileNotFoundError: If the file does not exist.
493493
KeyError: If required fields are missing or unsupported keys are present.
494494
"""
495-
with open(file_name, "r", encoding='utf-8') as file:
495+
with open(file_name, encoding='utf-8') as file:
496496
return parse_config_data(yaml.safe_load(file) or {})
497497

498498

lobster/tools/core/html_report/html_report.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,14 @@ def create_policy_diagram(doc, report, dot):
107107
style = 'shape=hexagon'
108108
style += f', href="#sec-{name_hash(level.name)}"'
109109

110-
graph += ' n_%s [label="%s", %s];\n' % \
111-
(name_hash(level.name),
112-
level.name,
113-
style)
110+
graph += f' n_{name_hash(level.name)} [label="{level.name}", {style}];\n'
114111

115112
for level in report.config.values():
116113
source = name_hash(level.name)
117114
for target in map(name_hash, level.traces):
118115
# Not a mistake; we want to show the tracing down, whereas
119116
# in the config file we indicate how we trace up.
120-
graph += ' n_%s -> n_%s;\n' % (target, source)
117+
graph += f' n_{target} -> n_{source};\n'
121118
graph += "}\n"
122119

123120
with tempfile.TemporaryDirectory() as tmp_dir:
@@ -157,11 +154,11 @@ def create_item_coverage(doc, report):
157154
doc.add_line('<td><a href="#sec-%s">%s</a></td>' %
158155
(name_hash(level.name),
159156
html.escape(level.name)))
160-
doc.add_line("<td>%.1f%%</td>" % data.coverage)
157+
doc.add_line(f"<td>{data.coverage:.1f}%</td>")
161158
doc.add_line("<td>")
162159
doc.add_line('<progress value="%u" max="%u">' %
163160
(data.ok, data.items))
164-
doc.add_line("%.2f%%" % data.coverage)
161+
doc.add_line(f"{data.coverage:.2f}%")
165162
doc.add_line('</progress>')
166163
doc.add_line("</td>")
167164
doc.add_line('<td align="right">%u</td>' % data.ok)
@@ -232,30 +229,30 @@ def write_item_tracing(doc, report, item):
232229
doc.add_line("<div>Traces to:")
233230
doc.add_line("<ul>")
234231
for ref in item.ref_down:
235-
doc.add_line("<li>%s</li>" % xref_item(report.items[ref.key()]))
232+
doc.add_line(f"<li>{xref_item(report.items[ref.key()])}</li>")
236233
doc.add_line("</ul>")
237234
doc.add_line("</div>")
238235
if item.ref_up:
239236
doc.add_line("<div>Derived from:")
240237
doc.add_line("<ul>")
241238
for ref in item.ref_up:
242-
doc.add_line("<li>%s</li>" % xref_item(report.items[ref.key()]))
239+
doc.add_line(f"<li>{xref_item(report.items[ref.key()])}</li>")
243240
doc.add_line("</ul>")
244241
doc.add_line("</div>")
245242

246243
if item.tracing_status == Tracing_Status.JUSTIFIED:
247244
doc.add_line("<div>Justifications:")
248245
doc.add_line("<ul>")
249246
for msg in item.just_global + item.just_up + item.just_down:
250-
doc.add_line("<li>%s</li>" % html.escape(msg))
247+
doc.add_line(f"<li>{html.escape(msg)}</li>")
251248
doc.add_line("</ul>")
252249
doc.add_line("</div>")
253250

254251
if item.messages:
255252
doc.add_line("<div>Issues:")
256253
doc.add_line("<ul>")
257254
for msg in item.messages:
258-
doc.add_line("<li>%s</li>" % html.escape(msg))
255+
doc.add_line(f"<li>{html.escape(msg)}</li>")
259256
doc.add_line("</ul>")
260257
doc.add_line("</div>")
261258

@@ -422,9 +419,9 @@ def write_html(report, dot, high_contrast, render_md) -> str:
422419
doc.add_line(f'<div id="custom-data-banner">{content}</div>')
423420
menu = doc.navbar.add_dropdown("LOBSTER", "right")
424421
menu.add_link("Documentation",
425-
"%s/blob/main/README.md" % LOBSTER_GH)
422+
f"{LOBSTER_GH}/blob/main/README.md")
426423
menu.add_link("License",
427-
"%s/blob/main/LICENSE.md" % LOBSTER_GH)
424+
f"{LOBSTER_GH}/blob/main/LICENSE.md")
428425
menu.add_link("Source", LOBSTER_GH)
429426

430427
### Summary (Coverage & Policy)
@@ -548,7 +545,7 @@ def write_html(report, dot, high_contrast, render_md) -> str:
548545
write_item_box_begin(doc, item, report)
549546
if isinstance(item, Requirement) and item.status:
550547
doc.add_line('<div class="attribute">')
551-
doc.add_line("Status: %s" % html.escape(item.status))
548+
doc.add_line(f"Status: {html.escape(item.status)}")
552549
doc.add_line('</div>')
553550
if (isinstance(item, (Requirement, Activity)) and item.text):
554551
if render_md:

0 commit comments

Comments
 (0)