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.
@@ -0,0 +1,351 @@
1
+ import argparse
2
+ import importlib.metadata
3
+ import importlib.resources
4
+ import logging
5
+ import re
6
+ import sys
7
+ import tomllib
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ import yaml
12
+
13
+ from rulepack.config import CONFIG_FILE_NAME, StrictModel
14
+ from rulepack.config.project_paths import find_git_root
15
+ from rulepack.lint.command import main as run_lint
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ Action = Literal["create", "append", "exists, skipped"]
20
+ RULEPACK_REPOSITORY = "https://github.com/justmatias/rulepack"
21
+ PRE_COMMIT_CONFIG = ".pre-commit-config.yaml"
22
+ WORKFLOW = Path(".github/workflows/rulepack.yml")
23
+ DEFAULT_CHECKS_DIR = "lint"
24
+ PYPROJECT = "pyproject.toml"
25
+ POE_TASKS_FILE = "poe_tasks.toml"
26
+ POE_TASK_HEADER = re.compile(r"^\[[^\]]*\.(?P<task>[A-Za-z0-9_-]+)\]$", re.MULTILINE)
27
+ TOP_LEVEL_KEY = re.compile(r"^[^\s#-][^:]*:")
28
+ LIST_ITEM = re.compile(r"^(?P<indent>\s*)-\s")
29
+
30
+
31
+ class InitError(Exception):
32
+ pass
33
+
34
+
35
+ class PlannedFile(StrictModel):
36
+ path: Path
37
+ action: Action
38
+ # The file's full content after the change; empty when skipped.
39
+ content: str = ""
40
+
41
+
42
+ class PoeTasksTarget(StrictModel):
43
+ path: Path
44
+ # The dotted table the tasks live under in that file.
45
+ table: str
46
+
47
+
48
+ class ReposInsertionPoint(StrictModel):
49
+ line_index: int
50
+ item_indent: str
51
+
52
+
53
+ def read_rulepack_version() -> str:
54
+ return importlib.metadata.version("rulepack")
55
+
56
+
57
+ def render_template(name: str, **values: str) -> str:
58
+ text = (
59
+ importlib.resources
60
+ .files("rulepack.init")
61
+ .joinpath("templates", name)
62
+ .read_text(encoding="utf-8")
63
+ )
64
+ for key, value in values.items():
65
+ text = text.replace(f"{{{{{key}}}}}", value)
66
+ return text
67
+
68
+
69
+ def plan_new_file(path: Path, content: str) -> PlannedFile:
70
+ if path.exists():
71
+ return PlannedFile(path=path, action="exists, skipped")
72
+ return PlannedFile(path=path, action="create", content=content)
73
+
74
+
75
+ def plan_layout(root: Path, checks_dir: str | None) -> list[PlannedFile]:
76
+ """The config, plus a local checks folder when the repo keeps its own checks."""
77
+ local_checks = f'sgconfig = "{checks_dir}/sgconfig.yml"\n\n' if checks_dir else ""
78
+ config = plan_new_file(
79
+ root / CONFIG_FILE_NAME,
80
+ render_template("rulepack.toml", local_checks=local_checks),
81
+ )
82
+ if checks_dir is None:
83
+ return [config]
84
+ checks = root / checks_dir
85
+ return [
86
+ config,
87
+ plan_new_file(checks / "sgconfig.yml", render_template("sgconfig.yml")),
88
+ plan_new_file(checks / "rules" / ".gitkeep", ""),
89
+ plan_new_file(checks / "rule-tests" / ".gitkeep", ""),
90
+ ]
91
+
92
+
93
+ def find_repos_insertion_point(lines: list[str]) -> ReposInsertionPoint:
94
+ """Where the rulepack entry goes in `repos:` and the indent its items use."""
95
+ start = next(
96
+ (index for index, line in enumerate(lines) if re.match(r"^repos:\s*$", line)),
97
+ None,
98
+ )
99
+ if start is None:
100
+ raise InitError(f"{PRE_COMMIT_CONFIG} has no top-level 'repos:' list")
101
+ end = next(
102
+ (
103
+ index
104
+ for index in range(start + 1, len(lines))
105
+ if TOP_LEVEL_KEY.match(lines[index])
106
+ ),
107
+ len(lines),
108
+ )
109
+ while end > start + 1 and not lines[end - 1].strip():
110
+ end -= 1
111
+ indent = next(
112
+ (
113
+ match["indent"]
114
+ for line in lines[start + 1 : end]
115
+ if (match := LIST_ITEM.match(line))
116
+ ),
117
+ " ",
118
+ )
119
+ return ReposInsertionPoint(line_index=end, item_indent=indent)
120
+
121
+
122
+ def append_pre_commit_entry(text: str, entry: str) -> str:
123
+ lines = text.splitlines()
124
+ insertion = find_repos_insertion_point(lines)
125
+ end = insertion.line_index
126
+ block = [
127
+ f"{insertion.item_indent}{line}" if line else line
128
+ for line in entry.splitlines()
129
+ ]
130
+ updated = "\n".join([*lines[:end], *block, *lines[end:]]) + "\n"
131
+ try:
132
+ before = (yaml.safe_load(text) or {}).get("repos") or []
133
+ except yaml.YAMLError as error:
134
+ raise InitError(f"{PRE_COMMIT_CONFIG} is not valid YAML: {error}") from error
135
+ after = (yaml.safe_load(updated) or {}).get("repos") or []
136
+ if len(after) != len(before) + 1 or after[: len(before)] != before:
137
+ raise InitError(f"could not append the rulepack hooks to {PRE_COMMIT_CONFIG}")
138
+ return updated
139
+
140
+
141
+ def plan_pre_commit(root: Path, version: str) -> PlannedFile:
142
+ path = root / PRE_COMMIT_CONFIG
143
+ entry = render_template("pre-commit.yaml", version=version)
144
+ if not path.is_file():
145
+ indented = "".join(f" {line}\n" for line in entry.splitlines())
146
+ return PlannedFile(path=path, action="create", content=f"repos:\n{indented}")
147
+ text = path.read_text(encoding="utf-8")
148
+ if RULEPACK_REPOSITORY in text:
149
+ return PlannedFile(path=path, action="exists, skipped")
150
+ return PlannedFile(
151
+ path=path, action="append", content=append_pre_commit_entry(text, entry)
152
+ )
153
+
154
+
155
+ def plan_workflow(root: Path, version: str) -> PlannedFile:
156
+ return plan_new_file(
157
+ root / WORKFLOW, render_template("workflow.yml", version=version)
158
+ )
159
+
160
+
161
+ def choose_poe_tasks_target(root: Path) -> PoeTasksTarget:
162
+ """pyproject.toml when the repo has one; otherwise poe's own poe_tasks.toml."""
163
+ pyproject = root / PYPROJECT
164
+ if pyproject.is_file():
165
+ return PoeTasksTarget(path=pyproject, table="tool.poe.tasks")
166
+ return PoeTasksTarget(path=root / POE_TASKS_FILE, table="tasks")
167
+
168
+
169
+ def read_poe_task_names(text: str, target: PoeTasksTarget) -> set[str]:
170
+ try:
171
+ table = tomllib.loads(text)
172
+ except tomllib.TOMLDecodeError as error:
173
+ raise InitError(f"{target.path.name} is not valid TOML: {error}") from error
174
+ for key in target.table.split("."):
175
+ table = table.get(key) or {}
176
+ return set(table)
177
+
178
+
179
+ def split_poe_task_blocks(table: str) -> dict[str, str]:
180
+ """The template's blocks (separated by blank lines), by the task they define."""
181
+ blocks = render_template("poe-tasks.toml", table=table).strip().split("\n\n")
182
+ return {
183
+ match["task"]: block
184
+ for block in blocks
185
+ if (match := POE_TASK_HEADER.search(block))
186
+ }
187
+
188
+
189
+ def plan_poe_tasks(root: Path) -> PlannedFile:
190
+ target = choose_poe_tasks_target(root)
191
+ path = target.path
192
+ text = path.read_text(encoding="utf-8") if path.is_file() else ""
193
+ defined = read_poe_task_names(text, target)
194
+ blocks = split_poe_task_blocks(target.table)
195
+ missing = [block for task, block in blocks.items() if task not in defined]
196
+ if not missing:
197
+ return PlannedFile(path=path, action="exists, skipped")
198
+ separator = "\n" if text and not text.endswith("\n") else ""
199
+ prefix = f"{text}{separator}\n" if text else ""
200
+ updated = prefix + "\n\n".join(missing) + "\n"
201
+ # Appended tables clash with tasks the file defines inline (`tasks = {...}`).
202
+ try:
203
+ tomllib.loads(updated)
204
+ except tomllib.TOMLDecodeError as error:
205
+ raise InitError(f"could not add the poe tasks to {path.name}") from error
206
+ return PlannedFile(
207
+ path=path, action="append" if text else "create", content=updated
208
+ )
209
+
210
+
211
+ def find_existing_layout(root: Path) -> Path | None:
212
+ candidates = (root / CONFIG_FILE_NAME, root / DEFAULT_CHECKS_DIR / "sgconfig.yml")
213
+ return next((path for path in candidates if path.is_file()), None)
214
+
215
+
216
+ def build_plan(root: Path, arguments: argparse.Namespace) -> list[PlannedFile]:
217
+ plan: list[PlannedFile] = []
218
+ if existing := find_existing_layout(root):
219
+ logger.info(
220
+ "init: %s already exists; the layout is left as it is, only missing "
221
+ "optional pieces are added",
222
+ existing.relative_to(root),
223
+ )
224
+ else:
225
+ plan.extend(plan_layout(root, choose_checks_dir(arguments)))
226
+ version = read_rulepack_version()
227
+ if arguments.pre_commit:
228
+ plan.append(plan_pre_commit(root, version))
229
+ if arguments.ci == "github":
230
+ plan.append(plan_workflow(root, version))
231
+ if arguments.poe:
232
+ plan.append(plan_poe_tasks(root))
233
+ return plan
234
+
235
+
236
+ def show_plan(plan: list[PlannedFile], root: Path) -> None:
237
+ for planned in plan:
238
+ logger.info(" %-16s %s", planned.action, planned.path.relative_to(root))
239
+
240
+
241
+ def ask_yes_no(question: str) -> bool:
242
+ sys.stderr.write(f"{question} [y/N] ")
243
+ sys.stderr.flush()
244
+ return sys.stdin.readline().strip().lower() in {"y", "yes"}
245
+
246
+
247
+ def choose_checks_dir(arguments: argparse.Namespace) -> str | None:
248
+ """--checks-dir, or the person's answer when nobody passed it.
249
+
250
+ Only a person at a terminal is asked; --yes, --dry-run, scripts and agents get
251
+ the default, a repo that keeps its checks elsewhere.
252
+ """
253
+ checks_dir: str | None = arguments.checks_dir
254
+ can_ask = sys.stdin.isatty() and not arguments.yes and not arguments.dry_run
255
+ if checks_dir is not None or not can_ask:
256
+ return checks_dir
257
+ keeps_own_checks = ask_yes_no(
258
+ f"Keep this repo's own checks in {DEFAULT_CHECKS_DIR}/?"
259
+ )
260
+ return DEFAULT_CHECKS_DIR if keeps_own_checks else None
261
+
262
+
263
+ def write_plan(plan: list[PlannedFile]) -> None:
264
+ for planned in plan:
265
+ if planned.action == "exists, skipped":
266
+ continue
267
+ planned.path.parent.mkdir(parents=True, exist_ok=True)
268
+ planned.path.write_text(planned.content, encoding="utf-8")
269
+
270
+
271
+ def parse_relative_folder(value: str) -> str:
272
+ path = Path(value)
273
+ if path.is_absolute() or ".." in path.parts:
274
+ raise argparse.ArgumentTypeError(f"'{value}' must be a folder inside the repo")
275
+ return path.as_posix()
276
+
277
+
278
+ def parse_arguments(argv: list[str] | None) -> argparse.Namespace:
279
+ parser = argparse.ArgumentParser(
280
+ prog="rulepack init",
281
+ description=(
282
+ "Scaffold the rules-as-checks layout: .rulepack.toml, and with "
283
+ "--checks-dir an ast-grep sgconfig with empty rules/ and rule-tests/. "
284
+ "Shows the plan and waits for confirmation; never overwrites a file."
285
+ ),
286
+ )
287
+ parser.add_argument(
288
+ "--checks-dir",
289
+ type=parse_relative_folder,
290
+ help=(
291
+ "Keep this repo's own checks in this folder (for example lint). "
292
+ "Without it, the repo only consumes checks kept elsewhere."
293
+ ),
294
+ )
295
+ parser.add_argument(
296
+ "--pre-commit",
297
+ action="store_true",
298
+ help=f"Add the rulepack hooks to {PRE_COMMIT_CONFIG}, pinned to this version.",
299
+ )
300
+ parser.add_argument(
301
+ "--ci",
302
+ choices=["github"],
303
+ help=f"Write {WORKFLOW.as_posix()}, which runs the rulepack action.",
304
+ )
305
+ parser.add_argument(
306
+ "--poe",
307
+ action="store_true",
308
+ help=(
309
+ f"Add lint-rules and lint-rules-changed poe tasks to {PYPROJECT}, "
310
+ f"or to {POE_TASKS_FILE} when the repo has no {PYPROJECT}."
311
+ ),
312
+ )
313
+ parser.add_argument(
314
+ "--dry-run", action="store_true", help="Print the plan and write nothing."
315
+ )
316
+ parser.add_argument(
317
+ "--yes", action="store_true", help="Write without asking for confirmation."
318
+ )
319
+ return parser.parse_args(argv)
320
+
321
+
322
+ def main(argv: list[str] | None = None) -> int:
323
+ """`rulepack init`: scaffold the rules-as-checks layout in any repo.
324
+
325
+ It shows every file it would write and waits for confirmation. It never overwrites
326
+ a file: it creates missing ones, and appends to `.pre-commit-config.yaml` and the
327
+ poe tasks file only when the rulepack entries are not there yet, so a second run
328
+ changes nothing.
329
+ """
330
+ arguments = parse_arguments(argv)
331
+ current_directory = Path.cwd().resolve()
332
+ root = find_git_root(current_directory) or current_directory
333
+ try:
334
+ plan = build_plan(root, arguments)
335
+ except InitError as error:
336
+ logger.error("rulepack init: %s", error)
337
+ return 2
338
+ logger.info("init: plan for %s", root)
339
+ show_plan(plan, root)
340
+ if all(planned.action == "exists, skipped" for planned in plan):
341
+ logger.info("init: nothing to write")
342
+ return 0
343
+ if arguments.dry_run:
344
+ logger.info("init: dry run, nothing written")
345
+ return 0
346
+ if not arguments.yes and not ask_yes_no("Write these files?"):
347
+ logger.info("init: nothing written")
348
+ return 1
349
+ write_plan(plan)
350
+ logger.info("init: done; running rulepack lint on the new layout")
351
+ return run_lint([])
@@ -0,0 +1,10 @@
1
+ # Rules as checks (written by `rulepack init --poe`).
2
+ [{{table}}.lint-rules]
3
+ help = "Run every rulepack check on the whole repo"
4
+ cmd = "rulepack lint"
5
+
6
+ # Only the files changed against the base branch; warnings fail too.
7
+ # Add --base-ref REF to change the base, or --staged to scan the staged files.
8
+ [{{table}}.lint-rules-changed]
9
+ help = "Run the rulepack checks on the files changed against the base branch"
10
+ cmd = "rulepack lint --changed"
@@ -0,0 +1,6 @@
1
+ - repo: https://github.com/justmatias/rulepack
2
+ rev: v{{version}}
3
+ hooks:
4
+ - id: rulepack-lint
5
+ - id: rulepack-rules
6
+ - id: rulepack-imports
@@ -0,0 +1,4 @@
1
+ # rulepack's config (written by `rulepack init`). Every `rulepack` command reads
2
+ # this file; run `rulepack config` to see the resolved values.
3
+ {{local_checks}}[scan]
4
+ exclude = []
@@ -0,0 +1,6 @@
1
+ # ast-grep config (written by `rulepack init`): one rule per file in rules/, and
2
+ # its valid and invalid cases in rule-tests/<id>-test.yml.
3
+ ruleDirs:
4
+ - rules
5
+ testConfigs:
6
+ - testDir: rule-tests
@@ -0,0 +1,23 @@
1
+ # Written by `rulepack init --ci github`: the full scan on every push, and on pull
2
+ # requests also the changed-files scan, where warnings fail too.
3
+ name: rulepack
4
+
5
+ on:
6
+ push:
7
+ branches: ["main"]
8
+ pull_request:
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ jobs:
14
+ lint:
15
+ name: rulepack lint
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ # The changed-files scan needs the base branch: keep the full history.
19
+ - uses: actions/checkout@v7
20
+ with:
21
+ fetch-depth: 0
22
+
23
+ - uses: justmatias/rulepack@v{{version}}
File without changes
@@ -0,0 +1,97 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+
4
+
5
+ class ChangedFilesError(Exception):
6
+ pass
7
+
8
+
9
+ def run_git(root: Path, *arguments: str) -> subprocess.CompletedProcess[str]:
10
+ return subprocess.run(
11
+ ["git", *arguments],
12
+ cwd=root,
13
+ capture_output=True,
14
+ text=True,
15
+ encoding="utf-8",
16
+ errors="replace",
17
+ check=False,
18
+ )
19
+
20
+
21
+ def read_git_lines(root: Path, *arguments: str) -> list[str]:
22
+ completed = run_git(root, *arguments)
23
+ if completed.returncode != 0:
24
+ raise ChangedFilesError(
25
+ f"git {' '.join(arguments)} failed: {completed.stderr.strip()}"
26
+ )
27
+ return [line for line in completed.stdout.splitlines() if line]
28
+
29
+
30
+ def ref_exists(root: Path, ref: str) -> bool:
31
+ completed = run_git(root, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}")
32
+ return completed.returncode == 0
33
+
34
+
35
+ def strip_remote_prefix(ref: str) -> str:
36
+ """`origin/main` -> `main`; a ref without a remote prefix stays as it is."""
37
+ return ref.split("/", 1)[1] if "/" in ref else ref
38
+
39
+
40
+ def resolve_base_ref(root: Path, explicit: str | None, default: str) -> str | None:
41
+ if explicit is not None:
42
+ if not ref_exists(root, explicit):
43
+ raise ChangedFilesError(
44
+ f"base ref '{explicit}' does not exist. Fetch it first "
45
+ "(CI: actions/checkout with fetch-depth: 0)."
46
+ )
47
+ return explicit
48
+ for candidate in (default, strip_remote_prefix(default)):
49
+ if ref_exists(root, candidate):
50
+ return candidate
51
+ return None
52
+
53
+
54
+ def resolve_diff_base(root: Path, base_ref: str | None, explicit: bool) -> str:
55
+ if base_ref is not None:
56
+ merge_base = run_git(root, "merge-base", base_ref, "HEAD")
57
+ if merge_base.returncode == 0:
58
+ return merge_base.stdout.strip()
59
+ if explicit:
60
+ raise ChangedFilesError(
61
+ f"no merge base between '{base_ref}' and HEAD (shallow clone?)."
62
+ )
63
+ return "HEAD" if ref_exists(root, "HEAD") else "--cached"
64
+
65
+
66
+ def list_changed_files(
67
+ root: Path,
68
+ *,
69
+ base_ref: str | None = None,
70
+ default_base_ref: str = "origin/main",
71
+ staged: bool = False,
72
+ extensions: list[str] | None = None,
73
+ ) -> list[Path]:
74
+ """Changed files that still exist, as absolute paths, sorted.
75
+
76
+ Without `staged`: committed changes since the merge base with the base ref,
77
+ uncommitted changes, and untracked files. If the default base has no merge
78
+ base, compare against HEAD (or include staged files before the first commit).
79
+ An explicit base must resolve. With `staged`: only the staged files.
80
+ """
81
+ if staged:
82
+ names = read_git_lines(
83
+ root, "diff", "--cached", "--name-only", "--diff-filter=ACMR"
84
+ )
85
+ else:
86
+ resolved = resolve_base_ref(root, base_ref, default_base_ref)
87
+ base = resolve_diff_base(root, resolved, explicit=base_ref is not None)
88
+ names = read_git_lines(
89
+ root, "diff", "--name-only", "--diff-filter=ACMR", base, "--"
90
+ )
91
+ names += read_git_lines(root, "ls-files", "--others", "--exclude-standard")
92
+ paths = {root / name for name in names}
93
+ return sorted(
94
+ path
95
+ for path in paths
96
+ if path.is_file() and (extensions is None or path.suffix in extensions)
97
+ )