| 1 | import path from "path"; |
| 2 | import fs from "fs"; |
| 3 | import pc from "picocolors"; |
| 4 | |
| 5 | const fileContent = (name: string) => `const completionSpec: Fig.Spec = { |
| 6 | name: "${name}", |
| 7 | description: "", |
| 8 | subcommands: [{ |
| 9 | name: "my_subcommand", |
| 10 | description: "Example subcommand", |
| 11 | subcommands: [{ |
| 12 | name: "my_nested_subcommand", |
| 13 | description: "Nested subcommand, example usage: '${name} my_subcommand my_nested_subcommand'" |
| 14 | }], |
| 15 | }], |
| 16 | options: [{ |
| 17 | name: ["--help", "-h"], |
| 18 | description: "Show help for ${name}", |
| 19 | }], |
| 20 | // Only uncomment if ${name} takes an argument |
| 21 | // args: {} |
| 22 | }; |
| 23 | export default completionSpec;`; |
| 24 | |
| 25 | export function createCompletionSpec(specName: string, autocompleteFolder: string) { |
| 26 | const sanitizedSpecName = specName.replace(" ", "-"); |
| 27 | const filePath = path.join(autocompleteFolder, `${sanitizedSpecName}.ts`); |
| 28 | const dirName = path.dirname(filePath); // we do not use parentDir directly cause specName may be nested e.g. `aws/spec` |
| 29 | |
| 30 | if (fs.existsSync(filePath)) { |
| 31 | console.log(pc.red("This completion spec already exists")); |
| 32 | console.log(pc.bold(`Start editing it from the src/${sanitizedSpecName}.ts now!`)); |
| 33 | return; |
| 34 | } |
| 35 | try { |
| 36 | fs.mkdirSync(dirName, { recursive: true }); |
| 37 | fs.writeFileSync(filePath, fileContent(sanitizedSpecName)); |
| 38 | console.log(pc.green(`Successfully created the new spec ${sanitizedSpecName}`)); |
| 39 | console.log(`Start editing it at ${pc.bold(`src/${sanitizedSpecName}.ts`)}!`); |
| 40 | } catch { |
| 41 | throw new Error(`An error occurred while creating the new "${sanitizedSpecName}" spec.`); |
| 42 | } |
| 43 | } |