コード例 #1
0
ファイル: test-cli.js プロジェクト: MikeeI/samples
#!/usr/bin/env node

var chalk = require('chalk')
var eDir = require('ensureDir')
var path = require('path')

var tp = path.resolve('./temp-ok-to-delete')

console.log(chalk.yellow.bold(tp))

eDir(tp,err=>console.log(chalk.blue.bold('edir',err)))

コード例 #2
0
gulp.task('help', function helpTask() {
  console.log('The following gulp tasks are available:');
  console.log('');
  console.log(chalk.yellow.bold('help'), '- Outputs this help message');
  console.log(chalk.red.bold('pre-commit'), '- Runs lint, enforce-coverage, and code-report for pre-commit check');
  console.log(chalk.yellow.bold('test'), '- Runs unit tests');
  console.log(chalk.yellow.bold('auto-test'), '- Runs unit tests with reporting');
  console.log(chalk.yellow.bold('coverage'), '- Runs unit tests and outputs code coverage report');
  console.log(chalk.yellow.bold('enforce-coverage'), '- Errors if coverage percentage drops below minimum');
  console.log(chalk.yellow.bold('clean-coverage'), '- Deletes the code coverage report');
  console.log(chalk.yellow.bold('code-report'), '- Generates a complexity analysis report');
  console.log(chalk.yellow.bold('clean-code-report'), '- Deletes the code complexity report');
  console.log(chalk.yellow.bold('reports'), '- Runs coverage and code-report tasks');
  console.log(chalk.yellow.bold('clean-reports'), '- Runs clean-coverage and clean-code-report tasks');
  console.log(chalk.yellow.bold('lint'), '- Lints the project sources');
});
コード例 #3
0
ファイル: index.js プロジェクト: ChetHarrison/generator-maryo
MaryoGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // Generate from a config file or prompt the user.
    if (this.options['config']) {
        var path = this.options['config'];
        if (path.substr(0,1) === '~') {
            path = process.env.HOME + path.substr(1);
        }

        fs.readFile(path, function (err, data) {
            var config = JSON.parse(data);

            this.styleFormat = config.styleFormat;
            this.templateFormat = config.templateFormat;
            this.testFramework = config.testFramework;
            this.includeBootstrap = config.includeBootstrap;

            cb();
        }.bind(this));
    } else {
        var styleFormat = ['css', 'sass', 'less'],
            templateFormat = ['_', 'dust'],
            testFramework = ['none', 'jasmine', 'mocha'],
            prompts = [{
                name: 'styleFormat',
                message: 'Which style format would you like to use ('+styleFormat.join("/")+')?',
                choices: styleFormat
            },
            {
                name: 'templateFormat',
                message: 'Which template library would you like to use ('+templateFormat.join("/")+')?',
                choices: templateFormat
            },
            {
                name: 'testFramework',
                message: 'Which test framework would you like to use ('+testFramework.join("/")+')?',
                choices: testFramework
            },
            {
                name: 'includeBootstrap',
                message: 'Would you like to include Twitter Bootstrap (y)?',
                type: 'confirm'
            }];

        // Be polite
        console.log(
            '\n     _-----_' +
            '\n    |       |' +
            '\n    |' + chalk.red('--(o)--') + '|   .--------------------------.' +
            '\n   `---------´  |    ' + chalk.yellow.bold('Welcome to Yeoman') + ',    |' +
            '\n    ' + chalk.yellow('(') + ' _' + chalk.yellow('´U`') + '_ ' + chalk.yellow(')') + '   |   ' + chalk.yellow.bold('ladies and gentlemen!') + '  |' +
            '\n    /___A___\\   \'__________________________\'' +
            '\n     ' + chalk.yellow('|  ~  |') +
            '\n   __' + chalk.yellow('\'.___.\'') + '__' +
            '\n ´   ' + chalk.red('`  |') + '° ' + chalk.red('´ Y') + ' `\n' +
            'Let\'s dance with Marionette.\n\n'
        );

        // Prompt the user and handle the user responses
        this.prompt(prompts, function (props, err) {
            this.styleFormat = props.styleFormat || styleFormat[0];
            this.templateFormat = props.templateFormat || templateFormat[0];
            this.testFramework = props.testFramework || testFramework[0];
            this.includeBootstrap = props.includeBootstrap;

            cb();
        }.bind(this));
    }
}
コード例 #4
0
 install() {
     const done = this.async();
     if (!this.skipInstall) {
         this.log('Installing dependencies, please wait...');
         this.info('Removing the node_modules directory');
         shelljs.rm('-rf', 'node_modules');
         const installCommand = this.clientPackageManager === 'yarn' ? 'yarn' : 'npm install';
         this.info(installCommand);
         shelljs.exec(installCommand, { silent: this.silent }, (code, msg, err) => {
             if (code !== 0) {
                 this.error(`${installCommand} failed.`);
             }
             done();
         });
     } else {
         const logMsg = `Start your Webpack development server with:\n${chalk.yellow.bold(`${this.clientPackageManager} start`)}\n`;
         this.success(logMsg);
         done();
     }
 }
コード例 #5
0
ファイル: index.js プロジェクト: MarcDiethelm/generator-xtc
	yeoman.generators.Base.apply(this, arguments);
	this.argument('name', { type: String, required: false });

	this.xtcPath = this.options.path ? path.resolve(process.cwd(), this.options.path) : process.cwd();
	var xtcPkg = require( path.join(this.xtcPath, 'package.json') );
	this.xtcCfg = require( path.join(this.xtcPath, 'lib/configure.js') ).get();
};

util.inherits(ModuleGenerator, yeoman.generators.NamedBase);

// welcome message
// http://patorjk.com/software/taag/#p=display&f=Pepper&t=xtc%20mod%20gen
var welcome =
	'\n' +
	chalk.yellow.bold("      _/__   _ _  _   _/  _  _  _ ") + '\n' +
	chalk.yellow.bold("    ></ /_  / / //_//_/  /_//_'/ /") + '\n' +
	chalk.yellow.bold("                         _/       ") + '\n\n' +
	chalk.blue.bold('    express-terrific module generator\n\n') +
	chalk.green('Please answer a few questions to create your new module.\n')
;
console.info(welcome);


ModuleGenerator.prototype.askFor = function askFor() {
	var cb = this.async();

	// module name
	var prompts = [
		{
			name: 'name'
コード例 #6
0
install.installDependencies = function (options) {
  var msg = {
    commands: [],
    template: _.template('\n\nI\'m all done. ' +
    '<%= skipInstall ? "Just run" : "Running" %> <%= commands %> ' +
    '<%= skipInstall ? "" : "for you " %>to install the required dependencies.' +
    '<% if (!skipInstall) { %> If this fails, try running the command yourself.<% } %>\n\n')
  };

  var commands = [];

  if (_.isFunction(options)) {
    options = {
      callback: options
    };
  }

  options = _.defaults(options || {}, {
    bower: true,
    npm: true,
    skipInstall: false,
    skipMessage: false,
    callback: function () {}
  });

  if (options.bower) {
    msg.commands.push('bower install');
    commands.push(function (cb) {
      this.env.runLoop.add('end', function (done) {
        this.bowerInstall(null, null, function () {
          done();
          cb();
        }, { once: 'installDependencies-bower' });
      }.bind(this));
    }.bind(this));
  }

  if (options.npm) {
    msg.commands.push('npm install');
    commands.push(function (cb) {
      this.env.runLoop.add('end', function (done) {
        this.npmInstall(null, null, function () {
          done();
          cb();
        });
      }.bind(this), { once: 'installDependencies-npm' });
    }.bind(this));
  }

  assert(msg.commands.length, 'installDependencies needs at least one of npm or bower to run.');

  if (options.skipInstall) {
    return options.callback();
  }

  if (!options.skipMessage) {
    this.env.adapter.log(msg.template(_.extend(options, { commands: chalk.yellow.bold(msg.commands.join(' & ')) })));
  }

  async.parallel(commands, options.callback);
};
コード例 #7
0
export default function helpEnvVar(name, value = undefined) {

    return value === undefined ?
        chalk.yellow.bold(name) :
        (chalk.yellow.bold(name) + "=" + value);
}
コード例 #8
0
 end: function(){
   this.log(chalk.green.bold('Installation successful!'));
   this.log(chalk.yellow.bold('Remember add dependencies to parent or current module, directive!'));
   //
 },
コード例 #9
0
 this.on('end', function () {
     //this.installDependencies({ skipInstall: options['skip-install'] });
     var info = chalk.yellow.bold("\nI'm all done. Please running bower install & npm install for you to install the required dependencies.")
     console.log(info);
 });
コード例 #10
0
ファイル: hello.js プロジェクト: hoffrocket/sabaletters
const chalk = require('chalk')
const pkg = require('../package.json')

console.log(`

${chalk.green('Hey there! 👋')}

Thanks for giving the ${pkg.name} a try. 🎉
To get you going really quickly this project includes a setup step.

${chalk.yellow.bold('yarn run setup')} automates the following steps for you:
  - creates a config file ${chalk.yellow('./.contentful.json')}
  - imports ${chalk.green('a predefined content model')}

When this is done run:

${chalk.yellow(
  'yarn run dev'
)} to start a development environment at ${chalk.green('localhost:8000')}

or

${chalk.yellow(
  'yarn run build'
)} to create a production ready static site in ${chalk.green('./public')}


`)
コード例 #11
0
 initializing: function () {
   var message = chalk.yellow.bold("Welcome to MEAN.js ") + chalk.yellow('A nean.js module showing crawled items');
   this.log(yosay(message, {maxLength: 19}));
 },
コード例 #12
0
async function eject() {
  try {
    const filesWithExpo = await filesUsingExpoSdk();
    const usingExpo = filesWithExpo.length > 0;

    let expoSdkWarning;
    if (usingExpo) {
      expoSdkWarning = `${chalk.bold('Warning!')} We found at least one file where your project imports the Expo SDK:
`;

      for (let filename of filesWithExpo) {
        expoSdkWarning += `  ${chalk.cyan(filename)}\n`;
      }

      expoSdkWarning += `
${chalk.yellow.bold('If you choose the "plain" React Native option below, these imports will stop working.')}`;
    } else {
      expoSdkWarning = `\
We didn't find any uses of the Expo SDK in your project, so you should be fine to eject to
"Plain" React Native. (This check isn't very sophisticated, though.)`;
    }

    log(
      `
${expoSdkWarning}

We ${chalk.italic('strongly')} recommend that you read this document before you proceed:
  ${chalk.cyan('https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md')}

Ejecting is permanent! Please be careful with your selection.
`
    );

    let reactNativeOptionMessage = "React Native: I'd like a regular React Native project.";

    if (usingExpo) {
      reactNativeOptionMessage = chalk.italic(
        "(WARNING: See above message for why this option may break your project's build)\n  "
      ) + reactNativeOptionMessage;
    }

    const questions = [
      {
        type: 'list',
        name: 'ejectMethod',
        message: 'How would you like to eject from create-react-native-app?',
        default: usingExpo ? 'expoKit' : 'raw',
        choices: [
          {
            name: reactNativeOptionMessage,
            value: 'raw',
          },
          {
            name: "ExpoKit: I'll create or log in with an Expo account to use React Native and the Expo SDK.",
            value: 'expoKit',
          },
          {
            name: "Cancel: I'll continue with my current project structure.",
            value: 'cancel',
          },
        ],
      },
    ];

    const { ejectMethod } = await inquirer.prompt(questions);

    if (ejectMethod === 'raw') {
      const useYarn = await fse.exists(path.resolve('yarn.lock'));
      const npmOrYarn = useYarn ? 'yarn' : 'npm';
      const appJson = JSON.parse(await fse.readFile(path.resolve('app.json')));
      const pkgJson = JSON.parse(await fse.readFile(path.resolve('package.json')));
      let {
        name: newName,
        displayName: newDisplayName,
        expo: { name: expName },
      } = appJson;

      // we ask user to provide a project name (default is package name stripped of dashes)
      // but we want to infer some good default choices, especially if they've set them up in app.json
      if (!newName) {
        newName = stripDashes(pkgJson.name);
      }

      if (!newDisplayName && expName) {
        newDisplayName = expName;
      }

      log("We have a couple of questions to ask you about how you'd like to name your app:");
      const { enteredName, enteredDisplayname } = await inquirer.prompt([
        {
          name: 'enteredDisplayname',
          message: "What should your app appear as on a user's home screen?",
          default: newDisplayName,
          validate: s => {
            return s.length > 0;
          },
        },
        {
          name: 'enteredName',
          message: 'What should your Android Studio and Xcode projects be called?',
          default: newName,
          validate: s => {
            return s.length > 0 && s.indexOf('-') === -1 && s.indexOf(' ') === -1;
          },
        },
      ]);

      appJson.name = enteredName;
      appJson.displayName = enteredDisplayname;

      log('Writing your selections to app.json...');
      // write the updated app.json file
      await fse.writeFile(path.resolve('app.json'), JSON.stringify(appJson, null, 2));
      log(chalk.green('Wrote to app.json, please update it manually in the future.'));

      const ejectCommand = 'node';
      const ejectArgs = [
        path.resolve('node_modules', 'react-native', 'local-cli', 'cli.js'),
        'eject',
      ];

      const { status } = spawn.sync(ejectCommand, ejectArgs, {
        stdio: 'inherit',
      });

      if (status !== 0) {
        log(chalk.red(`Eject failed with exit code ${status}, see above output for any issues.`));
        log(chalk.yellow('You may want to delete the `ios` and/or `android` directories.'));
        process.exit(1);
      } else {
        log('Successfully copied template native code.');
      }

      const newDevDependencies = [];
      // Try to replace the Babel preset.
      try {
        const projectBabelPath = path.resolve('.babelrc');
        // If .babelrc doesn't exist, the app is using the default config and
        // editing the config is not necessary.
        if (await fse.exists(projectBabelPath)) {
          const projectBabelRc = (await fse.readFile(projectBabelPath)).toString();

          // We assume the .babelrc is valid JSON. If we can't parse it (e.g. if
          // it's JSON5) the error is caught and a message asking to change it
          // manually gets printed.
          const babelRcJson = JSON.parse(projectBabelRc);
          if (babelRcJson.presets && babelRcJson.presets.includes('babel-preset-expo')) {
            babelRcJson.presets = babelRcJson.presets.map(
              preset =>
                preset === 'babel-preset-expo'
                  ? 'babel-preset-react-native-stage-0/decorator-support'
                  : preset
            );
            await fse.writeFile(projectBabelPath, JSON.stringify(babelRcJson, null, 2));
            newDevDependencies.push('babel-preset-react-native-stage-0');
            log(
              chalk.green(
                `Babel preset changed to \`babel-preset-react-native-stage-0/decorator-support\`.`
              )
            );
          }
        }
      } catch (e) {
        log(
          chalk.yellow(
            `We had an issue preparing your .babelrc for ejection.
If you have a .babelrc in your project, make sure to change the preset
from \`babel-preset-expo\` to \`babel-preset-react-native-stage-0/decorator-support\`.`
          )
        );
        log(chalk.red(e));
      }

      delete pkgJson.main;

      // NOTE: expo won't work after performing a raw eject, so we should delete this
      // it will be a better error message for the module to not be found than for whatever problems
      // missing native modules will cause
      delete pkgJson.dependencies.expo;
      delete pkgJson.devDependencies['react-native-scripts'];

      pkgJson.scripts.start = 'react-native start';
      pkgJson.scripts.ios = 'react-native run-ios';
      pkgJson.scripts.android = 'react-native run-android';

      // no longer relevant to an ejected project (maybe build is?)
      delete pkgJson.scripts.eject;

      log(`Updating your ${npmOrYarn} scripts in package.json...`);

      await fse.writeFile(path.resolve('package.json'), JSON.stringify(pkgJson, null, 2));

      log(chalk.green('Your package.json is up to date!'));

      log(`Adding entry point...`);

      const lolThatsSomeComplexCode = `import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('${newName}', () => App);
`;

      await fse.writeFile(path.resolve('index.js'), lolThatsSomeComplexCode);

      log(chalk.green('Added new entry points!'));

      log(
        `
Note that using \`${npmOrYarn} start\` will now require you to run Xcode and/or
Android Studio to build the native code for your project.`
      );

      log('Removing node_modules...');
      rimraf.sync(path.resolve('node_modules'));
      if (useYarn) {
        log('Installing packages with yarn...');
        const args = newDevDependencies.length > 0 ? ['add', '--dev', ...newDevDependencies] : [];
        spawn.sync('yarnpkg', args, { stdio: 'inherit' });
      } else {
        // npm prints the whole package tree to stdout unless we ignore it.
        const stdio = [process.stdin, 'ignore', process.stderr];

        log('Installing existing packages with npm...');
        spawn.sync('npm', ['install'], { stdio });

        if (newDevDependencies.length > 0) {
          log('Installing new packages with npm...');
          spawn.sync('npm', ['install', '--save-dev', ...newDevDependencies], {
            stdio,
          });
        }
      }
    } else if (ejectMethod === 'expoKit') {
      await detach();
    } else {
      // we don't want to print the survey for cancellations
      log('OK! If you change your mind you can run this command again.');
      return;
    }

    log(
      `${chalk.green('Ejected successfully!')}
Please consider letting us know why you ejected in this survey:
  ${chalk.cyan('https://goo.gl/forms/iD6pl218r7fn9N0d2')}`
    );
  } catch (e) {
    console.error(chalk.red(`Error running eject: ${e}`));
  }
}
コード例 #13
0
ファイル: index.js プロジェクト: anvaka/generator-an
function printInstructions() {
  console.log('Please run ' + chalk.yellow.bold('npm install') + ' to install all dependencies');
}
コード例 #14
0
import chalk      from "chalk";
import readline   from 'readline';
import ip         from 'ip';
import {log}      from './logger';

import config  from './config';
const {port, hostname} =  config;

export const url  = chalk.yellow.bold(`${hostname}:${port}`);

const ipAddress = ip.address();
export const resetTerminal = () => {
  process.stdout.write('\u001B[2J\u001B[0;0f');
  console.log(`Listening at: [ ${url} ]`);
  console.log(`Listening at: [ ${ipAddress} ]\n`);
};

const rl = readline.createInterface(process.stdin, process.stdout);

const commands = [
  {
    name: 'url',
    description: 'Show the full url of the application'
  },
  {
    name: 'port',
    description: 'Show on which port the server listens'
  },
  {
    name: 'clear',
    description: 'Clear the terminal window'
コード例 #15
0
ファイル: init.js プロジェクト: APshenkin/CodeceptJS
module.exports = function (initPath) {
  let testsPath = getTestRoot(initPath);

  print();
  print(`  Welcome to ${colors.magenta.bold('CodeceptJS')} initialization tool`);
  print("  It will prepare and configure a test environment for you");
  print();


  if (!path) {
    print(`No test root specified.`);
    print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`);
    print('----------------------------------');
  } else {
    print(`Installing to ${colors.bold(testsPath)}`);
  }

  if (!fileExists(testsPath)) {
    print(`Directory ${testsPath} does not exist, creating...`);
    mkdirp.sync(testsPath);
  }

  let configFile = path.join(testsPath, 'codecept.json');
  if (fileExists(configFile)) {
    error(`Config is already created at ${configFile}`);
    return;
  }


  inquirer.prompt(
    [
      {
        name: "tests",
        type: "input",
        default: "./*_test.js",
        message: "Where are your tests located?"
      },
      {
        name: "helpers",
        type: "checkbox",
        choices: helpers,
        message: "What helpers do you want to use?"
      },
      {
        name: "output",
        default: "./output",
        message: "Where should logs, screenshots, and reports to be stored?"
      },
      {
        name: "steps",
        type: "confirm",
        message: "Would you like to extend I object with custom steps?",
        default: true
      },
      {
        name: "translation",
        type: "list",
        message: "Do you want to choose localization for tests?",
        choices: translations
      },
      {
        name: "steps_file",
        type: "input",
        message: "Where would you like to place custom steps?",
        default: "./steps_file.js",
        when: function (answers) {
          return answers.steps;
        }
      }
    ], (result) => {
    let config = defaultConfig;
    config.name = testsPath.split(path.sep).pop();
    config.output = result.output;

    config.tests = result.tests;
    // create a directory tests if it is included in tests path
    let matchResults = config.tests.match(/[^*.]+/);
    if (matchResults) {
      mkdirp.sync(path.join(testsPath, matchResults[0]));
    }

    // append file mask to the end of tests
    if (!config.tests.match(/\*(.*?)$/)) {
      config.tests = config.tests.replace(/\/+$/, '') + "/*_test.js";
      console.log(`Adding default test mask: ${config.tests}`);
    }

    if (result.translation !== noTranslation) config.translation = result.translation;

    result.helpers.forEach((helper) => config.helpers[helper] = {});

    let helperConfigs = [];

    result.helpers.forEach((helperName) => {
      try {
        let Helper = require('../helper/' + helperName);
        if (Helper._checkRequirements) {
          packages = Helper._checkRequirements();
        }

        if (!Helper._config()) return;
        helperConfigs = helperConfigs.concat(Helper._config().map((config) => {
          config.message = `[${helperName}] ${config.message}`;
          config.name = `${helperName}_${config.name}`;
          config.type = config.type || 'input';
          return config;
        }));
      } catch (err) {
        error(err);
      }
    });

    let finish = () => {
      if (result.steps_file) {
        let stepFile = path.join(testsPath, result.steps_file);
        if (!fileExists(path.dirname(stepFile))) {
          mkdirp.sync(path.dirname(stepFile));
        }
        fs.writeFileSync(stepFile, defaultActor);
        config.include.I = result.steps_file;
        success('Steps file created at ' + stepFile);
      }

      fs.writeFileSync(configFile, JSON.stringify(config, null, 2));
      success(`Config created at ${configFile}`);

      if (config.output) {
        if (!fileExists(config.output)) {
          mkdirp.sync(path.join(testsPath, config.output));
          success("Directory for temporary output files created at `_output`");
        } else {
          print(`Directory for temporary output files is already created at '${config.output}'`);
        }
      }
      success("Almost done! Create your first test by executing `codeceptjs gt` (generate test) command");

      if (packages) {
        print("\n--");
        if (isLocal) {
          print("Please install dependent packages locally: " + colors.bold('npm install --save-dev ' + packages.join(' ')));
        } else {
          print("Please install dependent packages globally: [sudo] " + colors.bold('npm install -g ' + packages.join(' ')));
        }
      }
    };

    if (!result.helpers.length) {
      return finish();
    }

    print("Configure helpers...");
    inquirer.prompt(helperConfigs, (helperResult) => {

      Object.keys(helperResult).forEach((key) => {
        let helperName, configName;
        let parts = key.split('_');
        helperName = parts[0];
        configName = parts[1];
        if (!configName) return;
        config.helpers[helperName][configName] = helperResult[key];
      });

      finish();
    });


  });
};
コード例 #16
0
/**
 * Prepares the upgrade by checking execution policy, internet, and
 * checking for parameters.
 */
async function prepareUpgrade(_program) {
    debug('Upgrade: Preparing upgrade');

    // Set program reference
    program = _program;

    // Print version
    console.log(chalk.yellow.bold('npm-windows-upgrade ' + versions.nwuVersion));

    // Let's make sure that the user wants to upgrade
    debug('Upgrade: Asking for confirmation');
    if (program.prompt && !(await askForConfirmation())) return;

    // Check Execution Policy
    debug('Upgrade: Checking execution policy');
    const canExecute = await powershell.checkExecutionPolicy();

    debug('Upgrade: canExecute is ' + canExecute);
    if (canExecute.error && canExecute.error.length && canExecute.error.length > 0) {
        debug('Upgrade: Execution Policy check failed');
        console.log(chalk.bold.red('Encountered an error while checking the system\'s execution policy. The error was:'));
        console.log(canExecute.error);
        return;
    }

    if (!canExecute) {
        debug('Upgrade: Execution policy insufficient');
        console.log(chalk.bold.red('Scripts cannot be executed on this system.'));
        console.log(chalk.green('To fix, run the command below as Administrator in PowerShell and try again:'));
        console.log(chalk.red('Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force'));
        return;
    }

    // Check Internet Connection
    debug('Upgrade: Checking internet connection');
    const isOnline = await checkForInternet();

    if (!isOnline) {
        debug('Upgrade: Internet Check: Offline');
        console.error(chalk.bold.red('We have trouble connecting to the Internet. Aborting.'));
        return;
    }

    // Let's check our version
    if (!program.npmVersion) {
        debug('Upgrade: Getting available npm versions from npm');
        const availableVersions = await versions.getAvailableNPMVersions();
        const versionList = [{
            type: 'list',
            name: 'version',
            message: 'Which version do you want to install?',
            choices: availableVersions.reverse()
        }];

        debug('Upgrade: Got npm version list, now asking user for selection');
        inquirer.prompt(versionList).then(answer => upgrade(answer.version, program.npmPath));
    } else if (program.npmVersion === 'latest') {
        // If the version is "latest", let's find out what that is
        const latest = await versions.getLatestNPMVersion();

        upgrade(latest, program.npmPath);
    } else {
        upgrade(program.npmVersion, program.npmPath);
    }
}
コード例 #17
0
ファイル: index.js プロジェクト: dalbelap/generator-jhipster
            if (this.configOptions.skipI18nQuestion) return;

            this.composeLanguagesSub(this, this.configOptions, 'client');
        }
    },

    writing() {
        if (this.clientFramework === 'angular1') {
            return writeAngularJsFiles.call(this);
        }
        return writeAngularFiles.call(this);
    },

    install() {
        let logMsg =
            `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;

        if (this.clientFramework === 'angular1') {
            logMsg =
                `To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
        }

        const injectDependenciesAndConstants = (err) => {
            if (err) {
                this.warning('Install of dependencies failed!');
                this.log(logMsg);
            } else if (this.clientFramework === 'angular1') {
                this.spawnCommandSync('gulp', ['install']);
            } else {
                this.spawnCommandSync(this.clientPackageManager, ['run', 'webpack:build']);
            }
コード例 #18
0
/**
 * Prints helpful information to console
 */
function displayHelp() {
    let help = chalk.yellow.bold('  Automatically upgrade npm on Windows. Made with <3 for npm and Node by Microsoft.\n');
    help += '  All parameters optional. Version ' + versions.nwuVersion + '\n';

    console.log(help);
}
コード例 #19
0
ファイル: index.js プロジェクト: cmalven/generator-met
 this.on('end', function () {
   console.log('\n' + chalk.cyan.bold('All set!') + ' Run ' + chalk.yellow.bold('meteor') + ' to start your app.');
   // meteor
   // open('http://localhost:3000/');
 });
コード例 #20
0
    writing: function() {
        console.log(chalk.yellow.bold('[ Writing ]'));

/* -- Delete the templates directory */

        var deleteFolderRecursive = function(path) {
            if (fs.existsSync(path)) {
                fs.readdirSync(path).forEach(function(file, index) {
                    var curPath = path + "/" + file;
                    if (fs.statSync(curPath).isDirectory()) {
                        deleteFolderRecursive(curPath);
                    } else {
                        fs.unlinkSync(curPath);
                    }
                });
                fs.rmdirSync(path);
            }
        };

/* -- Delete files */

        console.log(chalk.green('> Deleting files'));
        for (var i = 0; i < this.install.DELETE_FILES.length; i++) {
            var file = this.install.DELETE_FILES[i];
            if (fs.existsSync(file.src) ) {
                if (fs.statSync(file.src).isDirectory()) {
                    console.log('+ Directory ' + chalk.green(file.src) + " deleted");
                    deleteFolderRecursive(file.src);
                } else {
                    console.log('+ File ' + chalk.green(file.src) + " deleted");
                    fs.unlinkSync(file.src);
                }
            }
        }

/* -- Move files */

        console.log(chalk.green('> Moving files'));
        for (var i = 0; i < this.install.MOVE_FILES.length; i++) {
            var file = this.install.MOVE_FILES[i];
            console.log('+ ' + file.src + ' moved to ' + chalk.green(file.dest));
            fs.renameSync(file.src,
                file.dest
                );
        }

/* -- Write template files */

        console.log(chalk.green('> Writing template files'));
        for (var i = 0; i < this.install.TEMPLATE_FILES.length; i++) {
            var file = this.install.TEMPLATE_FILES[i];
            console.log('+ ' + this.answers.templatesDir + "/" + file.src + ' wrote to ' + chalk.green(file.dest));
            this.fs.copyTpl(
                this.templatePath(file.src),
                this.destinationPath(file.dest),
                this.answers
            );
        }

/* -- Copy boilerplate files */

        console.log(chalk.green('> Copying boilerplate files'));
        for (var i = 0; i < this.install.BOILERPLATE_FILES.length; i++) {
            var file = this.install.BOILERPLATE_FILES[i];
            console.log('+ ' + this.answers.templatesDir + "/" + file.src + ' copied to ' + chalk.green(file.dest));
            this.fs.copy(
                this.templatePath(file.src),
                this.destinationPath(file.dest)
            );
        }

/* -- Copy boilerplate directories */

        console.log(chalk.green('> Copying boilerplate directories'));
        for (var i = 0; i < this.install.BOILERPLATE_DIRECTORIES.length; i++) {
            var dir = this.install.BOILERPLATE_DIRECTORIES[i];
            console.log('+ ' + this.answers.templatesDir + "/" + dir.src + ' copied to ' + chalk.green(dir.dest));
            ncp(this.templatePath(dir.src), this.destinationPath(dir.dest), function (err) {
                if (err) {
                    return console.error(err);
                }
            });
        }

/* -- mysql db restore */

        console.log(chalk.green('> Mysql database restore'));
        for (var i = 0; i < this.install.MYSQL_DBS.length; i++) {
            var command = "mysqldump -u " + this.install.MYSQL_DBS[i]['user']
                        + " -p"
                        + this.install.MYSQL_DBS[i]['password']
                        + " "
                        +  this.answers.appName
                        + " < "
                        + this.templatePath(this.install.MYSQL_DBS[i]['src']);
            console.log('+ ' + chalk.green(command) + ' executed');
            child_process.execSync(command);
        }

/* -- Craft base plugins */

        console.log(chalk.green('> Cloning base Craft plugins'));
        for (var i = 0; i < this.install.CRAFT_PLUGINS.length; i++) {
            var plugin = this.install.CRAFT_PLUGINS[i];
            console.log('+ ' + chalk.green(plugin.name) + ' plugin installed');
            var pluginPath = this.install.CRAFT_PLUGINS_DIRECTORY + '/' + plugin.dir;
            child_process.execSync('git clone ' + plugin.url + ' ' + pluginPath);
            if (plugin.subDirectory) {
              console.log('+ ' + chalk.green(plugin.name) + ' moving sub directory');
              var tmpPluginDir = this.install.CRAFT_PLUGINS_DIRECTORY + '/tmp-' + plugin.dir;
              child_process.execSync('mv ' + pluginPath + '/' + plugin.dir
                  + ' ' + tmpPluginDir
                  + ' && rm -rf ' + pluginPath
                  + ' && mv ' + tmpPluginDir + ' ' + pluginPath);
            }
        }

        console.log(chalk.green('> Sync to file system'));
        },
コード例 #21
0
ファイル: webpack.config.js プロジェクト: Thr1ve/visualizer
  ],

  output: {
    path: __dirname + '/lib',
    filename: 'index.js',
    publicPath: '/',
    libraryTarget: 'umd'
  },

  externals: {
  'react': 'react',
  'react-dom': 'react-dom'
  },

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
      {test: /\.css$/, loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'}
    ]
  },

  plugins: [
    new ProgressBarPlugin({
      format: `building... [${chalk.green(':bar')}] ${chalk.magenta.bold(':percent')} (${chalk.yellow.bold(':elapsed seconds')})`,
      clear: true
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};
コード例 #22
0
    initializing: function() {
        console.log(chalk.yellow.bold('[ Initializing ]'));

/* -- Process data in an array synchronously, moving onto the n+1 item only after the nth item callback */

        this.synchronousLoop = function(data, processData, loopDone) {
            if (data.length > 0) {
                var loop = function(data, i, processData, loopDone) {
                    processData(data[i], i, function() {
                        if (++i < data.length) {
                            loop(data, i, processData, loopDone);
                        } else {
                            loopDone();
                        }
                    });
                };
                loop(data, 0, processData, loopDone);
            } else {
                loopDone();
            }
        };

/* -- Set up the download command */

        this.download = function(url, cb) {
            var self = this;
            new download({mode: '775', extract: true})
                .get(url)
                .dest(this.destinationPath())
                .run(function(error, files) {
                    if (error) {
                        console.log(error);
                        process.exit();
                    } else {
                        cb();
                        console.log('  ' + chalk.green(files.length) + ' files download and extracted successfully;)');
                    }
                });
            };

        var done = this.async();

/* -- Load in our API JSON configs */

        this.answers = {};
        this.askInstall = true;

        var installPath = this.sourceRoot() + INSTALLS_DIR;
        fs.readdirSync(installPath).forEach(function(file, index) {
            var curPath = installPath + "/" + file;
            if (!fs.statSync(curPath).isDirectory()) {
                var ext = file.substr(file.lastIndexOf('.') + 1);
                if (ext == 'json') {
                    var data = fs.readFileSync(curPath);
                    var obj = JSON.parse(data);
/* -- Fill in the QUESTIONS with the found install JSON file */
                    installs[obj.INSTALL_KEY] = obj;
                    INSTALL_QUESTIONS[0].choices.push({key: obj.INSTALL_KEY, name: obj.INSTALL_NAME, value: obj.INSTALL_KEY});
                    }
                }
            });

/* -- Ask them which install they want */

        if (this.askInstall) {
            this._optionOrPrompt(INSTALL_QUESTIONS, function(answers) {
                this.install = installs[answers.installList];
/* -- Change the templates root based on the install choses */
                this.sourceRoot(this.sourceRoot() + "/" + this.install.INSTALL_KEY);
                done();
                }.bind(this));
            }
        },
コード例 #23
0
ファイル: output.js プロジェクト: udemy/CodeceptJS
 skipped: (test) => {
   print(`  ${colors.yellow.bold('S')} ${test.title}`);
 },
コード例 #24
0
    writing: function() {
        this.log(chalk.yellow.bold('[ Writing ]'));

this.log(this.answers);

/* -- Write template files */

        this.log(chalk.green('> Writing template files'));
        for (var i = 0; i < this.api.TEMPLATE_FILES.length; i++) {
            var file = this.api.TEMPLATE_FILES[i];
            var destFile;
            var skip = false;

            if ((typeof file.requires == 'object') && (file.requires.length)) {
                var _this = this;
                file.requires.forEach(function(thisRequires, index) {
                    if (_this.answers.pluginComponents.indexOf(thisRequires) == -1) {
                        skip = true;
                        }
                    });
                }
            if (!skip) {
                if (file.prefix) {
/* -- Handle templates that get prefixed */
                    if (file.subPrefix) {
/* -- Handle templates that have a prefix and a sub-prefix */
                        var subPrefix = this.answers[file.subPrefix];
                        var _this = this;
                        subPrefix.forEach(function(thisPrefix, index) {
                            destFile = _this.destDir + file.destDir + _this.answers.pluginHandle + thisPrefix + file.dest;
                            _this.log('+ ' + _this.answers.templatesDir + "/" + file.src + ' wrote to ' + chalk.green(destFile));
                            _this.answers['index'] = index;
                            _this.fs.copyTpl(
                                _this.templatePath(file.src),
                                _this.destinationPath(destFile),
                                _this.answers
                                );
                            });
                        } else {
/* -- Handle templates that only have a prefix */
                        destFile = this.destDir + file.destDir + this.answers.pluginHandle  + file.dest;
                        this.log('+ ' + this.answers.templatesDir + "/" + file.src + ' wrote to ' + chalk.green(destFile));
                        this.answers['index'] = 0;
                        this.fs.copyTpl(
                            this.templatePath(file.src),
                            this.destinationPath(destFile),
                            this.answers
                            );
                        }
                    } else {
/* -- Handle templates that are not prefixed */
                    destFile = this.destDir + file.destDir + file.dest;
                    this.log('+ ' + this.answers.templatesDir + "/" + file.src + ' wrote to ' + chalk.green(destFile));
                    this.answers['index'] = 0;
                    this.fs.copyTpl(
                        this.templatePath(file.src),
                        this.destinationPath(destFile),
                        this.answers
                        );
                    }
                }
            }

/* -- Copy boilerplate files */

        this.log(chalk.green('> Copying boilerplate files'));
        for (var i = 0; i < this.api.BOILERPLATE_FILES.length; i++) {
            var file = this.api.BOILERPLATE_FILES[i];
            var destFile = this.destDir + file.src;
            var skip = false;
            if ((typeof file.requires == 'object') && (file.requires.length)) {
                var _this = this;
                file.requires.forEach(function(thisRequires, index) {
                    if (_this.answers.pluginComponents.indexOf(thisRequires) == -1) {
                        skip = true;
                        }
                    });
                }
                if (!skip) {
                this.log('+ ' + this.answers.templatesDir + "/" + file.src + ' copied to ' + chalk.green(destFile));
                this.fs.copy(
                    this.templatePath(file.src),
                    this.destinationPath(destFile)
                    );
                }
            }


        this.log(chalk.green('> Sync to file system'));
        },
コード例 #25
0
 /**
  * Print a debug message.
  *
  * @param {string} msg - message to print
  * @param {string[]} args - arguments to print
  */
 debug(msg, ...args) {
     if (this.isDebugEnabled || (this.options && this.options.debug)) {
         this.log(`${chalk.yellow.bold('DEBUG!')} ${msg}`);
         args.forEach(arg => this.log(arg));
     }
 }
コード例 #26
0
    install: function() {
        this.log(chalk.yellow.bold('[ Install ]'));

        },
コード例 #27
0
ファイル: index.js プロジェクト: ButuzGOL/gd-pages
    return new Promise(function(resolve, reject) {
      var folderMapper = {};
      var walker = walk.walk(folderPath);

      console.log(chalk.yellow.bold('Start uploading folder', figures.ellipsis));

      folderMapper[folderPath] = id;

      walker.on('directory', function(root, stat, next) {
        drive.files.insert({
          auth: jwt,
          resource: {
            mimeType: 'application/vnd.google-apps.folder',
            title: stat.name,
            parents: [ { id: folderMapper[root] } ]
          }
        }, function(err, res) {
          if (err) return reject(err);

          folderMapper[root + '/' + stat.name] = res.id;

          var prefix = root.replace(folderPath, '');
          console.log('Empty folder created',
            ((prefix) ? (prefix + '/') : '') + stat.name);

          next();
        });
      });

      walker.on('file', function(root, stat, next) {
        var fullPath = root + '/' + stat.name;
        var mimeType = mime.lookup(fullPath);

        drive.files.insert({
          auth: jwt,
          resource: {
            title: stat.name,
            mimeType: mimeType,
            parents: [ { id: folderMapper[root] } ]
          },
          media: {
            mimeType: mimeType,
            body: fs.createReadStream(fullPath)
          },
        }, function(err, resp) {
          if (err) return reject(err);

          var prefix = root.replace(folderPath, '');
          console.log('File uploaded',
            ((prefix) ? (prefix + '/') : '') + stat.name);

          next();
        });
      });

      walker.on('end', function() {

        logSuccess('Uploading done');

        resolve(id);
      });
    });
コード例 #28
0
    prompting: function() {
        this.log(chalk.yellow.bold('[ Prompting ]'));
        var done = this.async();

/* -- Turn the pluginComponents into an array */

        if (this.options.pluginComponents) {
            this.options.pluginComponents = this.options.pluginComponents.split(',');
            }

/* -- Change any questions with "when" properties into functions */

        for (var i = 0; i < this.api.QUESTIONS.length; i++) {
            if (this.api.QUESTIONS[i].hasOwnProperty('when')) {
                    var whatsRequired = this.api.QUESTIONS[i].when;
                    this.api.QUESTIONS[i].when = newClosure(whatsRequired);
                }
            }
/* -- Ask some questions about how they want the plugin customized */

        this._optionOrPrompt(this.api.QUESTIONS, function(answers) {
            var now = new Date();

            this.answers = answers;
            this.answers.templatesDir = 'templates';
            this.answers.pluginDirName = this.answers.pluginName.directorize();
            this.answers.pluginCamelHandle = this.answers.pluginName.camelize();
            this.answers.pluginHandle = this.answers.pluginCamelHandle.capitalizeFirstLetter();

/* -- Auto-fill some variables we'll be using in our templates */

            this.answers.dateNow = now.toISOString();
            this.answers.niceDate = now.yyyymmdd();

            this.answers.copyrightNotice = "Copyright (c) " + now.getFullYear() + " " + this.answers.pluginAuthorName;
            this.answers.pluginDownloadUrl = "???";
            this.answers.pluginDocsUrl = "???";
            this.answers.pluginReleasesUrl = "???";
            this.answers.pluginCloneUrl = "???";
            if (this.answers.pluginAuthorGithub) {
                this.answers.pluginDownloadUrl = "https://github.com/" + this.answers.pluginAuthorGithub + "/" + this.answers.pluginDirName + "/archive/master.zip";
                this.answers.pluginDocsUrl = "https://github.com/" + this.answers.pluginAuthorGithub + "/" + this.answers.pluginDirName + "/blob/master/README.md";
                this.answers.pluginReleasesUrl = "https://raw.githubusercontent.com/" + this.answers.pluginAuthorGithub + "/" + this.answers.pluginDirName + "/master/releases.json";
                this.answers.pluginCloneUrl = "https://github.com/" + this.answers.pluginAuthorGithub + "/" + this.answers.pluginDirName + ".git";
                }

/* -- Clean up the various handle names, and convert them to arrays */

            var subPrefixHandles = ["controllerName", "elementName", "fieldName", "modelName", "purchasableName", "recordName", "serviceName", "taskName", "widgetName"];
            var _this = this;

            subPrefixHandles.forEach(function(subElement) {
                if (typeof _this.answers[subElement] != 'undefined') {
                    _this.answers[subElement] = _this.answers[subElement].split(',');
                    _this.answers[subElement].forEach(function(nameElement, nameIndex, nameArray) {
                        nameArray[nameIndex] = nameElement.prefixize();
                        });
                    }
                });

            done();
            }.bind(this));
        },
コード例 #29
0
ファイル: login.js プロジェクト: webdesignio/webdesignio-cli
function * login ({ rc = {}, argv: { _: [, url], identifier } }) {
  const parsedURL = parseURL(url)
  if (!url) return Promise.reject(new UserError('An `url` is required'))
  const email = yield readAsync({ prompt: 'E-Mail: ' })
  const password = yield readAsync({ prompt: 'Password: '******'*' })
  rc.url = url
  process.stdout.write('Attempting registration ...')
  const registrationRes = yield request({
    url: `${url}/api/v1/users`,
    method: 'POST',
    json: { email, password }
  })
  if (registrationRes.statusCode === 201) {
    console.log(' registered')
  } else if (registrationRes.statusCode !== 409) {
    console.log(' fail')
    throw new UserError(registrationRes.body || registrationRes.statusMessage)
  } else {
    console.log(' exists')
  }
  process.stdout.write('Fetching token ...')
  const res = yield request({
    url: `${url}/api/v1/tokens`,
    method: 'POST',
    json: { email, password }
  })
  console.log(' done')
  console.log()
  if ((res.statusCode / 100 | 0) !== 2) {
    throw new UserError(res.body || res.statusMessage)
  }
  rc.token = res.body.token
  let id = rc.id
  if (!id) {
    console.log(
      '    Now I need the website identifier. ' +
      chalk.yellow.bold('This identifier must be unique') +
      '.'
    )
    console.log('    It\'s the name of your website\'s subdomain.')
    console.log(
      '    (e.g. ' + chalk.cyan.bold(identifier || 'my-awesome-website') +
      ' which would up in ' +
      chalk.cyan.underline(
        parsedURL.protocol + '//' +
        chalk.bold(identifier || 'my-awesome-website') + '.' +
        parsedURL.host
      ) + ').'
    )
    let retry = false
    do {
      console.log()
      id = yield readAsync({ prompt: 'Identifier', default: identifier })
      const res = yield request({
        url: `${url}/api/v2/websites/${id}`,
        headers: { Authorization: `Bearer ${rc.token}` }
      })
      if ((res.statusCode / 100 | 0) === 2) {
        console.log()
        console.log('    ' + chalk.yellow.bold('Caution the website identifier is already taken!'))
        if (res.statusCode === 204) {
          console.log(
            '    ' +
            chalk.yellow.bold('You don\'t have access to the website ') +
            chalk.cyan.bold(id) + '.'
          )
        }
        console.log()
        const a = yield readAsync({ prompt: 'Change the identifier?', default: 'y' })
        retry = yn(a)
      } else {
        retry = false
      }
    } while (retry)
  }
  console.log()
  if (!id) throw new UserError('No identifier given!')
  rc.id = id
  yield writeFileAsync('.webdesigniorc.json', JSON.stringify(rc, null, 2))
  return 'Successfully logged in!'
}
コード例 #30
0
ファイル: index.js プロジェクト: ahars/generator-jhipster
        },

        composeLanguages() {
            if (this.configOptions.skipI18nQuestion) return;

            this.composeLanguagesSub(this, this.configOptions, 'server');
        }
    },

    writing: writeFiles(),

    end() {
        if (this.prodDatabaseType === 'oracle') {
            this.log('\n\n');
            this.warning(
                `${chalk.yellow.bold('You have selected Oracle database.\n')
                }Please follow our documentation on using Oracle to set up the \n` +
                'Oracle proprietary JDBC driver.'
            );
        }
        this.log(chalk.green.bold('\nServer application generated successfully.\n'));

        let executable = 'mvnw';
        if (this.buildTool === 'gradle') {
            executable = 'gradlew';
        }
        let logMsgComment = '';
        if (os.platform() === 'win32') {
            logMsgComment = ` (${chalk.yellow.bold(executable)} if using Windows Command Prompt)`;
        }
        this.log(chalk.green(`${'Run your Spring Boot application:' +