Skip to content

Commit

Permalink
Book: Add a sphinx preprocessor
Browse files Browse the repository at this point in the history
This is to avoid having to use build_book.py script.
1. Preprocessor is faster and doesn't use disk, as all communication is
   trough stdio.
2. It doesn't need to be executed explicitly. You can just use
   `mdbook build docs` and it will create correct documentation.
3. New script is shorter and simpler than old.

Script is based on example from https://rust-lang.github.io/mdBook/for_developers/preprocessors.html
and uses a function from build_book.py

In book.toml the command used is a simple bash script instead of just
`python ./sphinx_preprocessor.py` because the command is run in the
directory the user executed it in, not the directory that book.toml
is in (which is imho a poor design in this case), so in order to be able
to run the command both from main dir and from docs dir, such a script
locating the preprocessor is necessary.
  • Loading branch information
Lorak-mmk committed Jan 12, 2024
1 parent befa148 commit 8040546
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
11 changes: 10 additions & 1 deletion docs/book.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,13 @@ edition = "2021"

[output.html]
default-theme = "ayu"
git-repository-url = "https://github.com/scylladb/scylla-rust-driver"
git-repository-url = "https://github.com/scylladb/scylla-rust-driver"

[preprocessor.sphinx]
command = '''bash -c '
if test -f "./docs/sphinx_preprocessor.py"; then
python ./docs/sphinx_preprocessor.py "$@"
else
python ./sphinx_preprocessor.py "$@"
fi' run_preprocessor
'''
34 changes: 34 additions & 0 deletions docs/sphinx_preprocessor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import json
import sys

def remove_sphinx_markdown(md_file_text):
text_split = md_file_text.split("```eval_rst")

result = text_split[0]

for i in range(1, len(text_split)):
cur_chunk = text_split[i]
result += cur_chunk[cur_chunk.find("```") + 3:]

return result

def process_section(section):
if 'Chapter' in section:
section['Chapter']['content'] = remove_sphinx_markdown(section['Chapter']['content'])
for s in section['Chapter']['sub_items']:
process_section(s)

if __name__ == '__main__':
if len(sys.argv) > 1: # we check if we received any argument
if sys.argv[1] == "supports":
# then we are good to return an exit status code of 0, since the other argument will just be the renderer's name
sys.exit(0)

# load both the context and the book representations from stdin
context, book = json.load(sys.stdin)

for section in book['sections']:
process_section(section)

# we are done with the book's modification, we can just print it to stdout
print(json.dumps(book))

0 comments on commit 8040546

Please sign in to comment.