"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 upath_1 = tslib_1.__importDefault(require("upath"));
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");
function constructPipCompileCmd(content, outputFileName, haveCredentials) {
    const headerArguments = (0, common_1.extractHeaderCommand)(content, outputFileName);
    if (headerArguments.isCustomCommand) {
        throw new Error('Detected custom command, header modified or set by CUSTOM_COMPILE_COMMAND');
    }
    if (headerArguments.outputFile) {
        // TODO(not7cd): This file path can be relative like `reqs/main.txt`
        const file = upath_1.default.parse(outputFileName).base;
        if (headerArguments.outputFile !== file) {
            // we don't trust the user-supplied output-file argument;
            // TODO(not7cd): allow relative paths
            logger_1.logger.warn({ outputFile: headerArguments.outputFile, actualPath: file }, 'pip-compile was previously executed with an unexpected `--output-file` filename');
            // TODO(not7cd): this shouldn't be changed in extract function
            headerArguments.outputFile = file;
            headerArguments.argv.forEach((item, i) => {
                if (item.startsWith('--output-file=')) {
                    headerArguments.argv[i] = `--output-file=${(0, shlex_1.quote)(file)}`;
                }
            });
        }
    }
    else {
        logger_1.logger.debug(`pip-compile: implicit output file (${outputFileName})`);
    }
    // safeguard against index url leak if not explicitly set by an option
    if ((!headerArguments.noEmitIndexUrl && !headerArguments.emitIndexUrl) ||
        (!headerArguments.noEmitIndexUrl && haveCredentials)) {
        headerArguments.argv.splice(1, 0, '--no-emit-index-url');
    }
    return headerArguments.argv.map(shlex_1.quote).join(' ');
}
exports.constructPipCompileCmd = constructPipCompileCmd;
async function updateArtifacts({ packageFileName: inputFileName, newPackageFileContent: newInputContent, 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 packageFile = pipRequirements.extractPackageFile(newInputContent);
            const registryUrlVars = (0, common_1.getRegistryUrlVarsFromPackageFile)(packageFile);
            const cmd = constructPipCompileCmd(existingOutput, outputFileName, registryUrlVars.haveCredentials);
            const execOptions = await (0, common_1.getExecOptions)(config, inputFileName, registryUrlVars.environmentVars);
            logger_1.logger.trace({ 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