"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = void 0;
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 kubernetes_api_1 = require("../../datasource/kubernetes-api");
const kubernetesApiVersioning = tslib_1.__importStar(require("../../versioning/kubernetes-api"));
const extract_1 = require("../dockerfile/extract");
function extractPackageFile(content, packageFile, config) {
    logger_1.logger.trace('kubernetes.extractPackageFile()');
    const isKubernetesManifest = (0, regex_1.regEx)(/\s*apiVersion\s*:/).test(content) &&
        (0, regex_1.regEx)(/\s*kind\s*:/).test(content);
    if (!isKubernetesManifest) {
        return null;
    }
    const deps = [
        ...extractImages(content, config),
        ...extractApis(content, packageFile),
    ];
    return deps.length ? { deps } : null;
}
exports.extractPackageFile = extractPackageFile;
function extractImages(content, config) {
    const deps = [];
    for (const line of content.split(regex_1.newlineRegex)) {
        const match = (0, regex_1.regEx)(/^\s*-?\s*image:\s*['"]?([^\s'"]+)['"]?\s*/).exec(line);
        if (match) {
            const currentFrom = match[1];
            const dep = (0, extract_1.getDep)(currentFrom, true, config.registryAliases);
            logger_1.logger.debug({
                depName: dep.depName,
                currentValue: dep.currentValue,
                currentDigest: dep.currentDigest,
            }, 'Kubernetes image');
            deps.push(dep);
        }
    }
    return deps.filter((dep) => !dep.currentValue?.includes('${'));
}
function extractApis(content, packageFile) {
    let doc;
    try {
        // TODO: use schema (#9610)
        doc = (0, yaml_1.parseYaml)(content);
    }
    catch (err) {
        logger_1.logger.debug({ err, packageFile }, 'Failed to parse Kubernetes manifest.');
        return [];
    }
    return doc
        .filter(is_1.default.truthy)
        .filter((m) => is_1.default.nonEmptyStringAndNotWhitespace(m.kind) &&
        is_1.default.nonEmptyStringAndNotWhitespace(m.apiVersion))
        .filter((m) => kubernetes_api_1.supportedApis.has(m.kind))
        .map((configuration) => ({
        depName: configuration.kind,
        currentValue: configuration.apiVersion,
        datasource: kubernetes_api_1.KubernetesApiDatasource.id,
        versioning: kubernetesApiVersioning.id,
    }));
}
//# sourceMappingURL=extract.js.map