"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.gitBranchToNpmVersion = exports.gitBranchToNpmTag = exports.configureNpmRc = exports.deleteBranchTag = exports.executePublish = void 0;
const HandlerResult_1 = require("@atomist/automation-client/lib/HandlerResult");
const fs = require("fs-extra");
const p = require("path");
const LoggingProgressLog_1 = require("../../../api-helper/log/LoggingProgressLog");
const child_process_1 = require("../../../api-helper/misc/child_process");
const projectConfiguration_1 = require("../../../api-helper/project/configuration/projectConfiguration");
const withProject_1 = require("../../../api-helper/project/withProject");
const github = require("../../../core/util/github/ghub");
const types_1 = require("../../../typings/types");
/**
 * Execute npm publish
 *
 * Tags with branch-name unless the `tag` option is specified. If the branch === the repo's default branch
 * also the next tags is being set
 *
 * @param  projectLoader
 * @param  projectIdentifier
 * @param  preparations
 * @return {ExecuteGoal}
 */
function executePublish(projectIdentifier, options) {
    return withProject_1.doWithProject(async (goalInvocation) => {
        const { credentials, id, project, goalEvent } = goalInvocation;
        if (!(await projectConfiguration_1.projectConfigurationValue("npm.publish.enabled", project, true))) {
            return {
                code: 0,
                description: "Publish disabled",
                state: types_1.SdmGoalState.success,
            };
        }
        await configureNpmRc(options, project);
        const args = ["publish"];
        if (!!options.registry) {
            args.push("--registry", options.registry);
        }
        const access = await projectConfiguration_1.projectConfigurationValue("npm.publish.access", project, options.access);
        if (access) {
            args.push("--access", access);
        }
        if (!!options.tag) {
            args.push("--tag", options.tag);
        }
        else {
            args.push("--tag", gitBranchToNpmTag(id.branch));
        }
        let result = await goalInvocation.spawn("npm", args);
        if (result.code === 0) {
            const pi = await projectIdentifier(project);
            // Additionally publish the next tag
            if (goalEvent.push.repo.defaultBranch === goalEvent.branch && options.nextTag !== false) {
                const nextArgs = ["dist-tag", "add", `${pi.name}@${pi.version}`, "next"];
                if (!!options.registry) {
                    nextArgs.push("--registry", options.registry);
                }
                result = await goalInvocation.spawn("npm", nextArgs);
                if (result.code !== 0) {
                    return result;
                }
            }
            const url = `${options.registry}/${pi.name}/-/${pi.name}-${pi.version}.tgz`;
            result.externalUrls = [
                {
                    label: "NPM package",
                    url,
                },
            ];
            if (options.status) {
                await github.createStatus(credentials, id, {
                    context: "npm/atomist/package",
                    description: "NPM package",
                    target_url: url,
                    state: "success",
                });
            }
        }
        return result;
    });
}
exports.executePublish = executePublish;
async function deleteBranchTag(branch, project, options) {
    const pj = await project.getFile("package.json");
    if (pj) {
        const tag = gitBranchToNpmTag(branch);
        const name = JSON.parse(await pj.getContent()).name;
        await configureNpmRc(options, project);
        const result = await child_process_1.spawnLog("npm", ["dist-tags", "rm", name, tag], {
            cwd: project.baseDir,
            log: new LoggingProgressLog_1.LoggingProgressLog("npm dist-tag rm"),
        });
        return result;
    }
    return HandlerResult_1.Success;
}
exports.deleteBranchTag = deleteBranchTag;
/**
 * Create an npmrc file for the package.
 */
async function configureNpmRc(options, project) {
    await fs.writeFile(p.join(project.baseDir, ".npmrc"), options.npmrc, { mode: 0o600 });
    return options;
}
exports.configureNpmRc = configureNpmRc;
function gitBranchToNpmTag(branchName) {
    return `branch-${gitBranchToNpmVersion(branchName)}`;
}
exports.gitBranchToNpmTag = gitBranchToNpmTag;
function gitBranchToNpmVersion(branchName) {
    return branchName
        .replace(/[_/]/g, "-")
        .replace(/[^-.a-zA-Z0-9]+/g, "")
        .replace(/-+/g, "-");
}
exports.gitBranchToNpmVersion = gitBranchToNpmVersion;
//# sourceMappingURL=executePublish.js.map