yargs#CommandModule TypeScript Examples

The following examples show how to use yargs#CommandModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: approve.ts    From pdf-visual-diff with MIT License 6 votes vote down vote up
approve: CommandModule<unknown, Arguments> = {
  command: 'approve',
  describe: 'Approve new snapshots',
  builder: {
    path: {
      alias: 'p',
      default: '.',
    },
    'snapshots-dir-name': {
      alias: 's',
      default: '__snapshots__',
    },
  },
  handler: ({ path, snapshotsDirName }) => {
    return findImages(path, snapshotsDirName).then((files) => {
      const execDirLength = process.cwd().length
      const filesOutput = files.map((x) => '.' + x.substring(execDirLength)).join('\n')
      return askForConfirmation(`
New snapshots:          
${filesOutput}
Are you sure you want to overwrite current snapshots?`).then((overwrite) => {
        if (overwrite) {
          return Promise.all(
            files.map((x) =>
              fs.rename(x, mkCurrentSnapshotPath(x)).then(() => fs.unlink(mkDiffSnapshotPath(x))),
            ),
          ).then(() => console.log('Success! Snapshots are overwritten.'))
        }
        console.log('Command was discarded! No changes were made.')
        return Promise.resolve()
      })
    })
  },
}
Example #2
Source File: discard.ts    From pdf-visual-diff with MIT License 6 votes vote down vote up
discard: CommandModule<unknown, Arguments> = {
  command: 'discard',
  describe: 'Discard new snapshots and diffs',
  builder: {
    path: {
      alias: 'p',
      default: '.',
    },
    'snapshots-dir-name': {
      alias: 's',
      default: '__snapshots__',
    },
  },
  handler: ({ path, snapshotsDirName }) => {
    return findImages(path, snapshotsDirName, '*.@(new|diff).png').then((files) => {
      const execDirLength = process.cwd().length
      const filesOutput = files.map((x) => '.' + x.substring(execDirLength)).join('\n')
      return askForConfirmation(`
New snapshots and diff images:          
${filesOutput}
Are you sure you want to remove them all?`).then((overwrite) => {
        if (overwrite) {
          return Promise.all(files.map((x) => fs.unlink(x))).then(() =>
            console.log('Success! New snapshots and diff images removed.'),
          )
        }
        console.log('Command was discarded! No changes were made.')
        return Promise.resolve()
      })
    })
  },
}
Example #3
Source File: Runner.ts    From mpflow with MIT License 6 votes vote down vote up
/**
   * 注册 CLI 命令
   * @param command
   * @param describe
   * @param positional
   * @param options
   * @param handler
   */
  registerCommand<
    P extends Record<string, PositionalOptions> = Record<string, PositionalOptions>,
    O extends Record<string, Options> = Record<string, Options>
  >(
    command: CommandModule['command'],
    describe: CommandModule['describe'],
    positional: P,
    options: O,
    handler: (args: Arguments<InferredOptionTypes<P> & InferredOptionTypes<O>>) => void,
  ): void {
    this.service.registerCommand(command, describe, positional, options, handler)
  }
Example #4
Source File: Runner.ts    From mpflow with MIT License 6 votes vote down vote up
/**
   * 注册 CLI 命令
   * @param command
   * @param describe
   * @param positional
   * @param options
   * @param handler
   */
  registerCommand<
    P extends Record<string, PositionalOptions> = Record<string, PositionalOptions>,
    O extends Record<string, Options> = Record<string, Options>
  >(
    command: CommandModule['command'],
    describe: CommandModule['describe'],
    positional: P,
    options: O,
    handler: (args: Arguments<InferredOptionTypes<P> & InferredOptionTypes<O>>) => void,
  ): void {
    this._registerCommand(
      command,
      describe,
      yargs => {
        Object.keys(positional).forEach(key => (yargs = yargs.positional(key, positional[key])))
        yargs = yargs.options(options)
        return yargs
      },
      handler,
    )
  }
Example #5
Source File: Runner.ts    From mpflow with MIT License 6 votes vote down vote up
protected _registerCommand(
    command: CommandModule['command'],
    describe: CommandModule['describe'],
    builder: (args: Argv<any>) => Argv<any>,
    handler: (args: any) => void,
  ): void {
    const chalk = require('chalk') as typeof import('chalk')
    this.program.command({
      command,
      describe,
      handler: args => {
        this._commandPromise = (async () => {
          try {
            await handler(args as any)
          } catch (e) {
            console.error(chalk.red(e))
            process.exit(1)
          } finally {
            this._commandPromise = null
          }
        })()
      },
      builder,
    })
  }
Example #6
Source File: completion-fish.ts    From yaclt with Mozilla Public License 2.0 6 votes vote down vote up
CompletionFishCommand: CommandModule<
  Record<string, unknown>,
  GlobalArgv
> = {
  command: "completion-fish",
  describe: "Generate completion script for Fish",
  handler: () => {
    // eslint-disable-next-line no-console
    console.log(`
###-begin-yaclt-completions-###
#
# yargs command completion script
#
# Installation: yaclt completion-fish >> ~/.config/fish/config.fish
complete --no-files --command yaclt --arguments "(yaclt --get-yargs-completions (commandline -cp))"
`);
  },
}
Example #7
Source File: validate-argv-middleware.ts    From yaclt with Mozilla Public License 2.0 6 votes vote down vote up
Commands.forEach((command: CommandModule) => {
  const builderKeys = Object.keys(command.builder ?? {});
  if (builderKeys.length === 0) {
    return;
  }

  allValidOptions.push(...builderKeys);

  for (const key of builderKeys) {
    const alias = (command.builder as Record<string, Options> | undefined)?.[
      key
    ]?.alias;
    if (alias) {
      if (Array.isArray(alias)) {
        allValidOptions.push(...alias);
      } else {
        allValidOptions.push(alias as string);
      }
    }
  }
});
Example #8
Source File: create.ts    From typeorm-extension with MIT License 5 votes vote down vote up
export class DatabaseCreateCommand implements CommandModule {
    command = 'db:create';

    describe = 'Create database.';

    builder(args: Argv) {
        return args
            .option('root', {
                alias: 'r',
                default: process.cwd(),
                describe: 'Path to the data-source / config file.',
            })
            .option('connection', {
                alias: 'c',
                default: 'default',
                describe: 'Name of the connection on which run a query.',
                deprecated: true,
            })
            .option('config', {
                alias: 'f',
                default: 'ormconfig',
                describe: 'Name of the file with the data-source configuration.',
                deprecated: true,
            })
            .option('dataSource', {
                alias: 'd',
                default: 'data-source',
                describe: 'Name of the file with the data-source.',
            })
            .option('synchronize', {
                alias: 's',
                default: 'yes',
                describe: 'Create database schema for all entities.',
                choices: ['yes', 'no'],
            })
            .option('initialDatabase', {
                describe: 'Specify the initial database to connect to.',
            });
    }

    async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseCreateArguments = raw as DatabaseCreateArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        const context : DatabaseCreateContext = {
            ifNotExist: true,
            options: dataSourceOptions,
        };

        if (
            typeof args.initialDatabase === 'string' &&
            args.initialDatabase !== ''
        ) {
            context.initialDatabase = args.initialDatabase;
        }

        context.synchronize = args.synchronize === 'yes';

        await createDatabase(context);

        if (exitProcess) {
            process.exit(0);
        }
    }
}
Example #9
Source File: drop.ts    From typeorm-extension with MIT License 5 votes vote down vote up
export class DatabaseDropCommand implements CommandModule {
    command = 'db:drop';

    describe = 'Drop database.';

    builder(args: Argv) {
        return args
            .option('root', {
                alias: 'r',
                default: process.cwd(),
                describe: 'Path to the data-source / config file.',
            })
            .option('connection', {
                alias: 'c',
                default: 'default',
                describe: 'Name of the connection on which run a query.',
                deprecated: true,
            })
            .option('config', {
                alias: 'f',
                default: 'ormconfig',
                describe: 'Name of the file with the data-source configuration.',
                deprecated: true,
            })
            .option('dataSource', {
                alias: 'd',
                default: 'data-source',
                describe: 'Name of the file with the data-source.',
            });
    }

    async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseDropArguments = raw as DatabaseDropArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        await dropDatabase({
            ifExist: true,
            options: dataSourceOptions,
        });

        if (exitProcess) {
            process.exit(0);
        }
    }
}
Example #10
Source File: seed.ts    From typeorm-extension with MIT License 5 votes vote down vote up
export class SeedCommand implements CommandModule {
    command = 'seed';

    describe = 'Populate the database with an initial data set or generated data by a factory.';

    builder(args: Argv) {
        return args
            .option('root', {
                alias: 'r',
                default: process.cwd(),
                describe: 'Path to the data-source / config file.',
            })
            .option('connection', {
                alias: 'c',
                default: 'default',
                describe: 'Name of the connection on which run a query.',
                deprecated: true,
            })
            .option('config', {
                alias: 'f',
                default: 'ormconfig',
                describe: 'Name of the file with the data-source configuration.',
                deprecated: true,
            })
            .option('dataSource', {
                alias: 'd',
                default: 'data-source',
                describe: 'Name of the file with the data-source.',
            })
            .option('seed', {
                alias: 's',
                describe: 'Specify the seed class to run.',
            });
    }

    async handler(raw: Arguments, exitProcess = true) {
        const args : DatabaseSeedArguments = raw as DatabaseSeedArguments;

        const dataSourceOptions = await buildDataSourceOptions({
            name: args.connection,
            configName: args.config,
            directory: args.root,
            dataSourceName: args.dataSource,
        });

        setDataSourceOptions(dataSourceOptions);

        const dataSource = await useDataSource();

        await runSeeders(dataSource, {
            seedName: args.seed,
        });

        if (exitProcess) {
            process.exit(0);
        }
    }
}
Example #11
Source File: index.ts    From yaclt with Mozilla Public License 2.0 5 votes vote down vote up
Commands: CommandModule<any, any>[] = [
  NewCommand,
  ValidateCommand,
  PrepareReleaseCommand,
  CompletionFishCommand,
]
Example #12
Source File: prepare-release.ts    From yaclt with Mozilla Public License 2.0 5 votes vote down vote up
PrepareReleaseCommand: CommandModule<
  Record<string, unknown>,
  PrepareReleaseCommandOptions
> = {
  command: "prepare-release",
  describe:
    "Gather the changelogs from `--logsDir` and compile them into `--changelogFile` using `--changelogTemplate`",
  builder: {
    changelogTemplate: {
      type: "string",
      describe:
        "The Handlebars template to use to generate the changelog additions. Can be a filepath to read the template from, or a template literal string.",
      demandOption: false,
      default: defaultChangelogTemplate,
    },
    releaseNumber: {
      type: "string",
      describe: "A label for the release",
      demandOption: true,
    },
    releaseBranchPattern: {
      type: "string",
      describe:
        "A pattern to generate a release branch name which will be automatically checked out before preparing the release.",
      demandOption: false,
    },
    edit: {
      describe:
        "After compiling the gathered changelogs, open the chagelog file in `$EDITOR`, if `$EDITOR` is defined",
      type: "boolean",
      default: false,
      demandOption: false,
    },
    ...ValidateCommandOptions,
    prePrepare: {
      describe:
        "A hook function to run before preparing the release changes. Throw an error or return false to halt execution. Only usable from a Javascript configuration file. May be async.",
      demandOption: false,
      hidden: true,
    },
    postPrepare: {
      describe:
        "A hook function to run after preparing the release changes. Only usable from a Javascript configuration file. May be async.",
      demandOption: false,
      hidden: true,
    },
    ...CliOptions,
  },
  handler: async (argv: Arguments<PrepareReleaseCommandOptions>) => {
    await runAction(async () => {
      const options: ActionPrepareReleaseOptions = {
        plumbing: argv.plumbing,
        changeTypes: argv.changeTypes,
        changelogFile: argv.changelogFile,
        logsDir: argv.logsDir,
        format: argv.format,
        validationPattern: argv.validationPattern,
        releaseBranchPattern: argv.releaseBranchPattern,
        edit: argv.edit ?? false,
        preValidate: argv.preValidate,
        postValidate: argv.postValidate,
        prePrepare: argv.prePrepare,
        postPrepare: argv.postPrepare,
        releaseNumber: argv.releaseNumber,
        template: argv.changelogTemplate,
      };

      await ActionPrepareRelease(options);
    });
  },
}
Example #13
Source File: validate.ts    From yaclt with Mozilla Public License 2.0 5 votes vote down vote up
ValidateCommand: CommandModule<
  Record<string, unknown>,
  ValidateCommandOptions
> = {
  command: "validate",
  describe: "Validate existing changelogs against the specified format",
  builder: options,
  handler: (argv: Arguments<ValidateCommandOptions>) => {
    if (
      argv.format === options["format"]?.default &&
      argv.validationPattern !== options["validationPattern"]?.default
    ) {
      Logger.warn(
        "Using default value for --format but not for --validationPattern. Most likely you want to use a custom value for --format."
      );
    }

    if (
      argv.validationPattern === options["validationPattern"]?.default &&
      argv.format !== options["format"]?.default
    ) {
      Logger.warn(
        "Using default value for --validationPattern but not --format. Most likely you want to use a custom value for --validationPattern."
      );
    }

    runAction(() => {
      const options: ActionValidateOptions = {
        plumbing: argv.plumbing,
        logsDir: argv.logsDir,
        format: argv.format,
        changeTypes: argv.changeTypes,
        validationPattern: argv.validationPattern,
        preValidate: argv.preValidate,
        postValidate: argv.postValidate,
      };

      ActionValidate(options);
    });
  },
}
Example #14
Source File: new.ts    From yaclt with Mozilla Public License 2.0 4 votes vote down vote up
NewCommand: CommandModule<
  Record<string, unknown>,
  NewCommandOptions
> = {
  command: "new",
  describe: "Generate a new changelog entry",
  builder: {
    issueId: {
      describe:
        "The issue ID to be interpolated into the new changelog. Takes precedence over parsing from git branch based on --branchFormat",
      type: "string",
      demandOption: false,
    },
    message: {
      alias: "m",
      describe: "The change log message, defaults to a placeholder message",
      type: "string",
      demandOption: false,
    },
    lastCommit: {
      describe:
        "Use the first line of the most recent git commit message as the message for the new changelog entry",
      type: "boolean",
      demandOption: false,
      conflicts: "message",
    },
    changeType: {
      describe:
        "The change type tag to use, defaults to the first one defined in --changeTypes",
      type: "string",
      demandOption: false,
    },
    entryFileName: {
      describe:
        "Pass a custom entry filename. If using a JS config file and this is a function, it will be passed an instance of `DateTime` from Luxon representing the current timestamp. See Luxon documentation for `DateTime` API.",
      type: "string",
      demandOption: false,
    },
    edit: {
      describe:
        "After generating the changelog file, open it in `$EDITOR`, if `$EDITOR` is defined",
      type: "boolean",
      default: false,
      demandOption: false,
    },
    preNew: {
      describe:
        "A hook function to run before generating the changelog. Throw an error or return false to halt execution. Only usable from a Javascript config file. May be async.",
      demandOption: false,
      hidden: true,
    },
    postNew: {
      describe:
        "A hook function to run after generating the changelog. Only usable from a Javascript config file. May be async.",
      demandOption: false,
      hidden: true,
    },
    ...CliOptions,
  },
  handler: async (argv: Arguments<NewCommandOptions>) => {
    await runAction(async () => {
      if (argv.changeType && !argv.changeTypes.includes(argv.changeType)) {
        const message = `Invalid change type: ${argv.changeType}`;
        Logger.error(message);
        yargs.exit(1, new Error(message));
        return;
      }

      const options: ActionNewOptions = {
        plumbing: argv.plumbing,
        logsDir: argv.logsDir,
        format: argv.format,
        changeType:
          argv.changeType ??
          argv.changeTypes[0] ??
          StringFormatParams.changeType,
        issueId: argv.issueId,
        gitBranchFormat: argv.branchFormat,
        message: argv.message,
        entryFileName: argv.entryFileName,
        edit: argv.edit ?? false,
        preNew: argv.preNew,
        postNew: argv.postNew,
      };

      await ActionNew(options);
    });
  },
}