"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.executeIncrementVersion = exports.IncrementVersion = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const child_process_1 = require("../../api-helper/misc/child_process");
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 incrementing project version after a release.
 */
class IncrementVersion extends GoalWithFulfillment_1.FulfillableGoal {
    constructor(goalDetailsOrUniqueName = GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("increment-version"), ...dependsOn) {
        super(Object.assign(Object.assign({ workingDescription: "Incrementing version", completedDescription: "Incremented version", failedDescription: "Incrementing version failure" }, GoalWithFulfillment_1.getGoalDefinitionFrom(goalDetailsOrUniqueName, GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("increment-version"))), { displayName: "increment version" }), ...dependsOn);
    }
    /**
     * Add fulfillment to this goal.
     */
    with(registration) {
        super.addFulfillment({
            name: registration.name || GoalNameGenerator_1.DefaultGoalNameGenerator.generateName("increment-version"),
            goalExecutor: executeIncrementVersion(registration.versionIncrementer),
            pushTest: registration.pushTest,
        });
        return this;
    }
}
exports.IncrementVersion = IncrementVersion;
/**
 * Return goal executor that increments version using the provided
 * increment function and then commits & pushes the changes.
 *
 * Since this function changes and commits to the project at a time
 * when several other goals may be doing the same, it first checks out
 * the branch associated with the goal invocation and pulls to get the
 * latest head from the remote.
 */
function executeIncrementVersion(versionIncrementer) {
    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: false }, async (p) => {
            const version = await projectVersioner_1.goalInvocationVersion(gi);
            if (!version) {
                const message = `Current goal set does not have a version`;
                logger_1.logger.error(message);
                progressLog.write(message);
                return { code: 1, message };
            }
            const versionRelease = semver_1.releaseLikeVersion(version, gi);
            const slug = `${p.id.owner}/${p.id.repo}`;
            const branch = gi.goalEvent.branch;
            const remote = p.remote || "origin";
            const spawnOpts = { cwd: p.baseDir, log: progressLog };
            try {
                progressLog.write(`Pulling branch '${branch}' of ${slug}`);
                await p.checkout(branch);
                const pullResult = await child_process_1.spawnLog("git", ["pull", remote, branch], spawnOpts);
                if (pullResult.code) {
                    throw new Error(pullResult.message || "git pull failed");
                }
                p.branch = branch;
            }
            catch (e) {
                const message = `Failed to get latest changes on branch '${branch}' for ${slug}: ${e.message}`;
                logger_1.logger.error(message);
                progressLog.write(message);
                return { code: 1, message };
            }
            try {
                progressLog.write(`Incrementing version on branch '${branch}' for ${slug}`);
                const incrementResult = await versionIncrementer({
                    currentVersion: versionRelease,
                    goalEvent: gi.goalEvent,
                    id,
                    increment: "patch",
                    log: progressLog,
                    project: p,
                });
                if (incrementResult.code) {
                    throw new Error(incrementResult.message || "version incrementer failed");
                }
            }
            catch (e) {
                const message = `Failed to increment version on branch '${branch}' for ${slug}: ${e.message}`;
                logger_1.logger.error(message);
                progressLog.write(message);
                return { code: 1, message };
            }
            if (await p.isClean()) {
                const message = `Project versioner made no changes on branch '${branch}' for ${slug}`;
                progressLog.write(message);
                return { code: 0, message };
            }
            try {
                progressLog.write(`Committing version increment on branch '${branch}' for ${slug}`);
                await p.commit(`Version: increment after ${versionRelease} release\n\n[atomist:generated]`);
                await p.push();
            }
            catch (e) {
                const message = `Failed to increment version on branch '${branch}' for ${slug}: ${e.message}`;
                logger_1.logger.error(message);
                progressLog.write(message);
                return { code: 1, message };
            }
            return { code: 0, message: `Successfully incremented version on branch '${branch}' for ${slug}` };
        });
    };
}
exports.executeIncrementVersion = executeIncrementVersion;
//# sourceMappingURL=increment.js.map