Use new as_str method

Instead of `get(six.text_type)`, which was a surprisingly large portion of our
uses of six.
This commit is contained in:
Adrian Sampson 2016-06-25 19:16:14 -07:00
parent fa7b9999e7
commit 5efd5b21c5
28 changed files with 66 additions and 82 deletions

View file

@ -70,7 +70,7 @@ def configure():
"""Set up the python-musicbrainz-ngs module according to settings
from the beets configuration. This should be called at startup.
"""
hostname = config['musicbrainz']['host'].get(six.text_type)
hostname = config['musicbrainz']['host'].as_str()
musicbrainzngs.set_hostname(hostname)
musicbrainzngs.set_rate_limit(
config['musicbrainz']['ratelimit_interval'].as_number(),
@ -262,7 +262,7 @@ def album_info(release):
)
info.va = info.artist_id == VARIOUS_ARTISTS_ID
if info.va:
info.artist = config['va_name'].get(six.text_type)
info.artist = config['va_name'].as_str()
info.asin = release.get('asin')
info.releasegroup_id = release['release-group']['id']
info.country = release.get('country')

View file

@ -70,7 +70,7 @@ class FormattedMapping(collections.Mapping):
value = value.decode('utf8', 'ignore')
if self.for_path:
sep_repl = beets.config['path_sep_replace'].get(six.text_type)
sep_repl = beets.config['path_sep_replace'].as_str()
for sep in (os.path.sep, os.path.altsep):
if sep:
value = value.replace(sep, sep_repl)

View file

@ -14,7 +14,6 @@
# included in all copies or substantial portions of the Software.
from __future__ import division, absolute_import, print_function
import six
"""Provides the basic, interface-agnostic workflow for importing and
autotagging music files.
@ -641,7 +640,7 @@ class ImportTask(BaseImportTask):
changes['comp'] = False
else:
# VA.
changes['albumartist'] = config['va_name'].get(six.text_type)
changes['albumartist'] = config['va_name'].as_str()
changes['comp'] = True
elif self.choice_flag in (action.APPLY, action.RETAG):

View file

@ -126,7 +126,7 @@ class DateType(types.Float):
query = dbcore.query.DateQuery
def format(self, value):
return time.strftime(beets.config['time_format'].get(six.text_type),
return time.strftime(beets.config['time_format'].as_str(),
time.localtime(value or 0))
def parse(self, string):
@ -134,7 +134,7 @@ class DateType(types.Float):
# Try a formatted date string.
return time.mktime(
time.strptime(string,
beets.config['time_format'].get(six.text_type))
beets.config['time_format'].as_str())
)
except ValueError:
# Fall back to a plain timestamp number.
@ -338,7 +338,7 @@ class LibModel(dbcore.Model):
def __format__(self, spec):
if not spec:
spec = beets.config[self._format_config_key].get(six.text_type)
spec = beets.config[self._format_config_key].as_str()
result = self.evaluate_template(spec)
if isinstance(spec, bytes):
# if spec is a byte string then we must return a one as well
@ -1066,7 +1066,7 @@ class Album(LibModel):
item_dir = item_dir or self.item_dir()
filename_tmpl = Template(
beets.config['art_filename'].get(six.text_type))
beets.config['art_filename'].as_str())
subpath = self.evaluate_template(filename_tmpl, True)
if beets.config['asciify_paths']:
subpath = unidecode(subpath)
@ -1411,7 +1411,7 @@ class DefaultTemplateFunctions(object):
def tmpl_time(s, fmt):
"""Format a time value using `strftime`.
"""
cur_fmt = beets.config['time_format'].get(six.text_type)
cur_fmt = beets.config['time_format'].as_str()
return time.strftime(fmt, time.strptime(s, cur_fmt))
def tmpl_aunique(self, keys=None, disam=None):

View file

@ -524,7 +524,7 @@ def colorize(color_name, text):
global COLORS
if not COLORS:
COLORS = dict((name,
config['ui']['colors'][name].get(six.text_type))
config['ui']['colors'][name].as_str())
for name in COLOR_NAMES)
# In case a 3rd party plugin is still passing the actual color ('red')
# instead of the abstract color name ('text_error')
@ -607,7 +607,7 @@ def get_path_formats(subview=None):
subview = subview or config['paths']
for query, view in subview.items():
query = PF_KEY_QUERIES.get(query, query) # Expand common queries.
path_formats.append((query, Template(view.get(six.text_type))))
path_formats.append((query, Template(view.as_str())))
return path_formats

View file

@ -269,8 +269,8 @@ class BeatportPlugin(BeetsPlugin):
self.register_listener('import_begin', self.setup)
def setup(self, session=None):
c_key = self.config['apikey'].get(six.text_type)
c_secret = self.config['apisecret'].get(six.text_type)
c_key = self.config['apikey'].as_str()
c_secret = self.config['apisecret'].as_str()
# Get the OAuth token from a file or log in.
try:

View file

@ -1181,12 +1181,12 @@ class BPDPlugin(BeetsPlugin):
)
def func(lib, opts, args):
host = self.config['host'].get(six.text_type)
host = self.config['host'].as_str()
host = args.pop(0) if args else host
port = args.pop(0) if args else self.config['port'].get(int)
if args:
raise beets.ui.UserError(u'too many arguments')
password = self.config['password'].get(six.text_type)
password = self.config['password'].as_str()
volume = self.config['volume'].get(int)
debug = opts.debug or False
self.start_bpd(lib, host, int(port), password, volume, debug)

View file

@ -26,7 +26,6 @@ from beets.util import confit
from beets.autotag import hooks
import acoustid
from collections import defaultdict
import six
API_KEY = '1vOwZtEn'
SCORE_THRESH = 0.5
@ -182,7 +181,7 @@ class AcoustidPlugin(plugins.BeetsPlugin):
def submit_cmd_func(lib, opts, args):
try:
apikey = config['acoustid']['apikey'].get(six.text_type)
apikey = config['acoustid']['apikey'].as_str()
except confit.NotFoundError:
raise ui.UserError(u'no Acoustid user API key provided')
submit_items(self._log, apikey, lib.items(ui.decargs(args)))

View file

@ -29,7 +29,6 @@ from beets.plugins import BeetsPlugin
from beets.util.confit import ConfigTypeError
from beets import art
from beets.util.artresizer import ArtResizer
import six
_fs_lock = threading.Lock()
_temp_files = [] # Keep track of temporary transcoded files for deletion.
@ -56,7 +55,7 @@ def get_format(fmt=None):
"""Return the command template and the extension from the config.
"""
if not fmt:
fmt = config['convert']['format'].get(six.text_type).lower()
fmt = config['convert']['format'].as_str().lower()
fmt = ALIASES.get(fmt, fmt)
try:
@ -75,14 +74,14 @@ def get_format(fmt=None):
# Convenience and backwards-compatibility shortcuts.
keys = config['convert'].keys()
if 'command' in keys:
command = config['convert']['command'].get(six.text_type)
command = config['convert']['command'].as_str()
elif 'opts' in keys:
# Undocumented option for backwards compatibility with < 1.3.1.
command = u'ffmpeg -i $source -y {0} $dest'.format(
config['convert']['opts'].get(six.text_type)
config['convert']['opts'].as_str()
)
if 'extension' in keys:
extension = config['convert']['extension'].get(six.text_type)
extension = config['convert']['extension'].as_str()
return (command.encode('utf8'), extension.encode('utf8'))
@ -390,7 +389,7 @@ class ConvertPlugin(BeetsPlugin):
path_formats = ui.get_path_formats()
if not opts.format:
opts.format = self.config['format'].get(six.text_type).lower()
opts.format = self.config['format'].as_str().lower()
pretend = opts.pretend if opts.pretend is not None else \
self.config['pretend'].get(bool)
@ -423,7 +422,7 @@ class ConvertPlugin(BeetsPlugin):
"""Transcode a file automatically after it is imported into the
library.
"""
fmt = self.config['format'].get(six.text_type).lower()
fmt = self.config['format'].as_str().lower()
if should_transcode(item, fmt):
command, ext = get_format()

View file

@ -34,7 +34,6 @@ import time
import json
import socket
import os
import six
# Silence spurious INFO log lines generated by urllib3.
@ -67,8 +66,8 @@ class DiscogsPlugin(BeetsPlugin):
def setup(self, session=None):
"""Create the `discogs_client` field. Authenticate if necessary.
"""
c_key = self.config['apikey'].get(six.text_type)
c_secret = self.config['apisecret'].get(six.text_type)
c_key = self.config['apikey'].as_str()
c_secret = self.config['apisecret'].as_str()
# Get the OAuth token from a file or log in.
try:
@ -226,7 +225,7 @@ class DiscogsPlugin(BeetsPlugin):
result.data['formats'][0].get('descriptions', [])) or None
va = result.data['artists'][0]['name'].lower() == 'various'
if va:
artist = config['va_name'].get(six.text_type)
artist = config['va_name'].as_str()
year = result.data['year']
label = result.data['labels'][0]['name']
mediums = len(set(t.medium for t in tracks))

View file

@ -22,7 +22,6 @@ import re
from beets import plugins
from beets import ui
from beets.util import displayable_path
import six
def split_on_feat(artist):
@ -138,7 +137,7 @@ class FtInTitlePlugin(plugins.BeetsPlugin):
# Only update the title if it does not already contain a featured
# artist and if we do not drop featuring information.
if not drop_feat and not contains_feat(item.title):
feat_format = self.config['format'].get(six.text_type)
feat_format = self.config['format'].as_str()
new_format = feat_format.format(feat_part)
new_title = u"{0} {1}".format(item.title, new_format)
self._log.info(u'title: {0} -> {1}', item.title, new_title)

View file

@ -22,7 +22,6 @@ from beets.plugins import BeetsPlugin
from beets.dbcore.query import StringFieldQuery
from beets import config
import difflib
import six
class FuzzyQuery(StringFieldQuery):
@ -45,5 +44,5 @@ class FuzzyPlugin(BeetsPlugin):
})
def queries(self):
prefix = self.config['prefix'].get(six.text_type)
prefix = self.config['prefix'].as_str()
return {prefix: FuzzyQuery}

View file

@ -21,7 +21,6 @@ import subprocess
from beets.plugins import BeetsPlugin
from beets.ui import _arg_encoding
from beets.util import shlex_split
import six
class CodingFormatter(string.Formatter):
@ -80,8 +79,8 @@ class HookPlugin(BeetsPlugin):
for hook_index in range(len(hooks)):
hook = self.config['hooks'][hook_index]
hook_event = hook['event'].get(six.text_type)
hook_command = hook['command'].get(six.text_type)
hook_event = hook['event'].as_str()
hook_command = hook['command'].as_str()
self.create_and_register_hook(hook_event, hook_command)

View file

@ -14,7 +14,6 @@
# included in all copies or substantial portions of the Software.
from __future__ import division, absolute_import, print_function
import six
"""Write paths of imported files in various formats to ease later import in a
music player. Also allow printing the new file locations to stdout in case
@ -120,7 +119,7 @@ class ImportFeedsPlugin(BeetsPlugin):
if 'm3u' in formats:
m3u_basename = bytestring_path(
self.config['m3u_name'].get(six.text_type))
self.config['m3u_name'].as_str())
m3u_path = os.path.join(feedsdir, m3u_basename)
_write_m3u(m3u_path, paths)

View file

@ -65,14 +65,14 @@ class InlinePlugin(BeetsPlugin):
for key, view in itertools.chain(config['item_fields'].items(),
config['pathfields'].items()):
self._log.debug(u'adding item field {0}', key)
func = self.compile_inline(view.get(six.text_type), False)
func = self.compile_inline(view.as_str(), False)
if func is not None:
self.template_fields[key] = func
# Album fields.
for key, view in config['album_fields'].items():
self._log.debug(u'adding album field {0}', key)
func = self.compile_inline(view.get(six.text_type), True)
func = self.compile_inline(view.as_str(), True)
if func is not None:
self.album_template_fields[key] = func

View file

@ -23,7 +23,6 @@ import subprocess
from beets import ui
from beets import util
from beets.plugins import BeetsPlugin
import six
class KeyFinderPlugin(BeetsPlugin):
@ -53,7 +52,7 @@ class KeyFinderPlugin(BeetsPlugin):
def find_key(self, items, write=False):
overwrite = self.config['overwrite'].get(bool)
bin = util.bytestring_path(self.config['bin'].get(six.text_type))
bin = util.bytestring_path(self.config['bin'].as_str())
for item in items:
if item['initial_key'] and not overwrite:

View file

@ -187,7 +187,7 @@ class LastGenrePlugin(plugins.BeetsPlugin):
# the original tags list
tags = [x.title() for x in tags if self._is_allowed(x)]
return self.config['separator'].get(six.text_type).join(
return self.config['separator'].as_str().join(
tags[:self.config['count'].get(int)]
)
@ -299,7 +299,7 @@ class LastGenrePlugin(plugins.BeetsPlugin):
result = None
if isinstance(obj, library.Item):
result = self.fetch_artist_genre(obj)
elif obj.albumartist != config['va_name'].get(six.text_type):
elif obj.albumartist != config['va_name'].as_str():
result = self.fetch_album_artist_genre(obj)
else:
# For "Various Artists", pick the most popular track genre.

View file

@ -22,7 +22,6 @@ from beets import dbcore
from beets import config
from beets import plugins
from beets.dbcore import types
import six
API_URL = 'http://ws.audioscrobbler.com/2.0/'
@ -111,7 +110,7 @@ class CustomUser(pylast.User):
def import_lastfm(lib, log):
user = config['lastfm']['user'].get(six.text_type)
user = config['lastfm']['user'].as_str()
per_page = config['lastimport']['per_page'].get(int)
if not user:

View file

@ -259,7 +259,7 @@ class Genius(Backend):
"""Fetch lyrics from Genius via genius-api."""
def __init__(self, config, log):
super(Genius, self).__init__(config, log)
self.api_key = config['genius_api_key'].get(six.text_type)
self.api_key = config['genius_api_key'].as_str()
self.headers = {'Authorization': "Bearer %s" % self.api_key}
def search_genius(self, artist, title):
@ -470,8 +470,8 @@ class Google(Backend):
"""Fetch lyrics from Google search results."""
def __init__(self, config, log):
super(Google, self).__init__(config, log)
self.api_key = config['google_API_key'].get(six.text_type)
self.engine_id = config['google_engine_ID'].get(six.text_type)
self.api_key = config['google_API_key'].as_str()
self.engine_id = config['google_engine_ID'].as_str()
def is_lyrics(self, text, artist=None):
"""Determine whether the text seems to be valid lyrics.

View file

@ -22,7 +22,6 @@ from beets import config
import musicbrainzngs
import re
import six
SUBMISSION_CHUNK_SIZE = 200
UUID_REGEX = r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$'
@ -58,8 +57,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin):
super(MusicBrainzCollectionPlugin, self).__init__()
config['musicbrainz']['pass'].redact = True
musicbrainzngs.auth(
config['musicbrainz']['user'].get(six.text_type),
config['musicbrainz']['pass'].get(six.text_type),
config['musicbrainz']['user'].as_str(),
config['musicbrainz']['pass'].as_str(),
)
self.config.add({'auto': False})
if self.config['auto']:

View file

@ -65,14 +65,14 @@ class MPDClientWrapper(object):
self._log = log
self.music_directory = (
mpd_config['music_directory'].get(six.text_type))
mpd_config['music_directory'].as_str())
self.client = MPDClient()
def connect(self):
"""Connect to the MPD.
"""
host = mpd_config['host'].get(six.text_type)
host = mpd_config['host'].as_str()
port = mpd_config['port'].get(int)
if host[0] in ['/', '~']:
@ -84,7 +84,7 @@ class MPDClientWrapper(object):
except socket.error as e:
raise ui.UserError(u'could not connect to MPD: {0}'.format(e))
password = mpd_config['password'].get(six.text_type)
password = mpd_config['password'].as_str()
if password:
try:
self.client.password(password)

View file

@ -87,9 +87,9 @@ class MPDUpdatePlugin(BeetsPlugin):
def update(self, lib):
self.update_mpd(
config['mpd']['host'].get(six.text_type),
config['mpd']['host'].as_str(),
config['mpd']['port'].get(int),
config['mpd']['password'].get(six.text_type),
config['mpd']['password'].as_str(),
)
def update_mpd(self, host='localhost', port=6600, password=None):

View file

@ -27,7 +27,6 @@ from beets import logging
from beets import ui
from beets.plugins import BeetsPlugin
from beets.util import syspath, command_output, displayable_path
import six
# Utilities.
@ -103,7 +102,7 @@ class Bs1770gainBackend(Backend):
'method': 'replaygain',
})
self.chunk_at = config['chunk_at'].as_number()
self.method = b'--' + bytes(config['method'].get(six.text_type))
self.method = b'--' + bytes(config['method'].as_str())
cmd = b'bs1770gain'
try:
@ -257,7 +256,7 @@ class CommandBackend(Backend):
'noclip': True,
})
self.command = config["command"].get(six.text_type)
self.command = config["command"].as_str()
if self.command:
# Explicit executable path.
@ -810,7 +809,7 @@ class ReplayGainPlugin(BeetsPlugin):
})
self.overwrite = self.config['overwrite'].get(bool)
backend_name = self.config['backend'].get(six.text_type)
backend_name = self.config['backend'].as_str()
if backend_name not in self.backends:
raise ui.UserError(
u"Selected ReplayGain backend {0} is not supported. "

View file

@ -24,7 +24,6 @@ from collections import defaultdict
from beets.plugins import BeetsPlugin
from beets import ui
from beets import library
import six
def rewriter(field, rules):
@ -52,7 +51,7 @@ class RewritePlugin(BeetsPlugin):
# Gather all the rewrite rules for each field.
rules = defaultdict(list)
for key, view in self.config.items():
value = view.get(six.text_type)
value = view.as_str()
try:
fieldname, pattern = key.split(None, 1)
except ValueError:

View file

@ -19,7 +19,6 @@ from __future__ import division, absolute_import, print_function
import re
from beets.plugins import BeetsPlugin
import six
__author__ = 'baobab@heresiarch.info'
__version__ = '1.1'
@ -82,7 +81,7 @@ class ThePlugin(BeetsPlugin):
if self.config['strip']:
return r
else:
fmt = self.config['format'].get(six.text_type)
fmt = self.config['format'].as_str()
return fmt.format(r, t.strip()).strip()
else:
return u''

View file

@ -25,7 +25,6 @@ from flask import g
from werkzeug.routing import BaseConverter, PathConverter
import os
import json
import six
# Utilities.
@ -322,7 +321,7 @@ class WebPlugin(BeetsPlugin):
}
CORS(app)
# Start the web application.
app.run(host=self.config['host'].get(six.text_type),
app.run(host=self.config['host'].as_str(),
port=self.config['port'].get(int),
debug=opts.debug, threaded=True)
cmd.func = func

View file

@ -1175,7 +1175,7 @@ class LibraryFieldTypesTest(unittest.TestCase):
t = beets.library.DateType()
# format
time_format = beets.config['time_format'].get(six.text_type)
time_format = beets.config['time_format'].as_str()
time_local = time.strftime(time_format,
time.localtime(123456789))
self.assertEqual(time_local, t.format(123456789))

View file

@ -39,7 +39,6 @@ from beets import config
from beets import plugins
from beets.util.confit import ConfigError
from beets import util
import six
class ListTest(unittest.TestCase):
@ -1258,15 +1257,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper):
config['format_item'].set('$foo')
self.assertEqual(parser.parse_args([]), ({'path': None}, []))
self.assertEqual(config['format_item'].get(six.text_type), u'$foo')
self.assertEqual(config['format_item'].as_str(), u'$foo')
self.assertEqual(parser.parse_args([u'-p']),
({'path': True, 'format': u'$path'}, []))
self.assertEqual(parser.parse_args(['--path']),
({'path': True, 'format': u'$path'}, []))
self.assertEqual(config['format_item'].get(six.text_type), u'$path')
self.assertEqual(config['format_album'].get(six.text_type), u'$path')
self.assertEqual(config['format_item'].as_str(), u'$path')
self.assertEqual(config['format_album'].as_str(), u'$path')
def test_format_option(self):
parser = ui.CommonOptionsParser()
@ -1275,15 +1274,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper):
config['format_item'].set('$foo')
self.assertEqual(parser.parse_args([]), ({'format': None}, []))
self.assertEqual(config['format_item'].get(six.text_type), u'$foo')
self.assertEqual(config['format_item'].as_str(), u'$foo')
self.assertEqual(parser.parse_args([u'-f', u'$bar']),
({'format': u'$bar'}, []))
self.assertEqual(parser.parse_args([u'--format', u'$baz']),
({'format': u'$baz'}, []))
self.assertEqual(config['format_item'].get(six.text_type), u'$baz')
self.assertEqual(config['format_album'].get(six.text_type), u'$baz')
self.assertEqual(config['format_item'].as_str(), u'$baz')
self.assertEqual(config['format_album'].as_str(), u'$baz')
def test_format_option_with_target(self):
with self.assertRaises(KeyError):
@ -1298,8 +1297,8 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper):
self.assertEqual(parser.parse_args([u'-f', u'$bar']),
({'format': u'$bar'}, []))
self.assertEqual(config['format_item'].get(six.text_type), u'$bar')
self.assertEqual(config['format_album'].get(six.text_type), u'$album')
self.assertEqual(config['format_item'].as_str(), u'$bar')
self.assertEqual(config['format_album'].as_str(), u'$album')
def test_format_option_with_album(self):
parser = ui.CommonOptionsParser()
@ -1310,15 +1309,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper):
config['format_album'].set('$album')
parser.parse_args([u'-f', u'$bar'])
self.assertEqual(config['format_item'].get(six.text_type), u'$bar')
self.assertEqual(config['format_album'].get(six.text_type), u'$album')
self.assertEqual(config['format_item'].as_str(), u'$bar')
self.assertEqual(config['format_album'].as_str(), u'$album')
parser.parse_args([u'-a', u'-f', u'$foo'])
self.assertEqual(config['format_item'].get(six.text_type), u'$bar')
self.assertEqual(config['format_album'].get(six.text_type), u'$foo')
self.assertEqual(config['format_item'].as_str(), u'$bar')
self.assertEqual(config['format_album'].as_str(), u'$foo')
parser.parse_args([u'-f', u'$foo2', u'-a'])
self.assertEqual(config['format_album'].get(six.text_type), u'$foo2')
self.assertEqual(config['format_album'].as_str(), u'$foo2')
def test_add_all_common_options(self):
parser = ui.CommonOptionsParser()