Skip to content

Commit 2e2dfb1

Browse files
authored
Merge pull request #1127 from moreati/import-cleanups
Consolidate backward compatibility imports and polyfills
2 parents ce6297b + 0e7eefb commit 2e2dfb1

24 files changed

+99
-244
lines changed

ansible_mitogen/affinity.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@
8383
import os
8484
import struct
8585

86-
import mitogen.core
8786
import mitogen.parent
8887

8988

@@ -265,7 +264,7 @@ def _mask_to_bytes(self, mask):
265264
for x in range(16):
266265
chunks.append(struct.pack('<Q', mask & shiftmask))
267266
mask >>= 64
268-
return mitogen.core.b('').join(chunks)
267+
return b''.join(chunks)
269268

270269
def _get_thread_ids(self):
271270
try:

ansible_mitogen/logging.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,13 @@
3232
import logging
3333
import os
3434

35+
import ansible.utils.display
36+
3537
import mitogen.core
3638
import mitogen.utils
3739

38-
try:
39-
from __main__ import display
40-
except ImportError:
41-
import ansible.utils.display
42-
display = ansible.utils.display.Display()
4340

41+
display = ansible.utils.display.Display()
4442

4543
#: The process name set via :func:`set_process_name`.
4644
_process_name = None

ansible_mitogen/mixins.py

Lines changed: 8 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,16 @@
3535
import random
3636
import traceback
3737

38-
try:
39-
from shlex import quote as shlex_quote
40-
except ImportError:
41-
from pipes import quote as shlex_quote
42-
43-
from ansible.module_utils._text import to_bytes
44-
from ansible.parsing.utils.jsonify import jsonify
45-
4638
import ansible
4739
import ansible.constants
4840
import ansible.plugins
4941
import ansible.plugins.action
42+
import ansible.utils.unsafe_proxy
43+
import ansible.vars.clean
44+
45+
from ansible.module_utils.common.text.converters import to_bytes, to_text
46+
from ansible.module_utils.six.moves import shlex_quote
47+
from ansible.parsing.utils.jsonify import jsonify
5048

5149
import mitogen.core
5250
import mitogen.select
@@ -57,24 +55,6 @@
5755
import ansible_mitogen.utils
5856
import ansible_mitogen.utils.unsafe
5957

60-
from ansible.module_utils._text import to_text
61-
62-
try:
63-
from ansible.utils.unsafe_proxy import wrap_var
64-
except ImportError:
65-
from ansible.vars.unsafe_proxy import wrap_var
66-
67-
try:
68-
# ansible 2.8 moved remove_internal_keys to the clean module
69-
from ansible.vars.clean import remove_internal_keys
70-
except ImportError:
71-
try:
72-
from ansible.vars.manager import remove_internal_keys
73-
except ImportError:
74-
# ansible 2.3.3 has remove_internal_keys as a protected func on the action class
75-
# we'll fallback to calling self._remove_internal_keys in this case
76-
remove_internal_keys = lambda a: "Not found"
77-
7858

7959
LOG = logging.getLogger(__name__)
8060

@@ -413,10 +393,7 @@ def _execute_module(self, module_name=None, module_args=None, tmp=None,
413393
self._remove_tmp_path(tmp)
414394

415395
# prevents things like discovered_interpreter_* or ansible_discovered_interpreter_* from being set
416-
# handle ansible 2.3.3 that has remove_internal_keys in a different place
417-
check = remove_internal_keys(result)
418-
if check == 'Not found':
419-
self._remove_internal_keys(result)
396+
ansible.vars.clean.remove_internal_keys(result)
420397

421398
# taken from _execute_module of ansible 2.8.6
422399
# propagate interpreter discovery results back to the controller
@@ -440,7 +417,7 @@ def _execute_module(self, module_name=None, module_args=None, tmp=None,
440417
result['deprecations'] = []
441418
result['deprecations'].extend(self._discovery_deprecation_warnings)
442419

443-
return wrap_var(result)
420+
return ansible.utils.unsafe_proxy.wrap_var(result)
444421

445422
def _postprocess_response(self, result):
446423
"""

ansible_mitogen/planner.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ def read_file(path):
477477
finally:
478478
os.close(fd)
479479

480-
return mitogen.core.b('').join(bits)
480+
return b''.join(bits)
481481

482482

483483
def _propagate_deps(invocation, planner, context):

ansible_mitogen/plugins/connection/mitogen_local.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,7 @@
4242
import ansible_mitogen.connection
4343
import ansible_mitogen.process
4444

45-
46-
if sys.version_info > (3,):
47-
viewkeys = dict.keys
48-
elif sys.version_info > (2, 7):
49-
viewkeys = dict.viewkeys
50-
else:
51-
viewkeys = lambda dct: set(dct)
45+
viewkeys = getattr(dict, 'viewkeys', dict.keys)
5246

5347

5448
def dict_diff(old, new):

ansible_mitogen/process.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,9 @@
6161
import ansible
6262
import ansible.constants as C
6363
import ansible.errors
64+
6465
import ansible_mitogen.logging
6566
import ansible_mitogen.services
66-
67-
from mitogen.core import b
6867
import ansible_mitogen.affinity
6968

7069

@@ -639,7 +638,7 @@ def worker_main(self):
639638

640639
try:
641640
# Let the parent know our listening socket is ready.
642-
mitogen.core.io_op(self.model.child_sock.send, b('1'))
641+
mitogen.core.io_op(self.model.child_sock.send, b'1')
643642
# Block until the socket is closed, which happens on parent exit.
644643
mitogen.core.io_op(self.model.child_sock.recv, 1)
645644
finally:

ansible_mitogen/runner.py

Lines changed: 24 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@
4040
__metaclass__ = type
4141

4242
import atexit
43+
import ctypes
4344
import json
45+
import logging
4446
import os
4547
import re
4648
import shlex
@@ -50,19 +52,12 @@
5052
import traceback
5153
import types
5254

55+
from ansible.module_utils.six.moves import shlex_quote
56+
5357
import mitogen.core
5458
import ansible_mitogen.target # TODO: circular import
55-
from mitogen.core import b
56-
from mitogen.core import bytes_partition
57-
from mitogen.core import str_rpartition
5859
from mitogen.core import to_text
5960

60-
try:
61-
import ctypes
62-
except ImportError:
63-
# Python 2.4
64-
ctypes = None
65-
6661
try:
6762
# Python >= 3.4, PEP 451 ModuleSpec API
6863
import importlib.machinery
@@ -77,15 +72,6 @@
7772
except ImportError:
7873
from io import StringIO
7974

80-
try:
81-
from shlex import quote as shlex_quote
82-
except ImportError:
83-
from pipes import quote as shlex_quote
84-
85-
# Absolute imports for <2.5.
86-
logging = __import__('logging')
87-
88-
8975
# Prevent accidental import of an Ansible module from hanging on stdin read.
9076
import ansible.module_utils.basic
9177
ansible.module_utils.basic._ANSIBLE_ARGS = '{}'
@@ -95,15 +81,13 @@
9581
# explicit call to res_init() on each task invocation. BSD-alikes export it
9682
# directly, Linux #defines it as "__res_init".
9783
libc__res_init = None
98-
if ctypes:
99-
libc = ctypes.CDLL(None)
100-
for symbol in 'res_init', '__res_init':
101-
try:
102-
libc__res_init = getattr(libc, symbol)
103-
except AttributeError:
104-
pass
84+
libc = ctypes.CDLL(None)
85+
for symbol in 'res_init', '__res_init':
86+
try:
87+
libc__res_init = getattr(libc, symbol)
88+
except AttributeError:
89+
pass
10590

106-
iteritems = getattr(dict, 'iteritems', dict.items)
10791
LOG = logging.getLogger(__name__)
10892

10993

@@ -217,13 +201,13 @@ def _parse(self, fp):
217201
for line in fp:
218202
# ' #export foo=some var ' -> ['#export', 'foo=some var ']
219203
bits = shlex_split_b(line)
220-
if (not bits) or bits[0].startswith(b('#')):
204+
if (not bits) or bits[0].startswith(b'#'):
221205
continue
222206

223-
if bits[0] == b('export'):
207+
if bits[0] == b'export':
224208
bits.pop(0)
225209

226-
key, sep, value = bytes_partition(b(' ').join(bits), b('='))
210+
key, sep, value = b' '.join(bits).partition(b'=')
227211
if key and sep:
228212
yield key, value
229213

@@ -596,7 +580,7 @@ def load_module(self, fullname):
596580
mod.__path__ = []
597581
mod.__package__ = str(fullname)
598582
else:
599-
mod.__package__ = str(str_rpartition(to_text(fullname), '.')[0])
583+
mod.__package__ = str(to_text(fullname).rpartition('.')[0])
600584
exec(code, mod.__dict__)
601585
self._loaded.add(fullname)
602586
return mod
@@ -611,7 +595,7 @@ class TemporaryEnvironment(object):
611595
def __init__(self, env=None):
612596
self.original = dict(os.environ)
613597
self.env = env or {}
614-
for key, value in iteritems(self.env):
598+
for key, value in mitogen.core.iteritems(self.env):
615599
key = mitogen.core.to_text(key)
616600
value = mitogen.core.to_text(value)
617601
if value is None:
@@ -819,7 +803,7 @@ def __init__(self, interpreter_fragment, is_python, **kwargs):
819803
self.interpreter_fragment = interpreter_fragment
820804
self.is_python = is_python
821805

822-
b_ENCODING_STRING = b('# -*- coding: utf-8 -*-')
806+
b_ENCODING_STRING = b'# -*- coding: utf-8 -*-'
823807

824808
def _get_program(self):
825809
return self._rewrite_source(
@@ -852,13 +836,13 @@ def _rewrite_source(self, s):
852836
# While Ansible rewrites the #! using ansible_*_interpreter, it is
853837
# never actually used to execute the script, instead it is a shell
854838
# fragment consumed by shell/__init__.py::build_module_command().
855-
new = [b('#!') + utf8(self.interpreter_fragment)]
839+
new = [b'#!' + utf8(self.interpreter_fragment)]
856840
if self.is_python:
857841
new.append(self.b_ENCODING_STRING)
858842

859-
_, _, rest = bytes_partition(s, b('\n'))
843+
_, _, rest = s.partition(b'\n')
860844
new.append(rest)
861-
return b('\n').join(new)
845+
return b'\n'.join(new)
862846

863847

864848
class NewStyleRunner(ScriptRunner):
@@ -971,16 +955,15 @@ def _setup_args(self):
971955
# change the default encoding. This hack was removed from Ansible long ago,
972956
# but not before permeating into many third party modules.
973957
PREHISTORIC_HACK_RE = re.compile(
974-
b(r'reload\s*\(\s*sys\s*\)\s*'
975-
r'sys\s*\.\s*setdefaultencoding\([^)]+\)')
958+
br'reload\s*\(\s*sys\s*\)\s*sys\s*\.\s*setdefaultencoding\([^)]+\)',
976959
)
977960

978961
def _setup_program(self):
979962
source = ansible_mitogen.target.get_small_file(
980963
context=self.service_context,
981964
path=self.path,
982965
)
983-
self.source = self.PREHISTORIC_HACK_RE.sub(b(''), source)
966+
self.source = self.PREHISTORIC_HACK_RE.sub(b'', source)
984967

985968
def _get_code(self):
986969
try:
@@ -998,7 +981,7 @@ def _get_code(self):
998981
if mitogen.core.PY3:
999982
main_module_name = '__main__'
1000983
else:
1001-
main_module_name = b('__main__')
984+
main_module_name = b'__main__'
1002985

1003986
def _handle_magic_exception(self, mod, exc):
1004987
"""
@@ -1030,7 +1013,7 @@ def _get_module_package(self):
10301013
approximation of the original package hierarchy, so that relative
10311014
imports function correctly.
10321015
"""
1033-
pkg, sep, modname = str_rpartition(self.py_module_name, '.')
1016+
pkg, sep, _ = self.py_module_name.rpartition('.')
10341017
if not sep:
10351018
return None
10361019
if mitogen.core.PY3:
@@ -1073,7 +1056,7 @@ def _run(self):
10731056

10741057

10751058
class JsonArgsRunner(ScriptRunner):
1076-
JSON_ARGS = b('<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>')
1059+
JSON_ARGS = b'<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>'
10771060

10781061
def _get_args_contents(self):
10791062
return json.dumps(self.args).encode()

ansible_mitogen/services.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@
5050

5151
import ansible.constants
5252

53+
from ansible.module_utils.six import reraise
54+
5355
import mitogen.core
5456
import mitogen.service
5557
import ansible_mitogen.loaders
@@ -66,20 +68,6 @@
6668
ansible_mitogen.loaders.shell_loader.get('sh')
6769

6870

69-
if sys.version_info[0] == 3:
70-
def reraise(tp, value, tb):
71-
if value is None:
72-
value = tp()
73-
if value.__traceback__ is not tb:
74-
raise value.with_traceback(tb)
75-
raise value
76-
else:
77-
exec(
78-
"def reraise(tp, value, tb=None):\n"
79-
" raise tp, value, tb\n"
80-
)
81-
82-
8371
def _get_candidate_temp_dirs():
8472
try:
8573
# >=2.5

0 commit comments

Comments
 (0)