rulepack 0.8.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.
- rulepack/__init__.py +0 -0
- rulepack/__main__.py +5 -0
- rulepack/cli.py +40 -0
- rulepack/config/__init__.py +12 -0
- rulepack/config/command.py +72 -0
- rulepack/config/project_paths.py +37 -0
- rulepack/config/resolve.py +103 -0
- rulepack/config/settings.py +42 -0
- rulepack/hook/__init__.py +0 -0
- rulepack/hook/command.py +177 -0
- rulepack/hook/payload.py +62 -0
- rulepack/init/__init__.py +0 -0
- rulepack/init/command.py +351 -0
- rulepack/init/templates/poe-tasks.toml +10 -0
- rulepack/init/templates/pre-commit.yaml +6 -0
- rulepack/init/templates/rulepack.toml +4 -0
- rulepack/init/templates/sgconfig.yml +6 -0
- rulepack/init/templates/workflow.yml +23 -0
- rulepack/lint/__init__.py +0 -0
- rulepack/lint/changed_files.py +97 -0
- rulepack/lint/command.py +363 -0
- rulepack-0.8.0.dist-info/METADATA +188 -0
- rulepack-0.8.0.dist-info/RECORD +26 -0
- rulepack-0.8.0.dist-info/WHEEL +4 -0
- rulepack-0.8.0.dist-info/entry_points.txt +2 -0
- rulepack-0.8.0.dist-info/licenses/LICENSE +21 -0
rulepack/__init__.py
ADDED
|
File without changes
|
rulepack/__main__.py
ADDED
rulepack/cli.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import importlib
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import logging
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
COMMANDS = {
|
|
10
|
+
"config": "rulepack.config.command",
|
|
11
|
+
"hook": "rulepack.hook.command",
|
|
12
|
+
"init": "rulepack.init.command",
|
|
13
|
+
"lint": "rulepack.lint.command",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv: list[str] | None = None) -> int:
|
|
18
|
+
arguments = sys.argv[1:] if argv is None else argv
|
|
19
|
+
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
prog="rulepack",
|
|
22
|
+
description=(
|
|
23
|
+
"Run ast-grep and import-linter checks from shared, versioned rule packs."
|
|
24
|
+
),
|
|
25
|
+
epilog="Run 'rulepack <command> --help' for what each command does.",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--version",
|
|
29
|
+
action="version",
|
|
30
|
+
version=f"rulepack {importlib.metadata.version('rulepack')}",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument("command", choices=COMMANDS)
|
|
33
|
+
parsed = parser.parse_args(arguments[:1])
|
|
34
|
+
command = importlib.import_module(COMMANDS[parsed.command])
|
|
35
|
+
config = importlib.import_module("rulepack.config")
|
|
36
|
+
try:
|
|
37
|
+
return int(command.main(arguments[1:]))
|
|
38
|
+
except config.ConfigError as error:
|
|
39
|
+
logger.error("rulepack: %s", error)
|
|
40
|
+
return 2
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from rulepack.config.project_paths import CONFIG_FILE_NAME
|
|
2
|
+
from rulepack.config.resolve import ConfigError, resolve_config
|
|
3
|
+
from rulepack.config.settings import ProjectConfig, ResolvedConfig, StrictModel
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"CONFIG_FILE_NAME",
|
|
7
|
+
"ConfigError",
|
|
8
|
+
"ProjectConfig",
|
|
9
|
+
"ResolvedConfig",
|
|
10
|
+
"StrictModel",
|
|
11
|
+
"resolve_config",
|
|
12
|
+
]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from rulepack.config.project_paths import CONFIG_FILE_NAME
|
|
8
|
+
from rulepack.config.resolve import flatten, resolve_config
|
|
9
|
+
from rulepack.config.settings import ResolvedConfig
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def display_value(value: Any, root: Path) -> Any:
|
|
13
|
+
if isinstance(value, list):
|
|
14
|
+
return [display_value(item, root) for item in value]
|
|
15
|
+
if isinstance(value, Path):
|
|
16
|
+
return (
|
|
17
|
+
value.relative_to(root).as_posix()
|
|
18
|
+
if value.is_relative_to(root)
|
|
19
|
+
else str(value)
|
|
20
|
+
)
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def describe(config: ResolvedConfig) -> dict[str, Any]:
|
|
25
|
+
values = flatten(config.values.model_dump())
|
|
26
|
+
return {
|
|
27
|
+
"file": str(config.file) if config.file else None,
|
|
28
|
+
"root": str(config.root),
|
|
29
|
+
"settings": {
|
|
30
|
+
key: {
|
|
31
|
+
"value": display_value(value, config.root),
|
|
32
|
+
"source": config.sources[key],
|
|
33
|
+
}
|
|
34
|
+
for key, value in values.items()
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv: list[str] | None = None) -> int:
|
|
40
|
+
parser = argparse.ArgumentParser(
|
|
41
|
+
prog="rulepack config",
|
|
42
|
+
description=(
|
|
43
|
+
f"Print the resolved project config ({CONFIG_FILE_NAME}) and where "
|
|
44
|
+
"each value comes from."
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument("--sgconfig", type=Path)
|
|
48
|
+
parser.add_argument("--importlinter", type=Path)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"--json", action="store_true", help="Print the resolved config as JSON."
|
|
51
|
+
)
|
|
52
|
+
arguments = parser.parse_args(argv)
|
|
53
|
+
|
|
54
|
+
description = describe(
|
|
55
|
+
resolve_config({
|
|
56
|
+
"sgconfig": arguments.sgconfig,
|
|
57
|
+
"importlinter": arguments.importlinter,
|
|
58
|
+
})
|
|
59
|
+
)
|
|
60
|
+
if arguments.json:
|
|
61
|
+
sys.stdout.write(json.dumps(description, indent=2) + "\n")
|
|
62
|
+
return 0
|
|
63
|
+
lines = [
|
|
64
|
+
f"# file: {description['file'] or 'none (built-in defaults)'}",
|
|
65
|
+
f"# root: {description['root']}",
|
|
66
|
+
]
|
|
67
|
+
lines.extend(
|
|
68
|
+
f"{key} = {json.dumps(setting['value'])} # {setting['source']}"
|
|
69
|
+
for key, setting in description["settings"].items()
|
|
70
|
+
)
|
|
71
|
+
sys.stdout.write("\n".join(lines) + "\n")
|
|
72
|
+
return 0
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
CONFIG_FILE_NAME = ".rulepack.toml"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def find_git_root(start: Path) -> Path | None:
|
|
7
|
+
return next(
|
|
8
|
+
(
|
|
9
|
+
directory
|
|
10
|
+
for directory in (start, *start.parents)
|
|
11
|
+
if (directory / ".git").exists()
|
|
12
|
+
),
|
|
13
|
+
None,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def candidate_directories(start: Path, git_root: Path | None) -> list[Path]:
|
|
18
|
+
if git_root is None:
|
|
19
|
+
return [start]
|
|
20
|
+
directories = [start]
|
|
21
|
+
for parent in start.parents:
|
|
22
|
+
if not parent.is_relative_to(git_root):
|
|
23
|
+
break
|
|
24
|
+
directories.append(parent)
|
|
25
|
+
return directories
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def find_config_path(start: Path, git_root: Path | None) -> Path | None:
|
|
29
|
+
"""Find the nearest config without looking above the git root."""
|
|
30
|
+
return next(
|
|
31
|
+
(
|
|
32
|
+
directory / CONFIG_FILE_NAME
|
|
33
|
+
for directory in candidate_directories(start, git_root)
|
|
34
|
+
if (directory / CONFIG_FILE_NAME).is_file()
|
|
35
|
+
),
|
|
36
|
+
None,
|
|
37
|
+
)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import tomllib
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from pydantic import ValidationError
|
|
6
|
+
|
|
7
|
+
from rulepack.config.project_paths import find_config_path, find_git_root
|
|
8
|
+
from rulepack.config.settings import ProjectConfig, ResolvedConfig, Source
|
|
9
|
+
|
|
10
|
+
# Keys whose values are paths (or lists of paths) relative to the config file.
|
|
11
|
+
PATH_KEYS = {
|
|
12
|
+
"sgconfig",
|
|
13
|
+
"importlinter",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ConfigError(Exception):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def read_toml(path: Path) -> dict[str, Any]:
|
|
22
|
+
try:
|
|
23
|
+
return tomllib.loads(path.read_text(encoding="utf-8"))
|
|
24
|
+
except tomllib.TOMLDecodeError as error:
|
|
25
|
+
raise ConfigError(f"{path}: invalid TOML ({error})") from error
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def flatten(data: dict[str, Any], prefix: str = "") -> dict[str, Any]:
|
|
29
|
+
flat: dict[str, Any] = {}
|
|
30
|
+
for key, value in data.items():
|
|
31
|
+
if isinstance(value, dict):
|
|
32
|
+
flat.update(flatten(value, f"{prefix}{key}."))
|
|
33
|
+
else:
|
|
34
|
+
flat[f"{prefix}{key}"] = value
|
|
35
|
+
return flat
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def unflatten(flat: dict[str, Any]) -> dict[str, Any]:
|
|
39
|
+
data: dict[str, Any] = {}
|
|
40
|
+
for dotted_key, value in flat.items():
|
|
41
|
+
*parents, leaf = dotted_key.split(".")
|
|
42
|
+
table = data
|
|
43
|
+
for parent in parents:
|
|
44
|
+
table = table.setdefault(parent, {})
|
|
45
|
+
table[leaf] = value
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def absolute(value: Any, base: Path) -> Any:
|
|
50
|
+
if isinstance(value, list):
|
|
51
|
+
return [absolute(item, base) for item in value]
|
|
52
|
+
path = Path(value).expanduser()
|
|
53
|
+
return path if path.is_absolute() else base / path
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def validate(data: dict[str, Any], origin: str) -> ProjectConfig:
|
|
57
|
+
try:
|
|
58
|
+
return ProjectConfig.model_validate(data)
|
|
59
|
+
except ValidationError as error:
|
|
60
|
+
raise ConfigError(f"{origin}: {error}") from error
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def resolve_config(
|
|
64
|
+
overrides: dict[str, Any] | None = None, start: Path | None = None
|
|
65
|
+
) -> ResolvedConfig:
|
|
66
|
+
"""Merge built-in defaults, the repo config and flags, in that order.
|
|
67
|
+
|
|
68
|
+
`overrides` maps dotted keys (`sgconfig`, `scan.exclude`) to flag values;
|
|
69
|
+
None means the flag was not given. Flag paths resolve against the current
|
|
70
|
+
directory, file and default paths against the config file's directory.
|
|
71
|
+
"""
|
|
72
|
+
current_directory = Path.cwd()
|
|
73
|
+
start = (start or current_directory).resolve()
|
|
74
|
+
git_root = find_git_root(start)
|
|
75
|
+
config_file = find_config_path(start, git_root)
|
|
76
|
+
file_data = read_toml(config_file) if config_file else {}
|
|
77
|
+
root = config_file.parent if config_file else (git_root or start)
|
|
78
|
+
|
|
79
|
+
file_values = flatten(
|
|
80
|
+
validate(file_data, str(config_file)).model_dump(exclude_unset=True)
|
|
81
|
+
)
|
|
82
|
+
merged = flatten(ProjectConfig().model_dump())
|
|
83
|
+
sources: dict[str, Source] = dict.fromkeys(merged, "default")
|
|
84
|
+
merged.update(file_values)
|
|
85
|
+
sources.update(dict.fromkeys(file_values, "file"))
|
|
86
|
+
for key in merged:
|
|
87
|
+
if key in PATH_KEYS:
|
|
88
|
+
merged[key] = absolute(merged[key], root)
|
|
89
|
+
for key, value in (overrides or {}).items():
|
|
90
|
+
if value is None:
|
|
91
|
+
continue
|
|
92
|
+
if key not in merged:
|
|
93
|
+
raise ConfigError(f"unknown config key '{key}'")
|
|
94
|
+
merged[key] = absolute(value, current_directory) if key in PATH_KEYS else value
|
|
95
|
+
sources[key] = "flag"
|
|
96
|
+
|
|
97
|
+
return ResolvedConfig(
|
|
98
|
+
root=root,
|
|
99
|
+
git_root=git_root,
|
|
100
|
+
file=config_file,
|
|
101
|
+
values=validate(unflatten(merged), "resolved config"),
|
|
102
|
+
sources=sources,
|
|
103
|
+
)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
|
|
6
|
+
Source = Literal["default", "file", "flag"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class StrictModel(BaseModel):
|
|
10
|
+
model_config = ConfigDict(extra="forbid")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ScanSettings(StrictModel):
|
|
14
|
+
exclude: list[str] = []
|
|
15
|
+
extensions: list[str] = [".py"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ChangedSettings(StrictModel):
|
|
19
|
+
base_ref: str = "origin/main"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HookSettings(StrictModel):
|
|
23
|
+
enabled: bool = True
|
|
24
|
+
timeout: float = Field(default=10.0, gt=0, allow_inf_nan=False)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProjectConfig(StrictModel):
|
|
28
|
+
sgconfig: Path = Path("lint/sgconfig.yml")
|
|
29
|
+
importlinter: Path = Path(".importlinter")
|
|
30
|
+
scan: ScanSettings = ScanSettings()
|
|
31
|
+
hooks: HookSettings = HookSettings()
|
|
32
|
+
changed: ChangedSettings = ChangedSettings()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ResolvedConfig(StrictModel):
|
|
36
|
+
"""The merged config. Every path value is absolute."""
|
|
37
|
+
|
|
38
|
+
root: Path
|
|
39
|
+
git_root: Path | None
|
|
40
|
+
file: Path | None
|
|
41
|
+
values: ProjectConfig
|
|
42
|
+
sources: dict[str, Source]
|
|
File without changes
|
rulepack/hook/command.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import time
|
|
9
|
+
from enum import IntEnum
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from pydantic import TypeAdapter
|
|
13
|
+
|
|
14
|
+
from rulepack.config import ConfigError, ResolvedConfig, resolve_config
|
|
15
|
+
from rulepack.config.project_paths import find_config_path, find_git_root
|
|
16
|
+
from rulepack.hook.payload import HookPayload
|
|
17
|
+
from rulepack.lint.command import ScanFinding, StepResult, select_files
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HookExit(IntEnum):
|
|
23
|
+
QUIET = 0
|
|
24
|
+
# Agents show a hook's stderr to the model when it exits 2.
|
|
25
|
+
REPORT = 2
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def run_lint(root: Path, arguments: list[str], timeout: float) -> dict[str, StepResult]:
|
|
29
|
+
command = [sys.executable, "-P", "-m", "rulepack", "lint", "--json", *arguments]
|
|
30
|
+
# Files let a timed-out lint process return without waiting for a child's pipes.
|
|
31
|
+
with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as errors:
|
|
32
|
+
completed = subprocess.run(
|
|
33
|
+
command,
|
|
34
|
+
cwd=root,
|
|
35
|
+
stdout=output,
|
|
36
|
+
stderr=errors,
|
|
37
|
+
timeout=timeout,
|
|
38
|
+
check=False,
|
|
39
|
+
)
|
|
40
|
+
# `rulepack lint` exits 1 when a check fails, and higher when it cannot run.
|
|
41
|
+
if completed.returncode > 1:
|
|
42
|
+
errors.seek(0)
|
|
43
|
+
raise RuntimeError(errors.read().decode("utf-8", errors="replace").strip())
|
|
44
|
+
output.seek(0)
|
|
45
|
+
return TypeAdapter(dict[str, StepResult]).validate_json(output.read())
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def format_finding(finding: ScanFinding | str) -> str:
|
|
49
|
+
if isinstance(finding, str):
|
|
50
|
+
return finding
|
|
51
|
+
return f"{finding.file}:{finding.line}: {finding.rule}: {finding.message}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def list_findings(results: dict[str, StepResult]) -> list[str]:
|
|
55
|
+
return sorted({
|
|
56
|
+
format_finding(finding)
|
|
57
|
+
for step, result in results.items()
|
|
58
|
+
if not result.ok
|
|
59
|
+
for finding in result.findings or [f"{step} failed"]
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def resolve_hook_config(start: Path) -> ResolvedConfig | None:
|
|
64
|
+
"""The project's config, when it has a config file that leaves hooks enabled."""
|
|
65
|
+
config = resolve_config(start=start)
|
|
66
|
+
hooks_enabled = config.file is not None and config.values.hooks.enabled
|
|
67
|
+
return config if hooks_enabled else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def lint_within_budget(
|
|
71
|
+
config: ResolvedConfig, arguments: list[str], started: float
|
|
72
|
+
) -> list[str]:
|
|
73
|
+
"""Lint with what is left of the hook's time budget, which starts at `started`."""
|
|
74
|
+
budget = config.values.hooks.timeout
|
|
75
|
+
remaining = budget - (time.monotonic() - started)
|
|
76
|
+
if remaining <= 0:
|
|
77
|
+
raise subprocess.TimeoutExpired("rulepack lint", budget)
|
|
78
|
+
return list_findings(run_lint(config.root, arguments, remaining))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def find_edited_file_findings(
|
|
82
|
+
root: Path, edited: list[Path], started: float
|
|
83
|
+
) -> list[str]:
|
|
84
|
+
config = resolve_hook_config(root)
|
|
85
|
+
if config is None:
|
|
86
|
+
return []
|
|
87
|
+
files = select_files(config, edited)
|
|
88
|
+
if not files:
|
|
89
|
+
return []
|
|
90
|
+
arguments = ["--files", *[str(path) for path in files], "--only", "scan"]
|
|
91
|
+
return lint_within_budget(config, arguments, started)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def find_stop_marker_path(root: Path, session: str) -> Path:
|
|
95
|
+
"""The temp file that holds the digest of the findings a session's stop reported."""
|
|
96
|
+
key = hashlib.sha256(json.dumps([str(root), session]).encode()).hexdigest()
|
|
97
|
+
return Path(tempfile.gettempdir()) / f"rulepack-stop-{key}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def find_new_stop_findings(directory: Path, session: str, started: float) -> list[str]:
|
|
101
|
+
"""The changed files' findings, unless this session's last stop reported them."""
|
|
102
|
+
config = resolve_hook_config(directory)
|
|
103
|
+
if config is None:
|
|
104
|
+
return []
|
|
105
|
+
findings = lint_within_budget(config, ["--changed", "--only", "scan"], started)
|
|
106
|
+
marker = find_stop_marker_path(config.root, session)
|
|
107
|
+
if not findings:
|
|
108
|
+
marker.unlink(missing_ok=True)
|
|
109
|
+
return []
|
|
110
|
+
digest = hashlib.sha256(json.dumps(findings).encode()).hexdigest().encode()
|
|
111
|
+
if marker.is_file() and marker.read_bytes() == digest:
|
|
112
|
+
return []
|
|
113
|
+
with tempfile.NamedTemporaryFile(
|
|
114
|
+
dir=marker.parent, delete_on_close=False
|
|
115
|
+
) as pending:
|
|
116
|
+
pending.write(digest)
|
|
117
|
+
pending.close()
|
|
118
|
+
Path(pending.name).replace(marker)
|
|
119
|
+
return findings
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def group_paths_by_project(
|
|
123
|
+
directory: Path, paths: list[Path]
|
|
124
|
+
) -> dict[Path, list[Path]]:
|
|
125
|
+
"""The edited paths inside the workspace, keyed by the project config's folder."""
|
|
126
|
+
workspace = find_git_root(directory) or directory
|
|
127
|
+
projects: dict[Path, list[Path]] = {}
|
|
128
|
+
for path in paths:
|
|
129
|
+
if not path.is_relative_to(workspace):
|
|
130
|
+
continue
|
|
131
|
+
git_root = find_git_root(path.parent)
|
|
132
|
+
start = path.parent if git_root else directory
|
|
133
|
+
config = find_config_path(start, git_root)
|
|
134
|
+
if config and path.is_relative_to(config.parent):
|
|
135
|
+
projects.setdefault(config.parent, []).append(path)
|
|
136
|
+
return projects
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def find_post_edit_findings(payload: HookPayload, started: float) -> list[str]:
|
|
140
|
+
directory = payload.resolve_directory()
|
|
141
|
+
projects = group_paths_by_project(directory, payload.list_edited_paths(directory))
|
|
142
|
+
return [
|
|
143
|
+
finding
|
|
144
|
+
for root, paths in projects.items()
|
|
145
|
+
for finding in find_edited_file_findings(root, paths, started)
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def find_event_findings(event: str, payload: HookPayload, started: float) -> list[str]:
|
|
150
|
+
if event == "post-edit":
|
|
151
|
+
return find_post_edit_findings(payload, started)
|
|
152
|
+
return find_new_stop_findings(
|
|
153
|
+
payload.resolve_directory(), payload.session_id, started
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def main(argv: list[str] | None = None) -> int:
|
|
158
|
+
"""Write the event's findings to stderr; a check that cannot run stays quiet."""
|
|
159
|
+
started = time.monotonic()
|
|
160
|
+
parser = argparse.ArgumentParser(
|
|
161
|
+
prog="rulepack hook", description="Run checks for agent edits and stops."
|
|
162
|
+
)
|
|
163
|
+
parser.add_argument("event", choices=("post-edit", "stop"))
|
|
164
|
+
event = parser.parse_args(argv).event
|
|
165
|
+
try:
|
|
166
|
+
payload = HookPayload.model_validate_json(sys.stdin.read())
|
|
167
|
+
findings = find_event_findings(event, payload, started)
|
|
168
|
+
except subprocess.TimeoutExpired:
|
|
169
|
+
logger.warning("rulepack hook: timed out (time budget exhausted)")
|
|
170
|
+
return HookExit.QUIET
|
|
171
|
+
except (ConfigError, OSError, RuntimeError, ValueError) as error:
|
|
172
|
+
logger.warning("rulepack hook: %s", error)
|
|
173
|
+
return HookExit.QUIET
|
|
174
|
+
if not findings:
|
|
175
|
+
return HookExit.QUIET
|
|
176
|
+
sys.stderr.write("\n".join(findings) + "\n")
|
|
177
|
+
return HookExit.REPORT
|
rulepack/hook/payload.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def parse_patch_paths(patch: str) -> list[str]:
|
|
7
|
+
"""The files an apply_patch command adds or updates, after any move."""
|
|
8
|
+
paths: list[str] = []
|
|
9
|
+
updating = False
|
|
10
|
+
for line in patch.split("\n"):
|
|
11
|
+
# Leading whitespace in an update hunk marks unchanged file content.
|
|
12
|
+
header, _, path = (line.rstrip() if updating else line.strip()).partition(": ")
|
|
13
|
+
if not path:
|
|
14
|
+
continue
|
|
15
|
+
match header:
|
|
16
|
+
case "*** Update File":
|
|
17
|
+
paths.append(path)
|
|
18
|
+
updating = True
|
|
19
|
+
case "*** Add File":
|
|
20
|
+
paths.append(path)
|
|
21
|
+
updating = False
|
|
22
|
+
case "*** Delete File":
|
|
23
|
+
updating = False
|
|
24
|
+
case "*** Move to" if updating:
|
|
25
|
+
paths[-1] = path
|
|
26
|
+
return paths
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ToolInput(BaseModel):
|
|
30
|
+
file_path: Path | None = None
|
|
31
|
+
command: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class HookPayload(BaseModel):
|
|
35
|
+
"""The fields rulepack reads from an agent's hook payload; others are ignored."""
|
|
36
|
+
|
|
37
|
+
model_config = ConfigDict(coerce_numbers_to_str=True)
|
|
38
|
+
|
|
39
|
+
cwd: Path | None = None
|
|
40
|
+
workspace_roots: list[Path] = Field(default_factory=list)
|
|
41
|
+
file_path: Path | None = None
|
|
42
|
+
tool_name: str | None = None
|
|
43
|
+
tool_input: ToolInput = Field(default_factory=ToolInput)
|
|
44
|
+
session_id: str = ""
|
|
45
|
+
|
|
46
|
+
def resolve_directory(self) -> Path:
|
|
47
|
+
"""The agent's cwd, else the workspace root that holds the edited file."""
|
|
48
|
+
if self.cwd is not None:
|
|
49
|
+
return self.cwd.resolve()
|
|
50
|
+
if self.file_path is not None:
|
|
51
|
+
edited = self.file_path.resolve()
|
|
52
|
+
for workspace in self.workspace_roots:
|
|
53
|
+
if edited.is_relative_to(root := workspace.resolve()):
|
|
54
|
+
return root
|
|
55
|
+
return Path.cwd()
|
|
56
|
+
|
|
57
|
+
def list_edited_paths(self, directory: Path) -> list[Path]:
|
|
58
|
+
if self.tool_name == "apply_patch":
|
|
59
|
+
patch = self.tool_input.command or ""
|
|
60
|
+
return [(directory / path).resolve() for path in parse_patch_paths(patch)]
|
|
61
|
+
path = self.tool_input.file_path or self.file_path
|
|
62
|
+
return [(directory / path).resolve()] if path else []
|
|
File without changes
|