"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGitStatusContextCombinedName = getGitStatusContextCombinedName;
exports.getGitStatusContextFromCombinedName = getGitStatusContextFromCombinedName;
exports.getBranchNameWithoutRefsheadsPrefix = getBranchNameWithoutRefsheadsPrefix;
exports.getBranchNameWithoutRefsPrefix = getBranchNameWithoutRefsPrefix;
exports.getRenovatePRFormat = getRenovatePRFormat;
exports.getStorageExtraCloneOpts = getStorageExtraCloneOpts;
exports.max4000Chars = max4000Chars;
exports.getProjectAndRepo = getProjectAndRepo;
exports.getRepoByName = getRepoByName;
exports.mapMergeStrategy = mapMergeStrategy;
const GitInterfaces_js_1 = require("azure-devops-node-api/interfaces/GitInterfaces.js");
const logger_1 = require("../../../logger");
const sanitize_1 = require("../../../util/sanitize");
const string_1 = require("../../../util/string");
const pr_body_1 = require("../pr-body");
function getGitStatusContextCombinedName(context) {
    if (!context) {
        return undefined;
    }
    const combinedName = `${context.genre ? `${context.genre}/` : ''}${
    // TODO: types (#22198)
    context.name}`;
    logger_1.logger.trace(`Got combined context name of ${combinedName}`);
    return combinedName;
}
function getGitStatusContextFromCombinedName(context) {
    if (!context) {
        return undefined;
    }
    let name = context;
    let genre;
    const lastSlash = context.lastIndexOf('/');
    if (lastSlash > 0) {
        name = context.substring(lastSlash + 1);
        genre = context.substring(0, lastSlash);
    }
    return {
        genre,
        name,
    };
}
function getBranchNameWithoutRefsheadsPrefix(branchPath) {
    if (!branchPath) {
        logger_1.logger.error(`getBranchNameWithoutRefsheadsPrefix(undefined)`);
        return undefined;
    }
    if (!branchPath.startsWith('refs/heads/')) {
        logger_1.logger.trace(`The refs/heads/ name should have started with 'refs/heads/' but it didn't. (${branchPath})`);
        return branchPath;
    }
    return branchPath.substring(11, branchPath.length);
}
function getBranchNameWithoutRefsPrefix(branchPath) {
    if (!branchPath) {
        logger_1.logger.error(`getBranchNameWithoutRefsPrefix(undefined)`);
        return undefined;
    }
    if (!branchPath.startsWith('refs/')) {
        logger_1.logger.trace(`The ref name should have started with 'refs/' but it didn't. (${branchPath})`);
        return branchPath;
    }
    return branchPath.substring(5, branchPath.length);
}
const stateMap = {
    [GitInterfaces_js_1.PullRequestStatus.Abandoned]: 'closed',
    [GitInterfaces_js_1.PullRequestStatus.Completed]: 'merged',
};
function getRenovatePRFormat(azurePr) {
    const number = azurePr.pullRequestId;
    const sourceBranch = getBranchNameWithoutRefsheadsPrefix(azurePr.sourceRefName);
    const targetBranch = getBranchNameWithoutRefsheadsPrefix(azurePr.targetRefName);
    const bodyStruct = (0, pr_body_1.getPrBodyStruct)(azurePr.description);
    const createdAt = azurePr.creationDate?.toISOString();
    // TODO #22198
    const state = stateMap[azurePr.status] ?? 'open';
    const sourceRefName = azurePr.sourceRefName;
    return {
        ...azurePr,
        sourceBranch,
        state,
        number,
        bodyStruct,
        sourceRefName,
        targetBranch,
        createdAt,
    };
}
function getStorageExtraCloneOpts(config) {
    let authType;
    let authValue;
    if (!config.token && config.username && config.password) {
        authType = 'basic';
        authValue = (0, string_1.toBase64)(`${config.username}:${config.password}`);
    }
    else if (config.token?.length === 52) {
        authType = 'basic';
        authValue = (0, string_1.toBase64)(`:${config.token}`);
    }
    else {
        authType = 'bearer';
        authValue = config.token;
    }
    (0, sanitize_1.addSecretForSanitizing)(authValue, 'global');
    return {
        '-c': `http.extraheader=AUTHORIZATION: ${authType} ${authValue}`,
    };
}
function max4000Chars(str) {
    if (str && str.length >= 4000) {
        return str.substring(0, 3999);
    }
    return str;
}
function getProjectAndRepo(str) {
    logger_1.logger.trace(`getProjectAndRepo(${str})`);
    const strSplit = str.split(`/`);
    if (strSplit.length === 1) {
        return {
            project: str,
            repo: str,
        };
    }
    if (strSplit.length === 2) {
        return {
            project: strSplit[0],
            repo: strSplit[1],
        };
    }
    const msg = `${str} can be only structured this way : 'repository' or 'projectName/repository'!`;
    logger_1.logger.error(msg);
    throw new Error(msg);
}
function getRepoByName(name, repos) {
    logger_1.logger.trace(`getRepoByName(${name})`);
    let { project, repo } = getProjectAndRepo(name);
    project = project.toLowerCase();
    repo = repo.toLowerCase();
    const foundRepo = repos?.find((r) => project === r?.project?.name?.toLowerCase() &&
        repo === r?.name?.toLowerCase());
    if (!foundRepo) {
        logger_1.logger.debug(`Repo not found: ${name}`);
    }
    return foundRepo ?? null;
}
function mapMergeStrategy(mergeStrategy) {
    switch (mergeStrategy) {
        case 'rebase':
        case 'fast-forward':
            return GitInterfaces_js_1.GitPullRequestMergeStrategy.Rebase;
        case 'merge-commit':
            return GitInterfaces_js_1.GitPullRequestMergeStrategy.NoFastForward;
        case 'squash':
            return GitInterfaces_js_1.GitPullRequestMergeStrategy.Squash;
        default:
            return GitInterfaces_js_1.GitPullRequestMergeStrategy.NoFastForward;
    }
}
//# sourceMappingURL=util.js.map