"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getReleaseList = exports.getReleaseNotesMd = 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 schema_1 = require("../../../../../../modules/datasource/gitea-releases/schema");
const schema_2 = require("../../../../../../modules/platform/gitea/schema");
const gitea_1 = require("../../../../../../util/http/gitea");
const string_1 = require("../../../../../../util/string");
exports.id = 'gitea-changelog';
const http = new gitea_1.GiteaHttp(exports.id);
async function getReleaseNotesMd(repository, apiBaseUrl, sourceDirectory) {
    logger_1.logger.trace('gitea.getReleaseNotesMd()');
    const apiPrefix = `${apiBaseUrl}repos/${repository}/contents`;
    const sourceDir = sourceDirectory ? `/${sourceDirectory}` : '';
    const tree = (await http.getJson(`${apiPrefix}${sourceDir}`, {
        paginate: false, // no pagination yet
    }, schema_2.ContentsListResponseSchema)).body;
    const allFiles = tree.filter((f) => f.type === 'file');
    let files = [];
    if (!files.length) {
        files = allFiles.filter((f) => changelog_filename_regex_1.default.test(f.name));
    }
    if (!files.length) {
        logger_1.logger.trace('no changelog file found');
        return null;
    }
    const { path: changelogFile } = files.shift();
    /* istanbul ignore if */
    if (files.length !== 0) {
        logger_1.logger.debug(`Multiple candidates for changelog file, using ${changelogFile}`);
    }
    const fileRes = await http.getJson(`${apiPrefix}/${changelogFile}`, schema_2.ContentsResponseSchema);
    // istanbul ignore if: should never happen
    if (!fileRes.body.content) {
        logger_1.logger.debug(`Missing content for changelog file, using ${changelogFile}`);
        return null;
    }
    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('gitea.getReleaseNotesMd()');
    const apiUrl = `${project.apiBaseUrl}repos/${project.repository}/releases`;
    const res = await http.getJson(`${apiUrl}?draft=false`, {
        paginate: true,
    }, schema_1.ReleasesSchema);
    return res.body.map((release) => ({
        url: `${project.baseUrl}${project.repository}/releases/tag/${release.tag_name}`,
        notesSourceUrl: apiUrl,
        name: release.name,
        body: release.body,
        tag: release.tag_name,
    }));
}
exports.getReleaseList = getReleaseList;
//# sourceMappingURL=index.js.map