"use strict";

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

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _ini = _interopRequireDefault(require("ini"));

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

/**
 * External dependencies
 */
async function getRepoFromGitConfig() {
  const file = await find();

  if (!file.length) {
    return '';
  }

  const config = _ini.default.parse(_fs.default.readFileSync(file, 'utf-8')); // Find the first 'wpcomvip' remote


  for (const key in config) {
    if ('remote' !== key.substring(0, 6)) {
      continue;
    }

    if (!config[key].url) {
      continue;
    }

    if (0 > config[key].url.indexOf('wpcomvip/')) {
      continue;
    }

    let repo = config[key].url;
    repo = repo.replace(/.git$/, '');
    repo = repo.replace('https://github.com/', '');
    repo = repo.replace('git@github.com:', '');
    return repo;
  }

  return;
}

async function find(dir) {
  dir = dir || process.cwd();
  const test = dir + '/.git/config';

  if (await exists(test)) {
    return test;
  } // Bail if we went all the way and didn't find it


  const directory = _path.default.parse(dir);

  if (directory.dir === directory.root) {
    return '';
  } // cd ..


  const up = dir.split(_path.default.sep);
  up.pop();
  return find(up.join(_path.default.sep));
}

async function exists(file) {
  return new Promise(resolve => {
    _fs.default.access(file, _fs.default.constants.F_OK, err => resolve(!err));
  });
}