"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseGitUrl = parseGitUrl;
exports.getHttpUrl = getHttpUrl;
exports.getRemoteUrlWithToken = getRemoteUrlWithToken;
const tslib_1 = require("tslib");
const git_url_parse_1 = tslib_1.__importDefault(require("git-url-parse"));
const logger_1 = require("../../logger");
const common_1 = require("../common");
const hostRules = tslib_1.__importStar(require("../host-rules"));
const regex_1 = require("../regex");
function parseGitUrl(url) {
    return (0, git_url_parse_1.default)(url);
}
function getHttpUrl(url, token) {
    const parsedUrl = parseGitUrl(url);
    let { protocol } = parsedUrl;
    const origProtocol = protocol;
    // Convert non-https URLs to https and strip port
    if (!(0, regex_1.regEx)(/^https?$/).test(protocol)) {
        parsedUrl.port = 443;
        protocol = 'https';
    }
    parsedUrl.user = '';
    parsedUrl.token = token ?? '';
    switch ((0, common_1.detectPlatform)(parsedUrl.toString(protocol))) {
        case 'gitlab':
            if (token) {
                parsedUrl.token = token.includes(':')
                    ? token
                    : `gitlab-ci-token:${token}`;
            }
            break;
        case 'github':
            if (token) {
                parsedUrl.token = token.includes(':')
                    ? token
                    : `x-access-token:${token}`;
            }
            break;
        case 'bitbucket-server':
            // SSH URLs look like ssh://git@git.my.com:7999/project/repo.git
            // HTTPS URLs look like https://git.my.com/scm/project/repo.git
            // git-url-parse can't detect bitbucket-server from SSH URL
            // and thus doesn't know it should insert '/scm/'
            if (origProtocol === 'ssh') {
                parsedUrl.source = 'bitbucket-server';
            }
            break;
    }
    return new URL(parsedUrl.toString(protocol)).href;
}
function getRemoteUrlWithToken(url, hostType) {
    let coercedUrl;
    try {
        coercedUrl = getHttpUrl(url);
    }
    catch {
        logger_1.logger.warn({ url }, `Attempting to use non-git url for git operations`);
        coercedUrl = url;
    }
    const hostRule = hostRules.find({ url: coercedUrl, hostType });
    if (hostRule?.token) {
        logger_1.logger.debug(`Found hostRules token for url ${url}`);
        return getHttpUrl(url, encodeURIComponent(hostRule.token));
    }
    if (hostRule?.username && hostRule?.password) {
        logger_1.logger.debug(`Found hostRules username and password for url ${url}`);
        const encodedUsername = encodeURIComponent(hostRule.username);
        const encodedPassword = encodeURIComponent(hostRule.password);
        return getHttpUrl(url, `${encodedUsername}:${encodedPassword}`);
    }
    return url;
}
//# sourceMappingURL=url.js.map