"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../logger");
const filter_map_1 = require("../../../util/filter-map");
const fs_1 = require("../../../util/fs");
const result_1 = require("../../../util/result");
const schema_1 = require("./schema");
function extractFromDependenciesSection(parsedFile, section, poetryLockfile) {
    return extractFromSection(parsedFile?.tool?.poetry?.[section], section, poetryLockfile);
}
function extractFromDependenciesGroupSection(groupSections, poetryLockfile) {
    if (!groupSections) {
        return [];
    }
    const deps = [];
    for (const groupName of Object.keys(groupSections)) {
        deps.push(...extractFromSection(groupSections[groupName]?.dependencies, groupName, poetryLockfile));
    }
    return deps;
}
function extractFromSection(sectionContent, depType, poetryLockfile) {
    if (!sectionContent) {
        return [];
    }
    return (0, filter_map_1.filterMap)(Object.values(sectionContent), (dep) => {
        if (dep.depName === 'python' || dep.depName === 'source') {
            return null;
        }
        dep.depType = depType;
        const packageName = dep.packageName ?? dep.depName;
        if (packageName && packageName in poetryLockfile) {
            dep.lockedVersion = poetryLockfile[packageName];
        }
        return dep;
    });
}
function extractRegistries(pyprojectfile) {
    const sources = pyprojectfile?.tool?.poetry?.source;
    if (!Array.isArray(sources) || sources.length === 0) {
        return undefined;
    }
    const registryUrls = new Set();
    for (const source of sources) {
        if (source.url) {
            registryUrls.add(source.url);
        }
    }
    registryUrls.add(process.env.PIP_INDEX_URL ?? 'https://pypi.org/pypi/');
    return Array.from(registryUrls);
}
async function extractPackageFile(content, packageFile) {
    logger_1.logger.trace(`poetry.extractPackageFile(${packageFile})`);
    const { val: pyprojectfile, err } = result_1.Result.parse(content, schema_1.PoetrySchemaToml).unwrap();
    if (err) {
        logger_1.logger.debug({ packageFile, err }, `Poetry: error parsing pyproject.toml`);
        return null;
    }
    // handle the lockfile
    const lockfileName = (0, fs_1.getSiblingFileName)(packageFile, 'poetry.lock');
    // TODO #22198
    const lockContents = (await (0, fs_1.readLocalFile)(lockfileName, 'utf8'));
    const lockfileMapping = result_1.Result.parse(lockContents, schema_1.Lockfile.transform(({ lock }) => lock)).unwrapOrElse({});
    const deps = [
        ...extractFromDependenciesSection(pyprojectfile, 'dependencies', lockfileMapping),
        ...extractFromDependenciesSection(pyprojectfile, 'dev-dependencies', lockfileMapping),
        ...extractFromDependenciesSection(pyprojectfile, 'extras', lockfileMapping),
        ...extractFromDependenciesGroupSection(pyprojectfile?.tool?.poetry?.group, lockfileMapping),
    ];
    if (!deps.length) {
        return null;
    }
    const extractedConstraints = {};
    const pythonVersion = pyprojectfile?.tool?.poetry?.dependencies?.python?.currentValue;
    if (is_1.default.nonEmptyString(pythonVersion)) {
        extractedConstraints.python = pythonVersion;
    }
    const res = {
        deps,
        registryUrls: extractRegistries(pyprojectfile),
        extractedConstraints,
    };
    // Try poetry.lock first
    let lockFile = (0, fs_1.getSiblingFileName)(packageFile, 'poetry.lock');
    // istanbul ignore next
    if (await (0, fs_1.localPathExists)(lockFile)) {
        res.lockFiles = [lockFile];
    }
    else {
        // Try pyproject.lock next
        lockFile = (0, fs_1.getSiblingFileName)(packageFile, 'pyproject.lock');
        if (await (0, fs_1.localPathExists)(lockFile)) {
            res.lockFiles = [lockFile];
        }
    }
    return res;
}
exports.extractPackageFile = extractPackageFile;
//# sourceMappingURL=extract.js.map