UNPKG

1.59 kBPlain TextView Raw
1import * as execa from "execa";
2import * as fs from "fs-extra";
3import { logger } from "backfill-logger";
4import { outputFolderAsArray } from "backfill-config";
5
6export type ExecaReturns = execa.ExecaChildProcess;
7export type BuildCommand = () => Promise<ExecaReturns | void>;
8
9export function getRawBuildCommand(): string {
10 return process.argv.slice(2).join(" ");
11}
12
13export function createBuildCommand(
14 buildCommand: string[],
15 clearOutputFolder: boolean,
16 outputFolder: string | string[]
17): () => Promise<ExecaReturns | void> {
18 return async (): Promise<ExecaReturns | void> => {
19 const parsedBuildCommand = buildCommand.join(" ");
20
21 if (!parsedBuildCommand) {
22 throw new Error("Command not provided");
23 }
24
25 // Clear outputFolder to guarantee a deterministic cache
26 if (clearOutputFolder) {
27 await Promise.all(
28 outputFolderAsArray(outputFolder).map(folder => fs.remove(folder))
29 );
30 }
31
32 // Set up runner
33 logger.profile("buildCommand:run");
34 const runner = execa(parsedBuildCommand, {
35 shell: true,
36 ...(process.env.NODE_ENV !== "test" ? { stdio: "inherit" } : {})
37 });
38
39 return (
40 runner
41 // Add build time to the performance logger
42 .then(() => {
43 logger.setTime("buildTime", "buildCommand:run");
44 })
45 // Catch to pretty-print the command that failed and re-throw
46 .catch(err => {
47 if (process.env.NODE_ENV !== "test") {
48 logger.error(`Failed while running: "${parsedBuildCommand}"`);
49 }
50 throw err;
51 })
52 );
53 };
54}