internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: docker/docker-py

Issue:
docker-py installation breaks docker-compose
im not quite sure if this is correct, but trying to install `docker-py` through pip after i've installed `docker-compose` breaks `docker-compose` with

```
Traceback (most recent call last):
  File "/usr/local/bin/docker-compose", line 7, in <module>
    from compose.cli.main import main
  File "/usr/local/lib/python2.7/site-packages/compose/cli/main.py", line 20, in <module>
    from ..bundle import get_image_digests
  File "/usr/local/lib/python2.7/site-packages/compose/bundle.py", line 13, in <module>
    from .network import get_network_defs_for_service
  File "/usr/local/lib/python2.7/site-packages/compose/network.py", line 7, in <module>
    from docker.types import IPAMConfig
ImportError: cannot import name IPAMConfig
```

To fix that error, i just need to do the installations in this order:
```
pip install docker-py
pip install docker-compose
```


gist:
https://gist.github.com/serialdoom/3a443c420aa29f9422f8c5fc73f46602

python/pip versions tried:
```
docker run -it python:2.7.13 bash -c 'pip --version'
pip 9.0.1 from /usr/local/lib/python2.7/site-packages (python 2.7)
docker run -it python:2.7.12 bash -c 'pip --version'
pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7)
```


Discussion:
I have the very same problem, I rolled back to 1.10.5 to fix the issue
apparently my proposed fix doesnt quite work as its breaking docker-py.

instead of @aboutlo sulution, downgrating `docker-compose` to `1.9.0` also fixes the problem
The newer version of `docker-compose` uses the `docker` package which unfortunately conflicts with the `docker-py` package. I'd suggest using virtualenv to isolate those projects, or make sure to only use `docker` (not `docker-py`) going forward.

HTH.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -1,10 +1,20 @@
 #!/usr/bin/env python
+from __future__ import print_function
+
 import codecs
 import os
 import sys
 
+import pip
+
 from setuptools import setup, find_packages
 
+if 'docker-py' in [x.project_name for x in pip.get_installed_distributions()]:
+    print(
+        'ERROR: "docker-py" needs to be uninstalled before installing this'
+        ' package:\npip uninstall docker-py', file=sys.stderr
+    )
+    sys.exit(1)
 
 ROOT_DIR = os.path.dirname(__file__)
 SOURCE_DIR = os.path.join(ROOT_DIR)


Test patch:
Repository: docker/docker-py

Issue:
tar fails if context contains UNIX socket
First reported: docker/compose#4363


Discussion:

Resolving patch:
diff --git a/docker/errors.py b/docker/errors.py
--- a/docker/errors.py
+++ b/docker/errors.py
@@ -22,7 +22,7 @@ def create_api_error_from_http_exception(e):
     cls = APIError
     if response.status_code == 404:
         if explanation and ('No such image' in str(explanation) or
-                            'not found: does not exist or no read access'
+                            'not found: does not exist or no pull access'
                             in str(explanation)):
             cls = ImageNotFound
         else:
diff --git a/docker/utils/utils.py b/docker/utils/utils.py
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -4,7 +4,6 @@
 import os.path
 import json
 import shlex
-import sys
 import tarfile
 import tempfile
 import warnings
@@ -15,6 +14,7 @@
 import requests
 import six
 
+from .. import constants
 from .. import errors
 from .. import tls
 
@@ -90,7 +90,12 @@ def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):
     for path in sorted(exclude_paths(root, exclude, dockerfile=dockerfile)):
         i = t.gettarinfo(os.path.join(root, path), arcname=path)
 
-        if sys.platform == 'win32':
+        if i is None:
+            # This happens when we encounter a socket file. We can safely
+            # ignore it and proceed.
+            continue
+
+        if constants.IS_WINDOWS_PLATFORM:
             # Windows doesn't keep track of the execute bit, so we make files
             # and directories executable by default.
             i.mode = i.mode & 0o755 | 0o111


Test patch:
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py
--- a/tests/unit/utils_test.py
+++ b/tests/unit/utils_test.py
@@ -5,6 +5,7 @@
 import os
 import os.path
 import shutil
+import socket
 import sys
 import tarfile
 import tempfile
@@ -894,6 +895,20 @@ def test_tar_with_directory_symlinks(self):
                 sorted(tar_data.getnames()), ['bar', 'bar/foo', 'foo']
             )
 
+    def test_tar_socket_file(self):
+        base = tempfile.mkdtemp()
+        self.addCleanup(shutil.rmtree, base)
+        for d in ['foo', 'bar']:
+            os.makedirs(os.path.join(base, d))
+        sock = socket.socket(socket.AF_UNIX)
+        self.addCleanup(sock.close)
+        sock.bind(os.path.join(base, 'test.sock'))
+        with tar(base) as archive:
+            tar_data = tarfile.open(fileobj=archive)
+            self.assertEqual(
+                sorted(tar_data.getnames()), ['bar', 'foo']
+            )
+
 
 class ShouldCheckDirectoryTest(unittest.TestCase):
     exclude_patterns = [
Repository: docker/docker-py

Issue:
DaemonApiMixin.events does not propagate HttpHeaders from config.json
The docker.api.daemon.DaemonApiMixin.events does not make use of the config.json, which could have custom HTTP headers to pass to the server.


Discussion:

Resolving patch:
diff --git a/docker/api/daemon.py b/docker/api/daemon.py
--- a/docker/api/daemon.py
+++ b/docker/api/daemon.py
@@ -54,7 +54,7 @@ def events(self, since=None, until=None, filters=None, decode=None):
         }
 
         return self._stream_helper(
-            self.get(self._url('/events'), params=params, stream=True),
+            self._get(self._url('/events'), params=params, stream=True),
             decode=decode
         )
 


Test patch:
diff --git a/tests/unit/api_test.py b/tests/unit/api_test.py
--- a/tests/unit/api_test.py
+++ b/tests/unit/api_test.py
@@ -228,7 +228,8 @@ def test_events(self):
             'GET',
             url_prefix + 'events',
             params={'since': None, 'until': None, 'filters': None},
-            stream=True
+            stream=True,
+            timeout=DEFAULT_TIMEOUT_SECONDS
         )
 
     def test_events_with_since_until(self):
@@ -247,7 +248,8 @@ def test_events_with_since_until(self):
                 'until': ts + 10,
                 'filters': None
             },
-            stream=True
+            stream=True,
+            timeout=DEFAULT_TIMEOUT_SECONDS
         )
 
     def test_events_with_filters(self):
@@ -265,7 +267,8 @@ def test_events_with_filters(self):
                 'until': None,
                 'filters': expected_filters
             },
-            stream=True
+            stream=True,
+            timeout=DEFAULT_TIMEOUT_SECONDS
         )
 
     def _socket_path_for_client_session(self, client):
Repository: docker/docker-py

Issue:
Cannot wait blocking generator output from events()
Since upgrade to `docker 2.2.0`. 

API 'events()' using same API client time out. 
So I got `UnixHTTPConnectionPool(host='localhost', port=None): Read timed out.` exception message.

But in my use case, `containers()` or other client APIs are reasonable to set an default timeout.
But `events()` should have another timeout setting for users.


Discussion:
Ah, right, that's going to be an issue. Thank you for reporting it!

Resolving patch:
diff --git a/docker/api/daemon.py b/docker/api/daemon.py
--- a/docker/api/daemon.py
+++ b/docker/api/daemon.py
@@ -68,9 +68,10 @@ def events(self, since=None, until=None, filters=None, decode=None):
             'until': until,
             'filters': filters
         }
+        url = self._url('/events')
 
         return self._stream_helper(
-            self._get(self._url('/events'), params=params, stream=True),
+            self._get(url, params=params, stream=True, timeout=None),
             decode=decode
         )
 


Test patch:
diff --git a/tests/integration/api_service_test.py b/tests/integration/api_service_test.py
--- a/tests/integration/api_service_test.py
+++ b/tests/integration/api_service_test.py
@@ -363,7 +363,7 @@ def test_create_service_with_secret(self):
         self.tmp_secrets.append(secret_id)
         secret_ref = docker.types.SecretReference(secret_id, secret_name)
         container_spec = docker.types.ContainerSpec(
-            'busybox', ['top'], secrets=[secret_ref]
+            'busybox', ['sleep', '999'], secrets=[secret_ref]
         )
         task_tmpl = docker.types.TaskTemplate(container_spec)
         name = self.get_service_name()
@@ -388,7 +388,7 @@ def test_create_service_with_unicode_secret(self):
         self.tmp_secrets.append(secret_id)
         secret_ref = docker.types.SecretReference(secret_id, secret_name)
         container_spec = docker.types.ContainerSpec(
-            'busybox', ['top'], secrets=[secret_ref]
+            'busybox', ['sleep', '999'], secrets=[secret_ref]
         )
         task_tmpl = docker.types.TaskTemplate(container_spec)
         name = self.get_service_name()
diff --git a/tests/unit/api_test.py b/tests/unit/api_test.py
--- a/tests/unit/api_test.py
+++ b/tests/unit/api_test.py
@@ -229,7 +229,7 @@ def test_events(self):
             url_prefix + 'events',
             params={'since': None, 'until': None, 'filters': None},
             stream=True,
-            timeout=DEFAULT_TIMEOUT_SECONDS
+            timeout=None
         )
 
     def test_events_with_since_until(self):
@@ -249,7 +249,7 @@ def test_events_with_since_until(self):
                 'filters': None
             },
             stream=True,
-            timeout=DEFAULT_TIMEOUT_SECONDS
+            timeout=None
         )
 
     def test_events_with_filters(self):
@@ -268,7 +268,7 @@ def test_events_with_filters(self):
                 'filters': expected_filters
             },
             stream=True,
-            timeout=DEFAULT_TIMEOUT_SECONDS
+            timeout=None
         )
 
     def _socket_path_for_client_session(self, client):
Repository: docker/docker-py

Issue:
Can't Create/Update an replicated service with replicas = 0, bug finded
I try to update a service with the following code:
```
 service.update(
            name=service.name,
            mode=docker.types.ServiceMode('replicated', replicas=0),
            networks=networks_list,
        )
```
First, I want to update the replicas only but I have to put name and network or the api think I want to change them (?) then send me an error.
Second, the ServiceMode object created here don't work and looks like this :  `{'replicated': {}}`
The reason for this is https://github.com/docker/docker-py/blob/master/docker/types/services.py#L410 where the if should be an if exist.
I would love to do a pull request but i'm a newbie and I'm already lost with my first one : #1568 
Thx for everything


Discussion:
I added the following code to work around this issue for now:

```
mode = docker.types.ServiceMode("replicated", int(count))
if int(count) == 0:
    mode.get('replicated')['Replicas'] = 0
```

Resolving patch:
diff --git a/docker/types/services.py b/docker/types/services.py
--- a/docker/types/services.py
+++ b/docker/types/services.py
@@ -407,7 +407,7 @@ def __init__(self, mode, replicas=None):
                 'replicas can only be used for replicated mode'
             )
         self[mode] = {}
-        if replicas:
+        if replicas is not None:
             self[mode]['Replicas'] = replicas
 
     @property


Test patch:
diff --git a/tests/unit/dockertypes_test.py b/tests/unit/dockertypes_test.py
--- a/tests/unit/dockertypes_test.py
+++ b/tests/unit/dockertypes_test.py
@@ -305,6 +305,12 @@ def test_replicated_replicas(self):
         assert mode.mode == 'replicated'
         assert mode.replicas == 21
 
+    def test_replicated_replicas_0(self):
+        mode = ServiceMode('replicated', 0)
+        assert mode == {'replicated': {'Replicas': 0}}
+        assert mode.mode == 'replicated'
+        assert mode.replicas == 0
+
     def test_invalid_mode(self):
         with pytest.raises(InvalidArgument):
             ServiceMode('foobar')
Repository: docker/docker-py

Issue:
Question about stream flag when building image
[This section of the docs](https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.ImageCollection.build) says:

> **stream (bool)** – Deprecated for API version > 1.8 (always True). Return a blocking generator you can iterate over to retrieve build output as it happens

However, if I attempt to run something like:

```py
docker.images.build(path='docker/example/', tag='example', stream=True)
```

It is blocked until the image is built, and returns the image then.

What's a "blocking generator" and how is it supposed to be used?

Thanks!


Discussion:
[This](https://github.com/docker/docker-py/blob/master/docker/models/images.py#L166) seems to be the function. I don't see how `stream` plays any role here. It delegates to the low-level API but whether `stream` or not doesn't seem to affect how this method itself behaves. It intercepts the stream and does not return until the stream is over (effectively making it non-stream), iiuc.
anyone here? if this is an official project then the lack of support (or response) is a bit astonishing.
It's just a mistake in the documentation. `stream` has no effect on the high-level API.

Resolving patch:
diff --git a/docker/models/images.py b/docker/models/images.py
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -126,9 +126,6 @@ def build(self, **kwargs):
             rm (bool): Remove intermediate containers. The ``docker build``
                 command now defaults to ``--rm=true``, but we have kept the old
                 default of `False` to preserve backward compatibility
-            stream (bool): *Deprecated for API version > 1.8 (always True)*.
-                Return a blocking generator you can iterate over to retrieve
-                build output as it happens
             timeout (int): HTTP timeout
             custom_context (bool): Optional if using ``fileobj``
             encoding (str): The encoding for a stream. Set to ``gzip`` for


Test patch:
Repository: docker/docker-py

Issue:
DockerClient.secrets is not a property
`DockerClient.secrets` is not decorated with `property` and so must be called rather than just accessed. This is inconsistent with the docs and similar collections on the client attribute (e.g. images, containers, etc.).


Discussion:
Oops. Thanks for the report!

Resolving patch:
diff --git a/docker/client.py b/docker/client.py
--- a/docker/client.py
+++ b/docker/client.py
@@ -119,6 +119,7 @@ def plugins(self):
         """
         return PluginCollection(client=self)
 
+    @property
     def secrets(self):
         """
         An object for managing secrets on the server. See the


Test patch:
Repository: docker/docker-py

Issue:
image.tag does not return anything
There's no return statement in `images.tag`:
https://github.com/docker/docker-py/blob/master/docker/models/images.py#L99

[Readthedocs](https://docker-py.readthedocs.io/en/stable/images.html) (and the method comments) suggest it should return a bool for success.

I saw this running version 2.2.1 of the library
```
# pip freeze | grep docker
docker==2.2.1
docker-pycreds==0.2.1
```

**Repro code:**
```
import docker
def test_tag(id):
    client = docker.DockerClient()
    image = client.images.get(id)
    tag_result = image.tag('test_image', tag='test_tag')
    if tag_result is None:
        print('oops')
```


Discussion:

Resolving patch:
diff --git a/docker/models/images.py b/docker/models/images.py
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -96,7 +96,7 @@ def tag(self, repository, tag=None, **kwargs):
         Returns:
             (bool): ``True`` if successful
         """
-        self.client.api.tag(self.id, repository, tag=tag, **kwargs)
+        return self.client.api.tag(self.id, repository, tag=tag, **kwargs)
 
 
 class ImageCollection(Collection):


Test patch:
diff --git a/tests/integration/models_images_test.py b/tests/integration/models_images_test.py
--- a/tests/integration/models_images_test.py
+++ b/tests/integration/models_images_test.py
@@ -71,7 +71,8 @@ def test_tag_and_remove(self):
         client = docker.from_env(version=TEST_API_VERSION)
         image = client.images.pull('alpine:latest')
 
-        image.tag(repo, tag)
+        result = image.tag(repo, tag)
+        assert result is True
         self.tmp_imgs.append(identifier)
         assert image.id in get_ids(client.images.list(repo))
         assert image.id in get_ids(client.images.list(identifier))
Repository: docker/docker-py

Issue:
client.networks.create check_duplicates docs not reflective of behavior
Docs say it does, but it's actually set to `None`.


Discussion:

Resolving patch:
diff --git a/docker/api/network.py b/docker/api/network.py
--- a/docker/api/network.py
+++ b/docker/api/network.py
@@ -52,7 +52,7 @@ def create_network(self, name, driver=None, options=None, ipam=None,
             options (dict): Driver options as a key-value dictionary
             ipam (IPAMConfig): Optional custom IP scheme for the network.
             check_duplicate (bool): Request daemon to check for networks with
-                same name. Default: ``True``.
+                same name. Default: ``None``.
             internal (bool): Restrict external access to the network. Default
                 ``False``.
             labels (dict): Map of labels to set on the network. Default


Test patch:
Repository: docker/docker-py

Issue:
.dockerignore does not work with patterns begin with slash
docker version:

```
docker -v
Docker version 17.03.1-ce, build c6d412e
```
reproduce:

```
mkdir app
cd app
mkdir foo
touch foo/bar
echo '/foo/bar' > .dockerignore
printf 'FROM alpine:3.1\nWORKDIR /app\nCOPY . .\n' > Dockerfile
docker build -t app .
docker run --rm app find foo
```

output:

```
foo
foo/bar
```

It seems the statement  from [the official document](https://docs.docker.com/engine/reference/builder/#dockerignore-file) below is not correct:

> For example, the patterns `/foo/bar` and `foo/bar` both exclude a file or directory named `bar` in the `foo` subdirectory of `PATH` or in the root of the git repository located at `URL`.

We should either amend the document or fix the bug.



Discussion:

Resolving patch:
diff --git a/docker/utils/build.py b/docker/utils/build.py
--- a/docker/utils/build.py
+++ b/docker/utils/build.py
@@ -26,6 +26,7 @@ def exclude_paths(root, patterns, dockerfile=None):
     if dockerfile is None:
         dockerfile = 'Dockerfile'
 
+    patterns = [p.lstrip('/') for p in patterns]
     exceptions = [p for p in patterns if p.startswith('!')]
 
     include_patterns = [p[1:] for p in exceptions]


Test patch:
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py
--- a/tests/unit/utils_test.py
+++ b/tests/unit/utils_test.py
@@ -768,6 +768,11 @@ def test_single_subdir_single_filename(self):
             self.all_paths - set(['foo/a.py'])
         )
 
+    def test_single_subdir_single_filename_leading_slash(self):
+        assert self.exclude(['/foo/a.py']) == convert_paths(
+            self.all_paths - set(['foo/a.py'])
+        )
+
     def test_single_subdir_with_path_traversal(self):
         assert self.exclude(['foo/whoops/../a.py']) == convert_paths(
             self.all_paths - set(['foo/a.py'])
Repository: docker/docker-py

Issue:
using private image in FROM during build is broken
Example:
```
import docker
from io import BytesIO

dockerfile="""
FROM <some-private-image-on-docker-hub>
CMD ["ls"]
"""

f = BytesIO(dockerfile.encode('utf-8'))

client = docker.APIClient(version='auto')
client.login(username='<user>', password='<pass>')

for l in client.build(fileobj=f, rm=True, tag='test', stream=True, pull=True):
  print(l)
```

This example will error saying that it failed to find the image in FROM. If you add the full registry:

```
client = docker.APIClient(version='auto')
client.login(username='<user>', password='<pass>', registry='https://index.docker.io/v1/')
```

It will succeed. If you leave off the trailing slash on the registry url, it will fail.

python 3.5.2
docker-py 2.4.2


Discussion:
Are you using a credentials store?
In this case no, I'm testing from within a docker container.

I've verified by checking the value of `client._auth_configs`.
Alright, thanks! I'll try to reproduce.

Resolving patch:
diff --git a/docker/api/build.py b/docker/api/build.py
--- a/docker/api/build.py
+++ b/docker/api/build.py
@@ -274,7 +274,10 @@ def _set_auth_headers(self, headers):
                         self._auth_configs, registry
                     )
             else:
-                auth_data = self._auth_configs
+                auth_data = self._auth_configs.copy()
+                # See https://github.com/docker/docker-py/issues/1683
+                if auth.INDEX_NAME in auth_data:
+                    auth_data[auth.INDEX_URL] = auth_data[auth.INDEX_NAME]
 
             log.debug(
                 'Sending auth config ({0})'.format(
diff --git a/docker/auth.py b/docker/auth.py
--- a/docker/auth.py
+++ b/docker/auth.py
@@ -10,7 +10,7 @@
 from .constants import IS_WINDOWS_PLATFORM
 
 INDEX_NAME = 'docker.io'
-INDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME)
+INDEX_URL = 'https://index.{0}/v1/'.format(INDEX_NAME)
 DOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json')
 LEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg'
 TOKEN_USERNAME = '<token>'
@@ -118,7 +118,7 @@ def _resolve_authconfig_credstore(authconfig, registry, credstore_name):
     if not registry or registry == INDEX_NAME:
         # The ecosystem is a little schizophrenic with index.docker.io VS
         # docker.io - in that case, it seems the full URL is necessary.
-        registry = 'https://index.docker.io/v1/'
+        registry = INDEX_URL
     log.debug("Looking for auth entry for {0}".format(repr(registry)))
     store = dockerpycreds.Store(credstore_name)
     try:


Test patch:
Repository: docker/docker-py

Issue:
_check_api_features should support pure dict params
https://github.com/docker/docker-py/blob/2.4.2-release/docker/api/service.py#L41

Originally reported: https://github.com/moby/moby/issues/34116#issuecomment-315484688


Discussion:

Resolving patch:
diff --git a/docker/api/service.py b/docker/api/service.py
--- a/docker/api/service.py
+++ b/docker/api/service.py
@@ -38,7 +38,7 @@ def _check_api_features(version, task_template, update_config):
                         'Placement.preferences is not supported in'
                         ' API version < 1.27'
                     )
-        if task_template.container_spec.get('TTY'):
+        if task_template.get('ContainerSpec', {}).get('TTY'):
             if utils.version_lt(version, '1.25'):
                 raise errors.InvalidVersion(
                     'ContainerSpec.TTY is not supported in API version < 1.25'


Test patch:
diff --git a/tests/integration/api_service_test.py b/tests/integration/api_service_test.py
--- a/tests/integration/api_service_test.py
+++ b/tests/integration/api_service_test.py
@@ -376,6 +376,23 @@ def test_create_service_with_tty(self):
         assert 'TTY' in con_spec
         assert con_spec['TTY'] is True
 
+    @requires_api_version('1.25')
+    def test_create_service_with_tty_dict(self):
+        container_spec = {
+            'Image': BUSYBOX,
+            'Command': ['true'],
+            'TTY': True
+        }
+        task_tmpl = docker.types.TaskTemplate(container_spec)
+        name = self.get_service_name()
+        svc_id = self.client.create_service(task_tmpl, name=name)
+        svc_info = self.client.inspect_service(svc_id)
+        assert 'TaskTemplate' in svc_info['Spec']
+        assert 'ContainerSpec' in svc_info['Spec']['TaskTemplate']
+        con_spec = svc_info['Spec']['TaskTemplate']['ContainerSpec']
+        assert 'TTY' in con_spec
+        assert con_spec['TTY'] is True
+
     def test_create_service_global_mode(self):
         container_spec = docker.types.ContainerSpec(
             BUSYBOX, ['echo', 'hello']