"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.patternMatchReviewer = void 0;
const projectUtils_1 = require("@atomist/automation-client/lib/project/util/projectUtils");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
/**
 * Return a ReviewerRegistration that objects to the given antipatterns and looks in the specified files
 * @param {string} name
 * @param opts targeting options
 * @param {AntiPattern} antiPatterns
 * @return {ReviewerRegistration}
 */
function patternMatchReviewer(name, opts, ...antiPatterns) {
    return {
        name,
        pushTest: opts.pushTest,
        inspection: async (project, cri) => {
            logger_1.logger.debug("Running regexp review '%s' on %s against %j", name, opts.globPattern, antiPatterns);
            const result = { repoId: project.id, comments: [] };
            await projectUtils_1.doWithFiles(project, opts.globPattern, async (f) => {
                const content = await f.getContent();
                antiPatterns.forEach(problem => {
                    const rex = typeof problem.antiPattern === "string" ?
                        new RegExp(_.escapeRegExp(problem.antiPattern)) :
                        problem.antiPattern;
                    if (rex.test(content)) {
                        logger_1.logger.debug("%s: Antipattern %s found in %s", name, problem.antiPattern, f.path);
                        result.comments.push({
                            severity: opts.severity || "error",
                            detail: problem.comment,
                            category: opts.category || name,
                            subcategory: opts.subcategory,
                            sourceLocation: {
                                path: f.path,
                                offset: undefined,
                                lineFrom1: findLineNumber(content, rex),
                            },
                        });
                    }
                });
            });
            return result;
        },
    };
}
exports.patternMatchReviewer = patternMatchReviewer;
function findLineNumber(source, regex) {
    const lines = source.split("\n");
    const lineFrom0 = lines.findIndex(l => regex.test(l));
    return lineFrom0 + 1;
}
//# sourceMappingURL=patternMatchReviewer.js.map