UNPKG

2.68 kBJavaScriptView Raw
1const {parse, format} = require('url'); // eslint-disable-line node/no-deprecated-api
2const {isNil} = require('lodash');
3const hostedGitInfo = require('hosted-git-info');
4const {verifyAuth} = require('./git');
5
6/**
7 * Determine the the git repository URL to use to push, either:
8 * - The `repositoryUrl` as is if allowed to push
9 * - The `repositoryUrl` converted to `https` or `http` with Basic Authentication
10 *
11 * In addition, expand shortcut URLs (`owner/repo` => `https://github.com/owner/repo.git`) and transform `git+https` / `git+http` URLs to `https` / `http`.
12 *
13 * @param {Object} context semantic-release context.
14 *
15 * @return {String} The formatted Git repository URL.
16 */
17module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
18 const GIT_TOKENS = {
19 GIT_CREDENTIALS: undefined,
20 GH_TOKEN: undefined,
21 // GitHub Actions require the "x-access-token:" prefix for git access
22 // https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation
23 GITHUB_TOKEN: isNil(env.GITHUB_ACTION) ? undefined : 'x-access-token:',
24 GL_TOKEN: 'gitlab-ci-token:',
25 GITLAB_TOKEN: 'gitlab-ci-token:',
26 BB_TOKEN: 'x-token-auth:',
27 BITBUCKET_TOKEN: 'x-token-auth:',
28 };
29
30 const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
31 const {protocol, ...parsed} = parse(repositoryUrl);
32
33 if (info && info.getDefaultRepresentation() === 'shortcut') {
34 // Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
35 repositoryUrl = info.https();
36 } else if (protocol && protocol.includes('http')) {
37 // Replace `git+https` and `git+http` with `https` or `http`
38 repositoryUrl = format({...parsed, protocol: protocol.includes('https') ? 'https' : 'http', href: null});
39 }
40
41 // Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
42 try {
43 await verifyAuth(repositoryUrl, branch, {cwd, env});
44 } catch (_) {
45 const envVar = Object.keys(GIT_TOKENS).find(envVar => !isNil(env[envVar]));
46 const gitCredentials = `${GIT_TOKENS[envVar] || ''}${env[envVar] || ''}`;
47
48 if (gitCredentials) {
49 // If credentials are set via environment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
50 const [match, auth, host, path] = /^(?!.+:\/\/)(?:(.*)@)?(.*?):(.*)$/.exec(repositoryUrl) || [];
51 return format({
52 ...parse(match ? `ssh://${auth ? `${auth}@` : ''}${host}/${path}` : repositoryUrl),
53 auth: gitCredentials,
54 protocol: protocol && /http[^s]/.test(protocol) ? 'http' : 'https',
55 });
56 }
57 }
58
59 return repositoryUrl;
60};