diffctx 1.12.1

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Nikolay Eremeev
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,210 @@
1
+ # diffctx — smart diff context for LLM code review
2
+
3
+ [![CI](https://github.com/nikolay-e/diffctx/actions/workflows/ci.yml/badge.svg)](https://github.com/nikolay-e/diffctx/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/diffctx)](https://pypi.org/project/diffctx/)
5
+ [![crates.io](https://img.shields.io/crates/v/diffctx)](https://crates.io/crates/diffctx)
6
+ [![License](https://img.shields.io/pypi/l/diffctx)](https://pypi.org/project/diffctx/)
7
+
8
+ **diffctx selects the minimum code an LLM needs to review a git diff.**
9
+ Instead of pasting whole files, it walks the dependency graph from the changed
10
+ lines outward and stops as soon as additional context stops paying for itself.
11
+
12
+ > Coming from [`treemapper`](https://pypi.org/project/treemapper/)? That name is
13
+ > deprecated — it was a thin wrapper around diffctx. Every command, flag, and
14
+ > API call works unchanged: `treemapper` → `diffctx`, `treemapper-mcp` → `diffctx-mcp`.
15
+
16
+ ## Why not just use `tree` or repomix?
17
+
18
+ | | `tree` | repomix | Claude Code Review | **diffctx** |
19
+ |---|:---:|:---:|:---:|:---:|
20
+ | **Primary use case** | directory listing | full repo export | automated PR review | **diff context for code review** |
21
+ | Smart diff context | ✗ | ✗ | ✓ | ✓ |
22
+ | Works with any LLM | ✓ | ✓ | Claude only | ✓ |
23
+ | Free / local / offline | ✓ | ✓ | $15–25/review | ✓ |
24
+ | GitHub required | ✗ | ✗ | ✓ | ✗ |
25
+ | Multiple output formats | ✗ | limited | — | YAML/JSON/MD/txt |
26
+ | Python API | ✗ | ✗ | ✗ | ✓ |
27
+ | MCP server | ✗ | ✗ | ✗ | ✓ |
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ uvx diffctx . --diff HEAD~1 # zero-install, run once via uv
33
+ pipx install diffctx # recommended: isolated CLI, no venv needed
34
+ pip install diffctx # or: into an active environment
35
+ pipx install 'diffctx[mcp]' # + MCP server for AI assistants
36
+ ```
37
+
38
+ The `[tree-sitter]` extra adds AST-level parsing for more accurate context
39
+ selection across 30+ languages.
40
+
41
+ Without Python:
42
+
43
+ ```bash
44
+ cargo install diffctx # native CLI from crates.io
45
+ docker run --rm -v "$PWD:/repo" ghcr.io/nikolay-e/diffctx . --diff HEAD~1
46
+ ```
47
+
48
+ Prebuilt binaries for linux (x86_64/aarch64), macOS (arm64) and Windows (x64)
49
+ are attached to every [release](https://github.com/nikolay-e/diffctx/releases/latest).
50
+ The native binary covers diff mode with YAML/JSON output; tree mode, Markdown
51
+ output, the `graph` subcommand and the MCP server live in the Python package.
52
+ `cargo add diffctx` embeds the selection pipeline in a Rust project
53
+ ([docs.rs](https://docs.rs/diffctx)).
54
+
55
+ ## Quick start
56
+
57
+ ```bash
58
+ diffctx . --diff HEAD~1 # smart context for last commit → paste into Claude/ChatGPT
59
+ diffctx . -f md -c # full codebase export → clipboard in Markdown
60
+ ```
61
+
62
+ ![diffctx demo](https://raw.githubusercontent.com/nikolay-e/diffctx/main/docs/demo.gif)
63
+
64
+ *`diffctx . --diff HEAD~1` selects only the fragments — functions, imports,
65
+ type definitions — that an LLM actually needs to review the last commit,
66
+ instead of dumping every changed file in full.*
67
+
68
+ ## Diff context mode
69
+
70
+ Finds the minimal set of code fragments needed to understand a change —
71
+ imports, callers, type definitions, config dependencies — across 50+ file
72
+ types. It builds a code graph (imports, co-changes, type refs), propagates
73
+ relevance from the changed lines outward, and stops when relevance drops below
74
+ `--tau` or the `--budget` token cap is reached.
75
+
76
+ | Flag | Default | Description |
77
+ |-------------|---------|--------------------------------------------------------------------------|
78
+ | `--scoring` | `ego` | `ego` = bounded expansion around changed nodes (fast, predictable radius); `ppr` = Personalized PageRank (global, smoother decay, slower); `bm25` = lexical retrieval against the diff hunks (baseline for sparse graphs) |
79
+ | `--budget` | auto | Hard token cap: `N` enforces a fixed cap, `-1` disables it, `0` is a strict-zero floor (empty selection; use `--full` for changed files only) |
80
+ | `--alpha` | 0.60 | PPR damping; higher = context clusters tighter around changes (`--scoring ppr` only) |
81
+ | `--tau` | 0.12 | Relevance threshold for full fragment content; lower-scoring fragments are stubbed or dropped (lower = more context) |
82
+ | `--full` | false | Only the changed files, every fragment, no related-code context |
83
+ | `--timeout` | 300 | Wall-clock deadline in seconds; on expiry diffctx exits 124 instead of hanging |
84
+
85
+ Calibration of `--alpha`, `--tau`, and the edge-weight priors:
86
+ [`docs/parameter-strategy.md`](docs/parameter-strategy.md). Theory:
87
+ [Context-Selection for Git Diff (Zenodo, 2026)](https://doi.org/10.5281/zenodo.18824580).
88
+
89
+ ### `graph` subcommand
90
+
91
+ Explore the underlying dependency graph directly, without a diff:
92
+
93
+ ```bash
94
+ diffctx graph . # Mermaid graph of directory deps (default)
95
+ diffctx graph . --summary # cycles, hotspots, coupling metrics
96
+ diffctx graph . --level fragment -f json # fragment-level graph as JSON
97
+ diffctx graph . --level file -f graphml -o g.xml # file-level graph as GraphML
98
+ ```
99
+
100
+ ## Usage
101
+
102
+ <!-- BEGIN USAGE -->
103
+ ```bash
104
+ # full codebase export:
105
+ diffctx . # Markdown to stdout + token count
106
+ diffctx . -f md -c # Markdown → clipboard
107
+ diffctx . -f json -o tree.json # JSON → file
108
+ diffctx . --no-content # structure only, no file contents
109
+ diffctx . --max-depth 3 # limit depth
110
+ diffctx . -i custom.ignore # custom ignore patterns
111
+
112
+ # diff context mode (requires git repo):
113
+ diffctx . --diff # uncommitted changes (working tree vs HEAD)
114
+ diffctx . --diff HEAD~1 # context for last commit
115
+ diffctx . --diff main..feature # context for feature branch
116
+ diffctx . --diff HEAD~1 --budget 30000 # limit to ~30k tokens
117
+ diffctx . --diff HEAD~1 -c # diff context to clipboard
118
+ ```
119
+ <!-- END USAGE -->
120
+
121
+ Every run reports token count and size on stderr — `12,847 tokens
122
+ (o200k_base), 52.3 KB` (tiktoken, the GPT-4o tokenizer; `~`-prefixed
123
+ approximation above 1 MB). `-c/--copy` sends output to the clipboard via
124
+ `pbcopy` (macOS), `clip` (Windows), or `wl-copy`/`xclip`/`xsel` (Linux).
125
+ Unreadable files are replaced by placeholders such as `<binary file: N bytes>`,
126
+ `<file too large: N bytes>`, or `<unreadable content: not utf-8>`.
127
+
128
+ ## Python API
129
+
130
+ ```python
131
+ from pathlib import Path
132
+ from diffctx import build_diff_context, map_directory, to_json, to_markdown, to_text, to_yaml
133
+
134
+ ctx = build_diff_context(
135
+ Path("."),
136
+ "HEAD~1..HEAD",
137
+ budget_tokens=None, # None = auto; 0 = strict-zero floor (empty); -1 = uncapped; N = hard cap
138
+ alpha=0.6,
139
+ tau=0.12,
140
+ full=False,
141
+ scoring_mode="ego",
142
+ timeout=300,
143
+ )
144
+ print(to_markdown(ctx))
145
+
146
+ tree = map_directory(
147
+ ".",
148
+ max_depth=None,
149
+ no_content=False,
150
+ max_file_bytes=None,
151
+ ignore_file=None,
152
+ no_default_ignores=False,
153
+ whitelist_file=None,
154
+ )
155
+ print(to_yaml(tree))
156
+ ```
157
+
158
+ ## MCP server
159
+
160
+ diffctx includes an [MCP](https://modelcontextprotocol.io) server that lets AI
161
+ assistants (Claude Code, Cursor, Windsurf, etc.) call diff context analysis
162
+ automatically during code review. Install with `pip install 'diffctx[mcp]'`
163
+ and add to your MCP client config (e.g. `~/.claude/mcp.json` for Claude Code):
164
+
165
+ ```json
166
+ {
167
+ "mcpServers": {
168
+ "diffctx": {
169
+ "command": "diffctx-mcp"
170
+ }
171
+ }
172
+ }
173
+ ```
174
+
175
+ The server exposes a `get_diff_context` tool that assistants call when
176
+ reviewing PRs, explaining changes, or investigating broken tests. Configs for
177
+ Cursor, Continue, Windsurf, and Zed:
178
+ [`src/diffctx/mcp/README.md`](src/diffctx/mcp/README.md).
179
+
180
+ ## Ignore patterns
181
+
182
+ Respects `.gitignore` and `.diffctx/ignore` automatically — hierarchically at
183
+ every directory level, with gitignore semantics (negation `!important.log`,
184
+ anchored `/root_only.txt`). `.diffctx/whitelist` acts as an include-only
185
+ filter, and the output file is always auto-ignored. `--no-default-ignores`
186
+ disables the built-in patterns; `--no-ignores` disables all ignore rules
187
+ (tree mode only).
188
+
189
+ ## Exit codes
190
+
191
+ | Code | Meaning |
192
+ |------|---------|
193
+ | `0` | Success — output contains content |
194
+ | `1` | Runtime error (bad path, permission denied, etc.) |
195
+ | `2` | Usage error (invalid flags/arguments) |
196
+ | `3` | Environment error (`--diff` outside a git repo, git not installed, no commits yet) |
197
+ | `4` | `--diff` produced no semantic context (clean tree, binary-only, everything filtered); output is still emitted. Deletion/rename-only diffs list `deleted_files`/`renamed_files` and exit `0` |
198
+ | `130`| Interrupted (Ctrl-C) |
199
+ | `141`| Broken pipe (e.g. piping into `head`) |
200
+
201
+ ## License
202
+
203
+ Apache 2.0
204
+
205
+ ---
206
+
207
+ - [Changelog](CHANGELOG.md)
208
+ - [Security policy](SECURITY.md) — threat model and vulnerability reporting
209
+ - [Parameter strategy](docs/parameter-strategy.md) — how `--alpha`,
210
+ `--tau`, and edge weights are calibrated
package/bin/diffctx.js ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { spawnSync } = require('child_process');
7
+
8
+ const binaryName = process.platform === 'win32' ? 'diffctx.exe' : 'diffctx';
9
+ const binaryPath = path.join(__dirname, binaryName);
10
+
11
+ if (!fs.existsSync(binaryPath)) {
12
+ console.error(
13
+ 'diffctx: the native binary is missing — the postinstall download did not run or failed.\n' +
14
+ 'Reinstall with "npm install diffctx", or use "pip install diffctx" / "cargo install diffctx".'
15
+ );
16
+ process.exit(1);
17
+ }
18
+
19
+ const result = spawnSync(binaryPath, process.argv.slice(2), { stdio: 'inherit' });
20
+ if (result.error) {
21
+ console.error(`diffctx: ${result.error.message}`);
22
+ process.exit(1);
23
+ }
24
+ process.exit(result.status === null ? 1 : result.status);
package/checksums.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "diffctx-1.12.1-aarch64-apple-darwin.tar.gz": "93eec66793bbf7f7d62f4288e990852da7d7a6ab79d3b6b29bea03ae2ac7e434",
3
+ "diffctx-1.12.1-aarch64-unknown-linux-gnu.tar.gz": "55610bfe7856f96a73e87451eddc1aa1a546b84ddc2778cf67738e2333f16f02",
4
+ "diffctx-1.12.1-x86_64-pc-windows-msvc.zip": "731177d8af8807e7bc1ba7f021a1723c48da3dfc75bb544415b55b268d5f03b4",
5
+ "diffctx-1.12.1-x86_64-unknown-linux-gnu.tar.gz": "f37da41a6381497c15df881f35b8caf324d8ac5fa331118d2736537a246a71b1"
6
+ }
package/install.js ADDED
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const crypto = require('crypto');
8
+ const https = require('https');
9
+ const { execFileSync } = require('child_process');
10
+
11
+ const { version } = require('./package.json');
12
+ const checksums = require('./checksums.json');
13
+
14
+ const TARGETS = {
15
+ 'linux-x64': { target: 'x86_64-unknown-linux-gnu', archive: 'tar.gz' },
16
+ 'linux-arm64': { target: 'aarch64-unknown-linux-gnu', archive: 'tar.gz' },
17
+ 'darwin-arm64': { target: 'aarch64-apple-darwin', archive: 'tar.gz' },
18
+ 'win32-x64': { target: 'x86_64-pc-windows-msvc', archive: 'zip' },
19
+ };
20
+
21
+ function selectTarget() {
22
+ const key = `${process.platform}-${process.arch}`;
23
+ const selected = TARGETS[key];
24
+ if (!selected) {
25
+ throw new Error(
26
+ `diffctx has no prebuilt binary for ${key}. ` +
27
+ 'Install via pip ("pip install diffctx") or cargo ("cargo install diffctx") instead.'
28
+ );
29
+ }
30
+ return selected;
31
+ }
32
+
33
+ function download(url, destination, redirectsLeft = 5) {
34
+ return new Promise((resolve, reject) => {
35
+ https
36
+ .get(url, { headers: { 'user-agent': `diffctx-npm/${version}` } }, (response) => {
37
+ const { statusCode, headers } = response;
38
+ if (statusCode >= 300 && statusCode < 400 && headers.location) {
39
+ response.resume();
40
+ if (redirectsLeft === 0) {
41
+ reject(new Error(`too many redirects for ${url}`));
42
+ return;
43
+ }
44
+ resolve(download(headers.location, destination, redirectsLeft - 1));
45
+ return;
46
+ }
47
+ if (statusCode !== 200) {
48
+ response.resume();
49
+ reject(new Error(`download failed for ${url}: HTTP ${statusCode}`));
50
+ return;
51
+ }
52
+ const file = fs.createWriteStream(destination);
53
+ response.pipe(file);
54
+ file.on('finish', () => file.close(resolve));
55
+ file.on('error', reject);
56
+ })
57
+ .on('error', reject);
58
+ });
59
+ }
60
+
61
+ function verify(archivePath, expectedSha256) {
62
+ const actual = crypto.createHash('sha256').update(fs.readFileSync(archivePath)).digest('hex');
63
+ if (actual !== expectedSha256) {
64
+ throw new Error(`checksum mismatch for ${path.basename(archivePath)}: ${actual} != ${expectedSha256}`);
65
+ }
66
+ }
67
+
68
+ function extract(archivePath, archiveKind, destinationDir) {
69
+ if (archiveKind === 'zip') {
70
+ execFileSync(
71
+ 'powershell',
72
+ ['-NoProfile', '-Command', `Expand-Archive -LiteralPath '${archivePath}' -DestinationPath '${destinationDir}' -Force`],
73
+ { stdio: 'inherit' }
74
+ );
75
+ return;
76
+ }
77
+ execFileSync('tar', ['-xzf', archivePath, '-C', destinationDir], { stdio: 'inherit' });
78
+ }
79
+
80
+ async function main() {
81
+ const { target, archive } = selectTarget();
82
+ const assetName = `diffctx-${version}-${target}.${archive}`;
83
+ const expectedSha256 = checksums[assetName];
84
+ if (!expectedSha256) {
85
+ throw new Error(`no published checksum for ${assetName}`);
86
+ }
87
+
88
+ const binDir = path.join(__dirname, 'bin');
89
+ fs.mkdirSync(binDir, { recursive: true });
90
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'diffctx-'));
91
+ const archivePath = path.join(workDir, assetName);
92
+
93
+ const url = `https://github.com/nikolay-e/diffctx/releases/download/v${version}/${assetName}`;
94
+ await download(url, archivePath);
95
+ verify(archivePath, expectedSha256);
96
+ extract(archivePath, archive, workDir);
97
+
98
+ const binaryName = process.platform === 'win32' ? 'diffctx.exe' : 'diffctx';
99
+ fs.copyFileSync(path.join(workDir, binaryName), path.join(binDir, binaryName));
100
+ if (process.platform !== 'win32') {
101
+ fs.chmodSync(path.join(binDir, binaryName), 0o755);
102
+ }
103
+ fs.rmSync(workDir, { recursive: true, force: true });
104
+ }
105
+
106
+ main().catch((error) => {
107
+ console.error(`diffctx: ${error.message}`);
108
+ process.exit(1);
109
+ });
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "diffctx",
3
+ "version": "1.12.1",
4
+ "description": "Selects the minimum code an LLM needs to review a git diff",
5
+ "keywords": [
6
+ "git",
7
+ "diff",
8
+ "llm",
9
+ "code-review",
10
+ "context"
11
+ ],
12
+ "homepage": "https://github.com/nikolay-e/diffctx",
13
+ "bugs": "https://github.com/nikolay-e/diffctx/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/nikolay-e/diffctx.git"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "author": "Nikolay Eremeev",
20
+ "bin": {
21
+ "diffctx": "bin/diffctx.js"
22
+ },
23
+ "files": [
24
+ "bin/diffctx.js",
25
+ "install.js",
26
+ "checksums.json"
27
+ ],
28
+ "scripts": {
29
+ "postinstall": "node install.js"
30
+ },
31
+ "engines": {
32
+ "node": ">=18"
33
+ }
34
+ }