diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2025-02-22 14:39:47 -0400 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2025-02-22 14:39:47 -0400 |
commit | 3a633a8343949099d7f3a7a4efa8efba4baa340d (patch) | |
tree | bc985daf16c72ba51a0962ea36fb6aaa79fa3834 /src/data/yaml.js | |
parent | f886fbe24de02cdafa80e8d7f32fed0845dfa46d (diff) |
yaml: reorderDocumentsInYAMLSourceText
Diffstat (limited to 'src/data/yaml.js')
-rw-r--r-- | src/data/yaml.js | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/src/data/yaml.js b/src/data/yaml.js index 1045da4f..be494dad 100644 --- a/src/data/yaml.js +++ b/src/data/yaml.js @@ -1531,3 +1531,73 @@ export function matchFilenameToThings(filename, wikiData) { } } } + +export function* splitDocumentsInYAMLSourceText(sourceText) { + const dividerRegex = /^-{3,}\n?/gm; + let previousDivider = ''; + + while (true) { + const {lastIndex} = dividerRegex; + const match = dividerRegex.exec(sourceText); + if (match) { + const nextDivider = match[0].trim(); + + yield { + previousDivider, + nextDivider, + text: sourceText.slice(lastIndex, match.index), + }; + + previousDivider = nextDivider; + } else { + const nextDivider = ''; + + yield { + previousDivider, + nextDivider, + text: sourceText.slice(lastIndex).replace(/(?<!\n)$/, '\n'), + }; + + return; + } + } +} + +export function recombineDocumentsIntoYAMLSourceText(documents) { + const dividers = + unique( + documents + .flatMap(d => [d.previousDivider, d.nextDivider]) + .filter(Boolean)); + + const divider = dividers[0]; + + if (dividers.length > 1) { + // TODO: Accommodate mixed dividers as best as we can lol + logWarn`Found multiple dividers in this file, using only ${divider}`; + } + + let sourceText = ''; + + for (const document of documents) { + if (sourceText) { + sourceText += divider + '\n'; + } + + sourceText += document.text; + } + + return sourceText; +} + +export function reorderDocumentsInYAMLSourceText(sourceText, order) { + const sourceDocuments = + Array.from(splitDocumentsInYAMLSourceText(sourceText)); + + const sortedDocuments = + Array.from( + order, + sourceIndex => sourceDocuments[sourceIndex]); + + return recombineDocumentsIntoYAMLSourceText(sortedDocuments); +} |