Snakefile 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # -*- coding: utf-8; -*-
  2. import locale
  3. import os.path
  4. import regex
  5. import urllib.parse
  6. import bibtexparser
  7. from collections.abc import Iterable, Mapping
  8. from distutils.spawn import find_executable
  9. from fnmatch import fnmatch
  10. from subprocess import check_output, check_call
  11. from tempfile import NamedTemporaryFile
  12. from bibtexparser.bibdatabase import BibDatabase
  13. try:
  14. from os import scandir, walk
  15. except ImportError:
  16. from scandir import scandir, walk
  17. def unnest(*args):
  18. '''Un-nest list- and tuple-like elements in arguments.
  19. "List-like" means anything with a len() and whose elments can be
  20. accessed with numeric indexing, except for string-like elements. It
  21. must also be an instance of the collections.Iterable abstract class.
  22. Dict-like elements and iterators/generators are not affected.
  23. This function always returns a list, even if it is passed a single
  24. scalar argument.
  25. '''
  26. result = []
  27. for arg in args:
  28. if isinstance(arg, str):
  29. # String
  30. result.append(arg)
  31. elif isinstance(arg, Mapping):
  32. # Dict-like
  33. result.append(arg)
  34. elif isinstance(arg, Iterable):
  35. try:
  36. # Duck-typing test for list-ness (a stricter condition
  37. # than just "iterable")
  38. for i in range(len(arg)):
  39. result.append(arg[i])
  40. except TypeError:
  41. # Iterable but not list-like
  42. result.append(arg)
  43. else:
  44. # Not iterable
  45. result.append(arg)
  46. return result
  47. def check_output_decode(*args, encoding=locale.getpreferredencoding(), **kwargs):
  48. '''Shortcut for check.output + str.decode'''
  49. return check_output(*args, **kwargs).decode(encoding)
  50. def find_mac_app(name):
  51. try:
  52. result = check_output_decode(
  53. ['mdfind',
  54. 'kMDItemDisplayName=={name}.app&&kMDItemKind==Application'.format(name=name)]).split('\n')[0]
  55. if not result:
  56. raise Exception("No result found")
  57. return result
  58. except Exception:
  59. return None
  60. def glob_recursive(pattern, top='.', include_hidden=False, *args, **kwargs):
  61. '''Combination of glob.glob and os.walk.
  62. Reutrns the relative path to every file or directory matching the
  63. pattern anywhere in the specified directory hierarchy. Defaults to the
  64. current working directory. Any additional arguments are passed to
  65. os.walk.'''
  66. for (path, dirs, files) in walk(top, *args, **kwargs):
  67. for f in dirs + files:
  68. if include_hidden or f.startswith('.'):
  69. continue
  70. if fnmatch(f, pattern):
  71. yield os.path.normpath(os.path.join(path, f))
  72. LYXPATH = find_executable('lyx') or \
  73. os.path.join(find_mac_app('LyX'), 'Contents/MacOS/lyx') or \
  74. '/bin/false'
  75. def rsync_list_files(*paths, extra_rsync_args=(), include_dirs=False):
  76. '''Iterate over the files in path that rsync would copy.
  77. By default, only files are listed, not directories, since doit doesn't
  78. like dependencies on directories because it can't hash them.
  79. This uses "rsync --list-only" to make rsync directly indicate which
  80. files it would copy, so any exclusion/inclusion rules are taken into
  81. account.
  82. '''
  83. rsync_list_cmd = [ 'rsync', '-r', '--list-only' ] + unnest(extra_rsync_args) + unnest(paths) + [ '.' ]
  84. rsync_out = check_output_decode(rsync_list_cmd).splitlines()
  85. for line in rsync_out:
  86. s = regex.search('^(-|d)(?:\S+\s+){4}(.*)', line)
  87. if s is not None:
  88. if include_dirs or s.group(1) == '-':
  89. yield s.group(2)
  90. def lyx_bib_deps(lyxfile):
  91. '''Return an iterator over all bib files referenced by a Lyx file.
  92. This will only return the names of existing files, so it will be
  93. unreliable in the case of an auto-generated bib file.
  94. '''
  95. try:
  96. with open(lyxfile) as f:
  97. lyx_text = f.read()
  98. bib_names = []
  99. for m in regex.finditer('bibfiles "(.*?)"', lyx_text):
  100. bib_names.extend(m.group(1).split(','))
  101. # Unfortunately LyX doesn't indicate which bib names refer to
  102. # files in the current directory and which don't. Currently that's
  103. # not a problem for me since all my refs are in bib files in the
  104. # current directory.
  105. for bn in bib_names:
  106. bib_path = bn + '.bib'
  107. yield bib_path
  108. except FileNotFoundError:
  109. pass
  110. def lyx_hrefs(lyxfile):
  111. '''Return an iterator over hrefs in a LyX file.'''
  112. pattern = '''
  113. (?xsm)
  114. ^ LatexCommand \\s+ href \\s* \\n
  115. (?: name \\b [^\\n]+ \\n )?
  116. target \\s+ "(.*?)" $
  117. '''
  118. with open(lyxfile) as f:
  119. return (urllib.parse.unquote(m.group(1)) for m in
  120. re.finditer(pattern, f.read()))
  121. examples_base_url = 'https://darwinawardwinner.github.io/resume/examples/'
  122. examples_dir = 'examples'
  123. def resume_example_deps(lyxfile):
  124. '''Iterate over all referenced example files in a LyX file.'''
  125. for href in lyx_hrefs(lyxfile):
  126. if href.startswith(examples_base_url) and not href.endswith('/'):
  127. expath = href[len(examples_base_url):]
  128. yield os.path.join(examples_dir, expath)
  129. readme_files = list(glob_recursive('README.mkdn', top='examples'))
  130. index_files = [ os.path.join(os.path.dirname(f), 'index.html') for f in readme_files ]
  131. rsync_common_args = ['-rL', '--size-only', '--delete', '--exclude', '.DS_Store', '--delete-excluded',]
  132. all_example_files = set(rsync_list_files('examples', extra_rsync_args=rsync_common_args))
  133. r_html_files = [ f + '.html' for f in all_example_files if f.endswith('.R') ]
  134. all_example_files = all_example_files.union(index_files)
  135. all_example_files = all_example_files.union(r_html_files)
  136. rule build_all:
  137. input: 'ryan_thompson_resume.pdf', #'ryan_thompson_resume.html',
  138. 'ryan_thompson_cv.pdf', #'ryan_thompson_cv.html',
  139. #'index.html',
  140. index_files, r_html_files
  141. rule create_resume_pdf:
  142. input: lyxfile='ryan_thompson_resume.lyx',
  143. bibfiles=list(lyx_bib_deps('ryan_thompson_resume.lyx')),
  144. example_files=list(resume_example_deps('ryan_thompson_resume.lyx')),
  145. headshot='headshot-crop.png',
  146. output: pdf='ryan_thompson_resume.pdf'
  147. shell: '{LYXPATH:q} --export-to pdf4 {output.pdf:q} {input.lyxfile:q}'
  148. # rule create_resume_html:
  149. # input: lyxfile='ryan_thompson_resume.lyx',
  150. # bibfiles=list(lyx_bib_deps('ryan_thompson_resume.lyx')),
  151. # example_files=list(resume_example_deps('ryan_thompson_resume.lyx')),
  152. # headshot='headshot-crop.png',
  153. # output: html='ryan_thompson_resume.html'
  154. # run:
  155. # with NamedTemporaryFile() as tempf:
  156. # shell('{LYXPATH:q} --export-to xhtml {tempf.name:q} {input.lyxfile:q}')
  157. # shell('''cat {tempf.name:q} | perl -lape 's[<span class="flex_cv_image">(.*?)</span>][<span class="flex_cv_image"><img src="$1" width="100"></span>]g' > {output.html:q}''')
  158. rule create_cv_pdf:
  159. input: lyxfile='ryan_thompson_cv.lyx',
  160. bibfiles=list(lyx_bib_deps('ryan_thompson_cv.lyx')),
  161. example_files=list(resume_example_deps('ryan_thompson_cv.lyx')),
  162. headshot='headshot-crop.png',
  163. output: pdf='ryan_thompson_cv.pdf'
  164. shell: '{LYXPATH:q} --export-to pdf4 {output.pdf:q} {input.lyxfile:q}'
  165. # rule create_cv_html:
  166. # input: lyxfile='ryan_thompson_cv.lyx',
  167. # bibfiles=list(lyx_bib_deps('ryan_thompson_cv.lyx')),
  168. # example_files=list(resume_example_deps('ryan_thompson_cv.lyx')),
  169. # headshot='headshot-crop.png',
  170. # output: html='ryan_thompson_cv.html'
  171. # run:
  172. # with NamedTemporaryFile() as tempf:
  173. # shell('{LYXPATH:q} --export-to xhtml {tempf.name:q} {input.lyxfile:q}')
  174. # shell('''cat {tempf.name:q} | perl -lape 's[<span class="flex_cv_image">(.*?)</span>][<span class="flex_cv_image"><img src="$1" width="100"></span>]g' > {output.html:q}''')
  175. # rule link_resume_to_index_html:
  176. # input: 'ryan_thompson_resume.html'
  177. # output: 'index.html'
  178. # shell: 'ln -s {input:q} {output:q}'
  179. rule examples_readme_to_index_html:
  180. input: '{dirname}README.mkdn'
  181. output: '{dirname,examples(/.*)?/}index.html'
  182. shell: 'pandoc -t html -o {output[0]:q} {input[0]:q}'
  183. rule R_to_html:
  184. input: '{dirname}/{basename,[^/]+}.R'
  185. output: '{dirname}/{basename}.R.html'
  186. shell: 'pygmentize -f html -O full -l R -o {output:q} {input:q}'
  187. rule process_bib:
  188. '''Preprocess bib file for LaTeX.
  189. For entries with a DOI, all URLs are stripped, since the DOI already
  190. provides a clickable link. For entries with no DOI, all but one URL is
  191. discarded, since LyX can't handle entries with multiple URLs. The
  192. shortest URL is kept.'''
  193. input: '{basename}.bib'
  194. output: '{basename,.*(?<!-PROCESSED)}-PROCESSED.bib'
  195. run:
  196. with open(input[0]) as infile:
  197. bib_db = bibtexparser.load(infile)
  198. entries = bib_db.entries
  199. for entry in entries:
  200. # Keep DOI or exactly one URL
  201. if 'doi' in entry:
  202. try:
  203. del entry['url']
  204. except KeyError:
  205. pass
  206. else:
  207. try:
  208. entry_urls = regex.split('\\s+', entry['url'])
  209. shortest_url = min(entry_urls, key=len)
  210. # Need to fix e.g. 'http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=55329{\\&}tool=pmcentrez{\\&}rendertype=abstract'
  211. shortest_url = re.sub('\\{\\\\?(.)\\}', '\\1', shortest_url)
  212. entry['url'] = shortest_url
  213. except KeyError:
  214. pass
  215. # Boldface my name
  216. authors = regex.split("\\s+and\\s+",entry['author'])
  217. for i in range(len(authors)):
  218. m = regex.search('^Thompson,\\s+(R.*)$', authors[i])
  219. if m:
  220. authors[i] = f"\\textbf{{{m.group(1)} Thompson}}"
  221. entry['author'] = ' and '.join(authors)
  222. # Fix CD4+ formatting (superscript plus sign)
  223. entry['title'] = regex.sub('CD4\\+', 'CD4$^{+}$', entry['title'])
  224. new_db = BibDatabase()
  225. new_db.entries = entries
  226. with open(output[0], 'w') as outfile:
  227. bibtexparser.dump(new_db, outfile)