# -*- coding: utf-8 -*-
"""
kombu.utils.encoding
~~~~~~~~~~~~~~~~~~~~~

Utilities to encode text, and to safely emit text from running
applications without crashing with the infamous :exc:`UnicodeDecodeError`
exception.

"""
from __future__ import absolute_import

import sys
import traceback

from kombu.five import text_t

is_py3k = sys.version_info >= (3, 0)

if sys.platform.startswith('java'):     # pragma: no cover

    def default_encoding(isatty=True):
        return 'utf-8'
else:

    def default_encoding(isatty=True):  # noqa
        if isatty:
            return sys.getdefaultencoding()
        else:
            return sys.getfilesystemencoding()

if is_py3k:  # pragma: no cover

    def str_to_bytes(s):
        if isinstance(s, str):
            return s.encode()
        return s

    def bytes_to_str(s):
        if isinstance(s, bytes):
            return s.decode()
        return s

    def from_utf8(s, *args, **kwargs):
        return s

    def ensure_bytes(s):
        if not isinstance(s, bytes):
            return str_to_bytes(s)
        return s

    def default_encode(obj):
        return obj

    str_t = str

else:

    def str_to_bytes(s):                # noqa
        if isinstance(s, unicode):
            return s.encode()
        return s

    def bytes_to_str(s):                # noqa
        return s

    def from_utf8(s, *args, **kwargs):  # noqa
        return s.encode('utf-8', *args, **kwargs)

    def default_encode(obj):            # noqa
        return unicode(obj, default_encoding())

    str_t = unicode
    ensure_bytes = str_to_bytes


try:
    bytes_t = bytes
except NameError:  # pragma: no cover
    bytes_t = str  # noqa


def safe_str(s, errors='replace'):
    s = bytes_to_str(s)
    if not isinstance(s, (text_t, bytes)):
        return safe_repr(s, errors)
    return _safe_str(s, errors)


def _safe_str(s, errors='replace', isatty=True):
    if is_py3k:  # pragma: no cover
        if isinstance(s, str):
            return s
        try:
            return str(s)
        except Exception as exc:
            return '<Unrepresentable {0!r}: {1!r} {2!r}>'.format(
                type(s), exc, '\n'.join(traceback.format_stack()))
    encoding = default_encoding(isatty=isatty)
    try:
        if isinstance(s, unicode):
            return s.encode(encoding, errors)
        return unicode(s, encoding, errors)
    except Exception as exc:
        return '<Unrepresentable {0!r}: {1!r} {2!r}>'.format(
            type(s), exc, '\n'.join(traceback.format_stack()))


def safe_repr(o, errors='replace'):
    try:
        return repr(o)
    except Exception:
        return _safe_str(o, errors)

@@ -441,26 +441,24 @@
 ncoding(
-isatty=Tru
+file=Non
 e):%0A    
@@ -508,26 +508,24 @@
 ncoding(
-isatty=Tru
+file=Non
 e):  # n
@@ -540,18 +540,33 @@
     
-if isatty:
+file = file or sys.stdout
 %0A   
@@ -574,76 +574,49 @@
     
-    
 return 
-sys.getdefaultencoding()%0A        else:%0A            return
+getattr(file, 'encoding', None) or
  sys
@@ -1448,16 +1448,27 @@
 code(obj
+, file=None
 ):      
@@ -1525,16 +1525,20 @@
 ncoding(
+file
 ))%0A%0A    
@@ -1846,24 +1846,41 @@
 , errors)%0A%0A%0A
+if is_py3k:%0A%0A    
 def _safe_st
@@ -1906,57 +1906,19 @@
 e', 
-isatty=True):%0A    if is_py3k:  # pragma: no cover
+file=None):
 %0A   
@@ -2171,16 +2171,85 @@
 ack()))%0A
+else:%0A    def _safe_str(s, errors='replace', file=None):  # noqa%0A    
     enco
@@ -2276,23 +2276,18 @@
 ing(
-isatty=isatty
+file
 )%0A
+    
     
@@ -2291,32 +2291,36 @@
    try:%0A        
+   
+ 
 if isinstance(s,
@@ -2322,32 +2322,36 @@
 ce(s, unicode):%0A
+    
             retu
@@ -2380,32 +2380,36 @@
 errors)%0A        
+  
+  
 return unicode(s
@@ -2424,24 +2424,28 @@
 ng, errors)%0A
+    
     except E
@@ -2461,32 +2461,36 @@
 as exc:%0A        
+ 
+   
 return '%3CUnrepre
@@ -2519,32 +2519,36 @@
 %7B2!r%7D%3E'.format(%0A
+    
             type

Use safe_str(file=) instead