Files
test-repo/scripts/build/build.mjs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

257 lines
6.6 KiB
JavaScript
Raw Normal View History

2021-05-15 20:09:52 +08:00
#!/usr/bin/env node
2021-05-15 20:09:52 +08:00
import path from "node:path";
import fs from "node:fs/promises";
import readline from "node:readline";
import chalk from "chalk";
import minimist from "minimist";
import prettyBytes from "pretty-bytes";
2022-02-07 12:00:43 +08:00
import createEsmUtils from "esm-utils";
2021-09-10 10:20:43 +08:00
import {
PROJECT_ROOT,
DIST_DIR,
readJson,
writeJson,
copyFile,
2021-09-11 09:55:46 +08:00
} from "../utils/index.mjs";
import bundler from "./bundler.mjs";
import bundleConfigs from "./config.mjs";
import saveLicenses from "./save-licenses.mjs";
2022-02-07 12:00:43 +08:00
const { require } = createEsmUtils(import.meta);
2020-10-26 09:44:09 +08:00
const statusConfig = [
{ color: "bgGreen", text: "DONE" },
{ color: "bgRed", text: "FAIL" },
{ color: "bgGray", text: "SKIPPED" },
];
const maxLength = Math.max(...statusConfig.map(({ text }) => text.length)) + 2;
const padStatusText = (text) => {
while (text.length < maxLength) {
text = text.length % 2 ? `${text} ` : ` ${text}`;
}
return text;
};
const status = {};
for (const { color, text } of statusConfig) {
status[text] = chalk[color].black(padStatusText(text));
}
2018-05-29 14:59:57 -03:00
function fitTerminal(input, suffix = "") {
2018-06-14 11:15:04 -03:00
const columns = Math.min(process.stdout.columns || 40, 80);
2020-10-26 09:44:09 +08:00
const WIDTH = columns - maxLength + 1;
2018-05-29 14:59:57 -03:00
if (input.length < WIDTH) {
2022-02-07 12:00:43 +08:00
const repeatCount = Math.max(WIDTH - input.length - 1 - suffix.length, 0);
input += chalk.dim(".").repeat(repeatCount) + suffix;
2018-05-24 15:30:45 -03:00
}
2018-05-29 14:59:57 -03:00
return input;
}
2022-01-27 09:37:55 +08:00
const clear = () => {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
};
2022-01-09 01:15:04 +08:00
async function createBundle(bundleConfig, options) {
try {
2022-02-07 12:00:43 +08:00
for await (const {
name,
started,
skipped,
relativePath,
absolutePath,
} of bundler(bundleConfig, options)) {
2022-01-27 09:37:55 +08:00
const displayName = name.startsWith("esm/") ? ` ${name}` : name;
2020-10-26 09:44:09 +08:00
2022-01-27 09:37:55 +08:00
if (started) {
process.stdout.write(fitTerminal(displayName));
continue;
2018-06-18 15:16:40 -03:00
}
2022-01-27 09:37:55 +08:00
if (skipped) {
if (!options.files) {
process.stdout.write(fitTerminal(displayName));
console.log(status.SKIPPED);
}
2022-01-27 09:37:55 +08:00
continue;
}
2022-02-07 12:00:43 +08:00
const sizeMessages = [];
2022-01-27 09:37:55 +08:00
if (options.printSize) {
2022-02-07 12:00:43 +08:00
const { size } = await fs.stat(absolutePath);
sizeMessages.push(prettyBytes(size));
}
if (options.compareSize) {
// TODO: Use `import.meta.resolve` when Node.js support
const stablePrettierDirectory = path.dirname(
require.resolve("prettier")
2021-09-10 10:20:43 +08:00
);
2022-02-07 12:00:43 +08:00
const stableVersionFile = path.join(
stablePrettierDirectory,
relativePath
);
let stableSize;
try {
({ size: stableSize } = await fs.stat(stableVersionFile));
} catch {
// No op
}
2022-02-07 12:00:43 +08:00
if (stableSize) {
const { size } = await fs.stat(absolutePath);
const sizeDiff = size - stableSize;
const message = chalk[sizeDiff > 0 ? "yellow" : "green"](
prettyBytes(sizeDiff)
);
sizeMessages.push(`${message}`);
} else {
sizeMessages.push(chalk.blue("[NEW FILE]"));
}
}
if (sizeMessages.length > 0) {
2022-01-27 09:37:55 +08:00
// Clear previous line
clear();
2022-02-07 12:00:43 +08:00
process.stdout.write(
fitTerminal(displayName, `${sizeMessages.join(", ")} `)
);
2022-01-27 09:37:55 +08:00
}
console.log(status.DONE);
}
} catch (error) {
2020-10-26 09:44:09 +08:00
console.log(status.FAIL + "\n");
console.error(error);
throw error;
}
2018-05-24 15:30:45 -03:00
}
2018-05-29 14:59:57 -03:00
async function preparePackage() {
2021-09-10 10:20:43 +08:00
const packageJson = await readJson(path.join(PROJECT_ROOT, "package.json"));
packageJson.bin = "./bin-prettier.js";
2022-04-06 16:05:22 +08:00
packageJson.engines.node = ">=12.17.0";
2021-09-10 10:20:43 +08:00
delete packageJson.dependencies;
delete packageJson.devDependencies;
delete packageJson.browserslist;
2022-02-12 15:39:16 +08:00
delete packageJson.type;
2021-09-10 10:20:43 +08:00
packageJson.scripts = {
2018-05-24 15:30:45 -03:00
prepublishOnly:
2018-05-29 00:22:59 -06:00
"node -e \"assert.equal(require('.').version, require('..').version)\"",
2018-05-24 15:30:45 -03:00
};
2021-09-10 10:20:43 +08:00
packageJson.files = ["*.js", "esm/*.mjs"];
await writeJson(path.join(DIST_DIR, "package.json"), packageJson);
2018-05-29 14:59:57 -03:00
2021-09-10 10:20:43 +08:00
for (const file of ["README.md", "LICENSE"]) {
await copyFile(path.join(PROJECT_ROOT, file), path.join(DIST_DIR, file));
}
2018-05-24 15:30:45 -03:00
}
2018-06-18 15:16:40 -03:00
async function run(params) {
2022-01-27 16:53:07 +08:00
params.files = params.file ? new Set([params.file].flat()) : params.file;
2022-02-18 17:12:18 +08:00
delete params.file;
2022-01-27 09:37:55 +08:00
params.saveAs = params["save-as"];
2022-02-18 17:12:18 +08:00
delete params["save-as"];
2022-01-27 09:37:55 +08:00
params.printSize = params["print-size"];
2022-02-18 17:12:18 +08:00
delete params["print-size"];
params.compareSize = params["compare-size"];
delete params["compare-size"];
2022-01-27 16:53:07 +08:00
if (params.report === "") {
params.report = ["html"];
2020-10-26 09:44:09 +08:00
}
2022-01-27 16:53:07 +08:00
params.reports = params.report ? [params.report].flat() : params.report;
delete params.report;
2022-01-27 09:37:55 +08:00
if (params.saveAs && !(params.files && params.files.size === 1)) {
throw new Error("'--save-as' can only use together with one '--file' flag");
}
if (
params.saveAs &&
!path.join(DIST_DIR, params.saveAs).startsWith(DIST_DIR)
) {
throw new Error("'--save-as' can only relative path");
}
2022-02-02 10:23:51 +08:00
if (params.clean) {
let stat;
try {
stat = await fs.stat(DIST_DIR);
} catch {
// No op
}
if (stat) {
if (stat.isDirectory()) {
await fs.rm(DIST_DIR, { recursive: true, force: true });
} else {
throw new Error(`"${DIST_DIR}" is not a directory`);
}
}
}
2022-02-07 12:00:43 +08:00
if (params.compareSize) {
if (params.minify === false) {
throw new Error(
"'--compare-size' can not use together with '--no-minify' flag"
);
}
if (params.saveAs) {
throw new Error(
"'--compare-size' can not use together with '--save-as' flag"
);
}
}
2022-01-27 09:37:55 +08:00
const shouldPreparePackage =
!params.playground && !params.files && params.minify === null;
const shouldSaveBundledPackagesLicenses = shouldPreparePackage;
2018-06-18 15:16:40 -03:00
const licenses = [];
if (shouldSaveBundledPackagesLicenses) {
params.onLicenseFound = (dependencies) => licenses.push(...dependencies);
}
2018-05-29 14:59:57 -03:00
console.log(chalk.inverse(" Building packages "));
2021-09-09 12:23:53 +08:00
2022-01-27 09:37:55 +08:00
for (const bundleConfig of bundleConfigs) {
2022-01-09 01:15:04 +08:00
await createBundle(bundleConfig, params);
2021-09-09 12:23:53 +08:00
}
2018-06-18 15:16:40 -03:00
2021-09-09 12:23:53 +08:00
if (shouldPreparePackage) {
2020-10-26 09:44:09 +08:00
await preparePackage();
}
if (shouldSaveBundledPackagesLicenses) {
2022-01-16 10:21:29 +08:00
await saveLicenses(licenses.filter(({ name }) => name !== "prettier"));
} else {
console.warn(
chalk.red("Bundled packages licenses not included in `dist/LICENSE`.")
);
}
2018-05-24 15:30:45 -03:00
}
await run(
2018-06-18 15:16:40 -03:00
minimist(process.argv.slice(2), {
2022-02-09 09:31:03 +08:00
boolean: ["playground", "print-size", "compare-size", "minify", "clean"],
2022-01-27 16:53:07 +08:00
string: ["file", "save-as", "report"],
2022-01-27 11:16:50 +08:00
default: {
2022-02-02 10:23:51 +08:00
clean: false,
2022-01-27 11:16:50 +08:00
playground: false,
printSize: false,
2022-02-07 12:00:43 +08:00
compareSize: false,
2022-01-27 11:16:50 +08:00
minify: null,
},
2022-01-27 09:37:55 +08:00
unknown(flag) {
throw new Error(`Unknown flag ${chalk.red(flag)}`);
},
2018-06-18 15:16:40 -03:00
})
);