#!/usr/bin/env python

import argparse
import compileall
import os


# This is _walk_dir from the Python 3 version of compileall, slightly modified
# to support Python 2.7.
def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
    if not quiet:
        print('Listing {!r}...'.format(dir))
    try:
        names = os.listdir(dir)
    except OSError:
        if quiet < 2:
            print("Can't list {!r}".format(dir))
        names = []
    names.sort()
    for name in names:
        if name == '__pycache__':
            continue
        fullname = os.path.join(dir, name)
        if ddir is not None:
            dfile = os.path.join(ddir, name)
        else:
            dfile = None
        if not os.path.isdir(fullname):
            yield fullname
        elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
              os.path.isdir(fullname) and not os.path.islink(fullname)):
            for f in _walk_dir(fullname, ddir=dfile, maxlevels=maxlevels - 1,
                               quiet=quiet):
                yield f


if __name__ == '__main__':
    # Parse command line arguments.
    parser = argparse.ArgumentParser(
        description='Compile Python files to pyc files and delete the source.')
    parser.add_argument('--version', action='version', version='%(prog)s v0.2')

    parser.add_argument('path', nargs='*', default='.',
                        help='Paths to dirty')

    args = parser.parse_args()

    # Compile python along each path.
    exit_status = 0
    for dest in args.path:
        # This is based on the code from the __main__ of compileall. Compile the
        # file (or directory) and then remove the file (or recursively remove
        # files in a directory).
        if os.path.isfile(dest):
            if compileall.compile_file(dest, quiet=True):
                os.remove(dest)
            else:
                exit_status = 1
        else:
            if compileall.compile_dir(dest, quiet=True):
                for name in _walk_dir(dest, quiet=True):
                    if name[-3:] == '.py':
                        os.remove(name)
            else:
                exit_status = 1

    # Exit with a reasonable exit status.
    exit(exit_status)
