farmcontrol-server/scripts/finalize-desktop-artifacts.mjs
Tom Butcher 3a34082bfd
Some checks failed
farmcontrol/farmcontrol-server/pipeline/head There was a failure building this commit
Update macOS build process and dependencies
- Added `create-dmg` package to package.json for improved DMG creation.
- Modified Jenkinsfile to clean up staging directories correctly.
- Enhanced finalize-desktop-artifacts.mjs to utilize `create-dmg` for generating DMG files, improving artifact management and error handling.
2026-08-01 22:00:50 +01:00

379 lines
9.3 KiB
JavaScript

import {
cpSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
renameSync,
rmSync,
statSync,
} from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import {
getReleaseArch,
getReleaseArtifactName,
getReleaseVersion,
} from "./release-artifact-utils.mjs";
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageJson = JSON.parse(
readFileSync(path.join(rootDir, "package.json"), "utf8"),
);
const buildEnv = process.env.ELECTROBUN_BUILD_ENV || "stable";
const targetOs =
process.env.ELECTROBUN_OS ||
(process.platform === "darwin"
? "macos"
: process.platform === "win32"
? "win"
: process.platform === "linux"
? "linux"
: null);
const buildArch = getReleaseArch(
process.env.ELECTROBUN_ARCH || process.arch,
);
const version =
process.env.ELECTROBUN_APP_VERSION || getReleaseVersion(packageJson);
const artifactDir =
process.env.ELECTROBUN_ARTIFACT_DIR || path.join(rootDir, "app_dist");
const identifier =
process.env.ELECTROBUN_APP_IDENTIFIER || "com.tombutcher.farmcontrolserver";
const artifactPrefix = `farmcontrol-server-${version}-`;
function getBuildRoot() {
const electrobunBuildDir = process.env.ELECTROBUN_BUILD_DIR;
if (!electrobunBuildDir) {
return path.join(rootDir, "build");
}
const baseName = path.basename(electrobunBuildDir);
if (baseName.startsWith("stable-")) {
return path.dirname(electrobunBuildDir);
}
return electrobunBuildDir;
}
function walkFiles(dir) {
const files = [];
if (!existsSync(dir)) {
return files;
}
for (const entry of readdirSync(dir)) {
const fullPath = path.join(dir, entry);
const stats = statSync(fullPath);
if (stats.isDirectory()) {
files.push(...walkFiles(fullPath));
} else {
files.push(fullPath);
}
}
return files;
}
function findByExtension(root, extension) {
return walkFiles(root).find((filePath) =>
filePath.toLowerCase().endsWith(extension.toLowerCase()),
);
}
function findMacAppBundle(arch) {
const platformDir = path.join(getBuildRoot(), `stable-macos-${arch}`);
if (!existsSync(platformDir)) {
return null;
}
for (const child of readdirSync(platformDir)) {
if (child.endsWith(".app")) {
return path.join(platformDir, child);
}
}
return null;
}
function findMacDmgSource(arch) {
const prefixedArtifact = walkFiles(artifactDir).find(
(filePath) =>
filePath.includes(`stable-macos-${arch}`) &&
filePath.toLowerCase().endsWith(".dmg"),
);
if (prefixedArtifact) {
return prefixedArtifact;
}
const buildDmg = findByExtension(
path.join(getBuildRoot(), `stable-macos-${arch}`),
".dmg",
);
if (buildDmg) {
return buildDmg;
}
return findByExtension(artifactDir, ".dmg");
}
function findWindowsInstallerFiles() {
const buildRoot = getBuildRoot();
if (!existsSync(buildRoot)) {
return null;
}
for (const entry of readdirSync(buildRoot)) {
if (!entry.startsWith("stable-win-")) {
continue;
}
const platformDir = path.join(buildRoot, entry);
const files = walkFiles(platformDir);
const setupExe = files.find((filePath) => /-setup\.exe$/i.test(filePath));
const setupArchive = files.find((filePath) =>
/-setup\.tar\.zst$/i.test(filePath),
);
const setupMetadata = files.find((filePath) =>
/-setup\.metadata\.json$/i.test(filePath),
);
const setupZip = files.find((filePath) => /-setup\.zip$/i.test(filePath));
if (setupExe && setupArchive && setupMetadata) {
return { setupExe, setupArchive, setupMetadata, setupZip };
}
}
return null;
}
function publishArtifact(sourcePath, arch, ext) {
if (!sourcePath || !existsSync(sourcePath)) {
throw new Error(
`Missing source artifact for ${arch}.${ext}: ${sourcePath ?? "not found"}`,
);
}
mkdirSync(artifactDir, { recursive: true });
const destination = path.join(
artifactDir,
getReleaseArtifactName(version, arch, ext),
);
cpSync(sourcePath, destination);
console.log(`Published ${destination}`);
return destination;
}
function cleanStagingArtifacts(keepNames) {
if (!existsSync(artifactDir)) {
return;
}
for (const entry of readdirSync(artifactDir)) {
if (keepNames.includes(entry) || entry.startsWith(artifactPrefix)) {
continue;
}
if (
entry.includes("stable-macos-") ||
entry.includes("stable-win-") ||
entry.endsWith("-update.json") ||
entry.endsWith(".tar.gz")
) {
rmSync(path.join(artifactDir, entry), { recursive: true, force: true });
}
}
}
function buildMacDmg(appBundlePath, arch) {
const dmgPath = path.join(
artifactDir,
getReleaseArtifactName(version, arch, "dmg"),
);
const createDmgCli = path.join(rootDir, "node_modules/create-dmg/cli.js");
if (!existsSync(createDmgCli)) {
throw new Error(
"create-dmg not found. Install dependencies with pnpm install or bun install.",
);
}
mkdirSync(artifactDir, { recursive: true });
const tempOutputDir = path.join(
path.dirname(appBundlePath),
".finalize-dmg-output",
);
rmSync(tempOutputDir, { recursive: true, force: true });
mkdirSync(tempOutputDir, { recursive: true });
const result = spawnSync(
"node",
[
createDmgCli,
appBundlePath,
tempOutputDir,
"--overwrite",
"--no-code-sign",
"--no-version-in-filename",
"--dmg-title",
"Farm Control Server",
],
{ cwd: rootDir, stdio: "inherit" },
);
const createdDmg = walkFiles(tempOutputDir).find((filePath) =>
filePath.toLowerCase().endsWith(".dmg"),
);
if (result.status !== 0 || !createdDmg) {
rmSync(tempOutputDir, { recursive: true, force: true });
throw new Error(
`create-dmg failed (exit ${result.status ?? 1}) or produced no .dmg file`,
);
}
rmSync(dmgPath, { force: true });
renameSync(createdDmg, dmgPath);
rmSync(tempOutputDir, { recursive: true, force: true });
console.log(`Published ${dmgPath}`);
return dmgPath;
}
function cleanMacBuildDir(arch) {
const platformDir = path.join(getBuildRoot(), `stable-macos-${arch}`);
if (existsSync(platformDir)) {
rmSync(platformDir, { recursive: true, force: true });
console.log(`Removed build output ${platformDir}`);
}
}
function buildMacPkg(appBundlePath, arch) {
const pkgPath = path.join(
artifactDir,
getReleaseArtifactName(version, arch, "pkg"),
);
const result = spawnSync(
"pkgbuild",
[
"--component",
appBundlePath,
"--install-location",
"/Applications",
"--identifier",
identifier,
"--version",
version,
pkgPath,
],
{ stdio: "inherit" },
);
if (result.status !== 0) {
throw new Error(`pkgbuild failed with exit code ${result.status ?? 1}`);
}
console.log(`Published ${pkgPath}`);
return pkgPath;
}
function buildWindowsNsis(installerFiles, arch) {
const scriptPath = path.join(rootDir, "scripts/build-windows-nsis.ps1");
const exePath = path.join(
artifactDir,
getReleaseArtifactName(version, arch, "exe"),
);
const powershell =
process.env.SystemRoot
? path.join(
process.env.SystemRoot,
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
)
: "powershell.exe";
const result = spawnSync(
powershell,
[
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
scriptPath,
"-SetupExe",
installerFiles.setupExe,
"-SetupArchive",
installerFiles.setupArchive,
"-SetupMetadata",
installerFiles.setupMetadata,
"-OutputExe",
exePath,
"-Version",
version,
],
{ stdio: "inherit" },
);
if (result.status !== 0) {
throw new Error(
`build-windows-nsis.ps1 failed with exit code ${result.status ?? 1}`,
);
}
console.log(`Published ${exePath}`);
return exePath;
}
if (buildEnv === "dev") {
console.log("finalize-desktop-artifacts: skipping dev build");
process.exit(0);
}
if (targetOs === "macos") {
const appBundle = findMacAppBundle(buildArch);
if (!appBundle) {
console.log(
`finalize-desktop-artifacts: no macOS ${buildArch} app bundle found, skipping`,
);
process.exit(0);
}
const existingDmg = findMacDmgSource(buildArch);
const dmgPath = existingDmg
? publishArtifact(existingDmg, buildArch, "dmg")
: buildMacDmg(appBundle, buildArch);
const published = [dmgPath, buildMacPkg(appBundle, buildArch)];
cleanStagingArtifacts(published.map((filePath) => path.basename(filePath)));
cleanMacBuildDir(buildArch);
} else if (targetOs === "win") {
const arch = getReleaseArch(process.env.ELECTROBUN_ARCH || "x64");
const installerFiles = findWindowsInstallerFiles();
if (!installerFiles) {
throw new Error(
"Could not find the Windows installer files (setup exe, archive, and metadata)",
);
}
const published = [buildWindowsNsis(installerFiles, arch)];
if (installerFiles.setupZip) {
published.push(publishArtifact(installerFiles.setupZip, arch, "zip"));
}
cleanStagingArtifacts(published.map((filePath) => path.basename(filePath)));
} else {
console.log(
"finalize-desktop-artifacts: no desktop packaging configured for",
targetOs ?? "unknown target",
);
process.exit(0);
}