"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const shlex_1 = require("shlex");
const error_messages_1 = require("../../../constants/error-messages");
const logger_1 = require("../../../logger");
const exec_1 = require("../../../util/exec");
const fs_1 = require("../../../util/fs");
const git_1 = require("../../../util/git");
async function updateArtifacts({ packageFileName, updatedDeps, newPackageFileContent, config, }) {
    logger_1.logger.trace(`helmfile.updateArtifacts(${packageFileName})`);
    const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
    if (!isLockFileMaintenance &&
        (updatedDeps === undefined || updatedDeps.length < 1)) {
        logger_1.logger.debug('No updated helmfile deps - returning null');
        return null;
    }
    const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'helmfile.lock');
    const existingLockFileContent = await (0, git_1.getFile)(lockFileName);
    if (is_1.default.falsy(existingLockFileContent)) {
        logger_1.logger.debug('No helmfile.lock found');
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(packageFileName, newPackageFileContent);
        const execOptions = {
            docker: {},
            extraEnv: {},
            toolConstraints: [
                {
                    toolName: 'helm',
                    constraint: config.constraints?.helm,
                },
                {
                    toolName: 'helmfile',
                    constraint: config.constraints?.helmfile,
                },
            ],
        };
        await (0, exec_1.exec)(`helmfile deps -f ${(0, shlex_1.quote)(packageFileName)}`, execOptions);
        const newHelmLockContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
        if (existingLockFileContent === newHelmLockContent) {
            logger_1.logger.debug('helmfile.lock is unchanged');
            return null;
        }
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: newHelmLockContent,
                },
            },
        ];
    }
    catch (err) {
        // istanbul ignore if
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.debug({ err }, 'Failed to update Helmfile lock file');
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
exports.updateArtifacts = updateArtifacts;
//# sourceMappingURL=artifacts.js.map