/**
* Release packages, built from this checkout on macOS:
*
* bun tools/package.ts macos universal .app in a drag-to-Applications DMG (ad-hoc signed)
* bun tools/package.ts windows fmm.exe cross-compiled with cargo-xwin (MSVC) in a container on FMM_LINUX_HOST
* bun tools/package.ts linux AppImage and Arch package, built in containers on FMM_LINUX_HOST
* bun tools/package.ts all
*
* Output goes to out/release/<version>/. Every platform builds the same files: the tracked and
* non-ignored ones in this working tree. Uncommitted changes are refused unless --dirty is passed.
*/
import { spawnSync, type SpawnSyncOptions } from 'node:child_process'
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
const root = path.resolve(import.meta.dir, '..')
const APP_NAME = 'Factorio Mod Manager'
const BUNDLE_ID = 'com.werry.factoriomodmanager'
const AUTHOR = 'werry'
const AUTHOR_URL = 'https://gitgud.io/werry'
const REPO_URL = 'https://gitgud.io/werry/factoriomodmanager'
const LINUX_HOST = process.env.FMM_LINUX_HOST ?? 'asabove'
const LOCAL_BUILD = process.env.FMM_LOCAL_BUILD === '1'
export function workspaceVersion(cargoToml: string): string {
const section = cargoToml.split(/^\[workspace\.package\]$/m)[1] ?? ''
const version = /^version\s*=\s*"([^"]+)"/m.exec(section)?.[1]
if (!version) throw new Error('No [workspace.package] version in Cargo.toml')
return version
}
export function infoPlist(version: string, build: string, year: number): string {
const entries: [string, string][] = [
['CFBundleName', APP_NAME],
['CFBundleDisplayName', APP_NAME],
['CFBundleIdentifier', BUNDLE_ID],
['CFBundleExecutable', 'fmm'],
['CFBundleIconFile', 'AppIcon'],
['CFBundlePackageType', 'APPL'],
['CFBundleShortVersionString', version],
['CFBundleVersion', build],
['NSHumanReadableCopyright', `© ${year} ${AUTHOR}`],
['LSMinimumSystemVersion', '11.0'],
['LSApplicationCategoryType', 'public.app-category.games'],
]
const body = entries.map(([k, v]) => ` <key>${k}</key>\n <string>${v}</string>`).join('\n')
return `<?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>
${body}
<key>NSHighResolutionCapable</key>
<true/>
</dict>
</plist>
`
}
/** The standard About panel shows Contents/Resources/Credits.html below the version. */
export function creditsHtml(): string {
return `<!doctype html>
<html><head><meta charset="utf-8"><style>
body { font: 11px -apple-system, sans-serif; text-align: center; }
</style></head><body>
<p>Made by <a href="${AUTHOR_URL}">${AUTHOR}</a></p>
<p><a href="${REPO_URL}">${REPO_URL.replace('https://', '')}</a></p>
</body></html>
`
}
function run(cmd: string, args: string[], options: SpawnSyncOptions = {}): string {
const r = spawnSync(cmd, args, { cwd: root, encoding: 'utf8', stdio: ['inherit', 'pipe', 'inherit'], ...options })
if (r.error) throw r.error
if (r.status !== 0) throw new Error(`${cmd} ${args.join(' ')} failed (${r.status})`)
return typeof r.stdout === 'string' ? r.stdout : ''
}
function cargo(args: string[], env: Record<string, string> = {}) {
run('cargo', args, { stdio: 'inherit', env: { ...process.env, ...env } })
}
function background(dir: string) {
// Quick Look renders the HTML template in a 1024 px viewport at 2x; the 660x470 band is centred
// and scaled to the full width, so it spans 2048x1458 device pixels.
const html = path.join(dir, 'background.html')
writeFileSync(html, readFileSync(path.join(root, 'packaging/macos/dmg-background.html'), 'utf8').replaceAll('__ROOT__', root))
run('qlmanage', ['-t', '-s', '2048', '-o', dir, html], { stdio: 'ignore' })
const band = path.join(dir, 'band.png')
run('sips', ['-c', '1458', '2048', `${html}.png`, '--out', band], { stdio: 'ignore' })
run('sips', ['-z', '940', '1320', band, '--out', path.join(dir, '[email protected]')], { stdio: 'ignore' }) run('sips', ['-z', '470', '660', band, '--out', path.join(dir, 'background.png')], { stdio: 'ignore' })
const tiff = path.join(dir, 'background.tiff')
run('tiffutil', ['-cathidpicheck', path.join(dir, 'background.png'), path.join(dir, '[email protected]'), '-out', tiff], { stdio: 'ignore' }) return tiff
}
function finderLayout(volume: string) {
const app = `${APP_NAME}.app`
const script = `
tell application "Finder"
tell disk "${volume}"
open
set current view of container window to icon view
set toolbar visible of container window to false
set statusbar visible of container window to false
set the bounds of container window to {200, 120, 860, 590}
set opts to the icon view options of container window
set arrangement of opts to not arranged
set icon size of opts to 108
set text size of opts to 12
set background picture of opts to file ".background:background.tiff"
set position of item "${app}" of container window to {155, 230}
set position of item "Applications" of container window to {495, 230}
update without registering applications
delay 1
close
end tell
end tell`
run('osascript', ['-e', script], { stdio: 'inherit' })
}
function macos(out: string, version: string, headless: boolean) {
const triples = ['x86_64-apple-darwin', 'aarch64-apple-darwin']
for (const target of triples) {
cargo(['build', '--release', '--locked', '-p', 'fmm', '--target', target], { MACOSX_DEPLOYMENT_TARGET: '11.0' })
}
const work = mkdtempSync(path.join(tmpdir(), 'fmm-macos-'))
try {
const app = path.join(work, 'stage', `${APP_NAME}.app`)
const contents = path.join(app, 'Contents')
mkdirSync(path.join(contents, 'MacOS'), { recursive: true })
mkdirSync(path.join(contents, 'Resources'), { recursive: true })
run('lipo', ['-create', '-output', path.join(contents, 'MacOS/fmm'), ...triples.map(t => path.join(root, 'target', t, 'release/fmm'))])
cpSync(path.join(root, 'assets/game/factorio.icns'), path.join(contents, 'Resources/AppIcon.icns'))
// The commit count makes a monotonically increasing build number: "Version 0.1.0 (42)".
const build = run('git', ['rev-list', '--count', 'HEAD']).trim()
writeFileSync(path.join(contents, 'Info.plist'), infoPlist(version, build, new Date().getFullYear()))
writeFileSync(path.join(contents, 'Resources/Credits.html'), creditsHtml())
writeFileSync(path.join(contents, 'PkgInfo'), 'APPL????')
// Ad-hoc: arm64 requires a signature; without a Developer ID, Gatekeeper still asks once.
run('codesign', ['--force', '--sign', '-', '--timestamp=none', app])
run('codesign', ['--verify', '--strict', '--verbose=2', app], { stdio: 'inherit' })
const archs = run('lipo', ['-archs', path.join(contents, 'MacOS/fmm')]).trim().split(/\s+/).sort()
if (archs.join(' ') !== 'arm64 x86_64') throw new Error(`Unexpected architectures: ${archs.join(' ')}`)
const stage = path.join(work, 'stage')
symlinkSync('/Applications', path.join(stage, 'Applications'))
const dmg = path.join(out, `FactorioModManager-${version}-macos-universal.dmg`)
if (headless) {
run('hdiutil', ['create', '-quiet', '-ov', '-volname', APP_NAME, '-srcfolder', stage, '-fs', 'HFS+', '-format', 'UDZO', dmg])
run('hdiutil', ['verify', dmg], { stdio: 'inherit' })
console.log(`[package] ${path.relative(root, dmg)}`)
return
}
mkdirSync(path.join(stage, '.background'))
cpSync(background(work), path.join(stage, '.background/background.tiff'))
// Finder scripts the disk by name, so an already mounted namesake would get the layout.
if (existsSync(path.join('/Volumes', APP_NAME))) throw new Error(`Eject /Volumes/${APP_NAME} first`)
const rw = path.join(work, 'rw.dmg')
run('hdiutil', ['create', '-quiet', '-volname', APP_NAME, '-srcfolder', stage, '-fs', 'HFS+', '-format', 'UDRW', '-ov', rw])
const attach = run('hdiutil', ['attach', '-readwrite', '-noverify', '-noautoopen', rw])
const mount = /\/Volumes\/.*$/m.exec(attach)?.[0]
if (mount !== path.join('/Volumes', APP_NAME)) throw new Error(`Unexpected mount point:\n${attach}`)
try {
finderLayout(APP_NAME)
run('sync', [])
} finally {
run('hdiutil', ['detach', '-quiet', mount])
}
rmSync(dmg, { force: true })
run('hdiutil', ['convert', '-quiet', rw, '-format', 'UDZO', '-imagekey', 'zlib-level=9', '-o', dmg])
console.log(`[package] ${path.relative(root, dmg)}`)
} finally {
rmSync(work, { recursive: true, force: true })
}
}
const REMOTE = '~/fmm-build'
function ssh(command: string, input?: Buffer) {
run('ssh', [LINUX_HOST, command], { stdio: [input ? 'pipe' : 'inherit', 'inherit', 'inherit'], input })
}
function fetch(out: string, name: string) {
if (!LOCAL_BUILD) run('scp', ['-q', `${LINUX_HOST}:${REMOTE}/out/${name}`, path.join(out, name)], { stdio: 'inherit' })
console.log(`[package] ${path.relative(root, path.join(out, name))}`)
}
function buildShell(out: string, script: string) {
if (LOCAL_BUILD) {
run('bash', ['-e', '-c', script], {
env: { ...process.env, build_src: root, build_out: out },
stdio: 'inherit',
})
} else {
ssh(`set -e; build_src=${REMOTE}/src; build_out=${REMOTE}/out; ${script}`)
}
}
let sent = false
/** Replace ~/fmm-build/src on the build host with this tree's tracked and non-ignored files. */
function sendTree() {
if (sent || LOCAL_BUILD) return
const files = run('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'])
.split('\0')
.filter(f => f && existsSync(path.join(root, f)))
const archive = spawnSync('tar', ['--no-mac-metadata', '--no-xattrs', '--no-fflags', '-cf', '-', '-s', ',^,src/,', '--null', '-T', '-'], {
cwd: root, input: files.join('\0'), maxBuffer: 1 << 30,
})
if (archive.status !== 0) throw new Error(`tar failed: ${archive.stderr}`)
ssh(`set -e; rm -rf ${REMOTE}/src ${REMOTE}/out; mkdir -p ${REMOTE}/out; tar -x -C ${REMOTE}`, archive.stdout)
sent = true
}
function windows(out: string, version: string) {
sendTree()
buildShell(out, `cd "$build_src"; podman build -q -t fmm-windows -f packaging/windows/Containerfile packaging/windows`)
const exe = `FactorioModManager-${version}-windows-x86_64.exe`
// fmm-xwin caches the downloaded MSVC CRT and Windows SDK between runs.
buildShell(out, `podman run --rm -v "$build_src:/src" -v "$build_out:/out" -v fmm-cargo:/usr/local/cargo/registry -v fmm-target-windows:/src/target -v fmm-xwin:/root/.cache/cargo-xwin fmm-windows bash -c '
set -e
cargo xwin build --release --locked -p fmm --target x86_64-pc-windows-msvc
cp target/x86_64-pc-windows-msvc/release/fmm.exe /out/${exe}'`)
fetch(out, exe)
}
function linux(out: string, version: string) {
sendTree()
buildShell(out, `cd "$build_src"
podman build -q -t fmm-build -f packaging/linux/Containerfile packaging/linux
podman build -q -t fmm-arch -f packaging/arch-bin/Containerfile packaging/arch-bin`)
const appimage = `FactorioModManager-${version}-linux-x86_64.AppImage`
const arch = `FactorioModManager-${version}-arch-x86_64.pkg.tar.zst`
// One compiled binary feeds both formats. The AppImage bundles no system libraries, so like the
// Arch package it relies on the desktop's fontconfig, ALSA and graphics stack (glibc 2.35+).
buildShell(out, `podman run --rm -v "$build_src:/src" -v "$build_out:/out" -v fmm-cargo:/usr/local/cargo/registry -v fmm-target:/src/target fmm-build bash -c '
set -e
cargo build --release --locked -p fmm
app=/tmp/AppDir
install -Dm755 target/release/fmm $app/usr/bin/fmm
install -Dm644 packaging/arch/factoriomodmanager.desktop $app/usr/share/applications/factoriomodmanager.desktop
install -Dm644 assets/game/factorio-icon.png $app/usr/share/icons/hicolor/64x64/apps/factoriomodmanager.png
cp packaging/arch/factoriomodmanager.desktop $app/
cp assets/game/factorio-icon.png $app/factoriomodmanager.png
ln -s factoriomodmanager.png $app/.DirIcon
ln -s usr/bin/fmm $app/AppRun
ARCH=x86_64 /opt/appimagetool --no-appstream --runtime-file /opt/runtime-x86_64 $app /out/${appimage}
mkdir -p /out/arch
install -m755 target/release/fmm /out/arch/fmm
cp packaging/arch/factoriomodmanager.desktop /out/arch/
cp assets/game/factorio-icon.png /out/arch/factoriomodmanager.png
sed s/__VERSION__/${version}/ packaging/arch-bin/PKGBUILD > /out/arch/PKGBUILD'`)
buildShell(out, `podman run --rm --userns=keep-id -v "$build_out/arch:/pkg" fmm-arch makepkg -f --nodeps --noconfirm
mv "$build_out/arch/factoriomodmanager-bin-${version}-1-x86_64.pkg.tar.zst" "$build_out/${arch}"`)
fetch(out, appimage)
fetch(out, arch)
}
function main() {
const args = process.argv.slice(2)
const dirty = args.includes('--dirty')
const headless = args.includes('--headless')
const which = args.filter(a => a !== '--dirty' && a !== '--headless')
const valid = ['macos', 'windows', 'linux', 'all']
if (which.length === 0 || which.some(w => !valid.includes(w))) {
console.error(`usage: bun tools/package.ts <${valid.join('|')}>... [--dirty] [--headless]`)
process.exit(2)
}
const status = run('git', ['-c', 'core.fileMode=false', 'status', '--porcelain', '--untracked-files=no'])
if (status.trim() && !dirty) throw new Error('Uncommitted changes; commit them or pass --dirty')
const version = workspaceVersion(readFileSync(path.join(root, 'Cargo.toml'), 'utf8'))
const out = path.join(root, 'out/release', version)
mkdirSync(out, { recursive: true })
const all = which.includes('all')
if (all || which.includes('macos')) macos(out, version, headless)
if (all || which.includes('windows')) windows(out, version)
if (all || which.includes('linux')) linux(out, version)
}
if (import.meta.main) main()