-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit
More file actions
executable file
·793 lines (679 loc) · 29.9 KB
/
pre-commit
File metadata and controls
executable file
·793 lines (679 loc) · 29.9 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
#!/usr/bin/env python3
# Pre-commit hook for Git repos.
# Andrew Benson (28-July-2021) — ported to Python
import os
import re
import shutil
import subprocess
import sys
import tempfile
GREEN = '\033[1;32m'
RED = '\033[1;31m'
YELLOW = '\033[1;33m'
RESET = '\033[0m'
def print_ok(msg):
print(f"{GREEN}\u2714 {RESET}{msg}")
def print_fail(msg):
print(f"{RED}\u2715 {RESET}{msg}")
def print_warn(msg):
print(f"{YELLOW}\u26a0 {RESET}{msg}")
# ── Staged files ─────────────────────────────────────────────────────────────
def get_staged_files():
try:
ref = subprocess.check_output(
['git', 'rev-parse', '--verify', 'HEAD^{commit}'],
stderr=subprocess.DEVNULL,
).decode().strip()
except subprocess.CalledProcessError:
# Empty repo — use the SHA for an empty tree
ref = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
result = subprocess.run(
['git', 'diff-index', '--cached', '--diff-filter=ACMRD',
'--ignore-submodules', ref],
capture_output=True, text=True,
)
files = []
for line in result.stdout.splitlines():
parts = line.split()
files.append({
'sha': parts[3],
'status': parts[4],
'fileName': parts[5],
'tmpFileName': None,
})
return files
def extract_staged_files(files):
for f in files:
if f['status'] == 'D':
continue
suffix = os.path.splitext(f['fileName'])[1]
fd, tmp = tempfile.mkstemp(suffix=suffix)
os.close(fd)
f['tmpFileName'] = tmp
subprocess.run(
f"git cat-file blob {f['sha']} > {tmp}",
shell=True, check=True,
)
def cleanup(files):
for f in files:
if f.get('tmpFileName') and os.path.exists(f['tmpFileName']):
try:
os.unlink(f['tmpFileName'])
except OSError:
pass
# ── Fortran static analysis ──────────────────────────────────────────────────
# Simplified Fortran variable-declaration pattern (mirrors Fortran::Utils)
_DECL_RE = re.compile(
r'^\s*(?:integer|real|complex|logical|character|double\s+precision'
r'|type\s*\(|class\s*\().*::',
re.IGNORECASE,
)
def _function_is_empty(body_lines):
"""Return True if a Fortran function/subroutine body is effectively empty."""
in_docstring = False
for line in body_lines:
s = line.strip()
if not s:
continue
if re.match(r'^\s*!!\}', s):
in_docstring = False
continue
if re.match(r'^\s*!!\{', s):
in_docstring = True
continue
if in_docstring:
continue
if re.match(r'^![^\$]', s): # comment, but not !$ directive
continue
if re.match(r'^use(\s*,\s*intrinsic)?\s*::', s, re.IGNORECASE):
continue
if re.match(r'^implicit\s+none\s*$', s, re.IGNORECASE):
continue
if re.match(r'^return\s*$', s, re.IGNORECASE):
continue
if _DECL_RE.match(s):
continue
return False
return True
def check_fortran_static(files):
all_ok = True
for f in files:
if f['status'] == 'D' or not f['fileName'].endswith('.F90'):
continue
with open(f['tmpFileName'], 'r', errors='replace') as fh:
lines = fh.readlines()
# Strip comments.
linesStripped = []
for line in lines:
linesStripped.append(re.sub(r'(["\'])(?:(?=(\\?))\2.)*?\1|(!).*','\1',line))
# Join continuation lines.
linesJoined = []
while linesStripped:
line = linesStripped.pop(0)
while re.search(r'&\s*$',line):
lineNext = linesStripped.pop(0)
line = re.sub(r'&\s*$','',line )
lineNext = re.sub(r'^\s*&','',lineNext)
line = line.rstrip("\n") + lineNext
linesJoined.append(line)
# ── Check 1: type/class pointer vars without =>null() in derived types
in_type = False
type_name = ''
for line in linesJoined:
# Type definition start: "type [, attrs] :: name" or "type name"
m = re.match(r'^\s*type(?:\s*,\s*[^:]+)?\s*::\s*(\w+)', line, re.IGNORECASE)
if not m:
m = re.match(r'^\s*type\s+(\w+)\s*$', line, re.IGNORECASE)
if m:
in_type = True
type_name = m.group(1)
if re.match(r'^\s*end\s+type\b', line, re.IGNORECASE):
in_type = False
type_name = ''
if in_type:
m = re.match(
r'^\s*(?:type|class)\s*\(\s*\w+\s*\)\s*,[^:]*pointer[^:]*::\s*(.+)',
line, re.IGNORECASE,
)
if m:
for var in re.split(r',(?![^(]*\))', m.group(1)):
var = var.strip()
if var and '=>null()' not in var.replace(' ', '').lower():
vname = re.split(r'=>', var)[0].strip()
print(f"\t{YELLOW}\u26a0 {RESET}Pointer variable '{vname}'"
f" in type '{type_name}'"
f" in file '{f['fileName']}' is not null initialized")
all_ok = False
# ── Check 2: duplicate assignments in constructorAssign directives
for line in linesJoined:
if 'constructorAssign' not in line:
continue
vm = re.search(r'variables\s*=\s*["\']([^"\']+)["\']', line)
if not vm:
continue
variables = re.split(r'\s*,\s*', vm.group(1))
counts = {}
for v in variables:
counts[v] = counts.get(v, 0) + 1
for v, c in counts.items():
if c > 1:
print(f"\t{YELLOW}\u26a0 {RESET}Duplicated assignment of '{v}'"
f" in `constructorAssign` directive"
f" in file '{f['fileName']}'")
all_ok = False
# ── Checks 3 & 4: empty constructors / finalizers
# Collect type names
type_names = set()
for line in linesJoined:
for pat in (r'^\s*type\s*(?:,\s*[^:]+)?\s*::\s*(\w+)',
r'^\s*type\s+(\w+)\s*$'):
m = re.match(pat, line, re.IGNORECASE)
if m:
type_names.add(m.group(1).lower())
# Collect constructor names (from matching interfaces)
constructors = set()
finalizers = set()
in_interface = False
for line in linesJoined:
m = re.match(r'^\s*interface\s+(\w+)\s*$', line, re.IGNORECASE)
if m and m.group(1).lower() in type_names:
in_interface = True
if in_interface:
m = re.match(r'^\s*module\s+procedure\s+(.+)', line, re.IGNORECASE)
if m:
constructors.update(
p.strip().lower()
for p in re.split(r'\s*,\s*', m.group(1))
if p.strip()
)
if re.match(r'^\s*end\s+interface\b', line, re.IGNORECASE):
in_interface = False
# Collect finalizer names
m = re.match(r'^\s*final\s*::\s*(.+)', line, re.IGNORECASE)
if m:
finalizers.update(
n.strip().lower()
for n in re.split(r'\s*,\s*', m.group(1))
if n.strip()
)
# Examine each function/subroutine body
for i, line in enumerate(lines):
# Constructor: zero-argument function (not a module function)
m = re.match(
r'^\s*(?!\s*module\s+function)(?:\w+\s+)?function\s+(\w+)\s*\(\s*\)',
line, re.IGNORECASE,
)
if m and not re.match(r'^\s*module\s+function', line, re.IGNORECASE):
fname = m.group(1).lower()
if fname in constructors:
end_re = re.compile(
r'^\s*end\s+function\s+' + re.escape(fname) + r'\b',
re.IGNORECASE,
)
body = []
j = i + 1
while j < len(lines) and not end_re.match(lines[j]):
body.append(lines[j])
j += 1
if _function_is_empty(body):
print(f"\t{YELLOW}\u26a0 {RESET}Empty constructor function"
f" '{m.group(1)}' in file '{f['fileName']}'")
all_ok = False
# Finalizer: subroutine
m = re.match(r'^\s*subroutine\s+(\w+)\s*\(', line, re.IGNORECASE)
if m:
sname = m.group(1).lower()
if sname in finalizers:
end_re = re.compile(
r'^\s*end\s+subroutine\s+' + re.escape(sname) + r'\b',
re.IGNORECASE,
)
body = []
j = i + 1
while j < len(lines) and not end_re.match(lines[j]):
body.append(lines[j])
j += 1
if _function_is_empty(body):
print(f"\t{YELLOW}\u26a0 {RESET}Empty finalizer function"
f" '{m.group(1)}' in file '{f['fileName']}'")
all_ok = False
if all_ok:
print_ok('Fortran static analysis')
else:
print_fail('Fortran static analysis')
sys.exit(1)
# ── Bibliography ─────────────────────────────────────────────────────────────
def check_bibliography(files):
valid = True
for f in files:
if f['status'] == 'D' or not f['fileName'].endswith('.bib'):
continue
with open(f['fileName'], 'r', errors='replace') as fh:
for line in fh:
if re.match(r'^\s*file\s*=\s*\{', line):
valid = False
if valid:
print_ok('Validate bibliography')
else:
print_warn('Validate bibliography')
# ── Spell checking ────────────────────────────────────────────────────────────
_spell_words = []
_spell_words_loaded = False
def _load_spell_words():
global _spell_words, _spell_words_loaded
if _spell_words_loaded:
return
state_storables = 'work/build/stateStorables.xml'
if os.path.exists(state_storables):
try:
import xml.etree.ElementTree as ET
root = ET.parse(state_storables).getroot()
instances = [
e.text.strip()
for e in root.findall('.//functionClassInstances/*')
if e.text
]
_spell_words.extend(instances)
classes = {
e.tag: True
for e in root.findall('.//functionClasses/*')
}
for cls in classes:
_spell_words.append(cls)
prefix = re.sub(r'Class$', '', cls)
_spell_words.append(prefix)
match_longest = 0
for iname in instances:
if iname.lower().startswith(prefix.lower()):
if len(prefix) > match_longest:
match_longest = len(prefix)
instance_suffix = iname[len(prefix):]
if instance_suffix:
instance_suffix = (instance_suffix[0].lower()
+ instance_suffix[1:])
_spell_words.append(instance_suffix)
except Exception:
pass
words_file = 'aux/words.dict'
if os.path.exists(words_file):
with open(words_file, 'r', errors='replace') as fh:
for line in fh:
word = line.strip()
if word:
_spell_words.append(word)
_spell_words_loaded = True
def _spell_check_file(file_name, original_name):
"""Spell-check a file. Returns True if no misspellings found."""
_load_spell_words()
is_latex = file_name.endswith('.tex')
dict_file = file_name + '.dict'
spell_file = file_name + '.spell'
# Write personal dictionary
unique_words = sorted(set(w for w in _spell_words if w))
with open(dict_file, 'w') as fh:
fh.write('\n'.join(unique_words) + '\n')
# Pre-process the file
words_set = set(_spell_words)
_camel_re = re.compile(
r'\b(?<!\\)([a-zA-Z0-9][a-zA-Z]*'
r'(?:[a-z0-9][a-zA-Z]*[A-Z]|[A-Z][a-zA-Z]*[a-z])'
r'[a-zA-Z0-9]*)\b'
)
def _split_camel(m):
word = m.group(0)
if word in words_set:
return word
if word == 'FoX':
return 'fox'
return re.sub(r'([a-z0-9])([A-Z0-9])', r'\1 \2', word)
with open(file_name, 'r', errors='replace') as fin, \
open(spell_file, 'w') as fout:
for line in fin:
line = _camel_re.sub(_split_camel, line)
if is_latex:
# Remove non-roman text in LaTeX subscripts starting with {
line = re.sub(
r'(_\{)([^}]*\\mathrm\{[^}]{1,2}\}[^}]*)(\})',
r'\1\3', line,
)
# Remove non-roman text in LaTeX subscripts starting with \mathrm
line = re.sub(
r'(_\\mathrm\{)([^}]{1,2})(\})',
r'\1\3', line,
)
# Remove glossary labels
line = re.sub(r'\\gls\{[^}]*\}', r'\\gls{}', line)
line = re.sub(r'\\glslink\{[^}]*\}', r'\\glslink{}', line)
line = re.sub(r'\\newacronym(\{[^}]*\}){2}',
r'\\newacronym{}{}', line)
line = re.sub(r'\\newglossaryentry\{[^}]*\}\{name=\{[^}]*\}',
r'\\newglossaryentry{}{', line)
line = line.replace('firstplural=', 'first plural=')
# Translate accents
line = line.replace("\\'e", 'e').replace('\\"o', 'o')
# Remove LaTeX double quotes
line = line.replace("''", '').replace('``', '')
fout.write(line)
# Run hunspell
if not shutil.which('hunspell'):
try:
os.unlink(spell_file)
os.unlink(dict_file)
except OSError:
pass
return True
args = ['hunspell', '-l']
if is_latex:
args.append('-t')
args += ['-i', 'utf-8', '-p', dict_file, spell_file]
result = subprocess.run(args, capture_output=True, text=True)
misspelled = {}
for word in result.stdout.splitlines():
if 'error - iconv:' in word:
continue
w = word.strip().lower()
if w:
misspelled[w] = misspelled.get(w, 0) + 1
try:
os.unlink(spell_file)
os.unlink(dict_file)
except OSError:
pass
for word, count in sorted(misspelled.items()):
instances = f'({count} instances) ' if count > 1 else ''
print(f"\t{YELLOW}\u26a0 {RESET}Possible misspelled word '{word}' "
f"{instances}in file '{original_name}'")
return len(misspelled) == 0
def _spell_check(text, text_type, original_name):
"""Spell-check a text fragment."""
suffix = '.tex' if text_type == 'latex' else '.txt'
fd, tmp = tempfile.mkstemp(suffix=suffix)
with os.fdopen(fd, 'w') as fh:
fh.write(text)
status = _spell_check_file(tmp, original_name)
try:
os.unlink(tmp)
except OSError:
pass
return status
def check_spell_latex(files):
all_ok = True
for f in files:
if f['status'] == 'D' or not f['fileName'].endswith('.tex'):
continue
if not _spell_check_file(f['tmpFileName'], f['fileName']):
all_ok = False
if all_ok:
print_ok('Spell check LaTeX')
else:
print_warn('Spell check LaTeX')
# ── Perl scripts ──────────────────────────────────────────────────────────────
def check_perl_scripts(files):
for f in files:
if f['status'] == 'D' or not re.search(r'\.p[lm]$', f['fileName']):
continue
if f['fileName'].endswith('.pl') and not os.access(f['fileName'], os.X_OK):
print_fail(f"Perl script is not executable ({f['fileName']})")
sys.exit(1)
result = subprocess.run(
['perl', '-c', f['tmpFileName']],
capture_output=True,
)
if result.returncode != 0:
print_fail(f"Perl script/module does not compile ({f['fileName']})")
sys.exit(1)
print_ok('Perl scripts')
# ── XML files ─────────────────────────────────────────────────────────────────
def check_xml_files(files):
for f in files:
if f['status'] == 'D' or not re.search(r'\.(xml|xsd)$', f['fileName']):
continue
result = subprocess.run(
['xmllint', '--noout', f['tmpFileName']],
capture_output=True,
)
if result.returncode != 0:
print_fail(f"XML file is invalid ({f['fileName']})")
sys.exit(1)
with open(f['tmpFileName'], 'r', errors='replace') as fh:
for line_num, line in enumerate(fh, 1):
if any(ord(c) > 127 for c in line):
highlighted = re.sub(
r'[^\x00-\x7F]+',
lambda m: f'\033[31m{m.group()}\033[0m',
line,
)
print(highlighted, end='')
print_fail(
f"XML file has non-ascii character"
f" ({f['fileName']}:{line_num})"
)
sys.exit(1)
print_ok('XML files')
# ── YAML files ────────────────────────────────────────────────────────────────
def check_yaml_files(files):
if not shutil.which('yamllint'):
return
for f in files:
if f['status'] == 'D' or not f['fileName'].endswith('.yml'):
continue
result = subprocess.run(
['yamllint', f['tmpFileName']],
capture_output=True,
)
if result.returncode != 0:
print_fail(f"YAML file is invalid ({f['fileName']})")
sys.exit(1)
print_ok('YAML files')
# ── LaTeX compilation ─────────────────────────────────────────────────────────
def _test_latex(raw_latex):
"""Compile a LaTeX fragment. Returns the log on failure, None on success."""
raw_latex = raw_latex.replace('&', '&').replace('<', '>')
galacticus = os.environ.get('GALACTICUS_EXEC_PATH', '')
frag = f'frag{os.getpid()}'
tex_path = os.path.join('doc', frag + '.tex')
with open(tex_path, 'w') as fh:
fh.write(r'\documentclass[letterpaper,10pt,headsepline]{scrbook}' + '\n')
fh.write(r'\usepackage{natbib}' + '\n')
fh.write(r'\usepackage{epsfig}' + '\n')
fh.write(r'\usepackage[acronym]{glossaries}' + '\n')
fh.write(r'\usepackage[backref,colorlinks]{hyperref}' + '\n')
fh.write(r'\usepackage{amssymb}' + '\n')
fh.write(r'\usepackage{amsmath}' + '\n')
fh.write(r'\usepackage{tensor}' + '\n')
fh.write(r'\usepackage{xcolor}' + '\n')
fh.write(r'\usepackage{listings}' + '\n')
fh.write(f'\\input{{{galacticus}/doc/commands}}' + '\n')
fh.write(f'\\input{{{galacticus}/doc/Glossary}}' + '\n')
fh.write(r'\newcommand{\docname}{tmp}' + '\n')
fh.write(r'\begin{document}' + '\n')
fh.write(raw_latex)
fh.write(r'\end{document}' + '\n')
result = subprocess.run(
f'cd doc; pdflatex -halt-on-error {frag} > {frag}.tmp',
shell=True,
)
log = None
if result.returncode != 0:
log_path = os.path.join('doc', frag + '.log')
if os.path.exists(log_path):
with open(log_path) as fh:
log = fh.read()
for ext in ('.tex', '.pdf', '.log', '.aux', '.tmp', '.glo'):
p = os.path.join('doc', frag + ext)
if os.path.exists(p):
os.unlink(p)
return log
# ── XML / LaTeX fragment testing ──────────────────────────────────────────────
def _process_fragments_file(f):
"""
Walk an F90/Inc file looking for embedded XML directives (!<) and LaTeX
blocks (!!{ ... !!}) and validate / compile them. Returns 0 on success.
"""
import xml.etree.ElementTree as ET
in_directive = False
in_xml = False
in_latex = False
in_comment = False
line_number = 0
directive_root = None
raw_directive = ''
stripped_directive = ''
raw_latex = None # None = not yet inside a LaTeX block
raw_comment = None # None = not yet inside a comment block
with open(f['tmpFileName'], 'r', errors='replace') as fh:
lines = fh.readlines()
for line in lines:
# ── Detect section ends (before accumulation, matching Perl order) ──
if re.match(r'^\s*!!\}', line):
in_latex = False
if re.match(r'^\s*!!\]', line):
in_xml = False
if not re.match(r'^\s*!\s', line):
in_comment = False
# ── Accumulate LaTeX ─────────────────────────────────────────────────
if in_latex and raw_latex is not None:
raw_latex += line
# ── Process completed LaTeX block ────────────────────────────────────
if raw_latex is not None and not in_latex:
log = _test_latex(raw_latex)
if log is not None:
print_fail(
f"LaTeX fragment compilation failed"
f" ({f['fileName']}:{line_number}):\n{log}"
)
return 1
_spell_check(raw_latex, 'latex', f['fileName'])
raw_latex = None
# ── Accumulate comment ───────────────────────────────────────────────
if in_comment and raw_comment is not None:
raw_comment += line
# ── Process completed comment block ──────────────────────────────────
if raw_comment is not None and not in_comment:
_spell_check(raw_comment, 'text', f['fileName'])
raw_comment = None
# ── XML directive detection ──────────────────────────────────────────
stripped_line = re.sub(r'^\s*\!<\s*', '', line)
is_directive = False
end_directive = False
if in_xml:
if re.match(r'^\s*<[^\s>/]+', stripped_line) or in_directive:
is_directive = True
if is_directive and not in_directive:
m = re.match(r'^\s*<([^\s>/]+)', stripped_line)
if m:
directive_root = m.group(1)
if is_directive and directive_root:
if re.search(r'</' + re.escape(directive_root) + r'>', stripped_line):
end_directive = True
if not in_directive:
if (re.search(r'<' + re.escape(directive_root) + r'\s[^>]*/>', stripped_line) or
re.search(r'<' + re.escape(directive_root) + r'/>', stripped_line)):
end_directive = True
if is_directive:
in_directive = True
# ── Accumulate directive / code ──────────────────────────────────────
if in_directive:
raw_directive += line
stripped_directive += stripped_line
# (raw_code accumulation omitted — not used downstream)
# ── Process completed directive ──────────────────────────────────────
if (not in_directive or end_directive) and raw_directive:
try:
root_elem = ET.fromstring(stripped_directive)
directive_name = root_elem.tag
except ET.ParseError as exc:
print_fail(
f"Parsing XML fragment failed"
f" ({f['fileName']}:{line_number})\n{exc}\n"
)
print(stripped_directive)
return 1
# Validate against XSD schema if available
galacticus = os.environ.get('GALACTICUS_EXEC_PATH', '')
schema_path = os.path.join(galacticus, 'schema', directive_name + '.xsd')
if os.path.exists(schema_path):
try:
from lxml import etree # type: ignore[import]
schema = etree.XMLSchema(etree.parse(schema_path))
schema.assertValid(etree.fromstring(stripped_directive.encode()))
except Exception as exc:
print_fail(
f"XML fragment validation failed"
f" ({f['fileName']}:{line_number}):\n{exc}\n"
)
return 1
# If the directive has a <description>, try to compile it as LaTeX
desc_elem = root_elem.find('description')
if desc_elem is not None and desc_elem.text:
log = _test_latex(desc_elem.text)
if log is not None:
print_fail(
f"XML LaTeX description compilation failed"
f" ({f['fileName']}:{line_number}):\n{log}"
)
return 1
_spell_check(desc_elem.text, 'latex', f['fileName'])
in_directive = False
raw_directive = ''
stripped_directive = ''
# ── Detect section starts (after accumulation, matching Perl order) ──
if re.match(r'^\s*!!\[', line):
in_xml = True
if re.match(r'^\s*!!\{', line):
in_latex = True
raw_latex = ''
if re.match(r'^\s*!\s', line) and not in_comment:
in_comment = True
raw_comment = line
line_number += 1
return 0
def check_xml_latex_fragments(files):
f90_files = [
f for f in files
if f['status'] != 'D' and re.search(r'\.(F90|Inc)$', f['fileName'])
]
# Process files in parallel using forked subprocesses (mirrors Perl ForkManager)
if f90_files:
import multiprocessing
with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as pool:
results = pool.map(_process_fragments_file, f90_files)
for rc in results:
if rc != 0:
sys.exit(rc)
print_ok('XML fragments')
print_ok('LaTeX fragments')
# ── Debugging statements ──────────────────────────────────────────────────────
def check_debugging_statements(files):
for f in files:
if f['status'] == 'D':
continue
if not re.search(r'\.(pl|pm|F90|Inc|h|c|cpp)$', f['fileName']):
continue
with open(f['tmpFileName'], 'r', errors='replace') as fh:
for line_num, line in enumerate(fh, 1):
if 'AJB HACK' in line:
print_fail(
f"Debugging statement remains"
f" ({f['fileName']}:{line_num}):"
)
sys.exit(1)
print_ok('Debugging statements removed')
# ── Main ──────────────────────────────────────────────────────────────────────
def main():
files = get_staged_files()
extract_staged_files(files)
try:
check_fortran_static(files)
check_bibliography(files)
check_spell_latex(files)
check_perl_scripts(files)
check_xml_files(files)
check_yaml_files(files)
check_xml_latex_fragments(files)
check_debugging_statements(files)
finally:
cleanup(files)
sys.exit(0)
if __name__ == '__main__':
main()