commander#Command TypeScript Examples

The following examples show how to use commander#Command. 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: WikiCommander.ts    From joplin-utils with MIT License 6 votes vote down vote up
wikiCommander = () => {
  const wikiCommanderProgram = new WikiCommanderProgram()
  return new Command('wiki')
    .addCommand(
      new Command('clean').description(i18n.t('common.cache.clean')).action(() => wikiCommanderProgram.clean()),
    )
    .description(i18n.t('wiki.description'))
    .action(() => wikiCommanderProgram.main())
}
Example #2
Source File: index.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export function registerMigrateCommand(program: Command) {
  const command = program
    .command('migrate [command]')
    .description('Migration utilities');

  command
    .command('package-roles')
    .description(`Add package role field to packages that don't have it`)
    .action(lazy(() => import('./migrate/packageRole').then(m => m.default)));

  command
    .command('package-scripts')
    .description('Set package scripts according to each package role')
    .action(
      lazy(() => import('./migrate/packageScripts').then(m => m.command)),
    );

  command
    .command('package-lint-configs')
    .description(
      'Migrates all packages to use @backstage/cli/config/eslint-factory',
    )
    .action(
      lazy(() => import('./migrate/packageLintConfigs').then(m => m.command)),
    );
}
Example #3
Source File: index.ts    From markmap with MIT License 6 votes vote down vote up
export function main(version: string) {
  const program = new Command();
  program
    .version(version)
    .description('Create a markmap from a Markdown input file')
    .arguments('<input>')
    .option('--no-open', 'do not open the output file after generation')
    .option('--no-toolbar', 'do not show toolbar')
    .option('-o, --output <output>', 'specify filename of the output HTML')
    .option(
      '-w, --watch',
      'watch the input file and update output on the fly, note that this feature is for development only'
    )
    .action(async (input, cmd) => {
      const content = await fs.readFile(input, 'utf8');
      const output = cmd.output || `${input.replace(/\.\w*$/, '')}.html`;
      if (cmd.watch) {
        await develop(input, {
          open: cmd.open,
          toolbar: cmd.toolbar,
        });
      } else {
        await createMarkmap({
          content,
          output,
          open: cmd.open,
          toolbar: cmd.toolbar,
        });
      }
    });
  program.parse(process.argv);
}
Example #4
Source File: index.ts    From terraform-visual with MIT License 6 votes vote down vote up
async function main() {
  const callerPath = process.cwd()

  const program = new Command()

  program.option('--out <path>', 'set the output dir', callerPath)
  program.requiredOption('--plan <path>', 'set the relative path to Terraform plan')
  program.parse(process.argv)

  // TODO: validation
  const inputOpts = program.opts() as InputOpts
  const outDirPath = path.resolve(callerPath, inputOpts.out, 'terraform-visual-report')
  const planFilePath = path.resolve(callerPath, inputOpts.plan)

  console.log(`outDirPath:   ${outDirPath}`)
  console.log(`planFilePath: ${planFilePath}`)

  await fs.copy(TEMPLATE_DIST_PATH, outDirPath)

  const tfBuffer = await fs.readFile(planFilePath)
  const tfContent = tfBuffer.toString()
  await fs.writeFile(path.resolve(outDirPath, 'plan.js'), `window.TF_PLAN = ${tfContent}`)

  const indexFilePath = path.resolve(outDirPath, 'index.html')
  console.log('')
  console.log('\x1b[32m%s\x1b[0m', 'Report generated successfully!')
  console.log('\x1b[32m%s\x1b[0m', `Please run "open ${path.relative(callerPath, indexFilePath)}"`)
}
Example #5
Source File: getCliOptions.ts    From build-scripts with MIT License 6 votes vote down vote up
module.exports = (program: Command): IHash<JsonValue> => {
  const cliOptions: IHash<JsonValue> = {};
  program.options.forEach((option: Option): void => {
    const key = camelcase(option.long, {
      pascalCase: false,
    });

    // 不传参数时是 undefined,这里不判断的话,lib/build 里跟 default 参数 merge 会有问题
    // version等参数的类型为function,需要过滤掉
    if (program[key] !== undefined && typeof program[key] !== 'function') {
      cliOptions[key] = program[key];
    }
  });

  return cliOptions;
};
Example #6
Source File: index.ts    From joplin-blog with MIT License 6 votes vote down vote up
(async () => {
  await i18n.load(await i18n.getLanguage())

  new Command()
    .addCommand(blogCommander())
    .addCommand(wikiCommander())
    .description('joplin-blog')
    .action(() => new BlogCommanderProgram().main())
    .parse()
})()
Example #7
Source File: BlogCommander.ts    From joplin-utils with MIT License 6 votes vote down vote up
blogCommander = () => {
  const blogCommanderProgram = new BlogCommanderProgram()
  return new Command('blog')
    .addCommand(
      new Command('clean').description(i18n.t('common.cache.clean')).action(() => blogCommanderProgram.clean()),
    )
    .description(i18n.t('blog.description'))
    .action(() => blogCommanderProgram.main())
}
Example #8
Source File: command.ts    From engine with MIT License 6 votes vote down vote up
command: producer = ({
  _command = Command,
  version = observe.config.version,
  startCreate = update.create.triggers.start,
}: props) => {
  if (!version) {
    return;
  }

  const program = new _command();

  program.version(version).usage("<command> [options]");

  program
    .command("create <app-name>")
    .description("Create a new engine project")
    .option(
      "-t, --template <template>",
      "If the template name starts with @, then then the template package used will match the option value\nOtherwise, the template package used will be @c11/template.<template>",
      "@c11/engine.template-react"
      // "cra-template-engine"
    )
    .action((name: string, options, cmd) => {
      const opts = cmd.opts();
      startCreate.set({
        name,
        template: opts.template,
      });
    });

  program.parse(process.argv);
}
Example #9
Source File: index.ts    From joplin-utils with MIT License 6 votes vote down vote up
(async () => {
  await i18n.init({ en, zhCN }, await getLanguage())

  new Command()
    .addCommand(blogCommander())
    .addCommand(wikiCommander())
    .description('joplin-blog')
    .action(() => new BlogCommanderProgram().main())
    .parse()
})()
Example #10
Source File: main.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export function run(): void {
    let program = new Command()

    program.description(`
Generates TypeScript definitions for chain events and extrinsics
for use within substrate-processor mapping handlers.
    `.trim())

    program.argument('config', 'JSON file with options')

    let configFile = program.parse().args[0]

    try {
        let config = readConfig(configFile)
        Typegen.generate(config)
    } catch(e: any) {
        printError(e)
        process.exit(1)
    }
}
Example #11
Source File: cli.ts    From ytdl with MIT License 6 votes vote down vote up
/**
 * Sets options in the `program`.
 * @param program Stores the commander.Command object
 */
function setOptions(program: commander.Command): void {
    program
        .option('-l, --link <url>', 'set the url for the YouTube video')
        .option('-n, --name <name>', 'search by name instead of link')
        .option('-i, --info', 'info about YouTube link')
        .option('-d, --download', 'download from YouTube link')
        .option('-p, --play', 'play YouTube media in your media player')
        .option('--set-player <media-player>', 'set the media player')
        .option('-fn, --filename <filename>', 'filename of downloaded content')
        .option('-q, --quality <quality>', 'quality of downloaded content')
        .option('-s, --size', 'get the size of the video to be downloaded')
        .option('-ao, --audio-only', 'download only audio stream')
        .option('-vo, --video-only', 'download only video stream');
}
Example #12
Source File: index.ts    From anchorcli with Apache License 2.0 6 votes vote down vote up
export function run(argv: string[]): void {
  try {
    program
      .name('anchorcli')
      .version('0.0.1')
      .option('-v,--verbose', 'Show verbose error logs')
      .description(
        'Command-line interface for interacting with Anchor Protocol on Terra',
      );
    _.each(commands, (command: Command) => {
      program.addCommand(command);
    });
    program.parse(argv);
  } catch (e) {
    logger.error(e.message);
  }
}
Example #13
Source File: cli.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export function createCli(
  version: string,
  clients: GeneratedClientInfo[],
  customClientNames?: string[],
  customClientsBaseDir?: string,
  program: Command = require('commander'),
): Command {
  program.version(version, '-v, --version')
    .usage('[command] [options]');

  program
    .command('list')
    .description('List all available clients and their clients')
    .option('-s, --save [saveTo]', 'Save information about clients ')
    .action((cmd) => exportList(clients, cmd));

  clients.forEach(client => {
    client.generators.forEach(function (generator) {

      const generationCommand = program
        .command(`${client.name}:${generator.name}`)
        .description(`Generates ${client.name} ${generator.name}`);

      extractAvailableOptions(generator.options).forEach(({pattern, description}) => {
        generationCommand.option(pattern, description);
      });

      program.allowUnknownOption(false);

      generationCommand.action(function (cmd) {
        return generate(generator.path, pickOptions(cmd, generator.options), generator.templateOverride);
      })

    })
  });

  return program;
}
Example #14
Source File: index.ts    From context-mod with MIT License 5 votes vote down vote up
program = new Command()
Example #15
Source File: util.ts    From yarn-audit-fix with MIT License 5 votes vote down vote up
describe('util', () => {
  describe('#mapFlags', () => {
    it('provides cross-util flags conversion', () => {
      const cases: [[TFlags, TFlagsMapping, TFlags]] = [
        [
          {
            only: 'prod',
            'audit-level': 'low',
          },
          {
            'audit-level': 'level',
            only: {
              key: 'groups',
              values: {
                prod: 'dependencies',
                dev: 'devDependencies',
              },
            },
          },
          {
            groups: 'dependencies',
            level: 'low',
          },
        ],
      ]

      cases.forEach(([flags, mapping, result]) => {
        expect(mapFlags(flags, mapping)).toEqual(result)
      })
    })
  })

  describe('#formatArgs', () => {
    it('return proper values', () => {
      const cases: [Record<string, any>, string[], string[]][] = [
        [{ _: [], '--': [] }, [], []],
        [{ foo: 'bar' }, [], ['--foo', 'bar']],
        [{ f: true }, [], ['-f']],
        [{ verbose: true }, [], ['--verbose']],
        [
          { f: true, foo: 'bar', b: true, baz: 'qux' },
          ['f', 'baz'],
          ['-f', '--baz', 'qux'],
        ],
        [
          new Command()
            .option('-w')
            .option('--force')
            .option('--audit-level <level>')
            .option('--bar')
            .option('--only <scope>')
            .option('-b <b>')
            .parse(
              [
                '-w',
                '1',
                '--force',
                '--audit-level=moderate',
                '--only=dev',
                '--',
                '--bar',
                '-b',
                '2',
              ],
              { from: 'user' },
            )
            .opts(),
          ['force', 'audit-level', 'only', 'bar', 'b'],
          ['--force', '--audit-level', 'moderate', '--only', 'dev'],
        ],
      ]

      cases.forEach(([input, picklist, output]) => {
        expect(formatFlags(normalizeFlags(input), ...picklist)).toEqual(output)
      })
    })
  })

  describe('#getSymlinkType', () => {
    it('resolves type by system profile and arg', () => {
      process.env.OSTYPE = 'msys'
      expect(getSymlinkType()).toBe('junction')
      expect(getSymlinkType('foo')).toBe('foo')
      expect(getSymlinkType('dir')).toBe('dir')

      process.env.OSTYPE = 'unknown'
      expect(getSymlinkType()).toBe(
        process.platform === 'win32' ? 'junction' : 'dir',
      )

      process.env.ostype = DEFAULT_OSTYPE
    })
  })

  describe('#getNpm', () => {
    const isWin = isWindows()
    const cmd = isWin ? 'npm.cmd' : 'npm'
    const localNpm = resolve(__dirname, '../../../node_modules/.bin', cmd)
    const cases: [any, string?, string?][] = [
      ['local', localNpm],
      ['system', cmd],
      [cmd, cmd],
      [localNpm, localNpm],
    ]
    cases.forEach(([npmPath, result, err]) => {
      it(`resolves npm ref: npmPath=${npmPath},  isWin=${isWin}`, () => {
        if (err) {
          expect(() => getNpm(npmPath)).toThrowError()
        } else {
          expect(getNpm(npmPath)).toBe(result)
        }
      })
    })
  })

  describe('#getTemp', () => {
    it('properly resolves temp dir path', () => {
      const pwd = process.cwd()
      const tempdir = resolve(__dirname, '../temp')
      const cases: [string, string | undefined, string][] = [
        [pwd, tempdir, tempdir],
        [pwd, undefined, resolve(pwd, 'node_modules/.cache/yarn-audit-fix')],
      ]

      cases.forEach(([cwd, temp, result]) => {
        expect(getTemp(cwd, temp)).toMatch(result)
      })
    })
  })

  describe('getWorkspaces', () => {
    it('returns paths of found package.json files', () => {
      const cwd = resolve(__dirname, '../fixtures/regular-monorepo')
      const manifest = readJson(join(cwd, 'package.json'))
      const files = getWorkspaces(cwd, manifest)
      const expected = ['a', 'b'].map((p) =>
        join(cwd, 'packages', p, 'package.json'),
      )

      expect(files).toEqual(expected)
    })
  })
})
Example #16
Source File: index.ts    From micropython-ctl with MIT License 5 votes vote down vote up
program = new Command()
Example #17
Source File: cli.ts    From homebridge-samsungtv-control2 with MIT License 5 votes vote down vote up
program = new Command()
Example #18
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
program = new Command()
Example #19
Source File: index.ts    From nota with MIT License 5 votes vote down vote up
commonOpts = (cmd: Command): Command =>
  cmd.argument("<file>").option("-c, --config <path>", "Path to config file")
Example #20
Source File: BlogCommander.ts    From joplin-blog with MIT License 5 votes vote down vote up
blogCommander = () =>
  new Command('blog')
    .description(
      i18n.t(
        'blog.Generate the files needed for the blog based on the notes in Joplin',
      ),
    )
    .action(() => new BlogCommanderProgram().main())
Example #21
Source File: cli.ts    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
export function launchCli(program: Command) {
  program.parse(process.argv); // invokes provided command

  if (!process.argv.slice(2).length) {
    program.outputHelp()
  }
}
Example #22
Source File: index.ts    From context-mod with MIT License 5 votes vote down vote up
preRunCmd = new Command()
Example #23
Source File: SeedCommand.ts    From node-experience with MIT License 5 votes vote down vote up
Seed = new Command('seed')
Example #24
Source File: main.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
export function run() {
    let program = new Command()

    program.description(`
Explores chain spec versions.

It scans the chain and finds all blocks where new spec version was introduced.
The result of exploration is saved in a json file:

[
    {
        "specVersion": 1,
        "blockNumber": 10,
        "blockHash": "0x..",
        "metadata": "0x.."
    },
    ...
]

If the output file already exists, exploration will start from the last known block.
The resulting file will be updated with new data.
`.trim())

    program.usage('squid-substrate-metadata-explorer --chain <ws://> --out <file> [options]')
    program.requiredOption('--chain <ws://>', 'chain rpc endpoint', urlOptionValidator(['ws:', 'wss:']))
    program.requiredOption('--out <file>', 'output file')
    program.option(
        '--archive <url>',
        'squid substrate archive (significantly speedups exploration)',
        urlOptionValidator(['http:', 'https:'])
    )

    let options = program.parse().opts() as {
        chain: string
        out: string
        archive?: string
    }

    let fromBlock = 0
    let initialData: ChainVersion[] | undefined
    if (fs.existsSync(options.out)) {
        initialData = JSON.parse(fs.readFileSync(options.out, 'utf-8'))
        initialData?.sort((a, b) => a.blockNumber - b.blockNumber)
    }
    if (initialData?.length) {
        fromBlock = initialData[initialData.length - 1].blockNumber
        console.log(`output file has explored versions, will continue from there and augment the file`)
    }

    if (fromBlock > 0) {
        console.log(`starting from block: ${fromBlock}`)
    }

    exploreChainVersions({
        chainEndpoint: options.chain,
        archiveEndpoint: options.archive,
        fromBlock,
        log: msg => console.log(msg)
    }).then(versions => {
        let data = initialData ? initialData.concat(versions.slice(1)) :  versions
        fs.writeFileSync(options.out, JSON.stringify(data, null, 2))
    }).catch(err => {
        console.error(err)
        process.exit(1)
    })
}
Example #25
Source File: CreateFolderLogger.ts    From node-experience with MIT License 5 votes vote down vote up
CreateFolderLogger = new Command('createFolderLogger')
Example #26
Source File: index.ts    From reactant with MIT License 5 votes vote down vote up
command = new Command() as Command
Example #27
Source File: options.impl.ts    From dm with MIT License 5 votes vote down vote up
export function parseOpts (cli: Command): Partial<IOpts> {
  const opts: Partial<IOpts> = cli.opts();

  // version 默认为 function 传参时变为string
  if (typeof opts.version === 'function') {
    opts.version = undefined
  }

  // cli.name 默认为 function 传参时变为string
  if (typeof cli.name === 'function') {
    opts.name = undefined;
  }

  if (opts['output.build']) {
    opts.output = {
      build: path.resolve(opts['output.build'])
    }
    delete opts['output.build']
  } else if (opts['output.audit']) {
    opts.output = {
      build: path.resolve(opts['output.audit'])
    }
    delete opts['output.audit']
  } else if (opts['output.preview']) {
    opts.output = {
      build: path.resolve(opts['output.preview'])
    }
    delete opts['output.preview']
  } else if (opts['output.upload']) {
    opts.output = {
      build: path.resolve(opts['output.upload'])
    }
    delete opts['output.upload']
  }

  for (const key in opts) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    if (typeof opts[key] === 'undefined') delete opts[key];
  }

  if (opts.debug) {
    log.setLevel(LogLevel.debug);
  }

  log.debug('opts:', opts)

  return opts
}
Example #28
Source File: query.ts    From anchorcli with Apache License 2.0 5 votes vote down vote up
command = new Command('query')
Example #29
Source File: cli.ts    From ytdl with MIT License 5 votes vote down vote up
/**
 * Parses the options specified in `program`.
 * @param program Stores the commander.Command program
 */
async function parseOptions(program: commander.Command): Promise<void> {
    const programOpts = program.opts();
    let optionsCount = 0;
    Object.keys(programOpts).forEach((programOpt) => {
        if (programOpts[programOpt]) optionsCount += 1;
    });

    if (optionsCount <= 1) program.help();

    if (
        (
            program.download
            || program.info
            || program.size
            || program.play
        )
        && !(program.link || programOpts.name)
    ) {
        logger.error('Link or name not specified, use -l or --link to specify link, -n or --name to specify name.');
        return;
    }

    let ytdl;
    if (program.link) {
        ytdl = await Ytdl.init(program.link);
    } else if (programOpts.name) {
        ytdl = await Ytdl.fromName(programOpts.name);
    }
    ytdl.setLogLevel('info');

    const options = {
        audioOnly: !!program.audioOnly,
        videoOnly: !!program.videoOnly,
    };

    const quality = program.quality || 'any';
    if (program.size) {
        logger.info(`Size: ${ytdl.info.size(quality)}`);
    }

    if (program.info) {
        const {
            id,
            title,
            time,
            description,
        } = ytdl.info.all();

        logger.info(`Video ID: ${id}`);
        logger.info(`Video Title: ${title}`);
        logger.info(`Video Time: ${time}`);
        logger.info(`Video Description:\n ${description}`);
    }

    if (program.play) {
        const player = await ytdl.play(quality, options, program.setPlayer);
        logger.info(`Playing on ${player.player}.`);
    }

    if (program.download) {
        const filename = program.filename || `${ytdl.info.videoTitle}.mp4`;

        // TODO: download by itag
        logger.info(`Downloading: ${ytdl.info.videoTitle}`);

        await ytdl.download(quality, filename, options);
    }
}