"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = exports.parseAzurePipelines = exports.extractAzurePipelinesTasks = exports.extractContainer = exports.extractRepository = void 0;
const global_1 = require("../../../config/global");
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const regex_1 = require("../../../util/regex");
const url_1 = require("../../../util/url");
const azure_pipelines_tasks_1 = require("../../datasource/azure-pipelines-tasks");
const git_tags_1 = require("../../datasource/git-tags");
const extract_1 = require("../dockerfile/extract");
const schema_1 = require("./schema");
const AzurePipelinesTaskRegex = (0, regex_1.regEx)(/^(?<name>[^@]+)@(?<version>.*)$/);
function extractRepository(repository, currentRepository) {
    let repositoryUrl = null;
    let depName = repository.name;
    if (repository.type === 'github') {
        repositoryUrl = `https://github.com/${repository.name}.git`;
    }
    else if (repository.type === 'git') {
        const platform = global_1.GlobalConfig.get('platform');
        const endpoint = global_1.GlobalConfig.get('endpoint');
        if (platform === 'azure' && endpoint) {
            // extract the project name if the repository from which the pipline is referencing templates contains the Azure DevOps project name
            if (repository.name.includes('/')) {
                const [projectName, repoName] = repository.name.split('/');
                repositoryUrl = (0, url_1.joinUrlParts)(endpoint, encodeURIComponent(projectName), '_git', encodeURIComponent(repoName));
                // if the repository from which the pipline is referencing templates does not contain the Azure DevOps project name, get the project name from the repository containing the pipeline file being process
            }
            else if (currentRepository && currentRepository.includes('/')) {
                const projectName = currentRepository.split('/')[0];
                depName = `${projectName}/${repository.name}`;
                repositoryUrl = (0, url_1.joinUrlParts)(endpoint, encodeURIComponent(projectName), '_git', encodeURIComponent(repository.name));
            }
            else {
                logger_1.logger.debug('Renovate cannot update Azure pipelines in git repositories when neither the current repository nor the target repository contains the Azure DevOps project name.');
            }
        }
    }
    if (repositoryUrl === null) {
        return null;
    }
    if (!repository.ref?.startsWith('refs/tags/')) {
        return null;
    }
    return {
        autoReplaceStringTemplate: 'refs/tags/{{newValue}}',
        currentValue: repository.ref.replace('refs/tags/', ''),
        datasource: git_tags_1.GitTagsDatasource.id,
        depName,
        depType: 'gitTags',
        packageName: repositoryUrl,
        replaceString: repository.ref,
    };
}
exports.extractRepository = extractRepository;
function extractContainer(container) {
    const dep = (0, extract_1.getDep)(container.image);
    logger_1.logger.debug({
        depName: dep.depName,
        currentValue: dep.currentValue,
        currentDigest: dep.currentDigest,
    }, 'Azure pipelines docker image');
    dep.depType = 'docker';
    return dep;
}
exports.extractContainer = extractContainer;
function extractAzurePipelinesTasks(task) {
    const match = AzurePipelinesTaskRegex.exec(task);
    if (match?.groups) {
        return {
            depName: match.groups.name,
            currentValue: match.groups.version,
            datasource: azure_pipelines_tasks_1.AzurePipelinesTasksDatasource.id,
        };
    }
    return null;
}
exports.extractAzurePipelinesTasks = extractAzurePipelinesTasks;
function parseAzurePipelines(content, packageFile) {
    const res = schema_1.AzurePipelinesYaml.safeParse(content);
    if (res.success) {
        return res.data;
    }
    else {
        logger_1.logger.debug({ err: res.error, packageFile }, 'Error parsing pubspec lockfile.');
    }
    return null;
}
exports.parseAzurePipelines = parseAzurePipelines;
function extractSteps(steps) {
    const deps = [];
    for (const step of (0, array_1.coerceArray)(steps)) {
        const task = extractAzurePipelinesTasks(step.task);
        if (task) {
            deps.push(task);
        }
    }
    return deps;
}
function extractJob(job) {
    return extractSteps(job?.steps);
}
function extractDeploy(deploy) {
    const deps = extractJob(deploy?.deploy);
    deps.push(...extractJob(deploy?.postRouteTraffic));
    deps.push(...extractJob(deploy?.preDeploy));
    deps.push(...extractJob(deploy?.routeTraffic));
    deps.push(...extractJob(deploy?.on?.failure));
    deps.push(...extractJob(deploy?.on?.success));
    return deps;
}
function extractJobs(jobs) {
    const deps = [];
    for (const jobOrDeployment of (0, array_1.coerceArray)(jobs)) {
        const deployment = jobOrDeployment;
        if (deployment.strategy) {
            deps.push(...extractDeploy(deployment.strategy.canary));
            deps.push(...extractDeploy(deployment.strategy.rolling));
            deps.push(...extractDeploy(deployment.strategy.runOnce));
            continue;
        }
        const job = jobOrDeployment;
        deps.push(...extractJob(job));
    }
    return deps;
}
function extractPackageFile(content, packageFile, config) {
    logger_1.logger.trace(`azurePipelines.extractPackageFile(${packageFile})`);
    const deps = [];
    const pkg = parseAzurePipelines(content, packageFile);
    if (!pkg) {
        return null;
    }
    for (const repository of (0, array_1.coerceArray)(pkg.resources?.repositories)) {
        const dep = extractRepository(repository, config.repository);
        if (dep) {
            deps.push(dep);
        }
    }
    for (const container of (0, array_1.coerceArray)(pkg.resources?.containers)) {
        const dep = extractContainer(container);
        if (dep) {
            deps.push(dep);
        }
    }
    for (const { jobs } of (0, array_1.coerceArray)(pkg.stages)) {
        deps.push(...extractJobs(jobs));
    }
    deps.push(...extractJobs(pkg.jobs));
    deps.push(...extractSteps(pkg.steps));
    if (!deps.length) {
        return null;
    }
    return { deps };
}
exports.extractPackageFile = extractPackageFile;
//# sourceMappingURL=extract.js.map