dodo.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env doit -f
  2. # -*- coding: utf-8; -*-
  3. from collections import Iterable, Mapping # in Python 3 use from collections.abc
  4. from distutils.spawn import find_executable
  5. from fnmatch import fnmatch
  6. from kwonly import kwonly
  7. from subprocess import check_output
  8. from types import StringTypes
  9. import os.path
  10. import regex
  11. try:
  12. from os import scandir, walk
  13. except ImportError:
  14. from scandir import scandir, walk
  15. DOIT_CONFIG = {
  16. 'default_tasks': ['publish'],
  17. }
  18. def unnest(*args):
  19. """Un-nest list- and tuple-like elements in arguments.
  20. "List-like" means anything with a len() and whose elments can be
  21. accessed with numeric indexing, except for string-like elements. It
  22. must also be an instance of the collections.Iterable abstract class.
  23. Dict-like elements and iterators/generators are not affected.
  24. This function always returns a list, even if it is passed a single
  25. scalar argument.
  26. """
  27. result = []
  28. for arg in args:
  29. if isinstance(arg, StringTypes):
  30. # String
  31. result.append(arg)
  32. elif isinstance(arg, Mapping):
  33. # Dict-like
  34. result.append(arg)
  35. elif isinstance(arg, Iterable):
  36. try:
  37. # Duck-typing test for list-ness (a stricter condition
  38. # than just "iterable")
  39. for i in xrange(len(arg)):
  40. result.append(arg[i])
  41. except TypeError:
  42. # Iterable but not list-like
  43. result.append(arg)
  44. else:
  45. # Not iterable
  46. result.append(arg)
  47. return result
  48. def find_mac_app(name):
  49. try:
  50. return check_output(
  51. ["mdfind",
  52. "kMDItemDisplayName==%s&&kMDItemKind==Application" % (name,) ]).strip()
  53. except Exception:
  54. return None
  55. def glob_recursive(pattern, top=".", include_hidden=False, *args, **kwargs):
  56. """Combination of glob.glob and os.walk.
  57. Reutrns the relative path to every file or directory matching the
  58. pattern anywhere in the specified directory hierarchy. Defaults to the
  59. current working directory. Any additional arguments are passed to
  60. os.walk."""
  61. for (path, dirs, files) in walk(top, *args, **kwargs):
  62. for f in dirs + files:
  63. if include_hidden or f.startswith("."):
  64. continue
  65. if fnmatch(f, pattern):
  66. yield os.path.normpath(os.path.join(path, f))
  67. LYXPATH = find_executable("lyx") or \
  68. os.path.join(find_mac_app("LyX"), "Contents/MacOS/lyx") or \
  69. '/bin/false'
  70. @kwonly(0)
  71. def rsync_list_files(extra_rsync_args=(), include_dirs=False, *paths):
  72. """Iterate over the files in path that rsync would copy.
  73. By default, only files are listed, not directories, since doit doesn't
  74. like dependencies on directories because it can't hash them.
  75. This uses "rsync --list-only" to make rsync directly indicate which
  76. files it would copy, so any exclusion/inclusion rules are taken into
  77. account.
  78. """
  79. rsync_list_cmd = [ 'rsync', '-r', "--list-only" ] + unnest(extra_rsync_args) + unnest(paths) + [ "." ]
  80. rsync_out = check_output(rsync_list_cmd).splitlines()
  81. for line in rsync_out:
  82. s = regex.search("^(-|d)(?:\S+\s+){4}(.*)", line)
  83. if s is not None:
  84. if include_dirs or s.group(1) == '-':
  85. yield s.group(2)
  86. rsync_common_args = ["-rL", "--size-only", "--delete", "--delete-excluded",
  87. "--exclude", ".DS_Store", "--exclude", ".#*" ]
  88. def task_lyx2pdf():
  89. yield {
  90. 'name': None,
  91. 'doc': "Convert LyX file to PDF."
  92. }
  93. for lyxfile in glob_recursive("*.lyx"):
  94. pdffile = lyxfile[:-3] + "pdf"
  95. lyx_cmd = [LYXPATH, "--export-to", "pdf4" , pdffile, lyxfile]
  96. yield {
  97. 'name': lyxfile,
  98. 'actions': [lyx_cmd],
  99. # Assume every bib file is a dependency of any LaTeX
  100. # operation
  101. 'file_dep': [lyxfile] + list(glob_recursive('*.bib')),
  102. 'targets': [pdffile],
  103. 'verbosity': 0,
  104. 'clean': True,
  105. }
  106. def task_readme2index():
  107. yield {
  108. 'name': None,
  109. 'doc': "Convert README.mkdn files to index.html."
  110. }
  111. for mkdnfile in glob_recursive("README.mkdn", top="examples"):
  112. htmlfile = os.path.join(os.path.dirname(mkdnfile), "index.html")
  113. yield {
  114. 'name': mkdnfile,
  115. 'actions': [["pandoc", "-t", "html", "-o", htmlfile, mkdnfile]],
  116. 'file_dep': [mkdnfile],
  117. 'targets': [htmlfile],
  118. 'clean': True,
  119. }
  120. def task_publish():
  121. yield {
  122. 'name': None,
  123. 'doc': "Sync resume and supporting files to my web server."
  124. }
  125. # Resume PDF file
  126. rsync_src = "ryan_thompson_resume.pdf"
  127. rsync_dest = "mneme:public_html/resume/"
  128. file_deps = [rsync_src]
  129. rsync_xfer_cmd = ["rsync"] + rsync_common_args + [ rsync_src, rsync_dest ]
  130. yield {
  131. 'name': rsync_src,
  132. 'actions': [rsync_xfer_cmd],
  133. 'file_dep': file_deps,
  134. 'task_dep': [ 'lyx2pdf' ],
  135. 'doc': "rsync resume PDF file to my web server.",
  136. 'verbosity': 2,
  137. }
  138. # Examples directory
  139. rsync_src = "examples"
  140. rsync_dest = "mneme:public_html/resume/"
  141. file_deps = list(rsync_list_files(rsync_src, extra_rsync_args=rsync_common_args))
  142. # Ensure the generated html files are in file_deps
  143. for f in file_deps:
  144. if os.path.basename(f) == "README.mkdn":
  145. htmlfile = os.path.join(os.path.dirname(f), "index.html")
  146. if htmlfile not in file_deps:
  147. file_deps.append(htmlfile)
  148. file_deps = sorted(file_deps)
  149. rsync_xfer_cmd = ["rsync"] + rsync_common_args + [ rsync_src, rsync_dest ]
  150. yield {
  151. 'name': rsync_src,
  152. 'actions': [rsync_xfer_cmd],
  153. 'file_dep': file_deps,
  154. 'task_dep': [ 'readme2index' ],
  155. 'doc': "rsync examples directory to my web server.",
  156. 'verbosity': 2,
  157. }
  158. # Dummy target if you just want to build everything but not publish
  159. def task_build():
  160. return {
  161. 'doc': 'Build resume and supporting files.',
  162. 'task_dep': [ 'lyx2pdf', 'readme2index' ],
  163. 'actions': [],
  164. }