wkentaro
9/5/2015 - 1:03 PM

split_readme.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import argparse

import inflection


parser = argparse.ArgumentParser()
parser.add_argument('filename', default='README.md')
args = parser.parse_args()

with open(args.filename) as f:
    readme = f.read()


pre_sections, sections = [], []
for line in readme.split('\n'):
    if re.match('^### .*', line):
        sections.append([])
    if sections:
        sections[-1].append(line)
    else:
        pre_sections.append(line)


# pre sections
with open('pre_sections.md', 'w') as f:
    f.writelines('\n'.join(pre_sections))


def transform_section_content(lines):
    for line in lines:
        if line.startswith('### '):
            line = line[2:]
        elif line.startswith('#### '):
            line = line[2:]
        yield line

for section in sections:
    header = section[0]
    m = re.match('^### ', header)
    title = header[m.end():].replace('\\', '')
    title = title.replace('jsk_perception/', '')
    title = title.replace('jsk_pcl/', '')
    filename = inflection.underscore(title) + '.md'
    filename = os.path.join('doc', filename)
    with open(filename, 'w') as f:
        section = transform_section_content(section)
        f.write('\n'.join(section))