Created
March 2, 2022 16:53
-
-
Save retorquere/0553c9e7ba4a7ce0df5e1e521e368fbf to your computer and use it in GitHub Desktop.
merge CSL styles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
from pathlib import Path | |
import xml.etree.ElementTree as ET | |
namespaces = {'csl': 'http://purl.org/net/xbiblio/csl'} | |
ET.register_namespace('', namespaces['csl']) | |
inline = ET.parse(sys.argv[1]) | |
bibliography = ET.parse(sys.argv[2]) | |
# rename macros and macro calls | |
for doc, arg in [(inline, 1), (bibliography, 2)]: | |
prefix = Path(sys.argv[arg]).stem | |
for elem in doc.getroot().iter(): | |
if 'macro' in elem.attrib: | |
elem.attrib['macro'] = prefix + '-' + elem.attrib['macro'] | |
for elem in doc.getroot().findall('csl:macro', namespaces=namespaces): | |
elem.attrib['name'] = prefix + '-' + elem.attrib['name'] | |
# merge titles/id | |
for elem in ['id', 'title', 'title-short']: | |
elems = [doc.getroot().find('csl:info/csl:' + elem, namespaces=namespaces) for doc in [inline, bibliography]] | |
if None not in elems: | |
elems[0].text = ' + '.join([e.text for e in elems]) | |
# remove bibliography from inline | |
inline.getroot().remove(inline.getroot().find('csl:bibliography', namespaces=namespaces)) | |
# add bibliography from bibliography | |
inline.getroot().append(bibliography.getroot().find('csl:bibliography', namespaces=namespaces)) | |
# add macros from bibliography | |
for macro in bibliography.getroot().findall('csl:macro', namespaces=namespaces): | |
inline.getroot().append(macro) | |
inline.write(sys.argv[3]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment