"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyPackageRules = applyPackageRules;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const slugify_1 = tslib_1.__importDefault(require("slugify"));
const config_1 = require("../../config");
const logger_1 = require("../../logger");
const matchers_1 = tslib_1.__importDefault(require("./matchers"));
function matchesRule(inputConfig, packageRule) {
    for (const matcher of matchers_1.default) {
        const isMatch = matcher.matches(inputConfig, packageRule);
        // no rules are defined
        if (is_1.default.nullOrUndefined(isMatch)) {
            continue;
        }
        if (!is_1.default.truthy(isMatch)) {
            return false;
        }
    }
    return true;
}
function applyPackageRules(inputConfig, stageName) {
    let config = { ...inputConfig };
    const packageRules = config.packageRules ?? [];
    logger_1.logger.trace({ dependency: config.depName, packageRules }, `Checking against ${packageRules.length} packageRules`);
    for (const packageRule of packageRules) {
        // This rule is considered matched if there was at least one positive match and no negative matches
        if (matchesRule(config, packageRule)) {
            // Package rule config overrides any existing config
            const toApply = removeMatchers({ ...packageRule });
            if (config.groupSlug && packageRule.groupName && !packageRule.groupSlug) {
                // Need to apply groupSlug otherwise the existing one will take precedence
                toApply.groupSlug = (0, slugify_1.default)(packageRule.groupName, {
                    lower: true,
                });
            }
            if (toApply.enabled === false && config.enabled !== false) {
                config.skipReason = 'package-rules';
                if (stageName) {
                    config.skipStage = stageName;
                }
            }
            if (toApply.enabled === true && config.enabled === false) {
                delete config.skipReason;
                delete config.skipStage;
            }
            config = (0, config_1.mergeChildConfig)(config, toApply);
        }
    }
    return config;
}
function removeMatchers(packageRule) {
    for (const key of Object.keys(packageRule)) {
        if (key.startsWith('match') || key.startsWith('exclude')) {
            delete packageRule[key];
        }
    }
    return packageRule;
}
//# sourceMappingURL=index.js.map