-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathbuild-wheels.mjs
More file actions
373 lines (303 loc) · 11.8 KB
/
build-wheels.mjs
File metadata and controls
373 lines (303 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env node
/**
* Build platform-specific Python wheels with bundled Copilot CLI binaries.
*
* Downloads the Copilot CLI binary for each platform from the npm registry
* and builds a wheel that includes it.
*
* Usage:
* node scripts/build-wheels.mjs [--platform PLATFORM] [--output-dir DIR]
*
* --platform: Build for specific platform only (linux-x64, linux-arm64, darwin-x64,
* darwin-arm64, win32-x64, win32-arm64). If not specified, builds all.
* --output-dir: Directory for output wheels (default: dist/)
*/
import { execSync } from "node:child_process";
import {
createWriteStream,
existsSync,
mkdirSync,
readFileSync,
writeFileSync,
chmodSync,
rmSync,
cpSync,
readdirSync,
statSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pythonDir = dirname(__dirname);
const repoRoot = dirname(pythonDir);
// Platform mappings: npm package suffix -> [wheel platform tag, binary name]
// Based on Node 24.11 binaries being included in the wheels
const PLATFORMS = {
"linux-x64": ["manylinux_2_28_x86_64", "copilot"],
"linux-arm64": ["manylinux_2_28_aarch64", "copilot"],
"darwin-x64": ["macosx_10_9_x86_64", "copilot"],
"darwin-arm64": ["macosx_11_0_arm64", "copilot"],
"win32-x64": ["win_amd64", "copilot.exe"],
"win32-arm64": ["win_arm64", "copilot.exe"],
};
function getCliVersion() {
const packageLockPath = join(repoRoot, "nodejs", "package-lock.json");
if (!existsSync(packageLockPath)) {
throw new Error(
`package-lock.json not found at ${packageLockPath}. Run 'npm install' in nodejs/ first.`
);
}
const packageLock = JSON.parse(readFileSync(packageLockPath, "utf-8"));
const version = packageLock.packages?.["node_modules/@github/copilot"]?.version;
if (!version) {
throw new Error("Could not find @github/copilot version in package-lock.json");
}
return version;
}
function getPkgVersion() {
const pyprojectPath = join(pythonDir, "pyproject.toml");
const content = readFileSync(pyprojectPath, "utf-8");
const match = content.match(/version\s*=\s*"([^"]+)"/);
if (!match) {
throw new Error("Could not find version in pyproject.toml");
}
return match[1];
}
async function downloadCliBinary(platform, cliVersion, cacheDir) {
const [, binaryName] = PLATFORMS[platform];
const cachedBinary = join(cacheDir, binaryName);
// Check cache
if (existsSync(cachedBinary)) {
console.log(` Using cached ${binaryName}`);
return cachedBinary;
}
const tarballUrl = `https://registry.npmjs.org/@github/copilot-${platform}/-/copilot-${platform}-${cliVersion}.tgz`;
console.log(` Downloading from ${tarballUrl}...`);
// Download tarball
const response = await fetch(tarballUrl);
if (!response.ok) {
throw new Error(`Failed to download: ${response.status} ${response.statusText}`);
}
// Extract to cache dir
mkdirSync(cacheDir, { recursive: true });
const tarballPath = join(cacheDir, `copilot-${platform}-${cliVersion}.tgz`);
const fileStream = createWriteStream(tarballPath);
await pipeline(response.body, fileStream);
// Extract binary from tarball using system tar
// On Windows, use the system32 tar to avoid Git Bash tar issues
const tarCmd = process.platform === "win32"
? `"${process.env.SystemRoot}\\System32\\tar.exe"`
: "tar";
try {
execSync(`${tarCmd} -xzf "${tarballPath}" -C "${cacheDir}" --strip-components=1 "package/${binaryName}"`, {
stdio: "inherit",
});
} catch (e) {
// Clean up on failure
if (existsSync(tarballPath)) {
rmSync(tarballPath);
}
throw new Error(`Failed to extract binary: ${e.message}`);
}
// Clean up tarball
rmSync(tarballPath);
// Verify binary exists
if (!existsSync(cachedBinary)) {
throw new Error(`Binary not found after extraction: ${cachedBinary}`);
}
// Make executable on Unix
if (!binaryName.endsWith(".exe")) {
chmodSync(cachedBinary, 0o755);
}
const size = statSync(cachedBinary).size / 1024 / 1024;
console.log(` Downloaded ${binaryName} (${size.toFixed(1)} MB)`);
return cachedBinary;
}
function getCliLicensePath() {
// Use license from node_modules (requires npm ci in nodejs/ first)
const licensePath = join(repoRoot, "nodejs", "node_modules", "@github", "copilot", "LICENSE.md");
if (!existsSync(licensePath)) {
throw new Error(
`CLI LICENSE.md not found at ${licensePath}. Run 'npm ci' in nodejs/ first.`
);
}
return licensePath;
}
async function buildWheel(platform, pkgVersion, cliVersion, outputDir, licensePath) {
const [wheelTag, binaryName] = PLATFORMS[platform];
console.log(`\nBuilding wheel for ${platform}...`);
// Cache directory includes version
const cacheDir = join(pythonDir, ".cli-cache", cliVersion, platform);
// Download/get cached binary
const binaryPath = await downloadCliBinary(platform, cliVersion, cacheDir);
// Create temp build directory
const buildDir = join(pythonDir, ".build-temp", platform);
if (existsSync(buildDir)) {
rmSync(buildDir, { recursive: true });
}
mkdirSync(buildDir, { recursive: true });
// Copy package source
const pkgDir = join(buildDir, "copilot");
cpSync(join(pythonDir, "copilot"), pkgDir, { recursive: true });
// Create bin directory and copy binary
const binDir = join(pkgDir, "bin");
mkdirSync(binDir, { recursive: true });
cpSync(binaryPath, join(binDir, binaryName));
// Create VERSION file
writeFileSync(join(binDir, "VERSION"), cliVersion);
// Create __init__.py
writeFileSync(join(binDir, "__init__.py"), '"""Bundled Copilot CLI binary."""\n');
// Copy and modify pyproject.toml for bundled CLI wheel
let pyprojectContent = readFileSync(join(pythonDir, "pyproject.toml"), "utf-8");
// Update SPDX expression and add license-files for both SDK and bundled CLI licenses
pyprojectContent = pyprojectContent.replace(
'license = "MIT"',
'license = "MIT AND LicenseRef-Copilot-CLI"\nlicense-files = ["LICENSE", "CLI-LICENSE.md"]'
);
// Add package-data configuration
const packageDataConfig = `
[tool.setuptools.package-data]
"copilot.bin" = ["*"]
`;
pyprojectContent = pyprojectContent.replace("\n[tool.ruff]", `${packageDataConfig}\n[tool.ruff]`);
writeFileSync(join(buildDir, "pyproject.toml"), pyprojectContent);
// Copy README
if (existsSync(join(pythonDir, "README.md"))) {
cpSync(join(pythonDir, "README.md"), join(buildDir, "README.md"));
}
// Copy SDK LICENSE
cpSync(join(repoRoot, "LICENSE"), join(buildDir, "LICENSE"));
// Copy CLI LICENSE
cpSync(licensePath, join(buildDir, "CLI-LICENSE.md"));
// Build wheel using uv (faster and doesn't require build package to be installed)
const distDir = join(buildDir, "dist");
execSync("uv build --wheel", {
cwd: buildDir,
stdio: "inherit",
});
// Find built wheel
const wheels = readdirSync(distDir).filter((f) => f.endsWith(".whl"));
if (wheels.length === 0) {
throw new Error("No wheel found after build");
}
const srcWheel = join(distDir, wheels[0]);
const newName = wheels[0].replace("-py3-none-any.whl", `-py3-none-${wheelTag}.whl`);
const destWheel = join(outputDir, newName);
// Repack wheel with correct platform tag
await repackWheelWithPlatform(srcWheel, destWheel, wheelTag);
// Clean up build dir
rmSync(buildDir, { recursive: true });
const size = statSync(destWheel).size / 1024 / 1024;
console.log(` Built ${newName} (${size.toFixed(1)} MB)`);
return destWheel;
}
async function repackWheelWithPlatform(srcWheel, destWheel, platformTag) {
// Write Python script to temp file to avoid shell escaping issues
const script = `
import sys
import zipfile
import tempfile
from pathlib import Path
src_wheel = Path(sys.argv[1])
dest_wheel = Path(sys.argv[2])
platform_tag = sys.argv[3]
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
# Extract wheel
with zipfile.ZipFile(src_wheel, 'r') as zf:
zf.extractall(tmpdir)
# Restore executable bit on the CLI binary (setuptools strips it)
for bin_path in (tmpdir / 'copilot' / 'bin').iterdir():
if bin_path.name in ('copilot', 'copilot.exe'):
bin_path.chmod(0o755)
# Find and update WHEEL file
wheel_info_dirs = list(tmpdir.glob('*.dist-info'))
if not wheel_info_dirs:
raise RuntimeError('No .dist-info directory found in wheel')
wheel_info_dir = wheel_info_dirs[0]
wheel_file = wheel_info_dir / 'WHEEL'
with open(wheel_file) as f:
wheel_content = f.read()
wheel_content = wheel_content.replace('Tag: py3-none-any', f'Tag: py3-none-{platform_tag}')
with open(wheel_file, 'w') as f:
f.write(wheel_content)
# Regenerate RECORD file
record_file = wheel_info_dir / 'RECORD'
records = []
for path in tmpdir.rglob('*'):
if path.is_file() and path.name != 'RECORD':
rel_path = path.relative_to(tmpdir)
records.append(f'{rel_path},,')
records.append(f'{wheel_info_dir.name}/RECORD,,')
with open(record_file, 'w') as f:
f.write('\\n'.join(records))
# Create new wheel
dest_wheel.parent.mkdir(parents=True, exist_ok=True)
if dest_wheel.exists():
dest_wheel.unlink()
with zipfile.ZipFile(dest_wheel, 'w', zipfile.ZIP_DEFLATED) as zf:
for path in tmpdir.rglob('*'):
if path.is_file():
zf.write(path, path.relative_to(tmpdir))
`;
// Write script to temp file
const scriptPath = join(pythonDir, ".build-temp", "repack_wheel.py");
mkdirSync(dirname(scriptPath), { recursive: true });
writeFileSync(scriptPath, script);
try {
execSync(`python "${scriptPath}" "${srcWheel}" "${destWheel}" "${platformTag}"`, {
stdio: "inherit",
});
} finally {
// Clean up script
rmSync(scriptPath);
}
}
async function main() {
const args = process.argv.slice(2);
let platform = null;
let outputDir = join(pythonDir, "dist");
// Parse args
for (let i = 0; i < args.length; i++) {
if (args[i] === "--platform" && args[i + 1]) {
platform = args[++i];
if (!PLATFORMS[platform]) {
console.error(`Invalid platform: ${platform}`);
console.error(`Valid platforms: ${Object.keys(PLATFORMS).join(", ")}`);
process.exit(1);
}
} else if (args[i] === "--output-dir" && args[i + 1]) {
outputDir = args[++i];
}
}
const cliVersion = getCliVersion();
const pkgVersion = getPkgVersion();
console.log(`CLI version: ${cliVersion}`);
console.log(`Package version: ${pkgVersion}`);
mkdirSync(outputDir, { recursive: true });
// Get CLI license from node_modules
const licensePath = getCliLicensePath();
const platforms = platform ? [platform] : Object.keys(PLATFORMS);
const wheels = [];
for (const p of platforms) {
try {
const wheel = await buildWheel(p, pkgVersion, cliVersion, outputDir, licensePath);
wheels.push(wheel);
} catch (e) {
console.error(`Error building wheel for ${p}:`, e.message);
if (platform) {
process.exit(1);
}
}
}
console.log(`\nBuilt ${wheels.length} wheel(s):`);
for (const wheel of wheels) {
console.log(` ${wheel}`);
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});