"use strict";
/*
 * Copyright © 2020 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.pipeline = exports.runPipeline = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const progress_1 = require("../../../api-helper/goal/progress/progress");
const withProject_1 = require("../../../api-helper/project/withProject");
const GoalWithFulfillment_1 = require("../../../api/goal/GoalWithFulfillment");
const types_1 = require("../../../typings/types");
const PipelineProgressReporter = progress_1.testProgressReporter({
    test: /Running step '(.*)'/i,
    phase: "$1",
});
/**
 * Execute provided pipeline steps in the order they are provided or until one fails
 */
async function runPipeline(gi, ...steps) {
    const { progressLog } = gi;
    const context = {};
    for (const step of steps) {
        try {
            if (!step.runWhen || !!(await step.runWhen(gi))) {
                progressLog.write(`Running step '${step.name}'`);
                const result = await step.run(gi, context);
                if (!!result && (result.code !== 0 || result.state !== types_1.SdmGoalState.failure)) {
                    return result;
                }
            }
            else {
                progressLog.write(`Skipping step '${step.name}'`);
            }
        }
        catch (e) {
            logger_1.logger.warn(`Step '${step.name}' errored with:`);
            logger_1.logger.warn(e);
            return {
                state: types_1.SdmGoalState.failure,
                phase: step.name,
            };
        }
    }
}
exports.runPipeline = runPipeline;
/**
 * Goal that executes the provided pipeline steps
 */
function pipeline(details, ...steps) {
    return GoalWithFulfillment_1.goal(details, withProject_1.doWithProject(async (gi) => {
        return runPipeline(gi, ...steps);
    }, { readOnly: false, detachHead: true }), { progressReporter: PipelineProgressReporter });
}
exports.pipeline = pipeline;
//# sourceMappingURL=pipeline.js.map