From 54c91ed1eabbd3f3b39093dabc392fa2885217a2 Mon Sep 17 00:00:00 2001 From: Caleb Foust Date: Sun, 26 Nov 2023 19:47:56 -0500 Subject: [PATCH] feat: Markdown story replacement --- .github/workflows/docs.yml | 9 ++++--- docs/book.toml | 3 +++ docs/storybook.py | 55 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 docs/storybook.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 9ac16f8e..0d259607 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -24,6 +24,11 @@ jobs: curl -sSL $url | tar -xz --directory=./mdbook echo `pwd`/mdbook >> $GITHUB_PATH + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.19" + - name: Build book run: | go run cmd/docs/main.go api > docs/src/generated-api.md @@ -35,10 +40,6 @@ jobs: with: repository: cfoust/cy - - name: Set up Go - uses: actions/setup-go@v4 - with: - go-version: "1.19" - name: Build run: > go build diff --git a/docs/book.toml b/docs/book.toml index 9ed9e0b1..b32b9257 100644 --- a/docs/book.toml +++ b/docs/book.toml @@ -9,3 +9,6 @@ authors = ["Caleb Foust"] [output.html] default-theme = "ayu" preferred-dark-theme = "ayu" + +[preprocessor.storybook] +command = "python3 storybook.py" diff --git a/docs/storybook.py b/docs/storybook.py new file mode 100644 index 00000000..a3862ec2 --- /dev/null +++ b/docs/storybook.py @@ -0,0 +1,55 @@ +import json +import sys +import re +import hashlib + +STORY_REGEX = re.compile("{{((\w+).)?(png|gif) (.+)}}") + +if __name__ == '__main__': + args = sys.argv + if len(args) > 1 and args[1] == "supports": + sys.exit(0) + + context, book = json.load(sys.stdin) + + # all the rendering jobs that need to be done + jobs = {} + + for section in book['sections']: + if not 'Chapter' in section: + continue + + content = section['Chapter']['content'] + replace = [] + + for ref in STORY_REGEX.finditer(content): + type_ = ref.group(3) + filename = ref.group(2) + command = ref.group(4) + if len(command) == 0: + continue + + # The filename is the hash of the args, or can be specified in + # Markdown + if not filename: + h = hashlib.new('sha256') + h.update(command.encode('utf-8')) + filename = h.hexdigest()[:12] + + filename += "." + type_ + + jobs[filename] = command + replace.append( + ( + ref.start(0), + ref.end(0), + f"![{command}](./stories/{filename})", + ) + ) + + for start, end, text in reversed(replace): + content = content[:start] + text + content[end:] + + section['Chapter']['content'] = content + + print(json.dumps(book))