1. Jonathan Fine
  2. javascript-for-python-programmers

Source

javascript-for-python-programmers / core-javascript / py / remove_answers.py

'''Remove answers from exercises file.'''

import os
import sys

NORMAL, SKIPPING, ERROR = range(3)
LINE, SOMETHING, START, STOP = range(4)

lookup = {}

# All other states are an error.
lookup[NORMAL, LINE] = NORMAL
lookup[NORMAL, SOMETHING] = NORMAL
lookup[NORMAL, START] = SKIPPING
lookup[SKIPPING, LINE] = SKIPPING
# lookup[NORMAL, STOP] = ERROR
# lookup[SKIPPING, SOMETHING] = ERROR
lookup[SKIPPING, STOP] = NORMAL


def doit(src, tgt):

    pending = []
    with open(src, 'rb') as lines:

        new_state = NORMAL

        for lineno, line in enumerate(lines):

            state = new_state


            stripped_line = line.strip()

            if stripped_line.startswith('something'):
                event = SOMETHING

            elif stripped_line == '// start':
                event = START

            elif stripped_line == '// stop':
                event = STOP

            else:
                event = LINE

            new_state = lookup[state, event]

            if event == SOMETHING:
                pass

            elif event == STOP:
                pass

            elif event == START:
                indent = len(line) - len(line.lstrip())
                spaces = line[0:indent]
                pending.append(spaces + '// Please write your answer here.')

            elif state == SKIPPING:
                pass

            elif event == LINE:
                pending.append(line.rstrip())


        with open(tgt, 'wb') as f:

            for line in pending:
                f.write(line + '\r\n')



if __name__ == '__main__':


    root = 'javascript-exercises'
    exercises_dir = root
    answers_dir = os.path.join(root, 'answers')


    names = [
        name
        for name in os.listdir(answers_dir)
        if name.endswith('.js')
        ]


    for name in names:

        src = os.path.join(answers_dir, name)
        tgt = os.path.join(exercises_dir, name)

        print name
        doit(src, tgt)