Example #1
0
export function handleDone(webpackStats: Object) {
  spinner.stop()

  const stats = webpackStats.toJson({}, true)
  if (!webpackStats.hasErrors() && !webpackStats.hasWarnings()) {
    spinner.stream.write(
      logSymbols.success +
      colors.green(" Updated ") +
      `(in ${ formatTime(stats.time / 1000) })`
    )
    return
  }

  if (stats.errors.length) {
    spinner.text = colors.red("Update failed") + "\n"
    spinner.fail()
    spinner = makeSpinner()

    const errors = stats.errors.some(isSyntaxError)
      // Show syntax error first
      ? stats.errors.filter(isSyntaxError)
      : stats.errors
    errors.forEach((msg) => plainLog(`Error in ${ betterMsg(msg) }\n`, "error"))
    return
  }

  spinner.text = colors.yellow("Updated with warnings") + "\n"
  spinner.fail()
  spinner = makeSpinner()
  stats.warnings.forEach(
    (msg) => plainLog(`Warning in ${ betterMsg(msg) } \n`, "warning")
  )
}
export default async ({ datoClient, contentfulData }) => {
  let spinner = ora('Fetching existing models').start();

  const itemTypes = await datoClient.itemTypes.all();

  const importedItemTypes = itemTypes.filter((itemType) => {
    return contentfulData.contentTypes.some((contentType) => {
      return itemType.apiKey === toItemApiKey(contentType.sys.id);
    });
  });

  spinner.succeed();

  if (importedItemTypes.length > 0) {
    spinner = ora('').start();
    const progress = new Progress(
      importedItemTypes.length,
      'Destroying existing models',
    );

    spinner.text = progress.tick();

    for (const itemType of importedItemTypes) {
      try {
        spinner.text = progress.tick();
        await datoClient.itemTypes.destroy(itemType.id);
      } catch (e) {
        spinner.fail(e);
        process.exit();
      }
    }

    spinner.succeed();
  }
};
Example #3
0
 .then((result) => {
     if (updateBusinessNetwork === false) {
         spinner = ora('Starting business network definition. This may take a minute...').start();
         let startOptions = cmdUtil.parseOptions(argv);
         if (loglevel) {
             startOptions.logLevel = loglevel;
         }
         return adminConnection.start(businessNetworkDefinition, startOptions);
     } else {
         spinner = ora('Updating business network definition. This may take a few seconds...').start();
         return adminConnection.update(businessNetworkDefinition);
     }
 }).then((result) => {
function checkUnused(currentState) {
    var spinner = ora('Checking for unused packages. --skip-unused if you don\'t want this.');
    spinner.enabled = spinner.enabled && currentState.get('spinner');
    spinner.start();

    return new _promise2.default(function (resolve) {
        if (skipUnused(currentState)) {
            resolve(currentState);
        }

        var depCheckOptions = {
            ignoreDirs: ['sandbox', 'dist', 'generated', '.generated', 'build', 'fixtures'],
            ignoreMatches: ['gulp-*', 'grunt-*', 'karma-*', 'angular-*', 'babel-*', 'metalsmith-*', 'grunt', 'mocha', 'ava']
        };

        depcheck(currentState.get('cwd'), depCheckOptions, resolve);
    }).then(function (depCheckResults) {
        spinner.stop();
        var unusedDependencies = [].concat(depCheckResults.dependencies, depCheckResults.devDependencies);
        currentState.set('unusedDependencies', unusedDependencies);

        var cwdPackageJson = currentState.get('cwdPackageJson');

        // currently missing will return devDependencies that aren't really missing
        var missingFromPackageJson = _.omit(depCheckResults.missing || {}, (0, _keys2.default)(cwdPackageJson.dependencies), (0, _keys2.default)(cwdPackageJson.devDependencies));
        currentState.set('missingFromPackageJson', missingFromPackageJson);
        return currentState;
    });
}
Example #5
0
async function prodBuild (argv) {
  const spinner = ora(`building for ${argv.env} ...`)
  spinner.start()

  try {
    const config = await buildWebpackConfig(argv)
    await promisify(rm)('dist/')
    const stats = await promisify(webpack)(config)
    spinner.stop()

    if (stats.hasErrors()) {
      throw stats.toJson().errors
    }

    console.log(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  } catch (e) {
    console.error(e)
    process.exit(1)
  }
}
Example #6
0
async function devBuild (argv) {
  const spinner = ora('compiling ...')
  spinner.start()

  const port = argv.port
  const config = await buildWebpackConfig(argv)
  const compiler = webpack(config)
  compiler.plugin('done', stats => {
    spinner.stop()
    const serverAddr = `http://localhost:${chalk.bold(port)}`
    const localIpAddr = `http://${ip.address()}:${chalk.bold(port)}`

    if (stats.hasErrors()) {
      console.error(chalk.red('Build failed!\n\n'))
    } else {
      console.log(chalk.green('Compiled successfully!\n\n'))
      console.log('You can view the application in browser.\n\n')
      console.log(`${chalk.bold('Local:')}             ${serverAddr}\n`)
      console.log(`${chalk.bold('On Your Network:')}   ${localIpAddr}\n`)
    }
  })

  const server = new WebpackDevServer(compiler, config.devServer)
  server.listen(port)
}
Example #7
0
  const applyPlan = (envDir, tempPlan) => {
    const spinner = ora('Applying the plan')
    spinner.stream = process.stdout
    spinner.start()

    const applyCmd = spawn('terraform', applyCmdOptions(tempPlan), {cwd: envDir})

    applyCmd.stdout.on('data', data => {
      console.log(data.toString())
      spinner.clear()
    })

    applyCmd.stderr.on('data', data => {
      console.log(data.toString())
      spinner.clear()
    })

    applyCmd.on('close', code => {
      if (code !== 0) {
        console.log(chalk.red(`terraform apply had a non-zero exit code (${code}), please review`))
      }

      fs.unlink(tempPlan)
      spinner.stop()

      process.exit(code)
    })
  }
Example #8
0
 return ev => {
   switch (ev.phase) {
     case 'start': {
       const spinner = 'earth';
       events[ev.type] = ora({
         text: ev.msg,
         spinner
       }).start();
       return;
     }
     case 'progress': {
       const spinner = events[ev.type];
       if (spinner) spinner.text = ev.msg;
       return;
     }
     case 'stop':
     default: {
       const spinner = events[ev.type];
       if (spinner) {
         spinner.stopAndPersist({ text: ev.msg, symbol: logSymbols.success });
         delete events[ev.type];
       }
       return;
     }
   }
 };
Example #9
0
function getEventLocationLatLng(data, callback) {
  const progressIndicator = ora(
    'Getting event location latitude and longitude'
  ).start();
  const { eventLocation } = data;

  request.get(
    {
      url: `${GOOGLE_MAPS_API_URL}/geocode/json`,
      json: true,
      qs: {
        address: eventLocation,
        key: NODESCHOOL_SEA_GOOGLE_MAPS_API_KEY
      }
    },
    function (error, response, body) {
      if (error) {
        console.log('geocoding error', error);
        progressIndicator.stopAndPersist(FAILURE_SYMBOL);
        callback(error);
        return;
      }
      progressIndicator.stopAndPersist(SUCCESS_SYMBOL);
      const eventLocationCoordinates =
        _.get(body, 'results[0].geometry.location') ||
        NODESCHOOL_SEA_DEFAULT_EVENT_COORDS;
      const updatedData = _.assign(data, {
        eventLocationCoordinates
      });
      callback(null, updatedData);
    }
  );
}
Example #10
0
export default async function loginCommand(username) {
	const {password} = await inquirer.prompt([{
		type: 'password',
		name: 'password',
		message: 'MyAnimeList password: '******'Verifying credentials').start();

	try {
		user.setUser(username, password);

		const authResponse = await user.verifyAuth();

		debug('Auth succeeded with', authResponse);

		spinner.stop();

		config.set('username', username);
		config.set('password', password);

		console.log(green('Logged in!'));
	} catch (err) {
		spinner.stop();

		console.log(red('Failed to login'), err.message);
	}
}
Example #11
0
	return new Promise((resolve, reject) => {
		let spinner = ora('Generate production package.json ...').start();
		let excludeField = ['scripts', 'devDependencies', 'build', 'directories'];
		let proPackageJson = {};
		let currentPkgInfo = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'));

		Object.keys(currentPkgInfo).forEach((item) => {
			if (excludeField.indexOf(item) === -1) {
				proPackageJson[item] = currentPkgInfo[item];
			}
		});

		proPackageJson.main = './main/app.js';

		// delete vue production dependencies
		Object.keys(proPackageJson.dependencies).forEach((item) => {
			if (/vue/.test(item)) {
				delete proPackageJson.dependencies[item];
			}
		});
		let distPath = path.join(__dirname, '../dist/package.json');
		if (!fs.existsSync(path.join(__dirname, '../dist'))) {
			fs.mkdirSync(path.join(__dirname, '../dist'));
		}
		fs.writeFile(distPath, jsbeautify(JSON.stringify(proPackageJson), {
			'indent_with_tabs': true,
			'indent_size': 4
		}), 'utf-8', function() {
			spinner.stop();
			logger.success('Generate production package.json succeed.');
			resolve();
		});
	});
Example #12
0
runPath.forEach((_folder) => {
    const webpackConfig = new webpackProd(_folder)
    const spinner = ora(`${_folder} building for production...`)
    const dist = path.resolve(__dirname, '../dist', _folder)
    const uselessFiles = [
        path.resolve(__dirname, `../dist/${_folder}/*.js`),
        path.resolve(__dirname, `../dist/${_folder}/*.css`),
    ]

    spinner.start()

    rm(dist, err => {
        if (err) throw err
        webpack(webpackConfig, (err, stats) => {
            spinner.stop()
            if (err) throw err
            uselessFiles.map((file) => {
                rm(file, err => {
                    if (err) throw err
                })
            })
            // process.stdout.write(stats.toString({
            //     colors: true,
            //     modules: false,
            //     children: false,
            //     chunks: false,
            //     chunkModules: false,
            // }) + '\n\n')
            console.log(chalk.cyan(`${_folder} pkg success!\n`))
        })
    })
})
Example #13
0
   /**
    * Command process for install command
    * @param {string} argv argument list from composer command
    * @return {Promise} promise when command complete
    */
    static handler(argv) {
        const cardName = argv.card;
        const installOptions = cmdUtil.parseOptions(argv);
        const adminConnection = cmdUtil.createAdminConnection();

        const spinner = ora('Installing business network. This may take a minute...').start();
        let definition;

        return adminConnection.connect(cardName).then(() => {
            const businessNetworkArchive = cmdUtil.getArchiveFileContents(argv.archiveFile);
            return BusinessNetworkDefinition.fromArchive(businessNetworkArchive);
        }).then((definition_) => {
            definition = definition_;
            return adminConnection.install(definition, installOptions);
        }).then((result) => {
            spinner.succeed();
            cmdUtil.log(chalk.bold.blue(`Successfully installed business network ${definition.getName()}, version ${definition.getVersion()}`));
            cmdUtil.log();
            return result;
        }).catch((error) => {
            spinner.fail();
            cmdUtil.log();
            throw error;
        });
    }
Example #14
0
gulp.task('css-concat', function () {
	var concat = require('gulp-concat-css');
	var through = require('through2');

	src = src || './*.css';
	src = src.split(/\s*,\s*/);
	if (!dest) throw Error('Define output file as `amaze css-concat -d ./file.css`');

	//setup spinner
	const spinner = ora({
		text: `Concatting '${src}' to ${dest}`,
		spinner: spinners.pipe,
		color: 'white'
	});
	spinner.start();
	var t = now();


	return gulp.src(src, {base: './'})
		.pipe(concat(dest, options))
		.pipe(gulp.dest('./'))
		.on('end', function () {
			console.log(` finished after ${(now() - t).toFixed(0)}ms.`)
			spinner.stop();
		});
});
Example #15
0
export default function dump(
  configFile,
  itemsRepo,
  quiet = false,
  destinationPath = process.cwd(),
) {
  /* eslint-disable global-require, import/no-dynamic-require */
  delete require.cache[configFile];
  const config = require(configFile);
  /* eslint-enable global-require, import/no-dynamic-require */

  i18n.availableLocales = itemsRepo.site.locales;
  [i18n.locale] = i18n.availableLocales;

  const startOperation = start(
    destinationPath,
    config.bind(config, itemsRepo),
  );

  const spinner = ora('Writing content').start();

  return startOperation()
    .then((operations) => {
      spinner.succeed();
      if (!quiet) {
        process.stdout.write('\n');
        operations.forEach(operation => process.stdout.write(`* ${operation}\n`));
        process.stdout.write('\n');
      }
    })
    .catch((e) => {
      spinner.fail();
      process.stderr.write(new PrettyError().render(e));
    });
}
Example #16
0
function processData(currentState) {
    const cwdPackageJson = currentState.get('cwdPackageJson');

    spinner = ora(`Checking the npm registry.`);
    spinner.enabled = currentState.get('spinner');
    spinner.start();

    function dependencies(pkg) {
        if (currentState.get('global')) {
            return currentState.get('globalPackages');
        }

        if (currentState.get('ignoreDev')) {
            return pkg.dependencies;
        }

        return merge(pkg.dependencies, pkg.devDependencies);
    }

    const allDependencies = Object.keys(dependencies(cwdPackageJson));

    const npmPromises = allDependencies.map(moduleName => processModule(moduleName, currentState));

    return Promise.all(npmPromises)
        .then(arrayOfPackageInfo => {
            const arrayOfPackageInfoCleaned = arrayOfPackageInfo
                    .filter(Boolean);

            currentState.set('packages', arrayOfPackageInfoCleaned);

            spinner.stop();
            return currentState;
        });
}
Example #17
0
    return co(function *() {
        yield getUnusedPackages(currentState);

        const spinner = ora(`Checking npm registries for updated packages.`);
        spinner.enabled = spinner.enabled && currentState.get('spinner');
        spinner.start();

        const cwdPackageJson = currentState.get('cwdPackageJson');

        function dependencies(pkg) {
            if (currentState.get('global')) {
                return currentState.get('globalPackages');
            }

            if (currentState.get('ignoreDev')) {
                return pkg.dependencies;
            }

            return merge(pkg.dependencies, pkg.devDependencies);
        }

        const allDependencies = dependencies(cwdPackageJson);
        const allDependenciesIncludingMissing = Object.keys(merge(allDependencies, currentState.get('missingFromPackageJson')));

        const arrayOfPackageInfo = yield allDependenciesIncludingMissing
            .map(moduleName => createPackageSummary(moduleName, currentState))
            .filter(Boolean);

        currentState.set('packages', arrayOfPackageInfo);

        spinner.stop();
        return currentState;
    });
function cloneRepo(root) {
    const spinner = ora('start download template...')
    spinner.start()
    console.log()

    return new Promise((resolve, rejct) => {
        command = 'git'
        args = [
            'clone'
        ].concat([
            templateRepository,
            root
        ])

        const child = spawn(command, args, { stdio: 'inherit' })
        child.on('close', code => {
            if (code !== 0) {
                reject({
                    command: `${command} ${args.join(' ')}`,
                })
                spinner.fail('clone template failed')
                return
            }
            removeRedundant(root)
            spinner.succeed('clone template succeed')
            resolve()
        })
    })
}
      function takeScreenshotForUrlAtWidths(url, widths, context) {
        var messageStart = 'Navigating to: ';
        var truncateLength = process.stdout.columns - 10 - messageStart.length;

        spinner = ora({
          text: messageStart + chalk.underline(truncate(url, truncateLength)),
          spinner: 'bounce'
        }).start();
        return navigateToUrl(url)
          .then(function() {
            console.log(' ✅');
            spinner.stop();
          },
          function (err) {
            if (/Authorization required/i.test(err.message)) {
              console.error( chalk.red('\n\nAuthorization error: check your API credentials') );
              process.exit(1);
            }
          })
          .then(function() {
            if (urlDelayMs) {
              console.log('\t\tdelay for ' + urlDelayS + 'sec');
              return delayPromise(urlDelayMs);
            } else {
              return Promise.resolve();
            }
          })
          .then(
            function() {
              return takeScreenshotsAtWidths(widths, url, context);
            },
            createErrorHandler('Error navigating to url: ' + url)
        );
      }
Example #20
0
module.exports = (middleware, args) => {
  const commandName = args._[0];
  const spinner = args.quiet ? null : ora(`Running ${commandName}`).start();
  const options = merge({
    args,
    debug: args.debug,
    quiet: args.quiet,
    env: {
      NODE_ENV: 'production'
    }
  }, args.options);
  const api = Neutrino(options);

  api.register(`${commandName}-cli`, (config, api) => api.commands[commandName](config, api));

  return api
    .run(`${commandName}-cli`, middleware)
    .fork((errors) => {
      if (!args.quiet) {
        spinner.fail(`Running ${commandName} failed`);
        errors.forEach(err => console.error(err));
      }

      process.exit(1);
    }, (output) => {
      if (!args.quiet) {
        spinner.succeed(`Running ${commandName} completed`);
        console.log(output);
      }
    });
};
Example #21
0
linter.lintFiles = function (files, standardOptions, done) {
  let index = 0
  const spinner = (files.length > 3) ? ora().start() : {}

  if (typeof standardOptions === 'function') {
    done = standardOptions
    standardOptions = {}
  }
  return Promise.all(files.map((file) => {
    spinner.text = 'Linting file ' + (++index) + ' of ' + files.length

    return new Promise((resolve, reject) => {
      linter.lintText(fs.readFileSync(file, 'utf8'), standardOptions, (err, errors, outputText) => {
        if (err) return reject(err)
        return resolve({
          file: file,
          errors: errors,
          input: fs.readFileSync(file, 'utf8'),
          output: outputText
        })
      })
    })
  })).then((results) => {
    console.log('\n')
    return done(null, results)
  }).catch((err) => {
    return done(err)
  })
}
Example #22
0
let startSpinner = (message, type) => {
    let spinner = ora();
    spinner.text = message;
    spinner.color = type;
    spinner.start();
    return spinner;
};
Example #23
0
module.exports = function(word, callback) {
  const spinner = ora().start();
  // say it
  try {
    if (!process.env.CI) {
      require('say').speak(word, isChinese(word) ? 'Ting-Ting' : null);
    }
  } catch(e) {
    // do nothing
  }

  let count = 0;
  const callbackAll = () => {
    count += 1;
    if (count >= 3) {
      spinner.stop();
      callback && callback();
    }
  };

  word = encodeURIComponent(word);

  // iciba
  request.get(SOURCE.iciba.replace('${word}', word), function (error, response, body) {
    if (!error && response.statusCode == 200) {
      parseString(body, function (err, result) {
        if (err) {
          return;
        }
        print.iciba(result.dict);
      });
    }
    callbackAll();
  });

  // youdao
  request.get(SOURCE.youdao.replace('${word}', word), function (error, response, body) {
    if (!error && response.statusCode == 200) {
      try {
        const data = JSON.parse(entities.decode(body));
        print.youdao(data);
      } catch(e) {
        // 来自您key的翻译API请求异常频繁,为保护其他用户的正常访问,只能暂时禁止您目前key的访问
      }
    }
    callbackAll();
  });

  // dictionaryapi
  request.get(SOURCE.dictionaryapi.replace('${word}', word), function (error, response, body) {
    if (!error && response.statusCode == 200) {
      parseString(body, function (err, result) {
        if (!err) {
          print.dictionaryapi(result.entry_list.entry, word);
        }
      });
    }
    callbackAll();
  });
};
Example #24
0
function go() {
	spinner = ora({
		text: 'Loading with spinner "' + spinners[spinIndex] + '"',
		spinner: spinners[spinIndex],
		color: 'yellow'
	});
	spinner.start();
}
Example #25
0
 .then (() => {
     spinner = ora('Downloading deployed Business Network Archive').start();
     return businessNetworkConnection.connect(Download.getDefaultProfileName(argv), argv.businessNetworkName, argv.enrollId, argv.enrollSecret)
         .then((result) => {
             businessNetworkDefinition = result;
             return businessNetworkConnection.disconnect();
         });
 })
Example #26
0
  .command('run', 'Run code on HackerEarth server', (yargs) => {
    var argv = yargs
      .usage('Usage: $0 run <options>')
      .demand(['s', 'i', 'o'])
      .alias('s', 'source').describe('s', 'Source Code file path')
      .alias('i', 'input').describe('i', 'Input file path')
      .alias('l', 'language').describe('l', 'Language. Change `config` for default.')
      .alias('o', 'output').describe('o', 'Output file path')
      .example('$0 run -s A.cpp -i Input00.in -o Output.txt -l CPP11')
      .argv;

    checkClientSecret();

    const source = fs.readFileSync(argv.source, 'utf8');
    var input = fs.readFileSync(argv.input, 'utf8');
    const output = argv.output;
    const spinner = ora('Running').start();
    const lang = argv.language === undefined ? config.default_lang : argv.language;
    var data = {
      'client_secret': config.CLIENT_SECRET,
      'async': 0,
      'input': input,
      'source': source,
      'lang': lang,
      'time_limit': config.time_limit,
      'memory_limit': config.memory_limit
    };
    request.post({url: RUN_URL, form: data}, (err, response) => {
      if (err) {
        spinner.stop();
        console.log(chalk.red('Error Occured'));
        openIssue();
      } else {
        spinner.stop();
        const result = JSON.parse(response.body);
        if (result.compile_status !== 'OK') {
          console.log(chalk.red('Compilation Error'));
          console.log(chalk.red(result.compile_status));
          process.exit(-1);
        }
        const runStatus = result.run_status;
        var data = runStatus.output === undefined ? '' : runStatus.output;
        fs.writeFileSync(output, data, 'utf8');
        var table = new Table({
          head: ['Message', 'Memory', 'Time', 'Web Link'],
          colWidths: [10, 10, 10, 40]
        });
        table.push([
          runStatus['status'],
          runStatus['memory_used'],
          runStatus['time_used'],
          result['web_link']
        ]);
        console.log(table.toString());
        end();
      }
    });
  })
Example #27
0
	return new Promise((resolve, reject) => {
		let spinner = ora('Building asar file ...').start();
		let currentPkgInfo = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8'));
		asar.createPackage(distPath, path.join(__dirname, `../asar/app-${currentPkgInfo.version}.asar`), function() {
			spinner.stop();
			logger.success('Building asar file successd.');
			resolve();
		});
	});
Example #28
0
 .action(function act(args, callback) {
   const spinner = ora('Loading news')
   spinner.start()
   api.getTopNews().then((topNewsList) => {
     spinner.stop()
     displayNews(topNewsList, this)
     callback()
   }).catch(() => callback())
 })
Example #29
0
 constructor(platform, environment) {
   this.platform = platform
   this.environment = environment
   this.config = new WebpackConfig(this.environment, this.platform).build()
   this.spinner = ora({
     text: chalk.cyan('Building Electron application'),
     color: 'cyan'
   })
 }
Example #30
0
const wait = msg => {
  const spinner = ora(gray(msg))
  spinner.color = 'gray'
  spinner.start()

  return () => {
    spinner.stop()
    process.stdout.write(eraseLines(1))
  }
}