codeveto 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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,479 @@
1
+ """Docker pack (SPEC 6.1, 6.5): Dockerfile and Containerfile patterns.
2
+
3
+ Instructions come from ``FileContext.statements()`` (continuation-joined,
4
+ heredoc bodies inside their ``RUN``), so a heredoc line that looks like an
5
+ instruction is never read as one. Arguments are split into words by
6
+ :func:`_words`, which follows Docker's quoting and drops the escape
7
+ character at line ends and comment lines inside a continuation. The ``RUN``
8
+ commands themselves are read by the shell pack (``shell/rm-rf-variable``).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Iterator
15
+ from dataclasses import dataclass
16
+
17
+ from codeveto import jsonsafe, lexers, statements
18
+ from codeveto.rules.base import FileContext, Hit, rule
19
+ from codeveto.statements import Statement
20
+
21
+ _KEYWORD = re.compile(r"[ \t]*([A-Za-z]{1,20})")
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class _Word:
26
+ start: int # offset in the statement's text
27
+ end: int
28
+ value: str # quotes removed
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class _Instruction:
33
+ keyword: str
34
+ words: tuple[_Word, ...]
35
+ args: str # the argument text, lines joined with spaces
36
+ statement: Statement
37
+
38
+
39
+ def _words(text: str, start: int, esc: str) -> tuple[list[_Word], str]:
40
+ """Words of ``text[start:]`` and the joined argument text.
41
+
42
+ Lines after the first that are comments are dropped; an ``esc`` at the
43
+ end of a line joins it with the next as whitespace.
44
+ """
45
+ words: list[_Word] = []
46
+ joined: list[str] = []
47
+ pos = start
48
+ first = True
49
+ while pos <= len(text):
50
+ nl = text.find("\n", pos)
51
+ line_end = len(text) if nl < 0 else nl
52
+ line = text[pos:line_end].rstrip("\r")
53
+ content_end = pos + len(line.rstrip(" \t"))
54
+ if not first and line.lstrip(" \t").startswith("#"):
55
+ pos = line_end + 1
56
+ if nl < 0:
57
+ break
58
+ continue
59
+ if content_end > pos and text[content_end - 1] == esc:
60
+ content_end -= 1
61
+ joined.append(text[pos:content_end])
62
+ _split_line(text, pos, content_end, esc, words)
63
+ first = False
64
+ if nl < 0:
65
+ break
66
+ pos = nl + 1
67
+ return words, " ".join(joined).strip()
68
+
69
+
70
+ def _split_line(text: str, i: int, end: int, esc: str, out: list[_Word]) -> None:
71
+ while i < end:
72
+ if text[i] in " \t":
73
+ i += 1
74
+ continue
75
+ start = i
76
+ value: list[str] = []
77
+ while i < end and text[i] not in " \t":
78
+ c = text[i]
79
+ if c in "\"'":
80
+ j = i + 1
81
+ while j < end and text[j] != c:
82
+ if text[j] == esc and c == '"' and j + 1 < end:
83
+ j += 1
84
+ value.append(text[j])
85
+ j += 1
86
+ i = min(j + 1, end)
87
+ continue
88
+ if c == esc and i + 1 < end:
89
+ value.append(text[i + 1])
90
+ i += 2
91
+ continue
92
+ value.append(c)
93
+ i += 1
94
+ out.append(_Word(start, i, "".join(value)))
95
+
96
+
97
+ def _instructions(stmts: tuple[Statement, ...], esc: str) -> list[_Instruction]:
98
+ out: list[_Instruction] = []
99
+ for stmt in stmts:
100
+ m = _KEYWORD.match(stmt.text)
101
+ if m is None:
102
+ continue
103
+ keyword = m.group(1).upper()
104
+ words, args = _words(stmt.text, m.end(), esc)
105
+ if keyword == "ONBUILD" and words:
106
+ continue # runs in a child image's build, not this one
107
+ out.append(_Instruction(keyword, tuple(words), args, stmt))
108
+ return out
109
+
110
+
111
+ def _parse(ctx: FileContext) -> list[_Instruction]:
112
+ text = ctx.new_text
113
+ if not text:
114
+ return []
115
+ return _instructions(ctx.statements(), lexers.docker_escape(text))
116
+
117
+
118
+ def _parse_text(text: str | None, path: str) -> list[_Instruction]:
119
+ if not text:
120
+ return []
121
+ result = lexers.lex(text, "dockerfile", path=path)
122
+ stmts = statements.split(text, "dockerfile", result, lexers.mask(text, result), path=path)
123
+ return _instructions(stmts, lexers.docker_escape(text))
124
+
125
+
126
+ def _position(ins: _Instruction, offset: int, ctx: FileContext) -> tuple[int, int]:
127
+ return ctx.line_index.position(ins.statement.start + offset)
128
+
129
+
130
+ # --- docker/secret-in-env -----------------------------------------------------------
131
+
132
+ _SECRET_LAST = frozenset(
133
+ {
134
+ "password",
135
+ "passwd",
136
+ "passphrase",
137
+ "pass",
138
+ "secret",
139
+ "token",
140
+ "apikey",
141
+ "credential",
142
+ "credentials",
143
+ "privatekey",
144
+ "secretkey",
145
+ "accesskey",
146
+ }
147
+ )
148
+ _SECRET_PAIRS = frozenset(
149
+ {
150
+ ("api", "key"),
151
+ ("private", "key"),
152
+ ("secret", "key"),
153
+ ("access", "key"),
154
+ ("auth", "key"),
155
+ ("signing", "key"),
156
+ ("encryption", "key"),
157
+ ("master", "key"),
158
+ ("client", "secret"),
159
+ }
160
+ )
161
+ _PLACEHOLDERS = frozenset(
162
+ {
163
+ "changeme",
164
+ "change_me",
165
+ "change-me",
166
+ "replaceme",
167
+ "replace_me",
168
+ "replace-me",
169
+ "placeholder",
170
+ "dummy",
171
+ "example",
172
+ "todo",
173
+ "none",
174
+ "null",
175
+ "nil",
176
+ "true",
177
+ "false",
178
+ "yes",
179
+ "no",
180
+ "on",
181
+ "off",
182
+ "unset",
183
+ "disabled",
184
+ "redacted",
185
+ }
186
+ )
187
+ _NAME_SPLIT = re.compile(r"[^A-Za-z0-9]+")
188
+
189
+
190
+ def secret_name(name: str) -> bool:
191
+ """Does an ENV/ARG name say it holds a secret (``DB_PASSWORD``, ``NPM_TOKEN``)?"""
192
+ tokens = [t for t in _NAME_SPLIT.split(name.lower()) if t]
193
+ if not tokens:
194
+ return False
195
+ if tokens[-1] in _SECRET_LAST:
196
+ return True
197
+ return len(tokens) >= 2 and (tokens[-2], tokens[-1]) in _SECRET_PAIRS
198
+
199
+
200
+ def literal_secret(value: str) -> bool:
201
+ """Is ``value`` a literal that could be a real secret (not a reference or placeholder)?"""
202
+ v = value.strip()
203
+ lower = v.lower()
204
+ if not v or "$" in v or lower in _PLACEHOLDERS:
205
+ return False
206
+ if v.startswith(("/", "./", "~/")):
207
+ return False # a path to a mounted secret, not the secret
208
+ if v.startswith("<") and v.endswith(">"):
209
+ return False
210
+ if lower.startswith(("your_", "your-", "<your")):
211
+ return False
212
+ if len(set(v)) == 1:
213
+ return False # xxxx, ****
214
+ return not (v.isdigit() and len(v) <= 4)
215
+
216
+
217
+ def _env_pairs(ins: _Instruction) -> Iterator[tuple[str, _Word | None, int, int, str]]:
218
+ """``(name, word, value start, value end, value)`` of each ENV/ARG definition."""
219
+ words = ins.words
220
+ if not words:
221
+ return
222
+ if ins.keyword == "ENV" and "=" not in words[0].value:
223
+ # Legacy form: ENV NAME the rest of the line.
224
+ if len(words) >= 2:
225
+ value = " ".join(w.value for w in words[1:])
226
+ yield words[0].value, words[0], words[1].start, words[-1].end, value
227
+ return
228
+ for word in words:
229
+ name, eq, value = word.value.partition("=")
230
+ if not eq:
231
+ continue
232
+ start = ins.statement.text.find("=", word.start, word.end) + 1
233
+ end = word.end
234
+ quote = ins.statement.text[start : start + 1]
235
+ if quote in ("'", '"') and end - start >= 2 and ins.statement.text[end - 1] == quote:
236
+ start, end = start + 1, end - 1
237
+ yield name, word, start, end, value
238
+
239
+
240
+ def _redact(
241
+ ctx: FileContext, ins: _Instruction, start: int, end: int
242
+ ) -> tuple[tuple[int, int, int | None], ...]:
243
+ spans: list[tuple[int, int, int | None]] = []
244
+ abs_start = ins.statement.start + start
245
+ abs_end = ins.statement.start + end
246
+ index = ctx.line_index
247
+ line, col = index.position(abs_start)
248
+ last_line, last_col = index.position(max(abs_end - 1, abs_start))
249
+ if line == last_line:
250
+ return ((line, col, last_col + 1),)
251
+ spans.append((line, col, None))
252
+ for mid in range(line + 1, last_line):
253
+ spans.append((mid, 1, None))
254
+ spans.append((last_line, 1, last_col + 1))
255
+ return tuple(spans)
256
+
257
+
258
+ @rule(
259
+ id="docker/secret-in-env",
260
+ severity="error",
261
+ title="Secret written into the image with ENV or ARG",
262
+ languages={"dockerfile"},
263
+ rationale=(
264
+ "ENV values are stored in the image config and ARG values in its build history, "
265
+ "so anyone who can pull the image can read them. Reported when the name ends in "
266
+ "a secret word (PASSWORD, TOKEN, SECRET, API_KEY, PRIVATE_KEY...) and the value "
267
+ "is a literal; `${VAR}` references, empty values, paths to mounted secrets and "
268
+ "placeholders such as `changeme` are not reported."
269
+ ),
270
+ hint="Pass secrets at build time with RUN --mount=type=secret, or at run time.",
271
+ tags={"docker", "security", "secrets", "cwe-798"},
272
+ )
273
+ def secret_in_env(ctx: FileContext) -> Iterator[Hit]:
274
+ """``ENV DB_PASSWORD=literal`` and ``ARG NPM_TOKEN=literal``."""
275
+ for ins in _parse(ctx):
276
+ if ins.keyword not in ("ENV", "ARG"):
277
+ continue
278
+ for name, _, start, end, value in _env_pairs(ins):
279
+ if not secret_name(name) or not literal_secret(value) or end <= start:
280
+ continue
281
+ line, column = _position(ins, start, ctx)
282
+ yield Hit(
283
+ line,
284
+ column=column,
285
+ message=f"{ins.keyword} {name[:80]} holds a literal secret",
286
+ evidence=f"{ins.keyword} {name[:80]}={value[:200]}",
287
+ redact=_redact(ctx, ins, start, end),
288
+ )
289
+
290
+
291
+ # --- docker/latest-tag --------------------------------------------------------------
292
+
293
+
294
+ def _from_parts(ins: _Instruction) -> tuple[_Word | None, str | None]:
295
+ """The image word of a FROM and its ``AS`` stage name."""
296
+ words = [w for w in ins.words if not w.value.startswith("--")]
297
+ image = words[0] if words else None
298
+ stage = None
299
+ if len(words) >= 3 and words[1].value.lower() == "as":
300
+ stage = words[2].value.lower()
301
+ return image, stage
302
+
303
+
304
+ def _tag(image: str) -> str | None:
305
+ """The tag of an image reference (``None`` without one); digests return ``@``."""
306
+ if "@" in image:
307
+ return "@"
308
+ last = image.rsplit("/", 1)[-1]
309
+ return last.split(":", 1)[1] if ":" in last else None
310
+
311
+
312
+ @rule(
313
+ id="docker/latest-tag",
314
+ severity="warning",
315
+ title="Base image not pinned to a version",
316
+ languages={"dockerfile"},
317
+ rationale=(
318
+ "FROM without a tag, or with `:latest`, builds on whatever the registry serves "
319
+ "that day, so builds are not reproducible and a compromised or breaking upstream "
320
+ "image flows in unreviewed. Digests (`@sha256:...`), earlier build stages, "
321
+ "`scratch` and image names built from ARG variables are not reported."
322
+ ),
323
+ hint="Pin a version tag, ideally with its digest: image:1.2.3@sha256:...",
324
+ tags={"docker", "supply-chain", "reproducibility"},
325
+ )
326
+ def latest_tag(ctx: FileContext) -> Iterator[Hit]:
327
+ """``FROM image`` and ``FROM image:latest``."""
328
+ stages: set[str] = set()
329
+ for ins in _parse(ctx):
330
+ if ins.keyword != "FROM":
331
+ continue
332
+ image, stage = _from_parts(ins)
333
+ if image is not None:
334
+ ref = image.value
335
+ lower = ref.lower()
336
+ tag = _tag(ref)
337
+ if not (lower in stages or lower == "scratch" or "$" in ref or tag == "@") and (
338
+ tag is None or tag == "latest"
339
+ ):
340
+ line, column = _position(ins, image.start, ctx)
341
+ what = "uses :latest" if tag else "has no tag (defaults to :latest)"
342
+ yield Hit(
343
+ line,
344
+ column=column,
345
+ message=f"Base image {ref[:120]} {what}",
346
+ evidence=f"FROM {ref[:200]}",
347
+ )
348
+ if stage is not None:
349
+ stages.add(stage)
350
+
351
+
352
+ # --- docker/root-user ---------------------------------------------------------------
353
+
354
+ _ROOT = frozenset({"root", "0"})
355
+ _NONROOT_TAG = re.compile(r"non-?root|rootless", re.IGNORECASE)
356
+
357
+
358
+ @dataclass(frozen=True, slots=True)
359
+ class _Final:
360
+ root: bool
361
+ from_line: int
362
+ end_line: int
363
+ user_line: int | None # the USER root line that decides it, if any
364
+
365
+
366
+ def _final_stage(instructions: list[_Instruction]) -> _Final | None:
367
+ """Whether the last stage runs as root, following ``FROM <earlier stage>``."""
368
+ users: dict[str, bool] = {} # stage name -> runs as root
369
+ current: tuple[bool, int, int | None] | None = None
370
+ from_line = end_line = 0
371
+ last_stage: str | None = None
372
+ for ins in instructions:
373
+ end_line = ins.statement.end_line
374
+ if ins.keyword == "FROM":
375
+ image, stage = _from_parts(ins)
376
+ ref = image.value if image is not None else ""
377
+ tag = _tag(ref) or ""
378
+ root = users[ref.lower()] if ref.lower() in users else not _NONROOT_TAG.search(tag)
379
+ current = (root, ins.statement.start_line, None)
380
+ from_line = ins.statement.start_line
381
+ if stage is not None:
382
+ users[stage] = root
383
+ last_stage = stage
384
+ elif ins.keyword == "USER" and current is not None and ins.words:
385
+ user = ins.words[0].value.split(":", 1)[0].lower()
386
+ # A user chosen at build time ($APP_USER) is not reported.
387
+ root = "$" not in user and user in _ROOT
388
+ current = (root, current[1], ins.statement.start_line if root else None)
389
+ if last_stage is not None:
390
+ users[last_stage] = root
391
+ if current is None:
392
+ return None
393
+ return _Final(current[0], from_line, end_line, current[2])
394
+
395
+
396
+ @rule(
397
+ id="docker/root-user",
398
+ severity="warning",
399
+ title="Image runs as root",
400
+ languages={"dockerfile"},
401
+ scope="file",
402
+ rationale=(
403
+ "Without a USER instruction (or with USER root/0) in the final stage, the "
404
+ "container's process runs as root, so a compromise of it starts with full "
405
+ "rights inside the container. Reported only when the change makes the final "
406
+ "stage run as root; a stage built FROM an earlier one inherits its USER, and "
407
+ "base images tagged nonroot or rootless count as non-root."
408
+ ),
409
+ hint="Create an unprivileged user and switch to it with USER before CMD/ENTRYPOINT.",
410
+ tags={"docker", "security", "least-privilege"},
411
+ )
412
+ def root_user(ctx: FileContext) -> Iterator[Hit]:
413
+ """The final stage runs as root and did not before the change."""
414
+ new = _final_stage(_parse(ctx))
415
+ if new is None or not new.root:
416
+ return
417
+ if ctx.old_text is not None:
418
+ old = _final_stage(_parse_text(ctx.old_text, ctx.old_path or ctx.path))
419
+ if old is not None and old.root:
420
+ return
421
+ if new.user_line is not None:
422
+ yield Hit(new.user_line, message="USER switches the final stage to root")
423
+ return
424
+ yield Hit(
425
+ new.from_line,
426
+ end_line=new.end_line,
427
+ message="The final stage has no USER instruction, so it runs as root",
428
+ )
429
+
430
+
431
+ # --- docker/add-remote-url ----------------------------------------------------------
432
+
433
+
434
+ def _add_sources(ins: _Instruction) -> tuple[list[tuple[str, int]], bool]:
435
+ """``([(source, offset)], has --checksum)`` of an ADD instruction."""
436
+ checksum = any(w.value.startswith("--checksum=") for w in ins.words)
437
+ args = ins.args
438
+ while args.startswith("--"):
439
+ _, _, args = args.partition(" ")
440
+ args = args.lstrip()
441
+ if args.startswith("["):
442
+ try:
443
+ items = jsonsafe.loads(args)
444
+ except ValueError:
445
+ items = None
446
+ if isinstance(items, list) and all(isinstance(x, str) for x in items):
447
+ text = ins.statement.text
448
+ offset = next((w.start for w in ins.words if text[w.start] == "["), 0)
449
+ return [(x, offset) for x in items[:-1]], checksum
450
+ words = [w for w in ins.words if not w.value.startswith("--")]
451
+ return [(w.value, w.start) for w in words[:-1]], checksum
452
+
453
+
454
+ @rule(
455
+ id="docker/add-remote-url",
456
+ severity="warning",
457
+ title="ADD downloads a URL without a checksum",
458
+ languages={"dockerfile"},
459
+ rationale=(
460
+ "ADD with an http(s) URL fetches whatever the server returns at build time, "
461
+ "unverified. `ADD --checksum=sha256:...` pins the content and is not reported; "
462
+ "COPY never fetches."
463
+ ),
464
+ hint="Add --checksum=sha256:<digest>, or download in RUN and verify the checksum.",
465
+ tags={"docker", "supply-chain"},
466
+ )
467
+ def add_remote_url(ctx: FileContext) -> Iterator[Hit]:
468
+ """``ADD https://...`` without ``--checksum``."""
469
+ for ins in _parse(ctx):
470
+ if ins.keyword != "ADD":
471
+ continue
472
+ sources, checksum = _add_sources(ins)
473
+ if checksum:
474
+ continue
475
+ for source, offset in sources:
476
+ if source.lower().startswith(("http://", "https://")):
477
+ line, column = _position(ins, offset, ctx)
478
+ yield Hit(line, column=column, evidence=f"ADD {source[:300]}")
479
+ break
@@ -0,0 +1,148 @@
1
+ """Rule examples as data (SPEC 5.3): one module per pack, ``examples/<pack>.py``.
2
+
3
+ Each module defines ``EXAMPLES``, a mapping from rule ID to that rule's
4
+ examples (``bad(...)``, ``good(...)`` or :class:`~codeveto.rules.base.Example`
5
+ values). The mapping is the link between a rule and its examples:
6
+ ``tests/rules/test_examples.py`` fails for a registered rule that has no
7
+ entry, fewer than two bad or two good examples, and for an entry whose rule
8
+ is not registered by the pack.
9
+
10
+ :func:`example_changeset` turns an example into the
11
+ :class:`~codeveto.model.Changeset` the engine reviews, the same way for the
12
+ tests, the website and the precision scripts.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib
18
+ from collections.abc import Mapping
19
+ from types import MappingProxyType
20
+
21
+ from codeveto.model import Changeset, FileChange, FileKind, FileStatus
22
+ from codeveto.rules.base import Change, Example
23
+
24
+ __all__ = ["ExampleError", "example_changeset", "load_examples"]
25
+
26
+ _SYMLINK = "120000"
27
+ _GITLINK = "160000"
28
+ _REGULAR = ("100644", "100755")
29
+
30
+
31
+ class ExampleError(ValueError):
32
+ """An examples module is missing ``EXAMPLES`` or holds something else than examples."""
33
+
34
+
35
+ def load_examples(pack: str) -> Mapping[str, tuple[Example, ...]]:
36
+ """``EXAMPLES`` of ``examples/<pack>.py``, validated; empty when there is no module."""
37
+ try:
38
+ module = importlib.import_module(f"{__name__}.{pack}")
39
+ except ModuleNotFoundError as exc:
40
+ if exc.name == f"{__name__}.{pack}":
41
+ return MappingProxyType({})
42
+ raise
43
+ data = getattr(module, "EXAMPLES", None)
44
+ if not isinstance(data, Mapping):
45
+ raise ExampleError(f"examples module {pack!r} must define an EXAMPLES mapping")
46
+ result: dict[str, tuple[Example, ...]] = {}
47
+ for rule_id, examples in data.items():
48
+ if not isinstance(rule_id, str) or not rule_id.startswith(f"{pack}/"):
49
+ raise ExampleError(f"examples module {pack!r} has a key outside its pack: {rule_id!r}")
50
+ items = tuple(examples)
51
+ if any(not isinstance(e, Example) for e in items):
52
+ raise ExampleError(f"examples for {rule_id!r} must all be Example values")
53
+ result[rule_id] = items
54
+ return MappingProxyType(result)
55
+
56
+
57
+ def _change(path: str, change: Change) -> FileChange:
58
+ has_old = change.old is not None
59
+ has_new = change.new is not None
60
+ if change.old_path is not None:
61
+ status = FileStatus.RENAMED
62
+ elif has_old and not has_new:
63
+ status = FileStatus.DELETED
64
+ elif has_old:
65
+ status = FileStatus.MODIFIED
66
+ else:
67
+ status = FileStatus.ADDED
68
+ new_mode = change.mode
69
+ if change.binary:
70
+ old_mode = "100644" if status is not FileStatus.ADDED else None
71
+ if status is FileStatus.DELETED:
72
+ new_mode = None
73
+ elif new_mode is None:
74
+ new_mode = "100644"
75
+ return FileChange(
76
+ path=path,
77
+ old_path=change.old_path,
78
+ status=status,
79
+ kind=FileKind.BINARY,
80
+ old_mode=old_mode,
81
+ new_mode=new_mode,
82
+ old_text=None,
83
+ new_text=None,
84
+ old_size=None if old_mode is None else (change.size or 0),
85
+ new_size=None if new_mode is None else (change.size or 0),
86
+ similarity=100 if status is FileStatus.RENAMED and change.old == change.new else None,
87
+ )
88
+ if new_mode in (_SYMLINK, _GITLINK):
89
+ kind = FileKind.SYMLINK if new_mode == _SYMLINK else FileKind.SUBMODULE
90
+ target = change.new
91
+ return FileChange(
92
+ path=path,
93
+ old_path=change.old_path,
94
+ status=status,
95
+ kind=kind,
96
+ old_mode=new_mode if has_old else None,
97
+ new_mode=new_mode if has_new else None,
98
+ old_text=None,
99
+ new_text=None,
100
+ old_size=None,
101
+ new_size=None,
102
+ symlink_target=target if kind is FileKind.SYMLINK else None,
103
+ submodule_old=change.old.strip() if kind is FileKind.SUBMODULE and change.old else None,
104
+ submodule_new=target.strip() if kind is FileKind.SUBMODULE and target else None,
105
+ similarity=100 if status is FileStatus.RENAMED and change.old == change.new else None,
106
+ )
107
+ flags = []
108
+ old_mode = "100644" if has_old else None
109
+ if has_new and new_mode is None:
110
+ new_mode = "100644"
111
+ if old_mode in _REGULAR and new_mode in _REGULAR and old_mode != new_mode:
112
+ flags.append("mode-change")
113
+ similarity = None
114
+ if status is FileStatus.RENAMED:
115
+ similarity = 100 if change.old == change.new else 90
116
+ return FileChange.from_texts(
117
+ path,
118
+ change.old,
119
+ change.new,
120
+ old_path=change.old_path,
121
+ status=status,
122
+ old_mode=old_mode,
123
+ new_mode=new_mode if has_new else None,
124
+ new_size=change.size,
125
+ similarity=similarity,
126
+ flags=flags,
127
+ )
128
+
129
+
130
+ def example_changeset(example: Example) -> Changeset:
131
+ """The changeset an example stands for, files in the example's order.
132
+
133
+ ``Change.mode`` is the new side's mode (old regular files are
134
+ ``100644``): ``100755`` makes the file executable, ``120000`` a symlink
135
+ to the ``new`` text, ``160000`` a submodule at the ``new`` commit.
136
+ ``binary=True`` makes a binary file whose texts only say which sides
137
+ exist. ``size`` overrides the new side's byte size.
138
+ """
139
+ files = tuple(_change(path, change) for path, change in example.files.items())
140
+ return Changeset(
141
+ mode="range",
142
+ base=None,
143
+ head=None,
144
+ merge_base=None,
145
+ anchor=None,
146
+ anchor_source="base",
147
+ files=files,
148
+ )