UNPKG

unbag

Version:

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

88 lines 3.03 kB
import { ParallelDefaultConfig } from "../commands/parallel/index.mjs"; import { TransformConfigDefault } from "../commands/transform/index.mjs"; import { useFs } from "./fs.mjs"; import { AbsolutePath, usePath } from "../utils/path.mjs"; import { bundleRequire } from "bundle-require"; import { releaseDefaultConfig } from "../commands/release/index.mjs"; import { arraify, filterNullable, Locale } from "./common.mjs"; import { useMessage } from "./message/index.mjs"; import { LogConfigDefault } from "./log.mjs"; import deepFreezeStrict from "deep-freeze-strict"; import _ from "lodash"; import { CommitConfigDefault } from "./../commands/commit/config.mjs"; const useDefaultConfig = () => { const defaultConfig = { root: process.cwd(), locale: Locale.zh_cn, tempDir: "./node_modules/.unbag", log: LogConfigDefault, transform: TransformConfigDefault, parallel: ParallelDefaultConfig, release: releaseDefaultConfig, commit: CommitConfigDefault, catch: () => {} }; return defaultConfig; }; const defineUserConfig = config => config; const resolveUserConfig = async options => { const { filePath, root, locale } = options; const fs = useFs(); const path = usePath(); const message = useMessage({ locale }); if (filePath) { const absoluteFilePath = path.resolve(root.content, filePath); const isExit = await fs.pathExists(absoluteFilePath); if (!isExit) { throw new Error(message.config.file.notFound(absoluteFilePath)); } return await loadUserConfigFromFile(new AbsolutePath({ content: absoluteFilePath })); } else { const configFileDefaultList = ["unbag.config.ts", "unbag.config.js", "unbag.config.cjs", "unbag.config.mjs"]; for (const filePath2 of configFileDefaultList) { const absoluteFilePath = path.resolve(root.content, filePath2); const isExit = await fs.pathExists(absoluteFilePath); if (!isExit) { break; } return await loadUserConfigFromFile(new AbsolutePath({ content: absoluteFilePath })); } } }; async function loadUserConfigFromFile(absoluteFilePath) { const { mod } = await bundleRequire({ filepath: absoluteFilePath.content, format: "esm" }); const config = mod.default || mod; config.configFileResolvedPath = absoluteFilePath; return config; } const mergeDefaultConfig = userConfig => { const defaultConfig = useDefaultConfig(); return mergeConfig(defaultConfig, userConfig || {}); }; const mergeConfig = (defaults, overrides) => { const customize = (objValue, srcValue) => { if (_.isArray(objValue) || _.isArray(srcValue)) { return filterNullable([...arraify(objValue), ...arraify(srcValue)]); } }; return _.mergeWith({}, defaults, overrides, customize); }; const deepFreezeConfig = userConfig => { return deepFreezeStrict(userConfig); }; export { deepFreezeConfig, defineUserConfig, loadUserConfigFromFile, mergeConfig, mergeDefaultConfig, resolveUserConfig, useDefaultConfig };