1
0
mirror of https://github.com/openSUSE/osc.git synced 2024-11-11 07:06:16 +01:00
github.com_openSUSE_osc/osc/util/helper.py
lethliel 4b29e1c543 add helper functions for python3 support
This functions are used in the whole code and are
mandatory for the python3 support to work. In python2
case nothing is touched.

* cmp_to_key:
  converts a cmp= into a key= function

* decode_list:
  decodes each element of a list. This is needed if
  we have a mixed list with strings and bytes.

* decode_it:
  Takes the input and checks if it is not a string.
  Then it uses chardet to get the encoding.
2018-11-08 09:55:07 +01:00

66 lines
1.6 KiB
Python

# Copyright (C) 2018 SUSE Linux. All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or (at your option) any later version.
def cmp_to_key(mycmp):
""" Converts a cmp= function into a key= function.
"""
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
def __hash__(self):
raise TypeError('hash not implemented')
return K
def decode_list(ilist):
""" Decodes the elements of a list if needed
"""
dlist = []
for elem in ilist:
if not isinstance(elem, str):
dlist.append(decode_it(elem))
else:
dlist.append(elem)
return dlist
def decode_it(obj):
""" Decodes the given object if obj is not a string
based on the chardet module if possible
"""
if isinstance(obj, str):
return obj
else:
try:
import chardet
return obj.decode(chardet.detect(obj)['encoding'])
except:
import locale
return obj.decode(locale.getlocale()[1])