"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
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 github_releases_1 = require("../../datasource/github-releases");
const schema_1 = require("./schema");
async function extractPackageFile(content, packageFile) {
    logger_1.logger.trace(`poetry.extractPackageFile(${packageFile})`);
    const { val: res, err } = result_1.Result.parse(content, schema_1.PoetrySchemaToml.transform(({ packageFileContent }) => packageFileContent)).unwrap();
    if (err) {
        logger_1.logger.debug({ packageFile, err }, `Poetry: error parsing pyproject.toml`);
        return null;
    }
    const lockfileName = (0, fs_1.getSiblingFileName)(packageFile, 'poetry.lock');
    const lockContents = (await (0, fs_1.readLocalFile)(lockfileName, 'utf8'));
    const lockfileMapping = result_1.Result.parse(lockContents, schema_1.Lockfile.transform(({ lock }) => lock)).unwrapOrElse({});
    let pythonVersion;
    (0, filter_map_1.filterMap)(res.deps, (dep) => {
        if (dep.depName === 'python') {
            if (dep.currentValue) {
                pythonVersion = dep.currentValue;
            }
            return {
                ...dep,
                // We use containerbase python as source, as there are a lot docker tags which can cause
                // issues with poetry versioning.
                packageName: 'containerbase/python-prebuild',
                datasource: github_releases_1.GithubReleasesDatasource.id,
                commitMessageTopic: 'Python',
                registryUrls: null,
            };
        }
        const packageName = dep.packageName ?? dep.depName;
        if (packageName && packageName in lockfileMapping) {
            dep.lockedVersion = lockfileMapping[packageName];
        }
        return dep;
    });
    if (!res.deps.length) {
        return null;
    }
    const extractedConstraints = {};
    if (is_1.default.nonEmptyString(pythonVersion)) {
        extractedConstraints.python = pythonVersion;
    }
    res.extractedConstraints = 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;
}
//# sourceMappingURL=extract.js.map