#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Antoine Durand-Gasselin
# Author: Antoine Durand-Gasselin <adg@crans.org>
#

import commands, os, sys
from affich_tools import cprint, ERREUR

EXCEPTIONS = ["./gestion/ldap_crans.py"]


def goto_darcs_root ():
    while not os.path.exists('_darcs') and os.getcwd() != '/':
        os.chdir('..')
    if not os.path.exists('_darcs'):
        cprint("Pas de dépôt darcs trouvé")
        sys.exit(1)
    cprint("Dans le repo darcs %s" % os.getcwd(), "bleu")

def darcs_modified ():
    ret, msg = commands.getstatusoutput('darcs whatsnew -s')
    if ret:
        cprint(ERREUR)
        print msg
    changes = msg.split('\n')
    python_files = []
    for i in changes:
        if i[0] in ['A', 'M'] and i.split()[1][-3:] == '.py':
            python_files.append(i[2:].split()[0])

    return python_files



def pylint_check ():
    files = darcs_modified()
    erreurs = ""
    will_fail = False
    l = len(files)
    f = 1
    for file in files:
        print
        cprint (u"[%d/%d] Vérification de %s" % (f, l, file), "gras")
        f += 1
        ret, output = commands.getstatusoutput('pylint %s' % file)
        msg = output.split('\n')
        is_fatal = False
        fatals = []
        has_errors = False
        errors = []
        for i in msg:
            if i[:2] == 'F:' :
                is_fatal = True
                fatals.append(i)
                will_fail = True
            if i[:2] == 'E:' :
                has_errors = True
                errors.append(i)

        if is_fatal:
            cprint ("%s a des erreurs fatales:" % file, 'rouge')
            print '\n'.join([ 4*' '+i for i in fatals])
        elif has_errors:
            cprint ("%s est sûrement plein d'erreurs" % file, 'jaune')
            print '\n'.join([ 4*' '+i for i in errors])
            if file not in EXCEPTIONS:
                will_fail = True
            else:
                cprint('Mais on s\'en fout: on sait que %s est trop sale' % file , 'rouge')
        else:
            cprint ('    OK', 'vert')

    if not will_fail:
        ret, output = commands.getstatusoutput('pylint %s' % ' '.join(files))
        print output
    else:
        sys.exit(1)


if __name__ == '__main__':
    goto_darcs_root()
    pylint_check ()
