mirror of
https://github.com/hensm/fx_cast.git
synced 2026-06-08 08:39:59 +00:00
90 lines
2.6 KiB
JavaScript
90 lines
2.6 KiB
JavaScript
// @ts-check
|
|
"use strict";
|
|
|
|
import path from "path";
|
|
import fs from "fs";
|
|
|
|
// eslint-disable-next-line no-unused-vars
|
|
import esbuild from "esbuild";
|
|
|
|
/**
|
|
* Walks file tree from a given root path.
|
|
* @param {string} rootPath
|
|
*/
|
|
function* walk(rootPath) {
|
|
const pathsToWalk = [rootPath];
|
|
while (pathsToWalk.length > 0) {
|
|
const currentPath = /** @type {string} */ (pathsToWalk.pop());
|
|
if (fs.statSync(currentPath).isFile()) {
|
|
yield currentPath;
|
|
} else {
|
|
for (const child of fs.readdirSync(currentPath)) {
|
|
pathsToWalk.push(path.join(currentPath, child));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @typedef {object} CopyFilesPluginOpts
|
|
* @prop {string} src Source path
|
|
* @prop {string} dest Destination path
|
|
* @prop {RegExp=} excludePattern Exclude path pattern
|
|
*/
|
|
/**
|
|
* Plugin that copies files from specified source to destination after
|
|
* each build.
|
|
*
|
|
* @type {(opts: CopyFilesPluginOpts) => esbuild.Plugin}
|
|
*/
|
|
export default opts => {
|
|
if (!fs.existsSync(opts.src)) {
|
|
throw new Error("copyFilesPlugin: src path not found!");
|
|
}
|
|
|
|
const matchingPaths = [...walk(opts.src)].filter(
|
|
path => !opts.excludePattern?.test(path)
|
|
);
|
|
|
|
return {
|
|
name: "copy-files",
|
|
setup(build) {
|
|
build.onEnd(() => {
|
|
// Copy any source files that changed
|
|
for (const srcPath of matchingPaths) {
|
|
const destPath = path.resolve(
|
|
opts.dest,
|
|
path.relative(opts.src, srcPath)
|
|
);
|
|
|
|
// Ignore if source file is missing
|
|
if (!fs.existsSync(srcPath)) {
|
|
if (fs.existsSync(destPath)) {
|
|
fs.rmSync(destPath);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
// Ensure containing destination directory exists
|
|
const dirName = path.dirname(destPath);
|
|
if (!fs.existsSync(dirName)) {
|
|
fs.mkdirSync(dirName, { recursive: true });
|
|
}
|
|
|
|
// Check if files match
|
|
if (fs.existsSync(destPath)) {
|
|
const srcContent = fs.readFileSync(srcPath);
|
|
const destContent = fs.readFileSync(destPath);
|
|
|
|
if (srcContent.equals(destContent)) {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
fs.copyFileSync(srcPath, destPath);
|
|
}
|
|
});
|
|
}
|
|
};
|
|
};
|