import L from "../../utils/logger"; import fs from "fs"; import path from "path"; function getRelativePath(src: string, dst: string): string { if (src.slice(-1) === "/") { src = src.slice(0, -1); } return src.split("/").reduce((acc) => acc + "../", "") + dst; } async function swapComponent(pairs: [string]): Promise { if (pairs.length % 2 === 1) { L.error("pairs should have even count"); throw new Error("pairs should have even count"); } for (let i = 0; i < pairs.length; i += 2) { const [src, dst] = pairs.slice(i, i + 2); L.info(`swap ${src} into ${dst}...`); try { const srcStat = fs.statSync(src); if (!srcStat.isDirectory()) { L.warn(`${src} is not a directory, skip...`); throw new Error(`${src} is not a directory`); } if ([".js", ".ts"].indexOf(dst.slice(-3)) === -1) { L.warn(`${dst} is not a js or ts file, skip...`); throw new Error(`${dst} is not a js or ts file`); } const dstStat = fs.statSync(dst); if (!dstStat.isFile()) { L.warn(`${dst} is not a js file, skip...`); throw new Error(`${dst} is not a js file`); } fs.writeFileSync( path.join(src, "package.json"), `{"main": "${getRelativePath(src, dst)}"}` ); } catch (ex) { L.warn(`exception raised`); throw ex; } } } export { swapComponent };