codiff 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 (45) hide show
  1. codiff/__init__.py +1 -0
  2. codiff/__main__.py +5 -0
  3. codiff/cli.py +247 -0
  4. codiff/db/__init__.py +16 -0
  5. codiff/db/engine.py +31 -0
  6. codiff/db/models.py +119 -0
  7. codiff/db/operations.py +238 -0
  8. codiff/diff/__init__.py +1 -0
  9. codiff/diff/analysis.py +145 -0
  10. codiff/diff/differ.py +45 -0
  11. codiff/diff/engine.py +80 -0
  12. codiff/diff/indexer.py +134 -0
  13. codiff/diff/snapshot.py +325 -0
  14. codiff/export/__init__.py +5 -0
  15. codiff/export/json.py +43 -0
  16. codiff/export/mermaid.py +475 -0
  17. codiff/export/terminal.py +866 -0
  18. codiff/languages/__init__.py +29 -0
  19. codiff/languages/parser.py +214 -0
  20. codiff/languages/python/__init__.py +0 -0
  21. codiff/languages/python/parser.py +927 -0
  22. codiff/languages/python/resolver.py +178 -0
  23. codiff/languages/repository.py +245 -0
  24. codiff/languages/resolver.py +582 -0
  25. codiff/languages/typescript/__init__.py +0 -0
  26. codiff/languages/typescript/parser.py +612 -0
  27. codiff/languages/typescript/resolver.py +95 -0
  28. codiff/mcp_server.py +83 -0
  29. codiff/schema/__init__.py +25 -0
  30. codiff/schema/diff.py +110 -0
  31. codiff/schema/parsing.py +76 -0
  32. codiff/setup.py +103 -0
  33. codiff/utils/__init__.py +0 -0
  34. codiff/utils/args.py +114 -0
  35. codiff/utils/files.py +62 -0
  36. codiff/utils/git.py +101 -0
  37. codiff/utils/instructions.py +14 -0
  38. codiff/utils/instructions.yaml +50 -0
  39. codiff/utils/terminal.py +10 -0
  40. codiff-0.1.0.dist-info/METADATA +487 -0
  41. codiff-0.1.0.dist-info/RECORD +45 -0
  42. codiff-0.1.0.dist-info/WHEEL +5 -0
  43. codiff-0.1.0.dist-info/entry_points.txt +3 -0
  44. codiff-0.1.0.dist-info/licenses/LICENSE +201 -0
  45. codiff-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,95 @@
1
+ """TypeScript-specific call resolver.
2
+
3
+ TypeScriptCallResolver extends BaseCallResolver with:
4
+ - Linear (single-inheritance) MRO — TypeScript does not support multiple inheritance
5
+ - super() / super.method() resolution for TypeScript classes
6
+ - 'this' as the instance keyword, 'constructor' as the constructor method name
7
+ """
8
+
9
+ from typing import List
10
+
11
+ from codiff.languages.resolver import BaseCallResolver
12
+
13
+
14
+ class TypeScriptCallResolver(BaseCallResolver):
15
+ # ------------------------------------------------------------------
16
+ # BaseCallResolver abstract interface
17
+ # ------------------------------------------------------------------
18
+
19
+ @property
20
+ def instance_keyword(self) -> str:
21
+ return "this"
22
+
23
+ @property
24
+ def constructor_method_name(self) -> str:
25
+ return "constructor"
26
+
27
+ # ------------------------------------------------------------------
28
+ # MRO (linear — TypeScript has single inheritance only)
29
+ # ------------------------------------------------------------------
30
+
31
+ def _compute_mro(self, class_name: str) -> List[str]:
32
+ if class_name in self._mro_cache:
33
+ return self._mro_cache[class_name]
34
+
35
+ in_progress = self._mro_tls.__dict__.setdefault("in_progress", set())
36
+ if class_name in in_progress:
37
+ return [class_name]
38
+
39
+ if class_name not in self.class_id_map:
40
+ return [class_name]
41
+
42
+ class_obj = next((c for c in self.classes if c.name == class_name), None)
43
+ if not class_obj or not class_obj.superclasses:
44
+ mro = [class_name]
45
+ self._mro_cache[class_name] = mro
46
+ return mro
47
+
48
+ parent_name = self._clean_superclass_name(class_obj.superclasses[0])
49
+ if parent_name is None:
50
+ mro = [class_name]
51
+ self._mro_cache[class_name] = mro
52
+ return mro
53
+
54
+ in_progress.add(class_name)
55
+ try:
56
+ parent_mro = self._compute_mro(parent_name)
57
+ finally:
58
+ in_progress.discard(class_name)
59
+
60
+ # Filter current class from parent's MRO to avoid cycles
61
+ parent_mro = [c for c in parent_mro if c != class_name]
62
+
63
+ mro = [class_name] + parent_mro
64
+ self._mro_cache[class_name] = mro
65
+ return mro
66
+
67
+ # ------------------------------------------------------------------
68
+ # super() / super.method() resolution
69
+ # ------------------------------------------------------------------
70
+
71
+ def _resolve_super_call(self, parts: List[str], function) -> List[str]:
72
+ """Resolve TypeScript super() and super.method() calls.
73
+
74
+ super() in constructor → parent's constructor
75
+ super.method() → first parent in MRO that defines method
76
+ """
77
+ if not function.class_name:
78
+ return []
79
+
80
+ class_obj = next((c for c in self.classes if c.name == function.class_name), None)
81
+ if not class_obj or not class_obj.superclasses:
82
+ return []
83
+
84
+ parent_name = self._clean_superclass_name(class_obj.superclasses[0])
85
+ if parent_name is None:
86
+ return []
87
+
88
+ if len(parts) == 1:
89
+ # super() → parent constructor
90
+ resolved = self._find_method_in_mro(parent_name, self.constructor_method_name)
91
+ return [resolved] if resolved else []
92
+
93
+ method_name = parts[1]
94
+ resolved = self._find_method_in_mro(parent_name, method_name)
95
+ return [resolved] if resolved else []
codiff/mcp_server.py ADDED
@@ -0,0 +1,83 @@
1
+ """MCP server — exposes codiff's structural diff as a tool for coding agents.
2
+
3
+ Run with:
4
+ codiff-mcp (after `pip install git+https://github.com/issahammoud/codiff.git`)
5
+ python -m codiff.mcp_server
6
+
7
+ Configure in Claude Code (.mcp.json in the project root):
8
+ {
9
+ "mcpServers": {
10
+ "codiff": { "command": "codiff-mcp" }
11
+ }
12
+ }
13
+ """
14
+
15
+ import sys
16
+ from typing import Optional
17
+
18
+ from mcp.server.fastmcp import FastMCP
19
+ from rich.console import Console
20
+
21
+ from codiff.utils.instructions import load as _load_instructions
22
+
23
+ # The MCP server communicates over stdio, so stdout is the JSON-RPC pipe.
24
+ # Open /dev/tty directly so Rich renders to the user's terminal with full
25
+ # colors and formatting — identical to running `codiff diff` from the CLI.
26
+ try:
27
+ _tty = open("/dev/tty", "w")
28
+ _console = Console(file=_tty, force_terminal=True)
29
+ except OSError:
30
+ _console = Console(file=sys.stderr, force_terminal=True)
31
+
32
+ # Replace the module-level console in export/terminal.py before any render calls.
33
+ import codiff.export.terminal as _render_mod
34
+
35
+ _render_mod.console = _console
36
+
37
+ mcp = FastMCP("codiff")
38
+
39
+ _DESCRIPTION: str = _load_instructions()["mcp_description"]
40
+
41
+
42
+ @mcp.tool(description=_DESCRIPTION)
43
+ def codiff_diff(
44
+ repo_path: str = ".",
45
+ base_ref: str = "HEAD",
46
+ head_ref: Optional[str] = None,
47
+ include_tests: bool = False,
48
+ include_deleted: bool = False,
49
+ format: str = "terminal",
50
+ ) -> str:
51
+ """Compute and render the structural call-graph diff.
52
+
53
+ Returns an empty string for format="terminal" (output goes to the TTY).
54
+ Returns the diagram/data as a string for format="mermaid" or "json".
55
+ """
56
+ from codiff.diff.engine import compute_diff
57
+ from codiff.export import render_json, render_mermaid, render_terminal
58
+
59
+ result = compute_diff(
60
+ repo_path,
61
+ base_ref=base_ref,
62
+ head_ref=head_ref,
63
+ include_tests=include_tests,
64
+ include_deleted=include_deleted,
65
+ )
66
+ head_label = head_ref or "working tree"
67
+
68
+ if format == "mermaid":
69
+ return render_mermaid(result)
70
+ if format == "json":
71
+ return render_json(result, base_ref=base_ref, head_ref=head_label)
72
+
73
+ # terminal — render to TTY, return empty string
74
+ render_terminal(result, base_ref=base_ref, head_ref=head_label, include_tests=include_tests)
75
+ return ""
76
+
77
+
78
+ def main() -> None:
79
+ mcp.run()
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
@@ -0,0 +1,25 @@
1
+ from codiff.schema.diff import (
2
+ AddedFunctionInfo,
3
+ AnalysisResult,
4
+ GraphDiff,
5
+ GraphSnapshot,
6
+ ModifiedFunctionInfo,
7
+ NodeInfo,
8
+ RemovedFunctionInfo,
9
+ SummaryStats,
10
+ )
11
+ from codiff.schema.parsing import ClassChunk, FunctionChunk, Parameter
12
+
13
+ __all__ = [
14
+ "Parameter",
15
+ "ClassChunk",
16
+ "FunctionChunk",
17
+ "NodeInfo",
18
+ "GraphSnapshot",
19
+ "GraphDiff",
20
+ "SummaryStats",
21
+ "AddedFunctionInfo",
22
+ "ModifiedFunctionInfo",
23
+ "RemovedFunctionInfo",
24
+ "AnalysisResult",
25
+ ]
codiff/schema/diff.py ADDED
@@ -0,0 +1,110 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Optional
3
+
4
+ # ---------------------------------------------------------------------------
5
+ # Graph snapshot types
6
+ # ---------------------------------------------------------------------------
7
+
8
+
9
+ @dataclass
10
+ class NodeInfo:
11
+ """Everything we need about a single function for diffing."""
12
+
13
+ function_id: str
14
+ name: str
15
+ file_path: str
16
+ class_name: Optional[str]
17
+ parameters: list[dict] # [{name, type, value}, ...]
18
+ return_type: Optional[str]
19
+ calls: list[str] # resolved callee function_ids
20
+ code: str # used to detect implementation changes
21
+
22
+
23
+ @dataclass
24
+ class GraphSnapshot:
25
+ """Nodes and edges of a resolved call graph at one point in time."""
26
+
27
+ nodes: dict[str, NodeInfo] = field(default_factory=dict)
28
+ edges: set[tuple[str, str]] = field(default_factory=set)
29
+ # class_id → list of superclass names (populated from ClassChunk.superclasses)
30
+ class_parents: dict[str, list[str]] = field(default_factory=dict)
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Diff types
35
+ # ---------------------------------------------------------------------------
36
+
37
+
38
+ @dataclass
39
+ class GraphDiff:
40
+ added_nodes: dict[str, NodeInfo] = field(default_factory=dict)
41
+ removed_nodes: dict[str, NodeInfo] = field(default_factory=dict)
42
+ # id → (old_node, new_node)
43
+ modified_nodes: dict[str, tuple[NodeInfo, NodeInfo]] = field(default_factory=dict)
44
+ added_edges: set[tuple[str, str]] = field(default_factory=set)
45
+ removed_edges: set[tuple[str, str]] = field(default_factory=set)
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Analysis result types
50
+ # ---------------------------------------------------------------------------
51
+
52
+
53
+ @dataclass
54
+ class SummaryStats:
55
+ added_functions: int
56
+ removed_functions: int
57
+ modified_functions: int
58
+ modules_touched: list[str] # sorted distinct file paths
59
+
60
+
61
+ @dataclass
62
+ class AddedFunctionInfo:
63
+ """A new function and how it connects to the rest of the graph."""
64
+
65
+ function_id: str
66
+ file_path: str
67
+ class_name: Optional[str]
68
+ existing_callers: list[str] # callers that existed in base
69
+ new_callers: list[str] # callers that are also new functions
70
+ existing_calls: list[str] # callees that existed in base
71
+ new_calls: list[str] # callees that are also new functions
72
+ is_entry_point: bool # True when no callers at all
73
+
74
+
75
+ @dataclass
76
+ class ModifiedFunctionInfo:
77
+ """An existing function whose code, calls, or signature changed."""
78
+
79
+ function_id: str
80
+ file_path: str
81
+ class_name: Optional[str]
82
+ signature_changed: bool
83
+ old_params: list[dict]
84
+ new_params: list[dict]
85
+ old_return_type: Optional[str]
86
+ new_return_type: Optional[str]
87
+ calls_added_new: list[str] # newly called functions that are also new
88
+ calls_added_existing: list[str] # newly called functions that already existed
89
+ calls_removed: list[str] # callees no longer called (were in base graph)
90
+ callers: list[str] # callers in head (context for who is affected)
91
+
92
+
93
+ @dataclass
94
+ class RemovedFunctionInfo:
95
+ """A function that was deleted."""
96
+
97
+ function_id: str
98
+ file_path: str
99
+ class_name: Optional[str]
100
+ was_called_by: list[str] # callers in base
101
+
102
+
103
+ @dataclass
104
+ class AnalysisResult:
105
+ summary: SummaryStats
106
+ added: list[AddedFunctionInfo]
107
+ modified: list[ModifiedFunctionInfo]
108
+ removed: list[RemovedFunctionInfo]
109
+ # class_id → superclass names, from head snapshot (for rendering inheritance arrows)
110
+ class_parents: dict[str, list[str]] = field(default_factory=dict)
@@ -0,0 +1,76 @@
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List, Optional
3
+
4
+
5
+ @dataclass
6
+ class Parameter:
7
+ name: str
8
+ type: Optional[str] = None
9
+ value: Optional[str] = None
10
+
11
+ def to_dict(self):
12
+ return {"name": self.name, "type": self.type, "value": self.value}
13
+
14
+
15
+ @dataclass
16
+ class ClassChunk:
17
+ id: str
18
+ name: str
19
+ code: str
20
+ docstring: Optional[str]
21
+ start_line: int
22
+ end_line: int
23
+ decorators: List[str]
24
+ superclasses: List[str]
25
+ file_path: str
26
+
27
+ def to_dict(self):
28
+ return {
29
+ "id": self.id,
30
+ "name": self.name,
31
+ "file_path": self.file_path,
32
+ "docstring": self.docstring,
33
+ "decorators": self.decorators,
34
+ "superclasses": self.superclasses,
35
+ "start_line": self.start_line,
36
+ "end_line": self.end_line,
37
+ "code": self.code,
38
+ }
39
+
40
+
41
+ @dataclass
42
+ class FunctionChunk:
43
+ id: str
44
+ name: str
45
+ code: str
46
+ docstring: Optional[str]
47
+ start_line: int
48
+ end_line: int
49
+ parameters: List[Parameter]
50
+ decorators: List[str]
51
+ file_path: str
52
+ class_name: Optional[str] = None
53
+ nested: Optional[str] = None
54
+ return_type: Optional[str] = None
55
+ calls: Optional[List[str]] = None
56
+ var_types: Optional[Dict[str, List[str]]] = None
57
+ var_sources: Optional[Dict[str, str]] = None
58
+
59
+ def to_dict(self):
60
+ return {
61
+ "id": self.id,
62
+ "name": self.name,
63
+ "file_path": self.file_path,
64
+ "class_name": self.class_name,
65
+ "nested": self.nested,
66
+ "parameters": [param.to_dict() for param in self.parameters],
67
+ "docstring": self.docstring,
68
+ "decorators": self.decorators,
69
+ "return_type": self.return_type,
70
+ "start_line": self.start_line,
71
+ "end_line": self.end_line,
72
+ "code": self.code,
73
+ "calls": self.calls,
74
+ "var_types": self.var_types,
75
+ "var_sources": self.var_sources,
76
+ }
codiff/setup.py ADDED
@@ -0,0 +1,103 @@
1
+ """Setup pipeline: parse a repository and write the call graph to the database."""
2
+
3
+ import logging
4
+ import os
5
+ import uuid
6
+
7
+ from sqlalchemy.orm import sessionmaker
8
+
9
+ from codiff.db import Base, Class, Function, Repository, get_db_path, make_sync_engine
10
+ from codiff.schema.parsing import ClassChunk, FunctionChunk
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def setup_repository(repo_path: str) -> str:
16
+ """Parse a repository and write the call graph to {repo_path}/.codiff.db.
17
+
18
+ Returns the repository UUID.
19
+ """
20
+ from codiff.languages import parse_repository
21
+
22
+ repo_path = os.path.abspath(repo_path)
23
+ if not os.path.isdir(repo_path):
24
+ raise FileNotFoundError(f"Repository path not found: {repo_path}")
25
+
26
+ repo_name = os.path.basename(repo_path)
27
+ db_path = get_db_path(repo_path)
28
+
29
+ logger.info("Setting up repository: %s", repo_name)
30
+ logger.info("Database: %s", db_path)
31
+
32
+ engine = make_sync_engine(db_path)
33
+ Base.metadata.create_all(engine)
34
+ Session = sessionmaker(bind=engine)
35
+ db = Session()
36
+
37
+ try:
38
+ repo_id = str(uuid.uuid4())
39
+ repository = Repository(id=repo_id, name=repo_name, url=repo_path)
40
+ db.add(repository)
41
+ db.commit()
42
+
43
+ logger.info("Parsing code...")
44
+ parsed = parse_repository(repo_path)
45
+ logger.info("Parsed %d functions, %d classes", len(parsed.functions), len(parsed.classes))
46
+
47
+ logger.info("Storing functions...")
48
+ fn: "FunctionChunk"
49
+ for fn in parsed.functions:
50
+ mod_doc = parsed.module_docstrings.get(fn.file_path)
51
+ cls_doc = parsed.class_docstrings.get(fn.class_name) if fn.class_name else None
52
+ db.add(
53
+ Function(
54
+ repository_id=repo_id,
55
+ function_id=fn.id,
56
+ name=fn.name,
57
+ file_path=fn.file_path,
58
+ class_name=fn.class_name,
59
+ nested=fn.nested,
60
+ code=fn.code,
61
+ docstring=fn.docstring,
62
+ module_docstring=mod_doc,
63
+ class_docstring=cls_doc,
64
+ start_line=fn.start_line,
65
+ end_line=fn.end_line,
66
+ parameters=[p.to_dict() for p in fn.parameters] if fn.parameters else None,
67
+ decorators=fn.decorators,
68
+ return_type=fn.return_type,
69
+ calls=fn.calls,
70
+ )
71
+ )
72
+
73
+ logger.info("Storing classes...")
74
+ cls: "ClassChunk"
75
+ for cls in parsed.classes:
76
+ db.add(
77
+ Class(
78
+ repository_id=repo_id,
79
+ class_id=cls.id,
80
+ name=cls.name,
81
+ file_path=cls.file_path,
82
+ code=cls.code,
83
+ docstring=cls.docstring,
84
+ start_line=cls.start_line,
85
+ end_line=cls.end_line,
86
+ decorators=cls.decorators,
87
+ superclasses=cls.superclasses,
88
+ )
89
+ )
90
+
91
+ repository.total_functions = len(parsed.functions)
92
+ repository.total_classes = len(parsed.classes)
93
+ repository.is_parsed = True
94
+ db.commit()
95
+
96
+ logger.info("Setup complete! Repository ID: %s", repo_id)
97
+ return repo_id
98
+
99
+ except Exception:
100
+ db.rollback()
101
+ raise
102
+ finally:
103
+ db.close()
File without changes
codiff/utils/args.py ADDED
@@ -0,0 +1,114 @@
1
+ """CLI argument parser for codiff."""
2
+
3
+ import argparse
4
+ import os
5
+
6
+ DEFAULT_WORKERS: int = max(1, (os.cpu_count() or 2) // 2)
7
+
8
+ SUPPORTED_AGENTS: list[str] = ["claude", "codex", "gemini", "vibe"]
9
+
10
+
11
+ def build_parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(
13
+ prog="codiff",
14
+ description="Structural diff of a codebase between two states",
15
+ )
16
+ parser.add_argument(
17
+ "-v",
18
+ "--verbose",
19
+ action="count",
20
+ default=0,
21
+ help="Verbosity: -v for INFO, -vv for DEBUG",
22
+ )
23
+
24
+ subparsers = parser.add_subparsers(dest="command", required=True)
25
+
26
+ # index
27
+ index_parser = subparsers.add_parser(
28
+ "index",
29
+ help="Parse a repository and write the call graph to the database",
30
+ )
31
+ index_parser.add_argument(
32
+ "repo_path",
33
+ help="Path to the repository root directory",
34
+ )
35
+
36
+ # diff
37
+ diff_parser = subparsers.add_parser(
38
+ "diff",
39
+ help="Show the structural delta between a base commit and the working tree",
40
+ )
41
+ diff_parser.add_argument(
42
+ "--base",
43
+ default="HEAD",
44
+ metavar="GIT_REF",
45
+ help="Base git ref to compare against (default: HEAD)",
46
+ )
47
+ diff_parser.add_argument(
48
+ "--head",
49
+ default=None,
50
+ metavar="GIT_REF",
51
+ help="Head git ref to compare to (default: working tree)",
52
+ )
53
+ diff_parser.add_argument(
54
+ "--include-tests",
55
+ action="store_true",
56
+ default=False,
57
+ help="Include test functions in the diff output (hidden by default)",
58
+ )
59
+ diff_parser.add_argument(
60
+ "--include-deleted",
61
+ action="store_true",
62
+ default=False,
63
+ help="Include deleted functions in the diff output (hidden by default)",
64
+ )
65
+ diff_parser.add_argument(
66
+ "--format",
67
+ choices=["terminal", "mermaid", "json"],
68
+ default="terminal",
69
+ metavar="FORMAT",
70
+ help="Output format: terminal (default), mermaid, or json",
71
+ )
72
+ diff_parser.add_argument(
73
+ "--repo",
74
+ default=".",
75
+ metavar="PATH",
76
+ help="Path to the repository root (default: current directory)",
77
+ )
78
+ diff_parser.add_argument(
79
+ "--workers",
80
+ type=int,
81
+ default=DEFAULT_WORKERS,
82
+ metavar="N",
83
+ help=(
84
+ f"Number of parallel workers for parsing and resolution"
85
+ f" (default: {DEFAULT_WORKERS}, half of cpu count)"
86
+ ),
87
+ )
88
+ diff_parser.add_argument(
89
+ "--debug",
90
+ action="store_true",
91
+ default=False,
92
+ help="Show timing breakdown for each processing step (sets log level to DEBUG)",
93
+ )
94
+
95
+ # init
96
+ init_parser = subparsers.add_parser(
97
+ "init",
98
+ help="Configure a coding agent to use codiff in the current project",
99
+ )
100
+ init_parser.add_argument(
101
+ "--agent",
102
+ required=True,
103
+ choices=SUPPORTED_AGENTS,
104
+ metavar="AGENT",
105
+ help=f"Coding agent to configure (supported: {', '.join(SUPPORTED_AGENTS)})",
106
+ )
107
+ init_parser.add_argument(
108
+ "--repo",
109
+ default=".",
110
+ metavar="PATH",
111
+ help="Path to the repository root (default: current directory)",
112
+ )
113
+
114
+ return parser
codiff/utils/files.py ADDED
@@ -0,0 +1,62 @@
1
+ import hashlib
2
+ import os
3
+ from pathlib import Path
4
+
5
+ # Directories whose presence anywhere in a path marks the file as test code
6
+ _TEST_DIRS = {"test", "tests", "testing", "spec", "specs", "__tests__", "e2e", "integration"}
7
+
8
+ # File name suffixes that mark a file as test code (checked on the bare filename)
9
+ _TEST_SUFFIXES = ("_test.py", "_tests.py", "_spec.py", "_specs.py")
10
+
11
+ # Exact filenames that are always test/fixture infrastructure
12
+ _TEST_NAMES = {"conftest.py", "setup_test.py"}
13
+
14
+
15
+ def is_test_file(file_path: str) -> bool:
16
+ """Return True if *file_path* is a test/spec file by any common convention.
17
+
18
+ Covers:
19
+ - Any path segment matching a test directory name (tests/, spec/, e2e/, …)
20
+ - Any path segment starting with ``test`` (test_foo.py, testutils.py, …)
21
+ - Filenames ending with ``_test.py``, ``_spec.py``, etc.
22
+ - Exact filenames like conftest.py
23
+ """
24
+ parts = Path(file_path).parts
25
+ name = parts[-1] if parts else ""
26
+ dirs = parts[:-1]
27
+ return (
28
+ any(d.lower() in _TEST_DIRS or d.lower().startswith("test") for d in dirs)
29
+ or name.startswith("test")
30
+ or any(name.endswith(s) for s in _TEST_SUFFIXES)
31
+ or name in _TEST_NAMES
32
+ )
33
+
34
+
35
+ def hash_file(path: str) -> str:
36
+ """Return SHA-256 hex digest of a file's contents."""
37
+ h = hashlib.sha256()
38
+ with open(path, "rb") as f:
39
+ for chunk in iter(lambda: f.read(65536), b""):
40
+ h.update(chunk)
41
+ return h.hexdigest()
42
+
43
+
44
+ def is_venv_dir(root: str, d: str) -> bool:
45
+ """Return True if *d* under *root* is a Python virtual environment or egg-info directory."""
46
+ if d.endswith(".egg-info"):
47
+ return True
48
+ return os.path.exists(os.path.join(root, d, "pyvenv.cfg"))
49
+
50
+
51
+ def is_path_in_venv(abs_path: str, repo_path: str) -> bool:
52
+ """Return True if *abs_path* lives inside a virtual environment under *repo_path*."""
53
+ try:
54
+ rel = os.path.relpath(abs_path, repo_path)
55
+ except ValueError:
56
+ return False
57
+ current = repo_path
58
+ for part in rel.split(os.sep)[:-1]:
59
+ current = os.path.join(current, part)
60
+ if os.path.exists(os.path.join(current, "pyvenv.cfg")):
61
+ return True
62
+ return False