"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 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 chartRegex = (0, regex_1.regEx)('^(?<registryRef>[^/]*)/(?<packageName>[^/]*)$');
function createDep(key, doc) {
    const dep = {
        depName: key,
        datasource: helm_1.HelmDatasource.id,
    };
    const anApp = doc.apps[key];
    if (!anApp) {
        return null;
    }
    if (!anApp.version) {
        dep.skipReason = 'unspecified-version';
        return dep;
    }
    dep.currentValue = anApp.version;
    // in case of OCI repository, we need a PackageDependency with a DockerDatasource and a packageName
    if ((0, oci_1.isOCIRegistry)(anApp.chart)) {
        dep.datasource = docker_1.DockerDatasource.id;
        dep.packageName = (0, oci_1.removeOCIPrefix)(anApp.chart);
        return dep;
    }
    const regexResult = anApp.chart ? chartRegex.exec(anApp.chart) : null;
    if (!regexResult?.groups) {
        dep.skipReason = 'invalid-url';
        return dep;
    }
    if (!is_1.default.nonEmptyString(regexResult.groups.packageName)) {
        dep.skipReason = 'invalid-name';
        return dep;
    }
    dep.packageName = regexResult.groups.packageName;
    const registryUrl = doc.helmRepos[regexResult.groups.registryRef];
    if (!is_1.default.nonEmptyString(registryUrl)) {
        dep.skipReason = 'no-repository';
        return dep;
    }
    dep.registryUrls = [registryUrl];
    return dep;
}
function extractPackageFile(content, packageFile, _config) {
    try {
        // TODO: use schema (#9610)
        const doc = (0, yaml_1.parseSingleYaml)(content, {
            json: true,
        });
        if (!doc.apps) {
            logger_1.logger.debug({ packageFile }, `Missing apps keys`);
            return null;
        }
        const deps = Object.keys(doc.apps)
            .map((key) => createDep(key, doc))
            .filter(is_1.default.truthy); // filter null values
        if (deps.length === 0) {
            return null;
        }
        return { deps };
    }
    catch (err) /* istanbul ignore next */ {
        if (err.stack?.startsWith('YAMLException:')) {
            logger_1.logger.debug({ err, packageFile }, 'YAML exception extracting');
        }
        else {
            logger_1.logger.debug({ err, packageFile }, 'Error extracting');
        }
        return null;
    }
}
//# sourceMappingURL=extract.js.map