From 386f58236440e1bae49bcf6e2a047fb808796155 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 22:25:03 -0700 Subject: [PATCH] Invent a new utility to deal with native strings --- beets/ui/commands.py | 4 ++-- beets/util/__init__.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 89ceef692..af18a5c0d 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1617,7 +1617,7 @@ def config_func(lib, opts, args): # Dump configuration. else: config_out = config.dump(full=opts.defaults, redact=opts.redact) - print_(util.as_string(config_out)) + print_(util.text_string(config_out)) def config_edit(): @@ -1687,7 +1687,7 @@ def completion_script(commands): """ base_script = os.path.join(_package_path('beets.ui'), 'completion_base.sh') with open(base_script, 'r') as base_script: - yield util.as_string(base_script.read()) + yield util.text_string(base_script.read()) options = {} aliases = {} diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 294074d10..ba9445f8f 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -647,6 +647,19 @@ def as_string(value): return six.text_type(value) +def text_string(value, encoding='utf8'): + """Convert a string, which can either be bytes or unicode, to + unicode. + + Text (unicode) is left untouched; bytes are decoded. This is useful + to convert from a "native string" (bytes on Python 2, str on Python + 3) to a consistently unicode value. + """ + if isinstance(value, bytes): + return value.decode(encoding) + return value + + def plurality(objs): """Given a sequence of hashble objects, returns the object that is most common in the set and the its number of appearance. The