UNPKG

@cjbarth/github-release-notes

Version:

Create a release from a tag and uses issues or commits to creating the release notes. It also can generate a CHANGELOG.md file based on the release notes (or generate a brand new).

1,089 lines (1,071 loc) 80.6 kB
Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _chalk = _interopRequireDefault(require("chalk")); var _githubApi = _interopRequireDefault(require("github-api")); var _utils = _interopRequireDefault(require("./_utils.js")); var _template = require("./_template.js"); var _connectivity = _interopRequireDefault(require("connectivity")); var _templates = _interopRequireDefault(require("./templates.js")); var _objectAssignDeep = _interopRequireDefault(require("object-assign-deep")); var _semverCompare = _interopRequireDefault(require("semver-compare")); var _fs = _interopRequireDefault(require("fs")); var _child_process = require("child_process"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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 _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var defaults = { tags: [], prefix: "", template: _templates["default"], prerelease: false, generate: false, quiet: false, override: false, debug: false, ignoreLabels: false, ignoreIssuesWith: false, ignoreCommitsWith: false, groupBy: false, milestoneMatch: "Release {{tag_name}}" }; var MAX_TAGS_LIMIT = 99; var TAGS_LIMIT = 30; /** Class creating release notes and changelog notes */ var Gren = /*#__PURE__*/function () { function Gren() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Gren); this.options = (0, _objectAssignDeep["default"])({}, defaults, props); this.tasks = []; var _this$options = this.options, username = _this$options.username, repo = _this$options.repo, token = _this$options.token, apiUrl = _this$options.apiUrl, tags = _this$options.tags, limit = _this$options.limit, ignoreLabels = _this$options.ignoreLabels, ignoreIssuesWith = _this$options.ignoreIssuesWith, ignoreCommitsWith = _this$options.ignoreCommitsWith, ignoreTagsWith = _this$options.ignoreTagsWith; this.options.head = this.options.head || (0, _child_process.execSync)("git symbolic-ref --short HEAD", { encoding: "utf-8" }); try { (0, _child_process.execSync)("git rev-parse --abbrev-ref --symbolic-full-name @{u}"); } catch (_unused) { this.options.head = (0, _child_process.execSync)("git remote show origin | grep 'HEAD branch' | cut -d' ' -f5", { encoding: "utf-8" }); } this.options.head = this.options.head.trim(); this.options.tags = _utils["default"].convertStringToArray(tags); this.options.ignoreLabels = _utils["default"].convertStringToArray(ignoreLabels); this.options.ignoreIssuesWith = _utils["default"].convertStringToArray(ignoreIssuesWith); this.options.ignoreCommitsWith = _utils["default"].convertStringToArray(ignoreCommitsWith); this.options.ignoreTagsWith = _utils["default"].convertStringToArray(ignoreTagsWith); this.options.version = this.options.version || _utils["default"].findRelevantVersion(); if (limit && limit > 0 && limit <= MAX_TAGS_LIMIT) { this.options.limit = limit; } else if (this.options.tags.indexOf("all") >= 0) { this.options.limit = MAX_TAGS_LIMIT; } else { this.options.limit = TAGS_LIMIT; } if (!token) { throw _chalk["default"].red("You must provide the TOKEN"); } if (this.options.debug) { this._outputOptions(this.options); } this.githubApi = new _githubApi["default"]({ token: token }, apiUrl); this.repo = this.githubApi.getRepo(username, repo); this.issues = this.githubApi.getIssues(username, repo); } /** * Generate release notes and draft a new release * * @since 0.10.0 * @public * * @return {Promise} */ return _createClass(Gren, [{ key: "release", value: (function () { var _release = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() { var _this = this; var blocks; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _utils["default"].printTask(this.options.quiet, "Generate release notes"); _context.next = 3; return this._hasNetwork(); case 3: _context.next = 5; return this._getReleaseBlocks(); case 5: blocks = _context.sent; return _context.abrupt("return", blocks.reduce(function (carry, block) { return carry.then(_this._prepareRelease.bind(_this, block)); }, Promise.resolve())); case 7: case "end": return _context.stop(); } }, _callee, this); })); function release() { return _release.apply(this, arguments); } return release; }() /** * Generate changelog file based on the release notes or generate new one * * @since 0.10.0 * @public * * @return {Promise} */ ) }, { key: "changelog", value: (function () { var _changelog = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { var releases; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _utils["default"].printTask(this.options.quiet, "Generate changelog file"); _context2.next = 3; return this._hasNetwork(); case 3: this._checkChangelogFile(); if (!this.options.generate) { _context2.next = 10; break; } _context2.next = 7; return this._getReleaseBlocks(); case 7: _context2.t0 = _context2.sent; _context2.next = 13; break; case 10: _context2.next = 12; return this._getListReleases(); case 12: _context2.t0 = _context2.sent; case 13: releases = _context2.t0; if (!(releases.length === 0)) { _context2.next = 16; break; } throw _chalk["default"].red("There are no releases, use --generate to create release notes, or run the release command."); case 16: return _context2.abrupt("return", this._createChangelog(this._templateReleases(releases))); case 17: case "end": return _context2.stop(); } }, _callee2, this); })); function changelog() { return _changelog.apply(this, arguments); } return changelog; }() /** * Check if the changelog file exists * * @since 0.8.0 * @private * * @return {string} */ ) }, { key: "_checkChangelogFile", value: function _checkChangelogFile() { var filePath = process.cwd() + "/" + this.options.changelogFilename; if (_fs["default"].existsSync(filePath) && !this.options.override) { throw _chalk["default"].black(_chalk["default"].bgYellow("Looks like there is already a changelog, to override it use --override")); } return filePath; } /** * Create the changelog file * * @since 0.8.0 * @private * * @param {string} body The body of the file */ }, { key: "_createChangelog", value: function _createChangelog(body) { var loaded = _utils["default"].task(this, "Creating ".concat(this.options.changelogFilename)); var filePath = process.cwd() + "/" + this.options.changelogFilename; _fs["default"].writeFileSync(filePath, this.options.template.changelogTitle + body); loaded(_chalk["default"].green("Changelog created in ".concat(filePath))); } /** * Edit a release from a given tag (in the options) * * @since 0.5.0 * @private * * @param {number} releaseId The id of the release to edit * @param {Object} releaseOptions The options to build the release: * @example * { * "tag_name": "v1.0.0", * "target_commitish": "master", * "name": "v1.0.0", * "body": "Description of the release", * "draft": false, * "prerelease": false * } * * @return {Promise} */ }, { key: "_editRelease", value: (function () { var _editRelease2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(releaseId, releaseOptions) { var loaded, _yield$this$repo$upda, release; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: loaded = _utils["default"].task(this, "Updating latest release"); _context3.next = 3; return this.repo.updateRelease(releaseId, releaseOptions); case 3: _yield$this$repo$upda = _context3.sent; release = _yield$this$repo$upda.data; loaded(_chalk["default"].green("".concat(release.name, " has been successfully updated!")) + _chalk["default"].blue("\nSee the results here: ".concat(release.html_url))); return _context3.abrupt("return", release); case 7: case "end": return _context3.stop(); } }, _callee3, this); })); function _editRelease(_x, _x2) { return _editRelease2.apply(this, arguments); } return _editRelease; }() /** * Create a release from a given tag (in the options) * * @since 0.1.0 * @private * * @param {Object} releaseOptions The options to build the release: * @example { * "tag_name": "1.0.0", * "target_commitish": "master", * "name": "v1.0.0", * "body": "Description of the release", * "draft": false, * "prerelease": false * } * * @return {Promise} */ ) }, { key: "_createRelease", value: (function () { var _createRelease2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(releaseOptions) { var loaded, _yield$this$repo$crea, release; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: loaded = _utils["default"].task(this, "Preparing the release"); _context4.next = 3; return this.repo.createRelease(releaseOptions); case 3: _yield$this$repo$crea = _context4.sent; release = _yield$this$repo$crea.data; loaded(_chalk["default"].green("".concat(release.name, " has been successfully created!")) + _chalk["default"].blue("\nSee the results here: ".concat(release.html_url))); return _context4.abrupt("return", release); case 7: case "end": return _context4.stop(); } }, _callee4, this); })); function _createRelease(_x3) { return _createRelease2.apply(this, arguments); } return _createRelease; }() /** * Creates the options to make the release * * @since 0.2.0 * @private * * @param {Object[]} tags The collection of tags * * @return {Promise} */ ) }, { key: "_prepareRelease", value: function _prepareRelease(block) { var releaseOptions = { tag_name: block.release, name: block.name, body: block.body, draft: this.options.draft, prerelease: this.options.prerelease }; if (block.id) { if (!this.options.override) { console.warn(_chalk["default"].black(_chalk["default"].bgYellow("Skipping ".concat(block.release, " (use --override to replace it)")))); return Promise.resolve(); } return this._editRelease(block.id, releaseOptions); } return this._createRelease(releaseOptions); } /** * Get the tags information from the given ones, and adds * the next one in case only one is given * * @since 0.5.0 * @private * * @param {Array|string} allTags * @param {Object[]} tags * * @return {Boolean|Array} */ }, { key: "_getSelectedTags", value: function _getSelectedTags(allTags) { var tags = this.options.tags; if (tags.indexOf("all") >= 0) { return allTags; } if (!allTags || !allTags.length || !tags.length) { return false; } var selectedTags = [].concat(tags); return allTags.filter(function (_ref, index) { var name = _ref.name; var isSelectedTag = selectedTags.includes(name); if (isSelectedTag && selectedTags.length === 1 && allTags[index + 1]) { selectedTags.push(allTags[index + 1].name); } return isSelectedTag; }).slice(0, 2); } /** * Temporary function for this.repo.listReleases to accept options * * @see https://github.com/github-tools/github/pull/485 * @param {Object} options * * @return {Promise} */ }, { key: "_listTags", value: function _listTags(options) { return this.repo._request("GET", "/repos/".concat(this.repo.__fullname, "/tags"), options); } /** * Get all the tags of the repo * * @since 0.1.0 * @private * @deprecated * * @param {Array} releases * @param {number} page * * @return {Promise} */ }, { key: "_getLastTags", value: (function () { var _getLastTags2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(releases) { var _this2 = this; var page, limit, _yield$this$_listTags, link, tags, filteredTags, totalPages, _args5 = arguments; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: page = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : 1; limit = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : this.options.limit; _context5.next = 4; return this._listTags({ per_page: limit, page: page }); case 4: _yield$this$_listTags = _context5.sent; link = _yield$this$_listTags.headers.link; tags = _yield$this$_listTags.data; if (tags.length) { _context5.next = 9; break; } throw _chalk["default"].red("\nLooks like you have no tags! Tag a commit first and then run gren again"); case 9: filteredTags = (this._getSelectedTags(tags) || [tags[0], tags[1]]).filter(Boolean).filter(function (_ref2) { var name = _ref2.name; return _this2.options.ignoreTagsWith.every(function (ignoreTag) { return !name.match(ignoreTag); }); }).map(function (tag) { var tagRelease = releases ? releases.filter(function (release) { return release.tag_name === tag.name; })[0] : false; var releaseId = tagRelease ? tagRelease.id : null; return { tag: tag, releaseId: releaseId }; }); totalPages = this._getLastPage(link); if (!((this.options.tags.indexOf("all") >= 0 || filteredTags.length < 2) && totalPages && +page < totalPages)) { _context5.next = 13; break; } return _context5.abrupt("return", this._getLastTags(releases, page + 1).then(function (moreTags) { return moreTags.concat(filteredTags); })); case 13: return _context5.abrupt("return", filteredTags); case 14: case "end": return _context5.stop(); } }, _callee5, this); })); function _getLastTags(_x4) { return _getLastTags2.apply(this, arguments); } return _getLastTags; }() /** * Get all the tags of the repo * * @since 0.1.0 * @private * @deprecated * * @param {Array} releases * @param {number} page * * @return {Promise} */ ) }, { key: "_getAllTags", value: (function () { var _getAllTags2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(releases) { var _this3 = this; var page, limit, _yield$this$_listTags2, link, tags, filteredTags, totalPages, _iterator, _step, tag, gotCommit, _args6 = arguments; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: page = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : 1; limit = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : this.options.limit; _context6.next = 4; return this._listTags({ per_page: limit, page: page }); case 4: _yield$this$_listTags2 = _context6.sent; link = _yield$this$_listTags2.headers.link; tags = _yield$this$_listTags2.data; if (tags.length) { _context6.next = 9; break; } throw _chalk["default"].red("\nLooks like you have no tags! Tag a commit first and then run gren again"); case 9: filteredTags = tags.filter(function (tag) { return tag && _this3.options.ignoreTagsWith.every(function (ignoreTag) { return !tag.name.match(ignoreTag); }); }).map(function (tag) { var tagRelease = releases ? releases.filter(function (release) { return release.tag_name === tag.name; })[0] : false; var releaseId = tagRelease ? tagRelease.id : null; var releaseDate = tagRelease ? tagRelease.published_at : null; return { tag: tag, releaseId: releaseId, date: releaseDate }; }); totalPages = this._getLastPage(link); if (!(totalPages && page < totalPages)) { _context6.next = 13; break; } return _context6.abrupt("return", this._getAllTags(releases, page + 1).then(function (moreTags) { return moreTags.concat(filteredTags); })); case 13: _iterator = _createForOfIteratorHelper(filteredTags); _context6.prev = 14; _iterator.s(); case 16: if ((_step = _iterator.n()).done) { _context6.next = 24; break; } tag = _step.value; _context6.next = 20; return this.repo.getCommit(tag.tag.commit.sha); case 20: gotCommit = _context6.sent; tag.commit = gotCommit.data; case 22: _context6.next = 16; break; case 24: _context6.next = 29; break; case 26: _context6.prev = 26; _context6.t0 = _context6["catch"](14); _iterator.e(_context6.t0); case 29: _context6.prev = 29; _iterator.f(); return _context6.finish(29); case 32: return _context6.abrupt("return", filteredTags); case 33: case "end": return _context6.stop(); } }, _callee6, this, [[14, 26, 29, 32]]); })); function _getAllTags(_x5) { return _getAllTags2.apply(this, arguments); } return _getAllTags; }() /** * Temporary function for this.repo.listReleases to accept options * * @see https://github.com/github-tools/github/pull/485 * @param {Object} options * * @return {Promise} */ ) }, { key: "_listReleases", value: function _listReleases(options) { return this.repo._request("GET", "/repos/".concat(this.repo.__fullname, "/releases"), options); } /** * Get the merged pull requests from the repo * * @private * * @param {number} page * @param {number} limit * * @return {Promise[]} The promises which returns pull requests */ }, { key: "_getMergedPullRequests", value: (function () { var _getMergedPullRequests2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(since) { var page, limit, results, link, prs, totalPages, filterPrs, _args7 = arguments; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: page = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : 1; limit = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : 1000; _context7.next = 4; return this.repo.listPullRequests({ state: "closed", sort: "updated", direction: "desc", per_page: limit, page: page }); case 4: results = _context7.sent; link = results.headers.link, prs = results.data; totalPages = this._getLastPage(link); filterPrs = prs.filter(function (pr) { return pr.merged_at; }); if (!(prs.length > 0 && new Date(since) < new Date(prs[prs.length - 1].updated_at) && totalPages && +page < totalPages)) { _context7.next = 10; break; } return _context7.abrupt("return", this._getMergedPullRequests(since, page + 1).then(function (prsResults) { return prsResults.concat(filterPrs); })); case 10: if (!(typeof this.options.overridePrs === "function")) { _context7.next = 12; break; } return _context7.abrupt("return", this.options.overridePrs(prs)); case 12: return _context7.abrupt("return", filterPrs); case 13: case "end": return _context7.stop(); } }, _callee7, this); })); function _getMergedPullRequests(_x6) { return _getMergedPullRequests2.apply(this, arguments); } return _getMergedPullRequests; }() /** * Get the last page from a Hypermedia link * * @since 0.11.1 * @private * * @param {string} link * * @return {boolean|number} */ ) }, { key: "_getLastPage", value: function _getLastPage(link) { var linkMatch = Boolean(link) && link.match(/page=(\d+)>; rel="last"/); return linkMatch && +linkMatch[1]; } /** * Get all releases * * @since 0.5.0 * @private * * @return {Promise} The promise which resolves an array of releases */ }, { key: "_getListReleases", value: (function () { var _getListReleases2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() { var page, limit, loaded, _yield$this$_listRele, link, releases, totalPages, _args8 = arguments; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: page = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : 1; limit = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : this.options.limit; loaded = _utils["default"].task(this, "Getting the list of releases"); _context8.next = 5; return this._listReleases({ per_page: limit, page: page }); case 5: _yield$this$_listRele = _context8.sent; link = _yield$this$_listRele.headers.link; releases = _yield$this$_listRele.data; totalPages = this._getLastPage(link); if (!(this.options.tags.indexOf("all") >= 0 && totalPages && +page < totalPages)) { _context8.next = 11; break; } return _context8.abrupt("return", this._getListReleases(page + 1).then(function (moreReleases) { return moreReleases.concat(releases); })); case 11: loaded("Releases found: ".concat(releases.length)); return _context8.abrupt("return", releases); case 13: case "end": return _context8.stop(); } }, _callee8, this); })); function _getListReleases() { return _getListReleases2.apply(this, arguments); } return _getListReleases; }() /** * Generate the releases bodies from a release Objects Array * * @since 0.8.0 * @private * @ignore * * @param {Array} releases The release Objects Array coming from GitHub * * @return {string} */ ) }, { key: "_templateReleases", value: function _templateReleases(releases) { var template = this.options.template; return releases.map(function (release) { return (0, _template.generate)({ release: release.name || release.tag_name, date: _utils["default"].formatDate(new Date(release.published_at)), body: release.body }, template.release); }).join(template.releaseSeparator); } /** * Return the templated commit message * * @since 0.1.0 * @private * * @param {Object} commit * * @return {string} */ }, { key: "_templateCommits", value: function _templateCommits(_ref3) { var sha = _ref3.sha, html_url = _ref3.html_url, author = _ref3.author, _ref3$commit = _ref3.commit, name = _ref3$commit.author.name, message = _ref3$commit.message; return (0, _template.generate)({ sha: sha, message: message.split("\n")[0], url: html_url, author: author && author.login, authorName: name }, this.options.template.commit); } /** * Generate the MD template from all the labels of a specific issue * * @since 0.5.0 * @private * * @param {Object} issue * * @return {string} */ }, { key: "_templateLabels", value: function _templateLabels(issue) { var _this4 = this; var labels = Array.from(issue.labels); if (!labels.length && this.options.template.noLabel) { labels.push({ name: this.options.template.noLabel }); } return labels.filter(function (label) { return _this4.options.ignoreLabels.indexOf(label.name) === -1; }).map(function (label) { return (0, _template.generate)({ label: label.name }, _this4.options.template.label); }).join(""); } /** * Generate the MD template for each issue * * @since 0.5.0 * @private * * @param {Object} issue * * @return {string} */ }, { key: "_templateIssue", value: function _templateIssue(issue) { return (0, _template.generate)({ labels: this._templateLabels(issue), name: issue.title, text: "#" + issue.number, url: issue.html_url, body: issue.body, pr_base: issue.base && issue.base.ref, pr_head: issue.head && issue.head.ref, user_login: issue.user.login, user_url: issue.user.html_url }, this.options.template.issue); } /** * Generate the Changelog issues body template * * @since 0.5.0 * @private * * @param {Object[]} blocks * * @return {string} */ }, { key: "_templateBody", value: function _templateBody(body, rangeBody) { if (Array.isArray(body) && body.length) { return body.join("\n") + "\n"; } if (rangeBody) { return "".concat(rangeBody, "\n"); } return "*No changelog for this release.*\n"; } /** * Generates the template for the groups * * @since 0.8.0 * @private * * @param {Object} groups The groups to template e.g. * { * 'bugs': [{...}, {...}, {...}] * } * * @return {string} */ }, { key: "_templateGroups", value: function _templateGroups(groups) { var _this5 = this; var groupPostProcessor = this.options.groupPostProcessor; return Object.entries(groups).map(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), key = _ref5[0], value = _ref5[1]; var heading = (0, _template.generate)({ heading: key }, _this5.options.template.group); var body = value.join("\n"); var content = heading + "\n" + body; return groupPostProcessor ? groupPostProcessor(content) : content; }); } /** * Filter a commit based on the includeMessages option and commit message * * @since 0.10.0 * @private * * @param {Object} commit * * @return {Boolean} */ }, { key: "_filterCommit", value: function _filterCommit(_ref6) { var message = _ref6.commit.message; var messageType = this.options.includeMessages; var filterMap = { merges: function merges(message) { return message.match(/^merge/i); }, commits: function commits(message) { return !message.match(/^merge/i); }, all: function all() { return true; } }; var shouldIgnoreMessage = this.options.ignoreCommitsWith.every(function (commitMessage) { var regex = new RegExp(commitMessage, "i"); return !message.split("\n")[0].match(regex); }); if (filterMap[messageType]) { return filterMap[messageType](message) && shouldIgnoreMessage; } return filterMap.commits(message) && shouldIgnoreMessage; } /** * Return a commit messages generated body * * @since 0.1.0 * @private * * @param {Array} commits * * @return {string} */ }, { key: "_generateCommitsBody", value: function _generateCommitsBody() { var commits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var bodyMessages = Array.from(commits); return bodyMessages.filter(this._filterCommit.bind(this)).map(this._templateCommits.bind(this)).join("\n"); } /** * Get the blocks of commits based on release dates * * @since 0.5.0 * @private * * @param {Array} releaseRanges The array of date ranges * * @return {Promise[]} */ }, { key: "_getCommitBlocks", value: (function () { var _getCommitBlocks2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(releaseRanges) { var _this6 = this; var taskName, loaded, ranges; return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: taskName = "Creating the body blocks from commits"; loaded = _utils["default"].task(this, taskName); ranges = releaseRanges.map(function (range) { return { id: range[0].id, name: _this6.options.prefix + range[0].name, release: range[0].name, published_at: range[0].date, body: _this6._generateCommitsBody(range[2]) + "\n" }; }); loaded("Commit ranges loaded: ".concat(ranges.length)); return _context9.abrupt("return", Promise.resolve(ranges)); case 5: case "end": return _context9.stop(); } }, _callee9, this); })); function _getCommitBlocks(_x7) { return _getCommitBlocks2.apply(this, arguments); } return _getCommitBlocks; }() /** * Compare the ignored labels with the passed ones * * @since 0.10.0 * @private * * @param {Array} labels The labels to check * @example [{ * name: 'bug' * }] * * @return {boolean} If the labels array contains any of the ignore ones */ ) }, { key: "_lablesAreIgnored", value: function _lablesAreIgnored(labels) { if (!labels || !Array.isArray(labels)) { return false; } var ignoreIssuesWith = this.options.ignoreIssuesWith; return ignoreIssuesWith.some(function (label) { return labels.map(function (_ref7) { var name = _ref7.name; return name; }).includes(label); }); } /** * Get all the closed issues from the current repo * * @since 0.5.0 * @private * * @param {Array} releaseRanges The array of date ranges * * @return {Promise} The promise which resolves the list of the issues */ }, { key: "_getClosedIssues", value: (function () { var _getClosedIssues2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(releaseRanges) { var type, loaded, _yield$this$issues$li, issues; return _regeneratorRuntime().wrap(function _callee10$(_context10) { while (1) switch (_context10.prev = _context10.next) { case 0: type = { issues: "Issues", milestones: "Issues" }[this.options.dataSource]; loaded = _utils["default"].task(this, "Getting all closed ".concat(type)); _context10.next = 4; return this.issues.listIssues({ state: "closed", since: releaseRanges[releaseRanges.length - 1][1].date }); case 4: _yield$this$issues$li = _context10.sent; issues = _yield$this$issues$li.data; loaded("".concat(type, " found: ").concat(issues.length)); return _context10.ab