lazy-js-utils
Version:
A collection of lazy-loaded JavaScript utilities for efficient development
223 lines (207 loc) • 6.35 kB
JavaScript
import { isFile$1 as isFile } from "../parallel-DHAKJPw_.js";
import { isStr$1 as isStr } from "../isBool-Bi9uSocl.js";
import { toAbsolutePath$1 as toAbsolutePath } from "../toAbsolutePath-Coj-fxcV.js";
import { jsShell, useNodeWorker, useProcressNodeWorker } from "../useNodeWorker-CooJWnAZ.js";
import process from "node:process";
import fs from "node:fs";
import path from "node:path";
import fsp from "node:fs/promises";
//#region src/node/fileCopy.ts
/**
* 将文件拷贝到另一个目录
* @param urls 需要被拷贝的文件路径
* @param destination 目录
* @returns IShellMessage
*/
function fileCopy(urls, destination) {
return jsShell(`cp -r {${urls.join(",")}} ${destination}`, "pipe");
}
//#endregion
//#region src/node/getExportBundle.ts
/**
* 获取npm包导出的文件内容
* @param { string } url npm包名
* @returns
*/
async function getExportBundle(url) {
if (/[./]/.test(url)) throw new Error("module must be a npm module");
const pkg = path.resolve(process.cwd(), "node_modules", url, "package.json");
const { module, main } = JSON.parse(await fsp.readFile(pkg, "utf-8"));
const modulePath = path.resolve(`./node_modules/${url}`, module || main);
return fsp.readFile(modulePath, "utf-8");
}
//#endregion
//#region src/string/ensureSuffix.ts
/**
* 确保后缀有这个字符串
* @param { string } suffix 后缀
* @param { string } str 字符串
* @returns string
*/
function ensureSuffix(suffix, str) {
if (str.endsWith(suffix)) return str;
return str + suffix;
}
//#endregion
//#region src/node/getPkg.ts
/**
* 获取当前package.json 对象
* @param { string } url 路径 默认 ./package.json
* @returns 返回json格式package.json
*/
async function getPkg(url = "./package.json") {
const resolvedPath = toAbsolutePath(ensureSuffix("/package.json", url));
if (!isFile(resolvedPath)) throw new Error(`${resolvedPath} is not a file`);
return JSON.parse(await fsp.readFile(resolvedPath, "utf-8"));
}
//#endregion
//#region src/node/getPkgTool.ts
/**
* 获取当前包管理器 ‘yarn’ | 'pnpm' | 'bun' | 'npm'
* @returns 返回当前package环境 ‘yarn’ | 'pnpm' | 'bun' | 'npm'
*/
async function getPkgTool() {
const pkg = await getPkg() || {};
const { packageManager } = pkg;
if (packageManager) {
const manager = packageManager.split("@")[0].replace(/[~^]/, "");
if (packageManager) return manager;
}
switch (true) {
case isFile(toAbsolutePath("./bun.lockb")): return "bun";
case isFile(toAbsolutePath("./pnpm-lock.yaml")):
case isFile(toAbsolutePath("./pnpm-workspace.yaml")): return "pnpm";
case isFile(toAbsolutePath("./yarn.lock")):
case isFile(toAbsolutePath("./lerna.json")): return "yarn";
default: return "npm";
}
}
//#endregion
//#region src/node/transformArgv.ts
/**
*
* @returns 处理argv --flag如果未设置值默认为true
*/
function transformArgv() {
var _process$argv;
return process === null || process === void 0 || (_process$argv = process.argv) === null || _process$argv === void 0 ? void 0 : _process$argv.slice(2).reduce((result, arg) => {
const [key, value] = arg.split("=");
result[key.slice(2)] = value || true;
return result;
}, {});
}
//#endregion
//#region src/node/withTaskName.ts
/**
* 处理gulp任务
* @param name 任务名
* @param fn 任务函数
* @returns
*/
function withTaskName(name, fn) {
return Object.assign(fn, { displayName: name });
}
//#endregion
//#region src/node/writeFile.ts
/**
* 重写文件
* @param { string } paths 路径
* @param { (content: string, index: number) => string } callback 回调接收文件字符串将返回的内容重新写入该文件
* @param { string } [encoding] 默认 'utf-8'
*/
function writeFile(paths, callback, encoding = "utf-8") {
if (isStr(paths)) paths = [paths];
paths.forEach(async (relativepath, i) => {
const content = await fsp.readFile(relativepath, encoding);
const result = (callback === null || callback === void 0 ? void 0 : callback(content, i)) || content;
fsp.writeFile(relativepath, result).catch((err) => {
throw err;
});
});
}
//#endregion
//#region src/node/hasPkg.ts
/**
* 判断是否存在package.json
* @param { string } rootPath 绝对路径
* @returns boolean
*/
async function hasPkg(rootPath) {
const url = path.resolve(rootPath, "package.json");
const { result } = await jsShell(`test -f "${url}" && echo "0"|| echo "1"`, "pipe");
return result === "0";
}
//#endregion
//#region src/node/isInstallPkg.ts
async function isInstallPkg(pkg) {
const { status } = await jsShell(`if ! command -v ${pkg} &> /dev/null; then
exit 1
else
exit 0
fi`);
return status === 0;
}
//#endregion
//#region src/node/isExist.ts
/**
* 判断文件是否存在
* @param url
* @returns
*/
function isExist(url) {
try {
fs.accessSync(toAbsolutePath(url));
return true;
} catch (error) {
return false;
}
}
//#endregion
//#region src/node/isGo.ts
/**
* 判断是否是在go环境
* @returns
*/
async function isGo(rootPath = process.cwd()) {
const url = path.resolve(rootPath, "go.mod");
const { result } = await jsShell(`(test -f "main.go" || test -f "${url}") && echo "0"|| echo "1"`, "pipe");
return result === "0";
}
//#endregion
//#region src/node/isRust.ts
/**
* 判断是否是rust环境
*/
async function isRust(rootPath = process.cwd()) {
const url = path.resolve(rootPath, "Cargo.toml");
const { result } = await jsShell(`test -f "${url}" && echo "0"|| echo "1"`, "pipe");
return result === "0";
}
//#endregion
//#region src/node/isWritable.ts
/**
* 同步地测试用户对 path 指定的文件或目录的权限
* @param { string } filename 文件或目录路径
* @returns
*/
function isWritable(filename) {
try {
fs.accessSync(filename, fs.constants.W_OK);
return true;
} catch {
return false;
}
}
//#endregion
//#region src/node/isPkg.ts
/**
* 判断路径下是否有package.jsons
* @param { string } rootPath 默认 process.cwd()
*/
async function isPkg(rootPath = process.cwd()) {
const url = path.resolve(rootPath.replace(/package.json$/, ""), "package.json");
const { result } = await jsShell(`test -f "${url}" && echo "0"|| echo "1"`, "pipe");
return result === "0";
}
//#endregion
export { fileCopy, getExportBundle, getPkg, getPkgTool, hasPkg, isExist, isGo, isInstallPkg, isPkg, isRust, isWritable, jsShell, transformArgv, useNodeWorker, useProcressNodeWorker, withTaskName, writeFile };