metadata: allow several values and one-liners

This commit is contained in:
Roipoussiere 2023-06-06 19:15:46 +02:00
parent 98a89aea11
commit 2e22152089

View File

@ -1,14 +1,26 @@
export function getMetadata(raw_code) {
// https://stackoverflow.com/a/15123777
const comment_regexp = /\/\*([\s\S]*?)\*\/|([^\\:]|^)\/\/(.*)$/gm;
const ALLOW_MANY = ['by', 'url', 'genre', 'license'];
const tag_regexp = /@([a-z]*):? (.*)/gm;
export function getMetadata(raw_code) {
const comment_regexp = /\/\*([\s\S]*?)\*\/|\/\/(.*)$/gm;
const tags = {};
for (const match of raw_code.matchAll(comment_regexp)) {
const comment = match[1] ? match[1] : '' + match[3] ? match[3] : '';
for (const tag_match of comment.trim().matchAll(tag_regexp)) {
tags[tag_match[1]] = tag_match[2].trim();
const tag_matches = (match[1] || match[2] || '').trim().split('@').slice(1);
for (const tag_match of tag_matches) {
let [tag, tag_value] = tag_match.split(/ (.*)/s);
tag = tag.trim();
tag_value = (tag_value || '').replaceAll(/ +/g, ' ').trim();
if (ALLOW_MANY.includes(tag)) {
const tag_list = tag_value
.split(/[,\n]/)
.map((t) => t.trim())
.filter((t) => t !== '');
tags[tag] = tag in tags ? tags[tag].concat(tag_list) : tag_list;
} else {
tag_value = tag_value.replaceAll(/\s+/g, ' ');
tags[tag] = tag in tags ? tags[tag] + ' ' + tag_value : tag_value;
}
}
}