当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript commander.Command类代码示例

本文整理汇总了TypeScript中commander.Command的典型用法代码示例。如果您正苦于以下问题:TypeScript Command类的具体用法?TypeScript Command怎么用?TypeScript Command使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Command类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: main

export default function main(
  argv: string[],
  stdout: NodeJS.WritableStream,
  stderr: NodeJS.WritableStream,
  exit: (code?: number) => never
) {
  const program = new commander.Command();
  setCommandOptions(program).parse(argv);

  if (program.args.length < 1) {
    program.outputHelp();
    exit(1);
  }

  const log = new Logger(program.color, stdout, stderr);

  program.args.forEach(file => {
    log.warn(`File: ${file}\n`);
    const code = fs.readFileSync(file, 'utf8');
    try {
      const generated = generate(code);
      if (generated) {
        const relativePath = path.relative(`${__dirname}/../closure-library`, file);
        const filepath = path
          .join(`${__dirname}/../closure-library.d.ts`, relativePath)
          .replace(/\.js$/, '.d.ts');
        mkdirp.sync(path.dirname(filepath));
        fs.writeFileSync(filepath, generated);
      }
    } catch (e) {
      console.error(file, e);
    }
  });
}
开发者ID:teppeis,项目名称:closure-ts,代码行数:34,代码来源:cli.ts

示例2: Command

const createProgramAndRegister = (script: Scripts) => {
	const program = new Command();

	registeredPrograms[script] = program;
	program.version(TOOLS_PKG.version);

	return program;
};
开发者ID:sutarmin,项目名称:dx-platform,代码行数:8,代码来源:program.ts

示例3: async

    execute: async (programArgs:string[]) => {

      const program = new Command();

      // Callback for command success
      let onResolve:any;

      // Callback for command rejection
      let onReject:any = () => Promise.reject(Error("Uninitilized rejection throw"));

      // Command execution promise
      const currentCommand = new Promise((resolve, reject) => {
        onResolve = resolve;
        onReject = reject;
      });

      program
        .version(pjson.version)
        .usage('<command> [options]')

        .option('--home <path>', 'Path to Duniter HOME (defaults to "$HOME/.config/duniter").')
        .option('-d, --mdb <name>', 'Database name (defaults to "duniter_default").')

        .option('--autoconf', 'With `config` and `init` commands, will guess the best network and key options witout asking for confirmation')
        .option('--addep <endpoint>', 'With `config` command, add given endpoint to the list of endpoints of this node')
        .option('--remep <endpoint>', 'With `config` command, remove given endpoint to the list of endpoints of this node')

        .option('--cpu <percent>', 'Percent of CPU usage for proof-of-work computation', parsePercent)

        .option('-c, --currency <name>', 'Name of the currency managed by this node.')

        .option('--nostdout', 'Disable stdout printing for `export-bc` command')
        .option('--noshuffle', 'Disable peers shuffling for `sync` command')

        .option('--timeout <milliseconds>', 'Timeout to use when contacting peers', parseInt)
        .option('--httplogs', 'Enable HTTP logs')
        .option('--nohttplogs', 'Disable HTTP logs')
        .option('--isolate', 'Avoid the node to send peering or status informations to the network')
        .option('--forksize <size>', 'Maximum size of fork window', parseInt)
        .option('--memory', 'Memory mode')
      ;

      for (const opt of options) {
        program
          .option(opt.optFormat, opt.optDesc, opt.optParser);
      }

      for (const cmd of commands) {
        program
          .command(cmd.command.name)
          .description(cmd.command.desc)
          .action(async function() {
            const args = Array.from(arguments);
            try {
              const resOfExecution = await cmd.executionCallback.apply(null, [program].concat(args));
              onResolve(resOfExecution);
            } catch (e) {
              onReject(e);
            }
          });
      }

      program
        .on('*', function (cmd:any) {
          console.log("Unknown command '%s'. Try --help for a listing of commands & options.", cmd);
          onResolve();
        });

      program.parse(programArgs);

      if (programArgs.length <= 2) {
        onReject('No command given.');
      }
      return currentCommand;
    }
开发者ID:Kalmac,项目名称:duniter,代码行数:75,代码来源:cli.ts

示例4: JsonConfigurationFileWriter

///<reference path="../typings/commander/commander.d.ts"/>
///<reference path="../typings/promptly/promptly.d.ts"/>
///<reference path="../typings/yamljs/yamljs.d.ts"/>
import * as Commander from "commander";
import * as Promptly from "promptly";
import * as YAML from "yamljs";

import { JsonConfigurationFileWriter } from "./json-configuration-file-writer";
import { JsonSchemaReader } from "./json-schema-reader";
import { ConfigGenerator } from "./config-generator";

import * as FileSystem from "fs";

let configWriter = new JsonConfigurationFileWriter();

let configurit = new Commander.Command();

configurit
  .version("")
  //.option("-v, --verbose", "Find out what's happening")
  .option("-s, --schema-location [location]", "Where is that schema")
  .option("-o, --output-file [location]", "Where it's gonna be")
  .option("-y, --yaml [location]", "I wants YAML")
  .option("-p, --pretty [location]", "It should be purtteh")
  .parse(process.argv);

let generator = new ConfigGenerator();

let getDetails = (currentConfig?: any) => {
  generator.getUserInput(currentConfig, true, true).then((config: any) => {
    let fileText = "";
开发者ID:configurit,项目名称:configurit,代码行数:31,代码来源:configurit.ts

示例5: SemanticVersion

import * as Commander from "commander";
import * as FileSystem from "fs";
import { SemanticVersion } from "./semantic-version";

const semverter = new Commander.Command();

const semverterVersion = FileSystem.readFileSync("./package.json").toJSON().version;

semverter
  .version(semverterVersion)
  .option("-p, --patch", "Iterate the patch version number")
  .parse(process.argv);


let packageJson = FileSystem.readFileSync("./package.json").toJSON();

const version = new SemanticVersion(packageJson.version);

if (semverter["patch"]) {
  version.patch++;
}

packageJson.version = version.toString();

FileSystem.writeFileSync("./package.json2", JSON.stringify(packageJson, null, 3));
开发者ID:jamesrichford,项目名称:semverter,代码行数:25,代码来源:semverter.ts

示例6: main

async function main() {
  // Command-line interface.
  let program = new commander.Command();
  let filename: string | undefined = undefined;
  program
    .usage('[options] <calendar.ics>')
    .option('-a, --agenda', 'print human-readable agenda')
    .option('-g, --grid', 'print availability grid')
    .option('-d, --date <date>', 'show data for a given day')
    .option('-w, --week <date>', 'show data for a given week')
    .action((fn) => {
      filename = fn;
    });
  program.parse(process.argv);

  if (!filename) {
    program.help();
    return;
  }
  let opts = program.opts();

  // Parse the calendar.
  let data = await read_string(filename);
  let jcal = ICAL.parse(data);

  // Time range.
  let day: ICAL.Time;
  let start: ICAL.Time;
  let end: ICAL.Time;
  if (opts.date) {
    // Show a single day.
    day = ICAL.Time.fromString(opts.date);
    start = end = day;
  } else {
    // Show a whole week (the default).
    if (opts.week) {
      day = ICAL.Time.fromString(opts.week);
    } else {
      day = ICAL.Time.now();
    }
    start = day.startOfWeek();
    end = day.endOfWeek();
    end.adjust(1, 0, 0, 0);  // "One past the end" for iteration.
  }

  // Get events in the range.
  let instances = Array.from(get_occurrences(jcal, start, end));

  // Display the data.
  let dates_iter = iter_time(start, end, new ICAL.Duration({ days: 1 }));
  if (opts.agenda) {
    // Agenda display.
    for (let date of dates_iter) {
      for (let line of show_agenda(instances, date)) {
        console.log(line);
      }
    }
  } else {
    // Grid display.
    console.log(draw_header());
    for (let date of dates_iter) {
      for (let line of draw_avail(instances, date)) {
        console.log(line);
      }
    }
  }

}
开发者ID:sampsyo,项目名称:calcat,代码行数:68,代码来源:calcat.ts

示例7: Command

#!/usr/bin/env node
import { Command } from 'commander';
import bootstrap from './cmds/bootstrap';
import configure from './cmds/configure';
import backup from './cmds/backup';
import restore from './cmds/restore';
import upload from './cmds/upload';
import chalk from 'chalk';

const program = new Command();

// TODO
// bootstrap:
// Check whether config.json exists
// If config.json exists, import it
// Ask which categories in .runtimeconfig.json should be imported
//   - Ask which new categories (names) should be created
//   - Ask for the slug for each category
//   - Add name/slug objects to .runtimeconfig.json
// Save .runtimeconfig.json

console.log(`Gettin' spooky 👻  with ${chalk.hex('#fedc5d').bold('poltergeist')}`);

program.version('0.0.0', '-v, --version');

program
  .command('bootstrap [destination]')
  .description('bootstrap project')
  .action(bootstrap);

program
开发者ID:accosine,项目名称:poltergeist,代码行数:31,代码来源:cli.ts

示例8: main

async function main() {
    let argv = process.argv;

    let path = require("path");
    let configDir = path.join(process.cwd(), "dist-client/config");
    let gmeConfig = require(configDir);
    let config = gmeConfig.config;
    let MongoURI = require("mongo-uri");
    let Command = require("commander").Command;
    let webgme = require("webgme");

    let logger = webgme.Logger.create("gme:bin:runplugin", config.bin.log);

    let program = new Command();
    let STORAGE_CONSTANTS = webgme.requirejs("common/storage/constants");
    let PluginCliManager = webgme.PluginCliManager;

    webgme.addToRequireJsPaths(config);
    program
        .version("2.2.0")
        .arguments("<pluginName> <projectName>")
        .option("-b, --branchName [string]", "Name of the branch to load and save to.", "master")
        .option("-c, --commitHash [string]", "Commit hash to run from, if set branch will only be used for update.")
        .option("-a, --activeNode [string]", "ID/Path to active node.", "")
        .option("-s, --activeSelection [string]", "IDs/Paths of selected nodes (comma separated with no spaces).",
        (val: string) => {
            return val ? val.split(",") : [];
        })
        .option("-n, --namespace [string]",
        "Namespace the plugin should run under.", "")
        .option("-m, --mongo-database-uri [url]",
        "URI of the MongoDB [default from the configuration file]", config.mongo.uri)
        .option("-u, --user [string]", "the user of the command [if not given we use the default user]",
        config.authentication.guestAccount)
        .option("-o, --owner [string]", "the owner of the project [by default, the user is the owner]")
        .option("-j, --pluginConfigPath [string]",
        "Path to json file with plugin options that should be overwritten.", "")

        .on("--help", () => {
            let env = process.env.NODE_ENV || "default";
            console.log("  Examples:");
            console.log();
            console.log("    $ node run_plugin.js PluginGenerator TestProject");
            console.log("    $ node run_plugin.js PluginGenerator TestProject -b branch1 -j pluginConfig.json");
            console.log("    $ node run_plugin.js MinimalWorkingExample TestProject -a /1/b");
            console.log("    $ node run_plugin.js MinimalWorkingExample TestProject -s /1,/1/c,/d");
            console.log("    $ node run_plugin.js MinimalWorkingExample TestProject -c #123..");
            console.log("    $ node run_plugin.js MinimalWorkingExample TestProject -b b1 -c " +
                "#def8861ca16237e6756ee22d27678d979bd2fcde");
            console.log();
            console.log("  Plugin paths using " + configDir + path.sep + "config." + env + ".js :");
            console.log();
            for (let path of config.plugin.basePaths) {
                console.log(`    "${path}"`);
            }
        })
        .parse(argv);

    if (program.args.length < 2) {
        program.help();
        return Promise.reject(new Error("A project and pluginName must be specified."));
    }

    // this line throws a TypeError for invalid databaseConnectionString
    MongoURI.parse(program.mongoDatabaseUri);

    config.mongo.uri = program.mongoDatabaseUri;

    let pluginName = program.args[0];
    let projectName = program.args[1];
    logger.info(`Executing ${pluginName} plugin on ${projectName} in branch ${program.branchName}`);

    let pluginConfig = {};
    if (program.pluginConfigPath) {
        try {
            pluginConfig = require(path.resolve(program.pluginConfigPath));
        } catch (e) {
            return Promise.reject(e);
        }
    }

    let gmeAuth: any = undefined;
    try {
        gmeAuth = await webgme.getGmeAuth(config);
    } catch (_err) {
        throw new Error("problem with authorization");
    }
    let storage = await webgme.getStorage(logger, config, gmeAuth);
    await storage.openDatabase();

    let params = {
        projectId: "",
        username: program.user
    };
    logger.info("Database is opened.");

    if (program.owner) {
        params.projectId = program.owner + STORAGE_CONSTANTS.PROJECT_ID_SEP + projectName;
    } else {
        params.projectId = program.user + STORAGE_CONSTANTS.PROJECT_ID_SEP + projectName;
//.........这里部分代码省略.........
开发者ID:phreed,项目名称:webgme-immortals,代码行数:101,代码来源:run_plugin.ts


注:本文中的commander.Command类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。