import yaml


def read_conda_environments(env_paths: list):
    """
    Read in a list of paths to yaml conda environment definitions.

    Used to create package whitelists for conda-mirror

    :param env_paths: A list of paths to conda environment definition yaml files
    :return: a list of packages defined in the environment.
    The package is a dictionary with a "name" member and optional
    "version" and "build" members.
    """
    packages = []
    for env_path in env_paths:
        with open(env_path, "rt") as f:
            env = yaml.safe_load(f)
            for dep in env["dependencies"]:

                # dep is in format <name>=<version>=<build>
                # but version and build are optional

                pkg_vals = dep.strip().split('=')
                pkg = {"name": pkg_vals[0]}
                if len(pkg_vals) > 1:
                    pkg["version"] = pkg_vals[1]
                if len(pkg_vals) > 2:
                    pkg["build"] = pkg_vals[2]
                packages.append(pkg)
    return packages