#!/bin/env python
# checkStat.py
#
#    ========== licence begin  GPL
#    Copyright (C) 2001 SAP AG
#
#    This program 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.
#
#    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, write to the Free Software
#    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#    ========== licence end
#


import string
import regex
import os

_errRE = regex.compile ('.*/\(.*\)([0-9]+):\([^:]*\):')

def incrCounter (dict, key):
    try:
        count = dict [key]
    except KeyError:
        count = 0
    count = count + 1
    dict [key] = count


class ErrorCounter:
    def __init__ (self):
        self.byError = {}
        self.byModule = {}

    def addFile (self, fname):
        split = string.split
        byError = self.byError
        byModule = self.byModule
        lines = open (fname, 'r').readlines ()
        for line in lines:
            try:
                if _errRE.match (line) == -1:
                    pass
                    # print 'no match for', line [:-1]
                else:
                    module, errkind = _errRE.group (1, 2)
                    words = split (errkind)
                    key = (words [1], words [2])
                    incrCounter (byError, key)
                    incrCounter (byModule, module)
            except:
                pass
                # print 'Error in ', line

    def addDir (self, dirname):
        files = os.listdir (dirname)
        join = os.path.join
        for filename in files:
            if filename [-5:] == '.cchk':
                self.addFile (join (dirname, filename))

    def dump (self):
        print 'Sorted by Error:'
        items = self.byError.items ()
        items.sort ()
        for key, count in items:
            code, name = key
            print "%-5s %15s: %6d" % (code, name, count)
        print 'Sorted by Module:'
        items = self.byModule.items ()
        items.sort ()
        for module, count in items:
            print "%-20s: %6d" % (module, count)

def main (options, args):
    counter = ErrorCounter ()
    for arg in args:
        if os.path.isdir (arg):
            counter.addDir (arg)
        else:
            counter.addFile (arg)
    counter.dump ()

def _options ():
    return [
        # (optstring, varname, typechar, default, help)
        ]

if __name__ == '__main__':
    import sys
    main (None, sys.argv [1:])
