All files / src/lib/compiler ensureBuildTools.ts

28.21% Statements 11/39
0% Branches 0/6
0% Functions 0/3
28.21% Lines 11/39

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 742x 2x 2x 2x   2x 2x 2x   2x   2x                                                         2x                                                               2x  
import fs from "fs-extra";
import { rimraf as rmdir } from "rimraf";
import { buildToolsRoot } from "consts";
import copy from "lib/helpers/fsCopy";
 
let inFlightPromise: Promise<string> | null = null;
let cachedPath: string | null = null;
let cacheExpiresAt = 0;
 
const CACHE_TTL_MS = 60_000; // 1 minute
 
const ensureBuildTools = async (tmpPath: string): Promise<string> => {
  const now = Date.now();
 
  // If cached and valid, return immediately
  Iif (cachedPath && now < cacheExpiresAt) {
    return cachedPath;
  }
 
  // If a build is already in progress, reuse it
  Iif (inFlightPromise) {
    return inFlightPromise;
  }
 
  inFlightPromise = (async () => {
    try {
      const result = await ensureBuildToolsInner(tmpPath);
 
      cachedPath = result;
      cacheExpiresAt = Date.now() + CACHE_TTL_MS;
 
      return result;
    } finally {
      inFlightPromise = null;
    }
  })();
 
  return inFlightPromise;
};
 
const ensureBuildToolsInner = async (tmpPath: string): Promise<string> => {
  const buildToolsPath = `${buildToolsRoot}/${process.platform}-${process.arch}`;
  const expectedVersionPath = `${buildToolsPath}/tools_version`;
 
  const tmpBuildToolsPath = `${tmpPath}/_gbstools`;
  const tmpVersionPath = `${tmpBuildToolsPath}/tools_version`;
 
  const expectedVersion = await fs.readFile(expectedVersionPath, "utf8");
 
  let needsCopy = false;
 
  try {
    const currentVersion = await fs.readFile(tmpVersionPath, "utf8");
    Iif (currentVersion !== expectedVersion) {
      needsCopy = true;
    }
  } catch {
    // No engine.json found
    needsCopy = true;
  }
 
  Iif (needsCopy) {
    await rmdir(tmpBuildToolsPath);
    await copy(buildToolsPath, tmpBuildToolsPath, {
      overwrite: true,
      mode: 0o755,
    });
  }
 
  return tmpBuildToolsPath;
};
 
export default ensureBuildTools;