#!/usr/bin/env python
#
# Copyright (C) 2001,2002,2003 Jason R. Mastaler <jason@mastaler.com>
#
# This file is part of TMDA.
#
# TMDA is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  A copy of this license should
# be included in the file COPYING.
#
# TMDA is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""
Recursively byte-compile all .py files in the given directory tree.

Based on code from Python's compileall module
Copyright (C) Python Software Foundation.
"""

import os
import sys
import py_compile


# If running Python 2.1, skip compilation of these files.
py21_ignore = ['_compat22.py']


def compile_dir(dir, maxlevels=10, ddir=None):
    major, minor = sys.version_info[0:2]
    if major == 2 and minor == 1:
        py21 = 1
    else:
        py21 = 0
    #print 'Listing', dir, '...'
    try:
        names = os.listdir(dir)
    except os.error:
        print "Can't list", dir
        names = []
    names.sort()
    success = 1
    for name in names:
        if py21 and name in py21_ignore:
            continue
        fullname = os.path.join(dir, name)
        if ddir:
            dfile = os.path.join(ddir, name)
        else:
            dfile = None
        if os.path.isfile(fullname):
            head, tail = name[:-3], name[-3:]
            if tail == '.py':
                cfile = fullname + (__debug__ and 'c' or 'o')
                print 'Compiling', fullname, '...'
                try:
                    py_compile.compile(fullname, None, dfile)
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    if type(sys.exc_type) == type(''):
                        exc_type_name = sys.exc_type
                    else: exc_type_name = sys.exc_type.__name__
                    print 'Sorry:', exc_type_name + ':',
                    print sys.exc_value
                    success = 0
        elif maxlevels > 0 and \
             name != os.curdir and name != os.pardir and \
             os.path.isdir(fullname) and \
             not os.path.islink(fullname):
            compile_dir(fullname, maxlevels - 1, dfile)
    return success


def main():
    dir = os.path.dirname(sys.argv[0])
    success = 1
    try:
        success = success and compile_dir(dir)
    except KeyboardInterrupt:
        print "\n[interrupt]"
        success = 0
    return success

if __name__ == '__main__':
    sys.exit(not main())
