"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.anyFileChangedWithExtension = exports.anyFileChangedSuchThat = exports.Rename = exports.filesChangedSince = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const child_process_1 = require("../child_process");
/**
 * Use git to list the files changed since the given sha
 * or undefined if we cannot determine it
 * @param {GitProject} project
 * @param {PushFields.Fragment} push
 * @return {Promise<string[]>}
 */
async function filesChangedSince(project, push) {
    // get the number of commits from the after
    const commitCount = push && push.commits ? push.commits.length : 1;
    const sha = push && push.after ? push.after.sha : "HEAD";
    try {
        return await gitDiff(sha, commitCount, project);
    }
    catch (err) {
        try {
            await child_process_1.execPromise("git", ["fetch", "--unshallow", "--no-tags"], { cwd: project.baseDir });
            return await gitDiff(sha, commitCount, project);
        }
        catch (err) {
            logger_1.logger.debug("Error diffing project %j since '%s': %s", project.id, sha, err.message);
            try {
                const gs = await project.gitStatus();
                logger_1.logger.debug("Git status sha '%s' and branch '%s'", gs.sha, gs.branch);
                const timeOfLastChange = await child_process_1.execPromise("ls", ["-ltr", "."], { cwd: project.baseDir });
                logger_1.logger.debug("Files with dates: " + timeOfLastChange.stdout);
            }
            catch (err) {
                logger_1.logger.debug("Error while trying extra logging: " + err.stack);
            }
            return undefined;
        }
    }
}
exports.filesChangedSince = filesChangedSince;
async function gitDiff(sha, commitCount, project) {
    const cr = await child_process_1.execPromise("git", ["diff", "--name-only", `${sha}~${commitCount}`], { cwd: project.baseDir });
    // stdout is nothing but a list of files, one per line
    logger_1.logger.debug(`Output from filesChangedSince ${sha} on ${JSON.stringify(project.id)}:\n${cr.stdout}`);
    return cr.stdout.split("\n")
        .filter(n => !!n);
}
class Rename {
    constructor(name, newName) {
        this.name = name;
        this.newName = newName;
        this.how = "renamed";
    }
}
exports.Rename = Rename;
/**
 * Does a file satisfying this text exist within the set of changed files?
 * @param {string[]} changedFilePaths
 * @param {string[]} test test for the file change
 * @return {boolean}
 */
function anyFileChangedSuchThat(changedFilePaths, test) {
    return changedFilePaths.some(test);
}
exports.anyFileChangedSuchThat = anyFileChangedSuchThat;
function anyFileChangedWithExtension(changedFilePaths, extensions) {
    return anyFileChangedSuchThat(changedFilePaths, path => extensions.some(ext => path.endsWith(prefixWithDot(ext))));
}
exports.anyFileChangedWithExtension = anyFileChangedWithExtension;
function prefixWithDot(ext) {
    return ext.startsWith(".") ? ext : "." + ext;
}
//# sourceMappingURL=filesChangedSince.js.map