"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getParsedSiblingChartYaml = exports.getSiblingChartYamlContent = exports.matchesHelmValuesInlineImage = exports.matchesHelmValuesDockerHeuristic = void 0;
const logger_1 = require("../../../logger");
const fs_1 = require("../../../util/fs");
const object_1 = require("../../../util/object");
const regex_1 = require("../../../util/regex");
const schema_1 = require("./schema");
const parentKeyRe = (0, regex_1.regEx)(/image$/i);
/**
 * Type guard to determine whether a given partial Helm values.yaml object potentially
 * defines a Helm Docker dependency.
 *
 * There is no exact standard of how Docker dependencies are defined in Helm
 * values.yaml files (as of February 26th 2021), this function defines a
 * heuristic based on the most commonly used format in the Helm charts:
 *
 * image:
 *   repository: 'something'
 *   tag: v1.0.0
 * image:
 *   repository: 'something'
 *   version: v1.0.0
 * renovateImage:
 *   repository: 'something'
 *   tag: v1.0.0
 */
function matchesHelmValuesDockerHeuristic(parentKey, data) {
    return !!(parentKeyRe.test(parentKey) &&
        data &&
        typeof data === 'object' &&
        (0, object_1.hasKey)('repository', data) &&
        ((0, object_1.hasKey)('tag', data) || (0, object_1.hasKey)('version', data)));
}
exports.matchesHelmValuesDockerHeuristic = matchesHelmValuesDockerHeuristic;
function matchesHelmValuesInlineImage(parentKey, data) {
    return !!(parentKeyRe.test(parentKey) && data && typeof data === 'string');
}
exports.matchesHelmValuesInlineImage = matchesHelmValuesInlineImage;
/**
 * This function looks for a Chart.yaml in the same directory as @param fileName and
 * returns its raw contents.
 *
 * @param fileName
 */
async function getSiblingChartYamlContent(fileName) {
    try {
        const chartFileName = (0, fs_1.getSiblingFileName)(fileName, 'Chart.yaml');
        return await (0, fs_1.readLocalFile)(chartFileName, 'utf8');
    }
    catch (err) {
        logger_1.logger.debug({ fileName }, 'Failed to read helm Chart.yaml');
        return null;
    }
}
exports.getSiblingChartYamlContent = getSiblingChartYamlContent;
/**
 * This function looks for a Chart.yaml in the same directory as @param fileName and
 * if it looks like a valid Helm Chart.yaml, it is parsed and returned as an object.
 *
 * @param fileName
 */
async function getParsedSiblingChartYaml(fileName) {
    try {
        const chartContents = await getSiblingChartYamlContent(fileName);
        if (!chartContents) {
            logger_1.logger.debug({ fileName }, 'Failed to find helm Chart.yaml');
            return null;
        }
        return schema_1.ChartDefinitionYaml.parse(chartContents);
    }
    catch (err) {
        logger_1.logger.debug({ fileName }, 'Failed to parse helm Chart.yaml');
        return null;
    }
}
exports.getParsedSiblingChartYaml = getParsedSiblingChartYaml;
//# sourceMappingURL=util.js.map