"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getReleaseList = exports.getReleaseNotesMd = exports.getTags = exports.id = void 0;
const tslib_1 = require("tslib");
const changelog_filename_regex_1 = tslib_1.__importDefault(require("changelog-filename-regex"));
const logger_1 = require("../../../../../../logger");
const graphql_1 = require("../../../../../../util/github/graphql");
const github_1 = require("../../../../../../util/http/github");
const string_1 = require("../../../../../../util/string");
const url_1 = require("../../../../../../util/url");
exports.id = 'github-changelog';
const http = new github_1.GithubHttp(exports.id);
async function getTags(endpoint, repository) {
    logger_1.logger.trace('github.getTags()');
    try {
        const tags = await (0, graphql_1.queryTags)({
            registryUrl: endpoint,
            packageName: repository,
        }, http);
        // istanbul ignore if
        if (!tags.length) {
            logger_1.logger.debug(`No Github tags found for repository:${repository}`);
        }
        return tags.map(({ version }) => version);
    }
    catch (err) {
        logger_1.logger.debug({ sourceRepo: repository, err }, 'Failed to fetch Github tags');
        // istanbul ignore if
        if (err.message?.includes('Bad credentials')) {
            logger_1.logger.warn('Bad credentials triggering tag fail lookup in changelog');
            throw err;
        }
        return [];
    }
}
exports.getTags = getTags;
async function getReleaseNotesMd(repository, apiBaseUrl, sourceDirectory) {
    logger_1.logger.trace('github.getReleaseNotesMd()');
    const apiPrefix = `${(0, url_1.ensureTrailingSlash)(apiBaseUrl)}repos/${repository}`;
    const { default_branch: defaultBranch = 'HEAD' } = (await http.getJson(apiPrefix)).body;
    // https://docs.github.com/en/rest/reference/git#get-a-tree
    const res = await http.getJson(`${apiPrefix}/git/trees/${defaultBranch}${sourceDirectory ? '?recursive=1' : ''}`);
    // istanbul ignore if
    if (res.body.truncated) {
        logger_1.logger.debug(`Git tree truncated repository:${repository}`);
    }
    const allFiles = res.body.tree.filter((f) => f.type === 'blob');
    let files = [];
    if (sourceDirectory?.length) {
        files = allFiles
            .filter((f) => f.path.startsWith(sourceDirectory))
            .filter((f) => changelog_filename_regex_1.default.test(f.path.replace((0, url_1.ensureTrailingSlash)(sourceDirectory), '')));
    }
    if (!files.length) {
        files = allFiles.filter((f) => changelog_filename_regex_1.default.test(f.path));
    }
    if (!files.length) {
        logger_1.logger.trace('no changelog file found');
        return null;
    }
    const { path: changelogFile, sha } = files.shift();
    /* istanbul ignore if */
    if (files.length !== 0) {
        logger_1.logger.debug(`Multiple candidates for changelog file, using ${changelogFile}`);
    }
    // https://docs.github.com/en/rest/reference/git#get-a-blob
    const fileRes = await http.getJson(`${apiPrefix}/git/blobs/${sha}`);
    const changelogMd = (0, string_1.fromBase64)(fileRes.body.content) + '\n#\n##';
    return { changelogFile, changelogMd };
}
exports.getReleaseNotesMd = getReleaseNotesMd;
async function getReleaseList(project, _release) {
    logger_1.logger.trace('github.getReleaseList()');
    const apiBaseUrl = project.apiBaseUrl; // TODO #7154
    const repository = project.repository;
    const notesSourceUrl = (0, url_1.joinUrlParts)(apiBaseUrl, 'repos', repository, 'releases');
    const releases = await (0, graphql_1.queryReleases)({
        registryUrl: apiBaseUrl,
        packageName: repository,
    }, http);
    const result = releases.map(({ url, id, version: tag, name, description: body }) => ({
        url,
        notesSourceUrl,
        id,
        tag,
        name,
        body,
    }));
    return result;
}
exports.getReleaseList = getReleaseList;
//# sourceMappingURL=index.js.map