"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractAllPackageFiles = void 0;
const tslib_1 = require("tslib");
const upath_1 = tslib_1.__importDefault(require("upath"));
const logger_1 = require("../../../logger");
const fs_1 = require("../../../util/fs");
const maven_1 = require("../../datasource/maven");
const catalog_1 = require("./extract/catalog");
const consistent_versions_plugin_1 = require("./extract/consistent-versions-plugin");
const parser_1 = require("./parser");
const common_1 = require("./parser/common");
const utils_1 = require("./utils");
const mavenDatasource = maven_1.MavenDatasource.id;
function updatePackageRegistries(packageRegistries, urls) {
    for (const url of urls) {
        const registryAlreadyKnown = packageRegistries.some((item) => item.registryUrl === url.registryUrl && item.scope === url.scope);
        if (!registryAlreadyKnown) {
            packageRegistries.push(url);
        }
    }
}
function getRegistryUrlsForDep(packageRegistries, dep) {
    const scope = dep.depType === 'plugin' ? 'plugin' : 'dep';
    const registryUrls = packageRegistries
        .filter((item) => item.scope === scope)
        .map((item) => item.registryUrl);
    if (!registryUrls.length && scope === 'plugin') {
        registryUrls.push(common_1.REGISTRY_URLS.gradlePluginPortal);
    }
    return [...new Set(registryUrls)];
}
async function parsePackageFiles(config, packageFiles, extractedDeps, packageFilesByName, packageRegistries) {
    const varRegistry = {};
    const fileContents = await (0, fs_1.getLocalFiles)(packageFiles);
    for (const packageFile of packageFiles) {
        packageFilesByName[packageFile] = {
            packageFile,
            datasource: mavenDatasource,
            deps: [],
        };
        try {
            // TODO #7154
            const content = fileContents[packageFile];
            const packageFileDir = upath_1.default.dirname((0, utils_1.toAbsolutePath)(packageFile));
            if ((0, utils_1.isPropsFile)(packageFile)) {
                const { vars, deps } = (0, parser_1.parseProps)(content, packageFile);
                (0, utils_1.updateVars)(varRegistry, packageFileDir, vars);
                extractedDeps.push(...deps);
            }
            else if ((0, utils_1.isTOMLFile)(packageFile)) {
                const deps = (0, catalog_1.parseCatalog)(packageFile, content);
                extractedDeps.push(...deps);
            }
            else if ((0, consistent_versions_plugin_1.isGcvPropsFile)(packageFile) &&
                (0, consistent_versions_plugin_1.usesGcv)(packageFile, fileContents)) {
                const deps = (0, consistent_versions_plugin_1.parseGcv)(packageFile, fileContents);
                extractedDeps.push(...deps);
            }
            else if ((0, utils_1.isGradleScriptFile)(packageFile)) {
                const vars = (0, utils_1.getVars)(varRegistry, packageFileDir);
                const { deps, urls, vars: gradleVars, } = (0, parser_1.parseGradle)(content, vars, packageFile, fileContents);
                updatePackageRegistries(packageRegistries, urls);
                (0, utils_1.updateVars)(varRegistry, packageFileDir, gradleVars);
                extractedDeps.push(...deps);
            }
        }
        catch (err) {
            logger_1.logger.warn({ err, config, packageFile }, `Failed to process Gradle file`);
        }
    }
    return extractedDeps;
}
async function extractAllPackageFiles(config, packageFiles) {
    const packageFilesByName = {};
    const packageRegistries = [];
    const extractedDeps = [];
    const gradleFiles = (0, utils_1.reorderFiles)(packageFiles);
    await parsePackageFiles(config, gradleFiles, extractedDeps, packageFilesByName, packageRegistries);
    if (!extractedDeps.length) {
        return null;
    }
    for (const dep of extractedDeps) {
        dep.fileReplacePosition = dep?.managerData?.fileReplacePosition; // #8224
        const key = dep.managerData?.packageFile;
        // istanbul ignore else
        if (key) {
            let pkgFile = packageFilesByName[key];
            // istanbul ignore if: won't happen if "apply from" processes only initially known files
            if (!pkgFile) {
                pkgFile = {
                    packageFile: key,
                    datasource: mavenDatasource,
                    deps: [],
                };
            }
            if (!dep.datasource) {
                dep.datasource = mavenDatasource;
            }
            if (dep.datasource === mavenDatasource) {
                dep.registryUrls = getRegistryUrlsForDep(packageRegistries, dep);
                if (!dep.depType) {
                    dep.depType = key.startsWith('buildSrc')
                        ? 'devDependencies'
                        : 'dependencies';
                }
            }
            const depAlreadyInPkgFile = pkgFile.deps.some((item) => item.depName === dep.depName &&
                item.managerData?.fileReplacePosition ===
                    dep.managerData?.fileReplacePosition);
            if (!depAlreadyInPkgFile) {
                pkgFile.deps.push(dep);
            }
            packageFilesByName[key] = pkgFile;
        }
        else {
            logger_1.logger.warn({ dep }, `Failed to process Gradle dependency`);
        }
    }
    return Object.values(packageFilesByName);
}
exports.extractAllPackageFiles = extractAllPackageFiles;
//# sourceMappingURL=extract.js.map