#
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#

import os


# pylint: disable=unused-variable
def tar_records(tar_file):
    records = {}

    while True:
        member_info = tar_file.next()
        if member_info is None:
            break

        member_file = tar_file.extractfile(member_info)
        if member_file is None:
            # memberFile was not a regular file, for instance directory
            continue

        if not member_info.isfile:
            continue

        key, ext = os.path.splitext(member_info.name)
        ext = ext[1:]  # remove leading .

        if not is_valid_tar_entry(key, ext):
            continue

        record = records.get(key, {})
        record["__key__"] = key
        record[ext] = member_file.read()
        records[key] = record

    return records


def is_valid_tar_entry(key, ext):
    if ext not in [
            "jpg", "cls", "json", "png", "jpeg", "bmp"
    ] and not (str.startswith("lab") or str.startswith("cls" or str)):
        return False

    # garbage generated by macos
    if os.path.basename(key).startswith("._"):
        return False

    return True
