"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.taskRnvPublish = exports["default"] = void 0;var _semver = _interopRequireDefault(require("semver"));
var _config = _interopRequireDefault(require("../../core/configManager/config"));
var _exec = require("../../core/systemManager/exec");
var _logger = require("../../core/systemManager/logger");
var _fileutils = require("../../core/systemManager/fileutils");
var _taskManager = require("../../core/taskManager");
var _constants = require("../../core/constants");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _toConsumableArray(arr) {return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();}function _nonIterableSpread() {throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _iterableToArray(iter) {if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);}function _arrayWithoutHoles(arr) {if (Array.isArray(arr)) return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}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);});};}


var includesPre = function includesPre(version) {
  if (version.includes('alpha')) return 'alpha';
  if (version.includes('beta')) return 'beta';
  if (version.includes('rc')) return 'rc';
  return false;
};


/*
 *
 * Usage
 * rnv publish
 * rnv publish patch|minor|major
 * rnv publish patch|minor|major alpha|beta|rc
 * rnv publish 1.0.0
 * rnv publish 1.0.0-alpha.1
 * rnv publish ... --dry-run
 *
 * Basically the same as release-it documentation. The only difference is that you don't need to specify --preRelease=beta
 * if you are publishing a beta/alpha/rc. That is done automatically by checking if the second arg is alpha, beta, rc.
 *
 */
var taskRnvPublish = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, parentTask, originTask) {var _pkgJson$releaseIt, _pkgJson$releaseIt$ho;var pkgJson, existingPath, args, maybeVersion, secondArg, prereleaseMark, dir, execCommonOpts, ci, publishMode, _pkgJson$releaseIt2, skipRootPublish, rootPublishCommand, rootPublishIfNecessary, releaseIt;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('taskRnvPublish');_context2.next = 3;return (

              (0, _taskManager.executeTask)(c, _constants.TASK_PROJECT_CONFIGURE, _constants.TASK_PUBLISH, originTask));case 3:_context2.next = 5;return (


              _config["default"].checkRequiredPackage(c,
              'release-it',
              '12.4.3',
              'devDependencies'));case 5:
            // make sure required object is present in package.json
            pkgJson = c.files.project["package"];
            existingPath = c.paths.project["package"];

            if (!pkgJson['release-it']) {
              pkgJson['release-it'] = {
                git: {
                  // eslint-disable-next-line no-template-curly-in-string
                  tagName: 'v${version}',
                  requireCleanWorkingDir: false },

                npm: {
                  publish: false },

                hooks: {
                  // eslint-disable-next-line no-template-curly-in-string
                  'before:git': 'npx rnv pkg version ${version}' } };


              (0, _fileutils.writeFileSync)(existingPath, pkgJson);
            }

            // backwards compatibility and user change friendly
            if (!((_pkgJson$releaseIt = pkgJson['release-it']) !== null && _pkgJson$releaseIt !== void 0 && (_pkgJson$releaseIt$ho = _pkgJson$releaseIt.hooks) !== null && _pkgJson$releaseIt$ho !== void 0 && _pkgJson$releaseIt$ho['before:git'])) {
              if (!pkgJson['release-it'].hooks) {
                pkgJson['release-it'].hooks = {};
              }
              // eslint-disable-next-line no-template-curly-in-string
              pkgJson['release-it'].hooks['before:git'] = 'npx rnv pkg version ${version}';
              (0, _fileutils.writeFileSync)(existingPath, pkgJson);
            }

            if (!pkgJson['release-it'].publish) {
              pkgJson['release-it'].publish = 'local';
              pkgJson['release-it'].skipRootPublish = true;
              pkgJson['release-it'].rootPublishCommand = 'npx rnv deploy -p ios -s debug';
              (0, _fileutils.writeFileSync)(existingPath, pkgJson);
            }

            args = _toConsumableArray(_config["default"].getConfig().program.rawArgs);
            args = args.slice(3);

            maybeVersion = args[0];
            secondArg = args[1];
            prereleaseMark = '';

            // for handling `rnv publish patch alpha`
            if (['alpha', 'beta', 'rc'].includes(secondArg)) {
              args.splice(1, 1); // remove it so it won't interfere with release-it
              prereleaseMark = "--preRelease=".concat(secondArg);
            }

            // for handling `rnv publish 1.0.0-alpha.1`
            if (_semver["default"].valid(maybeVersion) && includesPre(maybeVersion)) {
              prereleaseMark = "--preRelease=".concat(includesPre(maybeVersion));
            }

            dir = _config["default"].getConfig().paths.project.dir;
            execCommonOpts = { interactive: true, env: process.env, cwd: dir };
            ci = _config["default"].getConfig().program.ci;
            publishMode = pkgJson['release-it'].publish || 'local';_pkgJson$releaseIt2 =
            pkgJson['release-it'], skipRootPublish = _pkgJson$releaseIt2.skipRootPublish, rootPublishCommand = _pkgJson$releaseIt2.rootPublishCommand;

            rootPublishIfNecessary = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.next = 2;return (
                          (0, _exec.executeAsync)('npx rnv pkg publish', execCommonOpts));case 2:if (
                        skipRootPublish) {_context.next = 6;break;}if (
                        rootPublishCommand) {_context.next = 5;break;}throw (
                          new Error(
                          "You don't have a rootPublishCommand specified in package.json"));case 5:return _context.abrupt("return",


                        (0, _exec.executeAsync)(rootPublishCommand, execCommonOpts));case 6:case "end":return _context.stop();}}}, _callee);}));return function rootPublishIfNecessary() {return _ref2.apply(this, arguments);};}();



            releaseIt = function releaseIt() {return (0, _exec.executeAsync)("npx release-it ".concat(
              args.join(' '), " ").concat(prereleaseMark),
              execCommonOpts)["catch"](

              function (e) {
                if (e.includes('SIGINT')) return Promise.resolve();
                if (e.includes('--no-git.requireUpstream')) {
                  return Promise.reject(
                  new Error(
                  'Seems like you have no upstream configured for current branch. Run `git push -u <origin> <your_branch>` to fix it then try again.'));


                }
                return Promise.reject(e);
              }).
              then(rootPublishIfNecessary);};

            // we have a ci flag, checking if the project is configured for ci releases to do a bumpless deploy
            if (!ci) {_context2.next = 28;break;}if (!(
            publishMode !== 'ci')) {_context2.next = 27;break;}return _context2.abrupt("return",
            (0, _logger.logWarning)(
            'You are running publish with --ci flag but this project is set for local deployments. Check package.json release-it.publish property'));case 27:return _context2.abrupt("return",


            rootPublishIfNecessary());case 28:return _context2.abrupt("return",


            releaseIt());case 29:case "end":return _context2.stop();}}}, _callee2);}));return function taskRnvPublish(_x, _x2, _x3) {return _ref.apply(this, arguments);};}();exports.taskRnvPublish = taskRnvPublish;var _default =


{
  description: '',
  fn: taskRnvPublish,
  task: 'publish',
  params: _constants.PARAMS.withBase(),
  platforms: [] };exports["default"] = _default;
//# sourceMappingURL=task.rnv.publish.js.map