#!/usr/bin/env python
#
# filterator -- filter and format the output of comparator
#
import sys, comparator, re

def shortreport(clique):
    rep = ""
    (file, start, end, text) = state.extract_text(clique)
    if start == 1 and end == state.files[file]:
        rep += "%% %s:%d-%d: entire (%d matches)\n" % \
              (file, start, end, len(clique))
    else:
        rep += "%% %s:%d-%d: (%d matches)\n" % \
              (file, start, end, len(clique))
        rep += text
    rep += 75 * "-" + "\n"
    return rep

def longreport(clique):
    rep = ""
    (tfile, tstart, tend, text) = state.extract_text(clique)
    for (file, start, end) in clique:
        if start == 1 and end == state.files[file]:
            rep += "%% %s:%d-%d: (entire)\n" % (file, start, end)
        else:
            rep += "%% %s:%d-%d:\n" % (file, start, end)
    rep += text
    rep += 75 * "-" + "\n"
    return rep

if __name__ == '__main__':
    # Main line begins here
    import getopt
    try:
        (optlist, args) = getopt.getopt(sys.argv[1:], 'd:f:F:m:n')
    except getopt.GetoptError:
        sys.stderr.write("usage: filterator [-n] [-d dir] [-m size] [-f filter] [-F matchfile]\n")
        sys.exit(2)
    dir = None
    filter = None
    minsize = 5
    expand = True
    matchfiles = []
    linecounts = {}
    for (opt, val) in optlist:
        if opt == '-d':
            dir = val
        elif opt == '-f':
            filter = re.compile(val)
        elif opt == '-F':
            fp = open(val, "r")
            matchfiles = map(lambda x: x.strip(), fp.readlines())
            fp.close()
        elif opt == '-m':
            minsize = int(val)
        elif opt == '-n':
            expand = False

    try:
        state = comparator.CommonReport(sys.stdin, dir)
        if minsize:
            state.cliquefilter(lambda file,start,end: end-start+1 >= minsize)
        if filter:
            state.cliquefilter(lambda file, start, end: filter.search(file))
        if matchfiles:
            state.cliquefilter(lambda file, start, end: file in matchfiles)
        try:
            if expand:
                state.metadump(sys.stdout, (75 * '-')+"\n", longreport, {"Minimum-Size":minsize})
            else:
                state.dump(sys.stdout)
        except (KeyboardInterrupt, IOError):
            pass
    except comparator.ComparatorException, e:
        sys.stderr.write("filterator: " + e.message + "\n")
        sys.exit(1)

# End

