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

Commit b989b58

Browse files
author
Roma Koshel
committed
fix PR remarks
1 parent 1962698 commit b989b58

File tree

9 files changed

+41
-70
lines changed

9 files changed

+41
-70
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: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,22 @@
33
import hashlib
44
import re
55

6-
76
def _ruby_b64encode(value):
87
"""The Ruby function Base64.encode64 automatically breaks things up
98
into 60-character chunks.
109
"""
1110
b64 = base64.b64encode(value)
1211
for i in range(0, len(b64), 60):
13-
yield b64[i:i + 60].decode('utf-8')
14-
12+
yield b64[i:i + 60].decode()
1513

1614
def ruby_b64encode(value):
1715
return '\n'.join(_ruby_b64encode(value))
1816

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

2521
class UTC(datetime.tzinfo):
26-
2722
"""UTC timezone stub."""
2823

2924
ZERO = datetime.timedelta(0)
@@ -39,22 +34,18 @@ def dst(self, dt):
3934

4035
utc = UTC()
4136

42-
4337
def canonical_time(timestamp):
4438
if timestamp.tzinfo is not None:
4539
timestamp = timestamp.astimezone(utc).replace(tzinfo=None)
4640
return timestamp.replace(microsecond=0).isoformat() + 'Z'
4741

4842
canonical_path_regex = re.compile(r'/+')
49-
50-
5143
def canonical_path(path):
5244
path = canonical_path_regex.sub('/', path)
5345
if len(path) > 1:
5446
path = path.rstrip('/')
5547
return path
5648

57-
5849
def canonical_request(http_method, path, hashed_body, timestamp, user_id):
5950
# Canonicalize request parameters
6051
http_method = http_method.upper()
@@ -68,7 +59,6 @@ def canonical_request(http_method, path, hashed_body, timestamp, user_id):
6859
'X-Ops-Timestamp:%(timestamp)s\n'
6960
'X-Ops-UserId:%(user_id)s' % vars())
7061

71-
7262
def sign_request(key, http_method, path, body, host, timestamp, user_id):
7363
"""Generate the needed headers for the Opscode authentication protocol."""
7464
timestamp = canonical_time(timestamp)
@@ -86,5 +76,5 @@ def sign_request(key, http_method, path, body, host, timestamp, user_id):
8676
req = canonical_request(http_method, path, hashed_body, timestamp, user_id)
8777
sig = _ruby_b64encode(key.private_encrypt(req))
8878
for i, line in enumerate(sig):
89-
headers['x-ops-authorization-%s' % (i + 1)] = line
79+
headers['x-ops-authorization-%s'%(i+1)] = line
9080
return headers

chef/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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

chef/data_bag.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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):

chef/rsa.py

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,21 @@
99
else:
1010
_eay = CDLL('libcrypto.so')
1111

12-
# unsigned long ERR_get_error(void);
12+
#unsigned long ERR_get_error(void);
1313
ERR_get_error = _eay.ERR_get_error
1414
ERR_get_error.argtypes = []
1515
ERR_get_error.restype = c_ulong
1616

17-
# void ERR_error_string_n(unsigned long e, char *buf, size_t len);
17+
#void ERR_error_string_n(unsigned long e, char *buf, size_t len);
1818
ERR_error_string_n = _eay.ERR_error_string_n
1919
ERR_error_string_n.argtypes = [c_ulong, c_char_p, c_size_t]
2020
ERR_error_string_n.restype = None
2121

22-
2322
class SSLError(Exception):
24-
2523
"""An error in OpenSSL."""
2624

2725
def __init__(self, message, *args):
28-
message = message % args
26+
message = message%args
2927
err = ERR_get_error()
3028
if err:
3129
message += ':'
@@ -52,70 +50,64 @@ def __init__(self, message, *args):
5250
BIO_s_mem.argtypes = []
5351
BIO_s_mem.restype = c_void_p
5452

55-
# long BIO_ctrl(BIO *bp,int cmd,long larg,void *parg);
53+
#long BIO_ctrl(BIO *bp,int cmd,long larg,void *parg);
5654
BIO_ctrl = _eay.BIO_ctrl
5755
BIO_ctrl.argtypes = [c_void_p, c_int, c_long, c_void_p]
5856
BIO_ctrl.restype = c_long
5957

60-
# define BIO_CTRL_RESET 1 /* opt - rewind/zero etc */
58+
#define BIO_CTRL_RESET 1 /* opt - rewind/zero etc */
6159
BIO_CTRL_RESET = 1
62-
# define BIO_CTRL_INFO 3 /* opt - extra tit-bits */
60+
##define BIO_CTRL_INFO 3 /* opt - extra tit-bits */
6361
BIO_CTRL_INFO = 3
6462

65-
# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
66-
67-
63+
#define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
6864
def BIO_reset(b):
6965
return BIO_ctrl(b, BIO_CTRL_RESET, 0, None)
7066

71-
# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
72-
73-
67+
##define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
7468
def BIO_get_mem_data(b, pp):
7569
return BIO_ctrl(b, BIO_CTRL_INFO, 0, pp)
7670

7771
# int BIO_free(BIO *a)
7872
BIO_free = _eay.BIO_free
7973
BIO_free.argtypes = [c_void_p]
8074
BIO_free.restype = c_int
81-
82-
8375
def BIO_free_errcheck(result, func, arguments):
8476
if result == 0:
8577
raise SSLError('Unable to free BIO')
8678
BIO_free.errcheck = BIO_free_errcheck
8779

88-
# RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **x,
80+
#RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **x,
8981
# pem_password_cb *cb, void *u);
9082
PEM_read_bio_RSAPrivateKey = _eay.PEM_read_bio_RSAPrivateKey
9183
PEM_read_bio_RSAPrivateKey.argtypes = [c_void_p, c_void_p, c_void_p, c_void_p]
9284
PEM_read_bio_RSAPrivateKey.restype = c_void_p
9385

94-
# RSA *PEM_read_bio_RSAPublicKey(BIO *bp, RSA **x,
86+
#RSA *PEM_read_bio_RSAPublicKey(BIO *bp, RSA **x,
9587
# pem_password_cb *cb, void *u);
9688
PEM_read_bio_RSAPublicKey = _eay.PEM_read_bio_RSAPublicKey
9789
PEM_read_bio_RSAPublicKey.argtypes = [c_void_p, c_void_p, c_void_p, c_void_p]
9890
PEM_read_bio_RSAPublicKey.restype = c_void_p
9991

100-
# int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
92+
#int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
10193
# unsigned char *kstr, int klen,
10294
# pem_password_cb *cb, void *u);
10395
PEM_write_bio_RSAPrivateKey = _eay.PEM_write_bio_RSAPrivateKey
10496
PEM_write_bio_RSAPrivateKey.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p, c_int, c_void_p, c_void_p]
10597
PEM_write_bio_RSAPrivateKey.restype = c_int
10698

107-
# int PEM_write_bio_RSAPublicKey(BIO *bp, RSA *x);
99+
#int PEM_write_bio_RSAPublicKey(BIO *bp, RSA *x);
108100
PEM_write_bio_RSAPublicKey = _eay.PEM_write_bio_RSAPublicKey
109101
PEM_write_bio_RSAPublicKey.argtypes = [c_void_p, c_void_p]
110102
PEM_write_bio_RSAPublicKey.restype = c_int
111103

112-
# int RSA_private_encrypt(int flen, unsigned char *from,
104+
#int RSA_private_encrypt(int flen, unsigned char *from,
113105
# unsigned char *to, RSA *rsa,int padding);
114106
RSA_private_encrypt = _eay.RSA_private_encrypt
115107
RSA_private_encrypt.argtypes = [c_int, c_void_p, c_void_p, c_void_p, c_int]
116108
RSA_private_encrypt.restype = c_int
117109

118-
# int RSA_public_decrypt(int flen, unsigned char *from,
110+
#int RSA_public_decrypt(int flen, unsigned char *from,
119111
# unsigned char *to, RSA *rsa, int padding);
120112
RSA_public_decrypt = _eay.RSA_public_decrypt
121113
RSA_public_decrypt.argtypes = [c_int, c_void_p, c_void_p, c_void_p, c_int]
@@ -129,30 +121,28 @@ def BIO_free_errcheck(result, func, arguments):
129121
RSA_size.argtypes = [c_void_p]
130122
RSA_size.restype = c_int
131123

132-
# RSA *RSA_generate_key(int num, unsigned long e,
124+
#RSA *RSA_generate_key(int num, unsigned long e,
133125
# void (*callback)(int,int,void *), void *cb_arg);
134126
RSA_generate_key = _eay.RSA_generate_key
135127
RSA_generate_key.argtypes = [c_int, c_ulong, c_void_p, c_void_p]
136128
RSA_generate_key.restype = c_void_p
137129

138-
# define RSA_F4 0x10001L
130+
##define RSA_F4 0x10001L
139131
RSA_F4 = 0x10001
140132

141133
# void RSA_free(RSA *rsa);
142134
RSA_free = _eay.RSA_free
143135
RSA_free.argtypes = [c_void_p]
144136

145-
146137
class Key(object):
147-
148138
"""An OpenSSL RSA key."""
149139

150140
def __init__(self, fp=None):
151141
self.key = None
152142
self.public = False
153143
if not fp:
154144
return
155-
if isinstance(fp, six.binary_type) and fp.startswith('-----'.encode()):
145+
if isinstance(fp, six.binary_type) and fp.startswith(b'-----'):
156146
# PEM formatted text
157147
self.raw = fp
158148
elif isinstance(fp, six.string_types):

0 commit comments

Comments
 (0)