"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = exports.addExtraEnvVariable = exports.extractEnvironmentVariableName = exports.getMatchingHostRule = exports.getPipenvConstraint = exports.getPythonConstraint = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const semver_1 = tslib_1.__importDefault(require("semver"));
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 host_rules_1 = require("../../../util/host-rules");
const regex_1 = require("../../../util/regex");
const url_1 = require("../../../util/url");
const pypi_1 = require("../../datasource/pypi");
const extract_1 = require("./extract");
const schema_1 = require("./schema");
function getPythonConstraint(existingLockFileContent, config) {
    const { constraints = {} } = config;
    const { python } = constraints;
    if (python) {
        logger_1.logger.debug('Using python constraint from config');
        return python;
    }
    try {
        const result = schema_1.PipfileLockSchema.safeParse(existingLockFileContent);
        // istanbul ignore if: not easily testable
        if (!result.success) {
            logger_1.logger.warn({ error: result.error }, 'Invalid Pipfile.lock');
            return undefined;
        }
        // Exact python version has been included since 2022.10.9. It is more specific than the major.minor version
        // https://github.com/pypa/pipenv/blob/main/CHANGELOG.md#2022109-2022-10-09
        if (result.data._meta?.requires?.python_full_version) {
            const pythonFullVersion = result.data._meta.requires.python_full_version;
            return `== ${pythonFullVersion}`;
        }
        // Before 2022.10.9, only the major.minor version was included
        if (result.data._meta?.requires?.python_version) {
            const pythonVersion = result.data._meta.requires.python_version;
            return `== ${pythonVersion}.*`;
        }
    }
    catch (err) {
        // Do nothing
    }
    return undefined;
}
exports.getPythonConstraint = getPythonConstraint;
function getPipenvConstraint(existingLockFileContent, config) {
    const { constraints = {} } = config;
    const { pipenv } = constraints;
    if (pipenv) {
        logger_1.logger.debug('Using pipenv constraint from config');
        return pipenv;
    }
    try {
        const result = schema_1.PipfileLockSchema.safeParse(existingLockFileContent);
        // istanbul ignore if: not easily testable
        if (!result.success) {
            logger_1.logger.warn({ error: result.error }, 'Invalid Pipfile.lock');
            return '';
        }
        if (result.data.default?.pipenv?.version) {
            return result.data.default.pipenv.version;
        }
        if (result.data.develop?.pipenv?.version) {
            return result.data.develop.pipenv.version;
        }
        // Exact python version has been included since 2022.10.9
        const pythonFullVersion = result.data._meta?.requires?.python_full_version;
        if (is_1.default.string(pythonFullVersion) && semver_1.default.valid(pythonFullVersion)) {
            // python_full_version was added after 3.6 was already deprecated, so it should be impossible to have a 3.6 version
            // https://github.com/pypa/pipenv/blob/main/CHANGELOG.md#2022109-2022-10-09
            if (semver_1.default.satisfies(pythonFullVersion, '3.7.*')) {
                // Python 3.7 support was dropped in pipenv 2023.10.20
                // https://github.com/pypa/pipenv/blob/main/CHANGELOG.md#20231020-2023-10-20
                return '< 2023.10.20';
            }
            // Future deprecations will go here
        }
        // Before 2022.10.9, only the major.minor version was included
        const pythonVersion = result.data._meta?.requires?.python_version;
        if (pythonVersion) {
            if (pythonVersion === '3.6') {
                // Python 3.6 was deprecated in 2022.4.20
                // https://github.com/pypa/pipenv/blob/main/CHANGELOG.md#2022420-2022-04-20
                return '< 2022.4.20';
            }
            if (pythonVersion === '3.7') {
                // Python 3.7 was deprecated in 2023.10.20 but we shouldn't reach here unless we are < 2022.10.9
                // https://github.com/pypa/pipenv/blob/main/CHANGELOG.md#20231020-2023-10-20
                return '< 2022.10.9';
            }
        }
    }
    catch (err) {
        // Do nothing
    }
    return '';
}
exports.getPipenvConstraint = getPipenvConstraint;
function getMatchingHostRule(url) {
    const parsedUrl = (0, url_1.parseUrl)(url);
    if (parsedUrl) {
        parsedUrl.username = '';
        parsedUrl.password = '';
        const urlWithoutCredentials = parsedUrl.toString();
        return (0, host_rules_1.find)({ hostType: pypi_1.PypiDatasource.id, url: urlWithoutCredentials });
    }
    return null;
}
exports.getMatchingHostRule = getMatchingHostRule;
async function findPipfileSourceUrlsWithCredentials(pipfileContent, pipfileName) {
    const pipfile = await (0, extract_1.extractPackageFile)(pipfileContent, pipfileName);
    return (pipfile?.registryUrls
        ?.map(url_1.parseUrl)
        .filter(is_1.default.urlInstance)
        .filter((url) => is_1.default.nonEmptyStringAndNotWhitespace(url.username)) ?? []);
}
/**
 * This will extract the actual variable name from an environment-placeholder:
 * ${USERNAME:-defaultvalue} will yield 'USERNAME'
 */
function extractEnvironmentVariableName(credential) {
    const match = (0, regex_1.regEx)('([a-z0-9_]+)', 'i').exec(decodeURI(credential));
    return match?.length ? match[0] : null;
}
exports.extractEnvironmentVariableName = extractEnvironmentVariableName;
function addExtraEnvVariable(extraEnv, environmentVariableName, environmentValue) {
    logger_1.logger.trace(`Adding ${environmentVariableName} environment variable for pipenv`);
    if (extraEnv[environmentVariableName] &&
        extraEnv[environmentVariableName] !== environmentValue) {
        logger_1.logger.warn(`Possible misconfiguration, ${environmentVariableName} is already set to a different value`);
    }
    extraEnv[environmentVariableName] = environmentValue;
}
exports.addExtraEnvVariable = addExtraEnvVariable;
/**
 * Pipenv allows configuring source-urls for remote repositories with placeholders for credentials, i.e. http://$USER:$PASS@myprivate.repo
 * if a matching host rule exists for that repository, we need to set the corresponding variables.
 * Simply substituting them in the URL is not an option as it would impact the hash for the resulting Pipfile.lock
 *
 */
async function addCredentialsForSourceUrls(newPipfileContent, pipfileName, extraEnv) {
    const sourceUrls = await findPipfileSourceUrlsWithCredentials(newPipfileContent, pipfileName);
    for (const parsedSourceUrl of sourceUrls) {
        logger_1.logger.trace(`Trying to add credentials for ${parsedSourceUrl.toString()}`);
        const matchingHostRule = getMatchingHostRule(parsedSourceUrl.toString());
        if (matchingHostRule) {
            const usernameVariableName = extractEnvironmentVariableName(parsedSourceUrl.username);
            if (matchingHostRule.username && usernameVariableName) {
                addExtraEnvVariable(extraEnv, usernameVariableName, matchingHostRule.username);
            }
            const passwordVariableName = extractEnvironmentVariableName(parsedSourceUrl.password);
            if (matchingHostRule.password && passwordVariableName) {
                addExtraEnvVariable(extraEnv, passwordVariableName, matchingHostRule.password);
            }
        }
    }
}
async function updateArtifacts({ packageFileName: pipfileName, newPackageFileContent: newPipfileContent, config, }) {
    logger_1.logger.debug(`pipenv.updateArtifacts(${pipfileName})`);
    const lockFileName = pipfileName + '.lock';
    const existingLockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (!existingLockFileContent) {
        logger_1.logger.debug('No Pipfile.lock found');
        return null;
    }
    try {
        await (0, fs_1.writeLocalFile)(pipfileName, newPipfileContent);
        if (config.isLockFileMaintenance) {
            await (0, fs_1.deleteLocalFile)(lockFileName);
        }
        const cmd = 'pipenv lock';
        const tagConstraint = getPythonConstraint(existingLockFileContent, config);
        const pipenvConstraint = getPipenvConstraint(existingLockFileContent, config);
        const extraEnv = {
            PIPENV_CACHE_DIR: await (0, fs_1.ensureCacheDir)('pipenv'),
            PIP_CACHE_DIR: await (0, fs_1.ensureCacheDir)('pip'),
            WORKON_HOME: await (0, fs_1.ensureCacheDir)('virtualenvs'),
        };
        const execOptions = {
            cwdFile: pipfileName,
            docker: {},
            userConfiguredEnv: config.env,
            toolConstraints: [
                {
                    toolName: 'python',
                    constraint: tagConstraint,
                },
                {
                    toolName: 'pipenv',
                    constraint: pipenvConstraint,
                },
            ],
        };
        await addCredentialsForSourceUrls(newPipfileContent, pipfileName, extraEnv);
        execOptions.extraEnv = extraEnv;
        logger_1.logger.trace({ cmd }, 'pipenv lock command');
        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 Pipfile.lock');
        return [
            {
                file: {
                    type: 'addition',
                    path: lockFileName,
                    contents: await (0, fs_1.readLocalFile)(lockFileName, 'utf8'),
                },
            },
        ];
    }
    catch (err) {
        // istanbul ignore if
        if (err.message === error_messages_1.TEMPORARY_ERROR) {
            throw err;
        }
        logger_1.logger.debug({ err }, 'Failed to update Pipfile.lock');
        return [
            {
                artifactError: {
                    lockFile: lockFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
exports.updateArtifacts = updateArtifacts;
//# sourceMappingURL=artifacts.js.map