#!/usr/bin/python
# encoding=UTF-8

# Copyright © 2011, 2012 Jakub Wilk
#
# This program is free software.  It is distributed 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.
#
# This program 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
# this program.  If not, you can find it on the World Wide Web at
# http://www.gnu.org/copyleft/gpl.html, or write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import re
import sys

import pyflakes.scripts.pyflakes as flakes
import pyflakes.messages

class CompileError(Exception):
    pass

original_compile = compile

def my_compile(*args, **kwargs):
    # pyflakes itself doesn't catch all exceptions that could be raised by compile().
    # See bugs #674796 and #674797.
    try:
        return original_compile(*args, **kwargs)
    except Exception, ex:
        raise CompileError(ex)

__builtins__.compile = my_compile

def Message_str(self):
    tag = re.sub('[A-Z]', lambda m: '-' + m.group(0).lower(), type(self).__name__)
    arg_types = []
    tp = str
    for s in re.split('(%.)', self.message):
        if len(s) == 2:
            if s[0] == '%' and s[1] != '%':
                arg_types += [tp]
        if s.endswith(' line '):
            tp = lambda x: 'line ' + str(x)
        else:
            tp = str
    extra_args = [tp(arg) for arg, tp in zip(self.message_args, arg_types)]
    return 'pyflakes{tag} {line}: {args}'.format(
        tag=tag,
        line=self.lineno,
        args=' '.join(extra_args)
    )
pyflakes.messages.Message.__str__ = Message_str

if __name__ == '__main__':
    sys.stderr = sys.stdout
    for filename in sys.argv[1:]:
        print '# {0}'.format(filename.replace('\n', '?'))
        try:
            flakes.checkPath(filename)
        except CompileError:
            pass

# Local Variables:
# indent-tabs-mode: nil
# End:
# vim: syntax=python sw=4 sts=4 sr et
