"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.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TryToUpdateDependency = exports.UpdateDependencyTransform = exports.UpdateDependencyParameters = exports.AutoMergeCheckSuccessTag = exports.AutoMergeCheckSuccessLabel = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const decorators_1 = require("@atomist/automation-client/lib/decorators");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const slack_messages_1 = require("@atomist/slack-messages");
const StringCapturingProgressLog_1 = require("../../../api-helper/log/StringCapturingProgressLog");
const child_process_1 = require("../../../api-helper/misc/child_process");
const dateFormat_1 = require("../../../api-helper/misc/dateFormat");
exports.AutoMergeCheckSuccessLabel = "auto-merge:on-check-success";
exports.AutoMergeCheckSuccessTag = `[${exports.AutoMergeCheckSuccessLabel}]`;
let UpdateDependencyParameters = class UpdateDependencyParameters {
    constructor() {
        this.tag = "latest";
    }
};
__decorate([
    decorators_1.Parameter({
        displayName: "Desired NPM dist tag to update to",
        description: "The desired NPM dist tag to update dependencies to",
        pattern: /^.+$/,
        required: false,
    }),
    __metadata("design:type", String)
], UpdateDependencyParameters.prototype, "tag", void 0);
__decorate([
    decorators_1.Parameter({
        displayName: "NPM package to update",
        description: "The NPM package to update",
        pattern: /^.+$/,
        required: true,
    }),
    __metadata("design:type", String)
], UpdateDependencyParameters.prototype, "package", void 0);
UpdateDependencyParameters = __decorate([
    decorators_1.Parameters()
], UpdateDependencyParameters);
exports.UpdateDependencyParameters = UpdateDependencyParameters;
const UpdateDependencyTransform = async (p, ctx, params) => {
    const tag = params.tag;
    const range = tag === "latest" ? "^" : "";
    const pjFile = await p.getFile("package.json");
    const pj = JSON.parse(await pjFile.getContent());
    const versions = [];
    const message = {
        text: `Updating ${slack_messages_1.codeLine(params.package)} NPM dependency of ${slack_messages_1.codeLine(pj.name)}`,
        attachments: [
            {
                text: "",
                fallback: "Versions",
            },
        ],
    };
    const opts = {
        id: string_1.guid(),
    };
    const sendMessage = async (msg) => {
        if (msg) {
            message.attachments[0].text = `${message.attachments[0].text}${msg}`;
            message.attachments[0].footer = `${configuration_1.configurationValue("name")}:${configuration_1.configurationValue("version")}`;
        }
        await ctx.context.messageClient.respond(message, opts);
    };
    await sendMessage();
    if (pj.dependencies) {
        await updateDependencies(pj.dependencies, params.package, tag, range, versions, sendMessage);
    }
    if (pj.devDependencies) {
        await updateDependencies(pj.devDependencies, params.package, tag, range, versions, sendMessage);
    }
    await pjFile.setContent(`${JSON.stringify(pj, undefined, 2)}\n`);
    if (!(await p.isClean())) {
        await sendMessage(`\nVersion updated. Running ${slack_messages_1.codeLine("npm install")}`);
        // NPM doesn't like to go back to older versions; hence we delete the lock file here to force the
        // dependencies in
        p.deleteFileSync("package-lock.json");
        const result = await child_process_1.spawnLog("npm", ["i"], {
            cwd: p.baseDir,
            env: Object.assign(Object.assign({}, process.env), { NODE_ENV: "development" }),
            log: new StringCapturingProgressLog_1.StringCapturingProgressLog(),
        });
        await sendMessage(result.code === 0
            ? `\n:atomist_build_passed: ${slack_messages_1.codeLine("npm install")} completed successfully`
            : `\n:atomist_build_failed: ${slack_messages_1.codeLine("npm install")} failed`);
        // Exit if npm install failed
        if (result.code !== 0) {
            return {
                edited: false,
                target: p,
                success: false,
            };
        }
    }
    params.commitMessage = `Update ${params.package} dependency to tag ${params.tag}

${versions.join("\n")}

[atomist:generated] ${exports.AutoMergeCheckSuccessTag}`;
    return p;
};
exports.UpdateDependencyTransform = UpdateDependencyTransform;
async function updateDependencies(deps, pkg, tag, range, versions, sendMessage) {
    for (const k in deps) {
        if (deps.hasOwnProperty(k)) {
            if (k === pkg) {
                const oldVersion = deps[k];
                const version = `${range}${await latestVersion(`${k}@${tag}`)}`;
                if (version && oldVersion !== version) {
                    deps[k] = version;
                    versions.push(`${k} ${oldVersion} > ${version}`);
                    await sendMessage(`:atomist_build_passed: Updated ${slack_messages_1.codeLine(k)} from ${slack_messages_1.codeLine(oldVersion)} to ${slack_messages_1.codeLine(version)}\n`);
                }
            }
        }
    }
}
async function latestVersion(module) {
    const log = new StringCapturingProgressLog_1.StringCapturingProgressLog();
    const result = await child_process_1.spawnLog("npm", ["show", module, "version"], {
        logCommand: false,
        log,
    });
    if (result.code === 0) {
        return log.log.trim();
    }
    return undefined;
}
exports.TryToUpdateDependency = {
    transform: exports.UpdateDependencyTransform,
    paramsMaker: UpdateDependencyParameters,
    name: "UpdateDependency",
    description: `Update NPM dependency`,
    intent: ["update dependency", "update dep"],
    transformPresentation: ci => {
        return new BranchCommit(ci.parameters);
    },
};
class BranchCommit {
    constructor(params) {
        this.params = params;
    }
    get message() {
        return this.params.commitMessage || "Update NPM dependency";
    }
    get branch() {
        return `atomist-update-${this.params.tag}-${dateFormat_1.formatDate()}`;
    }
}
//# sourceMappingURL=tryToUpdateDependency.js.map