svlang-lint 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: svlang-lint
3
+ Version: 0.7.0
4
+ Summary: Python Plugin SDK for svlang-lint Static Linter
5
+ Author-email: Mayur Kubavat <mkubavat01@gmail.com>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # `svlang-lint` — Python Plugin SDK
11
+
12
+ Python plugin SDK for authoring custom SystemVerilog and UVM static lint rules, configuration models, and SARIF/HTML/JSON reports on top of [`svlang`](https://github.com/mayurkubavat/svlang).
13
+
14
+ ## Quickstart
15
+
16
+ ```python
17
+ from svlang_lint import Rule, Severity, Violation
18
+
19
+ class NoMagicTimeout(Rule):
20
+ rule_id = "USR-TIM-001"
21
+ severity = Severity.WARNING
22
+ ```
23
+
24
+ ## CLI Entry Points
25
+
26
+ - `svlang-lint-plugins` — run custom Python lint rules against a `svlang` design model.
27
+ - `svlang-lint-report` — generate formatted reports from `svlang lint --format json` output.
28
+
29
+ ## License
30
+
31
+ Apache-2.0
@@ -0,0 +1,22 @@
1
+ # `svlang-lint` — Python Plugin SDK
2
+
3
+ Python plugin SDK for authoring custom SystemVerilog and UVM static lint rules, configuration models, and SARIF/HTML/JSON reports on top of [`svlang`](https://github.com/mayurkubavat/svlang).
4
+
5
+ ## Quickstart
6
+
7
+ ```python
8
+ from svlang_lint import Rule, Severity, Violation
9
+
10
+ class NoMagicTimeout(Rule):
11
+ rule_id = "USR-TIM-001"
12
+ severity = Severity.WARNING
13
+ ```
14
+
15
+ ## CLI Entry Points
16
+
17
+ - `svlang-lint-plugins` — run custom Python lint rules against a `svlang` design model.
18
+ - `svlang-lint-report` — generate formatted reports from `svlang lint --format json` output.
19
+
20
+ ## License
21
+
22
+ Apache-2.0
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "svlang-lint"
7
+ version = "0.7.0"
8
+ description = "Python Plugin SDK for svlang-lint Static Linter"
9
+ readme = "README.md"
10
+ authors = [{ name = "Mayur Kubavat", email = "mkubavat01@gmail.com" }]
11
+ license = { text = "Apache-2.0" }
12
+ requires-python = ">=3.9"
13
+ dependencies = []
14
+
15
+ [project.scripts]
16
+ svlang-lint-plugins = "svlang_lint.plugin_runner:main"
17
+ svlang-lint-report = "svlang_lint.report:main"
18
+
19
+ # Only the SDK is packaged; examples/ and tests/ stay in the repository.
20
+ [tool.setuptools]
21
+ packages = ["svlang_lint"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ """
2
+ svlang-lint Python Plugin SDK
3
+ Enables verification teams to author custom SystemVerilog and UVM lint rules in Python.
4
+ """
5
+
6
+ from .rule import Fix, FixSafety, Rule, Severity, Violation
7
+ from .context import (Context, ClassInfo, MemberInfo, MethodInfo, PropertyInfo, CallInfo,
8
+ Argument, ConfigDbAccess, TlmPort, TlmConnection)
9
+ from .config import ProjectConfig, RuleConfig, Waiver, ConfigError
10
+
11
+ __version__ = "0.7.0"
12
+ __all__ = [
13
+ "Rule",
14
+ "Severity",
15
+ "Fix",
16
+ "FixSafety",
17
+ "Violation",
18
+ "Context",
19
+ "ClassInfo",
20
+ "MemberInfo",
21
+ "MethodInfo",
22
+ "PropertyInfo",
23
+ "CallInfo",
24
+ "Argument",
25
+ "ConfigDbAccess",
26
+ "TlmPort",
27
+ "TlmConnection",
28
+ "ProjectConfig",
29
+ "RuleConfig",
30
+ "Waiver",
31
+ "ConfigError",
32
+ ]
@@ -0,0 +1,419 @@
1
+ """
2
+ svlang-lint project configuration, written as plain Python classes.
3
+
4
+ A project config is a ``ProjectConfig`` subclass. Rule settings are
5
+ ``RuleConfig`` subclasses attached to it, and waivers are ``Waiver`` objects.
6
+ Because everything is a class, teams can share a base config and override
7
+ just the parts they need:
8
+
9
+ from svlang_lint.config import ProjectConfig, RuleConfig, Waiver, Severity
10
+
11
+ class CompanyBase(ProjectConfig):
12
+ library_paths = ["$UVM_HOME", "vip/**"]
13
+
14
+ class MaxLineLength(RuleConfig):
15
+ max_columns = 120
16
+
17
+ class MyBlock(CompanyBase):
18
+ exclude_paths = ["**/generated/**"]
19
+
20
+ class MaxLineLength(CompanyBase.MaxLineLength):
21
+ max_columns = 140 # override one option, keep the rest
22
+
23
+ waivers = CompanyBase.waivers + [
24
+ Waiver("UVM-OBJ-002", path="tb/stress_seq.sv", line=142,
25
+ reason="Objection in loop verified for stress bench"),
26
+ ]
27
+
28
+ class LegacyMacros(Waiver): # reusable, subclassable waiver
29
+ rules = ["SVL-STY-001"]
30
+ paths = ["**/legacy/**"]
31
+ reason = "Vendor macros we cannot edit"
32
+ expires = "2027-06-30"
33
+
34
+ The C++ engine runs this file through ``python3 -m svlang_lint.config_runner``,
35
+ which serializes the selected config to JSON with ``to_dict()``.
36
+ """
37
+
38
+ import datetime
39
+ import importlib.util
40
+ import inspect
41
+ import os
42
+ import re
43
+ import sys
44
+ from typing import Any, Dict, List, Optional, Union
45
+
46
+ from .rule import Severity
47
+
48
+ __all__ = ["ProjectConfig", "RuleConfig", "Waiver", "Severity", "ConfigError", "parent_project"]
49
+
50
+
51
+ class ConfigError(Exception):
52
+ """Raised for a config that is well-formed Python but not a valid svlang-lint config."""
53
+
54
+
55
+ def _severity_name(value: Union[Severity, str, None]) -> Optional[str]:
56
+ if value is None:
57
+ return None
58
+ if isinstance(value, Severity):
59
+ return value.value.upper()
60
+ name = str(value).strip().upper()
61
+ if name not in ("ERROR", "WARNING", "INFO"):
62
+ raise ConfigError(f"unknown severity {value!r}; use Severity.Error, Severity.Warning or Severity.Info")
63
+ return name
64
+
65
+
66
+ def _path_list(owner: str, attr: str, value: Any) -> List[str]:
67
+ if isinstance(value, str):
68
+ return [value]
69
+ if not isinstance(value, (list, tuple)) or not all(isinstance(p, str) for p in value):
70
+ raise ConfigError(f"{owner}.{attr} must be a list of path strings")
71
+ return list(value)
72
+
73
+
74
+ class RuleConfig:
75
+ """Settings for one rule.
76
+
77
+ The rule is identified by ``rule`` (an ID such as ``"SVL-STY-013"`` or a
78
+ name such as ``"MaxLineLength"``); when ``rule`` is not set, the class name
79
+ is used. Any other public class attribute becomes a rule option that the
80
+ rule reads at run time (for example ``max_columns`` on MaxLineLength).
81
+ """
82
+
83
+ rule: Optional[str] = None
84
+ enabled: bool = True
85
+ severity: Optional[Severity] = None
86
+ exclude_paths: List[str] = []
87
+ only_paths: List[str] = []
88
+
89
+ _RESERVED = ("rule", "enabled", "severity", "exclude_paths", "only_paths")
90
+
91
+ @classmethod
92
+ def rule_key(cls) -> str:
93
+ return cls.rule or cls.__name__
94
+
95
+ @classmethod
96
+ def options(cls) -> Dict[str, Any]:
97
+ """Collect option attributes across the class hierarchy (subclasses win)."""
98
+ opts: Dict[str, Any] = {}
99
+ for klass in reversed(cls.__mro__):
100
+ if klass is object or klass is RuleConfig:
101
+ continue
102
+ for key, value in vars(klass).items():
103
+ if key.startswith("_") or key in RuleConfig._RESERVED:
104
+ continue
105
+ if callable(value) or isinstance(value, (classmethod, staticmethod, property)):
106
+ continue
107
+ if not isinstance(value, (bool, int, float, str)):
108
+ raise ConfigError(
109
+ f"{cls.__qualname__}.{key}: rule options must be bool, int, float or str")
110
+ opts[key] = value
111
+ return opts
112
+
113
+ @classmethod
114
+ def to_dict(cls) -> Dict[str, Any]:
115
+ out: Dict[str, Any] = {"enabled": bool(cls.enabled)}
116
+ sev = _severity_name(cls.severity)
117
+ if sev:
118
+ out["severity"] = sev
119
+ paths = _path_list(cls.__qualname__, "exclude_paths", cls.exclude_paths)
120
+ if paths:
121
+ out["exclude_paths"] = paths
122
+ only = _path_list(cls.__qualname__, "only_paths", cls.only_paths)
123
+ if only:
124
+ out["only_paths"] = only
125
+ opts = cls.options()
126
+ if opts:
127
+ out["options"] = opts
128
+ return out
129
+
130
+
131
+ class Waiver:
132
+ """An approved exception. ``reason`` is mandatory so every waiver is reviewable.
133
+
134
+ Write one inline:
135
+
136
+ Waiver("UVM-OBJ-002", path="tb/stress_seq.sv", line=142, reason="...")
137
+
138
+ or as a class, which can be shared and subclassed:
139
+
140
+ class LegacyMacros(Waiver):
141
+ rules = ["SVL-STY-001", "SVL-STY-009"]
142
+ paths = ["**/legacy/**"]
143
+ reason = "Vendor macros we cannot edit"
144
+ owner = "dv-infra"
145
+ expires = "2027-06-30"
146
+ message = "trailing semicolon"
147
+ severity = Severity.Info # keep reporting, at a lower severity
148
+
149
+ ``rules`` / ``paths`` default to every rule / every file; ``line`` to any
150
+ line. ``paths`` use the same glob syntax as ``library_paths``. ``message``,
151
+ when set, is a regular expression searched against the diagnostic text; the
152
+ waiver applies only when it matches. With ``severity`` the finding is not
153
+ hidden but reported at that severity, with "[re-graded by ...]" after its
154
+ message. A waiver past its ``expires`` date (YYYY-MM-DD) stops applying
155
+ and is reported.
156
+ """
157
+
158
+ rules: List[str] = []
159
+ paths: List[str] = []
160
+ line: Optional[int] = None
161
+ reason: str = ""
162
+ owner: Optional[str] = None
163
+ expires: Optional[str] = None
164
+ message: Optional[str] = None
165
+ severity: Union[Severity, str, None] = None
166
+
167
+ def __init__(self, rule: Optional[str] = None, *, reason: Optional[str] = None,
168
+ path: Optional[str] = None, line: Optional[int] = None,
169
+ rules: Optional[List[str]] = None, paths: Optional[List[str]] = None,
170
+ owner: Optional[str] = None, expires: Optional[str] = None,
171
+ message: Optional[str] = None, severity: Union[Severity, str, None] = None):
172
+ if rule is not None:
173
+ self.rules = [rule]
174
+ if rules is not None:
175
+ self.rules = list(rules)
176
+ if path is not None:
177
+ self.paths = [path]
178
+ if paths is not None:
179
+ self.paths = list(paths)
180
+ if line is not None:
181
+ self.line = line
182
+ if reason is not None:
183
+ self.reason = reason
184
+ if owner is not None:
185
+ self.owner = owner
186
+ if expires is not None:
187
+ self.expires = expires
188
+ if message is not None:
189
+ self.message = message
190
+ if severity is not None:
191
+ self.severity = severity
192
+ self.validate()
193
+
194
+ @property
195
+ def label(self) -> str:
196
+ return type(self).__qualname__ if type(self) is not Waiver else f"Waiver({', '.join(self.rules) or '*'})"
197
+
198
+ def validate(self) -> None:
199
+ if isinstance(self.rules, str) or not all(isinstance(r, str) and r for r in self.rules):
200
+ raise ConfigError(f"{self.label}: rules must be a list of rule IDs or names")
201
+ _path_list(self.label, "paths", self.paths)
202
+ if not self.reason or not str(self.reason).strip():
203
+ raise ConfigError(f"{self.label} needs a non-empty reason")
204
+ if self.line is not None and (not isinstance(self.line, int) or self.line < 1):
205
+ raise ConfigError(f"{self.label}: line must be a positive integer")
206
+ if self.expires is not None:
207
+ try:
208
+ datetime.date.fromisoformat(str(self.expires))
209
+ except ValueError:
210
+ raise ConfigError(f"{self.label}: expires must be a YYYY-MM-DD date, got {self.expires!r}")
211
+ if self.message:
212
+ try:
213
+ re.compile(str(self.message))
214
+ except re.error as exc:
215
+ raise ConfigError(f"{self.label}: invalid message regex {self.message!r}: {exc}") from exc
216
+ try:
217
+ _severity_name(self.severity)
218
+ except ConfigError as exc:
219
+ raise ConfigError(f"{self.label}: {exc}") from None
220
+
221
+ def is_expired(self, today: Optional[datetime.date] = None) -> bool:
222
+ if self.expires is None:
223
+ return False
224
+ return datetime.date.fromisoformat(str(self.expires)) < (today or datetime.date.today())
225
+
226
+ def to_dict(self) -> Dict[str, Any]:
227
+ out: Dict[str, Any] = {"rules": list(self.rules) or ["*"], "reason": self.reason, "label": self.label}
228
+ if self.paths:
229
+ out["paths"] = list(self.paths)
230
+ if self.line:
231
+ out["line"] = self.line
232
+ if self.owner:
233
+ out["owner"] = self.owner
234
+ if self.expires:
235
+ out["expires"] = str(self.expires)
236
+ if self.message:
237
+ out["message"] = str(self.message)
238
+ if self.severity is not None:
239
+ out["severity"] = _severity_name(self.severity)
240
+ return out
241
+
242
+ def __repr__(self) -> str:
243
+ return f"{self.label}(paths={self.paths!r}, line={self.line!r})"
244
+
245
+
246
+ class ProjectConfig:
247
+ """Base class for a project config.
248
+
249
+ sources Files or globs to compile when none are given on the command
250
+ line (and around a file open in the editor).
251
+ filelists .f command files (-f style; their paths are relative to the
252
+ file list).
253
+ include_dirs +incdir directories.
254
+ defines "NAME" or "NAME=VALUE" macro definitions.
255
+ library_paths Third-party code (UVM, VIP). Compiled so your code
256
+ elaborates, but violations inside it are not reported.
257
+ exclude_paths Your own files that should not be linted (generated code).
258
+ report_library_macro_expansions
259
+ False (default): code expanded from a library macro, such as
260
+ `uvm_object_utils in your class, counts as library code.
261
+ preset The rule set when --preset is not given: "default"
262
+ (soundness, methodology, performance, security), "all",
263
+ "style", ... A rule you configure below runs whatever
264
+ the preset.
265
+ waivers List of Waiver objects or Waiver subclasses.
266
+ style, naming Optional dicts with the same keys as the JSON config.
267
+ compat Legacy compatibility dictionary accepted for backwards
268
+ compatibility with older configs (ignored by the native
269
+ Rust engine).
270
+
271
+ Rule settings are RuleConfig subclasses defined in (or assigned to) the
272
+ class body. Subclasses inherit them and may replace one by defining a
273
+ RuleConfig with the same rule key. Override ``rule_configs()`` or
274
+ ``to_dict()`` for anything more dynamic.
275
+ """
276
+
277
+ sources: List[str] = []
278
+ filelists: List[str] = []
279
+ include_dirs: List[str] = []
280
+ defines: List[str] = []
281
+ library_paths: List[str] = []
282
+ exclude_paths: List[str] = []
283
+ report_library_macro_expansions: bool = False
284
+ preset: str = ""
285
+ waivers: List[Waiver] = []
286
+ style: Dict[str, Any] = {}
287
+ naming: Dict[str, Any] = {}
288
+ compat: Dict[str, Any] = {}
289
+
290
+ def rule_configs(self) -> List[type]:
291
+ """All RuleConfig classes visible on this config, most-derived wins per rule key."""
292
+ by_key: Dict[str, type] = {}
293
+ for klass in reversed(type(self).__mro__):
294
+ for value in vars(klass).values():
295
+ if inspect.isclass(value) and issubclass(value, RuleConfig) and value is not RuleConfig:
296
+ by_key[value.rule_key()] = value
297
+ return list(by_key.values())
298
+
299
+ def to_dict(self) -> Dict[str, Any]:
300
+ name = type(self).__qualname__
301
+ out: Dict[str, Any] = {
302
+ "library_paths": _path_list(name, "library_paths", self.library_paths),
303
+ "exclude_paths": _path_list(name, "exclude_paths", self.exclude_paths),
304
+ "report_library_macro_expansions": bool(self.report_library_macro_expansions),
305
+ "rules": {rc.rule_key(): rc.to_dict() for rc in self.rule_configs()},
306
+ }
307
+ for key in ("sources", "filelists", "include_dirs", "defines"):
308
+ values = _path_list(name, key, getattr(self, key))
309
+ if values:
310
+ out[key] = values
311
+ if self.preset:
312
+ if not isinstance(self.preset, str):
313
+ raise ConfigError(f"{name}.preset must be a preset name, got {self.preset!r}")
314
+ out["preset"] = self.preset
315
+ out["waivers"] = []
316
+ warnings: List[str] = []
317
+ for w in self.waivers:
318
+ if inspect.isclass(w) and issubclass(w, Waiver):
319
+ w = w()
320
+ if not isinstance(w, Waiver):
321
+ raise ConfigError(f"{name}.waivers must contain Waiver objects or classes, got {w!r}")
322
+ if w.is_expired():
323
+ owner = f" (owner: {w.owner})" if w.owner else ""
324
+ warnings.append(f"waiver {w.label} expired on {w.expires}{owner}; it no longer applies")
325
+ out.setdefault("expired_waivers", []).append(f"{w.label} expired {w.expires}{owner}")
326
+ continue
327
+ out["waivers"].append(w.to_dict())
328
+ if warnings:
329
+ out["warnings"] = warnings
330
+ if self.style:
331
+ out["style"] = dict(self.style)
332
+ if self.naming:
333
+ out["naming"] = dict(self.naming)
334
+ if self.compat:
335
+ out["compat"] = dict(self.compat)
336
+ return out
337
+
338
+
339
+ # ---------------------------------------------------------------------------
340
+ # Layered configs: a sub-tree (a VIP, a block-level env) can keep its own
341
+ # .svlang-lint/config.py and build on the project's:
342
+ #
343
+ # from svlang_lint.config import parent_project
344
+ #
345
+ # class BlockEnv(parent_project()):
346
+ # exclude_paths = parent_project().exclude_paths + ["gen/**"]
347
+ #
348
+ # The loader sets the path of the config being loaded; parent_project() finds
349
+ # the next .svlang-lint/config.py further up and returns its project class with
350
+ # its relative paths made absolute, so they keep pointing where the parent
351
+ # meant them to.
352
+
353
+ _loading: List[str] = [] # stack of config files being loaded (absolute)
354
+ _loaded_layers: List[str] = [] # every config file loaded for this run, child first
355
+ _parent_cache: Dict[str, type] = {}
356
+
357
+ _PATH_ATTRS = ("sources", "filelists", "include_dirs", "library_paths", "exclude_paths")
358
+
359
+
360
+ def _project_root(config_path: str) -> str:
361
+ d = os.path.dirname(os.path.abspath(config_path))
362
+ return os.path.dirname(d) if os.path.basename(d) == ".svlang-lint" else d
363
+
364
+
365
+ def _anchor(path: str, root: str) -> str:
366
+ """Absolute form of a relative path; env-var, home, absolute and bare-name globs stay as written."""
367
+ if not path or path.startswith(("$", "~", "/")) or "/" not in path:
368
+ return path
369
+ return os.path.normpath(os.path.join(root, path))
370
+
371
+
372
+ def _anchored_class(cls: type, root: str) -> type:
373
+ """A subclass of a parent project whose relative paths are absolute."""
374
+ attrs: Dict[str, Any] = {}
375
+ for name in _PATH_ATTRS:
376
+ value = getattr(cls, name, [])
377
+ if isinstance(value, str):
378
+ value = [value]
379
+ attrs[name] = [_anchor(p, root) for p in value]
380
+ waivers = []
381
+ for w in getattr(cls, "waivers", []):
382
+ if inspect.isclass(w) and issubclass(w, Waiver):
383
+ w = w()
384
+ if isinstance(w, Waiver) and w.paths:
385
+ w = Waiver(rules=list(w.rules), paths=[_anchor(p, root) for p in w.paths], line=w.line,
386
+ reason=w.reason, owner=w.owner, expires=w.expires, message=w.message,
387
+ severity=w.severity)
388
+ waivers.append(w)
389
+ attrs["waivers"] = waivers
390
+ for rc in cls().rule_configs():
391
+ if rc.exclude_paths or rc.only_paths:
392
+ attrs[rc.__name__] = type(rc.__name__, (rc,), {
393
+ "rule": rc.rule_key(),
394
+ "exclude_paths": [_anchor(p, root) for p in rc.exclude_paths],
395
+ "only_paths": [_anchor(p, root) for p in rc.only_paths]})
396
+ return type(cls.__name__, (cls,), attrs)
397
+
398
+
399
+ def parent_project() -> type:
400
+ """The project class of the nearest .svlang-lint/config.py above this one."""
401
+ if not _loading:
402
+ raise ConfigError("parent_project() can only be called from a config being loaded by svlang-lint")
403
+ current = _loading[-1]
404
+ if current in _parent_cache:
405
+ return _parent_cache[current]
406
+ start = os.path.dirname(_project_root(current))
407
+ d = start
408
+ while True:
409
+ candidate = os.path.join(d, ".svlang-lint", "config.py")
410
+ if os.path.isfile(candidate) and os.path.abspath(candidate) != current:
411
+ break
412
+ parent = os.path.dirname(d)
413
+ if parent == d:
414
+ raise ConfigError(f"parent_project(): no .svlang-lint/config.py above {_project_root(current)}")
415
+ d = parent
416
+ from .config_runner import load_config_class # late import: the runner imports this module
417
+ cls = _anchored_class(load_config_class(candidate), _project_root(candidate))
418
+ _parent_cache[current] = cls
419
+ return cls
@@ -0,0 +1,105 @@
1
+ """
2
+ Loads a Python project config and writes it as JSON for the C++ engine.
3
+
4
+ python3 -m svlang_lint.config_runner --config .svlang-lint/config.py --out cfg.json
5
+
6
+ The config file may define ``config = SomeProject()`` explicitly. Otherwise the
7
+ runner picks the single most-derived ProjectConfig subclass defined in the
8
+ file (base classes imported from shared files are not candidates).
9
+ """
10
+
11
+ import argparse
12
+ import importlib.util
13
+ import inspect
14
+ import json
15
+ import os
16
+ import sys
17
+ import traceback
18
+
19
+ from . import config as config_module
20
+ from .config import ConfigError, ProjectConfig
21
+
22
+
23
+ def load_config(path: str) -> ProjectConfig:
24
+ explicit = load_config_class(path)
25
+ return explicit if isinstance(explicit, ProjectConfig) else explicit()
26
+
27
+
28
+ def load_config_class(path: str):
29
+ """The selected ProjectConfig class of a config file (or the instance it names)."""
30
+ path = os.path.abspath(path)
31
+ config_module._loaded_layers.append(path)
32
+ config_module._loading.append(path)
33
+ try:
34
+ return _load(path)
35
+ finally:
36
+ config_module._loading.pop()
37
+
38
+
39
+ def _load(path: str):
40
+ config_dir = os.path.dirname(path)
41
+ # Let configs import shared team bases sitting next to them.
42
+ if config_dir not in sys.path:
43
+ sys.path.insert(0, config_dir)
44
+ # If config is in a directory-scoped environment (.svlang-lint/), also add the project
45
+ # root (parent directory) so config.py can import repo packages and modules.
46
+ if os.path.basename(config_dir) == ".svlang-lint":
47
+ parent_dir = os.path.dirname(config_dir)
48
+ if parent_dir and parent_dir not in sys.path:
49
+ sys.path.insert(1, parent_dir)
50
+
51
+ # Unique per file, so a layered config and its parent do not replace each other.
52
+ module_name = "_svlang_lint_project_config_%d" % len(config_module._loaded_layers)
53
+ spec = importlib.util.spec_from_file_location(module_name, path)
54
+ if not spec or not spec.loader:
55
+ raise ConfigError(f"cannot import {path}")
56
+ module = importlib.util.module_from_spec(spec)
57
+ sys.modules[module_name] = module
58
+ spec.loader.exec_module(module)
59
+
60
+ explicit = getattr(module, "config", None)
61
+ if explicit is not None:
62
+ if inspect.isclass(explicit) and issubclass(explicit, ProjectConfig):
63
+ return explicit
64
+ if isinstance(explicit, ProjectConfig):
65
+ return explicit
66
+ raise ConfigError("'config' must be a ProjectConfig subclass or instance")
67
+
68
+ local = [obj for _, obj in inspect.getmembers(module, inspect.isclass)
69
+ if issubclass(obj, ProjectConfig) and obj is not ProjectConfig
70
+ and obj.__module__ == module_name]
71
+ leaves = [c for c in local if not any(o is not c and issubclass(o, c) for o in local)]
72
+ if not leaves:
73
+ raise ConfigError("no ProjectConfig subclass found; define one or set 'config = MyProject'")
74
+ if len(leaves) > 1:
75
+ names = ", ".join(sorted(c.__name__ for c in leaves))
76
+ raise ConfigError(f"several ProjectConfig classes found ({names}); set 'config = <one of them>'")
77
+ return leaves[0]
78
+
79
+
80
+ def main() -> int:
81
+ parser = argparse.ArgumentParser(description="svlang-lint Python config loader")
82
+ parser.add_argument("--config", required=True, help="Path to the Python config file")
83
+ parser.add_argument("--out", required=True, help="Where to write the JSON form")
84
+ args = parser.parse_args()
85
+
86
+ try:
87
+ cfg = load_config(args.config)
88
+ data = cfg.to_dict()
89
+ data["source"] = type(cfg).__qualname__
90
+ if len(config_module._loaded_layers) > 1:
91
+ data["layers"] = list(config_module._loaded_layers)
92
+ except ConfigError as e:
93
+ sys.stderr.write(f"{args.config}: {e}\n")
94
+ return 1
95
+ except Exception:
96
+ sys.stderr.write(traceback.format_exc())
97
+ return 1
98
+
99
+ with open(args.out, "w") as f:
100
+ json.dump(data, f, indent=2)
101
+ return 0
102
+
103
+
104
+ if __name__ == "__main__":
105
+ sys.exit(main())