"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyPackageRules = void 0;
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"));
const utils_1 = require("./utils");
function matchesRule(inputConfig, packageRule) {
    let positiveMatch = true;
    let matchApplied = false;
    // matches
    for (const groupMatchers of matchers_1.default) {
        const isMatch = (0, utils_1.matcherOR)('matches', groupMatchers, inputConfig, packageRule);
        // no rules are defined
        if (is_1.default.nullOrUndefined(isMatch)) {
            continue;
        }
        matchApplied = true;
        if (!is_1.default.truthy(isMatch)) {
            return false;
        }
    }
    // not a single match rule is defined --> assume to match everything
    if (!matchApplied) {
        positiveMatch = true;
    }
    // excludes
    for (const groupExcludes of matchers_1.default) {
        const isExclude = (0, utils_1.matcherOR)('excludes', groupExcludes, inputConfig, packageRule);
        // no rules are defined
        if (is_1.default.nullOrUndefined(isExclude)) {
            continue;
        }
        if (isExclude) {
            return false;
        }
    }
    return positiveMatch;
}
function applyPackageRules(inputConfig) {
    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,
                });
            }
            config = (0, config_1.mergeChildConfig)(config, toApply);
        }
    }
    return config;
}
exports.applyPackageRules = applyPackageRules;
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