Skip to content

Commit a57d8d0

Browse files
committed
format
Signed-off-by: Gregor Zeitlinger <[email protected]>
1 parent e21400b commit a57d8d0

File tree

5 files changed

+130
-92
lines changed

5 files changed

+130
-92
lines changed

.mise/tasks/lint-bom.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ def collect_have(bom_pom: Path) -> List[str]:
7777

7878
text = bom_pom.read_text(encoding="utf-8")
7979
# find artifactId values that start with MODULE_PREFIX
80-
matches = re.findall(r"<artifactId>\s*(%s[^<\s]*)\s*</artifactId>" % re.escape(MODULE_PREFIX), text)
80+
matches = re.findall(
81+
r"<artifactId>\s*(%s[^<\s]*)\s*</artifactId>" % re.escape(MODULE_PREFIX), text
82+
)
8183
return sorted(matches)
8284

8385

@@ -90,13 +92,20 @@ def main() -> int:
9092
have_text = "\n".join(have)
9193

9294
if want_text != have_text:
93-
print("The BOM file prometheus-metrics-bom/bom.xml does not match the current directory contents.")
95+
print(
96+
"The BOM file prometheus-metrics-bom/bom.xml does not match the current directory contents."
97+
)
9498
print("Expected:")
9599
print(want_text)
96100
print("Found:")
97101
print(have_text)
98102
print()
99-
diff = difflib.unified_diff(have_text.splitlines(keepends=True), want_text.splitlines(keepends=True), fromfile="found", tofile="expected")
103+
diff = difflib.unified_diff(
104+
have_text.splitlines(keepends=True),
105+
want_text.splitlines(keepends=True),
106+
fromfile="found",
107+
tofile="expected",
108+
)
100109
sys.stdout.writelines(diff)
101110
return 1
102111
else:
@@ -110,4 +119,3 @@ def main() -> int:
110119

111120
if __name__ == "__main__":
112121
sys.exit(main())
113-

.mise/tasks/super-linter.sh

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44

55
set -euo pipefail
66

7-
pushd "$(dirname "$0")/.."
8-
97
docker pull ghcr.io/super-linter/super-linter:latest
108

119
docker run --rm \

.mise/tasks/test_update-benchmarks.py

Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ class TestRunBenchmarksFiltering(unittest.TestCase):
1616
def setUp(self):
1717
# sample JMH table with mixed-class lines
1818
self.table = (
19-
'Benchmark Mode Cnt Score Error Units\n'
20-
'CounterBenchmark.codahaleIncNoLabels thrpt 57881.585 ops/s\n'
21-
'HistogramBenchmark.prometheusNative thrpt 2385.134 ops/s\n'
22-
'TextFormatUtilBenchmark.prometheusWriteToNull thrpt 885331.328 ops/s\n'
23-
'CounterBenchmark.prometheusInc thrpt 54090.469 ops/s\n'
19+
"Benchmark Mode Cnt Score Error Units\n"
20+
"CounterBenchmark.codahaleIncNoLabels thrpt 57881.585 ops/s\n"
21+
"HistogramBenchmark.prometheusNative thrpt 2385.134 ops/s\n"
22+
"TextFormatUtilBenchmark.prometheusWriteToNull thrpt 885331.328 ops/s\n"
23+
"CounterBenchmark.prometheusInc thrpt 54090.469 ops/s\n"
2424
)
2525

2626
# create temp dir to act as module path
@@ -30,61 +30,69 @@ def setUp(self):
3030
# Create three files with a javadoc <pre> block that contains mixed results
3131
self.files = {}
3232
javadoc_pre = (
33-
'/**\n'
34-
' * Example javadoc\n'
35-
' * <pre>\n'
36-
' * Benchmark Mode Cnt Score Error Units\n'
37-
' * CounterBenchmark.codahaleIncNoLabels thrpt 57881.585 ops/s\n'
38-
' * HistogramBenchmark.prometheusNative thrpt 2385.134 ops/s\n'
39-
' * TextFormatUtilBenchmark.prometheusWriteToNull thrpt 885331.328 ops/s\n'
40-
' * CounterBenchmark.prometheusInc thrpt 54090.469 ops/s\n'
41-
' * </pre>\n'
42-
' */\n'
33+
"/**\n"
34+
" * Example javadoc\n"
35+
" * <pre>\n"
36+
" * Benchmark Mode Cnt Score Error Units\n"
37+
" * CounterBenchmark.codahaleIncNoLabels thrpt 57881.585 ops/s\n"
38+
" * HistogramBenchmark.prometheusNative thrpt 2385.134 ops/s\n"
39+
" * TextFormatUtilBenchmark.prometheusWriteToNull thrpt 885331.328 ops/s\n"
40+
" * CounterBenchmark.prometheusInc thrpt 54090.469 ops/s\n"
41+
" * </pre>\n"
42+
" */\n"
4343
)
4444

45-
for cls in ('CounterBenchmark', 'HistogramBenchmark', 'TextFormatUtilBenchmark'):
46-
fname = os.path.join(self.module_path, f'{cls}.java')
47-
with open(fname, 'w', encoding='utf-8') as f:
45+
for cls in (
46+
"CounterBenchmark",
47+
"HistogramBenchmark",
48+
"TextFormatUtilBenchmark",
49+
):
50+
fname = os.path.join(self.module_path, f"{cls}.java")
51+
with open(fname, "w", encoding="utf-8") as f:
4852
f.write(javadoc_pre)
49-
f.write(f'public class {cls} {{}}\n')
53+
f.write(f"public class {cls} {{}}\n")
5054
self.files[cls] = fname
5155

5256
def tearDown(self):
5357
self.tmpdir.cleanup()
5458

5559
def _read_pre_contents(self, path):
56-
with open(path, 'r', encoding='utf-8') as f:
60+
with open(path, "r", encoding="utf-8") as f:
5761
content = f.read()
58-
m = re.search(r'<pre>\n([\s\S]*?)</pre>', content)
59-
return m.group(1) if m else ''
62+
m = re.search(r"<pre>\n([\s\S]*?)</pre>", content)
63+
return m.group(1) if m else ""
6064

6165
def test_update_only_inserts_matching_class_lines(self):
6266
updated = update_pre_blocks_under_module(self.module_path, self.table)
6367
# All three files should be updated
64-
self.assertEqual(set(os.path.basename(p) for p in updated),
65-
{os.path.basename(self.files['CounterBenchmark']),
66-
os.path.basename(self.files['HistogramBenchmark']),
67-
os.path.basename(self.files['TextFormatUtilBenchmark'])})
68+
self.assertEqual(
69+
set(os.path.basename(p) for p in updated),
70+
{
71+
os.path.basename(self.files["CounterBenchmark"]),
72+
os.path.basename(self.files["HistogramBenchmark"]),
73+
os.path.basename(self.files["TextFormatUtilBenchmark"]),
74+
},
75+
)
6876

6977
# Verify CounterBenchmark file contains only CounterBenchmark lines
70-
cb_pre = self._read_pre_contents(self.files['CounterBenchmark'])
71-
self.assertIn('CounterBenchmark.codahaleIncNoLabels', cb_pre)
72-
self.assertIn('CounterBenchmark.prometheusInc', cb_pre)
73-
self.assertNotIn('HistogramBenchmark.prometheusNative', cb_pre)
74-
self.assertNotIn('TextFormatUtilBenchmark.prometheusWriteToNull', cb_pre)
78+
cb_pre = self._read_pre_contents(self.files["CounterBenchmark"])
79+
self.assertIn("CounterBenchmark.codahaleIncNoLabels", cb_pre)
80+
self.assertIn("CounterBenchmark.prometheusInc", cb_pre)
81+
self.assertNotIn("HistogramBenchmark.prometheusNative", cb_pre)
82+
self.assertNotIn("TextFormatUtilBenchmark.prometheusWriteToNull", cb_pre)
7583

7684
# Verify HistogramBenchmark contains only its line
77-
hb_pre = self._read_pre_contents(self.files['HistogramBenchmark'])
78-
self.assertIn('HistogramBenchmark.prometheusNative', hb_pre)
79-
self.assertNotIn('CounterBenchmark.codahaleIncNoLabels', hb_pre)
80-
self.assertNotIn('TextFormatUtilBenchmark.prometheusWriteToNull', hb_pre)
85+
hb_pre = self._read_pre_contents(self.files["HistogramBenchmark"])
86+
self.assertIn("HistogramBenchmark.prometheusNative", hb_pre)
87+
self.assertNotIn("CounterBenchmark.codahaleIncNoLabels", hb_pre)
88+
self.assertNotIn("TextFormatUtilBenchmark.prometheusWriteToNull", hb_pre)
8189

8290
# Verify TextFormatUtilBenchmark contains only its line
83-
tf_pre = self._read_pre_contents(self.files['TextFormatUtilBenchmark'])
84-
self.assertIn('TextFormatUtilBenchmark.prometheusWriteToNull', tf_pre)
85-
self.assertNotIn('CounterBenchmark.prometheusInc', tf_pre)
86-
self.assertNotIn('HistogramBenchmark.prometheusNative', tf_pre)
91+
tf_pre = self._read_pre_contents(self.files["TextFormatUtilBenchmark"])
92+
self.assertIn("TextFormatUtilBenchmark.prometheusWriteToNull", tf_pre)
93+
self.assertNotIn("CounterBenchmark.prometheusInc", tf_pre)
94+
self.assertNotIn("HistogramBenchmark.prometheusNative", tf_pre)
8795

8896

89-
if __name__ == '__main__':
97+
if __name__ == "__main__":
9098
unittest.main()

.mise/tasks/update_benchmarks.py

Lines changed: 66 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ def run_cmd(cmd: List[str], cwd: Optional[str] = None) -> str:
3838
progress in real time while the command runs.
3939
"""
4040
try:
41-
proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
41+
proc = subprocess.Popen(
42+
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
43+
)
4244
except FileNotFoundError:
4345
# Helpful message if the executable is not found
4446
print(f"Command not found: {cmd[0]}")
@@ -50,45 +52,49 @@ def run_cmd(cmd: List[str], cwd: Optional[str] = None) -> str:
5052
# Stream lines as they appear and capture them for returning
5153
for line in proc.stdout:
5254
# Print immediately so callers (and CI) can observe progress
53-
print(line, end='')
55+
print(line, end="")
5456
output_lines.append(line)
5557
proc.wait()
5658
except KeyboardInterrupt:
5759
# If the user interrupts, ensure the child process is terminated
5860
proc.kill()
5961
proc.wait()
60-
print('\nCommand interrupted by user.')
62+
print("\nCommand interrupted by user.")
6163
raise
6264

63-
output = ''.join(output_lines)
65+
output = "".join(output_lines)
6466
if proc.returncode != 0:
65-
print(f"Command failed: {' '.join(cmd)}\nExit: {proc.returncode}\nOutput:\n{output}")
67+
print(
68+
f"Command failed: {' '.join(cmd)}\nExit: {proc.returncode}\nOutput:\n{output}"
69+
)
6670
raise SystemExit(proc.returncode)
6771
return output
6872

6973

7074
def build_benchmarks(mvnw: str, module: str) -> None:
7175
print(f"Building Maven module '{module}' using {mvnw} (this may take a while)...")
72-
cmd = [mvnw, '-pl', module, '-am', '-DskipTests', 'package']
76+
cmd = [mvnw, "-pl", module, "-am", "-DskipTests", "package"]
7377
run_cmd(cmd)
7478
print("Build completed.")
7579

7680

7781
def find_benchmarks_jar(module: str) -> str:
78-
pattern = os.path.join(module, 'target', '*.jar')
79-
jars = [p for p in glob.glob(pattern) if 'original' not in p and p.endswith('.jar')]
82+
pattern = os.path.join(module, "target", "*.jar")
83+
jars = [p for p in glob.glob(pattern) if "original" not in p and p.endswith(".jar")]
8084
# prefer jar whose basename contains module name
8185
jars_pref = [j for j in jars if module in os.path.basename(j)]
8286
chosen = (jars_pref or jars)[:1]
8387
if not chosen:
84-
raise FileNotFoundError(f"No jar found in {os.path.join(module, 'target')} (tried: {pattern})")
88+
raise FileNotFoundError(
89+
f"No jar found in {os.path.join(module, 'target')} (tried: {pattern})"
90+
)
8591
jar = chosen[0]
8692
print(f"Using jar: {jar}")
8793
return jar
8894

8995

9096
def run_jmh(jar: str, java_cmd: str, extra_args: Optional[str]) -> str:
91-
args = [java_cmd, '-jar', jar, '-rf', 'text']
97+
args = [java_cmd, "-jar", jar, "-rf", "text"]
9298
if extra_args:
9399
args += shlex.split(extra_args)
94100
print(f"Running JMH: {' '.join(args)}")
@@ -99,16 +105,23 @@ def run_jmh(jar: str, java_cmd: str, extra_args: Optional[str]) -> str:
99105

100106
def extract_first_table(jmh_output: str) -> str:
101107
# Try to extract the first table that starts with "Benchmark" header and continues until a blank line
102-
m = re.search(r'(\nBenchmark\s+Mode[\s\S]*?)(?:\n\s*\n|\Z)', jmh_output)
108+
m = re.search(r"(\nBenchmark\s+Mode[\s\S]*?)(?:\n\s*\n|\Z)", jmh_output)
103109
if not m:
104110
# fallback: collect all lines that contain 'thrpt' plus a header if present
105-
lines = [l for l in jmh_output.splitlines() if 'thrpt' in l]
111+
lines = [l for l in jmh_output.splitlines() if "thrpt" in l]
106112
if not lines:
107113
raise ValueError('Could not find any "thrpt" lines in JMH output')
108114
# try to find header
109-
header = next((l for l in jmh_output.splitlines() if l.startswith('Benchmark') and 'Mode' in l), 'Benchmark Mode Cnt Score Error Units')
110-
return header + '\n' + '\n'.join(lines)
111-
table = m.group(1).strip('\n')
115+
header = next(
116+
(
117+
l
118+
for l in jmh_output.splitlines()
119+
if l.startswith("Benchmark") and "Mode" in l
120+
),
121+
"Benchmark Mode Cnt Score Error Units",
122+
)
123+
return header + "\n" + "\n".join(lines)
124+
table = m.group(1).strip("\n")
112125
# Ensure we return only the table lines (remove any leading iteration info lines that JMH sometimes prints)
113126
# Normalize spaces: keep as-is
114127
return table
@@ -123,35 +136,39 @@ def filter_table_for_class(table: str, class_name: str) -> Optional[str]:
123136
# find header line index (starts with 'Benchmark' and contains 'Mode')
124137
header_idx = None
125138
for i, ln in enumerate(lines):
126-
if ln.strip().startswith('Benchmark') and 'Mode' in ln:
139+
if ln.strip().startswith("Benchmark") and "Mode" in ln:
127140
header_idx = i
128141
break
129-
header = lines[header_idx] if header_idx is not None else 'Benchmark Mode Cnt Score Error Units'
142+
header = (
143+
lines[header_idx]
144+
if header_idx is not None
145+
else "Benchmark Mode Cnt Score Error Units"
146+
)
130147

131148
matched = []
132-
pattern = re.compile(r'^\s*' + re.escape(class_name) + r'\.')
133-
for ln in lines[header_idx + 1 if header_idx is not None else 0:]:
134-
if 'thrpt' in ln and pattern.search(ln):
149+
pattern = re.compile(r"^\s*" + re.escape(class_name) + r"\.")
150+
for ln in lines[header_idx + 1 if header_idx is not None else 0 :]:
151+
if "thrpt" in ln and pattern.search(ln):
135152
matched.append(ln)
136153

137154
if not matched:
138155
return None
139-
return header + '\n' + '\n'.join(matched)
156+
return header + "\n" + "\n".join(matched)
140157

141158

142159
def update_pre_blocks_under_module(module: str, table: str) -> List[str]:
143160
# Find files under module and update any <pre>...</pre> block that contains 'thrpt'
144161
updated_files = []
145-
for path in glob.glob(os.path.join(module, '**'), recursive=True):
162+
for path in glob.glob(os.path.join(module, "**"), recursive=True):
146163
if os.path.isdir(path):
147164
continue
148165
try:
149-
with open(path, 'r', encoding='utf-8') as f:
166+
with open(path, "r", encoding="utf-8") as f:
150167
content = f.read()
151168
except Exception:
152169
continue
153170
# quick filter
154-
if '<pre>' not in content or 'thrpt' not in content:
171+
if "<pre>" not in content or "thrpt" not in content:
155172
continue
156173

157174
original = content
@@ -169,21 +186,21 @@ def update_pre_blocks_under_module(module: str, table: str) -> List[str]:
169186

170187
# Regex to find any line-starting Javadoc prefix like " * " before <pre>
171188
# This will match patterns like: " * <pre>... </pre>" and capture the prefix (e.g. " * ")
172-
pattern = re.compile(r'(?m)^(?P<prefix>[ \t]*\*[ \t]*)<pre>[\s\S]*?</pre>')
189+
pattern = re.compile(r"(?m)^(?P<prefix>[ \t]*\*[ \t]*)<pre>[\s\S]*?</pre>")
173190

174191
def repl(m: re.Match) -> str:
175-
prefix = m.group('prefix')
192+
prefix = m.group("prefix")
176193
# Build the new block with the same prefix on each line
177194
lines = filtered_table.splitlines()
178-
replaced = prefix + '<pre>\n'
195+
replaced = prefix + "<pre>\n"
179196
for ln in lines:
180-
replaced += prefix + ln.rstrip() + '\n'
181-
replaced += prefix + '</pre>'
197+
replaced += prefix + ln.rstrip() + "\n"
198+
replaced += prefix + "</pre>"
182199
return replaced
183200

184201
new_content, nsubs = pattern.subn(repl, content)
185202
if nsubs > 0 and new_content != original:
186-
with open(path, 'w', encoding='utf-8') as f:
203+
with open(path, "w", encoding="utf-8") as f:
187204
f.write(new_content)
188205
updated_files.append(path)
189206
print(f"Updated {path}: replaced {nsubs} <pre> block(s)")
@@ -192,34 +209,41 @@ def repl(m: re.Match) -> str:
192209

193210
def main(argv: List[str]):
194211
parser = argparse.ArgumentParser()
195-
parser.add_argument('--mvnw', default='./mvnw', help='Path to maven wrapper')
196-
parser.add_argument('--module', default='benchmarks', help='Module directory to build/run')
197-
parser.add_argument('--java', default='java', help='Java command')
198-
parser.add_argument('--jmh-args', default='', help='Extra arguments to pass to the JMH main (e.g. "-f 1 -wi 0 -i 1")')
212+
parser.add_argument("--mvnw", default="./mvnw", help="Path to maven wrapper")
213+
parser.add_argument(
214+
"--module", default="benchmarks", help="Module directory to build/run"
215+
)
216+
parser.add_argument("--java", default="java", help="Java command")
217+
parser.add_argument(
218+
"--jmh-args",
219+
default="",
220+
help='Extra arguments to pass to the JMH main (e.g. "-f 1 -wi 0 -i 1")',
221+
)
199222
args = parser.parse_args(argv)
200223

201224
build_benchmarks(args.mvnw, args.module)
202225
jar = find_benchmarks_jar(args.module)
203226
output = run_jmh(jar, args.java, args.jmh_args)
204227

205228
# Print a short preview of the JMH output
206-
preview = '\n'.join(output.splitlines()[:120])
207-
print('\n--- JMH output preview ---')
229+
preview = "\n".join(output.splitlines()[:120])
230+
print("\n--- JMH output preview ---")
208231
print(preview)
209-
print('--- end preview ---\n')
232+
print("--- end preview ---\n")
210233

211234
table = extract_first_table(output)
212235

213236
updated = update_pre_blocks_under_module(args.module, table)
214237

215238
if not updated:
216-
print('No files were updated (no <pre> blocks with "thrpt" found under the module).')
239+
print(
240+
'No files were updated (no <pre> blocks with "thrpt" found under the module).'
241+
)
217242
else:
218-
print('\nUpdated files:')
243+
print("\nUpdated files:")
219244
for p in updated:
220-
print(' -', p)
245+
print(" -", p)
221246

222247

223-
if __name__ == '__main__':
248+
if __name__ == "__main__":
224249
main(sys.argv[1:])
225-

0 commit comments

Comments
 (0)