#!/usr/bin/python

import compiler, sys
import os
from pyflakes import checker

# exit status
status = 0

def check(codeString, filename):
    global status
    try:
        tree = compiler.parse(codeString)
    except (SyntaxError, IndentationError):
        value = sys.exc_info()[1]
        try:
            (lineno, offset, line) = value[1][1:]
        except IndexError:
            print >> sys.stderr, 'could not compile %r' % (filename,)
            return 1
        if line.endswith("\n"):
            line = line[:-1]
        print >> sys.stderr, '%s:%d: could not compile' % (filename, lineno)
        print >> sys.stderr, line
        print >> sys.stderr, " " * (offset-2), "^"
        status = 2
    except UnicodeError, msg:
        print >> sys.stderr, 'encoding error at %r: %s' % (filename, msg)

    except UnicodeError, msg:
        print >> sys.stderr, 'encoding error at %r: %s' % (filename, msg)
        status = 2
    else:
        w = checker.Checker(tree, filename)
        w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
        for warning in w.messages:
            print warning
            if status == 0 and len(w.messages) > 0:
                status = 1
        return len(w.messages)


def checkPath(filename):
    if os.path.exists(filename):
        fd = file(filename, 'U')
        try:
            return check(fd.read(), filename)
        finally:
            fd.close()

def main(args):
    warnings = 0
    if args:
        for arg in args:
            if os.path.isdir(arg):
                for dirpath, dirnames, filenames in os.walk(arg):
                    for filename in filenames:
                        if filename.endswith('.py'):
                            warnings += checkPath(os.path.join(dirpath, filename))
            else:
                warnings += checkPath(arg)
    else:
        warnings += check(sys.stdin.read(), '<stdin>')
    
    raise SystemExit(warnings > 0)

if __name__ == '__main__':
    main(sys.argv[1:])
    sys.exit(status)
