mirror of
https://github.com/Sevichecc/Urara-Blog.git
synced 2025-05-03 19:19:30 +08:00
110 lines
2.5 KiB
Text
110 lines
2.5 KiB
Text
import fs__default from 'fs';
|
|
import path__default from 'path';
|
|
|
|
/** @param {string} dir */
|
|
function mkdirp(dir) {
|
|
try {
|
|
fs__default.mkdirSync(dir, { recursive: true });
|
|
} catch (/** @type {any} */ e) {
|
|
if (e.code === 'EEXIST') return;
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
/** @param {string} path */
|
|
function rimraf(path) {
|
|
fs__default.rmSync(path, { force: true, recursive: true });
|
|
}
|
|
|
|
/**
|
|
* @param {string} source
|
|
* @param {string} target
|
|
* @param {{
|
|
* filter?: (basename: string) => boolean;
|
|
* replace?: Record<string, string>;
|
|
* }} opts
|
|
*/
|
|
function copy(source, target, opts = {}) {
|
|
if (!fs__default.existsSync(source)) return [];
|
|
|
|
/** @type {string[]} */
|
|
const files = [];
|
|
|
|
const prefix = posixify(target) + '/';
|
|
|
|
const regex = opts.replace
|
|
? new RegExp(`\\b(${Object.keys(opts.replace).join('|')})\\b`, 'g')
|
|
: null;
|
|
|
|
/**
|
|
* @param {string} from
|
|
* @param {string} to
|
|
*/
|
|
function go(from, to) {
|
|
if (opts.filter && !opts.filter(path__default.basename(from))) return;
|
|
|
|
const stats = fs__default.statSync(from);
|
|
|
|
if (stats.isDirectory()) {
|
|
fs__default.readdirSync(from).forEach((file) => {
|
|
go(path__default.join(from, file), path__default.join(to, file));
|
|
});
|
|
} else {
|
|
mkdirp(path__default.dirname(to));
|
|
|
|
if (opts.replace) {
|
|
const data = fs__default.readFileSync(from, 'utf-8');
|
|
fs__default.writeFileSync(
|
|
to,
|
|
data.replace(
|
|
/** @type {RegExp} */ (regex),
|
|
(_match, key) => /** @type {Record<string, string>} */ (opts.replace)[key]
|
|
)
|
|
);
|
|
} else {
|
|
fs__default.copyFileSync(from, to);
|
|
}
|
|
|
|
files.push(to === target ? posixify(path__default.basename(to)) : posixify(to).replace(prefix, ''));
|
|
}
|
|
}
|
|
|
|
go(source, target);
|
|
|
|
return files;
|
|
}
|
|
|
|
/**
|
|
* Get a list of all files in a directory
|
|
* @param {string} cwd - the directory to walk
|
|
* @param {boolean} [dirs] - whether to include directories in the result
|
|
*/
|
|
function walk(cwd, dirs = false) {
|
|
/** @type {string[]} */
|
|
const all_files = [];
|
|
|
|
/** @param {string} dir */
|
|
function walk_dir(dir) {
|
|
const files = fs__default.readdirSync(path__default.join(cwd, dir));
|
|
|
|
for (const file of files) {
|
|
const joined = path__default.join(dir, file);
|
|
const stats = fs__default.statSync(path__default.join(cwd, joined));
|
|
if (stats.isDirectory()) {
|
|
if (dirs) all_files.push(joined);
|
|
walk_dir(joined);
|
|
} else {
|
|
all_files.push(joined);
|
|
}
|
|
}
|
|
}
|
|
|
|
return walk_dir(''), all_files;
|
|
}
|
|
|
|
/** @param {string} str */
|
|
function posixify(str) {
|
|
return str.replace(/\\/g, '/');
|
|
}
|
|
|
|
export { copy as c, mkdirp as m, posixify as p, rimraf as r, walk as w };
|