"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = void 0;
const tslib_1 = require("tslib");
const js_yaml_1 = require("js-yaml");
const logger_1 = require("../../../logger");
const regex_1 = require("../../../util/regex");
const github_tags_1 = require("../../datasource/github-tags");
const dockerVersioning = tslib_1.__importStar(require("../../versioning/docker"));
const extract_1 = require("../dockerfile/extract");
const dockerActionRe = (0, regex_1.regEx)(/^\s+uses: ['"]?docker:\/\/([^'"]+)\s*$/);
const actionRe = (0, regex_1.regEx)(/^\s+-?\s+?uses: (?<replaceString>['"]?(?<depName>[\w-]+\/[\w-]+)(?<path>\/.*)?@(?<currentValue>[^\s'"]+)['"]?(?:\s+#\s*(?:renovate\s*:\s*)?(?:pin\s+|tag\s*=\s*)?@?(?<tag>v?\d+(?:\.\d+(?:\.\d+)?)?))?)/);
// SHA1 or SHA256, see https://github.blog/2020-10-19-git-2-29-released/
const shaRe = (0, regex_1.regEx)(/^(?:[a-f0-9]{6,7}|[a-f0-9]{40}|[a-f0-9]{64})$/);
function extractWithRegex(content) {
    logger_1.logger.trace('github-actions.extractWithRegex()');
    const deps = [];
    for (const line of content.split(regex_1.newlineRegex)) {
        if (line.trim().startsWith('#')) {
            continue;
        }
        const dockerMatch = dockerActionRe.exec(line);
        if (dockerMatch) {
            const [, currentFrom] = dockerMatch;
            const dep = (0, extract_1.getDep)(currentFrom);
            dep.depType = 'docker';
            deps.push(dep);
            continue;
        }
        const tagMatch = actionRe.exec(line);
        if (tagMatch?.groups) {
            const { depName, currentValue, path = '', tag, replaceString, } = tagMatch.groups;
            let quotes = '';
            if (replaceString.indexOf("'") >= 0) {
                quotes = "'";
            }
            if (replaceString.indexOf('"') >= 0) {
                quotes = '"';
            }
            const dep = {
                depName,
                commitMessageTopic: '{{{depName}}} action',
                datasource: github_tags_1.GithubTagsDatasource.id,
                versioning: dockerVersioning.id,
                depType: 'action',
                replaceString,
                autoReplaceStringTemplate: `${quotes}{{depName}}${path}@{{#if newDigest}}{{newDigest}}${quotes}{{#if newValue}} # {{newValue}}{{/if}}{{/if}}{{#unless newDigest}}{{newValue}}${quotes}{{/unless}}`,
            };
            if (shaRe.test(currentValue)) {
                dep.currentValue = tag;
                dep.currentDigest = currentValue;
            }
            else {
                dep.currentValue = currentValue;
                if (!dockerVersioning.api.isValid(currentValue)) {
                    dep.skipReason = 'invalid-version';
                }
            }
            deps.push(dep);
        }
    }
    return deps;
}
function extractContainer(container) {
    let dep;
    if (typeof container === 'string') {
        dep = (0, extract_1.getDep)(container);
    }
    else {
        dep = (0, extract_1.getDep)(container?.image);
    }
    return dep;
}
function extractWithYAMLParser(content, filename) {
    logger_1.logger.trace('github-actions.extractWithYAMLParser()');
    const deps = [];
    let pkg;
    try {
        pkg = (0, js_yaml_1.load)(content, { json: true });
    }
    catch (err) {
        logger_1.logger.debug({ filename, err }, 'Failed to parse GitHub Actions Workflow YAML');
        return [];
    }
    for (const job of Object.values(pkg?.jobs ?? {})) {
        if (job.container !== undefined) {
            const dep = extractContainer(job.container);
            dep.depType = 'container';
            deps.push(dep);
        }
        for (const service of Object.values(job.services ?? {})) {
            const dep = extractContainer(service);
            dep.depType = 'service';
            deps.push(dep);
        }
    }
    return deps;
}
function extractPackageFile(content, filename) {
    logger_1.logger.trace('github-actions.extractPackageFile()');
    const deps = [
        ...extractWithRegex(content),
        ...extractWithYAMLParser(content, filename),
    ];
    if (!deps.length) {
        return null;
    }
    return { deps };
}
exports.extractPackageFile = extractPackageFile;
//# sourceMappingURL=extract.js.map