storybook/lib/cli/lib/helpers.js
Felipe K. De Boni 00433d8e95 Refactor CLI to use
Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, profile, prune,
    publish, rb, rebuild, repo, restart, root, run, run-script,
    s, se, search, set, shrinkwrap, star, stars, start, stop, t,
    team, test, token, tst, un, uninstall, unpublish, unstar,
    up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /Users/felipedeboni/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@5.6.0 /Users/felipedeboni/.nvm/versions/node/v9.5.0/lib/node_modules/npm and yarn install v1.5.1
[1/5] Validating package.json...
[2/5] Resolving packages...
success Already up-to-date.
Done in 1.69s. instead of third party packages #3274 #3060
2018-03-23 20:59:02 -03:00

165 lines
4.0 KiB
JavaScript

import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { sync as spawnSync } from 'cross-spawn';
import { gt } from 'semver';
import latestVersion from './latest_version';
import { version, devDependencies } from '../package.json';
const logger = console;
export async function getVersion(packageName) {
let current;
if (packageName === '@storybook/cli') {
current = version;
} else if (/storybook/.test(packageName)) {
current = devDependencies[packageName];
}
let latest;
try {
latest = await latestVersion(packageName);
} catch (e) {
if (current) {
logger.warn(`\n ${chalk.yellow(e.message)}`);
return current;
}
logger.error(`\n ${chalk.red(e.message)}`);
process.exit(1);
}
const versionToUse = current && gt(current, latest) ? current : latest;
return `^${versionToUse}`;
}
export function getVersions(...packageNames) {
return Promise.all(packageNames.map(getVersion));
}
export function getPackageJson() {
const packageJsonPath = path.resolve('package.json');
if (!fs.existsSync(packageJsonPath)) {
return false;
}
const jsonContent = fs.readFileSync(packageJsonPath, 'utf8');
return JSON.parse(jsonContent);
}
export function getBowerJson() {
const bowerJsonPath = path.resolve('bower.json');
if (!fs.existsSync(bowerJsonPath)) {
return false;
}
const jsonContent = fs.readFileSync(bowerJsonPath, 'utf8');
return JSON.parse(jsonContent);
}
export function writePackageJson(packageJson) {
const content = `${JSON.stringify(packageJson, null, 2)}\n`;
const packageJsonPath = path.resolve('package.json');
fs.writeFileSync(packageJsonPath, content, 'utf8');
}
export function getBabelRc() {
const babelRcPath = path.resolve('.babelrc');
if (!fs.existsSync(babelRcPath)) {
return false;
}
const babelRcContent = fs.readFileSync(babelRcPath, 'utf8');
return JSON.parse(babelRcContent);
}
export function writeBabelRc(babelRc) {
const content = `${JSON.stringify(babelRc, null, 2)}\n`;
const babelRcPath = path.resolve('.babelrc');
fs.writeFileSync(babelRcPath, content, 'utf8');
}
export function commandLog(message) {
process.stdout.write(chalk.cyan(' • ') + message);
const done = (errorMessage, errorInfo) => {
if (errorMessage) {
process.stdout.write(`. ${chalk.red('✖')}\n`);
logger.error(`\n ${chalk.red(errorMessage)}`);
if (!errorInfo) return;
const newErrorInfo = errorInfo
.split('\n')
.map(line => ` ${chalk.dim(line)}`)
.join('\n');
logger.error(`${newErrorInfo}\n`);
return;
}
process.stdout.write(`. ${chalk.green('✓')}\n`);
};
return done;
}
export function paddedLog(message) {
const newMessage = message
.split('\n')
.map(line => ` ${line}`)
.join('\n');
logger.log(newMessage);
}
export function getChars(char, amount) {
let line = '';
for (let lc = 0; lc < amount; lc++) { // eslint-disable-line
line += char;
}
return line;
}
export function codeLog(codeLines, leftPadAmount) {
let maxLength = 0;
const newLines = codeLines.map(line => {
maxLength = line.length > maxLength ? line.length : maxLength;
return line;
});
const finalResult = newLines
.map(line => {
const rightPadAmount = maxLength - line.length;
let newLine = line + getChars(' ', rightPadAmount);
newLine = getChars(' ', leftPadAmount || 2) + chalk.inverse(` ${newLine} `);
return newLine;
})
.join('\n');
logger.log(finalResult);
}
export function installDeps(options) {
let done = commandLog('Preparing to install dependencies');
done();
logger.log();
let result;
if (options.useYarn) {
result = spawnSync('yarn', { stdio: 'inherit' });
} else {
result = spawnSync('npm', ['install'], { stdio: 'inherit' });
}
logger.log();
done = commandLog('Installing dependencies');
if (result.status !== 0) {
done('An error occurred while installing dependencies.');
process.exit(1);
}
done();
}