"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.IsReleaseCommit = exports.executeRelease = exports.Release = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const GoalNameGenerator_1 = require("../../api/goal/GoalNameGenerator");
const GoalWithFulfillment_1 = require("../../api/goal/GoalWithFulfillment");
const projectVersioner_1 = require("../../core/delivery/build/local/projectVersioner");
const semver_1 = require("./semver");
/**
 * Class that abstracts creating a release for a project.
 */
class Release extends GoalWithFulfillment_1.FulfillableGoal {
    constructor(detailsOrUniqueName = GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("release"), ...dependsOn) {
        super(Object.assign(Object.assign({ workingDescription: "Releasing", completedDescription: "Released", failedDescription: "Releasing failure" }, GoalWithFulfillment_1.getGoalDefinitionFrom(detailsOrUniqueName, GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("release"))), { displayName: "release" }), ...dependsOn);
    }
    /**
     * Called by the SDM on initialization.  This function calls
     * `super.register` and adds a startup listener to the SDM.
     *
     * The startup listener registers a default, no-op goal fulfillment.
     */
    register(sdm) {
        super.register(sdm);
        sdm.addStartupListener(async () => {
            if (this.fulfillments.length === 0 && this.callbacks.length === 0) {
                this.with({
                    name: GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("noop-release"),
                    releaseCreator: async () => ({ code: 0, message: "Release goal executed" }),
                });
            }
        });
    }
    /**
     * Add fulfillment to this goal.
     */
    with(registration) {
        super.addFulfillment({
            name: registration.name || GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("release"),
            goalExecutor: executeRelease(registration.releaseCreator),
            pushTest: registration.pushTest,
        });
        return this;
    }
}
exports.Release = Release;
/**
 * Return an ExecuteGoal function that creates a release using the
 * provided releaseCreator function.  The function converts the
 * version associated with the goal set into a release-like semantic
 * version, see [[releaseLikeVersion]], before passing it to the
 * release creator function.
 *
 * @param releaseCreator Release creator function to use to create the release
 * @return Execute goal function
 */
function executeRelease(releaseCreator) {
    return async (gi) => {
        const { configuration, credentials, id, context, progressLog } = gi;
        if (!configuration.sdm.projectLoader) {
            const message = `Invalid configuration: no projectLoader`;
            logger_1.logger.error(message);
            progressLog.write(message);
            return { code: 1, message };
        }
        return configuration.sdm.projectLoader.doWithProject({ credentials, id, context, readOnly: true }, async (p) => {
            const slug = `${p.id.owner}/${p.id.repo}`;
            const version = await projectVersioner_1.goalInvocationVersion(gi);
            if (!version) {
                const msg = `Current goal set does not have a version`;
                logger_1.logger.error(msg);
                progressLog.write(msg);
                return { code: 1, msg };
            }
            const releaseVersion = semver_1.releaseLikeVersion(version, gi);
            progressLog.write(`Creating release ${releaseVersion} for ${slug}`);
            let releaseResult;
            try {
                releaseResult = await releaseCreator({
                    credentials,
                    goalEvent: gi.goalEvent,
                    id,
                    log: progressLog,
                    project: p,
                    releaseVersion,
                });
            }
            catch (e) {
                const msg = `Failed to create release for ${slug}: ${e.message}`;
                logger_1.logger.error(msg);
                progressLog.write(msg);
                return { code: 1, msg };
            }
            releaseResult.message =
                releaseResult.message ||
                    (releaseResult.code ? "Failed to create" : "Created") + ` release ${releaseVersion} for ${slug}`;
            progressLog.write(releaseResult.message);
            return releaseResult;
        });
    };
}
exports.executeRelease = executeRelease;
/**
 * Push test detecting if the after commit of the push is related to a
 * release.
 */
exports.IsReleaseCommit = {
    name: "IsReleaseCommit",
    mapping: async (pi) => {
        const versionRegexp = /Version: increment after .* release/i;
        const changelogRegexp = /Changelog: add release .*/i;
        const commitMessage = pi.push.after && pi.push.after.message ? pi.push.after.message : "";
        return versionRegexp.test(commitMessage) || changelogRegexp.test(commitMessage);
    },
};
//# sourceMappingURL=release.js.map