#!/usr/bin/env python
# This file is part of the Ranvier package.
# See http://furius.ca/ranvier/ for license and details.

"""ranvier-coverage-report [<options>] <URL> <connect-string>

Return coverage report from a Ranvier coverage results database.

The given <connect-string> decides which of the backends to use, e.g.

   dbm:///tmp/ranvier.coverage.dbm
   postgres://user:password@host/database
   ...

Note: this supports just some of the basic coverage results.  The return code is
meant to reflect if therer were errors or not, so that you can use this as part
of your tests.
"""

# stdlib imports.
import sys

# ranvier imports.
from ranvier import *

#-------------------------------------------------------------------------------
#
def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())

    parser.add_option('-q', '--quiet', action='store_true',
                      help="Only print errors.")

    parser.add_option('-i', '--ignore-id', action='append',
                      default=[],
                      help="Specify resource it that cannot be handled, "
                      "to ignore.")

    parser.add_option('-I', '--ignore-file', action='store',
                      help="Specify a file that contains a list of resource "
                      "ids that cannot be handled, to ignore.")

    opts, args = parser.parse_args()

    if len(args) != 2:
        parser.error("You must specify a resource map URL and a single "
                     "coverage database file.")
    url, connstr = args

    # Read the list of resource ids to ignore.
    ignore_ids = opts.ignore_id
    if opts.ignore_file:
        ignore_ids.extend(
            map(str.strip, open(opts.ignore_file, 'r').readlines()))
    
    # Fetch the list of resources and build the URL mapper from it.
    mapper = UrlMapper.urlload(url)
    
    # Create a coverage reporter that can read the coverage info.
    try:
        reporter = create_coverage_reporter(connstr)
    except RanvierError, e:
        raise SystemExit(e)

    # Get coverage info.
    coverage = reporter.get_coverage()

    # Render the output.
    output, errors, herrors, rerrors = \
        coverage_render_cmdline(mapper, coverage, ignore_ids, ignore_ids)
    if not opts.quiet:
        sys.stdout.write(output)
    sys.stderr.write(errors)

    if herrors:
        return 2
    elif rerrors:
        return 1
    else:
        return 0

if __name__ == '__main__':
    sys.exit(main())

