-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsf_lint.py
More file actions
833 lines (751 loc) · 28.2 KB
/
Copy pathjsf_lint.py
File metadata and controls
833 lines (751 loc) · 28.2 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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
#!/usr/bin/env python3
"""
jsf_lint.py - Configurable C++ linter based on simplified JSF AV rules.
Usage:
python3 jsf_lint.py <file_or_directory> [--config rules.yaml] [--format text|json|github]
Designed for use with Claude Code as a custom slash command or as a
standalone CI linting step for embedded C++ projects.
"""
import argparse
import json
import os
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
try:
import yaml
except ImportError:
print("PyYAML required. Install with: pip install pyyaml", file=sys.stderr)
sys.exit(1)
__version__ = "1.0.0"
# =============================================================================
# Data Structures
# =============================================================================
@dataclass
class Violation:
file: str
line: int
column: int
rule_id: str
jsf_ref: str
severity: str
message: str
def to_text(self) -> str:
return (
f"{self.file}:{self.line}:{self.column}: "
f"[{self.severity.upper()}] {self.rule_id} ({self.jsf_ref}): "
f"{self.message}"
)
def to_github(self) -> str:
level = "error" if self.severity == "error" else "warning"
return (
f"::{level} file={self.file},line={self.line},col={self.column}"
f"::{self.rule_id} ({self.jsf_ref}): {self.message}"
)
def to_dict(self) -> dict:
return {
"file": self.file,
"line": self.line,
"column": self.column,
"rule_id": self.rule_id,
"jsf_ref": self.jsf_ref,
"severity": self.severity,
"message": self.message,
}
@dataclass
class LintResult:
violations: list = field(default_factory=list)
files_checked: int = 0
errors: int = 0
warnings: int = 0
infos: int = 0
# =============================================================================
# Utility Functions
# =============================================================================
def strip_string_literals(line: str) -> str:
"""Remove string and character literals to avoid false positives."""
result = []
i = 0
in_string = False
in_char = False
escape = False
while i < len(line):
ch = line[i]
if escape:
escape = False
if in_string or in_char:
result.append("_")
else:
result.append(ch)
i += 1
continue
if ch == "\\":
escape = True
result.append("_" if (in_string or in_char) else ch)
i += 1
continue
if ch == '"' and not in_char:
if in_string:
in_string = False
result.append('"')
else:
in_string = True
result.append('"')
i += 1
continue
if ch == "'" and not in_string:
if in_char:
in_char = False
result.append("'")
else:
in_char = True
result.append("'")
i += 1
continue
if in_string or in_char:
result.append("_")
else:
result.append(ch)
i += 1
return "".join(result)
def strip_comments(lines: list[str]) -> list[str]:
"""
Return a copy of lines with comments replaced by whitespace.
Preserves line count and character positions.
"""
result = []
in_block = False
for line in lines:
out = []
i = 0
while i < len(line):
if in_block:
if line[i : i + 2] == "*/":
out.append(" ")
i += 2
in_block = False
else:
out.append(" ")
i += 1
else:
if line[i : i + 2] == "//":
out.append(" " * (len(line) - i))
break
elif line[i : i + 2] == "/*":
out.append(" ")
i += 2
in_block = True
else:
out.append(line[i])
i += 1
result.append("".join(out))
return result
def is_in_comment(original_line: str, col: int) -> bool:
"""Check if a column position falls inside a comment on the original line."""
i = 0
in_str = False
in_chr = False
while i < min(col, len(original_line)):
ch = original_line[i]
if ch == "\\" and (in_str or in_chr):
i += 2
continue
if ch == '"' and not in_chr:
in_str = not in_str
elif ch == "'" and not in_str:
in_chr = not in_chr
elif not in_str and not in_chr:
if original_line[i : i + 2] == "//":
return True
if original_line[i : i + 2] == "/*":
return True
i += 1
return False
def has_nolint(line: str, rule_id: str, marker: str) -> bool:
"""Check if a line contains an inline suppression for the given rule."""
pattern = rf"{marker}\(\s*{re.escape(rule_id)}\s*\)"
if re.search(pattern, line):
return True
if f"{marker}(*)" in line or f"{marker}" in line.split("//")[-1]:
# Blanket suppression
blanket = rf"{marker}(?:\(\s*\*\s*\))?"
comment_part = line.split("//")[-1] if "//" in line else ""
if re.search(blanket, comment_part):
return True
return False
# =============================================================================
# Individual Rule Checkers
# =============================================================================
class RuleChecker:
"""Base class for all rule checkers."""
def __init__(self, rule_id: str, config: dict):
self.rule_id = rule_id
self.enabled = config.get("enabled", True)
self.severity = config.get("severity", "warning")
self.jsf_ref = config.get("jsf_ref", "")
self.description = config.get("description", "")
self.params = config.get("params", {})
def check(self, filepath: str, lines: list[str],
stripped: list[str]) -> list[Violation]:
"""Override in subclasses. lines = original, stripped = no comments."""
return []
def _violation(self, filepath: str, line: int, col: int,
msg: str) -> Violation:
return Violation(
file=filepath, line=line, column=col,
rule_id=self.rule_id, jsf_ref=self.jsf_ref,
severity=self.severity, message=msg,
)
class PatternChecker(RuleChecker):
"""Checks for forbidden patterns via regex."""
def __init__(self, rule_id: str, config: dict):
super().__init__(rule_id, config)
raw = config.get("patterns", [])
if not raw and "pattern" in config:
raw = [config["pattern"]]
self.patterns = [re.compile(p) for p in raw]
def check(self, filepath, lines, stripped):
violations = []
for i, line in enumerate(stripped):
safe = strip_string_literals(line)
for pat in self.patterns:
for m in pat.finditer(safe):
if not is_in_comment(lines[i], m.start()):
violations.append(self._violation(
filepath, i + 1, m.start() + 1,
self.description,
))
return violations
class MaxLineLengthChecker(RuleChecker):
def check(self, filepath, lines, stripped):
limit = self.params.get("max_chars", 100)
violations = []
for i, line in enumerate(lines):
raw = line.rstrip("\n\r")
if len(raw) > limit:
violations.append(self._violation(
filepath, i + 1, limit + 1,
f"Line length {len(raw)} exceeds limit of {limit}.",
))
return violations
class MaxFunctionLengthChecker(RuleChecker):
def check(self, filepath, lines, stripped):
limit = self.params.get("max_lines", 100)
violations = []
# Simple brace-counting heuristic to find function bodies.
brace_depth = 0
func_start = None
func_name = ""
for i, line in enumerate(stripped):
safe = strip_string_literals(line)
# Detect function definition: something ending with ) {
if (brace_depth == 0
and re.search(r"\)\s*\{?\s*$", safe.strip())
and not re.match(r"^\s*(if|else|while|for|switch|catch)\b",
safe)):
name_match = re.search(
r"(\w+)\s*\([^)]*\)\s*(?:const)?\s*\{?\s*$", safe)
if name_match:
func_name = name_match.group(1)
for ch in safe:
if ch == "{":
if brace_depth == 0:
func_start = i
brace_depth += 1
elif ch == "}":
brace_depth -= 1
if brace_depth == 0 and func_start is not None:
length = i - func_start + 1
if length > limit:
violations.append(self._violation(
filepath, func_start + 1, 1,
f"Function '{func_name}' is {length} lines "
f"(limit: {limit}).",
))
func_start = None
func_name = ""
return violations
class MaxFunctionArgsChecker(RuleChecker):
def check(self, filepath, lines, stripped):
limit = self.params.get("max_args", 6)
violations = []
full = "\n".join(stripped)
# Match function declarations/definitions
pattern = re.compile(
r"(\w+)\s*\(([^)]{1,500})\)\s*(?:const)?\s*[{;]"
)
for m in pattern.finditer(full):
name = m.group(1)
if name in ("if", "while", "for", "switch", "catch", "return"):
continue
params = m.group(2).strip()
if not params or params == "void":
continue
# Count commas outside angle brackets
depth = 0
count = 1
for ch in params:
if ch in "<(":
depth += 1
elif ch in ">)":
depth -= 1
elif ch == "," and depth == 0:
count += 1
if count > limit:
line_num = full[: m.start()].count("\n") + 1
violations.append(self._violation(
filepath, line_num, 1,
f"Function '{name}' has {count} parameters "
f"(limit: {limit}).",
))
return violations
class NoTabsChecker(RuleChecker):
def check(self, filepath, lines, stripped):
violations = []
for i, line in enumerate(lines):
col = line.find("\t")
if col >= 0:
violations.append(self._violation(
filepath, i + 1, col + 1,
"Tab character found. Use spaces for indentation.",
))
return violations
class IncludeGuardChecker(RuleChecker):
def check(self, filepath, lines, stripped):
if not filepath.endswith(".h") and not filepath.endswith(".hpp"):
return []
has_ifndef = any(
re.match(r"\s*#\s*ifndef\b", l) for l in stripped
)
has_pragma = any(
re.match(r"\s*#\s*pragma\s+once\b", l) for l in stripped
)
if not has_ifndef and not has_pragma:
return [self._violation(
filepath, 1, 1,
"Header file lacks an include guard (#ifndef/#pragma once).",
)]
return []
class BracesRequiredChecker(RuleChecker):
"""Check that if/else/while/for bodies are enclosed in braces."""
def check(self, filepath, lines, stripped):
violations = []
keywords = re.compile(
r"^\s*(if|else\s+if|else|while|for)\s*(\(|$|\{)"
)
for i, line in enumerate(stripped):
safe = strip_string_literals(line)
m = keywords.match(safe)
if not m:
continue
# Check if this line or next line has an opening brace
rest = safe[m.end():]
# Find the closing paren for condition
if m.group(1) == "else" and "if" not in m.group(1):
# 'else' has no condition
if "{" not in rest:
next_line = stripped[i + 1].strip() if i + 1 < len(stripped) else ""
if not next_line.startswith("{"):
violations.append(self._violation(
filepath, i + 1, 1,
f"Body of '{m.group(1).strip()}' must be "
f"enclosed in braces.",
))
else:
# Has a condition in parens; find end of condition
depth = 0
found_open = False
scan = safe[m.start():]
for ch in scan:
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
found_open = True
elif found_open and ch == "{":
break
elif found_open and ch not in " \t\n\r":
# Non-brace after condition close
violations.append(self._violation(
filepath, i + 1, 1,
f"Body of '{m.group(1).strip()}' must be "
f"enclosed in braces.",
))
break
else:
if found_open:
# Check next line
next_line = (
stripped[i + 1].strip()
if i + 1 < len(stripped) else ""
)
if not next_line.startswith("{"):
violations.append(self._violation(
filepath, i + 1, 1,
f"Body of '{m.group(1).strip()}' must be "
f"enclosed in braces.",
))
return violations
class SwitchDefaultChecker(RuleChecker):
def check(self, filepath, lines, stripped):
violations = []
full = "\n".join(stripped)
for m in re.finditer(r"\bswitch\s*\(", full):
line_num = full[: m.start()].count("\n") + 1
# Find the matching brace block
start = full.index("{", m.end())
depth = 1
pos = start + 1
block = ""
while pos < len(full) and depth > 0:
if full[pos] == "{":
depth += 1
elif full[pos] == "}":
depth -= 1
block += full[pos]
pos += 1
if "default" not in block:
violations.append(self._violation(
filepath, line_num, 1,
"switch statement has no default case.",
))
return violations
class CStyleCommentChecker(RuleChecker):
def check(self, filepath, lines, stripped):
violations = []
in_block = False
for i, line in enumerate(lines):
safe = strip_string_literals(line)
j = 0
while j < len(safe):
if in_block:
if safe[j : j + 2] == "*/":
in_block = False
j += 2
continue
j += 1
else:
if safe[j : j + 2] == "//":
break
if safe[j : j + 2] == "/*":
violations.append(self._violation(
filepath, i + 1, j + 1,
"Use C++ style comments (//) instead of "
"C-style (/* */).",
))
in_block = True
j += 2
continue
j += 1
return violations
class MagicNumberChecker(RuleChecker):
def check(self, filepath, lines, stripped):
allowed = set(self.params.get("allowed_values", [0, 1, 2, -1]))
violations = []
# Match integer and float literals
num_pat = re.compile(
r"(?<![.\w])(-?\d+\.?\d*(?:[eE][+-]?\d+)?)[UuLlFf]*(?![.\w])"
)
for i, line in enumerate(stripped):
safe = strip_string_literals(line)
# Skip preprocessor lines, const/constexpr defs, enum/case
trimmed = safe.strip()
if trimmed.startswith("#"):
continue
if re.match(r".*(?:enum|case)\b", safe):
continue
if re.search(r"\b(?:constexpr|const)\b", safe):
continue
if re.match(r"\s*\w+\s*=\s*\d", trimmed):
# Enumerator or initializer in enum/struct
continue
for m in num_pat.finditer(safe):
try:
val = float(m.group(1))
except ValueError:
continue
if val in allowed:
continue
# Skip hex constants (handled elsewhere)
prefix_start = max(0, m.start() - 2)
if "0x" in safe[prefix_start : m.start() + 2]:
continue
# Skip inside array subscripts [N]
if m.start() > 0 and safe[m.start() - 1] == "[":
continue
violations.append(self._violation(
filepath, i + 1, m.start() + 1,
f"Magic number {m.group(0)}. Use a named constant.",
))
return violations
class NoCStyleCastChecker(RuleChecker):
"""Detect C-style casts: (type)expr. Ignores (void) casts."""
def check(self, filepath, lines, stripped):
violations = []
# Heuristic: (type_name) followed by expression
cast_pat = re.compile(
r"\(\s*((?:unsigned\s+|signed\s+|const\s+|volatile\s+)*"
r"(?:int|short|long|char|float|double|bool"
r"|u?int\d+_t|size_t|ptrdiff_t|\w+_t))\s*\*?\s*\)"
r"\s*[\w(]"
)
for i, line in enumerate(stripped):
safe = strip_string_literals(line)
for m in cast_pat.finditer(safe):
# Skip (void) casts: standard idiom for unused variables
cast_type = m.group(1).strip()
if cast_type == "void":
continue
if not is_in_comment(lines[i], m.start()):
violations.append(self._violation(
filepath, i + 1, m.start() + 1,
f"C-style cast detected. Use static_cast, "
f"reinterpret_cast, or const_cast.",
))
return violations
class DefineOnlyForGuardsChecker(RuleChecker):
def check(self, filepath, lines, stripped):
violations = []
for i, line in enumerate(stripped):
m = re.match(r"\s*#\s*define\s+(\w+)", line)
if not m:
continue
name = m.group(1)
# Allow include guards
if i > 0:
prev = stripped[i - 1].strip()
if re.match(r"#\s*ifndef\s+" + re.escape(name), prev):
continue
# Allow header-style guard names (all caps with _H suffix)
if re.match(r"^[A-Z_]+_H$", name):
continue
violations.append(self._violation(
filepath, i + 1, 1,
f"#define '{name}' should be replaced with constexpr "
f"or inline function.",
))
return violations
# =============================================================================
# Linter Engine
# =============================================================================
class JSFLinter:
"""Main linter that loads rules from YAML and runs checkers."""
# Map from YAML rule key to checker class.
CHECKER_MAP = {
# Complexity
"max_function_length": MaxFunctionLengthChecker,
"max_function_args": MaxFunctionArgsChecker,
"max_line_length": MaxLineLengthChecker,
# Prohibited features (pattern-based)
"no_goto": PatternChecker,
"no_continue": PatternChecker,
"no_exceptions": PatternChecker,
"no_unions": PatternChecker,
"no_errno": PatternChecker,
"no_setjmp_longjmp": PatternChecker,
"no_signal_h": PatternChecker,
"no_stdio": PatternChecker,
"no_atoi_atof": PatternChecker,
"no_abort_exit": PatternChecker,
"no_register": PatternChecker,
# Type safety
"no_raw_int_types": PatternChecker,
"no_c_style_casts": NoCStyleCastChecker,
"no_octal_constants": PatternChecker,
"hex_uppercase": PatternChecker,
"literal_suffix_uppercase": PatternChecker,
# Memory safety
"no_malloc_free": PatternChecker,
"no_raw_new_delete": PatternChecker,
"volatile_only_for_hardware": PatternChecker,
# Control flow
"braces_required": BracesRequiredChecker,
"switch_default_required": SwitchDefaultChecker,
"no_float_loop_counter": PatternChecker,
# Style
"no_tabs": NoTabsChecker,
"no_magic_numbers": MagicNumberChecker,
"no_identifier_leading_underscore": PatternChecker,
"include_guard_required": IncludeGuardChecker,
"cpp_comments_only": CStyleCommentChecker,
# Embedded
"define_only_for_guards": DefineOnlyForGuardsChecker,
}
def __init__(self, config_path: str):
with open(config_path, "r") as f:
self.config = yaml.safe_load(f)
self.checkers = self._build_checkers()
self.extensions = set(
self.config.get("meta", {}).get(
"file_extensions", [".cpp", ".h", ".hpp", ".c"]
)
)
self.suppression_marker = (
self.config.get("suppressions", {}).get("inline_marker", "NOLINT")
)
self.excluded_paths = self.config.get("suppressions", {}).get(
"excluded_paths", []
)
def _build_checkers(self) -> list[RuleChecker]:
checkers = []
for category_key, category_val in self.config.items():
if not isinstance(category_val, dict):
continue
if category_key in ("meta", "suppressions"):
continue
for rule_key, rule_conf in category_val.items():
if not isinstance(rule_conf, dict):
continue
if not rule_conf.get("enabled", True):
continue
checker_cls = self.CHECKER_MAP.get(rule_key)
if checker_cls:
checkers.append(checker_cls(rule_key, rule_conf))
return checkers
def _is_excluded(self, filepath: str) -> bool:
for excl in self.excluded_paths:
if excl in filepath:
return True
return False
def lint_file(self, filepath: str) -> list[Violation]:
if self._is_excluded(filepath):
return []
ext = Path(filepath).suffix
if ext not in self.extensions:
return []
with open(filepath, "r", errors="replace") as f:
lines = f.readlines()
stripped = strip_comments(lines)
all_violations = []
for checker in self.checkers:
violations = checker.check(filepath, lines, stripped)
# Apply inline suppressions
for v in violations:
if v.line <= len(lines):
original = lines[v.line - 1]
if not has_nolint(
original, v.rule_id, self.suppression_marker
):
all_violations.append(v)
all_violations.sort(key=lambda v: (v.file, v.line, v.column))
return all_violations
def lint_path(self, target: str) -> LintResult:
result = LintResult()
target_path = Path(target)
if target_path.is_file():
files = [str(target_path)]
elif target_path.is_dir():
files = []
for ext in self.extensions:
files.extend(
str(p) for p in target_path.rglob(f"*{ext}")
)
else:
print(f"Error: {target} not found.", file=sys.stderr)
sys.exit(1)
for fpath in sorted(files):
result.files_checked += 1
violations = self.lint_file(fpath)
result.violations.extend(violations)
for v in result.violations:
if v.severity == "error":
result.errors += 1
elif v.severity == "warning":
result.warnings += 1
else:
result.infos += 1
return result
# =============================================================================
# Output Formatting
# =============================================================================
def print_results(result: LintResult, fmt: str) -> None:
if fmt == "json":
output = {
"files_checked": result.files_checked,
"errors": result.errors,
"warnings": result.warnings,
"infos": result.infos,
"violations": [v.to_dict() for v in result.violations],
}
print(json.dumps(output, indent=2))
elif fmt == "github":
for v in result.violations:
print(v.to_github())
else:
for v in result.violations:
print(v.to_text())
print()
print(
f"Checked {result.files_checked} file(s): "
f"{result.errors} error(s), "
f"{result.warnings} warning(s), "
f"{result.infos} info(s)"
)
# =============================================================================
# Entry Point
# =============================================================================
def find_config(explicit: Optional[str]) -> str:
"""Locate the rules config file."""
if explicit:
return explicit
# Search upward from CWD
search = Path.cwd()
for _ in range(10):
candidate = search / "linter_rules.yaml"
if candidate.exists():
return str(candidate)
candidate = search / ".jsflint.yaml"
if candidate.exists():
return str(candidate)
parent = search.parent
if parent == search:
break
search = parent
# Default to script directory
script_dir = Path(__file__).parent
default = script_dir / "linter_rules.yaml"
if default.exists():
return str(default)
print("Error: No linter_rules.yaml found.", file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(
description="JSF AV C++ Linter for Embedded AI projects"
)
parser.add_argument(
"target",
help="File or directory to lint",
)
parser.add_argument(
"--config", "-c",
help="Path to linter_rules.yaml (auto-detected if omitted)",
default=None,
)
parser.add_argument(
"--format", "-f",
choices=["text", "json", "github"],
default="text",
help="Output format (default: text)",
)
parser.add_argument(
"--error-exit",
action="store_true",
help="Exit with code 1 if any errors found",
)
parser.add_argument(
"--version", "-V",
action="version",
version=f"jsf_lint {__version__}",
)
args = parser.parse_args()
config_path = find_config(args.config)
linter = JSFLinter(config_path)
result = linter.lint_path(args.target)
print_results(result, args.format)
if args.error_exit and result.errors > 0:
sys.exit(1)
if __name__ == "__main__":
main()