# coding=utf8

import io
import os
import shutil
import sys
import tarfile
import tempfile

version = "%d.%d" % (sys.version_info.major, sys.version_info.minor)
tmpdir = tempfile.mkdtemp(".%s" % version)
print("tmpdir %s" % tmpdir)
print('')

actions = []

def mktar(tarname, entryname, entrysize, entryio):
    global step
    step = "open" ; path = os.path.join(tmpdir, tarname)
    with tarfile.open(path, "w") as tar:
        step = "info" ; info = tarfile.TarInfo(entryname)
        step = "size" ; info.size = entrysize
        step = "add"  ; tar.addfile(info, entryio)

def py2_stringio(tarname, entry):
    global step
    step = "import" ; import StringIO
    step = "encode" ; data = entry
    step = "wrap"   ; source = StringIO.StringIO(data)
    step = "helper" ; mktar(tarname, entry, len(data), source)
actions.append(py2_stringio)

def io_stringio(tarname, entry):
    global step
    step = "encode" ; data = entry
    step = "wrap"   ; source = io.StringIO(data)
    step = "helper" ; mktar(tarname, entry, len(data), source)
actions.append(io_stringio)

def io_bytesio(tarname, entry):
    global step
    step = "encode" ; data = entry
    step = "wrap"   ; source = io.BytesIO(data)
    step = "helper" ; mktar(tarname, entry, len(data), source)
actions.append(io_bytesio)

def encode_default(tarname, entry):
    global step
    step = "encode" ; data = entry.encode()
    step = "wrap"   ; source = io.BytesIO(data)
    step = "helper" ; mktar(tarname, entry, len(data), source)
actions.append(encode_default)

def encode_utf8(tarname, entry):
    global step
    step = "encode" ; data = entry.encode('utf8')
    step = "wrap"   ; source = io.BytesIO(data)
    step = "helper" ; mktar(tarname, entry, len(data), source)
actions.append(encode_utf8)

longest = 0
for action in actions:
    length = 4 + len(action.__name__)
    if length > longest:
        longest = length

successful = actions[:]
for entry in ["ascii", "错误", u"7bit"]:
    print("%s %s %d %r" % (version, type(entry).__name__, len(entry), entry))
    for action in actions:
        pretty = "%*s" % (longest, action.__name__)
        try:
            global step ; step = "init"
            tarname = "%s.%s.tar" % (action.__name__, entry)
            action(tarname, entry)
            print("%s    ✓" % pretty)
        except Exception as err:
            if action in successful:
                successful.remove(action)
            print("%s    %s: %s: %s" % (pretty, step, type(err).__name__, err))
    print('')
print("successful: %s" % [action.__name__ for action in successful])

shutil.rmtree(tmpdir)

