|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Pack and restore the figures the documentation examples produce. |
| 3 | +
|
| 4 | +The documentation build runs every example in |
| 5 | +``src/microstructpy/examples``, which takes about twenty minutes and does |
| 6 | +not fit in the fifteen minute limit of a Read the Docs build on the free |
| 7 | +plan. The work is the same on every build, so this module moves it to a |
| 8 | +machine without a time limit: the documentation workflow packs what the |
| 9 | +examples produced, and the Read the Docs build restores it before Sphinx |
| 10 | +runs. |
| 11 | +
|
| 12 | +Two sets of files are needed, and both are in the archive: |
| 13 | +
|
| 14 | +* ``docs/source/auto_examples``, the output of Sphinx-Gallery. It holds |
| 15 | + the ``.md5`` of ``plot_demos.py``, which is what makes Sphinx-Gallery |
| 16 | + skip the examples instead of running them. |
| 17 | +* The PNG files under ``src/microstructpy/examples``, which the pages in |
| 18 | + ``docs/source/examples`` embed with ``figure::``. The meshes beside |
| 19 | + them are not in the archive, since no page refers to them. |
| 20 | +
|
| 21 | +An archive carries the digest of the inputs it was built from, from |
| 22 | +:mod:`docs.example_digest`. ``restore`` refuses an archive whose digest |
| 23 | +is not the digest of the working tree, so an edited example cannot be |
| 24 | +served with the figures of an older one. Refusing leaves the build to |
| 25 | +run the examples itself, which is slow and may time out, and that is the |
| 26 | +intended outcome: a build that cannot be warm should be loud, not stale. |
| 27 | +
|
| 28 | +Usage:: |
| 29 | +
|
| 30 | + python docs/example_cache.py pack examples.tar.gz |
| 31 | + python docs/example_cache.py restore examples.tar.gz |
| 32 | + python docs/example_cache.py name # archive name for this tree |
| 33 | +
|
| 34 | +""" |
| 35 | + |
| 36 | +import argparse |
| 37 | +import json |
| 38 | +import os |
| 39 | +import sys |
| 40 | +import tarfile |
| 41 | + |
| 42 | +HERE = os.path.dirname(os.path.abspath(__file__)) |
| 43 | +ROOT = os.path.dirname(HERE) |
| 44 | + |
| 45 | +sys.path.insert(0, HERE) |
| 46 | +from example_digest import digest # noqa: E402 |
| 47 | + |
| 48 | +GALLERY = os.path.join('docs', 'source', 'auto_examples') |
| 49 | +EXAMPLES = os.path.join('src', 'microstructpy', 'examples') |
| 50 | +MANIFEST = 'microstructpy-example-cache.json' |
| 51 | + |
| 52 | + |
| 53 | +def _gallery_members(): |
| 54 | + """Every file of the Sphinx-Gallery output, relative to the root.""" |
| 55 | + members = [] |
| 56 | + root = os.path.join(ROOT, GALLERY) |
| 57 | + for dirpath, dirnames, filenames in os.walk(root): |
| 58 | + dirnames.sort() |
| 59 | + for name in sorted(filenames): |
| 60 | + path = os.path.join(dirpath, name) |
| 61 | + members.append(os.path.relpath(path, ROOT)) |
| 62 | + return members |
| 63 | + |
| 64 | + |
| 65 | +def _figure_members(): |
| 66 | + """Every PNG an example wrote, relative to the root. |
| 67 | +
|
| 68 | + Only the files in the output directories of the examples, so that an |
| 69 | + input such as ``aluminum_micro.png`` is not carried in the archive. |
| 70 | + """ |
| 71 | + members = [] |
| 72 | + root = os.path.join(ROOT, EXAMPLES) |
| 73 | + for dirpath, dirnames, filenames in os.walk(root): |
| 74 | + dirnames.sort() |
| 75 | + if os.path.abspath(dirpath) == os.path.abspath(root): |
| 76 | + continue # the inputs live here, the figures are in subdirs |
| 77 | + for name in sorted(filenames): |
| 78 | + if name.endswith('.png'): |
| 79 | + path = os.path.join(dirpath, name) |
| 80 | + members.append(os.path.relpath(path, ROOT)) |
| 81 | + return members |
| 82 | + |
| 83 | + |
| 84 | +def pack(filename): |
| 85 | + """Write an archive of the figures and the gallery output.""" |
| 86 | + gallery = _gallery_members() |
| 87 | + figures = _figure_members() |
| 88 | + |
| 89 | + if not gallery: |
| 90 | + print('No %s to pack. Build the documentation first.' % GALLERY, |
| 91 | + file=sys.stderr) |
| 92 | + return 1 |
| 93 | + if not figures: |
| 94 | + print('No figures under %s to pack.' % EXAMPLES, file=sys.stderr) |
| 95 | + return 1 |
| 96 | + |
| 97 | + value = digest() |
| 98 | + manifest = json.dumps({'digest': value, |
| 99 | + 'gallery': len(gallery), |
| 100 | + 'figures': len(figures)}, indent=2).encode() |
| 101 | + |
| 102 | + with tarfile.open(filename, 'w:gz') as tar: |
| 103 | + info = tarfile.TarInfo(MANIFEST) |
| 104 | + info.size = len(manifest) |
| 105 | + tar.addfile(info, _BytesIO(manifest)) |
| 106 | + for rel in gallery + figures: |
| 107 | + tar.add(os.path.join(ROOT, rel), arcname=rel) |
| 108 | + |
| 109 | + size = os.path.getsize(filename) / 1048576.0 |
| 110 | + print('packed %d gallery files and %d figures for digest %s ' |
| 111 | + 'into %s (%.1f MB)' |
| 112 | + % (len(gallery), len(figures), value, filename, size)) |
| 113 | + return 0 |
| 114 | + |
| 115 | + |
| 116 | +def restore(filename): |
| 117 | + """Extract an archive, if its digest is the digest of this tree.""" |
| 118 | + if not os.path.exists(filename): |
| 119 | + print('No archive at %s.' % filename, file=sys.stderr) |
| 120 | + return 1 |
| 121 | + |
| 122 | + with tarfile.open(filename, 'r:gz') as tar: |
| 123 | + try: |
| 124 | + manifest = json.loads(tar.extractfile(MANIFEST).read().decode()) |
| 125 | + except KeyError: |
| 126 | + print('%s has no %s, refusing to restore it.' |
| 127 | + % (filename, MANIFEST), file=sys.stderr) |
| 128 | + return 1 |
| 129 | + |
| 130 | + current = digest() |
| 131 | + if manifest.get('digest') != current: |
| 132 | + print('The archive was built from %s and the examples digest ' |
| 133 | + 'to %s. Refusing to restore it, the examples will be run.' |
| 134 | + % (manifest.get('digest'), current), file=sys.stderr) |
| 135 | + return 1 |
| 136 | + |
| 137 | + members = [m for m in tar.getmembers() if m.name != MANIFEST] |
| 138 | + for m in members: |
| 139 | + if m.name.startswith('/') or '..' in m.name.split('/'): |
| 140 | + print('Refusing a path outside the tree: %s' % m.name, |
| 141 | + file=sys.stderr) |
| 142 | + return 1 |
| 143 | + try: |
| 144 | + tar.extractall(ROOT, members=members, filter='data') |
| 145 | + except TypeError: |
| 146 | + # filter= arrived in Python 3.12. The paths are checked above. |
| 147 | + tar.extractall(ROOT, members=members) |
| 148 | + |
| 149 | + print('restored %d files for digest %s' % (len(members), current)) |
| 150 | + return 0 |
| 151 | + |
| 152 | + |
| 153 | +def name(): |
| 154 | + """Print the archive name for this working tree.""" |
| 155 | + print('microstructpy-examples-%s.tar.gz' % digest()) |
| 156 | + return 0 |
| 157 | + |
| 158 | + |
| 159 | +class _BytesIO(object): |
| 160 | + """A minimal file object, so tarfile can add bytes already in memory.""" |
| 161 | + |
| 162 | + def __init__(self, data): |
| 163 | + self._data = data |
| 164 | + self._pos = 0 |
| 165 | + |
| 166 | + def read(self, size=-1): |
| 167 | + if size < 0: |
| 168 | + chunk = self._data[self._pos:] |
| 169 | + else: |
| 170 | + chunk = self._data[self._pos:self._pos + size] |
| 171 | + self._pos += len(chunk) |
| 172 | + return chunk |
| 173 | + |
| 174 | + |
| 175 | +def main(): |
| 176 | + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) |
| 177 | + sub = parser.add_subparsers(dest='command', required=True) |
| 178 | + p = sub.add_parser('pack', help='write an archive of the figures') |
| 179 | + p.add_argument('filename') |
| 180 | + r = sub.add_parser('restore', help='extract an archive of the figures') |
| 181 | + r.add_argument('filename') |
| 182 | + sub.add_parser('name', help='the archive name for this working tree') |
| 183 | + |
| 184 | + args = parser.parse_args() |
| 185 | + if args.command == 'pack': |
| 186 | + return pack(args.filename) |
| 187 | + if args.command == 'restore': |
| 188 | + return restore(args.filename) |
| 189 | + return name() |
| 190 | + |
| 191 | + |
| 192 | +if __name__ == '__main__': |
| 193 | + sys.exit(main()) |
0 commit comments