sagrep 0.9.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.
Files changed (79) hide show
  1. sagrep/__init__.py +34 -0
  2. sagrep/__main__.py +4 -0
  3. sagrep/annotation/__init__.py +25 -0
  4. sagrep/annotation/comment_annotation.py +96 -0
  5. sagrep/annotation/comment_markers.py +139 -0
  6. sagrep/annotation/directive_interpreter.py +71 -0
  7. sagrep/annotation/directive_syntax.py +398 -0
  8. sagrep/annotation/languages.py +245 -0
  9. sagrep/annotation/matcher.py +331 -0
  10. sagrep/annotation/messages.py +50 -0
  11. sagrep/annotation/models.py +97 -0
  12. sagrep/annotation/scope.py +143 -0
  13. sagrep/annotation/search.py +71 -0
  14. sagrep/annotation/source.py +112 -0
  15. sagrep/arguments.py +270 -0
  16. sagrep/cli.py +170 -0
  17. sagrep/command/__init__.py +12 -0
  18. sagrep/command/ast_grep_command.py +254 -0
  19. sagrep/command/find_builder.py +81 -0
  20. sagrep/command/find_command.py +55 -0
  21. sagrep/config_rule/__init__.py +50 -0
  22. sagrep/config_rule/config_loader.py +390 -0
  23. sagrep/config_rule/config_models.py +82 -0
  24. sagrep/config_rule/config_setup.py +326 -0
  25. sagrep/config_rule/rule_converter.py +676 -0
  26. sagrep/config_rule/rule_generator.py +469 -0
  27. sagrep/config_rule/rule_loader.py +504 -0
  28. sagrep/config_rule/rule_models.py +169 -0
  29. sagrep/config_rule/rule_preparation.py +112 -0
  30. sagrep/config_rule/rule_scope_filter.py +55 -0
  31. sagrep/config_rule/rule_selection.py +71 -0
  32. sagrep/config_rule/string_rule_converter.py +123 -0
  33. sagrep/config_rule/yaml_dynamics.py +114 -0
  34. sagrep/constant.py +84 -0
  35. sagrep/diagnostics.py +261 -0
  36. sagrep/extended_directive/comment_apply.py +114 -0
  37. sagrep/extended_directive/component.py +164 -0
  38. sagrep/extended_directive/directives.py +346 -0
  39. sagrep/extended_directive/occurs.py +240 -0
  40. sagrep/extended_directive/occurs_evaluator.py +59 -0
  41. sagrep/languages.py +64 -0
  42. sagrep/output_build/__init__.py +0 -0
  43. sagrep/output_build/cli_output.py +20 -0
  44. sagrep/output_build/models.py +75 -0
  45. sagrep/output_build/renderers.py +278 -0
  46. sagrep/output_build/report_builder.py +78 -0
  47. sagrep/output_build/transformer.py +559 -0
  48. sagrep/process/__init__.py +1 -0
  49. sagrep/process/ast_search.py +84 -0
  50. sagrep/process/direct_run.py +110 -0
  51. sagrep/process/rule_scan.py +250 -0
  52. sagrep/process/runner.py +111 -0
  53. sagrep/process/source_scanner.py +113 -0
  54. sagrep/shared/__init__.py +1 -0
  55. sagrep/shared/exceptions.py +36 -0
  56. sagrep/shared/module.py +56 -0
  57. sagrep/shared/parallel.py +75 -0
  58. sagrep/shared/types.py +6 -0
  59. sagrep/string_search/__init__.py +18 -0
  60. sagrep/string_search/gitignore.py +51 -0
  61. sagrep/string_search/matching.py +238 -0
  62. sagrep/string_search/models.py +130 -0
  63. sagrep/string_search/native_scope.py +54 -0
  64. sagrep/string_search/preparation.py +371 -0
  65. sagrep/string_search/result_assembly.py +64 -0
  66. sagrep/string_search/searcher.py +60 -0
  67. sagrep-0.9.0.dist-info/METADATA +503 -0
  68. sagrep-0.9.0.dist-info/RECORD +79 -0
  69. sagrep-0.9.0.dist-info/WHEEL +5 -0
  70. sagrep-0.9.0.dist-info/entry_points.txt +3 -0
  71. sagrep-0.9.0.dist-info/licenses/LICENSE +21 -0
  72. sagrep-0.9.0.dist-info/top_level.txt +2 -0
  73. sagrep_report/__init__.py +1 -0
  74. sagrep_report/__main__.py +4 -0
  75. sagrep_report/cli.py +88 -0
  76. sagrep_report/loader.py +76 -0
  77. sagrep_report/model.py +168 -0
  78. sagrep_report/renderer.py +59 -0
  79. sagrep_report/templates/report.html +371 -0
sagrep/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Lint and validate source code with AST rules, text-search rules, and annotations."""
2
+
3
+ from .shared.exceptions import (
4
+ SaGrepExecutionError,
5
+ SaGrepNotFoundError,
6
+ SaGrepOutputParseError,
7
+ SaGrepError,
8
+ )
9
+ from .config_rule.config_loader import (
10
+ ConfigParseError,
11
+ ConfigLoader,
12
+ ConfigPathResolver,
13
+ )
14
+ from .config_rule.config_models import Config
15
+ from .process.runner import SagrepRunner
16
+ from .extended_directive.occurs import OccursFilter
17
+ from .command import AstGrepCommand, FindBuilder
18
+ from .string_search import StringSearcher
19
+
20
+ __all__ = [
21
+ "SagrepRunner",
22
+ "AstGrepCommand",
23
+ "Config",
24
+ "ConfigLoader",
25
+ "ConfigPathResolver",
26
+ "ConfigParseError",
27
+ "SaGrepError",
28
+ "SaGrepNotFoundError",
29
+ "SaGrepExecutionError",
30
+ "SaGrepOutputParseError",
31
+ "OccursFilter",
32
+ "FindBuilder",
33
+ "StringSearcher",
34
+ ]
sagrep/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,25 @@
1
+ """Expose models and source processing for dynamic annotations."""
2
+
3
+ from .comment_annotation import CommentAnnotationRuleExtractor
4
+ from .comment_markers import CommentMarkerDiscovery, CommentMarkerRouter, CommentMarkerRoutes
5
+ from .matcher import AnnotationMatcher
6
+ from .models import (
7
+ AnnotationDirective,
8
+ AnnotationFindRule,
9
+ AnnotationFoundResult,
10
+ DetectedMarker,
11
+ FoundMatch,
12
+ )
13
+
14
+ __all__ = [
15
+ "AnnotationDirective",
16
+ "AnnotationFindRule",
17
+ "AnnotationFoundResult",
18
+ "CommentAnnotationRuleExtractor",
19
+ "CommentMarkerDiscovery",
20
+ "CommentMarkerRouter",
21
+ "CommentMarkerRoutes",
22
+ "DetectedMarker",
23
+ "FoundMatch",
24
+ "AnnotationMatcher",
25
+ ]
@@ -0,0 +1,96 @@
1
+ """Extract dynamic Annotation directives from simple comment detections."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from pathlib import Path
7
+
8
+ from .directive_syntax import (
9
+ APPLY_DIRECTIVE_NAME,
10
+ DYNAMIC_DIRECTIVE_NAMES,
11
+ MESSAGE_SEVERITIES,
12
+ DirectiveSyntaxParser,
13
+ )
14
+ from .directive_interpreter import AnnotationDirectiveInterpreter
15
+ from .models import AnnotationDirective, AnnotationFindRule, CommentDynamicInputs, DetectedMarker
16
+ from .comment_markers import SourceCommentRoutes
17
+ from .source import SourceMarkers
18
+
19
+
20
+ class CommentDirectiveParser:
21
+ """Adapt Comment directive syntax to shared dynamic interpretation."""
22
+
23
+ def __init__(self, *, syntax_parser: DirectiveSyntaxParser | None = None) -> None:
24
+ self._syntax_parser = syntax_parser if syntax_parser is not None else DirectiveSyntaxParser()
25
+ self._interpreter = AnnotationDirectiveInterpreter(self._syntax_parser)
26
+
27
+ def parse(self, detected_text: str, source_path: Path) -> list[tuple[AnnotationDirective, AnnotationFindRule]]:
28
+ """Return canonical metadata/search pairs in source order with Comment error context."""
29
+ parsed: list[tuple[AnnotationDirective, AnnotationFindRule]] = []
30
+ directive_source = self._syntax_parser.unwrap_quoted_source(detected_text)
31
+ directive_texts = self._syntax_parser.directive_texts(directive_source)
32
+ for ordinal, directive_text in enumerate(directive_texts):
33
+ try:
34
+ syntax = self._syntax_parser.parse(directive_text)
35
+ if syntax.name == APPLY_DIRECTIVE_NAME or syntax.name in MESSAGE_SEVERITIES:
36
+ continue
37
+ if syntax.name not in DYNAMIC_DIRECTIVE_NAMES:
38
+ raise ValueError(f"unsupported directive: {syntax.name}")
39
+
40
+ directive, rule = self._interpreter.interpret(syntax, source_ordinal=ordinal)
41
+ assert rule is not None
42
+ parsed.append((directive, rule))
43
+ except ValueError as error:
44
+ raise ValueError(
45
+ f"invalid dynamic annotation {directive_text!r} " f"in {source_path}: {error}"
46
+ ) from error
47
+ return parsed
48
+
49
+
50
+ class CommentAnnotationRuleExtractor:
51
+ """Extract directive metadata and search rules from comment detections."""
52
+
53
+ def __init__(self, *, directive_parser: CommentDirectiveParser | None = None) -> None:
54
+ self._directive_parser = directive_parser if directive_parser is not None else CommentDirectiveParser()
55
+
56
+ def extract_sources(self, sources: tuple[SourceCommentRoutes, ...]) -> tuple[CommentDynamicInputs, ...]:
57
+ """Extract separate metadata/search inputs per source with dynamic markers."""
58
+ inputs: list[CommentDynamicInputs] = []
59
+ for source in sources:
60
+ if source.routes.dynamic_markers:
61
+ directives, rules = self.extract(source.source_path, source.routes.dynamic_markers)
62
+ inputs.append(CommentDynamicInputs(source.source_path, tuple(directives), tuple(rules)))
63
+ return tuple(inputs)
64
+
65
+ def extract(
66
+ self,
67
+ source_path: Path,
68
+ markers: tuple[DetectedMarker, ...],
69
+ ) -> tuple[list[AnnotationDirective], list[AnnotationFindRule]]:
70
+ """Return same-order directive metadata and search rules, one set per distinct marker."""
71
+ distinct_markers = self._distinct_markers_in_source_order(source_path, markers)
72
+
73
+ annotation_directives: list[AnnotationDirective] = []
74
+ find_rules: list[AnnotationFindRule] = []
75
+ for detected_marker in distinct_markers:
76
+ try:
77
+ directives = self._directive_parser.parse(detected_marker.detected_text, source_path)
78
+ except ValueError as exc:
79
+ raise ValueError(f"{detected_marker.source_location}: {exc}") from exc
80
+ for directive, find_rule in directives:
81
+ find_rules.append(replace(find_rule, detected_marker=detected_marker))
82
+ annotation_directives.append(directive)
83
+
84
+ return annotation_directives, find_rules
85
+
86
+ def _distinct_markers_in_source_order(
87
+ self,
88
+ source_path: Path,
89
+ markers: tuple[DetectedMarker, ...],
90
+ ) -> list[DetectedMarker]:
91
+ # Identical markers (same position and text) are extracted once.
92
+ distinct_by_identity: dict[tuple[int, int, str], DetectedMarker] = {}
93
+ for marker in SourceMarkers(source_path, markers):
94
+ identity = (marker.start_byte, marker.end_byte, marker.detected_text)
95
+ distinct_by_identity.setdefault(identity, marker)
96
+ return sorted(distinct_by_identity.values(), key=lambda marker: marker.start_byte)
@@ -0,0 +1,139 @@
1
+ """Discover and route Comment marker inventories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from tree_sitter import Node, Parser
9
+
10
+ from ..shared.parallel import ParallelRunner
11
+ from .directive_syntax import (
12
+ ANNOTATION_MARKER_PATTERN, ANNOTATION_NAMES, APPLY_DIRECTIVE_NAME,
13
+ DYNAMIC_DIRECTIVE_NAMES, MESSAGE_SEVERITIES, DirectiveSyntax, DirectiveSyntaxParser,
14
+ )
15
+ from .languages import LanguageConfig, source_language_config_for
16
+ from .models import DetectedMarker
17
+ from .source import SyntaxNodes
18
+
19
+
20
+ class CommentMarkerDiscovery:
21
+ """Return comment and directive-expression nodes that contain a directive marker.
22
+
23
+ Files whose extension has no language configuration yield no markers.
24
+ """
25
+
26
+ def __init__(self, max_workers: int | None = 3, *, runner: ParallelRunner | None = None) -> None:
27
+ self._runner = runner if runner is not None else ParallelRunner(max_workers)
28
+
29
+ def supports_file(self, source_path: Path) -> bool:
30
+ return source_language_config_for(source_path) is not None
31
+
32
+ def discover_files(self, source_paths: tuple[Path, ...]) -> tuple[tuple[DetectedMarker, ...], ...]:
33
+ """Discover an inventory concurrently, retaining its order and empty file groups."""
34
+ work = [(str(path), path) for path in source_paths]
35
+ return tuple(self._runner.map_files(work, lambda _key, path: self.discover(path)))
36
+
37
+ def discover(self, source_path: Path) -> tuple[DetectedMarker, ...]:
38
+ """Parse the file once and return its markers in document order."""
39
+ if not self.supports_file(source_path):
40
+ return ()
41
+ return self.discover_bytes(source_path, source_path.read_bytes())
42
+
43
+ def discover_bytes(self, source_path: Path, source: bytes) -> tuple[DetectedMarker, ...]:
44
+ """Reject marker-free bytes before parsing and validating candidate comments."""
45
+ config = source_language_config_for(source_path)
46
+ if config is None:
47
+ return ()
48
+ if ANNOTATION_MARKER_PATTERN.search(source) is None:
49
+ return ()
50
+ root = Parser(config.language).parse(source).root_node
51
+ markers: list[DetectedMarker] = []
52
+ marker_end = -1
53
+ for node in SyntaxNodes(root):
54
+ if node.start_byte < marker_end or not self._is_marker_node(node, config):
55
+ continue
56
+ markers.append(self._marker_for(source_path, node, source))
57
+ marker_end = node.end_byte
58
+ return tuple(markers)
59
+
60
+ def _is_marker_node(self, node: Node, config: LanguageConfig) -> bool:
61
+ is_candidate = (
62
+ node.type in config.comment_node_types
63
+ or config.is_directive_expression(node)
64
+ )
65
+ return is_candidate and ANNOTATION_MARKER_PATTERN.search(node.text or b"") is not None
66
+
67
+ def _marker_for(self, source_path: Path, node: Node, source: bytes) -> DetectedMarker:
68
+ return DetectedMarker(
69
+ source_path=source_path,
70
+ start_byte=node.start_byte,
71
+ end_byte=node.end_byte,
72
+ detected_text=(node.text or b"").decode("utf-8", errors="surrogateescape"),
73
+ origin_line=node.start_point.row + 1,
74
+ origin_column=len(source[node.start_byte - node.start_point.column:node.start_byte].decode("utf-8", errors="surrogateescape")) + 1,
75
+ )
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class CommentMarkerRoutes:
80
+ """Markers grouped by the directive kinds they contain.
81
+
82
+ A marker holding multiple kinds contributes to each applicable route.
83
+ """
84
+
85
+ apply_markers: tuple[DetectedMarker, ...]
86
+ dynamic_markers: tuple[DetectedMarker, ...]
87
+ message_directives: tuple[tuple[DetectedMarker, int, DirectiveSyntax], ...] = ()
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class SourceCommentRoutes:
92
+ source_path: Path
93
+ routes: CommentMarkerRoutes
94
+
95
+
96
+ class CommentMarkerRouter:
97
+ """Classify markers by directive name without interpreting their values."""
98
+
99
+ def __init__(self, *, syntax_parser: DirectiveSyntaxParser | None = None) -> None:
100
+ self._syntax_parser = syntax_parser if syntax_parser is not None else DirectiveSyntaxParser()
101
+
102
+ def route_sources(
103
+ self, source_paths: tuple[Path, ...], marker_groups: tuple[tuple[DetectedMarker, ...], ...],
104
+ ) -> tuple[SourceCommentRoutes, ...]:
105
+ """Route one ordered marker group per source without interpreting directive values."""
106
+ return tuple(SourceCommentRoutes(path, self.route(markers)) for path, markers in zip(
107
+ source_paths, marker_groups, strict=True,
108
+ ))
109
+
110
+ def route(self, markers: tuple[DetectedMarker, ...]) -> CommentMarkerRoutes:
111
+ """Return markers routed to apply and dynamic processing, preserving order."""
112
+ apply_markers: list[DetectedMarker] = []
113
+ dynamic_markers: list[DetectedMarker] = []
114
+ messages: list[tuple[DetectedMarker, int, DirectiveSyntax]] = []
115
+ for marker in markers:
116
+ try:
117
+ syntax = self._parse_directives(marker.detected_text)
118
+ names = {directive.name for directive in syntax}
119
+ messages.extend((marker, ordinal, directive) for ordinal, directive in enumerate(syntax)
120
+ if directive.name in MESSAGE_SEVERITIES)
121
+ except ValueError as exc:
122
+ raise ValueError(f"{marker.source_location}: {exc}") from exc
123
+ if APPLY_DIRECTIVE_NAME in names:
124
+ apply_markers.append(marker)
125
+ if names & DYNAMIC_DIRECTIVE_NAMES:
126
+ dynamic_markers.append(marker)
127
+ return CommentMarkerRoutes(tuple(apply_markers), tuple(dynamic_markers), tuple(messages))
128
+
129
+ def _parse_directives(self, detected_text: str) -> tuple[DirectiveSyntax, ...]:
130
+ # Retain parsed message values so the terminal message route needs no extra parsing.
131
+ directive_source = self._syntax_parser.unwrap_quoted_source(detected_text)
132
+ syntax = tuple(
133
+ self._syntax_parser.parse(directive_text)
134
+ for directive_text in self._syntax_parser.directive_texts(directive_source)
135
+ )
136
+ unsupported = {directive.name for directive in syntax} - ANNOTATION_NAMES
137
+ if unsupported:
138
+ raise ValueError(f"unsupported directive: {min(unsupported)}")
139
+ return syntax
@@ -0,0 +1,71 @@
1
+ """Interpret Annotation directive semantics independently of input route and origin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from typing import TYPE_CHECKING
7
+
8
+ from .directive_syntax import DirectiveSyntax, DirectiveSyntaxParser, MESSAGE_SEVERITIES, RegexValue
9
+ from .models import AnnotationDirective, AnnotationFindRule
10
+
11
+ if TYPE_CHECKING:
12
+ from ..extended_directive.directives import YamlAnnotationRule
13
+
14
+
15
+ class AnnotationDirectiveInterpreter:
16
+ """Normalize dynamic and message syntax into canonical metadata and optional search input."""
17
+
18
+ def __init__(self, syntax_parser: DirectiveSyntaxParser) -> None:
19
+ self._syntax_parser = syntax_parser
20
+
21
+ def interpret(
22
+ self, syntax: DirectiveSyntax, *, source_ordinal: int = 0,
23
+ ) -> tuple[AnnotationDirective, AnnotationFindRule | None]:
24
+ """Interpret one declaration; only dynamic directives produce a search rule."""
25
+ rule: AnnotationFindRule | None
26
+ if syntax.name in MESSAGE_SEVERITIES:
27
+ directive, rule = self._interpret_message(syntax), None
28
+ else:
29
+ directive, rule = self._interpret_dynamic(syntax)
30
+ return replace(directive, source_ordinal=source_ordinal), rule
31
+
32
+ def interpret_yaml(self, annotation: YamlAnnotationRule) -> tuple[AnnotationDirective, AnnotationFindRule | None]:
33
+ """Validate decoded YAML once and preserve its declaration context for either behavior."""
34
+ try:
35
+ if not isinstance(annotation.value, str):
36
+ label = "message" if annotation.name.partition("(")[0].strip() in MESSAGE_SEVERITIES else "dynamic value"
37
+ raise ValueError(f"{label} must be a non-empty string")
38
+ syntax = self._syntax_parser.parse_yaml(annotation.name, annotation.value)
39
+ return self.interpret(syntax, source_ordinal=annotation.directive_ordinal)
40
+ except ValueError as error:
41
+ raise ValueError(f"{annotation.source_location}: {error}") from error
42
+
43
+ def _interpret_message(self, syntax: DirectiveSyntax) -> AnnotationDirective:
44
+ """Validate literal-only message semantics and build its metadata."""
45
+ if syntax.options:
46
+ raise ValueError("message directives do not support options")
47
+ if not syntax.value.strip():
48
+ raise ValueError("message must be a non-empty string")
49
+ return AnnotationDirective(syntax.name, MESSAGE_SEVERITIES[syntax.name], message=syntax.value)
50
+
51
+ def _interpret_dynamic(self, syntax: DirectiveSyntax) -> tuple[AnnotationDirective, AnnotationFindRule]:
52
+ """Decode search options and regex values without adapting source provenance."""
53
+ options = self._syntax_parser.parse_dynamic_options(
54
+ syntax.options, default_severity="warning" if syntax.name == "fire" else "error",
55
+ )
56
+ value = (
57
+ RegexValue(syntax.value, "", False)
58
+ if syntax.value_is_quoted and not options.uses_regex
59
+ else self._syntax_parser.parse_regex_value(syntax.value, validate=options.uses_regex)
60
+ )
61
+ return (
62
+ AnnotationDirective(
63
+ directive_name=syntax.name, severity=options.severity,
64
+ occurrence_options=options.occurrence_options,
65
+ ),
66
+ AnnotationFindRule(
67
+ search_pattern=value.pattern, is_regex=options.uses_regex or value.is_literal,
68
+ regex_flags=value.flags,
69
+ ),
70
+ )
71
+