"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = void 0;
const tslib_1 = require("tslib");
const minimatch_1 = require("minimatch");
const upath_1 = tslib_1.__importDefault(require("upath"));
const logger_1 = require("../../../logger");
const fs_1 = require("../../../util/fs");
const regex_1 = require("../../../util/regex");
const hermit_1 = require("../../datasource/hermit");
const pkgReferenceRegex = (0, regex_1.regEx)(`(?<packageName>.*?)-(?<version>[0-9]{1}.*)`);
/**
 * extractPackageFile scans the folder of the package files
 * and looking for .{packageName}-{version}.pkg
 */
async function extractPackageFile(content, filename) {
    logger_1.logger.trace('hermit.extractPackageFile()');
    const dependencies = [];
    const packages = await listHermitPackages(filename);
    if (!packages?.length) {
        return null;
    }
    for (const p of packages) {
        // version of a hermit package is either a Version or a Channel
        // Channel will prepend with @ to distinguish from normal version
        const version = p.Version === '' ? `@${p.Channel}` : p.Version;
        const dep = {
            datasource: hermit_1.HermitDatasource.id,
            depName: p.Name,
            currentValue: version,
        };
        dependencies.push(dep);
    }
    return { deps: dependencies };
}
exports.extractPackageFile = extractPackageFile;
/**
 * listHermitPackages will fetch all installed packages from the bin folder
 */
async function listHermitPackages(hermitFile) {
    logger_1.logger.trace('hermit.listHermitPackages()');
    const hermitFolder = upath_1.default.dirname(hermitFile);
    let files = [];
    try {
        files = await (0, fs_1.readLocalDirectory)(hermitFolder);
    }
    catch (e) {
        logger_1.logger.debug({ hermitFolder, err: e }, 'error listing hermit package references');
        return null;
    }
    logger_1.logger.trace({ files, hermitFolder }, 'files for hermit package list');
    const out = [];
    for (const f of files) {
        if (!(0, minimatch_1.minimatch)(f, '.*.pkg')) {
            continue;
        }
        const fileName = f
            .replace(`${hermitFolder}/`, '')
            .substring(1)
            .replace(/\.pkg$/, '');
        const channelParts = fileName.split('@');
        if (channelParts.length > 1) {
            out.push({
                Name: channelParts[0],
                Channel: channelParts[1],
                Version: '',
            });
        }
        const groups = pkgReferenceRegex.exec(fileName)?.groups;
        if (!groups) {
            logger_1.logger.debug({ fileName }, 'invalid hermit package reference file name found');
            continue;
        }
        out.push({
            Name: groups.packageName,
            Version: groups.version,
            Channel: '',
        });
    }
    return out;
}
//# sourceMappingURL=extract.js.map