UNPKG

bit-bin

Version:

<a href="https://opensource.org/licenses/Apache-2.0"><img alt="apache" src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"></a> <a href="https://github.com/teambit/bit/blob/master/CONTRIBUTING.md"><img alt="prs" src="https://img.shields.io/b

620 lines (476 loc) 18.1 kB
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _bluebird() { const data = require("bluebird"); _bluebird = function () { return data; }; return data; } function _defineProperty2() { const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); _defineProperty2 = function () { return data; }; return data; } function _padRight() { const data = _interopRequireDefault(require("pad-right")); _padRight = function () { return data; }; return data; } function _chalk() { const data = _interopRequireDefault(require("chalk")); _chalk = function () { return data; }; return data; } function _tar() { const data = _interopRequireDefault(require("tar")); _tar = function () { return data; }; return data; } function path() { const data = _interopRequireWildcard(require("path")); path = function () { return data; }; return data; } function _child_process() { const data = _interopRequireDefault(require("child_process")); _child_process = function () { return data; }; return data; } function _chai() { const data = require("chai"); _chai = function () { return data; }; return data; } function _tagCmd() { const data = require("../cli/commands/public-cmds/tag-cmd"); _tagCmd = function () { return data; }; return data; } function _utils() { const data = require("../utils"); _utils = function () { return data; }; return data; } function _runInteractiveCmd() { const data = _interopRequireDefault(require("../interactive/utils/run-interactive-cmd")); _runInteractiveCmd = function () { return data; }; return data; } function _constants() { const data = require("../constants"); _constants = function () { return data; }; return data; } function _featureToggle() { const data = require("../api/consumer/lib/feature-toggle"); _featureToggle = function () { return data; }; return data; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2().default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } const DEFAULT_DEFAULT_INTERVAL_BETWEEN_INPUTS = 200; /** * to enable a feature for Helper instance, in the e2e-test file add `helper.command.setFeatures('your-feature');` * to enable a feature for a single command, add the feature to the runCmd, e.g. `runCmd(cmd, cwd, stdio, 'your-feature');` * if you set both, the runCmd wins. * more about feature-toggle head to feature-toggle.ts file. */ class CommandHelper { constructor(scopes, debugMode) { (0, _defineProperty2().default)(this, "scopes", void 0); (0, _defineProperty2().default)(this, "debugMode", void 0); (0, _defineProperty2().default)(this, "bitBin", void 0); (0, _defineProperty2().default)(this, "featuresToggle", void 0); this.scopes = scopes; this.debugMode = debugMode; this.bitBin = process.env.npm_config_bit_bin || 'bit'; // e.g. npm run e2e-test --bit_bin=bit-dev } setFeatures(featuresToggle) { this.featuresToggle = featuresToggle; } resetFeatures() { this.featuresToggle = undefined; } runCmd(cmd, cwd = this.scopes.localPath, stdio = 'pipe', overrideFeatures) { if (this.debugMode) console.log((0, _padRight().default)(_chalk().default.green('cwd: '), 20, ' '), cwd); // eslint-disable-line no-console const isBitCommand = cmd.startsWith('bit '); if (isBitCommand) cmd = cmd.replace('bit', this.bitBin); const featuresTogglePrefix = isBitCommand ? this._getFeatureToggleCmdPrefix(overrideFeatures) : ''; cmd = featuresTogglePrefix + cmd; if (this.debugMode) console.log((0, _padRight().default)(_chalk().default.green('command: '), 20, ' '), cmd); // eslint-disable-line no-console // const cmdOutput = childProcess.execSync(cmd, { cwd, shell: true }); const cmdOutput = _child_process().default.execSync(cmd, { cwd, stdio }); if (this.debugMode) console.log((0, _padRight().default)(_chalk().default.green('output: '), 20, ' '), _chalk().default.cyan(cmdOutput.toString())); // eslint-disable-line no-console return cmdOutput.toString(); } _getFeatureToggleCmdPrefix(overrideFeatures) { const featuresToggle = overrideFeatures || this.featuresToggle; if (!featuresToggle) return ''; const featureToggleStr = `${_featureToggle().ENV_VAR_FEATURE_TOGGLE}=${featuresToggle}`; if (process.platform === 'win32') { return `set "${featureToggleStr}" && `; } return `${featureToggleStr} `; } listRemoteScope(raw = true, options = '') { return this.runCmd(`bit list ${this.scopes.remote} ${options} ${raw ? '--raw' : ''}`); } listLocalScope(options = '') { return this.runCmd(`bit list ${options}`); } listLocalScopeParsed(options = '') { const output = this.runCmd(`bit list --json ${options}`); return JSON.parse(output); } listRemoteScopeParsed(options = '') { const output = this.runCmd(`bit list ${this.scopes.remote} --json ${options}`); return JSON.parse(output); } listScopeParsed(scope, options = '') { const output = this.runCmd(`bit list ${scope} --json ${options}`); return JSON.parse(output); } catScope(includeExtraData = false) { const extraData = includeExtraData ? '--json-extra' : ''; const result = this.runCmd(`bit cat-scope --json ${extraData}`); return JSON.parse(result); } catObject(hash, parse = false) { const result = this.runCmd(`bit cat-object ${hash}`); if (!parse) return result; return JSON.parse(result); } catComponent(id, cwd, parse = true) { const result = this.runCmd(`bit cat-component ${id} --json`, cwd); return parse ? JSON.parse(result) : result; } addComponent(filePaths, options = {}, cwd = this.scopes.localPath) { const value = typeof options === 'string' ? options : Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); return this.runCmd(`bit add ${filePaths} ${value}`, cwd); } getConfig(configName) { return this.runCmd(`bit config get ${configName}`); } delConfig(configName) { return this.runCmd(`bit config del ${configName}`); } setConfig(configName, configVal) { return this.runCmd(`bit config set ${configName} ${configVal}`); } untrackComponent(id = '', all = false, cwd = this.scopes.localPath) { return this.runCmd(`bit untrack ${id} ${all ? '--all' : ''}`, cwd); } removeComponent(id, flags = '') { return this.runCmd(`bit remove ${id} ${flags}`); } deprecateComponent(id, flags = '') { return this.runCmd(`bit deprecate ${id} ${flags}`); } undeprecateComponent(id, flags = '') { return this.runCmd(`bit undeprecate ${id} ${flags}`); } tagComponent(id, tagMsg = 'tag-message', options = '') { return this.runCmd(`bit tag ${id} -m ${tagMsg} ${options}`); } tagWithoutMessage(id, version = '', options = '') { return this.runCmd(`bit tag ${id} ${version} ${options}`); } tagAllComponents(options = '', version = '', assertTagged = true) { const result = this.runCmd(`bit tag -a ${version} ${options}`); if (assertTagged) (0, _chai().expect)(result).to.not.have.string(_tagCmd().NOTHING_TO_TAG_MSG); return result; } // @todo: change to tagAllComponents tagAllComponentsNew(options = '', version = '', assertTagged = true) { const result = this.runCmd(`bit tag -a ${version} ${options}`); if (assertTagged) (0, _chai().expect)(result).to.not.have.string(_tagCmd().NOTHING_TO_TAG_MSG); return result; } rewireAndTagAllComponents(options = '', version = '', assertTagged = true) { this.linkAndRewire(); return this.tagAllComponentsNew(options, version, assertTagged); } tagScope(version, message = 'tag-message', options = '') { return this.runCmd(`bit tag -s ${version} -m ${message} ${options}`); } untag(id) { return this.runCmd(`bit untag ${id}`); } exportComponent(id, scope = this.scopes.remote, assert = true, flags = '') { const result = this.runCmd(`bit export ${scope} ${id} ${flags}`); if (assert) (0, _chai().expect)(result).to.not.have.string('nothing to export'); return result; } exportAllComponents(scope = this.scopes.remote) { return this.runCmd(`bit export ${scope} --force`); } exportAllComponentsAndRewire(scope = this.scopes.remote) { return this.runCmd(`bit export ${scope} --rewire --force`); } exportToCurrentScope(ids) { return this.runCmd(`bit export ${_constants().CURRENT_UPSTREAM} ${ids || ''}`); } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! export(options = '') { // --force just silents the prompt, which obviously needed for CIs return this.runCmd(`bit export --force ${options}`); } ejectComponents(ids, flags) { return this.runCmd(`bit eject ${ids} ${flags || ''}`); } ejectComponentsParsed(ids, flags) { const result = this.runCmd(`bit eject ${ids} ${flags || ''} --json`); const jsonStart = result.indexOf('{'); const jsonResult = result.substring(jsonStart); return JSON.parse(jsonResult); } importComponent(id) { return this.runCmd(`bit import ${this.scopes.remote}/${id}`); } importManyComponents(ids) { const idsWithRemote = ids.map(id => `${this.scopes.remote}/${id}`); return this.runCmd(`bit import ${idsWithRemote.join(' ')}`); } importComponentWithOptions(id = 'bar/foo.js', options) { const value = Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); return this.runCmd(`bit import ${this.scopes.remote}/${id} ${value}`); } importAllComponents(writeToFileSystem = false) { return this.runCmd(`bit import ${writeToFileSystem ? '--merge' : ''}`); } isolateComponent(id, flags) { const isolatedEnvOutput = this.runCmd(`bit isolate ${this.scopes.remote}/${id} ${this.scopes.remotePath} ${flags}`); const isolatedEnvOutputArray = isolatedEnvOutput.split('\n').filter(str => str); return isolatedEnvOutputArray[isolatedEnvOutputArray.length - 1]; } isolateComponentWithCapsule(id, capsuleDir) { return this.runCmd(`bit isolate ${id} --use-capsule --directory ${capsuleDir}`); } getCapsuleOfComponent(id) { const capsulesJson = this.runCmd('bit capsule-list -j'); const capsules = JSON.parse(capsulesJson); const capsulePath = capsules.capsules.find(c => c.endsWith(id)); if (!capsulePath) throw new Error(`unable to find the capsule for ${id}`); return capsulePath; } importExtension(id) { return this.runCmd(`bit import ${id} --extension`); } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! build(id = '') { return this.runCmd(`bit build ${id}`); } buildComponentWithOptions(id = '', options, cwd = this.scopes.localPath) { const value = Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); return this.runCmd(`bit build ${id} ${value}`, cwd); } testComponent(id = '') { return this.runCmd(`bit test ${id}`); } testComponentWithOptions(id = '', options, cwd = this.scopes.localPath) { const value = Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); return this.runCmd(`bit test ${id} ${value}`, cwd); } status() { return this.runCmd('bit status'); } statusJson() { const status = this.runCmd('bit status --json'); return JSON.parse(status); } expectStatusToBeClean() { const statusJson = this.statusJson(); Object.keys(statusJson).forEach(key => { (0, _chai().expect)(statusJson[key], `status.${key} should be empty`).to.have.lengthOf(0); }); } expectStatusToNotHaveIssues() { const statusJson = this.statusJson(); ['componentsWithMissingDeps', 'invalidComponents'].forEach(key => { (0, _chai().expect)(statusJson[key], `status.${key} should be empty`).to.have.lengthOf(0); }); } statusComponentIsStaged(id) { const status = this.statusJson(); return status.stagedComponents.includes(id); } statusComponentIsModified(id) { const status = this.statusJson(); return status.modifiedComponent.includes(id); } showComponent(id = 'bar/foo') { return this.runCmd(`bit show ${id}`); } showComponentParsed(id = 'bar/foo') { const output = this.runCmd(`bit show ${id} --json`); return JSON.parse(output); } showComponentWithOptions(id = 'bar/foo', options) { const value = Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); return this.runCmd(`bit show ${id} ${value}`); } checkoutVersion(version, ids, flags, cwd) { return this.runCmd(`bit checkout ${version} ${ids} ${flags || ''}`, cwd); } checkout(values) { return this.runCmd(`bit checkout ${values}`); } mergeVersion(version, ids, flags) { return this.runCmd(`bit merge ${version} ${ids} ${flags || ''}`); } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! diff(id = '') { const output = this.runCmd(`bit diff ${id}`); return (0, _utils().removeChalkCharacters)(output); } log(id) { return this.runCmd(`bit log ${id}`); } move(from, to) { return this.runCmd(`bit move ${path().normalize(from)} ${path().normalize(to)}`); } runTask(taskName) { return this.runCmd(`bit run ${taskName}`); } create(name) { return this.runCmd(`bit create ${name}`); } moveComponent(id, to) { return this.runCmd(`bit move ${id} ${path().normalize(to)} --component`); } link(flags) { return this.runCmd(`bit link ${flags || ''}`); } linkAndRewire(ids = '') { return this.runCmd(`bit link ${ids} --rewire`); } packComponent(id, options, extract = false) { const defaultOptions = { o: '', p: '', k: '', j: '' }; options = _objectSpread({}, defaultOptions, {}, options); const value = Object.keys(options).map(key => `-${key} ${options[key]}`).join(' '); const result = this.runCmd(`bit pack ${id} ${value}`); if (extract) { if (!options || // We don't just check that it's falsy because usually it's an empty string. // eslint-disable-next-line no-prototype-builtins !options.hasOwnProperty('-json') && !options.hasOwnProperty('j') || !options['-out-dir'] && !options.d) { throw new Error('extracting supporting only when packing with json and out-dir'); } const resultParsed = JSON.parse(result); if (!resultParsed || !resultParsed.tarPath) { throw new Error('npm pack results are invalid'); } const tarballFilePath = resultParsed.tarPath; const dir = options.d || options['-out-dir']; if (this.debugMode) { console.log(`untaring the file ${tarballFilePath} into ${dir}`); // eslint-disable-line no-console } _tar().default.x({ file: tarballFilePath, C: dir, sync: true }); } return result; } ejectConf(id = 'bar/foo', options) { const value = options ? Object.keys(options) // $FlowFixMe .map(key => `-${key} ${options[key]}`).join(' ') : ''; return this.runCmd(`bit eject-conf ${id} ${value}`); } injectConf(id = 'bar/foo', options) { const value = options ? Object.keys(options) // $FlowFixMe .map(key => `-${key} ${options[key]}`).join(' ') : ''; return this.runCmd(`bit inject-conf ${id} ${value}`); } doctor(options) { const parsedOpts = this.parseOptions(options); return this.runCmd(`bit doctor ${parsedOpts}`); } doctorOne(diagnosisName, options, cwd) { const parsedOpts = this.parseOptions(options); return this.runCmd(`bit doctor "${diagnosisName}" ${parsedOpts}`, cwd); } doctorList(options) { const parsedOpts = this.parseOptions(options); return this.runCmd(`bit doctor --list ${parsedOpts}`); } doctorJsonParsed() { const result = this.runCmd('bit doctor --json'); return JSON.parse(result); } parseOptions(options) { const value = Object.keys(options).map(key => { const keyStr = key.length === 1 ? `-${key}` : `--${key}`; return `${keyStr} ${options[key]}`; }).join(' '); return value; } runInteractiveCmd({ args = [], inputs = [], // Options for the process (execa) processOpts = { cwd: this.scopes.localPath }, // opts for interactive opts = { defaultIntervalBetweenInputs: DEFAULT_DEFAULT_INTERVAL_BETWEEN_INPUTS, verbose: false } }) { var _this = this; return (0, _bluebird().coroutine)(function* () { const processName = _this.bitBin || 'bit'; opts.verbose = !!_this.debugMode; const { stdout } = yield (0, _runInteractiveCmd().default)({ processName, args, inputs, processOpts, opts }); if (_this.debugMode) { console.log((0, _padRight().default)(_chalk().default.green('output: \n'), 20, ' ')); // eslint-disable-line no-console console.log(_chalk().default.cyan(stdout)); // eslint-disable-line no-console } return stdout; })(); } } exports.default = CommandHelper;