|
| 1 | +import itertools |
| 2 | + |
| 3 | +from docutils import nodes |
| 4 | +from sphinx.util.docutils import SphinxDirective |
| 5 | +from docutils.parsers.rst import directives |
| 6 | + |
| 7 | + |
| 8 | +def generate_author_list(authors): |
| 9 | + return [ |
| 10 | + nodes.Text(a, a) |
| 11 | + for a in authors |
| 12 | + ] |
| 13 | + |
| 14 | + |
| 15 | +class Author(SphinxDirective): |
| 16 | + required_arguments = 1 |
| 17 | + final_argument_whitespace = True |
| 18 | + |
| 19 | + def run(self): |
| 20 | + env = self.state.document.settings.env |
| 21 | + |
| 22 | + env.authors.setdefault(env.docname, []) |
| 23 | + env.authors[env.docname].append(self.arguments[0]) |
| 24 | + |
| 25 | + return [] |
| 26 | + |
| 27 | + |
| 28 | +class Authors(SphinxDirective): |
| 29 | + def run(self): |
| 30 | + env = self.state.document.settings.env |
| 31 | + return generate_author_list(env.authors.get(env.docname, [])) |
| 32 | + |
| 33 | + |
| 34 | +# maker node later to be replaced by list of all authors |
| 35 | +class allauthors(nodes.General, nodes.Element): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +class AllAuthors(SphinxDirective): |
| 40 | + def run(self): |
| 41 | + return [allauthors('')] |
| 42 | + |
| 43 | + |
| 44 | +def builder_inited(app): |
| 45 | + app.builder.env.authors = {} |
| 46 | + |
| 47 | + |
| 48 | +def purge_authors(app, env, docname): |
| 49 | + if not hasattr(env, 'authors'): |
| 50 | + return |
| 51 | + |
| 52 | + env.authors.pop(docname, None) |
| 53 | + |
| 54 | + |
| 55 | +def process_authorlists(app, doctree, fromdocname): |
| 56 | + env = app.builder.env |
| 57 | + authors = set(itertools.chain(*[authors for authors in env.authors.values()])) |
| 58 | + |
| 59 | + for node in doctree.traverse(allauthors): |
| 60 | + node.replace_self(generate_author_list(authors)) |
| 61 | + |
| 62 | + |
| 63 | +def setup(app): |
| 64 | + app.add_node(allauthors) |
| 65 | + |
| 66 | + directives.register_directive('author', Author) |
| 67 | + directives.register_directive('authors', Authors) |
| 68 | + directives.register_directive('allauthors', AllAuthors) |
| 69 | + |
| 70 | + app.connect('builder-inited', builder_inited) |
| 71 | + app.connect('env-purge-doc', purge_authors) |
| 72 | + app.connect('doctree-resolved', process_authorlists) |
| 73 | + |
| 74 | + return { |
| 75 | + 'version': '1.0.0', |
| 76 | + } |
0 commit comments