#!/usr/bin/env python

import os, sys

def coverage_all(directory):
    os.chdir(directory)
    r = os.popen('sage-coverage * | grep SCORE').readlines()

    s = []
    scr = 0
    total = 0
    for x in r:
        y = x.lstrip('SCORE ')
        i = y.rfind(' of ')
        j = y.rfind(')')
        n = int(y[i+4:j])

        i = y.rfind(':')
        j = y.rfind('%')
        scr += float(y[i+1:j]) * float(n)

        total += n

        s.append(y)

    print(''.join(s))

    # Trac #5859: Don't crash if there isn't anything to test.
    score = 100.0
    if total != 0:
        score = (float(scr) / total)

    print("Overall weighted coverage score: {:.1f}%".format(score))
    print("Total number of functions: {}".format(total))

    # Print up to 3 doctest coverage goals.
    i = 0
    for goal in [70, 75, 80, 85, 90, 95, 99]:
        if score < goal:
            i += 1
            if i > 3: break
            need = int((goal*total - scr)/100.0)
            print("We need {:>4} more function{} to get to {}% coverage."
                  .format(need, "" if (need == 1) else "s", goal))

if len(sys.argv) == 1:
    coverage_all(os.path.join(os.environ["SAGE_SRC"], 'sage'))
else:
    coverage_all(sys.argv[1])
