"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.spawnCodeTransform = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const LoggingProgressLog_1 = require("../../log/LoggingProgressLog");
const child_process_1 = require("../../misc/child_process");
/**
 * Convert a SpawnLogResult into a TransformResult.
 */
async function spawnToTransform(p, r) {
    let edited = false;
    let status;
    try {
        status = await p.gitStatus();
        edited = !status.isClean;
    }
    catch (e) {
        logger_1.logger.warn(`Failed to determine GitProject status: ${e.message}`);
    }
    const tr = {
        target: p,
        success: r.code === 0,
        edited,
        error: r.error,
        errorStep: (r.error) ? r.cmdString : undefined,
    };
    return tr;
}
/**
 * Create a code transform by wrapping child processes run in the
 * project directory.  If a command fails, no further commands will be
 * run and its error will be returned.
 *
 * @param commands array of commands to execute
 * @param log where to log output from commands
 * @return result of commands, success or the first failure
 */
function spawnCodeTransform(commands, log) {
    return async (project, papi) => {
        const p = project;
        const defaultOptions = {
            cwd: p.baseDir,
            log: log || papi.progressLog || new LoggingProgressLog_1.LoggingProgressLog("spawnCodeTransform"),
        };
        defaultOptions.log.stripAnsi = true;
        let commandResult;
        for (const cmd of commands) {
            try {
                commandResult = await child_process_1.spawnLog(cmd.command, cmd.args, Object.assign(Object.assign({}, defaultOptions), cmd.options));
            }
            catch (e) {
                e.message = `Uncaught error when running command ${cmd.command}: ${e.message}`;
                logger_1.logger.warn(e.message);
                commandResult = {
                    cmdString: [cmd.command, ...cmd.args].join(" "),
                    code: 99,
                    error: e,
                };
                const errorResult = await spawnToTransform(p, commandResult);
                return errorResult;
            }
            if (commandResult.error) {
                logger_1.logger.warn(`Error in command ${commandResult.cmdString}: ${commandResult.error.message}`);
                const failResult = await spawnToTransform(p, commandResult);
                return failResult;
            }
        }
        const result = await spawnToTransform(p, commandResult);
        return result;
    };
}
exports.spawnCodeTransform = spawnCodeTransform;
//# sourceMappingURL=spawnCodeTransform.js.map