Skip to content

Commit 3d2f2f7

Browse files
committed
Python 3 conversion
afaik it should be finished, but I didn't test the coverage so there may be some parts that still need to be converted. Some of the "changes" are just the formatter doing meaningless (in the context of actual conversion) changes such as switching single to double quotes.
1 parent 50aab09 commit 3d2f2f7

File tree

2 files changed

+68
-35
lines changed

2 files changed

+68
-35
lines changed

_moira.pyx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class MoiraException(Exception):
3535
__connected = False
3636

3737
def _error(code):
38-
raise MoiraException, (code, error_message(code))
38+
raise MoiraException((code, error_message(code)))
3939

4040
def connect(server=''):
4141
"""
@@ -86,9 +86,9 @@ def auth(program, krb4=False):
8686
discouraged
8787
"""
8888
if krb4:
89-
status = mr_auth(program)
89+
status = mr_auth(program.encode())
9090
else:
91-
status = mr_krb5_auth(program)
91+
status = mr_krb5_auth(program.encode())
9292
if status != MR_SUCCESS:
9393
_error(status)
9494

moira.py

Lines changed: 65 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,28 @@
1010
import re
1111

1212
import _moira
13-
from _moira import (auth, host, motd, noop, proxy, MoiraException)
13+
from _moira import auth, host, motd, noop, proxy, MoiraException
1414

1515

16-
help_re = re.compile('([a-z0-9_, ]*) \(([a-z0-9_, ]*)\)(?: => ([a-z0-9_, ]*))?',
17-
re.I)
18-
et_re = re.compile(r'^\s*#\s*define\s+([A-Za-z0-9_]+)\s+.*?([0-9]+)')
16+
help_re = re.compile("([a-z0-9_, ]*) \(([a-z0-9_, ]*)\)(?: => ([a-z0-9_, ]*))?", re.I)
17+
et_re = re.compile(r"^\s*#\s*define\s+([A-Za-z0-9_]+)\s+.*?([0-9]+)")
1918

2019

2120
_arg_cache = {}
2221
_return_cache = {}
2322
_et_cache = {}
2423

2524

25+
def _to_bytes(s):
26+
"""
27+
If given a string, converts it to bytes, otherwise returns it as is
28+
"""
29+
if isinstance(s, str):
30+
return s.encode()
31+
else:
32+
return s
33+
34+
2635
def _clear_caches():
2736
"""Clear query caches.
2837
@@ -33,9 +42,11 @@ def _clear_caches():
3342
_return_cache.clear()
3443

3544

36-
def connect(server=''):
37-
_moira.connect(server)
45+
def connect(server=""):
46+
_moira.connect(_to_bytes(server))
3847
version(-1)
48+
49+
3950
connect.__doc__ = _moira.connect.__doc__
4051

4152

@@ -54,13 +65,13 @@ def _load_help(handle):
5465
and return values into and out of dictionaries and into and out of
5566
tuples.
5667
"""
57-
help_string = ', '.join(query('_help', handle)[0]).strip()
68+
help_string = ", ".join(query("_help", handle)[0]).strip()
5869

59-
handle_str, arg_str, return_str = help_re.match(help_string).groups('')
70+
handle_str, arg_str, return_str = help_re.match(help_string).groups("")
6071

61-
handles = handle_str.split(', ')
62-
args = arg_str.split(', ')
63-
returns = return_str.split(', ')
72+
handles = handle_str.split(", ")
73+
args = arg_str.split(", ")
74+
returns = return_str.split(", ")
6475

6576
for h in handles:
6677
_arg_cache[h] = args
@@ -70,12 +81,21 @@ def _load_help(handle):
7081
def _list_query(handle, *args):
7182
"""
7283
Execute a Moira query and return the result as a list of tuples.
73-
84+
7485
This bypasses the tuple -> dict conversion done in moira.query()
7586
"""
7687
results = []
77-
_moira._query(handle, results.append, *args)
78-
return results
88+
89+
# Python 3 wants bytes
90+
args_converted = (_to_bytes(arg) for arg in args)
91+
92+
_moira._query(_to_bytes(handle), results.append, *args_converted)
93+
94+
# We get bytes back, convert back to string
95+
return [
96+
tuple(val.decode() for val in result)
97+
for result in results
98+
]
7999

80100

81101
def _parse_args(handle, args, kwargs):
@@ -91,34 +111,34 @@ def _parse_args(handle, args, kwargs):
91111
arguments that can be passed to the low-level Moira query
92112
function.
93113
"""
94-
if (handle not in _return_cache or
95-
not _return_cache[handle]):
114+
if handle not in _return_cache or not _return_cache[handle]:
96115
_load_help(handle)
97116

98117
if kwargs:
99-
return tuple(kwargs.get(i, '*')
100-
for i in _arg_cache[handle])
118+
return tuple(_to_bytes(kwargs.get(i, "*")) for i in _arg_cache[handle])
101119
else:
102-
return args
120+
return tuple(_to_bytes(arg) for arg in args)
103121

104122

105123
def query(handle, *args, **kwargs):
106124
"""
107125
Execute a Moira query and return the result as a list of dicts.
108-
126+
109127
Arguments can be specified either as positional or keyword
110128
arguments. If specified by keyword, they are cross-referenced with
111129
the argument name given by the query "_help handle".
112-
130+
113131
All of the real work of Moira is done in queries. There are over
114132
100 queries, each of which requires different arguments. The
115133
arguments to the queries should be passed as separate arguments to
116134
the function.
117135
"""
118-
if handle.startswith('_'):
119-
return _list_query(handle, *args)
136+
if handle.startswith("_"):
137+
args_converted = (_to_bytes(arg) for arg in args)
138+
139+
return _list_query(handle, *args_converted)
120140
else:
121-
fmt = kwargs.pop('fmt', dict)
141+
fmt = kwargs.pop("fmt", dict)
122142

123143
args = _parse_args(handle, args, kwargs)
124144

@@ -147,10 +167,10 @@ def access(handle, *args, **kwargs):
147167
args = _parse_args(handle, args, kwargs)
148168

149169
try:
150-
_moira._access(handle, *args)
170+
_moira._access(_to_bytes(handle), *args)
151171
return True
152172
except MoiraException as e:
153-
if e.code != errors()['MR_PERM']:
173+
if e.code != errors()["MR_PERM"]:
154174
raise
155175
return False
156176

@@ -160,6 +180,8 @@ def version(ver):
160180
# return values
161181
_clear_caches()
162182
return _moira.version(ver)
183+
184+
163185
version.__doc__ = _moira.version.__doc__
164186

165187

@@ -174,9 +196,8 @@ def errors():
174196
bug that it isn't.
175197
"""
176198
if not _et_cache:
177-
for prefix in ('/usr/include',
178-
'/sw/include'):
179-
header = os.path.join(prefix, 'moira/mr_et.h')
199+
for prefix in ("/usr/include", "/sw/include"):
200+
header = os.path.join(prefix, "moira/mr_et.h")
180201
if os.path.exists(header):
181202
for line in open(header):
182203
m = et_re.search(line)
@@ -187,6 +208,18 @@ def errors():
187208
return _et_cache
188209

189210

190-
__all__ = ['connect', 'disconnect', 'auth', 'host', 'motd', 'noop', 'query',
191-
'proxy', 'version', 'access', 'errors', '_list_query',
192-
'MoiraException']
211+
__all__ = [
212+
"connect",
213+
"disconnect",
214+
"auth",
215+
"host",
216+
"motd",
217+
"noop",
218+
"query",
219+
"proxy",
220+
"version",
221+
"access",
222+
"errors",
223+
"_list_query",
224+
"MoiraException",
225+
]

0 commit comments

Comments
 (0)