"""
Utility functions that map information from environments onto package cache
"""

from environment import Environment, environments


def packages_in_cache(env):
    """
    Determine whether a linked package in an environment still exists in cache.
    :param package: PackageInfo
    :return: bool
    """

    packages = env._packages


def hard_linked(env):
    """
    Return all packages that are hard-linked into env
    :param env:
    :return:
    """
    environ = Environment(env)
    return environ._link_type_packages(link_type='hard-link')


def explicitly_installed(env):
    environ = Environment(env)
    current_pkgs = set(environ.package_specs)
    
    hist = environ.history

    # Map date to explicitly installed package specs
    _ci = {'install', 'create'}
    installed_specs = {x['date']: set(t.split()[0] for t in x['specs']) for x in hist.get_user_requests if x['action'] in _ci}

    # See what packages were actually installed
    actually_installed = {date: set(pkg_spec) for date, pkg_spec in hist.construct_states}    
    for date, specs in installed_specs.items():
        # Translate name only spec to full specs
        name_spec = {x for x in actually_installed[date] if x.split('-')[0] in specs}
        actually_installed[date] = name_spec

    # Intersect with currently installed packages
    actually_installed = {date: specs.intersection(current_pkgs) for date, specs in actually_installed.items()}
    return actually_installed
        




@@ -78,16 +78,55 @@
 he%0A%22%22%22%0A%0A
+from os.path import join%0A%0Aimport utils%0A
 from env
@@ -167,16 +167,46 @@
 onments%0A
+from cache import PackageInfo%0A
 %0A%0Adef pa
@@ -568,16 +568,36 @@
  return 
+%7Bp.name: p for p in 
 environ.
@@ -642,41 +642,791 @@
 nk')
-%0A%0A%0Adef explicitly_installed(env):
+%7D%0A%0Adef check_hardlinked_env(env):%0A    %22%22%22%0A    Check all hardlinked packages in env%0A    %22%22%22%0A    return %7Bk: check_hardlinked_pkg(env, v) for k, v in hard_linked(env).items()%7D%0A%0A%0Adef check_hardlinked_pkg(env, Pkg):%0A    %22%22%22%0A    Check that pkg in cache is correctly (ie completely) hardlinked into env.%0A    :param env: path to environments%0A    :param Pkg: PackageInfo object%0A    :return: list%3Cstr%3E list of bad hard links%0A    %22%22%22%0A%0A    bad_linked = %5B%5D%0A    for f in Pkg.files:%0A        src = join(Pkg.path, f)%0A        tgt = join(env, f)%0A        if not utils.is_hardlinked(src, tgt):%0A            bad_linked.append(f)%0A    return bad_linked%0A%0A%0Adef explicitly_installed(env):%0A    %22%22%22%0A    Return list of explicitly installed packages.%0A    Note that this does not work with root environments%0A    %22%22%22%0A
 %0A   

Add queries for checking hardlinked packages