Skip to content

Commit 8b9ad78

Browse files
committed
Merge branch 'ruffify'
Manually merging #3126. Signed-off-by: Milas Bowman <milas.bowman@docker.com>
2 parents ee23105 + c68d532 commit 8b9ad78

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+470
-540
lines changed

.github/workflows/ci.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,16 @@ env:
66
DOCKER_BUILDKIT: '1'
77

88
jobs:
9-
flake8:
9+
lint:
1010
runs-on: ubuntu-latest
1111
steps:
1212
- uses: actions/checkout@v3
1313
- uses: actions/setup-python@v4
1414
with:
15-
python-version: '3.x'
16-
- run: pip install -U flake8
17-
- name: Run flake8
18-
run: flake8 docker/ tests/
15+
python-version: '3.11'
16+
- run: pip install -U ruff==0.0.284
17+
- name: Run ruff
18+
run: ruff docker tests
1919

2020
unit-tests:
2121
runs-on: ubuntu-latest

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ paragraph in the Docker contribution guidelines.
4444
Before we can review your pull request, please ensure that nothing has been
4545
broken by your changes by running the test suite. You can do so simply by
4646
running `make test` in the project root. This also includes coding style using
47-
`flake8`
47+
`ruff`
4848

4949
### 3. Write clear, self-contained commits
5050

Makefile

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ build-dind-certs:
4646
docker build -t dpy-dind-certs -f tests/Dockerfile-dind-certs .
4747

4848
.PHONY: test
49-
test: flake8 unit-test-py3 integration-dind integration-dind-ssl
49+
test: ruff unit-test-py3 integration-dind integration-dind-ssl
5050

5151
.PHONY: unit-test-py3
5252
unit-test-py3: build-py3
@@ -163,9 +163,9 @@ integration-dind-ssl: build-dind-certs build-py3 setup-network
163163

164164
docker rm -vf dpy-dind-ssl dpy-dind-certs
165165

166-
.PHONY: flake8
167-
flake8: build-py3
168-
docker run -t --rm docker-sdk-python3 flake8 docker tests
166+
.PHONY: ruff
167+
ruff: build-py3
168+
docker run -t --rm docker-sdk-python3 ruff docker tests
169169

170170
.PHONY: docs
171171
docs: build-docs

docker/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# flake8: noqa
21
from .api import APIClient
32
from .client import DockerClient, from_env
43
from .context import Context

docker/api/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
# flake8: noqa
21
from .client import APIClient

docker/api/build.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -314,9 +314,8 @@ def _set_auth_headers(self, headers):
314314
auth_data[auth.INDEX_URL] = auth_data.get(auth.INDEX_NAME, {})
315315

316316
log.debug(
317-
'Sending auth config ({})'.format(
318-
', '.join(repr(k) for k in auth_data.keys())
319-
)
317+
"Sending auth config (%s)",
318+
', '.join(repr(k) for k in auth_data),
320319
)
321320

322321
if auth_data:
@@ -336,12 +335,9 @@ def process_dockerfile(dockerfile, path):
336335
abs_dockerfile = os.path.join(path, dockerfile)
337336
if constants.IS_WINDOWS_PLATFORM and path.startswith(
338337
constants.WINDOWS_LONGPATH_PREFIX):
339-
abs_dockerfile = '{}{}'.format(
340-
constants.WINDOWS_LONGPATH_PREFIX,
341-
os.path.normpath(
342-
abs_dockerfile[len(constants.WINDOWS_LONGPATH_PREFIX):]
343-
)
344-
)
338+
normpath = os.path.normpath(
339+
abs_dockerfile[len(constants.WINDOWS_LONGPATH_PREFIX):])
340+
abs_dockerfile = f'{constants.WINDOWS_LONGPATH_PREFIX}{normpath}'
345341
if (os.path.splitdrive(path)[0] != os.path.splitdrive(abs_dockerfile)[0] or
346342
os.path.relpath(abs_dockerfile, path).startswith('..')):
347343
# Dockerfile not in context - read data to insert into tar later

docker/api/client.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,10 @@ def __init__(self, base_url=None, version=None,
160160
base_url, timeout, pool_connections=num_pools,
161161
max_pool_size=max_pool_size
162162
)
163-
except NameError:
163+
except NameError as err:
164164
raise DockerException(
165165
'Install pypiwin32 package to enable npipe:// support'
166-
)
166+
) from err
167167
self.mount('http+docker://', self._custom_adapter)
168168
self.base_url = 'http+docker://localnpipe'
169169
elif base_url.startswith('ssh://'):
@@ -172,10 +172,10 @@ def __init__(self, base_url=None, version=None,
172172
base_url, timeout, pool_connections=num_pools,
173173
max_pool_size=max_pool_size, shell_out=use_ssh_client
174174
)
175-
except NameError:
175+
except NameError as err:
176176
raise DockerException(
177177
'Install paramiko package to enable ssh:// support'
178-
)
178+
) from err
179179
self.mount('http+docker://ssh', self._custom_adapter)
180180
self._unmount('http://', 'https://')
181181
self.base_url = 'http+docker://ssh'
@@ -199,28 +199,27 @@ def __init__(self, base_url=None, version=None,
199199
self._version = version
200200
if not isinstance(self._version, str):
201201
raise DockerException(
202-
'Version parameter must be a string or None. Found {}'.format(
203-
type(version).__name__
204-
)
202+
'Version parameter must be a string or None. '
203+
f'Found {type(version).__name__}'
205204
)
206205
if utils.version_lt(self._version, MINIMUM_DOCKER_API_VERSION):
207206
raise InvalidVersion(
208-
'API versions below {} are no longer supported by this '
209-
'library.'.format(MINIMUM_DOCKER_API_VERSION)
207+
f'API versions below {MINIMUM_DOCKER_API_VERSION} are '
208+
f'no longer supported by this library.'
210209
)
211210

212211
def _retrieve_server_version(self):
213212
try:
214213
return self.version(api_version=False)["ApiVersion"]
215-
except KeyError:
214+
except KeyError as ke:
216215
raise DockerException(
217216
'Invalid response from docker daemon: key "ApiVersion"'
218217
' is missing.'
219-
)
218+
) from ke
220219
except Exception as e:
221220
raise DockerException(
222221
f'Error while fetching server API version: {e}'
223-
)
222+
) from e
224223

225224
def _set_request_timeout(self, kwargs):
226225
"""Prepare the kwargs for an HTTP request by inserting the timeout
@@ -248,19 +247,17 @@ def _url(self, pathfmt, *args, **kwargs):
248247
for arg in args:
249248
if not isinstance(arg, str):
250249
raise ValueError(
251-
'Expected a string but found {} ({}) '
252-
'instead'.format(arg, type(arg))
250+
f'Expected a string but found {arg} ({type(arg)}) instead'
253251
)
254252

255253
quote_f = partial(urllib.parse.quote, safe="/:")
256254
args = map(quote_f, args)
257255

256+
formatted_path = pathfmt.format(*args)
258257
if kwargs.get('versioned_api', True):
259-
return '{}/v{}{}'.format(
260-
self.base_url, self._version, pathfmt.format(*args)
261-
)
258+
return f'{self.base_url}/v{self._version}{formatted_path}'
262259
else:
263-
return f'{self.base_url}{pathfmt.format(*args)}'
260+
return f'{self.base_url}{formatted_path}'
264261

265262
def _raise_for_status(self, response):
266263
"""Raises stored :class:`APIError`, if one occurred."""
@@ -479,7 +476,7 @@ def _get_result_tty(self, stream, res, is_tty):
479476
return self._multiplexed_response_stream_helper(res)
480477
else:
481478
return sep.join(
482-
[x for x in self._multiplexed_buffer_helper(res)]
479+
list(self._multiplexed_buffer_helper(res))
483480
)
484481

485482
def _unmount(self, *args):

docker/api/container.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -863,8 +863,8 @@ def logs(self, container, stdout=True, stderr=True, stream=False,
863863
params['since'] = since
864864
else:
865865
raise errors.InvalidArgument(
866-
'since value should be datetime or positive int/float, '
867-
'not {}'.format(type(since))
866+
'since value should be datetime or positive int/float,'
867+
f' not {type(since)}'
868868
)
869869

870870
if until is not None:
@@ -880,8 +880,8 @@ def logs(self, container, stdout=True, stderr=True, stream=False,
880880
params['until'] = until
881881
else:
882882
raise errors.InvalidArgument(
883-
'until value should be datetime or positive int/float, '
884-
'not {}'.format(type(until))
883+
f'until value should be datetime or positive int/float, '
884+
f'not {type(until)}'
885885
)
886886

887887
url = self._url("/containers/{0}/logs", container)
@@ -953,7 +953,7 @@ def port(self, container, private_port):
953953
return port_settings.get(private_port)
954954

955955
for protocol in ['tcp', 'udp', 'sctp']:
956-
h_ports = port_settings.get(private_port + '/' + protocol)
956+
h_ports = port_settings.get(f"{private_port}/{protocol}")
957957
if h_ports:
958958
break
959959

docker/api/service.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@ def _check_api_features(version, task_template, update_config, endpoint_spec,
77

88
def raise_version_error(param, min_version):
99
raise errors.InvalidVersion(
10-
'{} is not supported in API version < {}'.format(
11-
param, min_version
12-
)
10+
f'{param} is not supported in API version < {min_version}'
1311
)
1412

1513
if update_config is not None:

docker/auth.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@ def resolve_repository_name(repo_name):
2222
index_name, remote_name = split_repo_name(repo_name)
2323
if index_name[0] == '-' or index_name[-1] == '-':
2424
raise errors.InvalidRepository(
25-
'Invalid index name ({}). Cannot begin or end with a'
26-
' hyphen.'.format(index_name)
25+
f'Invalid index name ({index_name}). '
26+
'Cannot begin or end with a hyphen.'
2727
)
2828
return resolve_index_name(index_name), remote_name
2929

3030

3131
def resolve_index_name(index_name):
3232
index_name = convert_to_hostname(index_name)
33-
if index_name == 'index.' + INDEX_NAME:
33+
if index_name == f"index.{INDEX_NAME}":
3434
index_name = INDEX_NAME
3535
return index_name
3636

@@ -99,27 +99,19 @@ def parse_auth(cls, entries, raise_on_error=False):
9999
for registry, entry in entries.items():
100100
if not isinstance(entry, dict):
101101
log.debug(
102-
'Config entry for key {} is not auth config'.format(
103-
registry
104-
)
102+
f'Config entry for key {registry} is not auth config'
105103
)
106104
# We sometimes fall back to parsing the whole config as if it
107105
# was the auth config by itself, for legacy purposes. In that
108106
# case, we fail silently and return an empty conf if any of the
109107
# keys is not formatted properly.
110108
if raise_on_error:
111109
raise errors.InvalidConfigFile(
112-
'Invalid configuration for registry {}'.format(
113-
registry
114-
)
110+
f'Invalid configuration for registry {registry}'
115111
)
116112
return {}
117113
if 'identitytoken' in entry:
118-
log.debug(
119-
'Found an IdentityToken entry for registry {}'.format(
120-
registry
121-
)
122-
)
114+
log.debug(f'Found an IdentityToken entry for registry {registry}')
123115
conf[registry] = {
124116
'IdentityToken': entry['identitytoken']
125117
}
@@ -130,16 +122,15 @@ def parse_auth(cls, entries, raise_on_error=False):
130122
# a valid value in the auths config.
131123
# https://github.com/docker/compose/issues/3265
132124
log.debug(
133-
'Auth data for {} is absent. Client might be using a '
134-
'credentials store instead.'.format(registry)
125+
f'Auth data for {registry} is absent. '
126+
f'Client might be using a credentials store instead.'
135127
)
136128
conf[registry] = {}
137129
continue
138130

139131
username, password = decode_auth(entry['auth'])
140132
log.debug(
141-
'Found entry (registry={}, username={})'
142-
.format(repr(registry), repr(username))
133+
f'Found entry (registry={registry!r}, username={username!r})'
143134
)
144135

145136
conf[registry] = {
@@ -277,7 +268,7 @@ def _resolve_authconfig_credstore(self, registry, credstore_name):
277268
except credentials.StoreError as e:
278269
raise errors.DockerException(
279270
f'Credentials store error: {repr(e)}'
280-
)
271+
) from e
281272

282273
def _get_store_instance(self, name):
283274
if name not in self._stores:

0 commit comments

Comments
 (0)