From 2048a4fbcbee186683ee084aaf4cb6296ddeafd4 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 23:28:22 +0100 Subject: [PATCH] Removed unicode_literals from ui --- beets/ui/__init__.py | 85 ++++---- beets/ui/commands.py | 493 ++++++++++++++++++++++--------------------- 2 files changed, 289 insertions(+), 289 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index be47ba1cb..12f12738a 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -18,8 +18,7 @@ interface. To invoke the CLI, just call beets.ui.main(). The actual CLI commands are implemented in the ui.commands module. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import locale import optparse @@ -192,7 +191,7 @@ def input_(prompt=None): try: resp = raw_input() except EOFError: - raise UserError('stdin stream ended while input required') + raise UserError(u'stdin stream ended while input required') return resp.decode(sys.stdin.encoding or 'utf8', 'ignore') @@ -238,7 +237,7 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, found_letter = letter break else: - raise ValueError('no unambiguous lettering found') + raise ValueError(u'no unambiguous lettering found') letters[found_letter.lower()] = option index = option.index(found_letter) @@ -321,9 +320,9 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, # Make a fallback prompt too. This is displayed if the user enters # something that is not recognized. if not fallback_prompt: - fallback_prompt = 'Enter one of ' + fallback_prompt = u'Enter one of ' if numrange: - fallback_prompt += '%i-%i, ' % numrange + fallback_prompt += u'%i-%i, ' % numrange fallback_prompt += ', '.join(display_letters) + ':' resp = input_(prompt) @@ -362,9 +361,9 @@ def input_yn(prompt, require=False): "yes" unless `require` is `True`, in which case there is no default. """ sel = input_options( - ('y', 'n'), require, prompt, 'Enter Y or N:' + ('y', 'n'), require, prompt, u'Enter Y or N:' ) - return sel == 'y' + return sel == u'y' def input_select_items(prompt, items, rep): @@ -378,15 +377,15 @@ def input_select_items(prompt, items, rep): """ out_items = [] choice = input_options( - ('y', 'n', 's'), False, - '%s? (Yes/no/select)' % prompt) + (u'y', u'n', u's'), False, + u'%s? (Yes/no/select)' % prompt) print() # go to a new line - if choice == 'y': + if choice == u'y': out_items = items - elif choice == 's': + elif choice == u's': for item in items: rep(item) - if input_yn('%s? (yes/no)' % prompt, True): + if input_yn(u'%s? (yes/no)' % prompt, True): out_items.append(item) print() # go to a new line return out_items @@ -396,14 +395,14 @@ def input_select_items(prompt, items, rep): def human_bytes(size): """Formats size, a number of bytes, in a human-readable way.""" - powers = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'H'] + powers = [u'', u'K', u'M', u'G', u'T', u'P', u'E', u'Z', u'Y', u'H'] unit = 'B' for power in powers: if size < 1024: - return "%3.1f %s%s" % (size, power, unit) + return u"%3.1f %s%s" % (size, power, unit) size /= 1024.0 - unit = 'iB' - return "big" + unit = u'iB' + return u"big" def human_seconds(interval): @@ -411,13 +410,13 @@ def human_seconds(interval): interval using English words. """ units = [ - (1, 'second'), - (60, 'minute'), - (60, 'hour'), - (24, 'day'), - (7, 'week'), - (52, 'year'), - (10, 'decade'), + (1, u'second'), + (60, u'minute'), + (60, u'hour'), + (24, u'day'), + (7, u'week'), + (52, u'year'), + (10, u'decade'), ] for i in range(len(units) - 1): increment, suffix = units[i] @@ -430,7 +429,7 @@ def human_seconds(interval): increment, suffix = units[-1] interval /= float(increment) - return "%3.1f %ss" % (interval, suffix) + return u"%3.1f %ss" % (interval, suffix) def human_seconds_short(interval): @@ -491,7 +490,7 @@ def _colorize(color, text): elif color in LIGHT_COLORS: escape = COLOR_ESCAPE + "%i;01m" % (LIGHT_COLORS[color] + 30) else: - raise ValueError('no such color %s', color) + raise ValueError(u'no such color %s', color) return escape + text + RESET_COLOR @@ -773,7 +772,7 @@ class CommonOptionsParser(optparse.OptionParser, object): Sets the album property on the options extracted from the CLI. """ album = optparse.Option(*flags, action='store_true', - help='match albums instead of tracks') + help=u'match albums instead of tracks') self.add_option(album) self._album_flags = set(flags) @@ -818,7 +817,7 @@ class CommonOptionsParser(optparse.OptionParser, object): callback=self._set_format, callback_kwargs={'fmt': '$path', 'store_true': True}, - help='print paths for matched items or albums') + help=u'print paths for matched items or albums') self.add_option(path) def add_format_option(self, flags=('-f', '--format'), target=None): @@ -846,7 +845,7 @@ class CommonOptionsParser(optparse.OptionParser, object): opt = optparse.Option(*flags, action='callback', callback=self._set_format, callback_kwargs=kwargs, - help='print with custom format') + help=u'print with custom format') self.add_option(opt) def add_all_common_options(self): @@ -912,7 +911,7 @@ class SubcommandsOptionParser(CommonOptionsParser): """ # A more helpful default usage. if 'usage' not in kwargs: - kwargs['usage'] = """ + kwargs['usage'] = u""" %prog COMMAND [ARGS...] %prog help COMMAND""" kwargs['add_help_option'] = False @@ -1020,7 +1019,7 @@ class SubcommandsOptionParser(CommonOptionsParser): cmdname = args.pop(0) subcommand = self._subcommand_for_name(cmdname) if not subcommand: - raise UserError("unknown command '{0}'".format(cmdname)) + raise UserError(u"unknown command '{0}'".format(cmdname)) suboptions, subargs = subcommand.parse_args(args) return subcommand, suboptions, subargs @@ -1072,7 +1071,7 @@ def _load_plugins(config): """ paths = config['pluginpath'].get(confit.StrSeq(split=False)) paths = map(util.normpath, paths) - log.debug('plugin paths: {0}', util.displayable_path(paths)) + log.debug(u'plugin paths: {0}', util.displayable_path(paths)) import beetsplug beetsplug.__path__ = paths + beetsplug.__path__ @@ -1142,10 +1141,10 @@ def _configure(options): old_key = 'list_format_{0}'.format(elem) if config[old_key].exists(): new_key = 'format_{0}'.format(elem) - log.warning('Warning: configuration uses "{0}" which is deprecated' - ' in favor of "{1}" now that it affects all commands. ' - 'See changelog & documentation.'.format(old_key, - new_key)) + log.warning( + u'Warning: configuration uses "{0}" which is deprecated' + u' in favor of "{1}" now that it affects all commands. ' + u'See changelog & documentation.'.format(old_key, new_key)) config[new_key].set(config[old_key]) config_path = config.user_config_path() @@ -1174,7 +1173,7 @@ def _open_library(config): ) lib.get_item(0) # Test database connection. except (sqlite3.OperationalError, sqlite3.DatabaseError): - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) raise UserError(u"database file {0} could not be opened".format( util.displayable_path(dbpath) )) @@ -1193,15 +1192,15 @@ def _raw_main(args, lib=None): parser.add_format_option(flags=('--format-item',), target=library.Item) parser.add_format_option(flags=('--format-album',), target=library.Album) parser.add_option('-l', '--library', dest='library', - help='library database file to use') + help=u'library database file to use') parser.add_option('-d', '--directory', dest='directory', - help="destination music directory") + help=u"destination music directory") parser.add_option('-v', '--verbose', dest='verbose', action='count', - help='log more details (use twice for even more)') + help=u'log more details (use twice for even more)') parser.add_option('-c', '--config', dest='config', - help='path to configuration file') + help=u'path to configuration file') parser.add_option('-h', '--help', dest='help', action='store_true', - help='show this help message and exit') + help=u'show this help message and exit') parser.add_option('--version', dest='version', action='store_true', help=optparse.SUPPRESS_HELP) @@ -1257,4 +1256,4 @@ def main(args=None): raise except KeyboardInterrupt: # Silently ignore ^C except in verbose mode. - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 192c920ef..869702e4a 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -17,8 +17,7 @@ interface. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import re @@ -72,9 +71,9 @@ def _do_query(lib, query, album, also_items=True): items = list(lib.items(query)) if album and not albums: - raise ui.UserError('No matching albums found.') + raise ui.UserError(u'No matching albums found.') elif not album and not items: - raise ui.UserError('No matching items found.') + raise ui.UserError(u'No matching items found.') return items, albums @@ -94,25 +93,25 @@ def fields_func(lib, opts, args): names.sort() print_(" " + "\n ".join(names)) - print_("Item fields:") + print_(u"Item fields:") _print_rows(library.Item.all_keys()) - print_("Album fields:") + print_(u"Album fields:") _print_rows(library.Album.all_keys()) with lib.transaction() as tx: # The SQL uses the DISTINCT to get unique values from the query unique_fields = 'SELECT DISTINCT key FROM (%s)' - print_("Item flexible attributes:") + print_(u"Item flexible attributes:") _print_keys(tx.query(unique_fields % library.Item._flex_table)) - print_("Album flexible attributes:") + print_(u"Album flexible attributes:") _print_keys(tx.query(unique_fields % library.Album._flex_table)) fields_cmd = ui.Subcommand( 'fields', - help='show fields available for queries and format strings' + help=u'show fields available for queries and format strings' ) fields_cmd.func = fields_func default_commands.append(fields_cmd) @@ -125,7 +124,7 @@ class HelpCommand(ui.Subcommand): def __init__(self): super(HelpCommand, self).__init__( 'help', aliases=('?',), - help='give detailed help on a specific sub-command', + help=u'give detailed help on a specific sub-command', ) def func(self, lib, opts, args): @@ -133,7 +132,7 @@ class HelpCommand(ui.Subcommand): cmdname = args[0] helpcommand = self.root_parser._subcommand_for_name(cmdname) if not helpcommand: - raise ui.UserError("unknown command '{0}'".format(cmdname)) + raise ui.UserError(u"unknown command '{0}'".format(cmdname)) helpcommand.print_help() else: self.root_parser.print_help() @@ -180,7 +179,7 @@ def dist_string(dist): """Formats a distance (a float) as a colorized similarity percentage string. """ - out = '%.1f%%' % ((1 - dist) * 100) + out = u'%.1f%%' % ((1 - dist) * 100) if dist <= config['match']['strong_rec_thresh'].as_number(): out = ui.colorize('text_success', out) elif dist <= config['match']['medium_rec_thresh'].as_number(): @@ -203,7 +202,7 @@ def penalty_string(distance, limit=None): if penalties: if limit and len(penalties) > limit: penalties = penalties[:limit] + ['...'] - return ui.colorize('text_warning', '(%s)' % ', '.join(penalties)) + return ui.colorize('text_warning', u'(%s)' % ', '.join(penalties)) def show_change(cur_artist, cur_album, match): @@ -254,21 +253,21 @@ def show_change(cur_artist, cur_album, match): artist_l, artist_r = ui.colordiff(artist_l, artist_r) album_l, album_r = ui.colordiff(album_l, album_r) - print_("Correcting tags from:") + print_(u"Correcting tags from:") show_album(artist_l, album_l) - print_("To:") + print_(u"To:") show_album(artist_r, album_r) else: print_(u"Tagging:\n {0.artist} - {0.album}".format(match.info)) # Data URL. if match.info.data_url: - print_('URL:\n %s' % match.info.data_url) + print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. - info.append('(Similarity: %s)' % dist_string(match.distance)) + info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: @@ -276,7 +275,7 @@ def show_change(cur_artist, cur_album, match): # Disambiguation. disambig = disambig_string(match.info) if disambig: - info.append(ui.colorize('text_highlight_minor', '(%s)' % disambig)) + info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) # Tracks. @@ -294,16 +293,16 @@ def show_change(cur_artist, cur_album, match): if medium != track_info.medium or disctitle != track_info.disctitle: media = match.info.media or 'Media' if match.info.mediums > 1 and track_info.disctitle: - lhs = '%s %s: %s' % (media, track_info.medium, - track_info.disctitle) + lhs = u'%s %s: %s' % (media, track_info.medium, + track_info.disctitle) elif match.info.mediums > 1: - lhs = '%s %s' % (media, track_info.medium) + lhs = u'%s %s' % (media, track_info.medium) elif track_info.disctitle: - lhs = '%s: %s' % (media, track_info.disctitle) + lhs = u'%s: %s' % (media, track_info.disctitle) else: lhs = None if lhs: - lines.append((lhs, '', 0)) + lines.append((lhs, u'', 0)) medium, disctitle = track_info.medium, track_info.disctitle # Titles. @@ -346,9 +345,9 @@ def show_change(cur_artist, cur_album, match): rhs += ' %s' % penalties if lhs != rhs: - lines.append((' * %s' % lhs, rhs, lhs_width)) + lines.append((u' * %s' % lhs, rhs, lhs_width)) elif config['import']['detail']: - lines.append((' * %s' % lhs, '', lhs_width)) + lines.append((u' * %s' % lhs, '', lhs_width)) # Print each track in two columns, or across two lines. col_width = (ui.term_width() - len(''.join([' * ', ' -> ']))) // 2 @@ -365,22 +364,22 @@ def show_change(cur_artist, cur_album, match): # Missing and unmatched tracks. if match.extra_tracks: - print_('Missing tracks ({0}/{1} - {2:.1%}):'.format( + print_(u'Missing tracks ({0}/{1} - {2:.1%}):'.format( len(match.extra_tracks), len(match.info.tracks), len(match.extra_tracks) / len(match.info.tracks) )) for track_info in match.extra_tracks: - line = ' ! %s (#%s)' % (track_info.title, format_index(track_info)) + line = u' ! %s (#%s)' % (track_info.title, format_index(track_info)) if track_info.length: - line += ' (%s)' % ui.human_seconds_short(track_info.length) + line += u' (%s)' % ui.human_seconds_short(track_info.length) print_(ui.colorize('text_warning', line)) if match.extra_items: - print_('Unmatched tracks ({0}):'.format(len(match.extra_items))) + print_(u'Unmatched tracks ({0}):'.format(len(match.extra_items))) for item in match.extra_items: - line = ' ! %s (#%s)' % (item.title, format_index(item)) + line = u' ! %s (#%s)' % (item.title, format_index(item)) if item.length: - line += ' (%s)' % ui.human_seconds_short(item.length) + line += u' (%s)' % ui.human_seconds_short(item.length) print_(ui.colorize('text_warning', line)) @@ -395,22 +394,22 @@ def show_item_change(item, match): cur_artist, new_artist = ui.colordiff(cur_artist, new_artist) cur_title, new_title = ui.colordiff(cur_title, new_title) - print_("Correcting track tags from:") - print_(" %s - %s" % (cur_artist, cur_title)) - print_("To:") - print_(" %s - %s" % (new_artist, new_title)) + print_(u"Correcting track tags from:") + print_(u" %s - %s" % (cur_artist, cur_title)) + print_(u"To:") + print_(u" %s - %s" % (new_artist, new_title)) else: - print_("Tagging track: %s - %s" % (cur_artist, cur_title)) + print_(u"Tagging track: %s - %s" % (cur_artist, cur_title)) # Data URL. if match.info.data_url: - print_('URL:\n %s' % match.info.data_url) + print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. - info.append('(Similarity: %s)' % dist_string(match.distance)) + info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: @@ -418,7 +417,7 @@ def show_item_change(item, match): # Disambiguation. disambig = disambig_string(match.info) if disambig: - info.append(ui.colorize('text_highlight_minor', '(%s)' % disambig)) + info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) @@ -432,7 +431,7 @@ def summarize_items(items, singleton): """ summary_parts = [] if not singleton: - summary_parts.append("{0} items".format(len(items))) + summary_parts.append(u"{0} items".format(len(items))) format_counts = {} for item in items: @@ -450,11 +449,11 @@ def summarize_items(items, singleton): average_bitrate = sum([item.bitrate for item in items]) / len(items) total_duration = sum([item.length for item in items]) total_filesize = sum([item.filesize for item in items]) - summary_parts.append('{0}kbps'.format(int(average_bitrate / 1000))) + summary_parts.append(u'{0}kbps'.format(int(average_bitrate / 1000))) summary_parts.append(ui.human_seconds_short(total_duration)) summary_parts.append(ui.human_bytes(total_filesize)) - return ', '.join(summary_parts) + return u', '.join(summary_parts) def _summary_judgment(rec): @@ -484,9 +483,9 @@ def _summary_judgment(rec): return None if action == importer.action.SKIP: - print_('Skipping.') + print_(u'Skipping.') elif action == importer.action.ASIS: - print_('Importing as-is.') + print_(u'Importing as-is.') return action @@ -525,31 +524,31 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Zero candidates. if not candidates: if singleton: - print_("No matching recordings found.") - opts = ('Use as-is', 'Skip', 'Enter search', 'enter Id', - 'aBort') + print_(u"No matching recordings found.") + opts = (u'Use as-is', u'Skip', u'Enter search', u'enter Id', + u'aBort') else: - print_("No matching release found for {0} tracks." + print_(u"No matching release found for {0} tracks." .format(itemcount)) - print_('For help, see: ' - 'http://beets.readthedocs.org/en/latest/faq.html#nomatch') - opts = ('Use as-is', 'as Tracks', 'Group albums', 'Skip', - 'Enter search', 'enter Id', 'aBort') + print_(u'For help, see: ' + u'http://beets.readthedocs.org/en/latest/faq.html#nomatch') + opts = (u'Use as-is', u'as Tracks', u'Group albums', u'Skip', + u'Enter search', u'enter Id', u'aBort') sel = ui.input_options(opts + extra_opts) - if sel == 'u': + if sel == u'u': return importer.action.ASIS - elif sel == 't': + elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == 'e': + elif sel == u'e': return importer.action.MANUAL - elif sel == 's': + elif sel == u's': return importer.action.SKIP - elif sel == 'b': + elif sel == u'b': raise importer.ImportAbort() - elif sel == 'i': + elif sel == u'i': return importer.action.MANUAL_ID - elif sel == 'g': + elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: return sel @@ -595,35 +594,35 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, disambig = disambig_string(match.info) if disambig: line.append(ui.colorize('text_highlight_minor', - '(%s)' % disambig)) + u'(%s)' % disambig)) - print_(' '.join(line)) + print_(u' '.join(line)) # Ask the user for a choice. if singleton: - opts = ('Skip', 'Use as-is', 'Enter search', 'enter Id', - 'aBort') + opts = (u'Skip', u'Use as-is', u'Enter search', u'enter Id', + u'aBort') else: - opts = ('Skip', 'Use as-is', 'as Tracks', 'Group albums', - 'Enter search', 'enter Id', 'aBort') + opts = (u'Skip', u'Use as-is', u'as Tracks', u'Group albums', + u'Enter search', u'enter Id', u'aBort') sel = ui.input_options(opts + extra_opts, numrange=(1, len(candidates))) - if sel == 's': + if sel == u's': return importer.action.SKIP - elif sel == 'u': + elif sel == u'u': return importer.action.ASIS - elif sel == 'm': + elif sel == u'm': pass - elif sel == 'e': + elif sel == u'e': return importer.action.MANUAL - elif sel == 't': + elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == 'b': + elif sel == u'b': raise importer.ImportAbort() - elif sel == 'i': + elif sel == u'i': return importer.action.MANUAL_ID - elif sel == 'g': + elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: return sel @@ -647,38 +646,38 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Ask for confirmation. if singleton: - opts = ('Apply', 'More candidates', 'Skip', 'Use as-is', - 'Enter search', 'enter Id', 'aBort') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'Enter search', u'enter Id', u'aBort') else: - opts = ('Apply', 'More candidates', 'Skip', 'Use as-is', - 'as Tracks', 'Group albums', 'Enter search', 'enter Id', - 'aBort') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') default = config['import']['default_action'].as_choice({ - 'apply': 'a', - 'skip': 's', - 'asis': 'u', - 'none': None, + u'apply': u'a', + u'skip': u's', + u'asis': u'u', + u'none': None, }) if default is None: require = True sel = ui.input_options(opts + extra_opts, require=require, default=default) - if sel == 'a': + if sel == u'a': return match - elif sel == 'g': + elif sel == u'g': return importer.action.ALBUMS - elif sel == 's': + elif sel == u's': return importer.action.SKIP - elif sel == 'u': + elif sel == u'u': return importer.action.ASIS - elif sel == 't': + elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == 'e': + elif sel == u'e': return importer.action.MANUAL - elif sel == 'b': + elif sel == u'b': raise importer.ImportAbort() - elif sel == 'i': + elif sel == u'i': return importer.action.MANUAL_ID elif sel in extra_actions: return sel @@ -688,15 +687,15 @@ def manual_search(singleton): """Input either an artist and album (for full albums) or artist and track name (for singletons) for manual search. """ - artist = input_('Artist:') - name = input_('Track:' if singleton else 'Album:') + artist = input_(u'Artist:') + name = input_(u'Track:' if singleton else u'Album:') return artist.strip(), name.strip() def manual_id(singleton): """Input an ID, either for an album ("release") or a track ("recording"). """ - prompt = u'Enter {0} ID:'.format('recording' if singleton else 'release') + prompt = u'Enter {0} ID:'.format(u'recording' if singleton else u'release') return input_(prompt).strip() @@ -821,37 +820,37 @@ class TerminalImportSession(importer.ImportSession): that's already in the library. """ log.warn(u"This {0} is already in the library!", - ("album" if task.is_album else "item")) + (u"album" if task.is_album else u"item")) if config['import']['quiet']: # In quiet mode, don't prompt -- just skip. log.info(u'Skipping.') - sel = 's' + sel = u's' else: # Print some detail about the existing and new items so the # user can make an informed decision. for duplicate in found_duplicates: - print_("Old: " + summarize_items( + print_(u"Old: " + summarize_items( list(duplicate.items()) if task.is_album else [duplicate], not task.is_album, )) - print_("New: " + summarize_items( + print_(u"New: " + summarize_items( task.imported_items(), not task.is_album, )) sel = ui.input_options( - ('Skip new', 'Keep both', 'Remove old') + (u'Skip new', u'Keep both', u'Remove old') ) - if sel == 's': + if sel == u's': # Skip new. task.set_choice(importer.action.SKIP) - elif sel == 'k': + elif sel == u'k': # Keep both. Do nothing; leave the choice intact. pass - elif sel == 'r': + elif sel == u'r': # Remove old. task.should_remove_duplicates = True else: @@ -859,7 +858,7 @@ class TerminalImportSession(importer.ImportSession): def should_resume(self, path): return ui.input_yn(u"Import of the directory:\n{0}\n" - "was interrupted. Resume (Y/n)?" + u"was interrupted. Resume (Y/n)?" .format(displayable_path(path))) def _get_plugin_choices(self, task): @@ -878,14 +877,14 @@ class TerminalImportSession(importer.ImportSession): extra_choices = list(chain(*plugins.send('before_choose_candidate', session=self, task=task))) # Take into account default options, for duplicate checking. - all_choices = [PromptChoice('a', 'Apply', None), - PromptChoice('s', 'Skip', None), - PromptChoice('u', 'Use as-is', None), - PromptChoice('t', 'as Tracks', None), - PromptChoice('g', 'Group albums', None), - PromptChoice('e', 'Enter search', None), - PromptChoice('i', 'enter Id', None), - PromptChoice('b', 'aBort', None)] +\ + all_choices = [PromptChoice(u'a', u'Apply', None), + PromptChoice(u's', u'Skip', None), + PromptChoice(u'u', u'Use as-is', None), + PromptChoice(u't', u'as Tracks', None), + PromptChoice(u'g', u'Group albums', None), + PromptChoice(u'e', u'Enter search', None), + PromptChoice(u'i', u'enter Id', None), + PromptChoice(u'b', u'aBort', None)] +\ extra_choices short_letters = [c.short for c in all_choices] @@ -919,7 +918,7 @@ def import_files(lib, paths, query): # Check parameter consistency. if config['import']['quiet'] and config['import']['timid']: - raise ui.UserError("can't be both quiet and timid") + raise ui.UserError(u"can't be both quiet and timid") # Open the log. if config['import']['log'].get() is not None: @@ -959,90 +958,90 @@ def import_func(lib, opts, args): query = None paths = args if not paths: - raise ui.UserError('no path specified') + raise ui.UserError(u'no path specified') import_files(lib, paths, query) import_cmd = ui.Subcommand( - 'import', help='import new music', aliases=('imp', 'im') + u'import', help=u'import new music', aliases=(u'imp', u'im') ) import_cmd.parser.add_option( - '-c', '--copy', action='store_true', default=None, - help="copy tracks into library directory (default)" + u'-c', u'--copy', action='store_true', default=None, + help=u"copy tracks into library directory (default)" ) import_cmd.parser.add_option( - '-C', '--nocopy', action='store_false', dest='copy', - help="don't copy tracks (opposite of -c)" + u'-C', u'--nocopy', action='store_false', dest='copy', + help=u"don't copy tracks (opposite of -c)" ) import_cmd.parser.add_option( - '-w', '--write', action='store_true', default=None, - help="write new metadata to files' tags (default)" + u'-w', u'--write', action='store_true', default=None, + help=u"write new metadata to files' tags (default)" ) import_cmd.parser.add_option( - '-W', '--nowrite', action='store_false', dest='write', - help="don't write metadata (opposite of -w)" + u'-W', u'--nowrite', action='store_false', dest='write', + help=u"don't write metadata (opposite of -w)" ) import_cmd.parser.add_option( - '-a', '--autotag', action='store_true', dest='autotag', - help="infer tags for imported files (default)" + u'-a', u'--autotag', action='store_true', dest='autotag', + help=u"infer tags for imported files (default)" ) import_cmd.parser.add_option( - '-A', '--noautotag', action='store_false', dest='autotag', - help="don't infer tags for imported files (opposite of -a)" + u'-A', u'--noautotag', action='store_false', dest='autotag', + help=u"don't infer tags for imported files (opposite of -a)" ) import_cmd.parser.add_option( - '-p', '--resume', action='store_true', default=None, - help="resume importing if interrupted" + u'-p', u'--resume', action='store_true', default=None, + help=u"resume importing if interrupted" ) import_cmd.parser.add_option( - '-P', '--noresume', action='store_false', dest='resume', - help="do not try to resume importing" + u'-P', u'--noresume', action='store_false', dest='resume', + help=u"do not try to resume importing" ) import_cmd.parser.add_option( - '-q', '--quiet', action='store_true', dest='quiet', - help="never prompt for input: skip albums instead" + u'-q', u'--quiet', action='store_true', dest='quiet', + help=u"never prompt for input: skip albums instead" ) import_cmd.parser.add_option( - '-l', '--log', dest='log', - help='file to log untaggable albums for later review' + u'-l', u'--log', dest='log', + help=u'file to log untaggable albums for later review' ) import_cmd.parser.add_option( - '-s', '--singletons', action='store_true', - help='import individual tracks instead of full albums' + u'-s', u'--singletons', action='store_true', + help=u'import individual tracks instead of full albums' ) import_cmd.parser.add_option( - '-t', '--timid', dest='timid', action='store_true', - help='always confirm all actions' + u'-t', u'--timid', dest='timid', action='store_true', + help=u'always confirm all actions' ) import_cmd.parser.add_option( - '-L', '--library', dest='library', action='store_true', - help='retag items matching a query' + u'-L', u'--library', dest='library', action='store_true', + help=u'retag items matching a query' ) import_cmd.parser.add_option( - '-i', '--incremental', dest='incremental', action='store_true', - help='skip already-imported directories' + u'-i', u'--incremental', dest='incremental', action='store_true', + help=u'skip already-imported directories' ) import_cmd.parser.add_option( - '-I', '--noincremental', dest='incremental', action='store_false', - help='do not skip already-imported directories' + u'-I', u'--noincremental', dest='incremental', action='store_false', + help=u'do not skip already-imported directories' ) import_cmd.parser.add_option( - '--flat', dest='flat', action='store_true', - help='import an entire tree as a single album' + u'--flat', dest='flat', action='store_true', + help=u'import an entire tree as a single album' ) import_cmd.parser.add_option( - '-g', '--group-albums', dest='group_albums', action='store_true', - help='group tracks in a folder into separate albums' + u'-g', u'--group-albums', dest='group_albums', action='store_true', + help=u'group tracks in a folder into separate albums' ) import_cmd.parser.add_option( - '--pretend', dest='pretend', action='store_true', - help='just print the files to import' + u'--pretend', dest='pretend', action='store_true', + help=u'just print the files to import' ) import_cmd.parser.add_option( - '-S', '--search-id', dest='search_ids', action='append', + u'-S', u'--search-id', dest='search_ids', action='append', metavar='BACKEND_ID', - help='restrict matching to a specific metadata backend ID' + help=u'restrict matching to a specific metadata backend ID' ) import_cmd.func = import_func default_commands.append(import_cmd) @@ -1066,9 +1065,9 @@ def list_func(lib, opts, args): list_items(lib, decargs(args), opts.album) -list_cmd = ui.Subcommand('list', help='query the library', aliases=('ls',)) -list_cmd.parser.usage += "\n" \ - 'Example: %prog -f \'$album: $title\' artist:beatles' +list_cmd = ui.Subcommand(u'list', help=u'query the library', aliases=(u'ls',)) +list_cmd.parser.usage += u"\n" \ + u'Example: %prog -f \'$album: $title\' artist:beatles' list_cmd.parser.add_all_common_options() list_cmd.func = list_func default_commands.append(list_cmd) @@ -1116,7 +1115,7 @@ def update_items(lib, query, album, move, pretend): old_item = lib.get_item(item.id) if old_item.albumartist == old_item.artist == item.artist: item.albumartist = old_item.albumartist - item._dirty.discard('albumartist') + item._dirty.discard(u'albumartist') # Check for and display changes. changed = ui.show_model_changes(item, @@ -1169,21 +1168,21 @@ def update_func(lib, opts, args): update_cmd = ui.Subcommand( - 'update', help='update the library', aliases=('upd', 'up',) + u'update', help=u'update the library', aliases=(u'upd', u'up',) ) update_cmd.parser.add_album_option() update_cmd.parser.add_format_option() update_cmd.parser.add_option( - '-m', '--move', action='store_true', dest='move', - help="move files in the library directory" + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory" ) update_cmd.parser.add_option( - '-M', '--nomove', action='store_false', dest='move', - help="don't move files in library" + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library" ) update_cmd.parser.add_option( - '-p', '--pretend', action='store_true', - help="show all changes but do nothing" + u'-p', u'--pretend', action='store_true', + help=u"show all changes but do nothing" ) update_cmd.func = update_func default_commands.append(update_cmd) @@ -1202,11 +1201,11 @@ def remove_items(lib, query, album, delete): print_() if delete: fmt = u'$path - $title' - prompt = 'Really DELETE %i file%s (y/n)?' % \ + prompt = u'Really DELETE %i file%s (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') else: fmt = '' - prompt = 'Really remove %i item%s from the library (y/n)?' % \ + prompt = u'Really remove %i item%s from the library (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') # Show all the items. @@ -1228,11 +1227,11 @@ def remove_func(lib, opts, args): remove_cmd = ui.Subcommand( - 'remove', help='remove matching items from the library', aliases=('rm',) + u'remove', help=u'remove matching items from the library', aliases=(u'rm',) ) remove_cmd.parser.add_option( - "-d", "--delete", action="store_true", - help="also remove files from disk" + u"-d", u"--delete", action="store_true", + help=u"also remove files from disk" ) remove_cmd.parser.add_album_option() remove_cmd.func = remove_func @@ -1257,7 +1256,7 @@ def show_stats(lib, query, exact): try: total_size += os.path.getsize(item.path) except OSError as exc: - log.info('could not get size of {}: {}', item.path, exc) + log.info(u'could not get size of {}: {}', item.path, exc) else: total_size += int(item.length * item.bitrate / 8) total_time += item.length @@ -1267,11 +1266,11 @@ def show_stats(lib, query, exact): if item.album_id: albums.add(item.album_id) - size_str = '' + ui.human_bytes(total_size) + size_str = u'' + ui.human_bytes(total_size) if exact: - size_str += ' ({0} bytes)'.format(total_size) + size_str += u' ({0} bytes)'.format(total_size) - print_("""Tracks: {0} + print_(u"""Tracks: {0} Total time: {1}{2} {3}: {4} Artists: {5} @@ -1279,8 +1278,8 @@ Albums: {6} Album artists: {7}""".format( total_items, ui.human_seconds(total_time), - ' ({0:.2f} seconds)'.format(total_time) if exact else '', - 'Total size' if exact else 'Approximate total size', + u' ({0:.2f} seconds)'.format(total_time) if exact else '', + u'Total size' if exact else u'Approximate total size', size_str, len(artists), len(albums), @@ -1293,11 +1292,11 @@ def stats_func(lib, opts, args): stats_cmd = ui.Subcommand( - 'stats', help='show statistics about the library or a query' + u'stats', help=u'show statistics about the library or a query' ) stats_cmd.parser.add_option( - '-e', '--exact', action='store_true', - help='exact size and time' + u'-e', u'--exact', action='store_true', + help=u'exact size and time' ) stats_cmd.func = stats_func default_commands.append(stats_cmd) @@ -1306,17 +1305,17 @@ default_commands.append(stats_cmd) # version: Show current beets version. def show_version(lib, opts, args): - print_('beets version %s' % beets.__version__) + print_(u'beets version %s' % beets.__version__) # Show plugins. names = sorted(p.name for p in plugins.find_plugins()) if names: - print_('plugins:', ', '.join(names)) + print_(u'plugins:', ', '.join(names)) else: - print_('no plugins loaded') + print_(u'no plugins loaded') version_cmd = ui.Subcommand( - 'version', help='output version information' + u'version', help=u'output version information' ) version_cmd.func = show_version default_commands.append(version_cmd) @@ -1343,8 +1342,8 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): # Apply changes *temporarily*, preview them, and collect modified # objects. - print_('Modifying {0} {1}s.' - .format(len(objs), 'album' if album else 'item')) + print_(u'Modifying {0} {1}s.' + .format(len(objs), u'album' if album else u'item')) changed = set() for obj in objs: if print_and_modify(obj, mods, dels): @@ -1352,22 +1351,22 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): # Still something to do? if not changed: - print_('No changes to make.') + print_(u'No changes to make.') return # Confirm action. if confirm: if write and move: - extra = ', move and write tags' + extra = u', move and write tags' elif write: - extra = ' and write tags' + extra = u' and write tags' elif move: - extra = ' and move' + extra = u' and move' else: - extra = '' + extra = u'' changed = ui.input_select_items( - 'Really modify%s' % extra, changed, + u'Really modify%s' % extra, changed, lambda o: print_and_modify(o, mods, dels)) # Apply changes to database and files @@ -1413,35 +1412,35 @@ def modify_parse_args(args): def modify_func(lib, opts, args): query, mods, dels = modify_parse_args(decargs(args)) if not mods and not dels: - raise ui.UserError('no modifications specified') + raise ui.UserError(u'no modifications specified') modify_items(lib, mods, dels, query, ui.should_write(opts.write), ui.should_move(opts.move), opts.album, not opts.yes) modify_cmd = ui.Subcommand( - 'modify', help='change metadata fields', aliases=('mod',) + u'modify', help=u'change metadata fields', aliases=(u'mod',) ) modify_cmd.parser.add_option( - '-m', '--move', action='store_true', dest='move', - help="move files in the library directory" + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory" ) modify_cmd.parser.add_option( - '-M', '--nomove', action='store_false', dest='move', - help="don't move files in library" + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library" ) modify_cmd.parser.add_option( - '-w', '--write', action='store_true', default=None, - help="write new metadata to files' tags (default)" + u'-w', u'--write', action='store_true', default=None, + help=u"write new metadata to files' tags (default)" ) modify_cmd.parser.add_option( - '-W', '--nowrite', action='store_false', dest='write', - help="don't write metadata (opposite of -w)" + u'-W', u'--nowrite', action='store_false', dest='write', + help=u"don't write metadata (opposite of -w)" ) modify_cmd.parser.add_album_option() modify_cmd.parser.add_format_option(target='item') modify_cmd.parser.add_option( - '-y', '--yes', action='store_true', - help='skip confirmation' + u'-y', u'--yes', action='store_true', + help=u'skip confirmation' ) modify_cmd.func = modify_func default_commands.append(modify_cmd) @@ -1462,11 +1461,11 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False): isalbummoved = lambda album: any(isitemmoved(i) for i in album.items()) objs = [o for o in objs if (isalbummoved if album else isitemmoved)(o)] - action = 'Copying' if copy else 'Moving' - act = 'copy' if copy else 'move' - entity = 'album' if album else 'item' + action = u'Copying' if copy else u'Moving' + act = u'copy' if copy else u'move' + entity = u'album' if album else u'item' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, - 's' if len(objs) != 1 else '') + u's' if len(objs) != 1 else u'') if not objs: return @@ -1480,7 +1479,7 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False): else: if confirm: objs = ui.input_select_items( - 'Really %s' % act, objs, + u'Really %s' % act, objs, lambda o: show_path_changes( [(o.path, o.destination(basedir=dest))])) @@ -1496,30 +1495,30 @@ def move_func(lib, opts, args): if dest is not None: dest = normpath(dest) if not os.path.isdir(dest): - raise ui.UserError('no such directory: %s' % dest) + raise ui.UserError(u'no such directory: %s' % dest) move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, opts.timid) move_cmd = ui.Subcommand( - 'move', help='move or copy items', aliases=('mv',) + u'move', help=u'move or copy items', aliases=(u'mv',) ) move_cmd.parser.add_option( - '-d', '--dest', metavar='DIR', dest='dest', - help='destination directory' + u'-d', u'--dest', metavar='DIR', dest='dest', + help=u'destination directory' ) move_cmd.parser.add_option( - '-c', '--copy', default=False, action='store_true', - help='copy instead of moving' + u'-c', u'--copy', default=False, action='store_true', + help=u'copy instead of moving' ) move_cmd.parser.add_option( - '-p', '--pretend', default=False, action='store_true', - help='show how files would be moved, but don\'t touch anything' + u'-p', u'--pretend', default=False, action='store_true', + help=u'show how files would be moved, but don\'t touch anything' ) move_cmd.parser.add_option( - '-t', '--timid', dest='timid', action='store_true', - help='always confirm all actions' + u'-t', u'--timid', dest='timid', action='store_true', + help=u'always confirm all actions' ) move_cmd.parser.add_album_option() move_cmd.func = move_func @@ -1561,14 +1560,14 @@ def write_func(lib, opts, args): write_items(lib, decargs(args), opts.pretend, opts.force) -write_cmd = ui.Subcommand('write', help='write tag information to files') +write_cmd = ui.Subcommand(u'write', help=u'write tag information to files') write_cmd.parser.add_option( - '-p', '--pretend', action='store_true', - help="show all changes but do nothing" + u'-p', u'--pretend', action='store_true', + help=u"show all changes but do nothing" ) write_cmd.parser.add_option( - '-f', '--force', action='store_true', - help="write tags even if the existing tags match the database" + u'-f', u'--force', action='store_true', + help=u"write tags even if the existing tags match the database" ) write_cmd.func = write_func default_commands.append(write_cmd) @@ -1618,29 +1617,29 @@ def config_edit(): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: - message = "Could not edit configuration: {0}".format(exc) + message = u"Could not edit configuration: {0}".format(exc) if not editor: - message += ". Please set the EDITOR environment variable" + message += u". Please set the EDITOR environment variable" raise ui.UserError(message) -config_cmd = ui.Subcommand('config', - help='show or edit the user configuration') +config_cmd = ui.Subcommand(u'config', + help=u'show or edit the user configuration') config_cmd.parser.add_option( - '-p', '--paths', action='store_true', - help='show files that configuration was loaded from' + u'-p', u'--paths', action='store_true', + help=u'show files that configuration was loaded from' ) config_cmd.parser.add_option( - '-e', '--edit', action='store_true', - help='edit user configuration with $EDITOR' + u'-e', u'--edit', action='store_true', + help=u'edit user configuration with $EDITOR' ) config_cmd.parser.add_option( - '-d', '--defaults', action='store_true', - help='include the default configuration' + u'-d', u'--defaults', action='store_true', + help=u'include the default configuration' ) config_cmd.parser.add_option( - '-c', '--clear', action='store_false', + u'-c', u'--clear', action='store_false', dest='redact', default=True, - help='do not redact sensitive fields' + help=u'do not redact sensitive fields' ) config_cmd.func = config_func default_commands.append(config_cmd) @@ -1700,30 +1699,31 @@ def completion_script(commands): # Add global options options['_global'] = { - 'flags': ['-v', '--verbose'], - 'opts': '-l --library -c --config -d --directory -h --help'.split(' ') + 'flags': [u'-v', u'--verbose'], + 'opts': u'-l --library -c --config -d --directory -h --help'.split( + u' ') } # Add flags common to all commands options['_common'] = { - 'flags': ['-h', '--help'] + 'flags': [u'-h', u'--help'] } # Start generating the script - yield "_beet() {\n" + yield u"_beet() {\n" # Command names - yield " local commands='%s'\n" % ' '.join(command_names) - yield "\n" + yield u" local commands='%s'\n" % ' '.join(command_names) + yield u"\n" # Command aliases - yield " local aliases='%s'\n" % ' '.join(aliases.keys()) + yield u" local aliases='%s'\n" % ' '.join(aliases.keys()) for alias, cmd in aliases.items(): - yield " local alias__%s=%s\n" % (alias, cmd) - yield '\n' + yield u" local alias__%s=%s\n" % (alias, cmd) + yield u'\n' # Fields - yield " fields='%s'\n" % ' '.join( + yield u" fields='%s'\n" % ' '.join( set(library.Item._fields.keys() + library.Album._fields.keys()) ) @@ -1732,15 +1732,16 @@ def completion_script(commands): for option_type, option_list in opts.items(): if option_list: option_list = ' '.join(option_list) - yield " local %s__%s='%s'\n" % (option_type, cmd, option_list) + yield u" local %s__%s='%s'\n" % ( + option_type, cmd, option_list) - yield ' _beet_dispatch\n' - yield '}\n' + yield u' _beet_dispatch\n' + yield u'}\n' completion_cmd = ui.Subcommand( 'completion', - help='print shell script that provides command line completion' + help=u'print shell script that provides command line completion' ) completion_cmd.func = print_completion completion_cmd.hide = True