diff-to-test 0.0.1__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,318 @@
1
+ """Example test discovery and LLM prompt construction."""
2
+
3
+ import re
4
+ from pathlib import Path, PurePosixPath
5
+
6
+ from diff2test.models import Attempt, Config, FileChange, Message, TestContext
7
+ from diff2test.profiles import Profile, load_profile, select_profile
8
+ from diff2test.prompts import load_prompt
9
+
10
+ _IGNORED_SCAN_DIRS = frozenset(
11
+ {".git", ".venv", "venv", "node_modules", "build", "dist", "__pycache__"}
12
+ )
13
+ _TEST_FILE_EXTS: dict[str, tuple[str, ...]] = {
14
+ "python": (".py",),
15
+ "dart": (".dart",),
16
+ "typescript": (".ts", ".tsx"),
17
+ "javascript": (".js", ".jsx", ".mjs", ".cjs"),
18
+ "go": (".go",),
19
+ "rust": (".rs",),
20
+ }
21
+
22
+
23
+ def _strip_source_root(posix_path: str, language: str) -> PurePosixPath:
24
+ parts = list(PurePosixPath(posix_path).parts)
25
+ if language == "python" and len(parts) >= 2 and parts[0] == "src":
26
+ # src/<pkg>/foo/bar.py -> foo/bar.py; src/bar.py -> bar.py
27
+ if len(parts) >= 3:
28
+ return PurePosixPath(*parts[2:])
29
+ return PurePosixPath(parts[1])
30
+ if language == "dart" and len(parts) >= 2 and parts[0] == "lib":
31
+ return PurePosixPath(*parts[1:])
32
+ if language in {"typescript", "javascript", "rust"} and len(parts) >= 2 and parts[0] == "src":
33
+ return PurePosixPath(*parts[1:])
34
+ return PurePosixPath(posix_path)
35
+
36
+
37
+ def _base_test_parts(
38
+ change: FileChange,
39
+ framework: str | None,
40
+ ) -> tuple[PurePosixPath, str, str]:
41
+ """Return ``(parent_dir, stem_base, test_suffix_with_ext)``."""
42
+ lang = change.language
43
+ if not lang and framework:
44
+ lang = {
45
+ "pytest": "python",
46
+ "flutter": "dart",
47
+ "npm": "typescript",
48
+ "go": "go",
49
+ "cargo": "rust",
50
+ }.get(framework, "")
51
+
52
+ rel = _strip_source_root(change.path.replace("\\", "/"), lang)
53
+ parent = rel.parent
54
+ stem = rel.stem
55
+ ext = PurePosixPath(change.path).suffix
56
+
57
+ if lang == "python":
58
+ test_parent = (
59
+ PurePosixPath("tests") / parent if str(parent) != "." else PurePosixPath("tests")
60
+ )
61
+ return test_parent, f"test_{stem}", ".py"
62
+ if lang == "dart":
63
+ test_parent = (
64
+ PurePosixPath("test") / parent if str(parent) != "." else PurePosixPath("test")
65
+ )
66
+ return test_parent, stem, "_test.dart"
67
+ if lang == "go":
68
+ return PurePosixPath(change.path.replace("\\", "/")).parent, stem, "_test.go"
69
+ if lang in {"typescript", "javascript"}:
70
+ test_parent = (
71
+ PurePosixPath("tests") / parent if str(parent) != "." else PurePosixPath("tests")
72
+ )
73
+ return test_parent, stem, f".test{ext or '.ts'}"
74
+ if lang == "rust":
75
+ test_parent = (
76
+ PurePosixPath("tests") / parent if str(parent) != "." else PurePosixPath("tests")
77
+ )
78
+ return test_parent, stem, "_test.rs"
79
+
80
+ test_parent = PurePosixPath("tests") / parent if str(parent) != "." else PurePosixPath("tests")
81
+ return test_parent, f"test_{stem}", ext or ".txt"
82
+
83
+
84
+ def resolve_test_path(
85
+ repo_root: Path,
86
+ change: FileChange,
87
+ framework: str | None = None,
88
+ ) -> Path:
89
+ """Resolve a non-colliding repo-relative test file path for ``change``."""
90
+ parent, base_stem, suffix = _base_test_parts(change, framework)
91
+ candidate = Path(*(parent.parts if str(parent) != "." else ())) / f"{base_stem}{suffix}"
92
+ if not (repo_root / candidate).exists():
93
+ return candidate
94
+
95
+ suffix_tag = "_diff2test"
96
+ attempt = 1
97
+ while True:
98
+ tag = suffix_tag if attempt == 1 else f"{suffix_tag}_{attempt}"
99
+ alt = Path(*(parent.parts if str(parent) != "." else ())) / f"{base_stem}{tag}{suffix}"
100
+ if not (repo_root / alt).exists():
101
+ return alt
102
+ attempt += 1
103
+
104
+
105
+ def _is_candidate_test_file(rel_path: Path, language: str) -> bool:
106
+ parts = rel_path.parts
107
+ if any(part in _IGNORED_SCAN_DIRS for part in parts):
108
+ return False
109
+ name = rel_path.name
110
+ if language and not name.endswith(_TEST_FILE_EXTS.get(language, ())):
111
+ return False
112
+ if language == "python":
113
+ return name.startswith("test_") or name.endswith("_test.py")
114
+ if language == "dart":
115
+ return name.endswith("_test.dart")
116
+ if language == "go":
117
+ return name.endswith("_test.go")
118
+ if language in {"typescript", "javascript"}:
119
+ return ".test." in name or ".spec." in name
120
+ if language == "rust":
121
+ return name.endswith("_test.rs") or "tests" in parts
122
+ return "test" in parts or "tests" in parts or name.startswith("test_") or "_test." in name
123
+
124
+
125
+ def _tokenize(text: str) -> set[str]:
126
+ return {tok for tok in re.split(r"[^a-zA-Z0-9]+", text.lower()) if tok}
127
+
128
+
129
+ def find_example_tests(repo_root: Path, change: FileChange, limit: int = 2) -> list[Path]:
130
+ """Find up to ``limit`` relevant existing test files (repo-relative) for style cloning."""
131
+ if limit <= 0 or not repo_root.is_dir():
132
+ return []
133
+
134
+ source_rel = _strip_source_root(change.path.replace("\\", "/"), change.language)
135
+ source_stem = source_rel.stem.lower()
136
+ source_dir_parts = set(p.lower() for p in source_rel.parent.parts if p != ".")
137
+ source_tokens = _tokenize(source_rel.as_posix())
138
+
139
+ scored: list[tuple[float, str, Path]] = []
140
+ for abs_path in repo_root.rglob("*"):
141
+ if not abs_path.is_file():
142
+ continue
143
+ rel_path = abs_path.relative_to(repo_root)
144
+ if not _is_candidate_test_file(rel_path, change.language):
145
+ continue
146
+
147
+ posix = rel_path.as_posix()
148
+ stem_lower = rel_path.stem.lower()
149
+ score = 0.0
150
+
151
+ if stem_lower in {f"test_{source_stem}", f"{source_stem}_test", f"{source_stem}.test"}:
152
+ score += 100.0
153
+ if source_dir_parts and source_dir_parts.issubset(
154
+ {p.lower() for p in rel_path.parent.parts}
155
+ ):
156
+ score += 40.0
157
+ overlap = len(source_tokens & _tokenize(posix))
158
+ score += overlap * 15.0
159
+
160
+ try:
161
+ mtime = abs_path.stat().st_mtime
162
+ except OSError:
163
+ mtime = 0.0
164
+ # Small recency bonus in [0, 1) so ties favor recently touched tests
165
+ score += min(mtime / 1e13, 0.999)
166
+
167
+ scored.append((score, posix, rel_path))
168
+
169
+ scored.sort(key=lambda item: (-item[0], item[1]))
170
+ return [item[2] for item in scored[:limit]]
171
+
172
+
173
+ def read_truncated(path: Path, max_lines: int = 200) -> str:
174
+ """Read up to ``max_lines`` lines from ``path`` with a truncation marker if needed."""
175
+ text = path.read_text(encoding="utf-8", errors="replace")
176
+ lines = text.splitlines()
177
+ if len(lines) <= max_lines:
178
+ return text
179
+ return "\n".join(lines[:max_lines]) + "\n... [truncated]"
180
+
181
+
182
+ _IMPORT_PREFIXES = ("import ", "from ", "package ", "use ", "const ", "require(")
183
+
184
+
185
+ def collect_source_context(repo_root: Path, change: FileChange, max_lines: int = 400) -> str:
186
+ """Collect full source code or windowed hunks + imports when the file is large."""
187
+ source_path = repo_root / change.path
188
+ if not source_path.is_file():
189
+ return ""
190
+
191
+ raw = source_path.read_text(encoding="utf-8", errors="replace")
192
+ lines = raw.splitlines()
193
+
194
+ if len(lines) <= max_lines:
195
+ content = raw
196
+ else:
197
+ changed_lines = {line_no for hunk in change.hunks for line_no, _ in hunk.added_lines}
198
+ selected: set[int] = set()
199
+ for idx, line in enumerate(lines, start=1):
200
+ if line.lstrip().startswith(_IMPORT_PREFIXES):
201
+ selected.add(idx)
202
+ for line_no in changed_lines:
203
+ start = max(1, line_no - 25)
204
+ end = min(len(lines), line_no + 25)
205
+ selected.update(range(start, end + 1))
206
+
207
+ if not selected:
208
+ selected.update(range(1, min(len(lines), max_lines) + 1))
209
+
210
+ chunks: list[str] = []
211
+ prev = 0
212
+ for idx in sorted(selected):
213
+ if prev and idx > prev + 1:
214
+ chunks.append("...")
215
+ chunks.append(f"{idx}: {lines[idx - 1]}")
216
+ prev = idx
217
+ content = "\n".join(chunks)
218
+
219
+ if change.language == "python":
220
+ conftest_path = repo_root / "tests" / "conftest.py"
221
+ if conftest_path.is_file():
222
+ conftest_text = read_truncated(conftest_path, max_lines=100)
223
+ content = f"{content}\n\n# --- tests/conftest.py ---\n{conftest_text}"
224
+
225
+ return content
226
+
227
+
228
+ def _format_diff_lines(change: FileChange) -> str:
229
+ lines = [f"+{line_no}: {text}" for hunk in change.hunks for line_no, text in hunk.added_lines]
230
+ return "\n".join(lines) if lines else "(no added lines)"
231
+
232
+
233
+ def _format_example_tests(example_tests: tuple[tuple[str, str], ...]) -> str:
234
+ if not example_tests:
235
+ return "(none found)"
236
+ blocks = [f"### `{path}`\n```\n{content.strip()}\n```" for path, content in example_tests]
237
+ return "\n\n".join(blocks)
238
+
239
+
240
+ def build_context(
241
+ repo_root: Path,
242
+ change: FileChange,
243
+ cfg: Config,
244
+ profile: Profile | None = None,
245
+ ) -> TestContext:
246
+ """Assemble ``TestContext`` for generating tests for ``change``."""
247
+ active_profile = profile
248
+ if active_profile is None:
249
+ if cfg.profile and cfg.profile != "auto":
250
+ active_profile = load_profile(cfg.profile, repo_root=repo_root)
251
+ else:
252
+ active_profile = select_profile(cfg.framework, repo_root=repo_root)
253
+
254
+ example_paths = find_example_tests(repo_root, change, limit=2)
255
+ example_tests = tuple(
256
+ (rel.as_posix(), read_truncated(repo_root / rel, max_lines=200)) for rel in example_paths
257
+ )
258
+ target_path = resolve_test_path(repo_root, change, framework=cfg.framework).as_posix()
259
+ source_code = collect_source_context(repo_root, change)
260
+
261
+ instructions = active_profile.instructions.strip()
262
+ if cfg.extra_instructions.strip():
263
+ instructions = f"{instructions}\n\n{cfg.extra_instructions.strip()}".strip()
264
+
265
+ return TestContext(
266
+ source_file=change,
267
+ source_code=source_code,
268
+ example_tests=example_tests,
269
+ target_test_path=target_path,
270
+ profile_instructions=instructions,
271
+ )
272
+
273
+
274
+ def build_generation_prompt(ctx: TestContext) -> list[Message]:
275
+ """Render system and user messages for initial test generation."""
276
+ system_msg = Message(role="system", content=load_prompt("system").strip())
277
+ symbols = ", ".join(ctx.source_file.changed_symbols) or "(none detected)"
278
+ user_template = load_prompt("generate")
279
+ user_content = user_template.format(
280
+ source_path=ctx.source_file.path,
281
+ language=ctx.source_file.language or "unknown",
282
+ target_test_path=ctx.target_test_path,
283
+ changed_symbols=symbols,
284
+ profile_instructions=ctx.profile_instructions or "(none)",
285
+ diff_lines=_format_diff_lines(ctx.source_file),
286
+ source_code=ctx.source_code,
287
+ example_tests=_format_example_tests(ctx.example_tests),
288
+ )
289
+ return [system_msg, Message(role="user", content=user_content.strip())]
290
+
291
+
292
+ def _tail_lines(text: str, max_lines: int) -> str:
293
+ lines = text.splitlines()
294
+ if len(lines) <= max_lines:
295
+ return text
296
+ return "... [earlier output truncated]\n" + "\n".join(lines[-max_lines:])
297
+
298
+
299
+ def build_fix_prompt(
300
+ ctx: TestContext,
301
+ attempt: Attempt,
302
+ max_output_lines: int = 150,
303
+ ) -> list[Message]:
304
+ """Render system and user messages for fixing a failed test attempt."""
305
+ system_msg = Message(role="system", content=load_prompt("system").strip())
306
+ violations = ", ".join(attempt.guard_violations) or "(none)"
307
+ user_template = load_prompt("fix")
308
+ user_content = user_template.format(
309
+ attempt_number=attempt.number,
310
+ target_test_path=ctx.target_test_path,
311
+ source_path=ctx.source_file.path,
312
+ exit_code=attempt.exit_code,
313
+ guard_violations=violations,
314
+ previous_code=attempt.test_code,
315
+ error_output=_tail_lines(attempt.output, max_output_lines),
316
+ source_code=ctx.source_code,
317
+ )
318
+ return [system_msg, Message(role="user", content=user_content.strip())]
@@ -0,0 +1,255 @@
1
+ """Git diff retrieval, parsing, and change filtering."""
2
+
3
+ import contextlib
4
+ import fnmatch
5
+ import logging
6
+ import re
7
+ import subprocess
8
+ from dataclasses import replace
9
+ from pathlib import Path
10
+
11
+ from diff2test.config import DEFAULT_EXCLUDES
12
+ from diff2test.models import Config, FileChange, Hunk
13
+ from diff2test.symbols import extract_changed_symbols
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(.+?) b/(.+)$")
18
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
19
+ _EXTENSION_LANGUAGE: dict[str, str] = {
20
+ ".py": "python",
21
+ ".dart": "dart",
22
+ ".ts": "typescript",
23
+ ".tsx": "typescript",
24
+ ".js": "javascript",
25
+ ".jsx": "javascript",
26
+ ".mjs": "javascript",
27
+ ".cjs": "javascript",
28
+ ".go": "go",
29
+ ".rs": "rust",
30
+ }
31
+
32
+
33
+ def detect_language(path: str) -> str:
34
+ """Return canonical language name from file extension, or empty string if unsupported."""
35
+ return _EXTENSION_LANGUAGE.get(Path(path).suffix.lower(), "")
36
+
37
+
38
+ class GitError(RuntimeError):
39
+ """Raised when a git command fails."""
40
+
41
+
42
+ def _run_git(repo_root: Path, args: list[str]) -> str:
43
+ """Execute a git command inside ``repo_root`` and return stdout."""
44
+ result = subprocess.run(
45
+ ["git", *args],
46
+ cwd=repo_root,
47
+ capture_output=True,
48
+ text=True,
49
+ encoding="utf-8",
50
+ errors="replace",
51
+ check=False,
52
+ )
53
+ if result.returncode != 0:
54
+ detail = result.stderr.strip() or result.stdout.strip() or f"exit code {result.returncode}"
55
+ raise GitError(f"git {' '.join(args)} failed: {detail}")
56
+ return result.stdout
57
+
58
+
59
+ def get_repo_root(path: Path) -> Path:
60
+ """Return the top-level git repository directory containing ``path``."""
61
+ target = path if path.is_dir() else path.parent
62
+ out = _run_git(target, ["rev-parse", "--show-toplevel"])
63
+ return Path(out.strip())
64
+
65
+
66
+ def _try_fetch_for_merge_base(repo_root: Path, base: str) -> None:
67
+ """Best-effort fetch to unshallow or retrieve ``base`` for merge-base resolution."""
68
+ with contextlib.suppress(GitError):
69
+ is_shallow = _run_git(repo_root, ["rev-parse", "--is-shallow-repository"]).strip()
70
+ if is_shallow == "true":
71
+ _run_git(repo_root, ["fetch", "--no-tags", "--unshallow"])
72
+
73
+ branch = base[len("origin/") :] if base.startswith("origin/") else base
74
+ if branch:
75
+ with contextlib.suppress(GitError):
76
+ _run_git(
77
+ repo_root,
78
+ ["fetch", "--no-tags", "origin", f"{branch}:refs/remotes/origin/{branch}"],
79
+ )
80
+
81
+
82
+ def get_merge_base(repo_root: Path, base: str, head: str = "HEAD") -> str:
83
+ """Return the merge-base commit SHA between ``base`` and ``head``."""
84
+ try:
85
+ return _run_git(repo_root, ["merge-base", base, head]).strip()
86
+ except GitError as first_exc:
87
+ _try_fetch_for_merge_base(repo_root, base)
88
+ try:
89
+ return _run_git(repo_root, ["merge-base", base, head]).strip()
90
+ except GitError:
91
+ try:
92
+ fallback = _run_git(repo_root, ["rev-parse", "--verify", base]).strip()
93
+ except GitError:
94
+ raise first_exc from None
95
+ logger.warning(
96
+ "Could not compute merge-base for %s..%s; falling back to %s.",
97
+ base,
98
+ head,
99
+ fallback,
100
+ )
101
+ return fallback
102
+
103
+
104
+ def get_diff(repo_root: Path, base: str, head: str = "HEAD") -> str:
105
+ """Return the unified diff between the merge-base of ``base``/``head`` and ``head``."""
106
+ merge_base = get_merge_base(repo_root, base, head)
107
+ return _run_git(
108
+ repo_root,
109
+ ["diff", "--unified=3", "--no-color", "--find-renames", f"{merge_base}..{head}"],
110
+ )
111
+
112
+
113
+ def _normalize_diff_path(raw_path: str) -> str:
114
+ return raw_path.strip().strip('"').replace("\\", "/")
115
+
116
+
117
+ def parse_diff(diff_text: str) -> list[FileChange]:
118
+ """Parse a unified ``git diff`` string into ``FileChange`` records."""
119
+ if not diff_text.strip():
120
+ return []
121
+
122
+ changes: list[FileChange] = []
123
+ sections = re.split(r"(?=^diff --git )", diff_text, flags=re.MULTILINE)
124
+
125
+ for section in sections:
126
+ section = section.strip("\r\n")
127
+ if not section.startswith("diff --git "):
128
+ continue
129
+
130
+ lines = section.splitlines()
131
+ header_match = _DIFF_HEADER_RE.match(lines[0])
132
+ if not header_match:
133
+ continue
134
+
135
+ path = _normalize_diff_path(header_match.group(2))
136
+ status = "M"
137
+ is_deleted = False
138
+ is_binary = False
139
+ hunks: list[Hunk] = []
140
+
141
+ current_hunk_meta: tuple[int, int, int, int] | None = None
142
+ current_added: list[tuple[int, str]] = []
143
+ new_line_no = 0
144
+
145
+ for line in lines[1:]:
146
+ if current_hunk_meta is None:
147
+ if line.startswith("new file mode "):
148
+ status = "A"
149
+ elif line.startswith("deleted file mode ") or line == "+++ /dev/null":
150
+ is_deleted = True
151
+ elif line.startswith(("rename from ", "rename to ")):
152
+ status = "R"
153
+ elif line.startswith("Binary files ") or line == "GIT binary patch":
154
+ is_binary = True
155
+ elif line.startswith("+++ b/"):
156
+ path = _normalize_diff_path(line[6:])
157
+
158
+ hunk_match = _HUNK_HEADER_RE.match(line)
159
+ if hunk_match:
160
+ if current_hunk_meta is not None:
161
+ hunks.append(Hunk(*current_hunk_meta, added_lines=tuple(current_added)))
162
+ old_start = int(hunk_match.group(1))
163
+ old_len = int(hunk_match.group(2) or "1")
164
+ new_start = int(hunk_match.group(3))
165
+ new_len = int(hunk_match.group(4) or "1")
166
+ current_hunk_meta = (old_start, old_len, new_start, new_len)
167
+ current_added = []
168
+ new_line_no = new_start
169
+ continue
170
+
171
+ if current_hunk_meta is None:
172
+ continue
173
+
174
+ if line.startswith("+") and not line.startswith("+++"):
175
+ current_added.append((new_line_no, line[1:]))
176
+ new_line_no += 1
177
+ elif line.startswith("-") and not line.startswith("---"):
178
+ continue
179
+ elif line.startswith(" "):
180
+ new_line_no += 1
181
+
182
+ if current_hunk_meta is not None:
183
+ hunks.append(Hunk(*current_hunk_meta, added_lines=tuple(current_added)))
184
+
185
+ if is_deleted or is_binary:
186
+ continue
187
+
188
+ changes.append(
189
+ FileChange(
190
+ path=path,
191
+ status=status,
192
+ hunks=tuple(hunks),
193
+ language=detect_language(path),
194
+ )
195
+ )
196
+
197
+ return changes
198
+
199
+
200
+ def _matches_exclude(posix_path: str, pattern: str) -> bool:
201
+ """Return True if ``posix_path`` matches a glob ``pattern``."""
202
+ norm_path = posix_path.lstrip("/")
203
+ norm_pattern = pattern.lstrip("/")
204
+ if fnmatch.fnmatch(norm_path, norm_pattern):
205
+ return True
206
+ if "/" not in norm_pattern and fnmatch.fnmatch(Path(norm_path).name, norm_pattern):
207
+ return True
208
+ return norm_pattern.startswith("**/") and _matches_exclude(norm_path, norm_pattern[3:])
209
+
210
+
211
+ def _added_line_count(change: FileChange) -> int:
212
+ return sum(len(hunk.added_lines) for hunk in change.hunks)
213
+
214
+
215
+ def filter_changes(changes: list[FileChange], cfg: Config) -> list[FileChange]:
216
+ """Filter ignored/unsupported changes and enforce diff line and file limits."""
217
+ patterns = DEFAULT_EXCLUDES + cfg.exclude
218
+ kept: list[FileChange] = []
219
+
220
+ for change in changes:
221
+ posix_path = change.path.replace("\\", "/")
222
+ if any(_matches_exclude(posix_path, pat) for pat in patterns):
223
+ continue
224
+ if not change.language:
225
+ continue
226
+ added_lines = _added_line_count(change)
227
+ if added_lines == 0:
228
+ continue
229
+ if added_lines > cfg.max_diff_lines:
230
+ logger.warning(
231
+ "Skipping '%s': %d added lines exceed max_diff_lines (%d).",
232
+ change.path,
233
+ added_lines,
234
+ cfg.max_diff_lines,
235
+ )
236
+ continue
237
+ kept.append(change)
238
+
239
+ kept.sort(key=lambda c: (-_added_line_count(c), c.path))
240
+ return kept[: cfg.max_files]
241
+
242
+
243
+ def enrich_with_symbols(repo_root: Path, changes: list[FileChange]) -> list[FileChange]:
244
+ """Populate ``changed_symbols`` on each ``FileChange`` by reading its source file."""
245
+ enriched: list[FileChange] = []
246
+ for change in changes:
247
+ file_path = repo_root / change.path
248
+ if not file_path.is_file():
249
+ enriched.append(change)
250
+ continue
251
+ source_code = file_path.read_text(encoding="utf-8", errors="replace")
252
+ changed_lines = {line_no for hunk in change.hunks for line_no, _ in hunk.added_lines}
253
+ symbols = extract_changed_symbols(source_code, changed_lines, change.language)
254
+ enriched.append(replace(change, changed_symbols=symbols))
255
+ return enriched