"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 logger_1 = require("../../../logger");
const exec_1 = require("../../../util/exec");
const fs_1 = require("../../../util/fs");
const git_1 = require("../../../util/git");
const regex_1 = require("../../../util/regex");
async function updateArtifacts({ packageFileName, config, updatedDeps, }) {
    const lockFileName = packageFileName.replace((0, regex_1.regEx)(/\.nix$/), '.lock');
    const existingLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (!existingLockFileContent) {
        logger_1.logger.debug('No flake.lock found');
        return null;
    }
    let cmd;
    if (config.isLockFileMaintenance) {
        cmd = `nix \
    --extra-experimental-features nix-command \
    --extra-experimental-features flakes \
    flake update`;
    }
    else {
        const inputs = updatedDeps
            .map(({ depName }) => depName)
            .filter(is_1.default.nonEmptyStringAndNotWhitespace)
            .map((depName) => `--update-input ${(0, shlex_1.quote)(depName)}`)
            .join(' ');
        cmd = `nix \
    --extra-experimental-features nix-command \
    --extra-experimental-features flakes \
    flake lock ${inputs}`;
    }
    const execOptions = {
        cwdFile: packageFileName,
        toolConstraints: [
            {
                toolName: 'nix',
                constraint: config.constraints?.nix,
            },
        ],
        docker: {},
    };
    try {
        await (0, exec_1.exec)(cmd, execOptions);
        const status = await (0, git_1.getRepoStatus)();
        if (!status.modified.includes(lockFileName)) {
            return null;
        }
        logger_1.logger.debug('Returning updated flake.lock');
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: await (0, fs_1.readLocalFile)(lockFileName),
                },
            },
        ];
    }
    catch (err) {
        logger_1.logger.warn({ err }, 'Error updating flake.lock');
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
exports.updateArtifacts = updateArtifacts;
//# sourceMappingURL=artifacts.js.map