import sys

__all__ = ['encode', 'decode']


def encode(data, encoding='utf-8'):
    if sys.version_info.major == 2:
        if not isinstance(data, basestring):
            data = str(data)
    else:
        if not isinstance(data, str):
            data = str(data)
    if encoding is not None:
        if sys.version_info.major == 2:
            data = data.encode(encoding)
        else:
            data = bytes(data, encoding=encoding)
    return data


def decode(data, encoding='utf-8'):
    if encoding is not None:
        data = data.decode(encoding)
    return data

@@ -1,8 +1,18 @@
+import os%0A
 import s
@@ -18,206 +18,736 @@
 sys%0A
-%0A__all__ = %5B'encode', 'decode'%5D%0A%0A%0Adef encode(data, encoding='utf-8'):%0A    if sys.version_info.major == 2:%0A        if not isinstance(data, basestring):%0A            data = str(data)%0A    else:%0A        
+import logging%0A%0Afrom future.utils import raise_with_traceback%0A%0A__all__ = %5B'encode', 'decode'%5D%0A%0Alogger = logging.getLogger(__name__)%0A%0A%0Adef encode(data, encoding='utf-8'):%0A    assert encoding == 'utf-8', %22Only UTF-8 encoding is currently supported.%22%0A    # Check if data is alreqdy encoded (for the purposes of unicode only%0A    # If not, convert to a string if necessary, and then encode as utf-8 bytes%0A    if sys.version_info.major == 2:%0A        if not isinstance(data, basestring):%0A            data = unicode(data)%0A        elif not isinstance(data, unicode):%0A            return data  # UTF-8 data is already encoded%0A    else:%0A        if isinstance(data, bytes):%0A            return data  # UTF-8 data is already encoded%0A        el
 if n
@@ -797,24 +797,48 @@
 = str(data)%0A
+    # Encode UTF-8 data%0A
     if encod
@@ -866,38 +866,11 @@
     
-if sys.version_info.major == 2
+try
 :%0A  
@@ -921,116 +921,459 @@
    e
-lse:%0A            data = bytes(data, encoding=encoding)%0A    return data%0A%0A%0Adef decode(data, encoding='utf-8'):
+xcept Exception as e:%0A            if os.environ.get('DEBUG'):%0A                raise_with_traceback(e)%0A            logger.warning(%22An encoding error has occurred... continuing anyway. To capture these errors, rerun the current command prefixed with %60DEBUG=1 %60.%22)%0A            data = data.encode(encoding, errors='ignore')%0A    return data%0A%0A%0Adef decode(data, encoding='utf-8'):%0A    assert encoding == 'utf-8', %22Only UTF-8 encoding is currently supported.%22
 %0A   
@@ -1390,32 +1390,49 @@
 ng is not None:%0A
+        try:%0A    
         data = d
@@ -1448,24 +1448,353 @@
 e(encoding)%0A
+        except Exception as e:%0A            if os.environ.get('DEBUG'):%0A                raise_with_traceback(e)%0A            logger.warning(%22An decoding error has occurred... continuing anyway. To capture these errors, rerun the current command prefixed with %60DEBUG=1 %60.%22)%0A            data = data.decode(encoding, errors='ignore')%0A
     return d

Fix unicode encoding in Python 2