"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 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 regex_1 = require("../../../util/regex");
const extract_1 = require("./extract");
/**
 * Create a RegExp that matches the first dependency pattern for
 * the named dependency that is followed by package hashes.
 *
 * The regular expression defines a single named group `depConstraint`
 * that holds the dependency constraint without the hash specifiers.
 * The substring matched by this named group will start with the dependency
 * name and end with a non-whitespace character.
 *
 * @param depName the name of the dependency
 */
function dependencyAndHashPattern(depName) {
    const escapedDepName = (0, regex_1.escapeRegExp)(depName);
    // extrasPattern covers any whitespace between the dep name and the optional extras specifier,
    // but it does not cover any whitespace in front of the equal signs.
    //
    // Use a non-greedy wildcard for the range pattern; otherwise, we would
    // include all but the last hash specifier into depConstraint.
    return (0, regex_1.regEx)(`^\\s*(?<depConstraint>${escapedDepName}${extract_1.extrasPattern}\\s*==.*?\\S)\\s+--hash=`, 'm');
}
async function updateArtifacts({ packageFileName, updatedDeps, newPackageFileContent, config, }) {
    logger_1.logger.debug(`pip_requirements.updateArtifacts(${packageFileName})`);
    if (!is_1.default.nonEmptyArray(updatedDeps)) {
        logger_1.logger.debug('No updated pip_requirements deps - returning null');
        return null;
    }
    try {
        const cmd = [];
        const rewrittenContent = newPackageFileContent.replace((0, regex_1.regEx)(/\\\n/g), '');
        for (const dep of updatedDeps) {
            if (!dep.depName) {
                continue;
            }
            const depAndHashMatch = dependencyAndHashPattern(dep.depName).exec(rewrittenContent);
            if (depAndHashMatch) {
                // If there's a match, then the regular expression guarantees
                // that the named subgroup deepConstraint did match as well.
                const depConstraint = depAndHashMatch.groups.depConstraint;
                cmd.push(`hashin ${(0, shlex_1.quote)(depConstraint)} -r ${(0, shlex_1.quote)(packageFileName)}`);
            }
        }
        if (!cmd.length) {
            logger_1.logger.debug('No hashin commands to run - returning');
            return null;
        }
        const execOptions = {
            cwdFile: '.',
            docker: {},
            userConfiguredEnv: config.env,
            toolConstraints: [
                { toolName: 'python', constraint: config.constraints?.python },
                { toolName: 'hashin', constraint: config.constraints?.hashin },
            ],
            extraEnv: {
                PIP_CACHE_DIR: await (0, fs_1.ensureCacheDir)('pip'),
            },
        };
        await (0, exec_1.exec)(cmd, execOptions);
        const newContent = await (0, fs_1.readLocalFile)(packageFileName, 'utf8');
        if (newContent === newPackageFileContent) {
            logger_1.logger.debug(`${packageFileName} is unchanged`);
            return null;
        }
        logger_1.logger.debug(`Returning updated ${packageFileName}`);
        return [
            {
                file: {
                    type: 'addition',
                    path: packageFileName,
                    contents: newContent,
                },
            },
        ];
    }
    catch (err) {
        // istanbul ignore if
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.debug({ err }, `Failed to update ${packageFileName} file`);
        return [
            {
                artifactError: {
                    lockFile: packageFileName,
                    stderr: `${String(err.stdout)}\n${String(err.stderr)}`,
                },
            },
        ];
    }
}
//# sourceMappingURL=artifacts.js.map