"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFileFlags = extractPackageFileFlags;
const global_1 = require("../../../config/global");
const regex_1 = require("../../../util/regex");
function cleanRegistryUrls(registryUrls) {
    return registryUrls.map((url) => {
        // handle the optional quotes in eg. `--extra-index-url "https://foo.bar"`
        const cleaned = url.replace((0, regex_1.regEx)(/^"/), '').replace((0, regex_1.regEx)(/"$/), '');
        if (!global_1.GlobalConfig.get('exposeAllEnv')) {
            return cleaned;
        }
        // interpolate any environment variables
        return cleaned.replace((0, regex_1.regEx)(/(\$[A-Za-z\d_]+)|(\${[A-Za-z\d_]+})/g), (match) => {
            const envvar = match
                .substring(1)
                .replace((0, regex_1.regEx)(/^{/), '')
                .replace((0, regex_1.regEx)(/}$/), '');
            const sub = process.env[envvar];
            return sub ?? match;
        });
    });
}
function extractPackageFileFlags(content) {
    let registryUrls = [];
    const additionalRegistryUrls = [];
    const additionalRequirementsFiles = [];
    const additionalConstraintsFiles = [];
    content.split(regex_1.newlineRegex).forEach((line) => {
        if (line.startsWith('-i ') || line.startsWith('--index-url ')) {
            registryUrls = [line.split(' ')[1]];
        }
        else if (line.startsWith('--extra-index-url ')) {
            const extraUrl = line
                .substring('--extra-index-url '.length)
                .split(' ')[0];
            additionalRegistryUrls.push(extraUrl);
        }
        else if (line.startsWith('-r ')) {
            additionalRequirementsFiles.push(line.split(' ')[1]);
        }
        else if (line.startsWith('-c ')) {
            additionalConstraintsFiles.push(line.split(' ')[1]);
        }
    });
    const res = { deps: [] };
    if (registryUrls.length > 0) {
        res.registryUrls = cleanRegistryUrls(registryUrls);
    }
    if (additionalRegistryUrls.length) {
        res.additionalRegistryUrls = cleanRegistryUrls(additionalRegistryUrls);
    }
    if (additionalRequirementsFiles.length) {
        if (!res.managerData) {
            res.managerData = {};
        }
        res.managerData.requirementsFiles = additionalRequirementsFiles;
    }
    if (additionalConstraintsFiles.length) {
        if (!res.managerData) {
            res.managerData = {};
        }
        res.managerData.constraintsFiles = additionalConstraintsFiles;
    }
    return res;
}
//# sourceMappingURL=common.js.map