.. versionchanged:: 2018.3.0
        If the loaded image should be tagged, then the repository and tag must
        now be passed separately using the ``repository`` and ``tag``
        arguments, rather than together in the (now deprecated) ``image``
        argument.

    Load a tar archive that was created using :py:func:`docker.save
    <salt.modules.dockermod.save>` (or via the Docker CLI using ``docker save``).

    path
        Path to docker tar archive. Path can be a file on the Minion, or the
        URL of a file on the Salt fileserver (i.e.
        ``salt://path/to/docker/saved/image.tar``). To load a file from a
        saltenv other than ``base`` (e.g. ``dev``), pass it at the end of the
        URL (ex. ``salt://path/to/rootfs/tarball.tar.xz?saltenv=dev``).

    repository
        If specified, the topmost layer of the newly-loaded image will be
        tagged with the specified repo using :py:func:`docker.tag
        <salt.modules.dockermod.tag_>`. If a repository name is provided, then
        the ``tag`` argument is also required.

        .. versionadded:: 2018.3.0

    tag
        Tag name to go along with the repository name, if the loaded image is
        to be tagged.

        .. versionadded:: 2018.3.0

    image
        .. deprecated:: 2018.3.0
            Use both ``repository`` and ``tag`` instead


    **RETURN DATA**

    A dictionary will be returned, containing the following keys:

    - ``Path`` - Path of the file that was saved
    - ``Layers`` - A list containing the IDs of the layers which were loaded.
      Any layers in the file that was loaded, which were already present on the
      Minion, will not be included.
    - ``Image`` - Name of tag applied to topmost layer

      *(Only present if tag was specified and tagging was successful)*
    - ``Time_Elapsed`` - Time in seconds taken to load the file
    - ``Warning`` - Message describing any problems encountered in attemp to
      tag the topmost layer

      *(Only present if tag was specified and tagging failed)*


    CLI Example:

    .. code-block:: bash

        salt myminion docker.load /path/to/image.tar
        salt myminion docker.load salt://path/to/docker/saved/image.tar repository=myuser/myimage tag=mytag

def load(path, repository=None, tag=None):
    '''
    .. versionchanged:: 2018.3.0
        If the loaded image should be tagged, then the repository and tag must
        now be passed separately using the ``repository`` and ``tag``
        arguments, rather than together in the (now deprecated) ``image``
        argument.

    Load a tar archive that was created using :py:func:`docker.save
    <salt.modules.dockermod.save>` (or via the Docker CLI using ``docker save``).

    path
        Path to docker tar archive. Path can be a file on the Minion, or the
        URL of a file on the Salt fileserver (i.e.
        ``salt://path/to/docker/saved/image.tar``). To load a file from a
        saltenv other than ``base`` (e.g. ``dev``), pass it at the end of the
        URL (ex. ``salt://path/to/rootfs/tarball.tar.xz?saltenv=dev``).

    repository
        If specified, the topmost layer of the newly-loaded image will be
        tagged with the specified repo using :py:func:`docker.tag
        <salt.modules.dockermod.tag_>`. If a repository name is provided, then
        the ``tag`` argument is also required.

        .. versionadded:: 2018.3.0

    tag
        Tag name to go along with the repository name, if the loaded image is
        to be tagged.

        .. versionadded:: 2018.3.0

    image
        .. deprecated:: 2018.3.0
            Use both ``repository`` and ``tag`` instead


    **RETURN DATA**

    A dictionary will be returned, containing the following keys:

    - ``Path`` - Path of the file that was saved
    - ``Layers`` - A list containing the IDs of the layers which were loaded.
      Any layers in the file that was loaded, which were already present on the
      Minion, will not be included.
    - ``Image`` - Name of tag applied to topmost layer

      *(Only present if tag was specified and tagging was successful)*
    - ``Time_Elapsed`` - Time in seconds taken to load the file
    - ``Warning`` - Message describing any problems encountered in attemp to
      tag the topmost layer

      *(Only present if tag was specified and tagging failed)*


    CLI Example:

    .. code-block:: bash

        salt myminion docker.load /path/to/image.tar
        salt myminion docker.load salt://path/to/docker/saved/image.tar repository=myuser/myimage tag=mytag
    '''
    if (repository or tag) and not (repository and tag):
        # Have to have both or neither
        raise SaltInvocationError(
            'If tagging, both a repository and tag are required'
        )

    local_path = __salt__['container_resource.cache_file'](path)
    if not os.path.isfile(local_path):
        raise CommandExecutionError(
            'Source file {0} does not exist'.format(path)
        )

    pre = images(all=True)
    cmd = ['docker', 'load', '-i', local_path]
    time_started = time.time()
    result = __salt__['cmd.run_all'](cmd)
    ret = {'Time_Elapsed': time.time() - time_started}
    _clear_context()
    post = images(all=True)
    if result['retcode'] != 0:
        msg = 'Failed to load image(s) from {0}'.format(path)
        if result['stderr']:
            msg += ': {0}'.format(result['stderr'])
        raise CommandExecutionError(msg)
    ret['Path'] = path

    new_layers = [x for x in post if x not in pre]
    ret['Layers'] = [x[:12] for x in new_layers]
    top_level_images = _get_top_level_images(post, subset=new_layers)
    if repository or tag:
        if len(top_level_images) > 1:
            ret['Warning'] = (
                'More than one top-level image layer was loaded ({0}), no '
                'image was tagged'.format(', '.join(top_level_images))
            )
        else:
            # Normally just joining the two would be quicker than a str.format,
            # but since we can't be positive the repo and tag will both be
            # strings when passed (e.g. a numeric tag would be loaded as an int
            # or float), and because the tag_ function will stringify them if
            # need be, a str.format is the correct thing to do here.
            tagged_image = '{0}:{1}'.format(repository, tag)
            try:
                result = tag_(top_level_images[0],
                              repository=repository,
                              tag=tag)
                ret['Image'] = tagged_image
            except IndexError:
                ret['Warning'] = ('No top-level image layers were loaded, no '
                                  'image was tagged')
            except Exception as exc:
                ret['Warning'] = (
                    'Failed to tag {0} as {1}: {2}'.format(
                        top_level_images[0], tagged_image, exc
                    )
                )
    return ret