|
| 1 | +import commander from "commander"; |
| 2 | +import { read as readBedrockYaml } from "../../lib/bedrockYaml"; |
| 3 | +import { build as buildCmd, exit as exitCmd } from "../../lib/commandBuilder"; |
| 4 | +import { logger } from "../../logger"; |
| 5 | +import decorator from "./get-display-name.decorator.json"; |
| 6 | +import { build as buildError, log as logError } from "../../lib/errorBuilder"; |
| 7 | +import { errorStatusCode } from "../../lib/errorStatusCode"; |
| 8 | + |
| 9 | +export interface CommandOptions { |
| 10 | + path: string | undefined; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Executes the command, can all exit function with 0 or 1 |
| 15 | + * when command completed successfully or failed respectively. |
| 16 | + * |
| 17 | + * @param opts validated option values |
| 18 | + * @param exitFn exit function |
| 19 | + */ |
| 20 | +export const execute = async ( |
| 21 | + opts: CommandOptions, |
| 22 | + exitFn: (status: number) => Promise<void> |
| 23 | +): Promise<void> => { |
| 24 | + // The assumption is that this command should be ran from the directory where bedrock.yaml exists |
| 25 | + try { |
| 26 | + if (!opts.path) { |
| 27 | + throw buildError( |
| 28 | + errorStatusCode.VALIDATION_ERR, |
| 29 | + "service-get-display-name-path-missing-param-err" |
| 30 | + ); |
| 31 | + } |
| 32 | + const bedrockFile = readBedrockYaml(process.cwd()); |
| 33 | + if (!bedrockFile) { |
| 34 | + throw buildError( |
| 35 | + errorStatusCode.FILE_IO_ERR, |
| 36 | + "service-get-display-name-bedrock-yaml-missing-err" |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + const serviceIndex = Object.keys(bedrockFile.services).find( |
| 41 | + (index) => opts.path === bedrockFile.services[+index].path |
| 42 | + ); |
| 43 | + |
| 44 | + if (serviceIndex) { |
| 45 | + console.log(bedrockFile.services[+serviceIndex].displayName); |
| 46 | + await exitFn(0); |
| 47 | + } |
| 48 | + |
| 49 | + throw buildError(errorStatusCode.ENV_SETTING_ERR, { |
| 50 | + errorKey: "service-get-display-name-err", |
| 51 | + values: [opts.path], |
| 52 | + }); |
| 53 | + } catch (err) { |
| 54 | + logError( |
| 55 | + buildError( |
| 56 | + errorStatusCode.VALIDATION_ERR, |
| 57 | + "service-get-display-name-generic-err", |
| 58 | + err |
| 59 | + ) |
| 60 | + ); |
| 61 | + await exitFn(1); |
| 62 | + } |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Adds the get-display-name command to the commander command object |
| 67 | + * @param command Commander command object to decorate |
| 68 | + */ |
| 69 | +export const commandDecorator = (command: commander.Command): void => { |
| 70 | + buildCmd(command, decorator).action(async (opts: CommandOptions) => { |
| 71 | + await execute(opts, async (status: number) => { |
| 72 | + await exitCmd(logger, process.exit, status); |
| 73 | + }); |
| 74 | + }); |
| 75 | +}; |
0 commit comments