"use strict";

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

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

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

var _lodash = _interopRequireDefault(require("lodash"));

var _glob = _interopRequireDefault(require("glob"));

var _gitdown = _interopRequireDefault(require("gitdown"));

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

const trimCode = code => {
  let lines = code.replace(/^\n/u, '').trimEnd().split('\n');
  const firsLineIndentation = lines[0].match(/^\s+/u);
  const lastLineIndentation = lines[lines.length - 1].match(/^\s+/u);
  const firstIndentSize = firsLineIndentation ? firsLineIndentation[0].length : 0;
  const lastIndentSize = lastLineIndentation ? lastLineIndentation[0].length : 0;
  lines = lines.map((line, index) => {
    const lineIndentSize = firstIndentSize !== 0 || index === 0 ? Math.min(firstIndentSize, lastIndentSize) : lastIndentSize;
    return line.slice(lineIndentSize);
  });
  return lines.join('\n');
};

const formatCodeSnippet = setup => {
  const paragraphs = [];
  paragraphs.push(trimCode(setup.code));

  if (setup.settings) {
    paragraphs.push(`// Settings: ${JSON.stringify(setup.settings)}`);
  }

  if (setup.options) {
    paragraphs.push(`// Options: ${JSON.stringify(setup.options)}`);
  }

  if (setup.errors) {
    paragraphs.push(`// Message: ${setup.errors[0].message}`);
  }

  return paragraphs.join('\n');
};

const getAssertions = () => {
  const assertionFiles = _glob.default.sync(_path.default.resolve(__dirname, '../../test/rules/assertions/*.js'));

  const assertionNames = assertionFiles.map(filePath => {
    return _path.default.basename(filePath, '.js');
  });
  const assertionCodes = assertionFiles.map(filePath => {
    // eslint-disable-next-line global-require, import/no-dynamic-require
    const codes = require(filePath);

    return {
      invalid: _lodash.default.map(codes.invalid, formatCodeSnippet),
      valid: _lodash.default.map(codes.valid, formatCodeSnippet)
    };
  });
  return _lodash.default.zipObject(assertionNames, assertionCodes);
};

const getSomeBranch = () => {
  const gitConfig = _fs.default.readFileSync(_path.default.join(__dirname, '../../.git/config')).toString();

  const _ref = /\[branch "([^"]+)"\]/u.exec(gitConfig) || [],
        _ref2 = _slicedToArray(_ref, 2),
        branch = _ref2[1];

  return branch;
};

const generateReadme =
/*#__PURE__*/
function () {
  var _ref3 = _asyncToGenerator(function* () {
    const assertions = getAssertions();

    const gitdown = _gitdown.default.readFile(_path.default.join(__dirname, '../../.README/README.md'));

    gitdown.setConfig({
      gitinfo: {
        defaultBranchName: getSomeBranch() || 'master',
        gitPath: _path.default.join(__dirname, '../../.git')
      }
    });
    let documentBody = yield gitdown.get();
    documentBody = documentBody.replace(/<!-- assertions ([a-z]+?) -->/gui, assertionsBlock => {
      const ruleName = assertionsBlock.match(/assertions ([a-z]+)/ui)[1];
      const ruleAssertions = assertions[ruleName];

      if (!ruleAssertions) {
        throw new Error(`No assertions available for rule "${ruleName}".`);
      }

      return 'The following patterns are considered problems:\n\n````js\n' + ruleAssertions.invalid.join('\n\n') + '\n````\n\nThe following patterns are not considered problems:\n\n````js\n' + ruleAssertions.valid.join('\n\n') + '\n````\n';
    });
    return documentBody;
  });

  return function generateReadme() {
    return _ref3.apply(this, arguments);
  };
}();

const generateReadmeAndWriteToDisk =
/*#__PURE__*/
function () {
  var _ref4 = _asyncToGenerator(function* () {
    const readme = yield generateReadme();

    const dist = _path.default.join(__dirname, '..', '..', 'README.md');

    _fs.default.writeFileSync(dist, readme);
  });

  return function generateReadmeAndWriteToDisk() {
    return _ref4.apply(this, arguments);
  };
}();

const assertReadmeIsUpToDate =
/*#__PURE__*/
function () {
  var _ref5 = _asyncToGenerator(function* () {
    const readme = yield generateReadme();

    const readmePath = _path.default.join(__dirname, '..', '..', 'README.md');

    const isUpToDate = _fs.default.readFileSync(readmePath).toString() === readme;

    if (!isUpToDate) {
      throw new Error('Readme is not up to date, please run `npm run create-readme` to update it.');
    }
  });

  return function assertReadmeIsUpToDate() {
    return _ref5.apply(this, arguments);
  };
}();

const main =
/*#__PURE__*/
function () {
  var _ref6 = _asyncToGenerator(function* () {
    try {
      const hasCheckFlag = process.argv.some(arg => {
        return arg === '--check';
      });

      if (hasCheckFlag) {
        yield assertReadmeIsUpToDate();
      } else {
        yield generateReadmeAndWriteToDisk();
      }
    } catch (error) {
      /* eslint-disable-next-line no-console */
      console.error(error);
      /* eslint-disable-next-line no-process-exit */

      process.exit(1);
    }
  });

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

main();
var _default = generateReadme;
exports.default = _default;
module.exports = exports.default;
//# sourceMappingURL=generateReadme.js.map