"use strict";
/*
 * Copyright © 2019 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.anyFileChanged = exports.isMaterialChange = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const micromatch = require("micromatch");
const GoalNameGenerator_1 = require("../../api/goal/GoalNameGenerator");
const PushTest_1 = require("../../api/mapping/PushTest");
const filesChangedSince_1 = require("../misc/git/filesChangedSince");
/**
 * Check if a Push represents a material change.
 *
 * Material changes are changes to files that should trigger certain activity
 * or goals. Often simple changes to MD or html files should not trigger a full CI/CD process.
 */
function isMaterialChange(options = {}) {
    return PushTest_1.pushTest(GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("material-change"), async (pci) => {
        const changedFiles = await filesChangedSince_1.filesChangedSince(pci.project, pci.push);
        if (!changedFiles) {
            logger_1.logger.debug("Cannot determine if change is material on '%s/%s'. Failed to enumerate changed files", pci.id.owner, pci.id.repo);
            return true;
        }
        logger_1.logger.debug(`Changed files: '${changedFiles.join(", ")}'`);
        if (anyFileChanged(options, changedFiles)) {
            logger_1.logger.debug("Change is material on '%s/%s'", pci.id.owner, pci.id.repo);
            return true;
        }
        else {
            logger_1.logger.debug("Change is immaterial on '%s/%s'", pci.id.owner, pci.id.repo);
        }
        return false;
    });
}
exports.isMaterialChange = isMaterialChange;
function anyFileChanged(options = {}, changedFiles) {
    return filesChangedSince_1.anyFileChangedWithExtension(changedFiles, options.extensions || []) ||
        filesChangedSince_1.anyFileChangedSuchThat(changedFiles, path => (options.files || []).some(f => path === f)) ||
        filesChangedSince_1.anyFileChangedSuchThat(changedFiles, path => (options.directories || []).some(d => path.startsWith(d))) ||
        micromatch(changedFiles, options.globs || []).length > 0;
}
exports.anyFileChanged = anyFileChanged;
//# sourceMappingURL=materialChangeTest.js.map