"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRemoteUrlWithToken = exports.getHttpUrl = exports.parseGitUrl = void 0;
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);
}
exports.parseGitUrl = parseGitUrl;
function getHttpUrl(url, token) {
    const parsedUrl = parseGitUrl(url);
    const protocol = (0, regex_1.regEx)(/^https?$/).exec(parsedUrl.protocol)
        ? parsedUrl.protocol
        : 'https';
    parsedUrl.token = token ?? '';
    if (token) {
        switch ((0, common_1.detectPlatform)(parsedUrl.toString(protocol))) {
            case 'gitlab':
                parsedUrl.token = token.includes(':')
                    ? token
                    : `gitlab-ci-token:${token}`;
                break;
            case 'github':
                parsedUrl.token = token.includes(':')
                    ? token
                    : `x-access-token:${token}`;
                break;
        }
    }
    return new URL(parsedUrl.toString(protocol)).href;
}
exports.getHttpUrl = getHttpUrl;
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;
}
exports.getRemoteUrlWithToken = getRemoteUrlWithToken;
//# sourceMappingURL=url.js.map