2

Following Sphinx TODO directive tutorial, I have made a Sphinx custom directive (let's call it A) that takes a file path as input, extracts information from this file, and produce nodes accordingly.

I want to create a new custom directive (let's call it B) that takes a directory as input, calls directive A on all files inside the directory (the search for files is actually a bit more involved than that, but it has no relevance to my issue) and appends the produced nodes.

I cannot find how to do that. I have started to write the Python file for this directive B, but I do not know how to get a hold of a node class corresponding to directive A. I'd like to write something like this:

def run(self):
    nodes = []
    directory = self.arguments[0]
    for filepath in directory:
        nodes += nodes.mydirectiveA("path/to/file") #not proper code
    return nodes

What am I missing here?

Note: I have found this question whose title was promissing, but I do not have this inheritance relationship in my case.

mzjn
  • 48,958
  • 13
  • 128
  • 248
Silverspur
  • 891
  • 1
  • 12
  • 33
  • I've ended up creating objects of directive A class, inside directive B `run` method, passing all the correct arguments to the constructor (see file docutils/parsers/rst/directives/__init__.py in docutils code base for Directive class constructor arguments). I do not know if this is the right way to solve the problem, though. – Silverspur Aug 06 '22 at 12:19

1 Answers1

1

IMO, you may not need to "get a hold of a node class corresponding to directive A". Directive class only helps you parse rST to arguments and options, it does not relate to the node creation.

As directive A is implemented by yourself, you can create a common helper function shared by both A and B for creating nodes, like this:

From:

class A(SphinxDirecitve):
  # ...
  def run(self) -> list[nodes.Node]
    # do sth
    pass

To:

def add_files_nodes(options) -> list[nodes.Node]:
   # do sth
   pass
class A(SphinxDirecitve):
  # ...
  def run(self) -> list[nodes.Node]
    opts = """convert self.options to function arguments"""
    return add_files_nodes(opts)
SilverRainZ
  • 156
  • 5