Last active
August 8, 2019 08:17
-
-
Save dmentipl/e9ec8007ef5cd383e884a7187b7e0fd4 to your computer and use it in GitHub Desktop.
Fix BibDesk file links
This file contains hidden or 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 python | |
""" | |
Fix file links in bibtex file used with BibDesk using bibtexparser. | |
To use, run the script then open the resulting bibtex file in BibDesk | |
and save it. This should fix all file links. | |
Daniel Mentiplay, 2019. | |
""" | |
import pathlib | |
import bibtexparser | |
# ------------------------------------------------------------------------------------ # | |
# EDIT THESE VARIABLES AS REQUIRED | |
# NOTE: BIBTEX_FILE and PDF_DIR must be pathlib.Path objects. | |
# Path to bibtex file. | |
BIBTEX_FILE = pathlib.Path('~/repos/phd/references/references.bib').expanduser() | |
# Path to PDFs. | |
PDF_DIR = pathlib.Path('~/Dropbox/references/astronomy').expanduser() | |
# New bibtex file name. | |
NEW_FILE = 'new.bib' | |
# ------------------------------------------------------------------------------------ # | |
def load_bibtex(path): | |
with open(path) as bibtex_file: | |
db = bibtexparser.bparser.BibTexParser(common_strings=True).parse_file( | |
bibtex_file | |
) | |
return db | |
def cite_key_has_pdf(cite_key): | |
return (PDF_DIR / f'{cite_key.replace(":", "")}.pdf').exists() | |
def update_cite_key_with_file_link(cite_key, reference_database): | |
reference_database.entries_dict[cite_key]['bdsk-file-1'] = str( | |
PDF_DIR / f'{cite_key.replace(":", "")}.pdf' | |
) | |
def add_files_to_database(database): | |
for entry in database.entries: | |
if cite_key_has_pdf(entry['ID']): | |
update_cite_key_with_file_link(entry['ID'], database) | |
if __name__ == '__main__': | |
# Load bibtex database. | |
print('Loading bibtex file with bibtexparser...') | |
reference_database = load_bibtex(BIBTEX_FILE) | |
# Add file links. | |
print('Adding file links...') | |
add_files_to_database(reference_database) | |
# Write new .bib file. | |
print(f'Writing {NEW_FILE} file with correct file links...') | |
with open(NEW_FILE, 'w') as bibtex_file: | |
bibtexparser.dump(reference_database, bibtex_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment