All files / src/lib/compiler makeBuild.ts

0% Statements 0/101
0% Branches 0/39
0% Functions 0/9
0% Lines 0/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import fs from "fs-extra";
import os from "os";
import Path from "path";
import {
  buildLinkFile,
  buildLinkFlags,
  getBuildCommands,
  getPackFiles,
} from "./buildMakeScript";
import { cacheObjData, fetchCachedObjData } from "./objCache";
import ensureBuildTools from "./ensureBuildTools";
import spawn, { ChildProcess } from "lib/helpers/cli/spawn";
import { gbspack } from "./gbspack";
import l10n from "shared/lib/lang/l10n";
import { ProjectResources } from "shared/lib/resources/types";
import psTree from "ps-tree";
import { promisify } from "util";
 
const psTreeAsync = promisify(psTree);
 
type MakeOptions = {
  buildRoot: string;
  tmpPath: string;
  data: ProjectResources;
  buildType: "rom" | "web" | "pocket";
  debug: boolean;
  progress: (msg: string) => void;
  warnings: (msg: string) => void;
};
 
const cpuCount = os.cpus().length;
const childSet = new Set<ChildProcess>();
let cancelling = false;
 
const makeBuild = async ({
  buildRoot = "/tmp",
  tmpPath = "/tmp",
  data,
  debug = false,
  buildType = "rom",
  progress = (_msg) => {},
  warnings = (_msg) => {},
}: MakeOptions) => {
  cancelling = false;
  const env = { ...process.env };
  const { settings } = data;
  const colorEnabled = settings.colorMode !== "mono";
  const sgbEnabled = settings.sgbEnabled && settings.colorMode !== "color";
  const colorOnly = settings.colorMode === "color";
  const targetPlatform = buildType === "pocket" ? "pocket" : "gb";
  const batterylessEnabled = settings.batterylessEnabled && buildType !== "web";
 
  const buildToolsPath = await ensureBuildTools(tmpPath);
  const buildToolsVersion = await fs.readFile(
    `${buildToolsPath}/tools_version`,
    "utf8"
  );
 
  env.PATH = [
    Path.join(buildToolsPath, "gbdk", "bin"),
    env.PATH ?? env.Path,
  ].join(Path.delimiter);
 
  env.GBDKDIR = `${buildToolsPath}/gbdk/`;
  env.GBS_TOOLS_VERSION = buildToolsVersion;
  env.TARGET_PLATFORM = targetPlatform;
 
  env.CART_TYPE = settings.cartType || "mbc5";
  env.TMP = tmpPath;
  env.TEMP = tmpPath;
  Iif (colorEnabled) {
    env.COLOR = "true";
  }
  Iif (sgbEnabled) {
    env.SGB = "true";
  }
  Iif (batterylessEnabled) {
    env.BATTERYLESS = "true";
  }
  env.COLOR_MODE = settings.colorMode;
  env.MUSIC_DRIVER = settings.musicDriver;
  Iif (debug) {
    env.DEBUG = "true";
  }
  if (settings.musicDriver === "huge") {
    env.MUSIC_DRIVER = "HUGE_TRACKER";
  } else {
    env.MUSIC_DRIVER = "GBT_PLAYER";
  }
  if (settings.cartType === "mbc3") {
    env.RUMBLE_ENABLE = "0x20";
  } else {
    env.RUMBLE_ENABLE = "0x08";
  }
 
  env.GBDK_COMPILER_PRESET = String(settings.compilerPreset);
 
  // Populate /obj with cached data
  await fetchCachedObjData(buildRoot, tmpPath, env);
 
  // Compile Source Files
  const makeCommands = await getBuildCommands(buildRoot, {
    colorEnabled,
    sgb: sgbEnabled,
    musicDriver: settings.musicDriver,
    batteryless: batterylessEnabled,
    debug,
    platform: process.platform,
    targetPlatform,
    cartType: settings.cartType,
    compilerPreset: settings.compilerPreset,
  });
 
  const options = {
    cwd: buildRoot,
    env,
    shell: true,
  };
 
  // Build source files in parallel
  const concurrency = cpuCount;
  await Promise.all(
    Array(concurrency)
      .fill(makeCommands.entries())
      .map(async (cursor) => {
        for (const [_, makeCommand] of cursor) {
          Iif (cancelling) {
            throw new Error("BUILD_CANCELLED");
          }
          try {
            progress(makeCommand.label);
          } catch (e) {
            throw e;
          }
          const { child, completed } = spawn(
            makeCommand.command,
            makeCommand.args,
            options,
            {
              onLog: (msg) => warnings(msg), // LCC writes errors to stdout
              onError: (msg) => warnings(msg),
            }
          );
          childSet.add(child);
          await completed;
          childSet.delete(child);
        }
      })
  );
 
  // GBSPack ---
 
  Iif (cancelling) {
    throw new Error("BUILD_CANCELLED");
  }
 
  progress(`${l10n("COMPILER_PACKING")}...`);
  const { cartSize } = await gbspack(await getPackFiles(buildRoot), {
    bankOffset: 1,
    filter: 255,
    extension: "rel",
    additional: batterylessEnabled ? 4 : 0,
    reserve:
      settings.musicDriver !== "huge"
        ? {
            // Reserve space in bank1 for gbt_player.lib
            1: 0x800,
          }
        : {},
  });
 
  // Link ROM ---
 
  Iif (cancelling) {
    throw new Error("BUILD_CANCELLED");
  }
 
  progress(`${l10n("COMPILER_LINKING")}...`);
  const linkFile = await buildLinkFile(buildRoot, cartSize);
  const linkFilePath = `${buildRoot}/obj/linkfile.lk`;
  await fs.writeFile(linkFilePath, linkFile);
 
  const linkCommand =
    process.platform === "win32"
      ? `..\\_gbstools\\gbdk\\bin\\lcc.exe`
      : `../_gbstools/gbdk/bin/lcc`;
  const linkArgs = buildLinkFlags(
    linkFilePath,
    data.metadata.name || "GBStudio",
    settings.cartType,
    colorEnabled,
    sgbEnabled,
    colorOnly,
    settings.musicDriver,
    debug,
    targetPlatform
  );
 
  const { completed: linkCompleted, child } = spawn(
    linkCommand,
    linkArgs,
    options,
    {
      onLog: (msg) => progress(msg),
      onError: (msg) => {
        Iif (msg.indexOf("Converted build") > -1) {
          return;
        }
        warnings(msg);
      },
    }
  );
 
  childSet.add(child);
  await linkCompleted;
  childSet.delete(child);
 
  // Store /obj in cache
  await cacheObjData(buildRoot, tmpPath, env);
};
 
export const cancelBuildCommandsInProgress = async () => {
  cancelling = true;
  // Kill all spawned commands and any commands that were spawned by those
  // e.g lcc spawns sdcc, etc.
  for (const child of childSet) {
    Iif (child.pid === undefined) {
      continue;
    }
    const spawnedChildren = await psTreeAsync(child.pid);
    for (const childChild of spawnedChildren) {
      try {
        process.kill(Number(childChild.PID));
      } catch (e) {}
    }
    try {
      child.kill();
    } catch (e) {}
  }
};
 
export default makeBuild;