UNPKG

gitter-markdown-processor

Version:
76 lines (66 loc) 2.37 kB
'use strict'; const url = require('url'); const URL_RE = /(?:\/(.*))+?\/(.*)\/(issues|merge_requests|pull|commit)\/([a-f0-9]+)$/; function isValidIssueNumber(val) { const number = Number(val); return number > 0 && number < Infinity; } function isValidCommitHash(val) { const hash = val.match(/[a-f0-9]*/)[0] || ''; return val.length === hash.length; } // eslint-disable-next-line complexity module.exports = function decorateUrl(href) { // https://github.com/gitterHQ/gitter/issues/1685 // https://github.com/gitterHQ/gitter/pull/21 // https://github.com/gitterHQ/ui-components/commit/ba64903a90bfaac2ac137af514e3dab62a302a5d // // https://gitlab.com/gitlab-org/gitter/webapp/issues/14 // https://gitlab.com/gitlab-org/gitter/webapp/-/issues/14 // https://gitlab.com/gitlab-org/gitter/webapp/merge_requests/1075 // https://gitlab.com/gitlab-org/gitter/styleguide/commit/6a61175e447548d9e1f3e5ed8e329d8578a38bb1 const urlObj = url.parse(href); const pathname = urlObj.pathname || ''; // removing the GitLab specific /-/ from the path before matching const pathMatches = pathname.replace('/-/', '/').match(URL_RE); const isGitLab = urlObj.hostname === 'gitlab.com'; const isGitHub = urlObj.hostname === 'github.com'; if ((isGitHub || isGitLab) && !urlObj.hash && pathMatches) { const group = pathMatches[1]; const project = pathMatches[2]; const pathType = pathMatches[3]; const id = pathMatches[4]; if ( (pathType === 'issues' || pathType === 'merge_requests' || pathType === 'pull') && id && isValidIssueNumber(id) ) { let type = 'issue'; if (project === 'issues') { type = 'issue'; } else if (pathType === 'merge_requests') { type = 'mr'; } else if (pathType === 'pull') { type = 'pr'; } return { type, provider: isGitLab ? 'gitlab' : 'github', repo: `${group}/${project}`, id, href, text: `${group}/${project}${isGitLab && type === 'mr' ? '!' : '#'}${id}`, }; } if (pathType === 'commit' && id && isValidCommitHash(id)) { return { type: 'commit', provider: isGitLab ? 'gitlab' : 'github', repo: `${group}/${project}`, id, href, text: `${group}/${project}@${id.substring(0, 7)}`, }; } } };