Skip to content

Commit

Permalink
[py2.py3] add function to coerce strings to six.binary_type
Browse files Browse the repository at this point in the history
python-autopxd already requires six, but the new `ensure_binary`
function is only in the git repo and hasn't been released to PyPI yet,
so I temporarily copied it here.

The source comes from:
benjaminp/six#204

It's a trivial function (every py2.py3 project has its own way to do
the same thing).

Fixes tarruda#12
Supersedes tarruda#3
  • Loading branch information
anthrotype committed Mar 24, 2018
1 parent b75f871 commit c7e3aff
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions autopxd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@
))


# TODO use upstream six.ensure_binary once next version of six is released
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, six.text_type):
return s.encode(encoding, errors)
elif isinstance(s, six.binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))


class PxdNode(object):
indent = ' '

Expand Down Expand Up @@ -311,7 +329,8 @@ def preprocess(code, extra_cpp_args=[]):
'cpp', '-nostdinc', '-D__attribute__(x)=', '-I', BUILTIN_HEADERS_DIR,
] + extra_cpp_args + ['-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
result = []
result.append(proc.communicate(input=code.encode('utf-8'))[0])
code = ensure_binary(code)
result.append(proc.communicate(input=code)[0])
while proc.poll() is None:
result.append(proc.communicate()[0])
if proc.returncode:
Expand Down Expand Up @@ -355,4 +374,5 @@ def translate(code, hdrname, extra_cpp_args=[], whitelist=None):
@click.argument('infile', type=click.File('rb'), default=sys.stdin)
@click.argument('outfile', type=click.File('wb'), default=sys.stdout)
def cli(infile, outfile):
outfile.write(translate(infile.read(), infile.name))
output = translate(infile.read(), infile.name)
outfile.write(ensure_binary(output))

0 comments on commit c7e3aff

Please sign in to comment.