"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = updateArtifacts;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
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");
async function updateArtifacts(updateArtifact) {
    const { packageFileName, updatedDeps, newPackageFileContent, config } = updateArtifact;
    logger_1.logger.debug(`gleam.updateArtifacts(${packageFileName})`);
    const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
    if (is_1.default.emptyArray(updatedDeps) && !isLockFileMaintenance) {
        logger_1.logger.debug('No updated gleam deps - returning null');
        return null;
    }
    const lockFileName = (0, fs_1.getSiblingFileName)(packageFileName, 'manifest.toml');
    const oldLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (!oldLockFileContent) {
        logger_1.logger.debug(`No ${lockFileName} found`);
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(packageFileName, newPackageFileContent);
        if (isLockFileMaintenance) {
            await (0, fs_1.deleteLocalFile)(lockFileName);
        }
        const execOptions = {
            cwdFile: packageFileName,
            docker: {},
            toolConstraints: [
                {
                    toolName: 'gleam',
                    constraint: config.constraints?.gleam,
                },
            ],
        };
        await (0, exec_1.exec)('gleam deps download', execOptions);
        const newLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
        if (!newLockFileContent) {
            logger_1.logger.debug(`No ${lockFileName} found`);
            return null;
        }
        if (oldLockFileContent === newLockFileContent) {
            logger_1.logger.debug(`No changes in ${lockFileName} content`);
            return null;
        }
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: newLockFileContent,
                },
            },
        ];
    }
    catch (err) {
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.warn({ lockfile: lockFileName, err }, `Failed to update lock file`);
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
//# sourceMappingURL=artifacts.js.map