ramplint 0.1.0__py3-none-any.whl
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.
- ramplint/__init__.py +16 -0
- ramplint/__main__.py +5 -0
- ramplint/cli.py +134 -0
- ramplint/config.py +61 -0
- ramplint/dom.py +152 -0
- ramplint/linter.py +115 -0
- ramplint/py.typed +0 -0
- ramplint/reporters.py +74 -0
- ramplint/rules/__init__.py +38 -0
- ramplint/rules/base.py +33 -0
- ramplint/rules/controls.py +59 -0
- ramplint/rules/document.py +25 -0
- ramplint/rules/forms.py +56 -0
- ramplint/rules/headings.py +45 -0
- ramplint/rules/images.py +38 -0
- ramplint/rules/names.py +50 -0
- ramplint/rules/tables.py +58 -0
- ramplint/template.py +149 -0
- ramplint-0.1.0.dist-info/METADATA +317 -0
- ramplint-0.1.0.dist-info/RECORD +23 -0
- ramplint-0.1.0.dist-info/WHEEL +4 -0
- ramplint-0.1.0.dist-info/entry_points.txt +2 -0
- ramplint-0.1.0.dist-info/licenses/LICENSE +21 -0
ramplint/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""ramplint - accessibility linter for Django and Jinja2 templates."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from ramplint.linter import Violation, iter_template_files, lint_file, lint_source # noqa: E402
|
|
6
|
+
from ramplint.rules import all_rules, select_rules # noqa: E402
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"__version__",
|
|
10
|
+
"Violation",
|
|
11
|
+
"all_rules",
|
|
12
|
+
"iter_template_files",
|
|
13
|
+
"lint_file",
|
|
14
|
+
"lint_source",
|
|
15
|
+
"select_rules",
|
|
16
|
+
]
|
ramplint/__main__.py
ADDED
ramplint/cli.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ramplint import __version__
|
|
10
|
+
from ramplint.config import ConfigError, load_config
|
|
11
|
+
from ramplint.linter import DEFAULT_EXTENSIONS, Violation, iter_template_files, lint_file
|
|
12
|
+
from ramplint.reporters import report_github, report_json, report_text
|
|
13
|
+
from ramplint.rules import all_rules, select_rules, unknown_selectors
|
|
14
|
+
|
|
15
|
+
EXIT_OK = 0
|
|
16
|
+
EXIT_VIOLATIONS = 1
|
|
17
|
+
EXIT_ERROR = 2
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _csv(value: str) -> list[str]:
|
|
21
|
+
return [item.strip() for item in value.split(",") if item.strip()]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
prog="ramplint",
|
|
27
|
+
description="Accessibility linter for Django and Jinja2 templates.",
|
|
28
|
+
)
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"paths", nargs="*", default=["."], help="files or directories to lint (default: .)"
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"--select",
|
|
34
|
+
type=_csv,
|
|
35
|
+
metavar="RULES",
|
|
36
|
+
help="comma-separated rule codes, code prefixes or names to enable (e.g. RL1,link-name)",
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--ignore", type=_csv, metavar="RULES", help="comma-separated rules to disable"
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--exclude",
|
|
43
|
+
action="append",
|
|
44
|
+
default=[],
|
|
45
|
+
metavar="GLOB",
|
|
46
|
+
help="glob pattern of paths to skip; may be repeated",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
"--extensions",
|
|
50
|
+
type=_csv,
|
|
51
|
+
metavar="EXTS",
|
|
52
|
+
help=f"file extensions to lint (default: {','.join(DEFAULT_EXTENSIONS)})",
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument(
|
|
55
|
+
"--format",
|
|
56
|
+
choices=("text", "json", "github"),
|
|
57
|
+
default=None,
|
|
58
|
+
help="output format (default: text, or github when running in GitHub Actions)",
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument("--config", type=Path, metavar="PATH", help="path to a pyproject.toml")
|
|
61
|
+
parser.add_argument("--no-color", action="store_true", help="disable colored output")
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"--exit-zero", action="store_true", help="exit with 0 even if problems are found"
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument("--list-rules", action="store_true", help="list available rules and exit")
|
|
66
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
67
|
+
return parser
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _list_rules() -> None:
|
|
71
|
+
for rule in all_rules():
|
|
72
|
+
print(f"{rule.code} {rule.name:<15} {rule.summary} [WCAG {rule.wcag}]")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _use_color(no_color: bool) -> bool:
|
|
76
|
+
if no_color or os.environ.get("NO_COLOR"):
|
|
77
|
+
return False
|
|
78
|
+
if os.environ.get("FORCE_COLOR"):
|
|
79
|
+
return True
|
|
80
|
+
return sys.stdout.isatty()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
84
|
+
parser = build_parser()
|
|
85
|
+
args = parser.parse_args(argv)
|
|
86
|
+
|
|
87
|
+
if args.list_rules:
|
|
88
|
+
_list_rules()
|
|
89
|
+
return EXIT_OK
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
config = load_config(args.config)
|
|
93
|
+
except ConfigError as exc:
|
|
94
|
+
print(f"ramplint: error: {exc}", file=sys.stderr)
|
|
95
|
+
return EXIT_ERROR
|
|
96
|
+
|
|
97
|
+
select = args.select if args.select is not None else config.select
|
|
98
|
+
ignore = (config.ignore or []) + (args.ignore or [])
|
|
99
|
+
unknown = unknown_selectors([*select, *ignore])
|
|
100
|
+
if unknown:
|
|
101
|
+
print(f"ramplint: error: unknown rule(s): {', '.join(unknown)}", file=sys.stderr)
|
|
102
|
+
return EXIT_ERROR
|
|
103
|
+
rules = select_rules(select, ignore)
|
|
104
|
+
|
|
105
|
+
extensions = args.extensions or config.extensions or list(DEFAULT_EXTENSIONS)
|
|
106
|
+
exclude = [*config.exclude, *args.exclude]
|
|
107
|
+
|
|
108
|
+
violations: list[Violation] = []
|
|
109
|
+
files_checked = 0
|
|
110
|
+
try:
|
|
111
|
+
for path in iter_template_files(args.paths, extensions=extensions, exclude=exclude):
|
|
112
|
+
files_checked += 1
|
|
113
|
+
violations.extend(lint_file(path, rules))
|
|
114
|
+
except FileNotFoundError as exc:
|
|
115
|
+
print(f"ramplint: error: no such file or directory: {exc}", file=sys.stderr)
|
|
116
|
+
return EXIT_ERROR
|
|
117
|
+
|
|
118
|
+
output_format = args.format or (
|
|
119
|
+
"github" if os.environ.get("GITHUB_ACTIONS") == "true" else "text"
|
|
120
|
+
)
|
|
121
|
+
if output_format == "json":
|
|
122
|
+
report_json(violations, files_checked, sys.stdout)
|
|
123
|
+
elif output_format == "github":
|
|
124
|
+
report_github(violations, files_checked, sys.stdout)
|
|
125
|
+
else:
|
|
126
|
+
report_text(violations, files_checked, sys.stdout, color=_use_color(args.no_color))
|
|
127
|
+
|
|
128
|
+
if violations and not args.exit_zero:
|
|
129
|
+
return EXIT_VIOLATIONS
|
|
130
|
+
return EXIT_OK
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
if __name__ == "__main__": # pragma: no cover
|
|
134
|
+
sys.exit(main())
|
ramplint/config.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Read settings from ``[tool.ramplint]`` in ``pyproject.toml``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
if sys.version_info >= (3, 11):
|
|
10
|
+
import tomllib
|
|
11
|
+
else: # pragma: no cover - exercised on Python < 3.11 only
|
|
12
|
+
import tomli as tomllib
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ConfigError(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Config:
|
|
21
|
+
select: list[str] = field(default_factory=list)
|
|
22
|
+
ignore: list[str] = field(default_factory=list)
|
|
23
|
+
exclude: list[str] = field(default_factory=list)
|
|
24
|
+
extensions: list[str] = field(default_factory=list)
|
|
25
|
+
source: Path | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_LIST_KEYS = ("select", "ignore", "exclude", "extensions")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def find_pyproject(start: Path) -> Path | None:
|
|
32
|
+
start = start.resolve()
|
|
33
|
+
for directory in (start, *start.parents):
|
|
34
|
+
candidate = directory / "pyproject.toml"
|
|
35
|
+
if candidate.is_file():
|
|
36
|
+
return candidate
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_config(path: Path | None = None, start: Path | None = None) -> Config:
|
|
41
|
+
"""Load config from ``path`` or the nearest ``pyproject.toml``."""
|
|
42
|
+
if path is None:
|
|
43
|
+
path = find_pyproject(start or Path.cwd())
|
|
44
|
+
if path is None:
|
|
45
|
+
return Config()
|
|
46
|
+
try:
|
|
47
|
+
with open(path, "rb") as fh:
|
|
48
|
+
data = tomllib.load(fh)
|
|
49
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
50
|
+
raise ConfigError(f"Cannot read {path}: {exc}") from exc
|
|
51
|
+
|
|
52
|
+
section = data.get("tool", {}).get("ramplint", {})
|
|
53
|
+
config = Config(source=path)
|
|
54
|
+
for key, value in section.items():
|
|
55
|
+
normalized = key.replace("_", "-")
|
|
56
|
+
if normalized not in _LIST_KEYS:
|
|
57
|
+
raise ConfigError(f"{path}: unknown option [tool.ramplint].{key}")
|
|
58
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
59
|
+
raise ConfigError(f"{path}: [tool.ramplint].{key} must be a list of strings")
|
|
60
|
+
setattr(config, normalized, list(value))
|
|
61
|
+
return config
|
ramplint/dom.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""A small, forgiving HTML tree built on top of :mod:`html.parser`.
|
|
2
|
+
|
|
3
|
+
Templates are usually fragments (partials, ``{% block %}`` bodies, includes),
|
|
4
|
+
so the tree never fails on unbalanced tags - it just does its best.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from html.parser import HTMLParser
|
|
12
|
+
|
|
13
|
+
from ramplint.template import MARKUP, PLACEHOLDERS, TEXT # noqa: F401
|
|
14
|
+
|
|
15
|
+
# fmt: off
|
|
16
|
+
VOID_ELEMENTS = frozenset(
|
|
17
|
+
{
|
|
18
|
+
"area", "base", "br", "col", "embed", "hr", "img", "input", "link",
|
|
19
|
+
"meta", "param", "source", "track", "wbr",
|
|
20
|
+
}
|
|
21
|
+
)
|
|
22
|
+
# fmt: on
|
|
23
|
+
|
|
24
|
+
# Opening the key tag implicitly closes any of these if they are open on top
|
|
25
|
+
# of the stack (a simplified version of the HTML "optional end tag" rules).
|
|
26
|
+
IMPLICIT_CLOSE = {
|
|
27
|
+
"li": frozenset({"li"}),
|
|
28
|
+
"dt": frozenset({"dt", "dd"}),
|
|
29
|
+
"dd": frozenset({"dt", "dd"}),
|
|
30
|
+
"tr": frozenset({"tr", "td", "th"}),
|
|
31
|
+
"td": frozenset({"td", "th"}),
|
|
32
|
+
"th": frozenset({"td", "th"}),
|
|
33
|
+
"thead": frozenset({"tbody", "tfoot", "tr", "td", "th"}),
|
|
34
|
+
"tbody": frozenset({"thead", "tbody", "tfoot", "tr", "td", "th"}),
|
|
35
|
+
"tfoot": frozenset({"thead", "tbody", "tr", "td", "th"}),
|
|
36
|
+
"option": frozenset({"option"}),
|
|
37
|
+
"p": frozenset({"p"}),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
RAW_TEXT_ELEMENTS = frozenset({"script", "style", "template"})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(eq=False)
|
|
44
|
+
class Node:
|
|
45
|
+
tag: str
|
|
46
|
+
attrs: dict[str, str]
|
|
47
|
+
line: int
|
|
48
|
+
col: int
|
|
49
|
+
parent: Node | None = None
|
|
50
|
+
children: list[Node | str] = field(default_factory=list)
|
|
51
|
+
#: True when attributes are generated at render time, e.g.
|
|
52
|
+
#: ``<input {{ widget.attrs }}>`` - we cannot know what they contain.
|
|
53
|
+
dynamic_attrs: bool = False
|
|
54
|
+
|
|
55
|
+
def get(self, name: str, default: str | None = None) -> str | None:
|
|
56
|
+
return self.attrs.get(name, default)
|
|
57
|
+
|
|
58
|
+
def has_value(self, name: str) -> bool:
|
|
59
|
+
"""The attribute exists and is not blank."""
|
|
60
|
+
value = self.attrs.get(name)
|
|
61
|
+
return value is not None and value.strip() != ""
|
|
62
|
+
|
|
63
|
+
def is_dynamic(self, name: str) -> bool:
|
|
64
|
+
value = self.attrs.get(name)
|
|
65
|
+
return value is not None and any(p in value for p in PLACEHOLDERS)
|
|
66
|
+
|
|
67
|
+
def iter(self, *tags: str) -> Iterator[Node]:
|
|
68
|
+
"""Depth-first iteration over descendants (not including self)."""
|
|
69
|
+
for child in self.children:
|
|
70
|
+
if isinstance(child, Node):
|
|
71
|
+
if not tags or child.tag in tags:
|
|
72
|
+
yield child
|
|
73
|
+
yield from child.iter(*tags)
|
|
74
|
+
|
|
75
|
+
def ancestors(self) -> Iterator[Node]:
|
|
76
|
+
node = self.parent
|
|
77
|
+
while node is not None:
|
|
78
|
+
yield node
|
|
79
|
+
node = node.parent
|
|
80
|
+
|
|
81
|
+
def text(self) -> str:
|
|
82
|
+
parts: list[str] = []
|
|
83
|
+
for child in self.children:
|
|
84
|
+
if isinstance(child, str):
|
|
85
|
+
parts.append(child)
|
|
86
|
+
elif child.tag not in RAW_TEXT_ELEMENTS:
|
|
87
|
+
parts.append(child.text())
|
|
88
|
+
return "".join(parts)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def role(self) -> str:
|
|
92
|
+
return (self.attrs.get("role") or "").strip().lower()
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def aria_hidden(self) -> bool:
|
|
96
|
+
return (self.attrs.get("aria-hidden") or "").strip().lower() == "true"
|
|
97
|
+
|
|
98
|
+
def __repr__(self) -> str: # pragma: no cover - debugging helper
|
|
99
|
+
return f"<{self.tag} at {self.line}:{self.col}>"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _TreeBuilder(HTMLParser):
|
|
103
|
+
def __init__(self) -> None:
|
|
104
|
+
super().__init__(convert_charrefs=True)
|
|
105
|
+
self.root = Node(tag="#document", attrs={}, line=1, col=1)
|
|
106
|
+
self.stack: list[Node] = [self.root]
|
|
107
|
+
|
|
108
|
+
# -- helpers -----------------------------------------------------------
|
|
109
|
+
def _make_node(self, tag: str, attrs: list[tuple[str, str | None]]) -> Node:
|
|
110
|
+
line, offset = self.getpos()
|
|
111
|
+
node = Node(tag=tag, attrs={}, line=line, col=offset + 1)
|
|
112
|
+
for name, value in attrs:
|
|
113
|
+
if any(p in name for p in PLACEHOLDERS):
|
|
114
|
+
node.dynamic_attrs = True
|
|
115
|
+
continue
|
|
116
|
+
node.attrs.setdefault(name, value if value is not None else "")
|
|
117
|
+
node.parent = self.stack[-1]
|
|
118
|
+
self.stack[-1].children.append(node)
|
|
119
|
+
return node
|
|
120
|
+
|
|
121
|
+
# -- HTMLParser hooks --------------------------------------------------
|
|
122
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
123
|
+
closes = IMPLICIT_CLOSE.get(tag)
|
|
124
|
+
if closes:
|
|
125
|
+
while len(self.stack) > 1 and self.stack[-1].tag in closes:
|
|
126
|
+
self.stack.pop()
|
|
127
|
+
node = self._make_node(tag, attrs)
|
|
128
|
+
if tag not in VOID_ELEMENTS:
|
|
129
|
+
self.stack.append(node)
|
|
130
|
+
|
|
131
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
132
|
+
self._make_node(tag, attrs)
|
|
133
|
+
|
|
134
|
+
def handle_endtag(self, tag: str) -> None:
|
|
135
|
+
for index in range(len(self.stack) - 1, 0, -1):
|
|
136
|
+
if self.stack[index].tag == tag:
|
|
137
|
+
del self.stack[index:]
|
|
138
|
+
return
|
|
139
|
+
# Stray end tag (common in partial templates) - ignore it.
|
|
140
|
+
|
|
141
|
+
def handle_data(self, data: str) -> None:
|
|
142
|
+
self.stack[-1].children.append(data)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse(html: str) -> Node:
|
|
146
|
+
builder = _TreeBuilder()
|
|
147
|
+
builder.feed(html)
|
|
148
|
+
builder.close()
|
|
149
|
+
return builder.root
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
__all__ = ["Node", "parse", "TEXT", "MARKUP"]
|
ramplint/linter.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import fnmatch
|
|
4
|
+
import os
|
|
5
|
+
from collections.abc import Iterable, Iterator
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ramplint import dom
|
|
10
|
+
from ramplint.rules import Rule, select_rules
|
|
11
|
+
from ramplint.template import prepare
|
|
12
|
+
|
|
13
|
+
DEFAULT_EXTENSIONS = (".html", ".htm", ".jinja", ".jinja2", ".j2", ".djhtml")
|
|
14
|
+
# fmt: off
|
|
15
|
+
DEFAULT_EXCLUDE_DIRS = frozenset(
|
|
16
|
+
{
|
|
17
|
+
".git", ".hg", ".svn", ".tox", ".nox", ".venv", "venv", "env",
|
|
18
|
+
"node_modules", "__pycache__", "build", "dist", "site-packages",
|
|
19
|
+
".mypy_cache", ".pytest_cache", ".ruff_cache", "htmlcov",
|
|
20
|
+
}
|
|
21
|
+
)
|
|
22
|
+
# fmt: on
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, order=True)
|
|
26
|
+
class Violation:
|
|
27
|
+
path: str
|
|
28
|
+
line: int
|
|
29
|
+
col: int
|
|
30
|
+
code: str
|
|
31
|
+
name: str
|
|
32
|
+
message: str
|
|
33
|
+
|
|
34
|
+
def to_dict(self) -> dict[str, object]:
|
|
35
|
+
return asdict(self)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def lint_source(
|
|
39
|
+
source: str, path: str = "<string>", rules: Iterable[Rule] | None = None
|
|
40
|
+
) -> list[Violation]:
|
|
41
|
+
"""Lint template source code and return the problems found."""
|
|
42
|
+
active = list(rules) if rules is not None else select_rules()
|
|
43
|
+
prepared = prepare(source)
|
|
44
|
+
root = dom.parse(prepared.html)
|
|
45
|
+
violations: set[Violation] = set()
|
|
46
|
+
for rule in active:
|
|
47
|
+
for node, message in rule.check(root):
|
|
48
|
+
if prepared.suppressions.is_suppressed(node.line, rule.code, rule.name):
|
|
49
|
+
continue
|
|
50
|
+
violations.add(
|
|
51
|
+
Violation(
|
|
52
|
+
path=path,
|
|
53
|
+
line=node.line,
|
|
54
|
+
col=node.col,
|
|
55
|
+
code=rule.code,
|
|
56
|
+
name=rule.name,
|
|
57
|
+
message=message,
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
return sorted(violations)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def lint_file(path: str | Path, rules: Iterable[Rule] | None = None) -> list[Violation]:
|
|
64
|
+
path = Path(path)
|
|
65
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
66
|
+
return lint_source(source, path=path.as_posix(), rules=rules)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _is_excluded(path: Path, patterns: Iterable[str]) -> bool:
|
|
70
|
+
posix = path.as_posix()
|
|
71
|
+
return any(
|
|
72
|
+
fnmatch.fnmatch(posix, pattern) or fnmatch.fnmatch(path.name, pattern)
|
|
73
|
+
for pattern in patterns
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def iter_template_files(
|
|
78
|
+
paths: Iterable[str | Path],
|
|
79
|
+
extensions: Iterable[str] = DEFAULT_EXTENSIONS,
|
|
80
|
+
exclude: Iterable[str] = (),
|
|
81
|
+
) -> Iterator[Path]:
|
|
82
|
+
"""Yield template files under ``paths``.
|
|
83
|
+
|
|
84
|
+
Files passed explicitly are always yielded (so pre-commit can hand us any
|
|
85
|
+
file it likes); directories are walked recursively.
|
|
86
|
+
"""
|
|
87
|
+
extensions = tuple(e.lower() if e.startswith(".") else f".{e.lower()}" for e in extensions)
|
|
88
|
+
exclude = list(exclude)
|
|
89
|
+
seen: set[Path] = set()
|
|
90
|
+
for raw in paths:
|
|
91
|
+
root = Path(raw)
|
|
92
|
+
if root.is_file():
|
|
93
|
+
if root not in seen and not _is_excluded(root, exclude):
|
|
94
|
+
seen.add(root)
|
|
95
|
+
yield root
|
|
96
|
+
continue
|
|
97
|
+
if not root.is_dir():
|
|
98
|
+
raise FileNotFoundError(raw)
|
|
99
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
100
|
+
current = Path(dirpath)
|
|
101
|
+
dirnames[:] = sorted(
|
|
102
|
+
d
|
|
103
|
+
for d in dirnames
|
|
104
|
+
if d not in DEFAULT_EXCLUDE_DIRS
|
|
105
|
+
and not d.endswith(".egg-info")
|
|
106
|
+
and not _is_excluded(current / d, exclude)
|
|
107
|
+
)
|
|
108
|
+
for filename in sorted(filenames):
|
|
109
|
+
file_path = current / filename
|
|
110
|
+
if not filename.lower().endswith(extensions):
|
|
111
|
+
continue
|
|
112
|
+
if file_path in seen or _is_excluded(file_path, exclude):
|
|
113
|
+
continue
|
|
114
|
+
seen.add(file_path)
|
|
115
|
+
yield file_path
|
ramplint/py.typed
ADDED
|
File without changes
|
ramplint/reporters.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
from ramplint.linter import Violation
|
|
8
|
+
|
|
9
|
+
_RESET = "\033[0m"
|
|
10
|
+
_BOLD = "\033[1m"
|
|
11
|
+
_RED = "\033[31m"
|
|
12
|
+
_CYAN = "\033[36m"
|
|
13
|
+
_DIM = "\033[2m"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _paint(text: str, *codes: str, color: bool) -> str:
|
|
17
|
+
return f"{''.join(codes)}{text}{_RESET}" if color else text
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def report_text(
|
|
21
|
+
violations: Sequence[Violation], files_checked: int, out: TextIO, color: bool = False
|
|
22
|
+
) -> None:
|
|
23
|
+
for v in violations:
|
|
24
|
+
location = _paint(f"{v.path}:{v.line}:{v.col}:", _BOLD, color=color)
|
|
25
|
+
code = _paint(v.code, _RED, _BOLD, color=color)
|
|
26
|
+
name = _paint(f"[{v.name}]", _DIM, color=color)
|
|
27
|
+
out.write(f"{location} {code} {v.message} {name}\n")
|
|
28
|
+
|
|
29
|
+
files_word = "file" if files_checked == 1 else "files"
|
|
30
|
+
if violations:
|
|
31
|
+
affected = len({v.path for v in violations})
|
|
32
|
+
problems = "problem" if len(violations) == 1 else "problems"
|
|
33
|
+
summary = (
|
|
34
|
+
f"Found {len(violations)} {problems} in {affected} of {files_checked} {files_word}."
|
|
35
|
+
)
|
|
36
|
+
out.write("\n" + _paint(summary, _RED, _BOLD, color=color) + "\n")
|
|
37
|
+
else:
|
|
38
|
+
out.write(
|
|
39
|
+
_paint(f"All checks passed ({files_checked} {files_word}).", _CYAN, color=color) + "\n"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def report_json(violations: Sequence[Violation], files_checked: int, out: TextIO) -> None:
|
|
44
|
+
json.dump(
|
|
45
|
+
{
|
|
46
|
+
"files_checked": files_checked,
|
|
47
|
+
"violations": [v.to_dict() for v in violations],
|
|
48
|
+
},
|
|
49
|
+
out,
|
|
50
|
+
indent=2,
|
|
51
|
+
)
|
|
52
|
+
out.write("\n")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _escape_github(value: str, *, property_value: bool = False) -> str:
|
|
56
|
+
value = value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
|
|
57
|
+
if property_value:
|
|
58
|
+
value = value.replace(":", "%3A").replace(",", "%2C")
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def report_github(violations: Sequence[Violation], files_checked: int, out: TextIO) -> None:
|
|
63
|
+
"""GitHub Actions workflow commands - shows problems inline in PR diffs."""
|
|
64
|
+
for v in violations:
|
|
65
|
+
file = _escape_github(v.path, property_value=True)
|
|
66
|
+
title = _escape_github(f"{v.code} {v.name}", property_value=True)
|
|
67
|
+
out.write(
|
|
68
|
+
f"::error file={file},line={v.line},col={v.col},title={title}::"
|
|
69
|
+
f"{_escape_github(v.message)}\n"
|
|
70
|
+
)
|
|
71
|
+
report_text(violations, files_checked, out, color=False)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
REPORTERS = {"text": report_text, "json": report_json, "github": report_github}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Built-in rules.
|
|
2
|
+
|
|
3
|
+
Importing this package registers every rule in :data:`REGISTRY`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from ramplint.rules import controls, document, forms, headings, images, tables # noqa: F401
|
|
9
|
+
from ramplint.rules.base import REGISTRY, Rule
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def all_rules() -> list[Rule]:
|
|
13
|
+
return sorted(REGISTRY.values(), key=lambda r: r.code)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _matches(rule: Rule, selector: str) -> bool:
|
|
17
|
+
selector = selector.strip()
|
|
18
|
+
if not selector:
|
|
19
|
+
return False
|
|
20
|
+
return rule.code.startswith(selector.upper()) or rule.name == selector.lower()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def select_rules(select: list[str] | None = None, ignore: list[str] | None = None) -> list[Rule]:
|
|
24
|
+
"""Pick rules by code prefix (``RL1``, ``RL101``) or name (``img-alt``)."""
|
|
25
|
+
rules = all_rules()
|
|
26
|
+
if select:
|
|
27
|
+
rules = [r for r in rules if any(_matches(r, s) for s in select)]
|
|
28
|
+
if ignore:
|
|
29
|
+
rules = [r for r in rules if not any(_matches(r, s) for s in ignore)]
|
|
30
|
+
return rules
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def unknown_selectors(selectors: list[str]) -> list[str]:
|
|
34
|
+
rules = all_rules()
|
|
35
|
+
return [s for s in selectors if s.strip() and not any(_matches(r, s) for r in rules)]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__all__ = ["REGISTRY", "Rule", "all_rules", "select_rules", "unknown_selectors"]
|
ramplint/rules/base.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
from ramplint.dom import Node
|
|
7
|
+
|
|
8
|
+
#: A check yields ``(node, message)`` pairs for every problem it finds.
|
|
9
|
+
Check = Callable[[Node], Iterator[tuple[Node, str]]]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Rule:
|
|
14
|
+
code: str
|
|
15
|
+
name: str
|
|
16
|
+
summary: str
|
|
17
|
+
wcag: str
|
|
18
|
+
check: Check
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
REGISTRY: dict[str, Rule] = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def rule(code: str, name: str, summary: str, wcag: str) -> Callable[[Check], Check]:
|
|
25
|
+
"""Register a check function as a rule."""
|
|
26
|
+
|
|
27
|
+
def decorator(func: Check) -> Check:
|
|
28
|
+
if code in REGISTRY: # pragma: no cover - programming error
|
|
29
|
+
raise ValueError(f"Duplicate rule code {code}")
|
|
30
|
+
REGISTRY[code] = Rule(code=code, name=name, summary=summary, wcag=wcag, check=func)
|
|
31
|
+
return func
|
|
32
|
+
|
|
33
|
+
return decorator
|