"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.branchAwareCodeTransform = void 0;
const HandlerResult_1 = require("@atomist/automation-client/lib/HandlerResult");
const editModes_1 = require("@atomist/automation-client/lib/operations/edit/editModes");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const constructionUtils_1 = require("@atomist/automation-client/lib/util/constructionUtils");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const slack_messages_1 = require("@atomist/slack-messages");
const _ = require("lodash");
const LoggingProgressLog_1 = require("../../log/LoggingProgressLog");
const handlerRegistrations_1 = require("../../machine/handlerRegistrations");
const toMachineOptions_1 = require("../../machine/toMachineOptions");
const messages_1 = require("../../misc/slack/messages");
/**
 * Wrap a CodeTransform to determine the target branch of the transform.
 *
 * If the target branch, as expressed by the CodeTransformRegistration.transformPresentation,
 * already exists, the wrapped CodeTransform will run against that branch instead of the
 * requested branch.
 * @param codeTransformRegistration
 * @param sdm
 */
function branchAwareCodeTransform(codeTransformRegistration, sdm) {
    return Object.assign(Object.assign({}, codeTransformRegistration), { listener: handleBranchAwareCodeTransform(codeTransformRegistration, sdm) });
}
exports.branchAwareCodeTransform = branchAwareCodeTransform;
function handleBranchAwareCodeTransform(codeTransformRegistration, sdm) {
    const codeTransform = constructionUtils_1.toFactory(handlerRegistrations_1.codeTransformRegistrationToCommand(toMachineOptions_1.toMachineOptions(sdm), codeTransformRegistration))();
    return async (ci) => {
        const target = ci.parameters.targets;
        if (!target || !target.repoRef || !target.repoRef.owner || !target.repoRef.repo) {
            await ci.context.messageClient.respond(messages_1.slackErrorMessage("Code Transform", `Can only invoke Code Transform ${slack_messages_1.italic(ci.commandName)} against a single repository. ` +
                `Please specify ${slack_messages_1.codeLine("targets.owner")} and ${slack_messages_1.codeLine("targets.repo")} parameters.`, ci.context));
            return HandlerResult_1.Success;
        }
        const id = ci.ids[0];
        return sdm.configuration.sdm.projectLoader.doWithProject({
            credentials: ci.credentials,
            id,
            readOnly: true,
            context: ci.context,
            cloneOptions: {
                alwaysDeep: false,
            },
        }, async (p) => {
            // Obtain the transform presentation to retrieve the target branch
            let branch = id.branch;
            if (codeTransformRegistration.transformPresentation) {
                const editMode = codeTransformRegistration.transformPresentation(Object.assign(Object.assign({}, ci), { progressLog: new LoggingProgressLog_1.LoggingProgressLog(codeTransformRegistration.name, "debug") }), p);
                if (editModes_1.isBranchCommit(editMode)) {
                    branch = editMode.branch;
                }
            }
            // Check if there is already a branch named
            const result = await ci.context.graphClient.query({
                name: "BranchForName",
                variables: {
                    branch,
                    owner: id.owner,
                    repo: id.repo,
                },
                options: GraphClient_1.QueryNoCacheOptions,
            });
            if (!!_.get(result, "Branch[0].id")) {
                // Branch exists; run the code transform on that branch instead
                logger_1.logger.debug(`Target branch '${branch}' already exists. Redirecting code transform to run against that branch`);
                const newParams = Object.assign({}, ci.parameters);
                newParams.targets.branch = branch;
                return codeTransform.handle(ci.context, newParams);
            }
            else {
                // Branch doesn't exist yet; run code transform as is
                logger_1.logger.debug(`Target branch '${branch}' does not exist. Applying code transform on requested branch`);
                return codeTransform.handle(ci.context, ci.parameters);
            }
        });
    };
}
//# sourceMappingURL=codeTransformWrapping.js.map