"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 js_yaml_1 = require("js-yaml");
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const extract_1 = require("../dockerfile/extract");
function extractPackageFile(content, fileName) {
    logger_1.logger.trace('tekton.extractPackageFile()');
    const deps = [];
    let docs;
    try {
        docs = (0, js_yaml_1.loadAll)(content);
    }
    catch (err) {
        logger_1.logger.debug({ err, fileName }, 'Failed to parse YAML resource as a Tekton resource');
        return null;
    }
    for (const doc of docs) {
        deps.push(...getDeps(doc));
    }
    if (!deps.length) {
        return null;
    }
    return { deps };
}
exports.extractPackageFile = extractPackageFile;
function getDeps(doc) {
    const deps = [];
    if (is_1.default.falsy(doc)) {
        return deps;
    }
    // Handle TaskRun resource
    addDep(doc.spec?.taskRef, deps);
    // Handle PipelineRun resource
    addDep(doc.spec?.pipelineRef, deps);
    // Handle Pipeline resource
    for (const task of (0, array_1.coerceArray)(doc.spec?.tasks)) {
        addDep(task.taskRef, deps);
    }
    // Handle TriggerTemplate resource
    for (const resource of (0, array_1.coerceArray)(doc.spec?.resourcetemplates)) {
        addDep(resource?.spec?.taskRef, deps);
        addDep(resource?.spec?.pipelineRef, deps);
    }
    // Handle list of TektonResources
    for (const item of (0, array_1.coerceArray)(doc.items)) {
        deps.push(...getDeps(item));
    }
    return deps;
}
function addDep(ref, deps) {
    if (is_1.default.falsy(ref)) {
        return;
    }
    let imageRef;
    // Find a bundle reference from the Bundle resolver
    if (ref.resolver === 'bundles') {
        for (const field of (0, array_1.coerceArray)(ref.resource)) {
            if (field.name === 'bundle') {
                imageRef = field.value;
                break;
            }
        }
    }
    if (is_1.default.nullOrUndefined(imageRef)) {
        // Fallback to older style bundle reference
        imageRef = ref.bundle;
    }
    const dep = (0, extract_1.getDep)(imageRef);
    dep.depType = 'tekton-bundle';
    logger_1.logger.trace({
        depName: dep.depName,
        currentValue: dep.currentValue,
        currentDigest: dep.currentDigest,
    }, 'Tekton bundle dependency found');
    deps.push(dep);
}
//# sourceMappingURL=extract.js.map