"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = exports.constructPipCompileCmd = void 0;
const tslib_1 = require("tslib");
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");
const pipRequirements = tslib_1.__importStar(require("../pip_requirements"));
const common_1 = require("./common");
const utils_1 = require("./utils");
function constructPipCompileCmd(compileArgs, haveCredentials, upgradePackages = []) {
    if (compileArgs.isCustomCommand) {
        throw new Error('Detected custom command, header modified or set by CUSTOM_COMPILE_COMMAND');
    }
    if (!compileArgs.outputFile) {
        logger_1.logger.debug(`pip-compile: implicit output file`);
    }
    // safeguard against index url leak if not explicitly set by an option
    if ((!compileArgs.noEmitIndexUrl && !compileArgs.emitIndexUrl) ||
        (!compileArgs.noEmitIndexUrl && haveCredentials)) {
        compileArgs.argv.splice(1, 0, '--no-emit-index-url');
    }
    for (const dep of upgradePackages) {
        compileArgs.argv.push(`--upgrade-package=${(0, shlex_1.quote)(dep.depName + '==' + dep.newVersion)}`);
    }
    return compileArgs.argv.map(shlex_1.quote).join(' ');
}
exports.constructPipCompileCmd = constructPipCompileCmd;
async function updateArtifacts({ packageFileName: inputFileName, newPackageFileContent: newInputContent, updatedDeps, config, }) {
    if (!config.lockFiles) {
        logger_1.logger.warn({ packageFileName: inputFileName }, 'pip-compile: No lock files associated with a package file');
        return null;
    }
    logger_1.logger.debug(`pipCompile.updateArtifacts(${inputFileName}->${JSON.stringify(config.lockFiles)})`);
    const result = [];
    for (const outputFileName of config.lockFiles) {
        const existingOutput = await (0, fs_1.readLocalFile)(outputFileName, 'utf8');
        if (!existingOutput) {
            logger_1.logger.debug('pip-compile: No output file found');
            return null;
        }
        try {
            await (0, fs_1.writeLocalFile)(inputFileName, newInputContent);
            // TODO(not7cd): use --upgrade option instead deleting
            if (config.isLockFileMaintenance) {
                await (0, fs_1.deleteLocalFile)(outputFileName);
            }
            const compileArgs = (0, common_1.extractHeaderCommand)(existingOutput, outputFileName);
            const cwd = (0, utils_1.inferCommandExecDir)(outputFileName, compileArgs.outputFile);
            const upgradePackages = updatedDeps.filter((dep) => dep.isLockfileUpdate);
            const packageFile = pipRequirements.extractPackageFile(newInputContent);
            const registryUrlVars = (0, common_1.getRegistryUrlVarsFromPackageFile)(packageFile);
            const cmd = constructPipCompileCmd(compileArgs, registryUrlVars.haveCredentials, upgradePackages);
            const execOptions = await (0, common_1.getExecOptions)(config, cwd, registryUrlVars.environmentVars);
            logger_1.logger.trace({ cwd, cmd }, 'pip-compile command');
            logger_1.logger.trace({ env: execOptions.extraEnv }, 'pip-compile extra env vars');
            await (0, exec_1.exec)(cmd, execOptions);
            const status = await (0, git_1.getRepoStatus)();
            if (!status?.modified.includes(outputFileName)) {
                return null;
            }
            result.push({
                file: {
                    type: 'addition',
                    path: outputFileName,
                    contents: await (0, fs_1.readLocalFile)(outputFileName, 'utf8'),
                },
            });
        }
        catch (err) {
            // istanbul ignore if
            if (err.message === error_messages_1.TEMPORARY_ERROR) {
                throw err;
            }
            logger_1.logger.debug({ err }, 'pip-compile: Failed to run command');
            result.push({
                artifactError: {
                    lockFile: outputFileName,
                    stderr: err.message,
                },
            });
        }
    }
    logger_1.logger.debug('pip-compile: Returning updated output file(s)');
    return result;
}
exports.updateArtifacts = updateArtifacts;
//# sourceMappingURL=artifacts.js.map