#!/usr/bin/python

# Tries to enforce exactly two newlines before a function definition.
# Beware: This is not yet optimal. Do not use it yet.

import sys, os, re


if "--debug" in sys.argv:
    opt_debug = True
    sys.argv.remove("--debug")
else:
    opt_debug = False


def main():
    for filename in sys.argv[1:]:
        try:
            sys.stdout.write("%s..." % filename)
            sys.stdout.flush()
            something_changed = cleanup_indentation_style(filename)
            sys.stdout.write(something_changed and "done.\n" or "unchanged.\n")

        except Exception, e:
            sys.stdout.write("ERROR: %s\n" % e)
            if opt_debug:
                raise


def cleanup_indentation_style(filename):
    content = file(filename).read()
    new_content = content
    new_content = fix_two_empty_lines_before_indented_commented_def(new_content)
    if new_content != content:
        file(filename, "w").write(new_content)
        return True
    else:
        return False

def fix_two_empty_lines_before_indented_commented_def(content):
    return re.sub(r"\n+(([ \t]*#[^\n]*\n)*)(\s*)def ", r"\n\n\n\1\3def ", content)

main()
