| 1 | import { Option, Subcommand } from "./convert"; |
| 2 | |
| 3 | function makeSingleOrArray<T>(arr: T[]): Fig.SingleOrArray<T> { |
| 4 | return arr.length === 1 ? (arr[0] as Fig.SingleOrArray<T>) : (arr as Fig.SingleOrArray<T>); |
| 5 | } |
| 6 | |
| 7 | function revertOption<ArgT extends Fig.Arg, OptionT>(option: Option<ArgT, OptionT>): Fig.Option { |
| 8 | const { name, args } = option; |
| 9 | |
| 10 | return { |
| 11 | name: makeSingleOrArray(name), |
| 12 | args, |
| 13 | }; |
| 14 | } |
| 15 | |
| 16 | export function revertSubcommand<ArgT extends Fig.Arg, OptionT, SubcommandT>( |
| 17 | subcommand: Subcommand<ArgT, OptionT, SubcommandT>, |
| 18 | postProcessingFn: ( |
| 19 | oldSub: Subcommand<ArgT, OptionT, SubcommandT>, |
| 20 | newSub: Fig.Subcommand |
| 21 | ) => Fig.Subcommand |
| 22 | ): Fig.Subcommand { |
| 23 | const { name, subcommands, options, persistentOptions, args } = subcommand; |
| 24 | |
| 25 | const newSubcommand: Fig.Subcommand = { |
| 26 | name: makeSingleOrArray(name), |
| 27 | subcommands: |
| 28 | Object.values(subcommands).length !== 0 |
| 29 | ? Object.values(subcommands).map((sub) => revertSubcommand(sub, postProcessingFn)) |
| 30 | : undefined, |
| 31 | options: |
| 32 | Object.values(options).length !== 0 |
| 33 | ? [ |
| 34 | ...Object.values(options).map((option) => revertOption(option)), |
| 35 | ...Object.values(persistentOptions).map((option) => revertOption(option)), |
| 36 | ] |
| 37 | : undefined, |
| 38 | args: Object.values(args).length !== 0 ? makeSingleOrArray(Object.values(args)) : undefined, |
| 39 | }; |
| 40 | return postProcessingFn(subcommand, newSubcommand); |
| 41 | } |