intentumdiff-python 0.0.1__py3-none-manylinux_2_39_x86_64.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 (165) hide show
  1. intentumdiff/__init__.py +134 -0
  2. intentumdiff/_differ_gate.py +210 -0
  3. intentumdiff/_differ_presentation.py +786 -0
  4. intentumdiff/_differ_runtime.py +320 -0
  5. intentumdiff/analysis/__init__.py +1 -0
  6. intentumdiff/analysis/compile_commands.py +151 -0
  7. intentumdiff/analysis/cross_file.py +71 -0
  8. intentumdiff/analysis/diagnostics.py +309 -0
  9. intentumdiff/analysis/guardrail_reports.py +254 -0
  10. intentumdiff/analysis/guardrails.py +318 -0
  11. intentumdiff/analysis/invariances.py +1207 -0
  12. intentumdiff/analysis/keyed_profiles.py +25 -0
  13. intentumdiff/analysis/resource_profiles.py +14 -0
  14. intentumdiff/analysis/schema_resolver.py +816 -0
  15. intentumdiff/analysis/text_review.py +46 -0
  16. intentumdiff/analysis/user_schemas.py +430 -0
  17. intentumdiff/assets.py +45 -0
  18. intentumdiff/cache/__init__.py +37 -0
  19. intentumdiff/cache/duckdb_store.py +98 -0
  20. intentumdiff/cache/sqlite_store.py +149 -0
  21. intentumdiff/cache/store.py +190 -0
  22. intentumdiff/cli/__init__.py +199 -0
  23. intentumdiff/cli/_commands.py +2141 -0
  24. intentumdiff/cli/_parser.py +1061 -0
  25. intentumdiff/cli/_shared.py +644 -0
  26. intentumdiff/content_type.py +59 -0
  27. intentumdiff/core/__init__.py +1 -0
  28. intentumdiff/core/commit_differ.py +599 -0
  29. intentumdiff/core/config.py +51 -0
  30. intentumdiff/core/cst_serializer.py +101 -0
  31. intentumdiff/core/diffignore.py +87 -0
  32. intentumdiff/core/index.py +189 -0
  33. intentumdiff/core/indexer.py +792 -0
  34. intentumdiff/core/models.py +837 -0
  35. intentumdiff/differ.py +2195 -0
  36. intentumdiff/github_app.py +287 -0
  37. intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
  38. intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
  39. intentumdiff/intentumdiff_rust_core/libintentumdiff_rust_core.so +0 -0
  40. intentumdiff/invariances/__init__.py +2 -0
  41. intentumdiff/invariances/rules.schema.json +283 -0
  42. intentumdiff/invariances/rules.yaml +349 -0
  43. intentumdiff/live_server.py +1314 -0
  44. intentumdiff/lsp/__init__.py +67 -0
  45. intentumdiff/lsp/client.py +544 -0
  46. intentumdiff/lsp/config.py +96 -0
  47. intentumdiff/lsp/enricher.py +227 -0
  48. intentumdiff/lsp/exceptions.py +27 -0
  49. intentumdiff/lsp/launcher.py +273 -0
  50. intentumdiff/lsp/servers.py +356 -0
  51. intentumdiff/lsp_server/__init__.py +14 -0
  52. intentumdiff/lsp_server/_codelens.py +67 -0
  53. intentumdiff/lsp_server/_diagnostics.py +62 -0
  54. intentumdiff/lsp_server/_handlers.py +175 -0
  55. intentumdiff/lsp_server/server.py +205 -0
  56. intentumdiff/plugins/__init__.py +1 -0
  57. intentumdiff/plugins/adapter.py +397 -0
  58. intentumdiff/plugins/builtins.py +323 -0
  59. intentumdiff/plugins/exceptions.py +93 -0
  60. intentumdiff/plugins/hub.py +1155 -0
  61. intentumdiff/plugins/language_metadata.py +250 -0
  62. intentumdiff/plugins/loader.py +1252 -0
  63. intentumdiff/plugins/registry.py +1079 -0
  64. intentumdiff/plugins/registry.schema.json +99 -0
  65. intentumdiff/plugins/registry_schema.py +280 -0
  66. intentumdiff/plugins/wit/plugin.wit +351 -0
  67. intentumdiff/rust_core.py +2370 -0
  68. intentumdiff/serve/__init__.py +19 -0
  69. intentumdiff/serve/_app.py +485 -0
  70. intentumdiff/serve/_static/index.html +326 -0
  71. intentumdiff/serve/_static/playground.js +567 -0
  72. intentumdiff/sources/__init__.py +1 -0
  73. intentumdiff/sources/base.py +28 -0
  74. intentumdiff/sources/file_source.py +48 -0
  75. intentumdiff/sources/git_source.py +375 -0
  76. intentumdiff/sources/live_buffer_source.py +113 -0
  77. intentumdiff/sources/patch_source.py +126 -0
  78. intentumdiff/sources/string_source.py +44 -0
  79. intentumdiff/testing.py +165 -0
  80. intentumdiff/vcs/__init__.py +37 -0
  81. intentumdiff/vcs/_safe_path.py +50 -0
  82. intentumdiff/vcs/base.py +136 -0
  83. intentumdiff/vcs/git_backend.py +97 -0
  84. intentumdiff/vcs/git_cli.py +100 -0
  85. intentumdiff/vcs/hg_backend.py +94 -0
  86. intentumdiff/vcs/perforce_backend.py +109 -0
  87. intentumdiff/vcs/svn_backend.py +105 -0
  88. intentumdiff/wasm/.gitkeep +2 -0
  89. intentumdiff/wasm/abap_parser.wasm +0 -0
  90. intentumdiff/wasm/adf_parser.wasm +0 -0
  91. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  92. intentumdiff/wasm/asm_parser.wasm +0 -0
  93. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  94. intentumdiff/wasm/astro_parser.wasm +0 -0
  95. intentumdiff/wasm/bash_parser.wasm +0 -0
  96. intentumdiff/wasm/clojure_parser.wasm +0 -0
  97. intentumdiff/wasm/cmake_parser.wasm +0 -0
  98. intentumdiff/wasm/cpp_parser.wasm +0 -0
  99. intentumdiff/wasm/csharp_parser.wasm +0 -0
  100. intentumdiff/wasm/css_parser.wasm +0 -0
  101. intentumdiff/wasm/dart_parser.wasm +0 -0
  102. intentumdiff/wasm/databricks_parser.wasm +0 -0
  103. intentumdiff/wasm/dax_parser.wasm +0 -0
  104. intentumdiff/wasm/delphi_parser.wasm +0 -0
  105. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  106. intentumdiff/wasm/elixir_parser.wasm +0 -0
  107. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  108. intentumdiff/wasm/generic_parser.wasm +0 -0
  109. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  110. intentumdiff/wasm/go_parser.wasm +0 -0
  111. intentumdiff/wasm/gomod_parser.wasm +0 -0
  112. intentumdiff/wasm/graphql_parser.wasm +0 -0
  113. intentumdiff/wasm/groovy_parser.wasm +0 -0
  114. intentumdiff/wasm/haskell_parser.wasm +0 -0
  115. intentumdiff/wasm/html_parser.wasm +0 -0
  116. intentumdiff/wasm/ini_parser.wasm +0 -0
  117. intentumdiff/wasm/java_parser.wasm +0 -0
  118. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  119. intentumdiff/wasm/json_parser.wasm +0 -0
  120. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  121. intentumdiff/wasm/latex_parser.wasm +0 -0
  122. intentumdiff/wasm/lua_parser.wasm +0 -0
  123. intentumdiff/wasm/make_parser.wasm +0 -0
  124. intentumdiff/wasm/markdown_parser.wasm +0 -0
  125. intentumdiff/wasm/mdx_parser.wasm +0 -0
  126. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  127. intentumdiff/wasm/odin_parser.wasm +0 -0
  128. intentumdiff/wasm/parser_manifest.json +590 -0
  129. intentumdiff/wasm/perl_parser.wasm +0 -0
  130. intentumdiff/wasm/php_parser.wasm +0 -0
  131. intentumdiff/wasm/plsql_parser.wasm +0 -0
  132. intentumdiff/wasm/po_parser.wasm +0 -0
  133. intentumdiff/wasm/postscript_parser.wasm +0 -0
  134. intentumdiff/wasm/powershell_parser.wasm +0 -0
  135. intentumdiff/wasm/proto_parser.wasm +0 -0
  136. intentumdiff/wasm/puppet_parser.wasm +0 -0
  137. intentumdiff/wasm/python_parser.wasm +0 -0
  138. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  139. intentumdiff/wasm/r_parser.wasm +0 -0
  140. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  141. intentumdiff/wasm/ruby_parser.wasm +0 -0
  142. intentumdiff/wasm/rust_parser.wasm +0 -0
  143. intentumdiff/wasm/sas_parser.wasm +0 -0
  144. intentumdiff/wasm/scala_parser.wasm +0 -0
  145. intentumdiff/wasm/scss_parser.wasm +0 -0
  146. intentumdiff/wasm/sql_parser.wasm +0 -0
  147. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  148. intentumdiff/wasm/svelte_parser.wasm +0 -0
  149. intentumdiff/wasm/swift_parser.wasm +0 -0
  150. intentumdiff/wasm/terraform_parser.wasm +0 -0
  151. intentumdiff/wasm/toml_parser.wasm +0 -0
  152. intentumdiff/wasm/tsql_parser.wasm +0 -0
  153. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  154. intentumdiff/wasm/vue_parser.wasm +0 -0
  155. intentumdiff/wasm/wat_parser.wasm +0 -0
  156. intentumdiff/wasm/xml_parser.wasm +0 -0
  157. intentumdiff/wasm/yaml_parser.wasm +0 -0
  158. intentumdiff/wasm/zig_parser.wasm +0 -0
  159. intentumdiff/watcher.py +259 -0
  160. intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
  161. intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
  162. intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
  163. intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
  164. intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
  165. intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
@@ -0,0 +1,165 @@
1
+ """
2
+ intentumdiff.testing
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ ``PluginTestHarness`` — unit-test helper for plugin authors.
6
+
7
+ Allows testing a ``.wasm`` plugin without going through the full pipeline::
8
+
9
+ from intentumdiff.testing import PluginTestHarness
10
+
11
+ harness = PluginTestHarness("path/to/my_plugin.wasm")
12
+
13
+ # Parser tests
14
+ assert harness.grammar_id == "my-lang"
15
+ tree = harness.process(cst_json, "my-lang", "example.ml")
16
+ assert tree.node_type == "module"
17
+
18
+ # Renderer tests
19
+ rendered = harness.render(diff_json)
20
+ assert "function" in rendered
21
+
22
+ # Security helpers
23
+ harness.assert_no_filesystem_access() # WAT-level check
24
+ harness.assert_fuel_exhausts(fuel=100) # confirm infinite-loop guard
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from intentumdiff.core.models import DiffConfig, LanguagePluginInfo, SemanticNode
33
+ from intentumdiff.plugins.adapter import ParserAdapter, RendererAdapter
34
+ from intentumdiff.plugins.exceptions import PluginFuelExhausted, PluginOutputError
35
+ from intentumdiff.plugins.loader import load_plugin
36
+
37
+
38
+ class PluginTestHarness:
39
+ """
40
+ Thin wrapper for testing a single ``.wasm`` plugin file in isolation.
41
+
42
+ Attributes are lazy — the plugin is loaded on first access so the harness
43
+ can be constructed cheaply in test parametrize lists.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ wasm_path: str | Path,
49
+ config: DiffConfig | None = None,
50
+ plugin_type: str = "parser",
51
+ ) -> None:
52
+ """
53
+ Parameters
54
+ ----------
55
+ wasm_path:
56
+ Path to the compiled ``.wasm`` plugin file.
57
+ config:
58
+ Optional ``DiffConfig`` — defaults are used otherwise.
59
+ plugin_type:
60
+ ``"parser"`` or ``"renderer"`` — determines which adapter is used.
61
+ """
62
+ self._wasm_path = Path(wasm_path)
63
+ self._config = config or DiffConfig()
64
+ self._plugin_type = plugin_type
65
+ self._parser_adapter: ParserAdapter | None = None
66
+ self._renderer_adapter: RendererAdapter | None = None
67
+ self._loaded_plugin: Any | None = None # shared LoadedPlugin instance
68
+
69
+ # ── Lazy adapters ────────────────────────────────────────────────────────
70
+
71
+ @property
72
+ def _plugin(self) -> Any:
73
+ """Return the shared LoadedPlugin, loading it on first access."""
74
+ if self._loaded_plugin is None:
75
+ self._loaded_plugin = load_plugin(self._wasm_path, self._config.plugin_fuel)
76
+ return self._loaded_plugin
77
+
78
+ @property
79
+ def _parser(self) -> ParserAdapter:
80
+ if self._parser_adapter is None:
81
+ self._parser_adapter = ParserAdapter(self._plugin)
82
+ return self._parser_adapter
83
+
84
+ @property
85
+ def _renderer(self) -> RendererAdapter:
86
+ if self._renderer_adapter is None:
87
+ self._renderer_adapter = RendererAdapter(self._plugin)
88
+ return self._renderer_adapter
89
+
90
+ # ── Parser helpers ───────────────────────────────────────────────────────
91
+
92
+ @property
93
+ def grammar_id(self) -> str:
94
+ return self._parser.grammar_id
95
+
96
+ @property
97
+ def language_ids(self) -> list[str]:
98
+ return self._parser.language_ids
99
+
100
+ @property
101
+ def language_info(self) -> list[LanguagePluginInfo]:
102
+ return self._parser.language_info
103
+
104
+ @property
105
+ def trivia_node_types(self) -> list[str]:
106
+ return self._parser.trivia_node_types
107
+
108
+ def detect_language(self, filename: str, content: str = "") -> str:
109
+ return self._parser.detect_language(filename, content)
110
+
111
+ def process(self, input_: str, language: str, filename: str) -> SemanticNode:
112
+ return self._parser.process(input_, language, filename)
113
+
114
+ # ── Renderer helpers ─────────────────────────────────────────────────────
115
+
116
+ @property
117
+ def format_name(self) -> str:
118
+ return self._renderer.format_name
119
+
120
+ def render(self, diff_json: str) -> str:
121
+ return self._renderer.render(diff_json)
122
+
123
+ # ── Security assertion helpers ───────────────────────────────────────────
124
+
125
+ def assert_rejects_malformed_output(self, input_json: str = "null") -> None:
126
+ """
127
+ Assert that a malformed plugin output raises ``PluginOutputError``.
128
+
129
+ Useful when testing a plugin that is expected to validate its own
130
+ input and return an ``{"error": "..."}`` object.
131
+ """
132
+ import pytest
133
+
134
+ with pytest.raises(PluginOutputError):
135
+ self._parser.process(input_json, "unknown", "test.txt")
136
+
137
+ def assert_fuel_exhausts(self, fuel: int = 100) -> None:
138
+ """
139
+ Assert that the plugin exhausts its fuel when given a tiny budget.
140
+
141
+ Use this to confirm that infinite-loop guard works for the plugin.
142
+ """
143
+ import pytest
144
+
145
+ plugin = load_plugin(self._wasm_path, fuel)
146
+ adapter = ParserAdapter(plugin)
147
+ with pytest.raises(PluginFuelExhausted):
148
+ adapter.process("{}", "unknown", "test.txt")
149
+
150
+ def assert_no_filesystem_access(self) -> None:
151
+ """
152
+ Assert the plugin does not import any WASI filesystem functions.
153
+
154
+ Reads the Wasm binary and looks for ``path_open`` / ``fd_read``
155
+ in the import section. This is a static check — it does not execute
156
+ the plugin.
157
+ """
158
+ binary = self._wasm_path.read_bytes()
159
+ forbidden = [b"path_open", b"fd_read", b"fd_write", b"fd_seek"]
160
+ for sym in forbidden:
161
+ if sym in binary:
162
+ raise AssertionError(
163
+ f"Plugin {self._wasm_path.name} imports forbidden WASI symbol "
164
+ f"{sym!r} — sandbox would not be effective."
165
+ )
@@ -0,0 +1,37 @@
1
+ """
2
+ intentumdiff.vcs
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ VCS backend abstraction layer.
6
+
7
+ Provides a ``VcsBackend`` abstract base and concrete implementations for the
8
+ version-control systems supported by IntentumDiff.
9
+
10
+ All backends are thin wrappers over the shared Rust ``vcs_backend`` core, which shells the
11
+ corresponding CLI (``git`` / ``svn`` / ``hg`` / ``p4``); none require a third-party VCS Python
12
+ library.
13
+
14
+ Exports
15
+ -------
16
+ :class:`VcsBackend` Abstract base class for all VCS backends.
17
+ :class:`ChangedFile` Frozen dataclass describing a single file-level change.
18
+ :class:`GitVcsBackend` Git backend (``git`` CLI).
19
+ :class:`SvnVcsBackend` Subversion backend (``svn`` CLI).
20
+ :class:`HgVcsBackend` Mercurial backend (``hg`` CLI).
21
+ :class:`PerforceVcsBackend` Perforce backend (``p4`` CLI; connection from env / ``P4CONFIG``).
22
+ """
23
+
24
+ from intentumdiff.vcs.base import ChangedFile, VcsBackend
25
+ from intentumdiff.vcs.git_backend import GitVcsBackend
26
+ from intentumdiff.vcs.hg_backend import HgVcsBackend
27
+ from intentumdiff.vcs.perforce_backend import PerforceVcsBackend
28
+ from intentumdiff.vcs.svn_backend import SvnVcsBackend
29
+
30
+ __all__ = [
31
+ "VcsBackend",
32
+ "ChangedFile",
33
+ "GitVcsBackend",
34
+ "SvnVcsBackend",
35
+ "HgVcsBackend",
36
+ "PerforceVcsBackend",
37
+ ]
@@ -0,0 +1,50 @@
1
+ """
2
+ intentumdiff.vcs._safe_path
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Shared helpers for validating VCS file paths before passing them to backend
6
+ commands or constructing filesystem paths.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path, PurePosixPath, PureWindowsPath
12
+
13
+
14
+ def safe_relative_path(file_path: str) -> str:
15
+ """Validate that *file_path* is relative and contains no traversal."""
16
+ if "\\" in file_path:
17
+ raise ValueError(
18
+ f"Unsafe file path: {file_path!r} - must use forward slashes."
19
+ )
20
+
21
+ windows = PureWindowsPath(file_path)
22
+ if windows.is_absolute() or windows.drive:
23
+ raise ValueError(
24
+ f"Unsafe file path: {file_path!r} - must be relative, not absolute."
25
+ )
26
+
27
+ safe = PurePosixPath(file_path)
28
+ if safe.is_absolute():
29
+ raise ValueError(
30
+ f"Unsafe file path: {file_path!r} - must be relative, not absolute."
31
+ )
32
+ if ".." in safe.parts:
33
+ raise ValueError(
34
+ f"Unsafe file path: {file_path!r} - must not contain '..' traversal."
35
+ )
36
+ return str(safe)
37
+
38
+
39
+ def safe_working_tree_path(root: str | Path, file_path: str) -> Path:
40
+ """Return a repository-contained on-disk path for *file_path* under *root*."""
41
+ safe = safe_relative_path(file_path)
42
+ root_path = Path(root).resolve()
43
+ candidate = (root_path / safe).resolve(strict=False)
44
+ try:
45
+ candidate.relative_to(root_path)
46
+ except ValueError:
47
+ raise ValueError(
48
+ f"Unsafe file path: {file_path!r} - resolved path escapes {root_path!s}."
49
+ ) from None
50
+ return candidate
@@ -0,0 +1,136 @@
1
+ """
2
+ intentumdiff.vcs.base
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Abstract base class for VCS backends and the ``ChangedFile`` data model.
6
+
7
+ All VCS backends must implement the five abstract diff methods. Two
8
+ non-abstract merge hooks (``get_merge_base``, ``get_conflict_content``) are
9
+ provided as stubs for future semantic-merge support.
10
+
11
+ ``ref`` is always a plain ``str`` at every boundary — each backend interprets
12
+ its own ref syntax (git SHA / SVN revision number / Perforce changelist /
13
+ Mercurial changeset hash).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from abc import ABC, abstractmethod
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Literal
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class ChangedFile:
26
+ """Describes a single file-level change between two VCS revisions.
27
+
28
+ Attributes
29
+ ----------
30
+ old_path:
31
+ Path to the file in the *old* revision, or ``None`` for newly-added
32
+ files.
33
+ new_path:
34
+ Path to the file in the *new* revision, or ``None`` for deleted files.
35
+ change_type:
36
+ One of ``"added"``, ``"deleted"``, ``"modified"``, ``"renamed"``, or
37
+ ``"copied"``.
38
+ is_binary:
39
+ ``True`` when the backend detected the file as binary (not diffable as
40
+ text).
41
+ """
42
+
43
+ old_path: str | None
44
+ new_path: str | None
45
+ change_type: Literal["added", "deleted", "modified", "renamed", "copied"]
46
+ is_binary: bool = field(default=False)
47
+
48
+
49
+ class VcsBackend(ABC):
50
+ """Minimal abstract VCS interface for IntentumDiff.
51
+
52
+ All backends must implement the five abstract diff methods:
53
+
54
+ * :meth:`get_blob` — file content at a revision
55
+ * :meth:`list_changed_files` — changed-file list between two refs
56
+ * :meth:`get_working_file` — on-disk content (working tree)
57
+ * :meth:`list_working_tree_changes` — uncommitted changes
58
+ * :meth:`resolve_root` — repository root path
59
+
60
+ Two non-abstract merge hooks are provided as ``NotImplementedError`` stubs
61
+ for future semantic-merge support:
62
+
63
+ * :meth:`get_merge_base`
64
+ * :meth:`get_conflict_content`
65
+ """
66
+
67
+ # ------------------------------------------------------------------
68
+ # Required: diff interface
69
+ # ------------------------------------------------------------------
70
+
71
+ @abstractmethod
72
+ def get_blob(self, path: str, ref: str) -> str:
73
+ """Return the content of *path* at revision *ref* as a UTF-8 string.
74
+
75
+ Returns an empty string when *path* does not exist at *ref* (e.g. for
76
+ newly-added files queried against the old ref).
77
+
78
+ Parameters
79
+ ----------
80
+ path:
81
+ File path relative to the repository root, using forward slashes.
82
+ ref:
83
+ VCS-specific revision identifier (SHA, revision number, etc.).
84
+ """
85
+
86
+ @abstractmethod
87
+ def list_changed_files(self, ref_a: str, ref_b: str) -> list[ChangedFile]:
88
+ """Return the list of files that changed between *ref_a* and *ref_b*.
89
+
90
+ Added files have ``old_path=None``.
91
+ Deleted files have ``new_path=None``.
92
+ Renamed files have both paths set and ``change_type="renamed"``.
93
+ """
94
+
95
+ @abstractmethod
96
+ def get_working_file(self, path: str) -> str:
97
+ """Return the current on-disk content of *path* as a UTF-8 string.
98
+
99
+ Returns an empty string when the file does not exist on disk.
100
+ """
101
+
102
+ @abstractmethod
103
+ def list_working_tree_changes(self, ref: str = "HEAD") -> list[ChangedFile]:
104
+ """Return uncommitted changes in the working tree relative to *ref*.
105
+
106
+ The default *ref* value (``"HEAD"``) is a git convention; backends
107
+ for other VCS systems should document their equivalent default.
108
+ """
109
+
110
+ @abstractmethod
111
+ def resolve_root(self) -> Path:
112
+ """Return the absolute path to the repository root."""
113
+
114
+ # ------------------------------------------------------------------
115
+ # Future: semantic-merge hooks (non-abstract stubs)
116
+ # ------------------------------------------------------------------
117
+
118
+ def get_merge_base(self, ref_a: str, ref_b: str) -> str: # pragma: no cover
119
+ """Return the common ancestor revision of *ref_a* and *ref_b*.
120
+
121
+ Raises ``NotImplementedError`` by default. Implement in backends that
122
+ support semantic merge.
123
+ """
124
+ raise NotImplementedError(
125
+ f"{type(self).__name__} does not yet implement get_merge_base()"
126
+ )
127
+
128
+ def get_conflict_content(self, path: str) -> tuple[str, str, str]: # pragma: no cover
129
+ """Return ``(base, ours, theirs)`` content for a conflicted *path*.
130
+
131
+ Raises ``NotImplementedError`` by default. Implement in backends that
132
+ support semantic merge.
133
+ """
134
+ raise NotImplementedError(
135
+ f"{type(self).__name__} does not yet implement get_conflict_content()"
136
+ )
@@ -0,0 +1,97 @@
1
+ """
2
+ intentumdiff.vcs.git_backend
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Git VCS backend — a thin wrapper over the shared Rust VCS module (#98, A2.4.4).
6
+
7
+ The git operations (root discovery, blob read, changed-file listing, merge-base) live
8
+ in the Rust core (``crates/rust-core-host/src/vcs_backend.rs``); this class only marshals
9
+ to/from the :class:`ChangedFile` DTO. The working-tree file read stays here — it is plain
10
+ disk I/O, not VCS logic.
11
+
12
+ Security
13
+ --------
14
+ All file paths are validated against the repository root to prevent path-traversal
15
+ attacks before any I/O is performed.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from pathlib import Path
22
+
23
+ from intentumdiff.vcs._safe_path import safe_relative_path, safe_working_tree_path
24
+ from intentumdiff.vcs.base import ChangedFile, VcsBackend
25
+
26
+
27
+ def _safe_path(file_path: str) -> str:
28
+ """Validate *file_path* is relative and contains no ``..`` components."""
29
+ return safe_relative_path(file_path)
30
+
31
+
32
+ class GitVcsBackend(VcsBackend):
33
+ """Git VCS backend — thin wrapper over the Rust ``vcs_backend`` (git dialect).
34
+
35
+ Parameters
36
+ ----------
37
+ repo_path:
38
+ Path to any directory inside the git repository; the work-tree root is
39
+ resolved by the core (raises ``ValueError`` for a non-repo path).
40
+ """
41
+
42
+ _VCS = "git"
43
+
44
+ def __init__(self, repo_path: str | os.PathLike[str] = ".") -> None:
45
+ from intentumdiff import rust_core
46
+
47
+ self._root = rust_core.vcs_backend_resolve_root(self._VCS, os.fspath(repo_path))
48
+
49
+ # ------------------------------------------------------------------
50
+ # VcsBackend implementation
51
+ # ------------------------------------------------------------------
52
+
53
+ def get_blob(self, path: str, ref: str) -> str:
54
+ """Return the content of *path* at git ref *ref* ("" when absent)."""
55
+ from intentumdiff import rust_core
56
+
57
+ return rust_core.vcs_backend_get_blob(self._VCS, self._root, _safe_path(path), ref)
58
+
59
+ def list_changed_files(self, ref_a: str, ref_b: str) -> list[ChangedFile]:
60
+ """Return files that changed between git refs *ref_a* and *ref_b*."""
61
+ from intentumdiff import rust_core
62
+
63
+ return [
64
+ ChangedFile(**row)
65
+ for row in rust_core.vcs_backend_changed_files(
66
+ self._VCS, self._root, ref_a, ref_b
67
+ )
68
+ ]
69
+
70
+ def get_working_file(self, path: str) -> str:
71
+ """Return the on-disk content of *path* in the working tree."""
72
+ full_path = safe_working_tree_path(self._root, _safe_path(path))
73
+ try:
74
+ return full_path.read_text(encoding="utf-8", errors="replace")
75
+ except FileNotFoundError:
76
+ return ""
77
+
78
+ def list_working_tree_changes(self, ref: str = "HEAD") -> list[ChangedFile]:
79
+ """Return uncommitted working-tree changes vs *ref* (binaries skipped)."""
80
+ from intentumdiff import rust_core
81
+
82
+ return [
83
+ ChangedFile(**row)
84
+ for row in rust_core.vcs_backend_working_tree_changes(
85
+ self._VCS, self._root, ref
86
+ )
87
+ ]
88
+
89
+ def resolve_root(self) -> Path:
90
+ """Return the git repository root (the directory containing ``.git``)."""
91
+ return Path(self._root)
92
+
93
+ def get_merge_base(self, ref_a: str, ref_b: str) -> str:
94
+ """Return the hexsha of the common ancestor of *ref_a* and *ref_b*."""
95
+ from intentumdiff import rust_core
96
+
97
+ return rust_core.vcs_backend_merge_base(self._VCS, self._root, ref_a, ref_b)
@@ -0,0 +1,100 @@
1
+ """
2
+ intentumdiff.vcs.git_cli
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Thin git-CLI helpers for the Python shell — repo discovery + a subprocess runner —
6
+ that replace the GitPython object model (#98, A2.4.3). Repo discovery delegates to the
7
+ shared Rust core (``rust_core.git_repo_toplevel``, which shells ``git rev-parse
8
+ --show-toplevel``); the raw ``run_git_bytes`` runner covers the few plumbing calls
9
+ (``ls-tree``/``cat-file``) that do not yet have a dedicated core entrypoint.
10
+
11
+ ``NotAGitRepositoryError`` is the native replacement for GitPython's
12
+ ``InvalidGitRepositoryError`` / ``NoSuchPathError``. It subclasses ``ValueError`` so
13
+ existing ``except ValueError`` handlers keep working during the migration.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import shutil
20
+ import subprocess
21
+
22
+
23
+ class NotAGitRepositoryError(ValueError):
24
+ """Raised when a path is not inside a usable git work tree.
25
+
26
+ Replaces GitPython's ``InvalidGitRepositoryError`` and ``NoSuchPathError`` (a path
27
+ that does not exist or is not a repo). Subclasses ``ValueError`` for back-compat
28
+ with handlers written against the GitPython era.
29
+ """
30
+
31
+
32
+ def resolve_repo_root(path: "str | os.PathLike[str]") -> str:
33
+ """Return the absolute work-tree root for the repository containing *path*.
34
+
35
+ Delegates to the Rust core (``git rev-parse --show-toplevel``). Accepts any
36
+ directory inside the repo (GitPython's ``search_parent_directories=True``
37
+ equivalent). Raises :class:`NotAGitRepositoryError` when *path* is not inside a
38
+ git work tree (non-repo, missing path, or a bare repository).
39
+ """
40
+ from intentumdiff import rust_core
41
+
42
+ try:
43
+ return rust_core.git_repo_toplevel(os.fspath(path))
44
+ except ValueError as exc: # rust_core raises ValueError on non-repo / bare / missing
45
+ raise NotAGitRepositoryError(
46
+ f"{os.fspath(path)!r} is not inside a git repository work tree."
47
+ ) from exc
48
+
49
+
50
+ def run_git_bytes(
51
+ repo_path: "str | os.PathLike[str]",
52
+ args: list[str],
53
+ *,
54
+ input_bytes: bytes | None = None,
55
+ ) -> bytes:
56
+ """Run ``git -C <repo_path> <args>`` and return stdout bytes (raises on failure).
57
+
58
+ A fixed ``git`` executable, no shell — the plumbing runner for the few tree/blob
59
+ reads without a dedicated core entrypoint yet.
60
+ """
61
+ git_exe = shutil.which("git")
62
+ if git_exe is None:
63
+ raise NotAGitRepositoryError("git executable not found on PATH")
64
+ proc = subprocess.run( # noqa: S603 - fixed git executable, arg list, no shell.
65
+ [git_exe, "-C", os.fspath(repo_path), *args],
66
+ input=input_bytes,
67
+ stdout=subprocess.PIPE,
68
+ stderr=subprocess.PIPE,
69
+ check=True,
70
+ )
71
+ return proc.stdout
72
+
73
+
74
+ def parse_name_status_z(data: bytes) -> "list[tuple[str, str, str]]":
75
+ """Parse ``git diff --name-status -z`` output into ``(code, old_path, new_path)``.
76
+
77
+ For Add/Delete/Modify a single path follows the status; for Rename/Copy two
78
+ paths follow (old then new). Paths are NUL-separated (``-z``).
79
+ """
80
+ tokens = [t for t in data.split(b"\0") if t]
81
+ entries: list[tuple[str, str, str]] = []
82
+ idx = 0
83
+ while idx < len(tokens):
84
+ status = tokens[idx].decode("ascii", errors="replace")
85
+ idx += 1
86
+ code = status[:1]
87
+ if code in {"R", "C"}:
88
+ if idx + 1 >= len(tokens):
89
+ break
90
+ old_path = tokens[idx].decode("utf-8", errors="replace")
91
+ new_path = tokens[idx + 1].decode("utf-8", errors="replace")
92
+ idx += 2
93
+ else:
94
+ if idx >= len(tokens):
95
+ break
96
+ old_path = tokens[idx].decode("utf-8", errors="replace")
97
+ new_path = old_path
98
+ idx += 1
99
+ entries.append((code, old_path, new_path))
100
+ return entries
@@ -0,0 +1,94 @@
1
+ """
2
+ intentumdiff.vcs.hg_backend
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Mercurial VCS backend — a thin wrapper over the shared Rust VCS module (#98, A2.4.4).
6
+
7
+ The Mercurial operations (root discovery, blob read, changed-file listing, status parsing)
8
+ live in the Rust core (``crates/rust-core-host/src/vcs_backend.rs``), which shells the ``hg``
9
+ CLI directly; this class only marshals to/from the :class:`ChangedFile` DTO. python-hglib is
10
+ no longer used — the core is the single implementation shared by every binding. The
11
+ working-tree file read stays here (plain disk I/O, not VCS logic).
12
+
13
+ Ref syntax
14
+ ----------
15
+ ``ref`` strings map to Mercurial revision syntax: changeset hash prefix, revision number
16
+ (as a string), tag name, or bookmark name. The special value ``"."`` refers to the current
17
+ working-directory parent. Revision inputs are validated in the core (an #88 control).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from pathlib import Path
24
+
25
+ from intentumdiff.vcs._safe_path import safe_relative_path, safe_working_tree_path
26
+ from intentumdiff.vcs.base import ChangedFile, VcsBackend
27
+
28
+
29
+ class HgVcsBackend(VcsBackend):
30
+ """Mercurial VCS backend — thin wrapper over the Rust ``vcs_backend`` (hg dialect).
31
+
32
+ Parameters
33
+ ----------
34
+ repo_path:
35
+ Path to any directory inside the Mercurial repository; the repository root is
36
+ resolved by the core (``hg root``), which raises ``ValueError`` for a non-repo path.
37
+ """
38
+
39
+ _VCS = "hg"
40
+
41
+ def __init__(self, repo_path: str | os.PathLike[str] = ".") -> None:
42
+ from intentumdiff import rust_core
43
+
44
+ self._root = rust_core.vcs_backend_resolve_root(self._VCS, os.fspath(repo_path))
45
+
46
+ # ------------------------------------------------------------------
47
+ # VcsBackend implementation
48
+ # ------------------------------------------------------------------
49
+
50
+ def get_blob(self, path: str, ref: str) -> str:
51
+ """Return file content at Mercurial revision *ref* ("" when absent)."""
52
+ from intentumdiff import rust_core
53
+
54
+ return rust_core.vcs_backend_get_blob(
55
+ self._VCS, self._root, safe_relative_path(path), ref
56
+ )
57
+
58
+ def list_changed_files(self, ref_a: str, ref_b: str) -> list[ChangedFile]:
59
+ """Return files changed between Mercurial revisions *ref_a* and *ref_b*."""
60
+ from intentumdiff import rust_core
61
+
62
+ return [
63
+ ChangedFile(**row)
64
+ for row in rust_core.vcs_backend_changed_files(
65
+ self._VCS, self._root, ref_a, ref_b
66
+ )
67
+ ]
68
+
69
+ def get_working_file(self, path: str) -> str:
70
+ """Return on-disk content of *path* in the Mercurial working directory."""
71
+ full_path = safe_working_tree_path(self._root, path)
72
+ try:
73
+ return full_path.read_text(encoding="utf-8", errors="replace")
74
+ except FileNotFoundError:
75
+ return ""
76
+
77
+ def list_working_tree_changes(self, ref: str = ".") -> list[ChangedFile]:
78
+ """Return uncommitted working-directory changes (``hg status``).
79
+
80
+ The default *ref* value ``"."`` is the Mercurial working-directory parent revision
81
+ (equivalent to git ``HEAD``); ``hg status`` always reports against it.
82
+ """
83
+ from intentumdiff import rust_core
84
+
85
+ return [
86
+ ChangedFile(**row)
87
+ for row in rust_core.vcs_backend_working_tree_changes(
88
+ self._VCS, self._root, ref
89
+ )
90
+ ]
91
+
92
+ def resolve_root(self) -> Path:
93
+ """Return the Mercurial repository root path."""
94
+ return Path(self._root)