Skip to content
This repository was archived by the owner on May 9, 2020. It is now read-only.

Commit e093c26

Browse files
Roma KoshelMarat Komarov
authored andcommitted
Corrected PR remarks
1 parent 1962698 commit e093c26

File tree

10 files changed

+51
-78
lines changed

10 files changed

+51
-78
lines changed

chef/api.py

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import six
2-
32
import datetime
43
import logging
54
import os
@@ -10,7 +9,6 @@
109
import six.moves.urllib.request
1110
import six.moves.urllib.error
1211
import six.moves.urllib.parse
13-
1412
import weakref
1513

1614
import pkg_resources
@@ -30,22 +28,18 @@
3028
puts Chef::Config.configuration.to_json
3129
""".strip()
3230

33-
3431
def api_stack_value():
3532
if not hasattr(api_stack, 'value'):
3633
api_stack.value = []
3734
return api_stack.value
3835

3936

4037
class UnknownRubyExpression(Exception):
41-
4238
"""Token exception for unprocessed Ruby expressions."""
4339

4440

4541
class ChefRequest(six.moves.urllib.request.Request):
46-
4742
"""Workaround for using PUT/DELETE with urllib2."""
48-
4943
def __init__(self, *args, **kwargs):
5044
self._method = kwargs.pop('method', None)
5145
# Request is an old-style class, no super() allowed.
@@ -58,7 +52,6 @@ def get_method(self):
5852

5953

6054
class ChefAPI(object):
61-
6255
"""The ChefAPI object is a wrapper for a single Chef server.
6356
6457
.. admonition:: The API stack
@@ -87,7 +80,7 @@ def __init__(self, url, key, client, version='0.10.8', headers={}):
8780
self.key = key
8881
self.client = client
8982
self.version = version
90-
self.headers = dict((k.lower(), v) for k, v in headers.items())
83+
self.headers = dict((k.lower(), v) for k, v in six.iteritems(headers))
9184
self.version_parsed = pkg_resources.parse_version(self.version)
9285
self.platform = self.parsed_url.hostname == 'api.opscode.com'
9386
if not api_stack_value():
@@ -106,19 +99,18 @@ def from_config_file(cls, path):
10699
url = key_path = client_name = None
107100
for line in open(path):
108101
if not line.strip() or line.startswith('#'):
109-
continue # Skip blanks and comments
102+
continue # Skip blanks and comments
110103
parts = line.split(None, 1)
111104
if len(parts) != 2:
112-
continue # Not a simple key/value, we can't parse it anyway
105+
continue # Not a simple key/value, we can't parse it anyway
113106
key, value = parts
114107
md = cls.ruby_string_re.search(value)
115108
if md:
116109
value = md.group(2)
117110
else:
118111
# Not a string, don't even try
119-
log.debug('Value for %s does not look like a string: %s' % (key, value))
112+
log.debug('Value for {0} does not look like a string: {1}'.format(key, value))
120113
continue
121-
122114
def _ruby_value(match):
123115
expr = match.group(1).strip()
124116
if expr == 'current_dir':
@@ -208,17 +200,17 @@ def _request(self, method, url, data, headers):
208200

209201
def request(self, method, path, headers={}, data=None):
210202
auth_headers = sign_request(key=self.key, http_method=method,
211-
path=self.parsed_url.path + path.split('?', 1)[0], body=data,
212-
host=self.parsed_url.netloc, timestamp=datetime.datetime.utcnow(),
213-
user_id=self.client)
203+
path=self.parsed_url.path+path.split('?', 1)[0], body=data,
204+
host=self.parsed_url.netloc, timestamp=datetime.datetime.utcnow(),
205+
user_id=self.client)
214206
request_headers = {}
215207
request_headers.update(self.headers)
216-
request_headers.update(dict((k.lower(), v) for k, v in headers.items()))
208+
request_headers.update(dict((k.lower(), v) for k, v in six.iteritems(headers)))
217209
request_headers['x-chef-version'] = self.version
218210
request_headers.update(auth_headers)
219211
try:
220212
response = self._request(method, self.url + path, data, dict(
221-
(k.capitalize(), v) for k, v in request_headers.items()))
213+
(k.capitalize(), v) for k, v in six.iteritems(request_headers)))
222214
except six.moves.urllib.error.HTTPError as e:
223215
e.content = e.read()
224216
try:
@@ -230,7 +222,7 @@ def request(self, method, path, headers={}, data=None):
230222
return response
231223

232224
def api_request(self, method, path, headers={}, data=None):
233-
headers = dict((k.lower(), v) for k, v in headers.items())
225+
headers = dict((k.lower(), v) for k, v in six.iteritems(headers))
234226
headers['accept'] = 'application/json'
235227
if data is not None:
236228
headers['content-type'] = 'application/json'

chef/auth.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
1+
import six.moves
12
import base64
23
import datetime
34
import hashlib
45
import re
56

6-
77
def _ruby_b64encode(value):
88
"""The Ruby function Base64.encode64 automatically breaks things up
99
into 60-character chunks.
1010
"""
1111
b64 = base64.b64encode(value)
12-
for i in range(0, len(b64), 60):
13-
yield b64[i:i + 60].decode('utf-8')
14-
12+
for i in six.moves.range(0, len(b64), 60):
13+
yield b64[i:i + 60].decode()
1514

1615
def ruby_b64encode(value):
1716
return '\n'.join(_ruby_b64encode(value))
1817

19-
2018
def sha1_base64(value):
2119
"""An implementation of Mixlib::Authentication::Digester."""
22-
return ruby_b64encode(hashlib.sha1(value.encode('utf-8')).digest())
23-
20+
return ruby_b64encode(hashlib.sha1(value.encode()).digest())
2421

2522
class UTC(datetime.tzinfo):
26-
2723
"""UTC timezone stub."""
2824

2925
ZERO = datetime.timedelta(0)
@@ -39,22 +35,18 @@ def dst(self, dt):
3935

4036
utc = UTC()
4137

42-
4338
def canonical_time(timestamp):
4439
if timestamp.tzinfo is not None:
4540
timestamp = timestamp.astimezone(utc).replace(tzinfo=None)
4641
return timestamp.replace(microsecond=0).isoformat() + 'Z'
4742

4843
canonical_path_regex = re.compile(r'/+')
49-
50-
5144
def canonical_path(path):
5245
path = canonical_path_regex.sub('/', path)
5346
if len(path) > 1:
5447
path = path.rstrip('/')
5548
return path
5649

57-
5850
def canonical_request(http_method, path, hashed_body, timestamp, user_id):
5951
# Canonicalize request parameters
6052
http_method = http_method.upper()
@@ -68,7 +60,6 @@ def canonical_request(http_method, path, hashed_body, timestamp, user_id):
6860
'X-Ops-Timestamp:%(timestamp)s\n'
6961
'X-Ops-UserId:%(user_id)s' % vars())
7062

71-
7263
def sign_request(key, http_method, path, body, host, timestamp, user_id):
7364
"""Generate the needed headers for the Opscode authentication protocol."""
7465
timestamp = canonical_time(timestamp)
@@ -86,5 +77,5 @@ def sign_request(key, http_method, path, body, host, timestamp, user_id):
8677
req = canonical_request(http_method, path, hashed_body, timestamp, user_id)
8778
sig = _ruby_b64encode(key.private_encrypt(req))
8879
for i, line in enumerate(sig):
89-
headers['x-ops-authorization-%s' % (i + 1)] = line
80+
headers['x-ops-authorization-%s'%(i+1)] = line
9081
return headers

chef/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def __init__(self, name, api=None, skip_load=False):
6262
self._populate(data)
6363

6464
def _populate(self, data):
65-
for name, cls in self.__class__.attributes.items():
65+
for name, cls in six.iteritems(self.__class__.attributes):
6666
if name in data:
6767
value = cls(data[name])
6868
else:
@@ -82,7 +82,7 @@ def list(cls, api=None):
8282
"""
8383
api = api or ChefAPI.get_global()
8484
cls._check_api_version(api)
85-
names = [name for name, url in api[cls.url].items()]
85+
names = [name for name, url in six.iteritems(api[cls.url])]
8686
return ChefQuery(cls, names, api)
8787

8888
@classmethod
@@ -93,7 +93,7 @@ def create(cls, name, api=None, **kwargs):
9393
api = api or ChefAPI.get_global()
9494
cls._check_api_version(api)
9595
obj = cls(name, api, skip_load=True)
96-
for key, value in kwargs.items():
96+
for key, value in six.iteritems(kwargs):
9797
setattr(obj, key, value)
9898
api.api_request('POST', cls.url, data=obj)
9999
return obj
@@ -121,7 +121,7 @@ def to_dict(self):
121121
'json_class': 'Chef::'+self.__class__.__name__,
122122
'chef_type': self.__class__.__name__.lower(),
123123
}
124-
for attr in self.__class__.attributes.keys():
124+
for attr in six.iterkeys(self.__class__.attributes):
125125
d[attr] = getattr(self, attr)
126126
return d
127127

chef/data_bag.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class DataBag(six.with_metaclass(DataBagMeta, ChefObject, ChefQuery)):
1919
2020
bag = DataBag('versions')
2121
item = bag['web']
22-
for name, item in bag.iteritems():
22+
for name, item in six.iteritems(bag):
2323
print item['qa_version']
2424
"""
2525

@@ -96,7 +96,7 @@ def create(cls, bag, name, api=None, **kwargs):
9696
keyword arguments."""
9797
api = api or ChefAPI.get_global()
9898
obj = cls(bag, name, api, skip_load=True)
99-
for key, value in kwargs.items():
99+
for key, value in six.iteritems(kwargs):
100100
obj[key] = value
101101
obj['id'] = name
102102
api.api_request('POST', cls.url+'/'+str(bag), data=obj.raw_data)

chef/fabric.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
2-
1+
import six
32
import functools
43

54
from chef.api import ChefAPI, autoconfigure
65
from chef.environment import Environment
76
from chef.exceptions import ChefError, ChefAPIVersionError
87
from chef.search import Search
9-
import collections
108

119
try:
1210
from fabric.api import env, task, roles, output
@@ -39,7 +37,7 @@ def __init__(self, query, api, hostname_attr, environment=None):
3937
self.query = query
4038
self.api = api
4139
self.hostname_attr = hostname_attr
42-
if isinstance(self.hostname_attr, str):
40+
if isinstance(self.hostname_attr, six.string_types):
4341
self.hostname_attr = (self.hostname_attr,)
4442
self.environment = environment
4543

@@ -52,7 +50,7 @@ def __call__(self):
5250
query += ' AND chef_environment:%s' % environment
5351
for row in Search('node', query, api=self.api):
5452
if row:
55-
if isinstance(self.hostname_attr, collections.Callable):
53+
if callable(self.hostname_attr):
5654
val = self.hostname_attr(row.object)
5755
if val:
5856
yield val
@@ -192,7 +190,7 @@ def migrate():
192190
.. versionadded:: 0.2.1
193191
"""
194192
# Allow passing a single iterable
195-
if len(tags) == 1 and not isinstance(tags[0], str):
193+
if len(tags) == 1 and not isinstance(tags[0], six.string_types):
196194
tags = tags[0]
197195
query = ' AND '.join('tags:%s'%tag.strip() for tag in tags)
198196
return chef_query(query, **kwargs)

chef/node.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import six
12
import collections
23

34
from chef.base import ChefObject
@@ -27,7 +28,7 @@ def __init__(self, search_path=[], path=None, write=None):
2728
def __iter__(self):
2829
keys = set()
2930
for d in self.search_path:
30-
keys |= set(d.keys())
31+
keys |= set(six.iterkeys(d))
3132
return iter(keys)
3233

3334
def __len__(self):

0 commit comments

Comments
 (0)