"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.pathHas = pathHas;
exports.pathHasAll = pathHasAll;
exports.propogateUntil = propogateUntil;

function path() {
  const data = _interopRequireWildcard(require("path"));

  path = function () {
    return data;
  };

  return data;
}

function fs() {
  const data = _interopRequireWildcard(require("fs-extra"));

  fs = function () {
    return data;
  };

  return data;
}

function _findUp() {
  const data = _interopRequireDefault(require("find-up"));

  _findUp = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function composePath(patternPath, patterns) {
  return patterns.map(pattern => {
    return path().join(patternPath, pattern);
  });
}
/**
 * determine whether given path matches patterns
 */


function pathHas(patterns) {
  return absPath => {
    let state = false;
    const paths = composePath(absPath, patterns);

    for (const potentialPath of paths) {
      if (state) return state;
      state = fs().existsSync(potentialPath);
    }

    return state;
  };
}
/**
 * determine whether given path have all files/dirs
 */


function pathHasAll(patterns) {
  return absPath => {
    let state = true;
    const paths = composePath(absPath, patterns);

    for (const potentialPath of paths) {
      if (!state) return false;
      state = fs().existsSync(potentialPath);
    }

    return state;
  };
}
/**
 * propogates the FS from given path and until passing pattern function test.
 * @name propogateUntil
 * @param {string} fromPath
 * @param {(path: string) => boolean} pattern
 * @returns {string|null} first path to pass the test.
 * @example
 * ```js
 *  propogateUntil('/usr/local/var', (path) => path.indexOf('/usr') !== -1);
 *  // => '/usr/local/var'
 * ```
 */


function propogateUntil(fromPath) {
  if (!fromPath) return null;
  if (!fs().existsSync(fromPath)) return null;

  const filePath = _findUp().default.sync([_constants().OBJECTS_DIR, path().join(_constants().BIT_HIDDEN_DIR, _constants().OBJECTS_DIR), path().join(_constants().DOT_GIT_DIR, _constants().BIT_GIT_DIR, _constants().OBJECTS_DIR)], {
    cwd: fromPath
  });

  if (!filePath) return null;
  return path().dirname(filePath);
}