Skip to content

Commit

Permalink
Dev: doc/toolchain: implement help2adoc (ClusterLabs#1374)
Browse files Browse the repository at this point in the history
convert help text generated by python's argparse to asciidoc
  • Loading branch information
nicholasyang2022 committed Apr 17, 2024
1 parent 300e209 commit d490294
Show file tree
Hide file tree
Showing 5 changed files with 413 additions and 0 deletions.
5 changes: 5 additions & 0 deletions doc/toolchain/bin/help2adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash
set -e
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
export PYTHONPATH=$(readlink -f "${SCRIPT_DIR}"/../lib)
python3 -m help2adoc.main "$@"
Empty file.
51 changes: 51 additions & 0 deletions doc/toolchain/lib/help2adoc/generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from .parser import Parser

import typing
import re


class AsciiDocGenerator(Parser):
USAGE_RE = re.compile('^usage:\\s*')

def __init__(self, output: typing.Callable[[str], None]):
self.output = output

def on_usage(self, text: str):
usage = text[self.USAGE_RE.match(text).end():]
self.output('Usage:\n\n ')
self.output(usage)
self.output('\n\n')

def on_paragraph(self, text: str):
self.output(self.escape(text))
self.output('\n\n')

def enter_options(self):
self.output('Options:\n\n')

def exit_options(self):
self.output('\n')

def on_option(self, option: str, help: str):
self.output('* `+++')
self.output(option)
self.output('+++`: ')
self.output(self.escape(help))
self.output('\n\n')

def enter_option_group(self, name: str):
self.output(name)
self.output(':\n\n')

def exit_option_group(self, name: str):
self.output('\n')

def enter_description(self):
pass

def exit_description(self):
pass

def escape(self, text: str):
# TODO
return text
28 changes: 28 additions & 0 deletions doc/toolchain/lib/help2adoc/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from .parser import lexer, LookAheadIterator
from .generator import AsciiDocGenerator

from argparse import ArgumentParser
import sys

def main():
ap = ArgumentParser('help2adoc')
ap.add_argument('file')
args = ap.parse_args()
with open(args.file, 'r') as f:
tokens = LookAheadIterator(lexer(f))
AsciiDocGenerator(sys.stdout.write).parse_help(tokens)
token = tokens.lookahead()
if token is None:
return
epilog_start = token.lineno
f.seek(0)
for i in range(epilog_start):
next(f)
print('....')
for line in f:
print(line, end='')
print('....')


if __name__ == '__main__':
main()
Loading

0 comments on commit d490294

Please sign in to comment.