
Since project name has changed to steth, name and path should be changed too. Change-Id: I83590ec90e1c3f4fac1faa3b842a9079b248488d
56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
# Copyright 2015 UnitedStack, Inc.
|
|
# All Rights Reserved.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
# not use this file except in compliance with the License. You may obtain
|
|
# a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
# License for the specific language governing permissions and limitations
|
|
# under the License.
|
|
|
|
import six
|
|
import sys
|
|
|
|
|
|
def safe_decode(text, incoming=None, errors='strict'):
|
|
"""Decodes incoming str using `incoming` if they're not already unicode.
|
|
|
|
:param incoming: Text's current encoding
|
|
:param errors: Errors handling policy. See here for valid
|
|
values http://docs.python.org/2/library/codecs.html
|
|
:returns: text or a unicode `incoming` encoded
|
|
representation of it.
|
|
:raises TypeError: If text is not an isntance of str
|
|
"""
|
|
if not isinstance(text, six.string_types):
|
|
raise TypeError("%s can't be decoded" % type(text))
|
|
|
|
if isinstance(text, six.text_type):
|
|
return text
|
|
|
|
if not incoming:
|
|
incoming = (sys.stdin.encoding or
|
|
sys.getdefaultencoding())
|
|
|
|
try:
|
|
return text.decode(incoming, errors)
|
|
except UnicodeDecodeError:
|
|
# Note(flaper87) If we get here, it means that
|
|
# sys.stdin.encoding / sys.getdefaultencoding
|
|
# didn't return a suitable encoding to decode
|
|
# text. This happens mostly when global LANG
|
|
# var is not set correctly and there's no
|
|
# default encoding. In this case, most likely
|
|
# python will use ASCII or ANSI encoders as
|
|
# default encodings but they won't be capable
|
|
# of decoding non-ASCII characters.
|
|
#
|
|
# Also, UTF-8 is being used since it's an ASCII
|
|
# extension.
|
|
return text.decode('utf-8', errors)
|