import re


def _get_coverage_map(tree, file):
    """
    Get a map of which lines are covered for a specified file
    :param tree: an element tree for the jacoco coverage report xml
    :param file: the file to find coverage for
    :return: a map of int -> boolean with a key of lines we have info for and value of whether or not it's covered
    """

    # skip files that are in the root directory
    if "/" not in file:
        return None

    # split file into group/package/filename as defined in jacoco's report
    file_info = re.search(r"(.*?)/src/.*?/((?:com|ca)/.*)\/(.*?\.java)", file)

    # skip files that don't match this
    if not file_info or len(file_info.groups()) != 3:
        return None

    group, package, file_name = file_info.groups()
    group = group.split("/")[-1]

    # look up the source file info in the report
    lookup = "group[@name='{}']/package[@name='{}']/sourcefile[@name='{}']".format(
        group, package, file_name
    )
    source_tree = tree.find(lookup)

    if not source_tree:
        print("Couldn't find a test coverage file for " + lookup)
        return []

    # search for lines with coverage information
    coverage_map = {}
    for line in source_tree.findall("line"):
        line_number = int(line.attrib["nr"])
        # We considered Covered = True if there are no missed instructions(mi) or missed branches(mb) in jacoco's info
        coverage_map[line_number] = (
            line.attrib["mi"] == "0" and line.attrib["mb"] == "0"
        )

    return coverage_map