'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _stringFormat;

function _load_stringFormat() {
  return _stringFormat = _interopRequireDefault(require('string-format'));
}

var _lodash;

function _load_lodash() {
  return _lodash = _interopRequireDefault(require('lodash.assignwith'));
}

var _lodash2;

function _load_lodash2() {
  return _lodash2 = _interopRequireDefault(require('lodash.groupby'));
}

var _lodash3;

function _load_lodash3() {
  return _lodash3 = _interopRequireDefault(require('lodash.unionby'));
}

var _ignore;

function _load_ignore() {
  return _ignore = _interopRequireDefault(require('ignore'));
}

var _arrayDifference;

function _load_arrayDifference() {
  return _arrayDifference = _interopRequireDefault(require('array-difference'));
}

var _analytics;

function _load_analytics() {
  return _analytics = require('../../../analytics/analytics');
}

var _utils;

function _load_utils() {
  return _utils = require('../../../utils');
}

var _bitId;

function _load_bitId() {
  return _bitId = require('../../../bit-id');
}

var _constants;

function _load_constants() {
  return _constants = require('../../../constants');
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../../../logger/logger'));
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('./exceptions');
}

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../../../error/general-error'));
}

var _versionShouldBeRemoved;

function _load_versionShouldBeRemoved() {
  return _versionShouldBeRemoved = _interopRequireDefault(require('./exceptions/version-should-be-removed'));
}

var _linkContent;

function _load_linkContent() {
  return _linkContent = require('../../../links/link-content');
}

var _missingMainFile;

function _load_missingMainFile() {
  return _missingMainFile = _interopRequireDefault(require('../../bit-map/exceptions/missing-main-file'));
}

var _missingMainFileMultipleComponents;

function _load_missingMainFileMultipleComponents() {
  return _missingMainFileMultipleComponents = _interopRequireDefault(require('./exceptions/missing-main-file-multiple-components'));
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// can be a path or a DSL, e.g: tests/{PARENT}/{FILE_NAME}
var REGEX_DSL_PATTERN = /{([^}]+)}/g;
// This is the contxt of the add operation. By default, the add is executed in the same folder in which the consumer is located and it is the process.cwd().
// In that case , give the value false to overridenConsumer .
// There is a possibility to execute add when the process.cwd() is different from the project directory. In that case , when add is done on a folder wchih is
// Different from process.cwd(), transfer true.
// Required for determining if the paths are relative to consumer or to process.cwd().

var AddComponents = function () {
  // id entered by the user
  function AddComponents(context, addProps) {
    _classCallCheck(this, AddComponents);

    this.alternateCwd = context.alternateCwd;
    this.consumer = context.consumer;
    this.bitMap = this.consumer.bitMap;
    this.componentPaths = this.joinConsumerPathIfNeeded(addProps.componentPaths);
    this.id = addProps.id;
    this.main = addProps.main;
    this.namespace = addProps.namespace;
    this.tests = addProps.tests ? this.joinConsumerPathIfNeeded(addProps.tests) : [];
    this.exclude = addProps.exclude ? this.joinConsumerPathIfNeeded(addProps.exclude) : [];
    this.override = addProps.override;
    this.trackDirFeature = addProps.trackDirFeature;
    this.origin = addProps.origin || (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED;
    this.warnings = {
      alreadyUsed: {},
      emptyDirectory: []
    };
    this.addedComponents = [];
  } // (default = false) replace the files array or only add files.


  _createClass(AddComponents, [{
    key: 'joinConsumerPathIfNeeded',
    value: function joinConsumerPathIfNeeded(paths) {
      if (paths.length > 0) {
        if (this.alternateCwd !== undefined && this.alternateCwd !== null) {
          var alternate = this.alternateCwd;
          return paths.map(function (file) {
            return (_path || _load_path()).default.join(alternate, file);
          });
        }
        return paths;
      }
      return [];
    }

    /**
     * @param {string[]} files - array of file-paths from which it should search for the dsl patterns.
     * @param {*} filesWithPotentialDsl - array of file-path which may have DSL patterns
     *
     * @returns array of file-paths from 'files' parameter that match the patterns from 'filesWithPotentialDsl' parameter
     */

  }, {
    key: 'getFilesAccordingToDsl',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(files, filesWithPotentialDsl) {
        var _this = this;

        var filesListAllMatches, filesListFlatten, filesListUnique;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                filesListAllMatches = filesWithPotentialDsl.map(function () {
                  var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(dsl) {
                    var filesListMatch;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            filesListMatch = files.map(function () {
                              var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(file) {
                                var fileInfo, generatedFile, matches, matchesAfterGitIgnore;
                                return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
                                  while (1) {
                                    switch (_context.prev = _context.next) {
                                      case 0:
                                        fileInfo = (0, (_utils || _load_utils()).calculateFileInfo)(file);
                                        generatedFile = (0, (_stringFormat || _load_stringFormat()).default)(dsl, fileInfo);
                                        _context.next = 4;
                                        return (0, (_utils || _load_utils()).glob)(generatedFile);

                                      case 4:
                                        matches = _context.sent;
                                        matchesAfterGitIgnore = _this.gitIgnore.filter(matches);
                                        return _context.abrupt('return', matchesAfterGitIgnore.filter(function (match) {
                                          return (_fsExtra || _load_fsExtra()).default.existsSync(match);
                                        }));

                                      case 7:
                                      case 'end':
                                        return _context.stop();
                                    }
                                  }
                                }, _callee, _this);
                              }));

                              return function (_x4) {
                                return _ref3.apply(this, arguments);
                              };
                            }());
                            return _context2.abrupt('return', Promise.all(filesListMatch));

                          case 2:
                          case 'end':
                            return _context2.stop();
                        }
                      }
                    }, _callee2, _this);
                  }));

                  return function (_x3) {
                    return _ref2.apply(this, arguments);
                  };
                }());
                _context3.t0 = (_ramda || _load_ramda()).default;
                _context3.next = 4;
                return Promise.all(filesListAllMatches);

              case 4:
                _context3.t1 = _context3.sent;
                filesListFlatten = _context3.t0.flatten.call(_context3.t0, _context3.t1);
                filesListUnique = (_ramda || _load_ramda()).default.uniq(filesListFlatten);
                return _context3.abrupt('return', filesListUnique.map(function (file) {
                  // when files array has the test file with different letter case, use the one from the file array
                  var fileNormalized = (0, (_utils || _load_utils()).pathNormalizeToLinux)(file);
                  var fileWithCorrectCase = files.find(function (f) {
                    return f.toLowerCase() === fileNormalized.toLowerCase();
                  }) || fileNormalized;
                  var relativeToConsumer = _this.consumer.getPathRelativeToConsumer(fileWithCorrectCase);
                  return (0, (_utils || _load_utils()).pathNormalizeToLinux)(relativeToConsumer);
                }));

              case 8:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function getFilesAccordingToDsl(_x, _x2) {
        return _ref.apply(this, arguments);
      }

      return getFilesAccordingToDsl;
    }()
  }, {
    key: 'addToBitMap',
    value: function addToBitMap(_ref4) {
      var _this2 = this;

      var componentId = _ref4.componentId,
          files = _ref4.files,
          mainFile = _ref4.mainFile,
          trackDir = _ref4.trackDir;

      var getComponentMap = function getComponentMap() {
        if (_this2.trackDirFeature) {
          return _this2.bitMap.addFilesToComponent({ componentId, files });
        }
        return _this2.bitMap.addComponent({
          componentId,
          files,
          mainFile,
          trackDir,
          origin: (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED,
          override: _this2.override
        });
      };
      var componentMap = getComponentMap();
      return { id: componentId.toString(), files: componentMap.files };
    }

    /**
     * unsupported files, such as, binary files, don't have link-file. instead, they have a symlink
     * inside the component dir, pointing to the dependency.
     * this methods check whether a file is auto generated for the unsupported files.
     */

  }, {
    key: '_isGeneratedForUnsupportedFiles',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(fileRelativePath, componentId, componentMap) {
        var componentFromModel, dependencies, sourcePaths, sourcePathsRelativeToConsumer;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                if (!(0, (_linkContent || _load_linkContent()).isSupportedExtension)(fileRelativePath)) {
                  _context4.next = 2;
                  break;
                }

                return _context4.abrupt('return', false);

              case 2:
                _context4.next = 4;
                return this.consumer.loadComponentFromModelIfExist(componentId);

              case 4:
                componentFromModel = _context4.sent;

                if (componentFromModel) {
                  _context4.next = 7;
                  break;
                }

                throw new (_generalError || _load_generalError()).default(`failed finding ${componentId.toString()} in the model although the component is imported, try running "bit import ${componentId.toString()} --objects" to get the component saved in the model`);

              case 7:
                dependencies = componentFromModel.getAllDependenciesCloned();
                sourcePaths = dependencies.getSourcesPaths();
                sourcePathsRelativeToConsumer = sourcePaths.map(function (sourcePath) {
                  return (0, (_utils || _load_utils()).pathJoinLinux)(componentMap.rootDir, sourcePath);
                });
                return _context4.abrupt('return', sourcePathsRelativeToConsumer.includes(fileRelativePath));

              case 11:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function _isGeneratedForUnsupportedFiles(_x5, _x6, _x7) {
        return _ref5.apply(this, arguments);
      }

      return _isGeneratedForUnsupportedFiles;
    }()

    /**
     * for imported component, the package.json in the root directory is a bit-generated file and as
     * such, it should be ignored
     */

  }, {
    key: '_isPackageJsonOnRootDir',
    value: function _isPackageJsonOnRootDir(pathRelativeToConsumerRoot, componentMap) {
      if (!componentMap.rootDir || componentMap.origin !== (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED) {
        throw new Error('_isPackageJsonOnRootDir should not get called on non imported components');
      }
      return (_path || _load_path()).default.join(componentMap.rootDir, (_constants || _load_constants()).PACKAGE_JSON) === (_path || _load_path()).default.normalize(pathRelativeToConsumerRoot);
    }

    /**
     * imported components might have wrapDir, when they do, files should not be added outside of
     * that wrapDir
     */

  }, {
    key: '_isOutsideOfWrapDir',
    value: function _isOutsideOfWrapDir(pathRelativeToConsumerRoot, componentMap) {
      if (!componentMap.rootDir || componentMap.origin !== (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED) {
        throw new Error('_isOutsideOfWrapDir should not get called on non imported components');
      }
      if (!componentMap.wrapDir) return false;
      var wrapDirRelativeToConsumerRoot = (_path || _load_path()).default.join(componentMap.rootDir, componentMap.wrapDir);
      return !(_path || _load_path()).default.normalize(pathRelativeToConsumerRoot).startsWith(wrapDirRelativeToConsumerRoot);
    }

    /**
     * Add or update existing (imported and new) component according to bitmap
     * there are 3 options:
     * 1. a user is adding a new component. there is no record for this component in bit.map
     * 2. a user is updating an existing component. there is a record for this component in bit.map
     * 3. some or all the files of this component were previously added as another component-id.
     */

  }, {
    key: 'addOrUpdateComponentInBitMap',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(component) {
        var _this3 = this;

        var consumerPath, parsedBitId, files, foundComponentFromBitMap, componentFilesP, componentFiles;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                consumerPath = this.consumer.getPath();
                parsedBitId = component.componentId;
                files = component.files;
                foundComponentFromBitMap = this.bitMap.getComponentIfExist(component.componentId, {
                  ignoreScopeAndVersion: true
                });
                componentFilesP = files.map(function () {
                  var _ref7 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(file) {
                    var filePath, isAutoGenerated, caseSensitive, existingIdOfFile, idOfFileIsDifferent, existingComponentOfFile, isImported, idFromBitMap, existingIdWithoutVersion, isGeneratedForUnsupportedFiles;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            // $FlowFixMe null is removed later on
                            filePath = (_path || _load_path()).default.join(consumerPath, file.relativePath);
                            _context5.next = 3;
                            return (0, (_utils || _load_utils()).isAutoGeneratedFile)(filePath);

                          case 3:
                            isAutoGenerated = _context5.sent;

                            if (!isAutoGenerated) {
                              _context5.next = 6;
                              break;
                            }

                            return _context5.abrupt('return', null);

                          case 6:
                            caseSensitive = false;
                            existingIdOfFile = _this3.bitMap.getComponentIdByPath(file.relativePath, caseSensitive);
                            idOfFileIsDifferent = existingIdOfFile && !existingIdOfFile.isEqual(parsedBitId);
                            existingComponentOfFile = existingIdOfFile ? _this3.bitMap.getComponent(existingIdOfFile) : undefined;
                            isImported = foundComponentFromBitMap && foundComponentFromBitMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED || existingComponentOfFile && existingComponentOfFile.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED;

                            if (!isImported) {
                              _context5.next = 31;
                              break;
                            }

                            // $FlowFixMe
                            idFromBitMap = foundComponentFromBitMap ? foundComponentFromBitMap.id : existingComponentOfFile.id;
                            // throw error in case user didn't add id to imported component or the id is incorrect

                            if (_this3.id) {
                              _context5.next = 15;
                              break;
                            }

                            throw new (_exceptions || _load_exceptions()).MissingComponentIdForImportedComponent(idFromBitMap.toStringWithoutVersion());

                          case 15:
                            if (!idOfFileIsDifferent) {
                              _context5.next = 18;
                              break;
                            }

                            existingIdWithoutVersion = existingIdOfFile.toStringWithoutVersion();
                            // $FlowFixMe $this.id is not null at this point

                            throw new (_exceptions || _load_exceptions()).IncorrectIdForImportedComponent(existingIdWithoutVersion, _this3.id, file.relativePath);

                          case 18:
                            if (!_this3._isPackageJsonOnRootDir(file.relativePath, foundComponentFromBitMap)) {
                              _context5.next = 20;
                              break;
                            }

                            return _context5.abrupt('return', null);

                          case 20:
                            if (!_this3._isOutsideOfWrapDir(file.relativePath, foundComponentFromBitMap)) {
                              _context5.next = 23;
                              break;
                            }

                            (_logger || _load_logger()).default.warn(`add-components: ignoring ${file.relativePath} as it is located outside of the wrapDir`);
                            return _context5.abrupt('return', null);

                          case 23:
                            _context5.next = 25;
                            return _this3._isGeneratedForUnsupportedFiles(file.relativePath, component.componentId, foundComponentFromBitMap);

                          case 25:
                            isGeneratedForUnsupportedFiles = _context5.sent;

                            if (!isGeneratedForUnsupportedFiles) {
                              _context5.next = 28;
                              break;
                            }

                            return _context5.abrupt('return', null);

                          case 28:
                            delete component.trackDir;
                            _context5.next = 34;
                            break;

                          case 31:
                            if (!idOfFileIsDifferent) {
                              _context5.next = 34;
                              break;
                            }

                            // not imported component file but exists in bitmap
                            if (_this3.warnings.alreadyUsed[existingIdOfFile]) {
                              _this3.warnings.alreadyUsed[existingIdOfFile].push(file.relativePath);
                            } else {
                              _this3.warnings.alreadyUsed[existingIdOfFile] = [file.relativePath];
                            }
                            // $FlowFixMe null is removed later on
                            return _context5.abrupt('return', null);

                          case 34:
                            return _context5.abrupt('return', file);

                          case 35:
                          case 'end':
                            return _context5.stop();
                        }
                      }
                    }, _callee5, _this3);
                  }));

                  return function (_x9) {
                    return _ref7.apply(this, arguments);
                  };
                }());
                _context6.next = 7;
                return Promise.all(componentFilesP);

              case 7:
                _context6.t0 = function (file) {
                  return file;
                };

                componentFiles = _context6.sent.filter(_context6.t0);

                if (componentFiles.length) {
                  _context6.next = 11;
                  break;
                }

                return _context6.abrupt('return', { id: component.componentId.toString(), files: [] });

              case 11:
                // $FlowFixMe it can't be null due to the filter function
                component.files = componentFiles;
                return _context6.abrupt('return', this.addToBitMap(component));

              case 13:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function addOrUpdateComponentInBitMap(_x8) {
        return _ref6.apply(this, arguments);
      }

      return addOrUpdateComponentInBitMap;
    }()

    // remove excluded files from file list

  }, {
    key: 'removeExcludedFiles',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(componentsWithFiles) {
        var files, resolvedExcludedFiles;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                files = (_ramda || _load_ramda()).default.flatten(componentsWithFiles.map(function (x) {
                  return x.files.map(function (i) {
                    return i.relativePath;
                  });
                }));
                _context7.next = 3;
                return this.getFilesAccordingToDsl(files, this.exclude);

              case 3:
                resolvedExcludedFiles = _context7.sent;

                componentsWithFiles.forEach(function (componentWithFiles) {
                  var mainFile = componentWithFiles.mainFile ? (0, (_utils || _load_utils()).pathNormalizeToLinux)(componentWithFiles.mainFile) : undefined;
                  if (resolvedExcludedFiles.includes(mainFile)) {
                    componentWithFiles.files = [];
                  } else {
                    // if mainFile is excluded, exclude all files
                    componentWithFiles.files = componentWithFiles.files.filter(function (key) {
                      return !resolvedExcludedFiles.includes(key.relativePath);
                    });
                  }
                });

              case 5:
              case 'end':
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));

      function removeExcludedFiles(_x10) {
        return _ref8.apply(this, arguments);
      }

      return removeExcludedFiles;
    }()

    /**
     * if the id is already saved in bitmap file, it might have more data (such as scope, version)
     * use that id instead.
     */

  }, {
    key: '_getIdAccordingToExistingComponent',
    value: function _getIdAccordingToExistingComponent(currentId) {
      var existingComponentId = this.bitMap.getExistingBitId(currentId, false);
      var componentExists = Boolean(existingComponentId);
      if (componentExists && this.bitMap.getComponent(existingComponentId).origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED) {
        throw new (_generalError || _load_generalError()).default(`One of your dependencies (${existingComponentId}) has already the same namespace and name.
    If you're trying to add a new component, please choose a new namespace or name.
    If you're trying to update a dependency component, please re-import it individually`);
      }
      if (currentId.includes((_constants || _load_constants()).VERSION_DELIMITER)) {
        if (!existingComponentId || // this id is new, it shouldn't have a version
        !existingComponentId.hasVersion() || // this component is new, it shouldn't have a version
        // user shouldn't add files to a an existing component with different version
        // $FlowFixMe this function gets called only when this.id is set
        existingComponentId.version !== (_bitId || _load_bitId()).BitId.getVersionOnlyFromString(this.id)) {
          // $FlowFixMe this.id is defined here
          throw new (_versionShouldBeRemoved || _load_versionShouldBeRemoved()).default(this.id);
        }
      }
      return existingComponentId || (_bitId || _load_bitId()).BitId.parse(currentId, false);
    }
  }, {
    key: '_getIdAccordingToTrackDir',
    value: function _getIdAccordingToTrackDir(dir) {
      var dirNormalizedToLinux = (0, (_utils || _load_utils()).pathNormalizeToLinux)(dir);
      var trackDirs = this.bitMap.getAllTrackDirs();
      if (!trackDirs) return null;
      return trackDirs[dirNormalizedToLinux];
    }

    /**
     * used for updating main file if exists or doesn't exists
     */

  }, {
    key: '_addMainFileToFiles',
    value: function _addMainFileToFiles(files) {
      var _this4 = this;

      var mainFile = this.main;
      if (mainFile && mainFile.match(REGEX_DSL_PATTERN)) {
        // it's a DSL
        files.forEach(function (file) {
          var fileInfo = (0, (_utils || _load_utils()).calculateFileInfo)(file.relativePath);
          var generatedFile = (0, (_stringFormat || _load_stringFormat()).default)(mainFile, fileInfo);
          var foundFile = _this4._findMainFileInFiles(generatedFile, files);
          if (foundFile) {
            mainFile = foundFile.relativePath;
          }
          if ((_fsExtra || _load_fsExtra()).default.existsSync(generatedFile) && !foundFile) {
            var shouldIgnore = _this4.gitIgnore.ignores(generatedFile);
            if (shouldIgnore) {
              // check if file is in exclude list
              throw new (_exceptions || _load_exceptions()).ExcludedMainFile(generatedFile);
            }
            files.push({
              relativePath: (0, (_utils || _load_utils()).pathNormalizeToLinux)(generatedFile),
              test: false,
              name: (_path || _load_path()).default.basename(generatedFile)
            });
            mainFile = generatedFile;
          }
        });
      }
      if (!mainFile) return undefined;
      if (this.alternateCwd) {
        mainFile = (_path || _load_path()).default.join(this.alternateCwd, mainFile);
      }
      var mainFileRelativeToConsumer = this.consumer.getPathRelativeToConsumer(mainFile);
      var mainPath = this.consumer.toAbsolutePath(mainFileRelativeToConsumer);
      if ((_fsExtra || _load_fsExtra()).default.existsSync(mainPath)) {
        var shouldIgnore = this.gitIgnore.ignores(mainFileRelativeToConsumer);
        if (shouldIgnore) throw new (_exceptions || _load_exceptions()).ExcludedMainFile(mainFileRelativeToConsumer);
        if ((0, (_utils || _load_utils()).isDir)(mainPath)) {
          throw new (_exceptions || _load_exceptions()).MainFileIsDir(mainPath);
        }
        var foundFile = this._findMainFileInFiles(mainFileRelativeToConsumer, files);
        if (foundFile) {
          return foundFile.relativePath;
        }
        files.push({
          relativePath: (0, (_utils || _load_utils()).pathNormalizeToLinux)(mainFileRelativeToConsumer),
          test: false,
          name: (_path || _load_path()).default.basename(mainFileRelativeToConsumer)
        });
        return mainFileRelativeToConsumer;
      }
      return mainFile;
    }
  }, {
    key: '_findMainFileInFiles',
    value: function _findMainFileInFiles(mainFile, files) {
      var normalizedMainFile = (0, (_utils || _load_utils()).pathNormalizeToLinux)(mainFile).toLowerCase();
      return files.find(function (file) {
        return file.relativePath.toLowerCase() === normalizedMainFile;
      });
    }
  }, {
    key: '_mergeTestFilesWithFiles',
    value: function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(files) {
        var _this5 = this;

        var testFiles, resolvedTestFiles;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                if ((_ramda || _load_ramda()).default.isEmpty(this.tests)) {
                  _context8.next = 6;
                  break;
                }

                _context8.next = 3;
                return this.getFilesAccordingToDsl(files.map(function (file) {
                  return file.relativePath;
                }), this.tests);

              case 3:
                _context8.t0 = _context8.sent;
                _context8.next = 7;
                break;

              case 6:
                _context8.t0 = [];

              case 7:
                testFiles = _context8.t0;
                resolvedTestFiles = testFiles.map(function (testFile) {
                  if ((0, (_utils || _load_utils()).isDir)((_path || _load_path()).default.join(_this5.consumer.getPath(), testFile))) throw new (_exceptions || _load_exceptions()).TestIsDirectory(testFile);
                  return {
                    relativePath: testFile,
                    test: true,
                    name: (_path || _load_path()).default.basename(testFile)
                  };
                });
                return _context8.abrupt('return', (0, (_lodash3 || _load_lodash3()).default)(resolvedTestFiles, files, 'relativePath'));

              case 10:
              case 'end':
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      function _mergeTestFilesWithFiles(_x11) {
        return _ref9.apply(this, arguments);
      }

      return _mergeTestFilesWithFiles;
    }()

    /**
     * given the component paths, prepare the id, mainFile and files to be added later on to bitmap
     * the id of the component is either entered by the user or, if not entered, concluded by the path.
     * e.g. bar/foo.js, the id would be bar/foo.
     * in case bitmap has already the same id, the complete id is taken from bitmap (see _getIdAccordingToExistingComponent)
     */

  }, {
    key: 'addOneComponent',
    value: function () {
      var _ref10 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(componentPathsStats) {
        var _this6 = this;

        var finalBitId, idFromPath, componentsWithFilesP, componentsWithFiles, componentId, files, groupedComponents, uniqComponents;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                finalBitId = void 0; // final id to use for bitmap file

                idFromPath = void 0;

                if (this.id) {
                  finalBitId = this._getIdAccordingToExistingComponent(this.id);
                }

                componentsWithFilesP = Object.keys(componentPathsStats).map(function () {
                  var _ref11 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(componentPath) {
                    var relativeComponentPath, matches, filteredMatches, filteredMatchedFiles, _resolvedMainFile, idOfTrackDir, absoluteComponentPath, splitPath, lastDir, nameSpaceOrDir, _trackDir, absolutePath, pathParsed, relativeFilePath, dirName, nameSpaceOrLastDir, files, resolvedMainFile;

                    return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
                      while (1) {
                        switch (_context9.prev = _context9.next) {
                          case 0:
                            if (!componentPathsStats[componentPath].isDir) {
                              _context9.next = 16;
                              break;
                            }

                            relativeComponentPath = _this6.consumer.getPathRelativeToConsumer(componentPath);
                            _context9.next = 4;
                            return (0, (_utils || _load_utils()).glob)((_path || _load_path()).default.join(relativeComponentPath, '**'), {
                              cwd: _this6.consumer.getPath(),
                              nodir: true
                            });

                          case 4:
                            matches = _context9.sent;
                            filteredMatches = _this6.gitIgnore.filter(matches);

                            if (filteredMatches.length) {
                              _context9.next = 8;
                              break;
                            }

                            throw new (_exceptions || _load_exceptions()).EmptyDirectory();

                          case 8:
                            filteredMatchedFiles = filteredMatches.map(function (match) {
                              return { relativePath: (0, (_utils || _load_utils()).pathNormalizeToLinux)(match), test: false, name: (_path || _load_path()).default.basename(match) };
                            });

                            // merge test files with files

                            _context9.next = 11;
                            return _this6._mergeTestFilesWithFiles(filteredMatchedFiles);

                          case 11:
                            filteredMatchedFiles = _context9.sent;
                            _resolvedMainFile = _this6._addMainFileToFiles(filteredMatchedFiles);


                            if (!finalBitId) {
                              idOfTrackDir = _this6._getIdAccordingToTrackDir(componentPath);

                              if (idOfTrackDir) {
                                finalBitId = idOfTrackDir;
                              } else {
                                absoluteComponentPath = (_path || _load_path()).default.resolve(componentPath);
                                splitPath = absoluteComponentPath.split((_path || _load_path()).default.sep);
                                lastDir = splitPath[splitPath.length - 1];
                                nameSpaceOrDir = _this6.namespace || splitPath[splitPath.length - 2];

                                if (!_this6.namespace) {
                                  idFromPath = { namespace: (_bitId || _load_bitId()).BitId.getValidIdChunk(nameSpaceOrDir), name: (_bitId || _load_bitId()).BitId.getValidIdChunk(lastDir) };
                                }
                                finalBitId = (_bitId || _load_bitId()).BitId.getValidBitId(nameSpaceOrDir, lastDir);
                              }
                            }

                            _trackDir = Object.keys(componentPathsStats).length === 1 && !_this6.exclude.length && _this6.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED ? relativeComponentPath : undefined;
                            return _context9.abrupt('return', {
                              componentId: finalBitId,
                              files: filteredMatchedFiles,
                              mainFile: _resolvedMainFile,
                              trackDir: _trackDir,
                              idFromPath
                            });

                          case 16:
                            // is file
                            absolutePath = (_path || _load_path()).default.resolve(componentPath);
                            pathParsed = (_path || _load_path()).default.parse(absolutePath);
                            relativeFilePath = _this6.consumer.getPathRelativeToConsumer(componentPath);

                            if (!finalBitId) {
                              dirName = pathParsed.dir;

                              if (!dirName) {
                                dirName = (_path || _load_path()).default.dirname(absolutePath);
                              }
                              nameSpaceOrLastDir = _this6.namespace || (_ramda || _load_ramda()).default.last(dirName.split((_path || _load_path()).default.sep));

                              if (!_this6.namespace) {
                                idFromPath = {
                                  namespace: (_bitId || _load_bitId()).BitId.getValidIdChunk(nameSpaceOrLastDir),
                                  name: (_bitId || _load_bitId()).BitId.getValidIdChunk(pathParsed.name)
                                };
                              }
                              finalBitId = (_bitId || _load_bitId()).BitId.getValidBitId(nameSpaceOrLastDir, pathParsed.name);
                            }

                            files = [{ relativePath: (0, (_utils || _load_utils()).pathNormalizeToLinux)(relativeFilePath), test: false, name: (_path || _load_path()).default.basename(relativeFilePath) }];
                            _context9.next = 23;
                            return _this6._mergeTestFilesWithFiles(files);

                          case 23:
                            files = _context9.sent;
                            resolvedMainFile = _this6._addMainFileToFiles(files);
                            return _context9.abrupt('return', { componentId: finalBitId, files, mainFile: resolvedMainFile, idFromPath });

                          case 26:
                          case 'end':
                            return _context9.stop();
                        }
                      }
                    }, _callee9, _this6);
                  }));

                  return function (_x13) {
                    return _ref11.apply(this, arguments);
                  };
                }());
                _context10.next = 6;
                return Promise.all(componentsWithFilesP);

              case 6:
                componentsWithFiles = _context10.sent;

                if ((_ramda || _load_ramda()).default.isEmpty(this.exclude)) {
                  _context10.next = 10;
                  break;
                }

                _context10.next = 10;
                return this.removeExcludedFiles(componentsWithFiles);

              case 10:
                componentId = finalBitId;

                componentsWithFiles = componentsWithFiles.filter(function (componentWithFiles) {
                  return componentWithFiles.files.length;
                });

                // $FlowFixMe

                if (!(componentsWithFiles.length === 0)) {
                  _context10.next = 14;
                  break;
                }

                return _context10.abrupt('return', { componentId, files: [] });

              case 14:
                if (!(componentsWithFiles.length === 1)) {
                  _context10.next = 16;
                  break;
                }

                return _context10.abrupt('return', componentsWithFiles[0]);

              case 16:
                files = componentsWithFiles.reduce(function (a, b) {
                  return a.concat(b.files);
                }, []);
                groupedComponents = (0, (_lodash2 || _load_lodash2()).default)(files, 'relativePath');
                uniqComponents = Object.keys(groupedComponents).map(function (key) {
                  return (_lodash || _load_lodash()).default.apply(undefined, [{}].concat(_toConsumableArray(groupedComponents[key]), [function (val1, val2) {
                    return val1 || val2;
                  }]));
                });
                // $FlowFixMe

                return _context10.abrupt('return', {
                  componentId,
                  files: uniqComponents,
                  mainFile: (_ramda || _load_ramda()).default.head(componentsWithFiles).mainFile,
                  trackDir: (_ramda || _load_ramda()).default.head(componentsWithFiles).trackDir,
                  idFromPath
                });

              case 20:
              case 'end':
                return _context10.stop();
            }
          }
        }, _callee10, this);
      }));

      function addOneComponent(_x12) {
        return _ref10.apply(this, arguments);
      }

      return addOneComponent;
    }()
  }, {
    key: 'getIgnoreList',
    value: function getIgnoreList() {
      var consumerPath = this.consumer.getPath();
      var ignoreList = (0, (_utils || _load_utils()).retrieveIgnoreList)(consumerPath);
      var importedComponents = this.bitMap.getAllComponents((_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED);
      var distDirsOfImportedComponents = Object.keys(importedComponents).map(function (key) {
        return (0, (_utils || _load_utils()).pathJoinLinux)(importedComponents[key].rootDir, (_constants || _load_constants()).DEFAULT_DIST_DIRNAME, '**');
      });
      var configsToIgnore = this.bitMap.getConfigDirsAndFilesToIgnore(this.consumer.getPath());
      var configDirs = configsToIgnore.dirs.map(function (dir) {
        return (0, (_utils || _load_utils()).pathJoinLinux)(dir, '**');
      });
      ignoreList = ignoreList.concat(distDirsOfImportedComponents);
      ignoreList = ignoreList.concat(configsToIgnore.files);
      ignoreList = ignoreList.concat(configDirs);
      return ignoreList;
    }
  }, {
    key: 'add',
    value: function () {
      var _ref12 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11() {
        var missingFiles, componentPathsStats, resolvedComponentPathsWithoutGitIgnore, resolvedExcludedFiles, resolvedComponentPathsWithGitIgnore, diff, resolvedTestFiles, isMultipleComponents, addedOne, addedResult;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                this.ignoreList = this.getIgnoreList();
                this.gitIgnore = (0, (_ignore || _load_ignore()).default)().add(this.ignoreList); // add ignore list

                // check unknown test files
                missingFiles = (0, (_utils || _load_utils()).getMissingTestFiles)(this.tests);

                if ((_ramda || _load_ramda()).default.isEmpty(missingFiles)) {
                  _context11.next = 5;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).PathsNotExist(missingFiles);

              case 5:
                componentPathsStats = {};
                _context11.t0 = (_ramda || _load_ramda()).default;
                _context11.next = 9;
                return Promise.all(this.componentPaths.map(function (componentPath) {
                  return (0, (_utils || _load_utils()).glob)(componentPath);
                }));

              case 9:
                _context11.t1 = _context11.sent;
                resolvedComponentPathsWithoutGitIgnore = _context11.t0.flatten.call(_context11.t0, _context11.t1);
                _context11.next = 13;
                return this.getFilesAccordingToDsl(resolvedComponentPathsWithoutGitIgnore, this.exclude);

              case 13:
                resolvedExcludedFiles = _context11.sent;

                this.ignoreList = [].concat(_toConsumableArray(this.ignoreList), _toConsumableArray(resolvedExcludedFiles));
                this.gitIgnore = (0, (_ignore || _load_ignore()).default)().add(this.ignoreList); // add ignore list

                resolvedComponentPathsWithGitIgnore = this.gitIgnore.filter(resolvedComponentPathsWithoutGitIgnore);
                // Run diff on both arrays to see what was filtered out because of the gitignore file

                diff = (0, (_arrayDifference || _load_arrayDifference()).default)(resolvedComponentPathsWithGitIgnore, resolvedComponentPathsWithoutGitIgnore);

                if (!(!(_ramda || _load_ramda()).default.isEmpty(this.tests) && this.id && (_ramda || _load_ramda()).default.isEmpty(resolvedComponentPathsWithoutGitIgnore))) {
                  _context11.next = 27;
                  break;
                }

                _context11.t2 = (_ramda || _load_ramda()).default;
                _context11.next = 22;
                return Promise.all(this.tests.map(function (componentPath) {
                  return (0, (_utils || _load_utils()).glob)(componentPath);
                }));

              case 22:
                _context11.t3 = _context11.sent;
                resolvedTestFiles = _context11.t2.flatten.call(_context11.t2, _context11.t3);

                componentPathsStats = validatePaths(resolvedTestFiles);
                _context11.next = 34;
                break;

              case 27:
                if (!(_ramda || _load_ramda()).default.isEmpty(resolvedComponentPathsWithoutGitIgnore)) {
                  _context11.next = 29;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).PathsNotExist(this.componentPaths);

              case 29:
                if ((_ramda || _load_ramda()).default.isEmpty(resolvedComponentPathsWithGitIgnore)) {
                  _context11.next = 33;
                  break;
                }

                componentPathsStats = validatePaths(resolvedComponentPathsWithGitIgnore);
                _context11.next = 34;
                break;

              case 33:
                throw new (_exceptions || _load_exceptions()).NoFiles(diff);

              case 34:
                // if a user entered multiple paths and entered an id, he wants all these paths to be one component
                // conversely, if a user entered multiple paths without id, he wants each dir as an individual component
                isMultipleComponents = Object.keys(componentPathsStats).length > 1 && !this.id;

                if (!isMultipleComponents) {
                  _context11.next = 40;
                  break;
                }

                _context11.next = 38;
                return this.addMultipleComponents(componentPathsStats);

              case 38:
                _context11.next = 50;
                break;

              case 40:
                (_logger || _load_logger()).default.debug('bit add - one component');
                // when a user enters more than one directory, he would like to keep the directories names
                // so then when a component is imported, it will write the files into the original directories
                _context11.next = 43;
                return this.addOneComponent(componentPathsStats);

              case 43:
                addedOne = _context11.sent;

                this._removeNamespaceIfNotNeeded([addedOne]);

                if ((_ramda || _load_ramda()).default.isEmpty(addedOne.files)) {
                  _context11.next = 50;
                  break;
                }

                _context11.next = 48;
                return this.addOrUpdateComponentInBitMap(addedOne);

              case 48:
                addedResult = _context11.sent;

                if (addedResult) this.addedComponents.push(addedResult);

              case 50:
                (_analytics || _load_analytics()).Analytics.setExtraData('num_components', this.addedComponents.length);
                return _context11.abrupt('return', { addedComponents: this.addedComponents, warnings: this.warnings });

              case 52:
              case 'end':
                return _context11.stop();
            }
          }
        }, _callee11, this);
      }));

      function add() {
        return _ref12.apply(this, arguments);
      }

      return add;
    }()
  }, {
    key: 'addMultipleComponents',
    value: function () {
      var _ref13 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(componentPathsStats) {
        var testToRemove, added;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                (_logger || _load_logger()).default.debug('bit add - multiple components');

                if ((_ramda || _load_ramda()).default.isEmpty(this.tests)) {
                  _context12.next = 7;
                  break;
                }

                _context12.next = 4;
                return this.getFilesAccordingToDsl(Object.keys(componentPathsStats), this.tests);

              case 4:
                _context12.t0 = _context12.sent;
                _context12.next = 8;
                break;

              case 7:
                _context12.t0 = [];

              case 8:
                testToRemove = _context12.t0;

                testToRemove.forEach(function (test) {
                  return delete componentPathsStats[(_path || _load_path()).default.normalize(test)];
                });
                _context12.next = 12;
                return this._tryAddingMultiple(componentPathsStats);

              case 12:
                added = _context12.sent;

                validateNoDuplicateIds(added);
                this._removeNamespaceIfNotNeeded(added);
                _context12.next = 17;
                return this._addMultipleToBitMap(added);

              case 17:
              case 'end':
                return _context12.stop();
            }
          }
        }, _callee12, this);
      }));

      function addMultipleComponents(_x14) {
        return _ref13.apply(this, arguments);
      }

      return addMultipleComponents;
    }()
  }, {
    key: '_addMultipleToBitMap',
    value: function () {
      var _ref14 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee14(added) {
        var _this7 = this;

        var missingMainFiles;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee14$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                missingMainFiles = [];
                _context14.next = 3;
                return Promise.all(added.map(function () {
                  var _ref15 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee13(component) {
                    var addedComponent;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee13$(_context13) {
                      while (1) {
                        switch (_context13.prev = _context13.next) {
                          case 0:
                            if ((_ramda || _load_ramda()).default.isEmpty(component.files)) {
                              _context13.next = 13;
                              break;
                            }

                            _context13.prev = 1;
                            _context13.next = 4;
                            return _this7.addOrUpdateComponentInBitMap(component);

                          case 4:
                            addedComponent = _context13.sent;

                            if (addedComponent && addedComponent.files.length) _this7.addedComponents.push(addedComponent);
                            _context13.next = 13;
                            break;

                          case 8:
                            _context13.prev = 8;
                            _context13.t0 = _context13['catch'](1);

                            if (_context13.t0 instanceof (_missingMainFile || _load_missingMainFile()).default) {
                              _context13.next = 12;
                              break;
                            }

                            throw _context13.t0;

                          case 12:
                            missingMainFiles.push(_context13.t0);

                          case 13:
                          case 'end':
                            return _context13.stop();
                        }
                      }
                    }, _callee13, _this7, [[1, 8]]);
                  }));

                  return function (_x16) {
                    return _ref15.apply(this, arguments);
                  };
                }()));

              case 3:
                if (!missingMainFiles.length) {
                  _context14.next = 5;
                  break;
                }

                throw new (_missingMainFileMultipleComponents || _load_missingMainFileMultipleComponents()).default(missingMainFiles.map(function (err) {
                  return err.componentId;
                }).sort());

              case 5:
              case 'end':
                return _context14.stop();
            }
          }
        }, _callee14, this);
      }));

      function _addMultipleToBitMap(_x15) {
        return _ref14.apply(this, arguments);
      }

      return _addMultipleToBitMap;
    }()
  }, {
    key: '_removeNamespaceIfNotNeeded',
    value: function _removeNamespaceIfNotNeeded(addedComponents) {
      var allIds = this.bitMap.getAllBitIds();
      addedComponents.forEach(function (addedComponent) {
        if (!addedComponent.idFromPath) return; // when the id was not generated from the path do nothing.
        var componentsWithSameName = addedComponents // $FlowFixMe
        .filter(function (a) {
          return a.idFromPath && a.idFromPath.name === addedComponent.idFromPath.name;
        });
        // $FlowFixMe
        var bitIdFromNameOnly = new (_bitId || _load_bitId()).BitId({ name: addedComponent.idFromPath.name });
        var existingComponentWithSameName = allIds.searchWithoutScopeAndVersion(bitIdFromNameOnly);
        if (componentsWithSameName.length === 1 && !existingComponentWithSameName) {
          addedComponent.componentId = bitIdFromNameOnly;
        }
      });
    }
  }, {
    key: '_tryAddingMultiple',
    value: function () {
      var _ref16 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee16(componentPathsStats) {
        var _this8 = this;

        var addedP, added;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee16$(_context16) {
          while (1) {
            switch (_context16.prev = _context16.next) {
              case 0:
                addedP = Object.keys(componentPathsStats).map(function () {
                  var _ref17 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(onePath) {
                    var oneComponentPathStat, addedComponent;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
                      while (1) {
                        switch (_context15.prev = _context15.next) {
                          case 0:
                            oneComponentPathStat = { [onePath]: componentPathsStats[onePath] };
                            _context15.prev = 1;
                            _context15.next = 4;
                            return _this8.addOneComponent(oneComponentPathStat);

                          case 4:
                            addedComponent = _context15.sent;
                            return _context15.abrupt('return', addedComponent);

                          case 8:
                            _context15.prev = 8;
                            _context15.t0 = _context15['catch'](1);

                            if (_context15.t0 instanceof (_exceptions || _load_exceptions()).EmptyDirectory) {
                              _context15.next = 12;
                              break;
                            }

                            throw _context15.t0;

                          case 12:
                            _this8.warnings.emptyDirectory.push(onePath);
                            return _context15.abrupt('return', null);

                          case 14:
                          case 'end':
                            return _context15.stop();
                        }
                      }
                    }, _callee15, _this8, [[1, 8]]);
                  }));

                  return function (_x18) {
                    return _ref17.apply(this, arguments);
                  };
                }());
                _context16.next = 3;
                return Promise.all(addedP);

              case 3:
                added = _context16.sent;
                return _context16.abrupt('return', (_ramda || _load_ramda()).default.reject((_ramda || _load_ramda()).default.isNil, added));

              case 5:
              case 'end':
                return _context16.stop();
            }
          }
        }, _callee16, this);
      }));

      function _tryAddingMultiple(_x17) {
        return _ref16.apply(this, arguments);
      }

      return _tryAddingMultiple;
    }()
  }]);

  return AddComponents;
}();

/**
 * validatePaths - validate if paths entered by user exist and if not throw an error
 *
 * @param {string[]} fileArray - array of paths
 * @returns {PathsStats} componentPathsStats
 */


exports.default = AddComponents;
function validatePaths(fileArray) {
  var componentPathsStats = {};
  fileArray.forEach(function (componentPath) {
    if (!(_fsExtra || _load_fsExtra()).default.existsSync(componentPath)) {
      throw new (_exceptions || _load_exceptions()).PathsNotExist([componentPath]);
    }
    componentPathsStats[componentPath] = {
      isDir: (0, (_utils || _load_utils()).isDir)(componentPath)
    };
  });
  return componentPathsStats;
}

/**
 * validate that no two files where added with the same id in the same bit add command
 */
function validateNoDuplicateIds(addComponents) {
  var duplicateIds = {};
  var newGroupedComponents = (0, (_lodash2 || _load_lodash2()).default)(addComponents, 'componentId');
  Object.keys(newGroupedComponents).forEach(function (key) {
    if (newGroupedComponents[key].length > 1) duplicateIds[key] = newGroupedComponents[key];
  });
  if (!(_ramda || _load_ramda()).default.isEmpty(duplicateIds) && !(_ramda || _load_ramda()).default.isNil(duplicateIds)) throw new (_exceptions || _load_exceptions()).DuplicateIds(duplicateIds);
}