"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.applySpec = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const error_1 = require("../support/error");
const retry_1 = require("../support/retry");
const api_1 = require("./api");
const config_1 = require("./config");
const resource_1 = require("./resource");
const spec_1 = require("./spec");
/**
 * Create or replace a Kubernetes resource using the provided spec.
 * This implementation uses read, patch, and create, but may switch to
 * [server-side
 * apply](https://github.com/kubernetes/enhancements/issues/555) when
 * it is available.
 *
 * @param spec Kubernetes resource spec sufficient to identify and create the resource
 * @return response from the Kubernetes API.
 */
async function applySpec(spec) {
    const slug = spec_1.specSlug(spec);
    let client;
    try {
        const kc = config_1.loadKubeConfig();
        client = kc.makeApiClient(api_1.K8sObjectApi);
    }
    catch (e) {
        e.message = `Failed to create Kubernetes client: ${error_1.k8sErrMsg(e)}`;
        throw e;
    }
    try {
        await client.read(spec);
    }
    catch (e) {
        logger_1.logger.debug(`Failed to read resource ${slug}: ${error_1.k8sErrMsg(e)}`);
        logger_1.logger.info(`Creating resource ${slug} using '${resource_1.logObject(spec)}'`);
        return retry_1.logRetry(() => client.create(spec), `create resource ${slug}`);
    }
    logger_1.logger.info(`Patching resource ${slug} using '${resource_1.logObject(spec)}'`);
    const options = {
        headers: {
            "Content-Type": "application/merge-patch+json",
        },
    };
    return retry_1.logRetry(() => client.patch(spec, options), `patch resource ${slug}`);
}
exports.applySpec = applySpec;
//# sourceMappingURL=apply.js.map