Visual Studio Code, rebuilt in Rust
Rust
#!/usr/bin/env bun
// Packages VSRustium.app (milestone 19): the release binary and bun in Contents/MacOS; product.json and the
// app files (port/tools/app-files.ts) in Contents/Resources/app;
// Info.plist with the reference's document types and the vsrustium URL protocol; then codesign with the hardened
// runtime and `spctl -a`. Run on the Studio after a release build and port/tools/build-exthost:
// port/tools/studio 'port/tools/package-app' env IDENTITY="Developer ID Application: ..." (default ad-hoc "-";
// a Developer ID signs in the GUI session), NOTARIZE=1 (notarize and staple), VSCODE_GPUI_EXTENSIONS (default the reference's extensions), OUT (default native/target/VSRustium.app),
// VERSION (default the VS Code tree's), PRERELEASE=1 (a pre-release: quality insider, version <VERSION>-insider; else quality stable), TAG (the GitHub release tag, default v<display version>, app-files.ts displayVersion),
// PRODUCT (a JSON object merged into product.json, for tests: '{"updateUrl": "http://127.0.0.1:8080"}'),
// ARCH (arm64 or x64, default the host's; for another arch first `cargo gc build --release -p app --target <triple>`)
// Next to the app it writes the update zip and the feed entries of port/notes.md "Update feed", per platform and arch:
// VSRustium-<display version>-darwin-<arch>.zip and darwin-<arch>-prerelease.json, and darwin-<arch>.json unless PRERELEASE=1.
import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { buildProduct, copyAppFiles, displayVersion, rebuildNativeModule, writeFeedEntries } from './app-files.ts';
import { vscodeSrc } from './vscode-src.ts';
const root = process.cwd();
const ref = process.env.REF ?? join(process.env.HOME!, 'Developer/vscode-ref-1.148.0');
const extensionsDir = process.env.VSCODE_GPUI_EXTENSIONS ?? join(ref, 'extensions');
const out = process.env.OUT ?? join(root, 'native/target/VSRustium.app');
const identity = process.env.IDENTITY ?? '-';
// VS Code's target platform names (darwin-arm64, darwin-x64), as gallery.rs CURRENT_TARGET_PLATFORM and the update feeds.
const platform = process.platform;
const hostArch = process.arch === 'arm64' ? 'arm64' : 'x64';
const arch = process.env.ARCH ?? hostArch;
if (arch !== 'arm64' && arch !== 'x64') {
throw new Error(`ARCH must be arm64 or x64, not ${arch}`);
}
const rustTarget = arch === 'x64' ? 'x86_64-apple-darwin' : 'aarch64-apple-darwin';
const machOArch = arch === 'x64' ? 'x86_64' : 'arm64';
// A stale bundle ships extension host code without the current patches (a mirror's out-exthost from an older sync).
// shortcut: compares with the port's inputs only, not the VS Code tree's src, which is pinned to the release tag.
const bundleTime = statSync('out-exthost/bootstrap-exthost.js').mtimeMs;
const exthostInputs = ['port/tools/build-exthost', 'port/product.json', ...new Bun.Glob('port/patches/src-*.patch').scanSync()];
const newerInputs = exthostInputs.filter(input => statSync(input).mtimeMs > bundleTime);
if (newerInputs.length) {
throw new Error(`out-exthost is older than ${newerInputs.join(', ')}: run port/tools/build-exthost`);
}
const product = await buildProduct();
const version = product.version;
rmSync(out, { recursive: true, force: true });
const contents = join(out, 'Contents');
const app = join(contents, 'Resources/app');
mkdirSync(join(contents, 'MacOS'), { recursive: true });
mkdirSync(app, { recursive: true });
cpSync(arch === hostArch ? 'native/target/release/vsrustium' : `native/target/${rustTarget}/release/vsrustium`, join(contents, 'MacOS/vsrustium'));
cpSync(arch === hostArch ? realpathSync(Bun.which('bun')!) : await downloadBun(), join(contents, 'MacOS/bun'));
// gulpfile.vscode.ts: the shell command's script, with the app binary for Electron's (cli.rs takes the CLI part).
const shellCommand = readFileSync(join(vscodeSrc, 'resources/darwin/bin/code.sh'), 'utf8').replaceAll('@@APPNAME@@', product.applicationName).replaceAll('@@NAME@@', 'vsrustium');
mkdirSync(join(app, 'bin'));
writeFileSync(join(app, 'bin/code'), shellCommand, { mode: 0o755 });
writeFileSync(join(app, 'product.json'), JSON.stringify(product, null, '\t'));
// codesign --strict refuses a bundle with a dangling link: copyAppFiles removes them.
const copiedEntries = await copyAppFiles(app, extensionsDir, platform, arch);
const machO = [];
for (const line of (await Bun.$`find ${contents} -type f -print0 | xargs -0 file -F ${'\t'}`.text()).split('\n')) {
const [file, kind] = line.split('\t');
if (kind?.trim().startsWith('Mach-O')) {
machO.push(file);
}
}
// The packages' native modules were built for the host by pnpm install: another arch's are rebuilt from their source.
for (const file of machO.filter(file => file.endsWith('.node'))) {
if ((await Bun.$`lipo -archs ${file}`.text()).trim() !== machOArch) {
await rebuildNativeModule(file, app, copiedEntries, [`--arch=${arch}`]);
// kerberos's binding.gyp builds x86_64 and arm64 on an arm64 host.
if ((await Bun.$`lipo -archs ${file}`.text()).trim() !== machOArch) {
await Bun.$`lipo ${file} -thin ${machOArch} -output ${file}`;
}
}
}
const wrongArch = [];
for (const file of machO) {
const archs = (await Bun.$`lipo -archs ${file}`.text()).trim();
if (archs !== machOArch) {
wrongArch.push(`${relative(out, file)} (${archs})`);
}
}
if (wrongArch.length) {
throw new Error(`not ${machOArch}: ${wrongArch.join(', ')}`);
}
// Info.plist: the reference build's document types (build/lib/electron.ts), the port's names and URL protocol.
const reference = JSON.parse(await Bun.$`plutil -convert json -o - ${join(ref, '.build/electron/Code - OSS.app/Contents/Info.plist')}`.text());
const plist = {
CFBundleDevelopmentRegion: 'en',
CFBundleDisplayName: product.nameLong,
CFBundleName: product.nameShort,
CFBundleExecutable: 'vsrustium',
CFBundleIconFile: 'AppIcon',
CFBundleIconName: 'AppIcon',
CFBundleIdentifier: product.darwinBundleIdentifier,
CFBundleInfoDictionaryVersion: '6.0',
CFBundlePackageType: 'APPL',
CFBundleShortVersionString: version,
CFBundleVersion: version,
CFBundleDocumentTypes: reference.CFBundleDocumentTypes,
CFBundleURLTypes: [{ CFBundleTypeRole: 'Viewer', CFBundleURLName: product.nameLong, CFBundleURLSchemes: [product.urlProtocol] }],
LSApplicationCategoryType: 'public.app-category.developer-tools',
// libghostty-vt builds for macOS 13.0 at the least: Ghostty's Config.zig forces it on a macOS host.
LSMinimumSystemVersion: '13.0',
NSHighResolutionCapable: true,
NSSupportsAutomaticGraphicsSwitching: true,
NSPrincipalClass: 'NSApplication',
NSHumanReadableCopyright: 'Copyright (C) VSRustium contributors and Microsoft Corporation. Apache License 2.0, portions MIT License.',
};
writeFileSync(join(contents, 'Info.plist.json'), JSON.stringify(plist));
await Bun.$`plutil -convert xml1 -o ${join(contents, 'Info.plist')} ${join(contents, 'Info.plist.json')}`;
rmSync(join(contents, 'Info.plist.json'));
writeFileSync(join(contents, 'PkgInfo'), 'APPL????');
// actool writes Assets.car (the Liquid Glass icon in every appearance) and AppIcon.icns (macOS 15 and older); it
// exits 0 without writing either when the .icon folder is not named AppIcon.icon, and fails on a relative path.
await Bun.$`xcrun actool ${join(root, 'port/AppIcon.icon')} --compile ${join(contents, 'Resources')} --platform macosx --minimum-deployment-target ${plist.LSMinimumSystemVersion} --app-icon AppIcon --output-partial-info-plist /dev/null --errors`;
if (!existsSync(join(contents, 'Resources/Assets.car')) || !existsSync(join(contents, 'Resources/AppIcon.icns'))) {
throw new Error('actool wrote no app icon');
}
for (const icon of new Set<string>(reference.CFBundleDocumentTypes.map((type: { CFBundleTypeIconFile: string }) => type.CFBundleTypeIconFile))) {
cpSync(join(vscodeSrc, 'resources/darwin', icon), join(contents, 'Resources', icon));
}
// Every Mach-O inside is signed first (native modules, ripgrep, bun), then the app; bun needs JIT and the
// executable memory of JavaScriptCore, and loads native modules signed by others.
const entitlements = join(contents, '..', '..', 'vsrustium.entitlements');
writeFileSync(entitlements, `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.security.cs.allow-jit</key><true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>
<key>com.apple.security.cs.disable-library-validation</key><true/>
</dict></plist>
`);
const binaries = machO.filter(file => file.startsWith(app));
const timestamp = identity === '-' ? '--timestamp=none' : '--timestamp';
// The Developer ID key sits in the login keychain, which stays locked in an ssh session (errSecInternalComponent):
// signing with it runs as a script opened in the GUI session.
const keychain = identity === '-' ? '' : `--keychain ${shellQuote(join(process.env.HOME!, 'Library/Keychains/login.keychain-db'))}`;
const sign = (paths: string[], withEntitlements: boolean) =>
`codesign --force ${timestamp} --options runtime ${keychain} --sign ${shellQuote(identity)} ${withEntitlements ? `--entitlements ${shellQuote(entitlements)}` : ''} ${paths.map(shellQuote).join(' ')}`;
const commands = [...(binaries.length ? [sign(binaries, false)] : []), sign([join(contents, 'MacOS/bun')], true), sign([out], true)];
const signed = identity === '-' ? await Bun.$`bash -ec ${commands.join('\n')}`.nothrow() : await inGuiSession('sign', commands);
rmSync(entitlements);
if (signed.exitCode !== 0) {
console.log(`codesign failed: ${signed.stderr.toString().trim()}`);
process.exit(1);
}
// NOTARIZE=1 submits the signed app with the notarytool profile vsrustium-notary (stored once by Artur in the
// Studio's login keychain: xcrun notarytool store-credentials vsrustium-notary --apple-id <id> --team-id N529W98U62)
// and staples the ticket.
if (process.env.NOTARIZE === '1') {
const zip = `${out}.zip`;
const notarized = await inGuiSession('notarize', [
`ditto -c -k --keepParent ${shellQuote(out)} ${shellQuote(zip)}`,
`xcrun notarytool submit ${shellQuote(zip)} --keychain-profile vsrustium-notary --wait`,
`xcrun stapler staple ${shellQuote(out)}`,
]);
rmSync(zip, { force: true });
console.log(`notarization: exit ${notarized.exitCode}\n${notarized.stderr.toString().trim()}`);
if (notarized.exitCode !== 0) {
process.exit(1);
}
}
const verify = await Bun.$`codesign --verify --deep --strict --verbose=2 ${out}`.nothrow();
console.log(`${out}: ${binaries.length + 2} signatures as ${identity}, codesign --verify ${verify.exitCode === 0 ? 'ok' : 'failed'}`);
console.log(verify.stderr.toString().trim());
if (verify.exitCode === 0) {
const zip = join(dirname(out), `VSRustium-${displayVersion(product)}-${platform}-${arch}.zip`);
rmSync(zip, { force: true });
// Without --norsrc --noextattr ditto stores each file's xattrs as `._` files inside the app; unzippers other than
// Archive Utility write them out and break the seal: "VSRustium is damaged" (issue 29).
await Bun.$`ditto -c -k --norsrc --noextattr --keepParent ${out} ${zip}`;
if ((await Bun.$`zipinfo -1 ${zip}`.text()).split('\n').some((entry) => entry.split('/').at(-1)!.startsWith('._'))) {
throw new Error(`${zip} holds AppleDouble ._ files`);
}
await writeFeedEntries(zip, product, platform, arch);
}
const size = (await Bun.$`du -sh ${out}`.text()).split('\t')[0];
console.log(`size ${size}`);
// With Gatekeeper assessments disabled (`spctl --master-disable`) spctl accepts any bundle: the check cannot fail.
const status = (await Bun.$`spctl --status`.nothrow().text()).trim();
if (status !== 'assessments enabled') {
console.log(`spctl -a: not assessed, Gatekeeper reports "${status}"`);
process.exit(verify.exitCode || 3);
}
const assessment = await Bun.$`spctl -a -vv ${out}`.nothrow();
console.log(`spctl -a: exit ${assessment.exitCode}: ${assessment.stderr.toString().trim()}`);
process.exit(verify.exitCode || assessment.exitCode);
// Bun of the host's version for another arch, from its GitHub release; the baseline x64 build runs without AVX2
// (Intel Macs before Haswell, Rosetta before macOS 15).
async function downloadBun() {
const pinned = { version: '1.4.5', arm64: ['bun-darwin-aarch64', 'b5d6bc2e13caf14e57c89661e89efd073ff16165b41bfe43882616410609cd10'], x64: ['bun-darwin-x64-baseline', 'fb0121739a7e80e7511b6bfe4d2116422b48ba18a013acadef0c425348e95891'] };
if (Bun.version !== pinned.version) {
throw new Error(`bun ${Bun.version} runs this script, the pinned ${arch} download is ${pinned.version}: update both`);
}
const [name, sha256] = pinned[arch];
const dir = join(root, 'native/target', `${name}-${pinned.version}`);
const binary = join(dir, name, 'bun');
if (existsSync(binary)) {
return binary;
}
const zip = await (await fetch(`https://github.com/oven-sh/bun/releases/download/bun-v${pinned.version}/${name}.zip`)).arrayBuffer();
const hash = new Bun.CryptoHasher('sha256').update(zip).digest('hex');
if (hash !== sha256) {
throw new Error(`${name}.zip has sha256 ${hash}, not the pinned ${sha256}`);
}
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'bun.zip'), Buffer.from(zip));
await Bun.$`ditto -x -k ${join(dir, 'bun.zip')} ${dir}`;
rmSync(join(dir, 'bun.zip'));
return binary;
}
function shellQuote(value: string) {
return `'${value.replaceAll("'", `'\\''`)}'`;
}
// Runs the commands in a .command script that Terminal opens in the GUI session, and waits for its exit code.
async function inGuiSession(name: string, commands: string[]) {
const base = `/tmp/vsrustium-${name}-${process.pid}`;
const done = `${base}.done`;
rmSync(done, { force: true });
writeFileSync(`${base}.command`, `#!/bin/bash\n( set -e\n${commands.join('\n')}\n) >${shellQuote(`${base}.log`)} 2>&1\necho $? >${shellQuote(done)}\n`, { mode: 0o755 });
await Bun.$`open ${`${base}.command`}`;
// notarytool --wait takes minutes; an hour without the done file means Terminal never ran the script.
for (let waited = 0; !existsSync(done) || !readFileSync(done, 'utf8').trim(); waited++) {
if (waited > 3600) {
throw new Error(`${base}.command did not finish in an hour (is a GUI session logged in?)`);
}
await Bun.sleep(1000);
}
const exitCode = Number(readFileSync(done, 'utf8'));
const log = readFileSync(`${base}.log`, 'utf8');
for (const file of [`${base}.command`, `${base}.log`, done]) {
rmSync(file, { force: true });
}
return { exitCode, stderr: Buffer.from(log) };
}