|
| 1 | +import { findUpSync } from "find-up"; |
| 2 | +import { getTheFileAbsolutePath, output, useConfigPath } from "./utils"; |
| 3 | +import { transformSfc } from "./transform"; |
| 4 | +import { CommandsOption } from "./constants"; |
| 5 | +import writeFile from "./writeFile"; |
| 6 | + |
| 7 | +const CONFIG_FILE_NAME = "tosetup.config" as const; |
| 8 | + |
| 9 | +async function setup() { |
| 10 | + output.log("tosetup begin...\n"); |
| 11 | + const argv = process.argv.slice(2).filter(Boolean); |
| 12 | + |
| 13 | + let { pathNames, commands } = argv.reduce<{ |
| 14 | + pathNames: string[]; |
| 15 | + commands: CommandsOption; |
| 16 | + }>( |
| 17 | + (p, c) => { |
| 18 | + if (c.startsWith("--")) { |
| 19 | + switch (c.split("--")[1] as keyof typeof p.commands) { |
| 20 | + case "propsNotOnlyTs": |
| 21 | + p.commands.propsNotOnlyTs = true; |
| 22 | + break; |
| 23 | + case "notUseNewFile": |
| 24 | + p.commands.notUseNewFile = true; |
| 25 | + break; |
| 26 | + |
| 27 | + default: |
| 28 | + break; |
| 29 | + } |
| 30 | + return p; |
| 31 | + } |
| 32 | + |
| 33 | + const absolutePath = getTheFileAbsolutePath(c); |
| 34 | + if (absolutePath) { |
| 35 | + p.pathNames.push(absolutePath); |
| 36 | + } |
| 37 | + |
| 38 | + return p; |
| 39 | + }, |
| 40 | + { pathNames: [], commands: {} }, |
| 41 | + ); |
| 42 | + |
| 43 | + if (!pathNames.length) { |
| 44 | + const configPath = findUpSync(CONFIG_FILE_NAME); |
| 45 | + if (!configPath) { |
| 46 | + output.error( |
| 47 | + `Please enter a file path or use a ${CONFIG_FILE_NAME} file.`, |
| 48 | + ); |
| 49 | + process.exit(1); |
| 50 | + } |
| 51 | + |
| 52 | + const config = await useConfigPath(CONFIG_FILE_NAME); |
| 53 | + |
| 54 | + pathNames = config.pathNames; |
| 55 | + |
| 56 | + commands = { ...commands, ...config.option }; |
| 57 | + } |
| 58 | + for (const path of pathNames) { |
| 59 | + output.log(`File ${path} start of transform...`); |
| 60 | + const code = transformSfc(path, commands); |
| 61 | + if (code) { |
| 62 | + try { |
| 63 | + const file = writeFile(code, path, commands); |
| 64 | + output.success(`File ${file} transform success.\n`); |
| 65 | + } catch (error) { |
| 66 | + output.error(`write ${path} failure.\n`); |
| 67 | + console.log(error); |
| 68 | + } |
| 69 | + } else { |
| 70 | + output.error(`File ${path} transform failure.\n`); |
| 71 | + } |
| 72 | + } |
| 73 | + output.log("\ntosetup end."); |
| 74 | +} |
| 75 | + |
| 76 | +export default setup; |
0 commit comments