ts-pack-cli 1.27.1__tar.gz

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,277 @@
1
+ # Build output
2
+ target/
3
+ build/
4
+ dist/
5
+ wheelhouse/
6
+ .build/
7
+ .yardoc/
8
+
9
+ # Language-specific build artifacts
10
+ *.so
11
+ *.dylib
12
+ *.dll
13
+ *.node
14
+ *.bundle
15
+ *.class
16
+ *.egg-info/
17
+ *$py.class
18
+ *.py[cod]
19
+ .rumdl_cache/
20
+ .playwright-mcp/
21
+ __pycache__/
22
+ _build/
23
+ deps/
24
+
25
+ # Python
26
+ .venv
27
+ .coverage
28
+ coverage.xml
29
+ .pytest_cache
30
+ .ruff_cache
31
+ .python-version
32
+
33
+ # Node.js
34
+ node_modules/
35
+ .pnpm-store/
36
+
37
+ # C#/.NET
38
+ packages/csharp/**/bin/
39
+ packages/csharp/**/obj/
40
+ packages/csharp/**/runtimes/
41
+
42
+ # Go vendored FFI artifacts
43
+ packages/go/include/*
44
+ !packages/go/include/ts_pack.h
45
+ # Staging dir written by `go run ./cmd/setup`. The leading dot
46
+ # matters — the old `packages/go/lib/` rule matched nothing and let 203 MB of
47
+ # compiled archives get committed. ~keep
48
+ packages/go/.lib/
49
+ # Compiled output of `go build ./cmd/setup`, which lands beside the source it was
50
+ # built from. Anchored so it cannot match the cmd/setup source directory. ~keep
51
+ /packages/go/setup
52
+
53
+ # Compiled object files and static archives are always build output
54
+ *.a
55
+ *.o
56
+
57
+ # Elixir build artifacts
58
+ crates/ts-pack-elixir/deps/
59
+ crates/ts-pack-elixir/_build/
60
+
61
+ # Ruby
62
+ crates/ts-pack-ruby/tmp/
63
+ packages/ruby/tmp/
64
+
65
+ # WASM crate sits outside pnpm-workspace.yaml; setup writes a stray lockfile
66
+ crates/ts-pack-core-wasm/pnpm-lock.yaml
67
+
68
+ # Parsers (cloned at build time)
69
+ parsers/
70
+
71
+ # Generated parser artifacts for in-repo (vendored) grammars — regenerated from grammar.js.
72
+ # Hand-written external scanners (scanner.c/scanner.cc) are source, not generated, so they
73
+ # stay tracked; only the generated outputs are ignored.
74
+ grammars/*/src/parser.c
75
+ grammars/*/src/grammar.json
76
+ grammars/*/src/node-types.json
77
+ grammars/*/src/tree_sitter/
78
+
79
+ # Test app build/install artifacts
80
+ test_apps/*/target/
81
+ test_apps/*/build/
82
+ test_apps/*/.venv/
83
+ test_apps/*/vendor/
84
+ test_apps/*/_build/
85
+ test_apps/*/deps/
86
+ test_apps/*/obj/
87
+ test_apps/*/bin/
88
+ test_apps/*/.dart_tool/
89
+ test_apps/*/.gradle/
90
+ test_apps/*/.build/
91
+ test_apps/c/build/
92
+ test_documents/file:/
93
+ test_apps/*/file:/
94
+
95
+ # E2E build artifacts
96
+ e2e/c/build/
97
+ e2e/swift_e2e/.build/
98
+ e2e/swift_e2e/Package.resolved
99
+ e2e/*/.gradle/
100
+
101
+ # Gradle local cache (machine-local build state, never committed)
102
+ packages/kotlin-android/.gradle/
103
+
104
+ # IDE / OS
105
+ .DS_store
106
+ .idea/
107
+ .basemind/
108
+ .run
109
+ *.bak
110
+ *.Cache
111
+ *.cscfg
112
+ *.suo
113
+ *.user
114
+ *.log
115
+
116
+ # Environment
117
+ .env
118
+ requirements.txt
119
+ vendor/
120
+
121
+ # PHP cs-fixer cache
122
+ packages/php/var/
123
+ .php-cs-fixer.cache
124
+ .php-cs-fixer.dist.php
125
+
126
+ # AI assistant config (generated)
127
+ CLAUDE.md
128
+ .claude/
129
+ .cursor/
130
+ .gemini/
131
+ .windsurf/
132
+ .codex/
133
+ # ~keep Ignore only the repo-root local MCP config; plugin/.mcp.json is a generated, tracked bundle.
134
+ /.mcp.json
135
+ AGENTS.md
136
+ GEMINI.md
137
+
138
+ .cache/
139
+ .lycheecache
140
+
141
+ # Astro Starlight docs-site build artifacts
142
+ docs-site/dist/
143
+ docs-site/.astro/
144
+
145
+
146
+ # Additional generated artifacts
147
+ .remote-cache/
148
+ .alef/
149
+ .gemini/
150
+ GEMINI.md
151
+ *.pyd
152
+ .venv/
153
+ .gems/
154
+ vendor/bundle/
155
+ *.h.bak
156
+ *.test
157
+ bin/
158
+ # The dart package ships `bin/download_libs.dart` as its `pubspec executables:`
159
+ # entry that consumers run after `pub get` to fetch the platform-specific native
160
+ # library. Without re-including this path, `git ls-files` and `actions/checkout`
161
+ # omit the file and `pub publish` ships a pubspec referencing a missing
162
+ # executable — and `dart run <pkg>:download_libs` fails on every consumer.
163
+ !packages/dart/bin/
164
+ !packages/dart/bin/**
165
+ # The cli-proxy npm package ships `bin/ts-pack.js` as its `package.json` `bin`
166
+ # launcher (downloads + execs the native ts-pack binary). The generic `bin/`
167
+ # rule above would otherwise drop it and publish a package with no executable.
168
+ !cli-proxy/npm/bin/
169
+ !cli-proxy/npm/bin/**
170
+ obj/
171
+ *.nupkg
172
+
173
+ e2e/zig/.zig-cache/
174
+ test_apps/zig/.zig-cache/
175
+ test_apps/zig/zig-pkg/
176
+ test_apps/swift_e2e/Package.resolved
177
+ # Root Package.resolved is a local SPM resolution artifact for the published root
178
+ # manifest — not consumed downstream (SPM ignores a dependency's Package.resolved).
179
+ /Package.resolved
180
+ # swift-bridge generated sources MUST be tracked: SPM consumers checking out
181
+ # the git tag don't run cargo build, so without these files in the tree the
182
+ # RustString type defined here is missing → ZSwiftPluginHelpers.swift won't
183
+ # compile. Regenerated on each rc cut via `cargo build -p tree-sitter-language-pack-swift`.
184
+ e2e/dart/.dart_tool/
185
+
186
+ test_apps/c/ffi/
187
+ e2e/c/ffi/
188
+
189
+ .ai-rulez/.generated-manifest.json
190
+
191
+ packages/zig/zig-pkg/
192
+ e2e/zig/zig-pkg/
193
+ packages/zig/.zig-global-cache/
194
+
195
+ # Scratch files `alef verify` writes and does not always clean up. ~keep
196
+ .tmp*.rb
197
+ .tmp*.php
198
+ erl_crash.dump
199
+ # The `*.Cache` rule above only matches this on case-insensitive filesystems
200
+ # (macOS); CI runs on Linux, so spell it out. ~keep
201
+ .phpunit.result.cache
202
+
203
+
204
+ # Alef-generated skills are source-controlled; other agent-local state stays ignored.
205
+ !.codex/
206
+ .codex/*
207
+ !.codex/skills/
208
+ .codex/skills/*
209
+ !.codex/skills/api/
210
+ !.codex/skills/api/SKILL.md
211
+ !.codex/skills/cli/
212
+ !.codex/skills/cli/SKILL.md
213
+ !.codex/skills/mcp/
214
+ !.codex/skills/mcp/SKILL.md
215
+ !.agents/
216
+ .agents/*
217
+ !.agents/skills/
218
+ .agents/skills/*
219
+ !.agents/skills/api/
220
+ !.agents/skills/api/SKILL.md
221
+ !.agents/skills/cli/
222
+ !.agents/skills/cli/SKILL.md
223
+ !.agents/skills/mcp/
224
+ !.agents/skills/mcp/SKILL.md
225
+ !.agents/plugins/
226
+ !.agents/plugins/marketplace.json
227
+ !.claude/
228
+ .claude/*
229
+ !.claude/skills/
230
+ .claude/skills/*
231
+ !.claude/skills/api/
232
+ !.claude/skills/api/SKILL.md
233
+ !.claude/skills/cli/
234
+ !.claude/skills/cli/SKILL.md
235
+ !.claude/skills/mcp/
236
+ !.claude/skills/mcp/SKILL.md
237
+ !.github/skills/
238
+ .github/skills/*
239
+ !.github/skills/api/
240
+ !.github/skills/api/SKILL.md
241
+ !.github/skills/cli/
242
+ !.github/skills/cli/SKILL.md
243
+ !.github/skills/mcp/
244
+ !.github/skills/mcp/SKILL.md
245
+
246
+ # poly (polylint) local cache
247
+ .polylint/
248
+
249
+ poly.local.toml
250
+
251
+ # Alef snippet validator scratch workspaces and caches ~keep
252
+ **/.alef-snippet-*/
253
+ **/.alef-cache/
254
+ **/.alef/
255
+
256
+ # Prerelease test-app staging (scripts/prerelease_test_apps.py) ~keep
257
+ .prerelease/
258
+
259
+ # BEGIN ai-rulez (DO NOT EDIT - managed by ai-rulez)
260
+ .ai-rulez/.config.local.*
261
+ .opencode/agents/
262
+ .opencode/commands/
263
+ /opencode.json
264
+ # END ai-rulez
265
+
266
+ # Agent harness output outside the ai-rulez managed block: the machine-local overlay,
267
+ # plugin-root manifests, and presets this repository does not enable.
268
+ .ai-rulez/config.local.*
269
+ .ai-rulez/local/
270
+ **/.ai-rulez/.generated-manifest.local.json
271
+ plugin/.ai-rulez/.generated-manifest.json
272
+ .agents/settings.json
273
+ .claude/settings.json
274
+ .claude/plugins.json
275
+ .codex/commands/
276
+ .codex/plugins.json
277
+ .github/commands/
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.5
2
+ Name: ts-pack-cli
3
+ Version: 1.27.1
4
+ Summary: CLI proxy for ts-pack — downloads and runs the native ts-pack binary from GitHub releases.
5
+ Project-URL: Homepage, https://github.com/xberg-io/tree-sitter-language-pack
6
+ Project-URL: Issues, https://github.com/xberg-io/tree-sitter-language-pack/issues
7
+ Project-URL: Repository, https://github.com/xberg-io/tree-sitter-language-pack.git
8
+ Author-email: Na'aman Hirschfeld <naaman@xberg.io>, Tobias Perlstein <tobias@xberg.io>
9
+ Maintainer-email: Na'aman Hirschfeld <naaman@xberg.io>, Tobias Perlstein <tobias@xberg.io>
10
+ License: MIT
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+
22
+ # ts-pack-cli
23
+
24
+ CLI proxy for [`ts-pack`](https://github.com/xberg-io/tree-sitter-language-pack). Installing
25
+ this package provides a `ts-pack` command. Platform wheels bundle the native binary; the
26
+ source distribution downloads the binary of the same release version from GitHub releases
27
+ and verifies it against that release's `SHA256SUMS` before running it.
28
+
29
+ The package version is the `ts-pack` release version, so `ts-pack-cli==X.Y.Z` always runs
30
+ `ts-pack` `X.Y.Z`.
@@ -0,0 +1,9 @@
1
+ # ts-pack-cli
2
+
3
+ CLI proxy for [`ts-pack`](https://github.com/xberg-io/tree-sitter-language-pack). Installing
4
+ this package provides a `ts-pack` command. Platform wheels bundle the native binary; the
5
+ source distribution downloads the binary of the same release version from GitHub releases
6
+ and verifies it against that release's `SHA256SUMS` before running it.
7
+
8
+ The package version is the `ts-pack` release version, so `ts-pack-cli==X.Y.Z` always runs
9
+ `ts-pack` `X.Y.Z`.
@@ -0,0 +1,149 @@
1
+ """Custom hatchling build hook that bundles the native ts-pack binary into a wheel.
2
+
3
+ When building a platform-specific wheel in CI, the target triple is supplied via
4
+ the ``TS_PACK_CLI_TARGET`` env var (the build host is always linux/amd64, so the
5
+ triple cannot be inferred from ``platform.*``). The matching
6
+ ``ts-pack-<target>.tar.gz`` / ``.zip`` is located (repo root or ``dist/``),
7
+ the binary is extracted into ``ts_pack_cli/bin/<target>/``, force-included in the
8
+ wheel, and the wheel is tagged for that platform so PyPI serves the right artifact.
9
+
10
+ If no target/binary is found (e.g. the sdist build, or an unknown platform), the
11
+ hook is a no-op and the package falls back to the runtime downloader in
12
+ ``ts_pack_cli/downloader.py`` (see ``cli.py``).
13
+
14
+ The linux-gnu binaries are linked on the ubuntu-24.04 runners (glibc 2.39), so the wheel
15
+ tag is manylinux_2_39; the publish workflow fails the wheel when the binary needs a newer glibc.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import shutil
22
+ import tarfile
23
+ import zipfile
24
+ from pathlib import Path
25
+
26
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
27
+
28
+ _TAG_MAP = {
29
+ "x86_64-pc-windows-msvc": "win_amd64",
30
+ "x86_64-unknown-linux-gnu": "manylinux_2_39_x86_64",
31
+ "aarch64-unknown-linux-gnu": "manylinux_2_39_aarch64",
32
+ "aarch64-apple-darwin": "macosx_15_0_arm64",
33
+ "x86_64-apple-darwin": "macosx_15_0_x86_64",
34
+ }
35
+
36
+
37
+ def _safe_destination(root: Path, member_name: str) -> Path:
38
+ """Resolve an archive member path and require it to stay under root."""
39
+ root = root.resolve()
40
+ target = (root / member_name.replace("\\", "/")).resolve(strict=False)
41
+ if target != root and not target.is_relative_to(root):
42
+ raise RuntimeError(f"archive member escapes extraction directory: {member_name}")
43
+ return target
44
+
45
+
46
+ def _extract_zip_bounded(archive: Path, extract_dir: Path) -> None:
47
+ """Extract zip entries after bounding each destination path."""
48
+ with zipfile.ZipFile(archive) as zf:
49
+ for member in zf.infolist():
50
+ target = _safe_destination(extract_dir, member.filename)
51
+ if member.is_dir():
52
+ target.mkdir(parents=True, exist_ok=True)
53
+ continue
54
+
55
+ target.parent.mkdir(parents=True, exist_ok=True)
56
+ with zf.open(member) as source, target.open("wb") as destination:
57
+ shutil.copyfileobj(source, destination)
58
+
59
+
60
+ def _extract_tar_bounded(archive: Path, extract_dir: Path) -> None:
61
+ """Extract regular tar entries after bounding each destination path."""
62
+ with tarfile.open(archive, "r:gz") as tf:
63
+ for member in tf.getmembers():
64
+ target = _safe_destination(extract_dir, member.name)
65
+ if member.isdir():
66
+ target.mkdir(parents=True, exist_ok=True)
67
+ continue
68
+ if not member.isfile():
69
+ raise RuntimeError(f"unsupported archive member type: {member.name}")
70
+
71
+ target.parent.mkdir(parents=True, exist_ok=True)
72
+ source = tf.extractfile(member)
73
+ if source is None:
74
+ raise RuntimeError(f"could not read archive member: {member.name}")
75
+ with source, target.open("wb") as destination:
76
+ shutil.copyfileobj(source, destination)
77
+
78
+
79
+ class CustomBuildHook(BuildHookInterface):
80
+ """Inject the matching native binary into a platform-tagged wheel."""
81
+
82
+ PLUGIN_NAME = "custom"
83
+
84
+ def initialize(self, version: str, build_data: dict) -> None: # noqa: ARG002
85
+ """Bundle a staged native binary when building a targeted wheel."""
86
+ target = os.environ.get("TS_PACK_CLI_TARGET", "").strip()
87
+ if not target:
88
+ return
89
+
90
+ archive = self._find_archive(target)
91
+ if archive is None:
92
+ raise RuntimeError(
93
+ f"TS_PACK_CLI_TARGET={target} but no ts-pack-{target}.(tar.gz|zip) "
94
+ f"found in repo root or dist/; refusing to build an empty platform wheel."
95
+ )
96
+
97
+ wheel_tag = _TAG_MAP.get(target)
98
+ if wheel_tag is None:
99
+ raise RuntimeError(f"no wheel platform tag mapped for target {target}")
100
+
101
+ binary = self._extract_binary(archive, target)
102
+
103
+ relative = f"ts_pack_cli/bin/{target}/{binary.name}"
104
+ force_include = build_data.setdefault("force_include", {})
105
+ force_include[str(binary)] = relative
106
+
107
+ self._include_staged_payload(force_include, binary, target)
108
+
109
+ build_data["pure_python"] = False
110
+ build_data["infer_tag"] = False
111
+ build_data["tag"] = f"py3-none-{wheel_tag}"
112
+
113
+ def _include_staged_payload(self, force_include: dict[str, str], binary: Path, target: str) -> None:
114
+ """Force-include every file the release archive staged beside the binary."""
115
+ stage_dir = binary.parent
116
+ for path in sorted(stage_dir.rglob("*")):
117
+ if not path.is_file() or path == binary:
118
+ continue
119
+ relative_path = path.relative_to(stage_dir).as_posix()
120
+ force_include[str(path)] = f"ts_pack_cli/bin/{target}/{relative_path}"
121
+
122
+ def _find_archive(self, target: str) -> Path | None:
123
+ root = Path(self.root)
124
+ repo_root = root.parent.parent
125
+ for base in (repo_root, repo_root / "dist", root, root / "dist"):
126
+ for ext in ("tar.gz", "zip"):
127
+ candidate = base / f"ts-pack-{target}.{ext}"
128
+ if candidate.is_file():
129
+ return candidate
130
+ return None
131
+
132
+ def _extract_binary(self, archive: Path, target: str) -> Path:
133
+ is_windows = target.endswith("windows-msvc")
134
+ binary_name = "ts-pack.exe" if is_windows else "ts-pack"
135
+ extract_dir = Path(self.root) / ".build-extract" / target
136
+ if extract_dir.exists():
137
+ shutil.rmtree(extract_dir, ignore_errors=True)
138
+ extract_dir.mkdir(parents=True, exist_ok=True)
139
+
140
+ if str(archive).lower().endswith(".zip"):
141
+ _extract_zip_bounded(archive, extract_dir)
142
+ else:
143
+ _extract_tar_bounded(archive, extract_dir)
144
+
145
+ for candidate in extract_dir.rglob(binary_name):
146
+ if candidate.is_file():
147
+ candidate.chmod(0o755)
148
+ return candidate
149
+ raise RuntimeError(f"binary {binary_name} not found inside {archive.name}")
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ build-backend = "hatchling.build"
3
+
4
+ requires = ["hatchling"]
5
+
6
+ [project]
7
+ name = "ts-pack-cli"
8
+ version = "1.27.1"
9
+ description = "CLI proxy for ts-pack — downloads and runs the native ts-pack binary from GitHub releases."
10
+ readme = "README.md"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Na'aman Hirschfeld", email = "naaman@xberg.io" },
14
+ { name = "Tobias Perlstein", email = "tobias@xberg.io" },
15
+ ]
16
+ maintainers = [
17
+ { name = "Na'aman Hirschfeld", email = "naaman@xberg.io" },
18
+ { name = "Tobias Perlstein", email = "tobias@xberg.io" },
19
+ ]
20
+ requires-python = ">=3.11"
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Environment :: Console",
24
+ "Intended Audience :: Developers",
25
+ "License :: OSI Approved :: MIT License",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ ]
31
+
32
+ urls.Homepage = "https://github.com/xberg-io/tree-sitter-language-pack"
33
+ urls.Issues = "https://github.com/xberg-io/tree-sitter-language-pack/issues"
34
+ urls.Repository = "https://github.com/xberg-io/tree-sitter-language-pack.git"
35
+ scripts.ts-pack = "ts_pack_cli.cli:main"
36
+
37
+ [tool.hatch]
38
+ build.hooks.custom.path = "hatch_build.py"
39
+ build.targets.wheel.packages = ["ts_pack_cli"]
@@ -0,0 +1,13 @@
1
+ """Make the build hook importable from the tests directory.
2
+
3
+ ``hatch_build.py`` sits at the package root because hatchling loads it by path
4
+ rather than as an installed module, so it is not importable from ``tests/``
5
+ without help.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@@ -0,0 +1,105 @@
1
+ """Pinned-version and checksum behaviour of the runtime downloader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import io
7
+ import tarfile
8
+
9
+ import pytest
10
+ from ts_pack_cli import __version__, downloader
11
+
12
+
13
+ def _tarball(binary: bytes) -> bytes:
14
+ buffer = io.BytesIO()
15
+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
16
+ info = tarfile.TarInfo("ts-pack")
17
+ info.size = len(binary)
18
+ archive.addfile(info, io.BytesIO(binary))
19
+ return buffer.getvalue()
20
+
21
+
22
+ def test_archive_name_matches_release_asset_naming() -> None:
23
+ assert downloader._archive_name("aarch64-apple-darwin") == "ts-pack-aarch64-apple-darwin.tar.gz"
24
+ assert downloader._archive_name("x86_64-pc-windows-msvc") == "ts-pack-x86_64-pc-windows-msvc.zip"
25
+
26
+
27
+ def test_asset_url_addresses_the_exact_tag_never_latest() -> None:
28
+ url = downloader._asset_url("1.28.0-rc.1", "ts-pack-aarch64-apple-darwin.tar.gz")
29
+ assert url == (
30
+ "https://github.com/xberg-io/tree-sitter-language-pack/releases/download/"
31
+ "v1.28.0-rc.1/ts-pack-aarch64-apple-darwin.tar.gz"
32
+ )
33
+ assert "latest" not in url
34
+
35
+
36
+ def test_verify_accepts_matching_digest() -> None:
37
+ data = b"payload"
38
+ downloader._verify_archive(data, "a.tar.gz", f"{hashlib.sha256(data).hexdigest()} a.tar.gz\n")
39
+
40
+
41
+ def test_verify_rejects_digest_mismatch() -> None:
42
+ sums = f"{hashlib.sha256(b'other').hexdigest()} a.tar.gz\n"
43
+ with pytest.raises(RuntimeError, match="checksum mismatch"):
44
+ downloader._verify_archive(b"payload", "a.tar.gz", sums)
45
+
46
+
47
+ def test_verify_rejects_archive_missing_from_sums() -> None:
48
+ sums = f"{hashlib.sha256(b'payload').hexdigest()} b.tar.gz\n"
49
+ with pytest.raises(RuntimeError, match="no checksum entry"):
50
+ downloader._verify_archive(b"payload", "a.tar.gz", sums)
51
+
52
+
53
+ def test_verify_fails_closed_without_sums_unless_allowed() -> None:
54
+ with pytest.raises(RuntimeError, match="refusing to install an unverified binary"):
55
+ downloader._verify_archive(b"payload", "a.tar.gz", None)
56
+ downloader._verify_archive(b"payload", "a.tar.gz", None, allow_unverified=True)
57
+
58
+
59
+ def _stub_download(monkeypatch, tmp_path, sums: str | None, archive: bytes):
60
+ requested: list[str] = []
61
+
62
+ def fake_get(url: str) -> bytes:
63
+ requested.append(url)
64
+ if url.endswith("/SHA256SUMS"):
65
+ if sums is None:
66
+ raise RuntimeError(f"HTTP 404 for {url}")
67
+ return sums.encode()
68
+ return archive
69
+
70
+ monkeypatch.setattr(downloader, "_http_get", fake_get)
71
+ monkeypatch.setattr(downloader, "_target_triple", lambda: "x86_64-unknown-linux-gnu")
72
+ monkeypatch.setattr(downloader, "_binary_name", lambda: "ts-pack")
73
+ monkeypatch.setattr(downloader.Path, "home", lambda: tmp_path)
74
+ monkeypatch.delenv("TS_PACK_BINARY", raising=False)
75
+ monkeypatch.delenv("TS_PACK_CLI_ALLOW_UNVERIFIED", raising=False)
76
+ return requested
77
+
78
+
79
+ def test_ensure_binary_downloads_only_the_package_version(monkeypatch, tmp_path) -> None:
80
+ archive = _tarball(b"#!/bin/sh\n")
81
+ sums = f"{hashlib.sha256(archive).hexdigest()} ts-pack-x86_64-unknown-linux-gnu.tar.gz\n"
82
+ requested = _stub_download(monkeypatch, tmp_path, sums, archive)
83
+
84
+ path = downloader.ensure_binary()
85
+
86
+ base = f"https://github.com/xberg-io/tree-sitter-language-pack/releases/download/v{__version__}/"
87
+ assert requested == [base + "ts-pack-x86_64-unknown-linux-gnu.tar.gz", base + "SHA256SUMS"]
88
+ assert path.endswith("ts-pack")
89
+
90
+
91
+ def test_ensure_binary_refuses_on_checksum_mismatch(monkeypatch, tmp_path) -> None:
92
+ archive = _tarball(b"#!/bin/sh\n")
93
+ sums = f"{'0' * 64} ts-pack-x86_64-unknown-linux-gnu.tar.gz\n"
94
+ _stub_download(monkeypatch, tmp_path, sums, archive)
95
+
96
+ with pytest.raises(RuntimeError, match="checksum mismatch"):
97
+ downloader.ensure_binary()
98
+ assert not list(tmp_path.rglob("ts-pack"))
99
+
100
+
101
+ def test_ensure_binary_refuses_when_release_has_no_sums(monkeypatch, tmp_path) -> None:
102
+ _stub_download(monkeypatch, tmp_path, None, _tarball(b"#!/bin/sh\n"))
103
+
104
+ with pytest.raises(RuntimeError, match="refusing to install an unverified binary"):
105
+ downloader.ensure_binary()
@@ -0,0 +1,50 @@
1
+ """The wheel build hook repackages the released CLI archive for one target."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import tarfile
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ from hatch_build import CustomBuildHook
11
+
12
+ _TARGET = "x86_64-unknown-linux-gnu"
13
+
14
+
15
+ def _hook(root: Path) -> CustomBuildHook:
16
+ return CustomBuildHook(str(root), {}, None, None, str(root), "wheel")
17
+
18
+
19
+ def _stage_archive(root: Path, target: str, member: str) -> None:
20
+ dist = root.parent.parent / "dist"
21
+ dist.mkdir(parents=True, exist_ok=True)
22
+ with tarfile.open(dist / f"ts-pack-{target}.tar.gz", "w:gz") as archive:
23
+ info = tarfile.TarInfo(member)
24
+ info.size = 4
25
+ archive.addfile(info, io.BytesIO(b"bin\n"))
26
+
27
+
28
+ def test_no_target_is_a_noop(tmp_path, monkeypatch) -> None:
29
+ monkeypatch.delenv("TS_PACK_CLI_TARGET", raising=False)
30
+ data: dict = {}
31
+ _hook(tmp_path).initialize("1.0.0", data)
32
+ assert data == {}
33
+
34
+
35
+ def test_target_without_archive_refuses_an_empty_wheel(tmp_path, monkeypatch) -> None:
36
+ monkeypatch.setenv("TS_PACK_CLI_TARGET", _TARGET)
37
+ with pytest.raises(RuntimeError, match="refusing to build an empty platform wheel"):
38
+ _hook(tmp_path / "a" / "b").initialize("1.0.0", {})
39
+
40
+
41
+ def test_target_bundles_the_binary_and_tags_the_wheel(tmp_path, monkeypatch) -> None:
42
+ root = tmp_path / "cli-proxy" / "pypi"
43
+ root.mkdir(parents=True)
44
+ _stage_archive(root, _TARGET, "ts-pack")
45
+ monkeypatch.setenv("TS_PACK_CLI_TARGET", _TARGET)
46
+ data: dict = {}
47
+ _hook(root).initialize("1.0.0", data)
48
+ assert list(data["force_include"].values()) == [f"ts_pack_cli/bin/{_TARGET}/ts-pack"]
49
+ assert data["tag"] == "py3-none-manylinux_2_39_x86_64"
50
+ assert data["pure_python"] is False
@@ -0,0 +1,5 @@
1
+ """CLI proxy for ts-pack."""
2
+
3
+ # ~keep Release tag form (1.28.0-rc.1), not the PEP 440 spelling in pyproject.toml: the downloader
4
+ # builds the GitHub release URL from it. scripts/sync_plugin_version.py keeps it on the product version.
5
+ __version__ = "1.27.1"
@@ -0,0 +1,44 @@
1
+ """CLI entry point for the ts-pack proxy.
2
+
3
+ A platform-specific wheel bundles the native binary under ``ts_pack_cli/bin/<target>/``;
4
+ the sdist (and unknown platforms) ship no binary and fall back to the runtime downloader.
5
+ Each wheel contains exactly one ``bin/<target>`` directory, so the binary is located by
6
+ globbing rather than recomputing the target triple.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import platform
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from .downloader import run
18
+
19
+
20
+ def _find_bundled_binary() -> str | None:
21
+ """Return the path to the bundled native binary if this wheel shipped one."""
22
+ bin_root = Path(__file__).parent / "bin"
23
+ if not bin_root.is_dir():
24
+ return None
25
+
26
+ binary_name = "ts-pack.exe" if platform.system().lower() == "windows" else "ts-pack"
27
+ for candidate in bin_root.glob(f"*/{binary_name}"):
28
+ if candidate.is_file() and os.access(candidate, os.X_OK):
29
+ return str(candidate)
30
+ return None
31
+
32
+
33
+ def main() -> None:
34
+ """Resolve the native binary (bundled or downloaded) and exec it with forwarded argv."""
35
+ bundled = _find_bundled_binary()
36
+ if bundled:
37
+ completed = subprocess.run([bundled, *sys.argv[1:]], check=False) # noqa: S603
38
+ sys.exit(completed.returncode)
39
+
40
+ sys.exit(run(sys.argv[1:]))
41
+
42
+
43
+ if __name__ == "__main__":
44
+ main()
@@ -0,0 +1,251 @@
1
+ """Download, verify, and run the native ts-pack binary.
2
+
3
+ The package version is the release version: the archive is fetched from the
4
+ ``v<version>`` release of this exact package, never from ``latest``, and checked
5
+ against that release's SHA256SUMS. All diagnostics go to stderr.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ import platform
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tarfile
17
+ import tempfile
18
+ import zipfile
19
+ from pathlib import Path, PurePosixPath
20
+ from typing import cast
21
+ from urllib.error import HTTPError, URLError
22
+ from urllib.parse import quote, urlsplit
23
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
24
+
25
+ from . import __version__
26
+
27
+ REPO = "xberg-io/tree-sitter-language-pack"
28
+ BIN_NAME = "ts-pack"
29
+ PKG_NAME = "ts-pack-cli"
30
+ ALLOW_UNVERIFIED_ENV = "TS_PACK_CLI_ALLOW_UNVERIFIED"
31
+ SUMS_NAME = "SHA256SUMS"
32
+ _USER_AGENT = "ts-pack-cli-python-proxy"
33
+
34
+
35
+ def _target_triple() -> str:
36
+ system = platform.system().lower()
37
+ machine = platform.machine().lower()
38
+
39
+ if system == "windows":
40
+ if machine in {"amd64", "x86_64"}:
41
+ return "x86_64-pc-windows-msvc"
42
+ raise RuntimeError(f"unsupported Windows arch: {machine}")
43
+ if system == "linux":
44
+ if machine in {"amd64", "x86_64"}:
45
+ return "x86_64-unknown-linux-gnu"
46
+ if machine in {"aarch64", "arm64"}:
47
+ return "aarch64-unknown-linux-gnu"
48
+ raise RuntimeError(f"unsupported Linux arch: {machine}")
49
+ if system == "darwin":
50
+ if machine in {"aarch64", "arm64"}:
51
+ return "aarch64-apple-darwin"
52
+ if machine in {"amd64", "x86_64"}:
53
+ return "x86_64-apple-darwin"
54
+ raise RuntimeError(f"unsupported macOS arch: {machine}")
55
+ raise RuntimeError(f"unsupported platform: {system} {machine}")
56
+
57
+
58
+ def _binary_name() -> str:
59
+ return f"{BIN_NAME}.exe" if platform.system().lower() == "windows" else BIN_NAME
60
+
61
+
62
+ class _HttpsOnlyRedirectHandler(HTTPRedirectHandler):
63
+ """Reject any redirect whose target is not https (downgrade/SSRF guard)."""
64
+
65
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def] # noqa: ANN001, ANN202, PLR0913
66
+ if urlsplit(newurl).scheme.lower() != "https":
67
+ raise URLError(f"refusing non-https redirect to: {newurl}")
68
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
69
+
70
+
71
+ _opener = build_opener(_HttpsOnlyRedirectHandler())
72
+
73
+
74
+ def _http_get(url: str) -> bytes:
75
+ if urlsplit(url).scheme.lower() != "https":
76
+ raise RuntimeError(f"refusing non-https URL: {url}")
77
+ request = Request(url, headers={"User-Agent": _USER_AGENT}) # noqa: S310 - scheme validated https-only above
78
+ try:
79
+ with _opener.open(request, timeout=60) as response:
80
+ if response.status != 200:
81
+ raise RuntimeError(f"HTTP {response.status} for {url}")
82
+ return cast("bytes", response.read())
83
+ except HTTPError as exc:
84
+ raise RuntimeError(f"HTTP {exc.code} for {url}") from exc
85
+ except URLError as exc:
86
+ raise RuntimeError(f"failed to fetch {url}: {exc}") from exc
87
+
88
+
89
+ def _archive_name(triple: str) -> str:
90
+ return f"{BIN_NAME}-{triple}.{'zip' if 'windows' in triple else 'tar.gz'}"
91
+
92
+
93
+ def _asset_url(version: str, name: str) -> str:
94
+ return f"https://github.com/{REPO}/releases/download/v{quote(version, safe='')}/{name}"
95
+
96
+
97
+ def _expected_digest(text: str, asset_name: str) -> str | None:
98
+ for line in text.splitlines():
99
+ stripped = line.strip()
100
+ if not stripped:
101
+ continue
102
+ parts = stripped.split()
103
+ if len(parts) < 2:
104
+ continue
105
+ name = parts[-1].lstrip("*")
106
+ if name == asset_name:
107
+ return parts[0].lower()
108
+ return None
109
+
110
+
111
+ def _verify_archive(data: bytes, asset_name: str, sums_text: str | None, *, allow_unverified: bool = False) -> None:
112
+ """Check ``data`` against the release's SHA256SUMS; fail closed when it is missing."""
113
+ if sums_text is None:
114
+ if allow_unverified:
115
+ print(
116
+ f"WARNING: no {SUMS_NAME} asset found for {asset_name}; installing unverified "
117
+ f"because {ALLOW_UNVERIFIED_ENV}=1 is set.",
118
+ file=sys.stderr,
119
+ )
120
+ return
121
+ raise RuntimeError(
122
+ f"no {SUMS_NAME} asset found in the release for {asset_name} - refusing to install an "
123
+ f"unverified binary. Set {ALLOW_UNVERIFIED_ENV}=1 to override."
124
+ )
125
+ expected = _expected_digest(sums_text, asset_name)
126
+ if not expected:
127
+ raise RuntimeError(f"no checksum entry for {asset_name} in {SUMS_NAME} - refusing to install unverified binary")
128
+ digest = hashlib.sha256(data).hexdigest().lower()
129
+ if digest != expected:
130
+ raise RuntimeError(f"checksum mismatch for {asset_name} (expected {expected}, got {digest})")
131
+
132
+
133
+ def _fetch_sums(version: str) -> str | None:
134
+ try:
135
+ return _http_get(_asset_url(version, SUMS_NAME)).decode("utf-8")
136
+ except RuntimeError as exc:
137
+ if "HTTP 404" in str(exc):
138
+ return None
139
+ raise
140
+
141
+
142
+ def _is_within(base: Path, target: Path) -> bool:
143
+ """True if `target`'s resolved path stays inside `base`."""
144
+ base_resolved = base.resolve()
145
+ try:
146
+ target.resolve().relative_to(base_resolved)
147
+ except ValueError:
148
+ return False
149
+ return True
150
+
151
+
152
+ def _reject_unsafe_member(name: str) -> None:
153
+ """Reject absolute paths and any `..` component (zip-slip / tar-slip)."""
154
+ normalized = name.replace("\\", "/")
155
+ pure = PurePosixPath(normalized)
156
+ if pure.is_absolute() or normalized.startswith("/"):
157
+ raise RuntimeError(f"refusing absolute path in archive: {name}")
158
+ if len(normalized) >= 2 and normalized[1] == ":":
159
+ raise RuntimeError(f"refusing absolute path in archive: {name}")
160
+ if any(part == ".." for part in pure.parts):
161
+ raise RuntimeError(f"refusing parent-directory escape in archive: {name}")
162
+
163
+
164
+ def _safe_extract(archive_path: Path, asset_name: str, dest: Path) -> None:
165
+ """Extract a tar/zip, validating every member stays within `dest`.
166
+
167
+ Does not rely on extractall() defaults or the 3.12-only ``filter='data'``:
168
+ each member name is rejected up front if it is absolute or contains ``..``,
169
+ and the resolved destination path is re-checked against ``dest``.
170
+ """
171
+ dest = dest.resolve()
172
+ dest.mkdir(parents=True, exist_ok=True)
173
+
174
+ if asset_name.lower().endswith(".zip"):
175
+ with zipfile.ZipFile(archive_path) as zf:
176
+ for entry in zf.namelist():
177
+ _reject_unsafe_member(entry)
178
+ if not _is_within(dest, dest / entry):
179
+ raise RuntimeError(f"refusing archive entry escaping dest: {entry}")
180
+ for entry in zf.namelist():
181
+ zf.extract(entry, dest)
182
+ else:
183
+ with tarfile.open(archive_path, "r:gz") as tf:
184
+ for member in tf.getmembers():
185
+ _reject_unsafe_member(member.name)
186
+ if not _is_within(dest, dest / member.name):
187
+ raise RuntimeError(f"refusing archive entry escaping dest: {member.name}")
188
+ if member.islnk() or member.issym():
189
+ link_target = dest / member.name
190
+ if not _is_within(dest, link_target.parent / member.linkname):
191
+ raise RuntimeError(f"refusing link escaping dest: {member.name}")
192
+ tf.extractall(dest) # noqa: S202 (members validated above)
193
+
194
+
195
+ def _find_binary(root: Path, name: str) -> Path | None:
196
+ for candidate in root.rglob(name):
197
+ if candidate.is_file():
198
+ return candidate
199
+ return None
200
+
201
+
202
+ def _cache_dir(tag: str) -> Path:
203
+ cache = Path.home() / ".cache" / PKG_NAME / tag
204
+ cache.mkdir(parents=True, exist_ok=True, mode=0o700)
205
+ return cache
206
+
207
+
208
+ def ensure_binary() -> str:
209
+ """Ensure the native binary for this package version exists locally, downloading if necessary."""
210
+ override = os.getenv("TS_PACK_BINARY")
211
+ if override:
212
+ return override
213
+
214
+ version = __version__
215
+ cache = _cache_dir(f"v{version}")
216
+ binary_path = cache / _binary_name()
217
+ if binary_path.exists() and os.access(binary_path, os.X_OK):
218
+ return str(binary_path)
219
+
220
+ name = _archive_name(_target_triple())
221
+ print(f"Downloading {BIN_NAME} {version} asset {name}...", file=sys.stderr)
222
+ with tempfile.TemporaryDirectory() as tmpdir:
223
+ tmp = Path(tmpdir)
224
+ data = _http_get(_asset_url(version, name))
225
+ _verify_archive(
226
+ data,
227
+ name,
228
+ _fetch_sums(version),
229
+ allow_unverified=os.getenv(ALLOW_UNVERIFIED_ENV) == "1",
230
+ )
231
+ archive_path = tmp / name
232
+ archive_path.write_bytes(data)
233
+ extract_dir = tmp / "extract"
234
+ extract_dir.mkdir()
235
+ _safe_extract(archive_path, name, extract_dir)
236
+ found = _find_binary(extract_dir, _binary_name())
237
+ if not found:
238
+ raise RuntimeError(f"binary {_binary_name()} not found after extracting {name}")
239
+ shutil.move(str(found), str(binary_path))
240
+
241
+ if platform.system().lower() != "windows":
242
+ binary_path.chmod(0o755)
243
+ print(f"{BIN_NAME} installed.", file=sys.stderr)
244
+ return str(binary_path)
245
+
246
+
247
+ def run(args: list[str]) -> int:
248
+ """Run the native binary with the given args, returning its exit code."""
249
+ binary_path = ensure_binary()
250
+ completed = subprocess.run([binary_path, *args], check=False) # noqa: S603
251
+ return completed.returncode