"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const regex_1 = require("../../../util/regex");
const yaml_1 = require("../../../util/yaml");
const docker_1 = require("../../datasource/docker");
const helm_1 = require("../../datasource/helm");
const oci_1 = require("../helmv3/oci");
const schema_1 = require("./schema");
const utils_1 = require("./utils");
const isValidChartName = (name) => !!name && !(0, regex_1.regEx)(/[!@#$%^&*(),.?":{}/|<>A-Z]/).test(name);
function isLocalPath(possiblePath) {
    return ['./', '../', '/'].some((localPrefix) => possiblePath.startsWith(localPrefix));
}
async function extractPackageFile(content, packageFile, config) {
    const deps = [];
    let registryData = {};
    // Record kustomization usage for all deps, since updating artifacts is run on the helmfile.yaml as a whole.
    let needKustomize = false;
    const docs = (0, yaml_1.parseYaml)(content, {
        customSchema: schema_1.Doc,
        failureBehaviour: 'filter',
        removeTemplates: true,
    });
    for (const doc of docs) {
        // Always check for repositories in the current document and override the existing ones if any (as YAML does)
        if (doc.repositories) {
            registryData = {};
            for (let i = 0; i < doc.repositories.length; i += 1) {
                registryData[doc.repositories[i].name] = doc.repositories[i];
            }
            logger_1.logger.debug({ registryAliases: registryData, packageFile }, `repositories discovered.`);
        }
        for (const dep of (0, array_1.coerceArray)(doc.releases)) {
            let depName = dep.chart;
            let repoName = null;
            // If it starts with ./ ../ or / then it's a local path
            if (isLocalPath(dep.chart)) {
                if ((0, utils_1.kustomizationsKeysUsed)(dep) ||
                    (await (0, utils_1.localChartHasKustomizationsYaml)(dep, packageFile))) {
                    needKustomize = true;
                }
                deps.push({
                    depName: dep.name,
                    skipReason: 'local-chart',
                });
                continue;
            }
            if ((0, oci_1.isOCIRegistry)(dep.chart)) {
                const v = dep.chart.substring(6).split('/');
                depName = v.pop();
                repoName = v.join('/');
            }
            else if (dep.chart.includes('/')) {
                const v = dep.chart.split('/');
                repoName = v.shift();
                depName = v.join('/');
            }
            else {
                repoName = dep.chart;
            }
            if (!is_1.default.string(dep.version)) {
                deps.push({
                    depName,
                    skipReason: 'invalid-version',
                });
                continue;
            }
            const res = {
                depName,
                currentValue: dep.version,
                registryUrls: [registryData[repoName]?.url]
                    .concat([config.registryAliases?.[repoName]])
                    .filter(is_1.default.string),
            };
            if ((0, utils_1.kustomizationsKeysUsed)(dep)) {
                needKustomize = true;
            }
            if ((0, oci_1.isOCIRegistry)(dep.chart)) {
                res.datasource = docker_1.DockerDatasource.id;
                res.packageName = `${repoName}/${depName}`;
            }
            else if (registryData[repoName]?.oci) {
                res.datasource = docker_1.DockerDatasource.id;
                const alias = registryData[repoName]?.url;
                if (alias) {
                    res.packageName = `${alias}/${depName}`;
                }
            }
            // By definition on helm the chart name should be lowercase letter + number + -
            // However helmfile support templating of that field
            if (!isValidChartName(res.depName)) {
                res.skipReason = 'unsupported-chart-type';
            }
            // Skip in case we cannot locate the registry
            if (res.datasource !== docker_1.DockerDatasource.id &&
                is_1.default.emptyArray(res.registryUrls)) {
                res.skipReason = 'unknown-registry';
            }
            deps.push(res);
        }
    }
    return deps.length
        ? {
            deps,
            datasource: helm_1.HelmDatasource.id,
            ...(needKustomize && { managerData: { needKustomize } }),
        }
        : null;
}
//# sourceMappingURL=extract.js.map