UNPKG

unbag

Version:

一个专门用来开发npm工具的包

108 lines 2.55 kB
import path from "node:path"; import { useFs } from "./../../utils/fs.mjs"; import { sleep } from "../../utils/common.mjs"; const WaitDefaultConfig = { timeout: 1e4, interval: 500 }; const genWaitResAbsoluteFilePath = params => { const { absoluteTempDir, tag } = params; const absoluteFilePath = path.resolve(absoluteTempDir, `${tag}.json`); return absoluteFilePath; }; const writeWaitResFile = async params => { const fs = useFs(); const { absoluteFilePath, content, merge } = params; await fs.modifyJson(absoluteFilePath, oldJson => { if (merge) { return { ...oldJson, ...content }; } else { return content; } }); }; const readWaitResFile = async absoluteFilePath => { const fs = useFs(); try { return fs.readJson(absoluteFilePath); } catch (error) {} }; const WaitCmdName = "parallel-wait"; const checkWaitFile = async params => { const startTime = Date.now(); const { absoluteFilePath, name } = params; const check = async () => { const thisCheckTime = Date.now(); const currentContent = await readWaitResFile(absoluteFilePath); if (!currentContent) { throw Error(); } await writeWaitResFile({ absoluteFilePath, merge: true, content: { lastCheckTime: thisCheckTime } }); const { timeout = WaitDefaultConfig.timeout, interval = WaitDefaultConfig.interval, finish } = currentContent; if (finish) { return { checkTime: thisCheckTime, content: currentContent }; } const timeSpan = thisCheckTime - startTime; if (timeSpan > timeout) { console.log(`${name} wait timeout`); const timeoutContent = { finish: true, result: false, message: "timeout" }; await writeWaitResFile({ absoluteFilePath, merge: true, content: { ...timeoutContent } }); return { checkTime: thisCheckTime, content: { ...currentContent, ...timeoutContent } }; } console.log(`${name} wait ...`); await sleep(interval); return await check(); }; return await check(); }; const genWaitCommand = params => { const { tag, name } = params || {}; let cmd = `unbag ${WaitCmdName} -n ${name} -tg ${tag}`; return cmd; }; export { WaitCmdName, WaitDefaultConfig, checkWaitFile, genWaitCommand, genWaitResAbsoluteFilePath, readWaitResFile, writeWaitResFile };