-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathbuild.rs
More file actions
427 lines (387 loc) · 16.1 KB
/
build.rs
File metadata and controls
427 lines (387 loc) · 16.1 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::io::Read;
use std::path::Path;
use std::time::Duration;
use sha2::Digest;
fn main() {
println!("cargo:rerun-if-env-changed=COPILOT_CLI_VERSION");
println!("cargo:rerun-if-env-changed=BUNDLED_CLI_CACHE_DIR");
println!("cargo::rustc-check-cfg=cfg(has_bundled_cli)");
// The `bundled-cli` cargo feature gates bundling at the build-system level.
// When disabled (e.g. via `default-features = false`), runtime archive
// helpers (tar/flate2/zip) are not in the graph and no download happens.
if std::env::var_os("CARGO_FEATURE_BUNDLED_CLI").is_none() {
return;
}
println!("cargo:rerun-if-changed=bundled_cli_version.txt");
println!("cargo:rerun-if-changed=../nodejs/package-lock.json");
let Some(platform) = target_platform() else {
println!("cargo:warning=Unsupported target platform for Copilot CLI bundling — skipping");
return;
};
let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR is always set by cargo");
let out = Path::new(&out_dir);
// Resolve version + per-asset SHA-256 from one of three sources, in order:
// 1. `COPILOT_CLI_VERSION` env-var override (live SHA256SUMS.txt fetch)
// 2. `bundled_cli_version.txt` snapshot at the crate root (published-crate
// consumer; generated by the publish workflow)
// 3. Sibling `../nodejs/package-lock.json` (mono-repo contributor build;
// live SHA256SUMS.txt fetch)
let (version, expected_hash) = resolve_version_and_hash(platform.asset_name);
let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}");
let cache_dir = std::env::var("BUNDLED_CLI_CACHE_DIR")
.ok()
.map(std::path::PathBuf::from);
let asset_name = platform.asset_name;
// Versioned cache key since copilot asset names don't include the version.
let cache_key = format!("v{version}-{asset_name}");
// Download the archive (or read from cache) and verify SHA-256. The raw
// archive is what gets embedded — extraction happens at runtime. Quiet on
// cache hit; logs `Downloading` + `Caching archive at` on cache miss.
let archive = cached_download(
&format!("{base_url}/{asset_name}"),
&cache_key,
&expected_hash,
&cache_dir,
);
// Sanity check: the runtime extraction path expects `binary_name` inside
// the archive. Fail the build now (with a clear message) rather than
// shipping a broken bundle if the upstream archive layout ever changes.
verify_binary_present_in_archive(&archive, platform.binary_name, asset_name);
std::fs::write(out.join("copilot_cli.archive"), &archive)
.expect("failed to write copilot_cli.archive");
let generated = format!(
r#"// Auto-generated by github-copilot-sdk build.rs. Do not edit.
pub(super) static CLI_ARCHIVE: &[u8] = include_bytes!("copilot_cli.archive");
pub(super) static CLI_VERSION: &str = "{version}";
pub(super) static CLI_BINARY_NAME: &str = "{binary_name}";
"#,
binary_name = platform.binary_name,
);
std::fs::write(out.join("bundled_cli.rs"), generated).expect("failed to write bundled_cli.rs");
println!("cargo:rustc-cfg=has_bundled_cli");
}
/// Resolve the CLI version and the expected SHA-256 hash for the current
/// target's archive. Picks one of three sources in order. Panics with a clear
/// error if none are available.
fn resolve_version_and_hash(asset_name: &str) -> (String, String) {
// 1. Env-var override — fetches live SHA256SUMS for the overridden version.
if let Ok(version) = std::env::var("COPILOT_CLI_VERSION") {
let hash = fetch_live_sha256(&version, asset_name);
return (version, hash);
}
// 2. Snapshot file at the crate root (published-crate consumer).
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set");
let snapshot = Path::new(&manifest_dir).join("bundled_cli_version.txt");
if snapshot.is_file() {
let contents = std::fs::read_to_string(&snapshot)
.unwrap_or_else(|e| panic!("failed to read {}: {e}", snapshot.display()));
return parse_snapshot(&contents, asset_name)
.unwrap_or_else(|e| panic!("invalid {}: {e}", snapshot.display()));
}
// 3. Mono-repo lockfile — read version, fetch live SHA256SUMS.
let lockfile = Path::new(&manifest_dir)
.join("..")
.join("nodejs")
.join("package-lock.json");
if lockfile.is_file() {
let version = read_version_from_package_lock(&lockfile);
let hash = fetch_live_sha256(&version, asset_name);
return (version, hash);
}
panic!(
"Could not resolve the Copilot CLI version to bundle.\n\
Tried:\n\
- COPILOT_CLI_VERSION env var (unset)\n\
- {} (missing)\n\
- {} (missing)\n\
To opt out of bundling, set `default-features = false` on the github-copilot-sdk dependency.",
snapshot.display(),
lockfile.display(),
);
}
/// Parse the `bundled_cli_version.txt` snapshot file. Format is one
/// `key=value` per line. The first line is `version=X.Y.Z`; subsequent lines
/// map asset filename to hex SHA-256. Blank lines and lines starting with `#`
/// are skipped.
fn parse_snapshot(contents: &str, asset_name: &str) -> Result<(String, String), String> {
let mut version: Option<String> = None;
let mut hash: Option<String> = None;
for (line_no, raw) in contents.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (key, value) = line
.split_once('=')
.ok_or_else(|| format!("line {}: expected `key=value`, got `{raw}`", line_no + 1))?;
match key.trim() {
"version" => version = Some(value.trim().to_string()),
k if k == asset_name => hash = Some(value.trim().to_string()),
_ => {}
}
}
let version = version.ok_or("missing `version=` line")?;
let hash = hash.ok_or_else(|| format!("missing hash for asset `{asset_name}`"))?;
Ok((version, hash))
}
/// Read the `@github/copilot` version from `nodejs/package-lock.json`.
fn read_version_from_package_lock(path: &Path) -> String {
let contents = std::fs::read_to_string(path)
.unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()));
// Minimal JSON walk: find `"node_modules/@github/copilot"` object and
// its `"version"` field. Full JSON parsing keeps build.rs dep-light by
// using a regex; the file is generated by npm and we're matching an
// exact key path.
let key = "\"node_modules/@github/copilot\"";
let key_pos = contents
.find(key)
.unwrap_or_else(|| panic!("{} does not contain {key}", path.display()));
let after_key = &contents[key_pos + key.len()..];
let version_key = "\"version\"";
let v_pos = after_key
.find(version_key)
.unwrap_or_else(|| panic!("no `version` field found near {key} in {}", path.display()));
let after_v = &after_key[v_pos + version_key.len()..];
let q1 = after_v.find('"').expect("malformed version");
let after_q1 = &after_v[q1 + 1..];
let q2 = after_q1.find('"').expect("malformed version");
after_q1[..q2].to_string()
}
/// Fetch the live `SHA256SUMS.txt` for the given version from GitHub Releases
/// and pluck out the entry for `asset_name`.
fn fetch_live_sha256(version: &str, asset_name: &str) -> String {
let base_url = format!("https://github.com/github/copilot-cli/releases/download/v{version}");
let checksums_url = format!("{base_url}/SHA256SUMS.txt");
let checksums = download_with_retry(&checksums_url);
let checksums_text =
std::str::from_utf8(&checksums).expect("checksums file is not valid UTF-8");
find_sha256_for_asset(checksums_text, asset_name)
}
struct Platform {
asset_name: &'static str,
binary_name: &'static str,
}
fn target_platform() -> Option<Platform> {
let os = std::env::var("CARGO_CFG_TARGET_OS").ok()?;
let arch = std::env::var("CARGO_CFG_TARGET_ARCH").ok()?;
match (os.as_str(), arch.as_str()) {
("macos", "aarch64") => Some(Platform {
asset_name: "copilot-darwin-arm64.tar.gz",
binary_name: "copilot",
}),
("macos", "x86_64") => Some(Platform {
asset_name: "copilot-darwin-x64.tar.gz",
binary_name: "copilot",
}),
("linux", "x86_64") => Some(Platform {
asset_name: "copilot-linux-x64.tar.gz",
binary_name: "copilot",
}),
("linux", "aarch64") => Some(Platform {
asset_name: "copilot-linux-arm64.tar.gz",
binary_name: "copilot",
}),
("windows", "x86_64") => Some(Platform {
asset_name: "copilot-win32-x64.zip",
binary_name: "copilot.exe",
}),
("windows", "aarch64") => Some(Platform {
asset_name: "copilot-win32-arm64.zip",
binary_name: "copilot.exe",
}),
_ => None,
}
}
/// Read a file from the download cache, or download it (with retries) and save
/// to cache. Verifies SHA-256 on every path. Evicts stale/corrupt cache entries
/// automatically. Cache I/O failures are treated as cache misses — they never
/// break the build.
fn cached_download(
url: &str,
cache_key: &str,
expected_hash: &str,
cache_dir: &Option<std::path::PathBuf>,
) -> Vec<u8> {
if let Some(dir) = cache_dir {
let cached_path = dir.join(cache_key);
if cached_path.is_file() {
match std::fs::read(&cached_path) {
Ok(data) if hex_sha256(&data) == expected_hash => {
// Silent cache hit — nothing to surface.
return data;
}
Ok(_) => {
println!("cargo:warning=Cached archive hash mismatch, re-downloading");
let _ = std::fs::remove_file(&cached_path);
}
Err(e) => {
println!(
"cargo:warning=Failed to read cache {}, re-downloading: {e}",
cached_path.display()
);
}
}
}
}
println!("cargo:warning=Downloading {url}");
let data = download_with_retry(url);
let actual_hash = hex_sha256(&data);
if actual_hash != expected_hash {
panic!(
"Archive integrity check failed for {url}!\n expected: {expected_hash}\n actual: {actual_hash}\n \
This could indicate a corrupted download or a supply-chain attack."
);
}
if let Some(dir) = cache_dir {
if let Err(e) = std::fs::create_dir_all(dir) {
println!(
"cargo:warning=Failed to create cache directory {}: {e}",
dir.display()
);
} else {
let cached_path = dir.join(cache_key);
println!("cargo:warning=Caching archive at {}", cached_path.display());
if let Err(e) = std::fs::write(&cached_path, &data) {
println!(
"cargo:warning=Failed to write cache file {}: {e}",
cached_path.display()
);
}
}
}
data
}
/// Maximum number of HTTP attempts (one initial + this many retries on transient errors).
const MAX_RETRIES: u32 = 3;
/// Download `url` with bounded retries on transient network errors. Backoff is
/// exponential starting at 1s. 4xx responses fail fast; 5xx and connect/read
/// errors are retried.
fn download_with_retry(url: &str) -> Vec<u8> {
let mut attempt = 0u32;
loop {
attempt += 1;
match try_download(url) {
Ok(bytes) => return bytes,
Err(err) if err.transient && attempt <= MAX_RETRIES => {
let backoff = Duration::from_secs(1u64 << (attempt - 1));
println!(
"cargo:warning=Transient download failure for {url} (attempt {attempt}/{}): {} — retrying in {}s",
MAX_RETRIES + 1,
err.message,
backoff.as_secs(),
);
std::thread::sleep(backoff);
}
Err(err) => panic!("Failed to download {url}: {}", err.message),
}
}
}
struct DownloadError {
message: String,
transient: bool,
}
fn try_download(url: &str) -> Result<Vec<u8>, DownloadError> {
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(30))
.timeout_read(Duration::from_secs(120))
.build();
match agent.get(url).call() {
Ok(response) => {
let mut bytes = Vec::new();
response
.into_reader()
.read_to_end(&mut bytes)
.map_err(|e| DownloadError {
message: format!("read error: {e}"),
transient: true,
})?;
Ok(bytes)
}
// 5xx — server-side, treat as transient.
Err(ureq::Error::Status(code, response)) if (500..600).contains(&code) => {
Err(DownloadError {
message: format!("HTTP {code} {}", response.status_text()),
transient: true,
})
}
// 4xx — client-side, fail fast.
Err(ureq::Error::Status(code, response)) => Err(DownloadError {
message: format!("HTTP {code} {}", response.status_text()),
transient: false,
}),
// Transport-layer (DNS, connect, TLS, read timeout) — treat as transient.
Err(ureq::Error::Transport(t)) => Err(DownloadError {
message: format!("transport error: {t}"),
transient: true,
}),
}
}
fn find_sha256_for_asset(sums: &str, asset_name: &str) -> String {
for line in sums.lines() {
// Format: "<hash> <filename>" (two spaces)
if let Some((hash, name)) = line.split_once(" ")
&& name.trim() == asset_name
{
return hash.trim().to_string();
}
}
panic!("SHA256SUMS.txt does not contain an entry for {asset_name}");
}
fn sha256(data: &[u8]) -> [u8; 32] {
let mut hasher = sha2::Sha256::new();
hasher.update(data);
hasher.finalize().into()
}
/// Walks the downloaded archive at build time to confirm an entry matching
/// `binary_name` exists. Panics with a clear message if not — defends against
/// silent breakage if the upstream archive layout ever changes.
fn verify_binary_present_in_archive(archive: &[u8], binary_name: &str, asset_name: &str) {
let found = if asset_name.ends_with(".zip") {
archive_contains_zip_entry(archive, binary_name)
} else {
archive_contains_tar_entry(archive, binary_name)
};
if !found {
panic!(
"Copilot CLI archive `{asset_name}` does not contain an entry named `{binary_name}`. \
The upstream archive layout may have changed; runtime extraction would fail. \
Update `verify_binary_present_in_archive` in build.rs and the matching `extract_binary` in src/embeddedcli.rs."
);
}
}
fn archive_contains_tar_entry(targz: &[u8], binary_name: &str) -> bool {
let gz = flate2::read::GzDecoder::new(targz);
let mut archive = tar::Archive::new(gz);
let Ok(entries) = archive.entries() else {
return false;
};
for entry in entries.flatten() {
let Ok(path) = entry.path() else {
continue;
};
let name = path.to_string_lossy();
if name == binary_name || name.ends_with(&format!("/{binary_name}")) {
return true;
}
}
false
}
fn archive_contains_zip_entry(zip_bytes: &[u8], binary_name: &str) -> bool {
let cursor = std::io::Cursor::new(zip_bytes);
let Ok(mut archive) = zip::ZipArchive::new(cursor) else {
return false;
};
for i in 0..archive.len() {
let Ok(entry) = archive.by_index(i) else {
continue;
};
let name = entry.name();
if name == binary_name || name.ends_with(&format!("/{binary_name}")) {
return true;
}
}
false
}
fn hex_sha256(data: &[u8]) -> String {
sha256(data).iter().map(|b| format!("{b:02x}")).collect()
}