view docs/test2rst.py @ 5657:6e37ce7be367 stable

test2rst: remove the abandoned index building part
author Anton Shestakov <av6@dwimlabs.net>
date Mon, 09 Nov 2020 23:03:31 +0800
parents 60ce376919c5
children 5ea837c515d9
line wrap: on
line source

#!/usr/bin/env python

import os
import re
import sys


ignored_patterns = [
    re.compile(r'^#if'),
    re.compile(r'^#else'),
    re.compile(r'^#endif'),
    re.compile(r'#rest-ignore$'),
]


def rstify(orig):
    newlines = []

    code_block_mode = False
    sphinx_directive_mode = False

    for line in orig.splitlines():

        # Emtpy lines doesn't change output
        if not line:
            newlines.append(line)
            code_block_mode = False
            sphinx_directive_mode = False
            continue

        ignored = False
        for pattern in ignored_patterns:
            if pattern.search(line):
                ignored = True
                break
        if ignored:
            continue

        # Sphinx directives mode
        if line.startswith('  .. '):

            # Insert a empty line to makes sphinx happy
            newlines.append("")

            # And unindent the directive
            line = line[2:]
            sphinx_directive_mode = True

        # Code mode
        codeline = line.startswith('  ')
        if codeline and not sphinx_directive_mode:
            if code_block_mode is False:
                newlines.extend(['::', ''])

            code_block_mode = True

        newlines.append(line)

    return "\n".join(newlines)


def main(base):
    if os.path.isdir(base):
        one_dir(base)
    else:
        one_file(base)


def one_dir(base):
    for fn in sorted(os.listdir(base)):
        if not fn.endswith('.t'):
            continue
        one_file(os.path.join(base, fn))


def one_file(path):
    with open(path) as f:
        content = f.read()
    rst = rstify(content)
    target = os.path.splitext(path)[0] + '.rst'
    with open(target, 'w') as f:
        f.write(rst)


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Please supply a path to tests dir as parameter')
        sys.exit()
    main(sys.argv[1])