1 | const {parse, format} = require('url');
|
2 | const {isNil} = require('lodash');
|
3 | const hostedGitInfo = require('hosted-git-info');
|
4 | const {verifyAuth} = require('./git');
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
|
18 | const GIT_TOKENS = {
|
19 | GIT_CREDENTIALS: undefined,
|
20 | GH_TOKEN: undefined,
|
21 |
|
22 |
|
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 |
|
35 | repositoryUrl = info.https();
|
36 | } else if (protocol && protocol.includes('http')) {
|
37 |
|
38 | repositoryUrl = format({...parsed, protocol: protocol.includes('https') ? 'https' : 'http', href: null});
|
39 | }
|
40 |
|
41 |
|
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 |
|
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 | };
|