"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
const logger_1 = require("../../../logger");
const fs_1 = require("../../../util/fs");
const regex_1 = require("../../../util/regex");
const git_tags_1 = require("../../datasource/git-tags");
const github_tags_1 = require("../../datasource/github-tags");
const hex_1 = require("../../datasource/hex");
const depSectionRegExp = (0, regex_1.regEx)(/defp\s+deps.*do/g);
const depMatchRegExp = (0, regex_1.regEx)(/{:(?<app>\w+)(\s*,\s*"(?<requirement>[^"]+)")?(\s*,\s*(?<opts>[^}]+))?}/gm);
const gitRegexp = (0, regex_1.regEx)(/git:\s*"(?<value>[^"]+)"/);
const githubRegexp = (0, regex_1.regEx)(/github:\s*"(?<value>[^"]+)"/);
const refRegexp = (0, regex_1.regEx)(/ref:\s*"(?<value>[^"]+)"/);
const branchOrTagRegexp = (0, regex_1.regEx)(/(?:branch|tag):\s*"(?<value>[^"]+)"/);
const organizationRegexp = (0, regex_1.regEx)(/organization:\s*"(?<value>[^"]+)"/);
const commentMatchRegExp = (0, regex_1.regEx)(/#.*$/);
const lockedVersionRegExp = (0, regex_1.regEx)(/^\s+"(?<app>\w+)".*?"(?<lockedVersion>\d+\.\d+\.\d+)"/);
async function extractPackageFile(content, packageFile) {
    logger_1.logger.trace(`mix.extractPackageFile(${packageFile})`);
    const deps = new Map();
    const contentArr = content
        .split(regex_1.newlineRegex)
        .map((line) => line.replace(commentMatchRegExp, ''));
    for (let lineNumber = 0; lineNumber < contentArr.length; lineNumber += 1) {
        if (contentArr[lineNumber].match(depSectionRegExp)) {
            let depBuffer = '';
            do {
                depBuffer += contentArr[lineNumber] + '\n';
                lineNumber += 1;
            } while (contentArr[lineNumber].trim() !== 'end');
            let depMatchGroups = depMatchRegExp.exec(depBuffer)?.groups;
            while (depMatchGroups) {
                const { app, requirement, opts } = depMatchGroups;
                const github = githubRegexp.exec(opts)?.groups?.value;
                const git = gitRegexp.exec(opts)?.groups?.value;
                const ref = refRegexp.exec(opts)?.groups?.value;
                const branchOrTag = branchOrTagRegexp.exec(opts)?.groups?.value;
                const organization = organizationRegexp.exec(opts)?.groups?.value;
                let dep;
                if (git ?? github) {
                    dep = {
                        depName: app,
                        currentDigest: ref,
                        currentValue: branchOrTag,
                        datasource: git ? git_tags_1.GitTagsDatasource.id : github_tags_1.GithubTagsDatasource.id,
                        packageName: git ?? github,
                    };
                }
                else {
                    dep = {
                        depName: app,
                        currentValue: requirement,
                        datasource: hex_1.HexDatasource.id,
                        packageName: organization ? `${app}:${organization}` : app,
                    };
                    if (requirement?.startsWith('==')) {
                        dep.currentVersion = requirement.replace((0, regex_1.regEx)(/^==\s*/), '');
                    }
                }
                deps.set(app, dep);
                logger_1.logger.trace({ dep }, `setting ${app}`);
                depMatchGroups = depMatchRegExp.exec(depBuffer)?.groups;
            }
        }
    }
    const lockFileName = (await (0, fs_1.findLocalSiblingOrParent)(packageFile, 'mix.lock')) ?? 'mix.lock';
    const lockFileContent = await (0, fs_1.readLocalFile)(lockFileName, 'utf8');
    if (lockFileContent) {
        const lockFileLines = lockFileContent.split(regex_1.newlineRegex).slice(1, -1);
        for (const line of lockFileLines) {
            const groups = lockedVersionRegExp.exec(line)?.groups;
            if (groups?.app && groups?.lockedVersion) {
                const dep = deps.get(groups.app);
                if (!dep) {
                    continue;
                }
                dep.lockedVersion = groups.lockedVersion;
                logger_1.logger.trace(`Found ${groups.lockedVersion} for ${groups.app}`);
            }
        }
    }
    const depsArray = Array.from(deps.values());
    if (depsArray.length === 0) {
        return null;
    }
    return {
        deps: depsArray,
        lockFiles: lockFileContent ? [lockFileName] : undefined,
    };
}
//# sourceMappingURL=extract.js.map