#!/usr/bin/env python3

#   Copyright (c) MediaTek USA Inc., 2020-2024
#
#   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, see
#   <http://www.gnu.org/licenses/>.
#
#
# This script traverses XML coverage data in one or more coverage data file
# (in Cobertura format - as generated by Cobertura or by the Coverage.py
# module - or in JaCoCo report format) and translates it into LCOV .info
# format.
#
#   xml2lcov [--output mydata.info] [--test-name name] [options] coverage.xml+
#
# See 'xml2lcov --help' for more usage information
#
# See the Cobertura or JaCoCo documentation to see how to generate the XML
# coverage data

import os
import os.path
import sys
import re
import argparse

# Windows path handling - see comments in py2lcov and xml2lcovutil.py
_dir = os.path.dirname(sys.argv[0].replace('\\', '/'))
if re.match(r'^[A-Za-z]:/', _dir):
    _mounts = ['', '/cygdrive']
    if 'LCOV_DRIVE_MOUNT' in os.environ:
        _mounts.insert(0, os.environ['LCOV_DRIVE_MOUNT'])
    _drive = _dir[0].lower()
    _dir = next((m + '/' + _drive + _dir[2:] for m in _mounts
                 if os.path.isdir(m + '/' + _drive)), _dir)
if _dir and _dir not in sys.path:
    sys.path.insert(0, _dir)

from xml2lcovutil import ProcessFile

def main():
    usageString="""xml2lcov: Translate XML coverage data (e.g., generated by Cobertura
or by JaCoCo) to LCOV .info format.
See the Cobertura or JaCoCo documentation for information on how to generate
the XML coverage data file.

Note that xml2lcov does not implement the full suite of LCOV features
(e.g., demangling, filtering, substitutions, etc.).
Please generate the translated LCOV format file and then read the data
back in to lcov to use any of those features.
%(usage)s%(jacoco)s
Example:

     # generate the LCOV-format .info file
   $ xml2lcov -o mydata.info coverage1.xml coverage2.xml

     # the same, from a JaCoCo XML report:  JaCoCo does not record where the
     # source files are, so tell xml2lcov where to look
   $ xml2lcov -o mydata.info -s src -s generated/src jacoco.xml

     # apply some filtering
   $ lcov -a mydata.info --filter branch,blank -o filtered.info

     # and use genhtml to produce an HTML coverage report:
   $ genhtml -o html_report mydata.info ....
   $ genhtml -o html_filtered filtered.info ....
     # use differential coverage to see exactly what filtering did
   $ genhtml -o html_differential --baseline-file mydata.info filtered.info ...

   """ % {
       'usage' : ProcessFile.usageNote,
       'jacoco' : ProcessFile.jacocoNote,
       }

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=usageString)

    parser.add_argument('-o', '--output', dest='output', default='xml2lcov.info',
                        help="specify the out LCOV .info file, default: xml2lcov.info")
    parser.add_argument('-t', '--test-name', '--testname', dest='testName', default='',
                        help="specify the test name for the TN: entry in LCOV .info file")
    parser.add_argument('-e', '--exclude', dest='excludePatterns', default='',
                        help="specify the exclude file patterns separated by ','")
    parser.add_argument('--format', dest='format', default='auto',
                        choices=['auto', 'cobertura', 'jacoco'],
                        help="input XML schema, default: auto - which uses the XML root element to tell 'coverage' (Cobertura) from 'report' (JaCoCo)")
    parser.add_argument('-s', '--source-directory', '--source-dir',
                        dest='sourceDirectories', default=[], action='append',
                        help="directory to search for source files - may be repeated.  Searched after the directories the XML itself names, and the only search path for JaCoCo XML, which names none")
    parser.add_argument('-v', '--verbose', dest='verbose', default=0, action='count',
                        help="print debug messages")
    parser.add_argument('--version-script', dest='version',
                        help="version extract callback")
    parser.add_argument('--checksum', dest='checksum', action='store_true',
                        default=False,
                        help="compute line checksum - see 'man lcov'")
    parser.add_argument('-k', "--keep-going", dest='keepGoing', default=False, action='store_true',
                        help="ignore errors")
    parser.add_argument('inputs', nargs='*',
                        help="list of XML coverage data input files - expected to be XML or Python .dat format")

    args = parser.parse_args()

    if not args.inputs:
       print("Error:  no input files")
       sys.exit(1)

    p = ProcessFile(args)

    for f in args.inputs:
        p.process_xml_file(f)

    p.close()


if __name__ == '__main__':
    main()
