From 55c68536c2adcc75216e2e2f9c76f08d6fb4fb56 Mon Sep 17 00:00:00 2001 From: Dave Hayes Date: Wed, 13 Feb 2013 09:59:58 -0600 Subject: [PATCH 0001/2280] Fix removal of suffixes for values that have them --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 71e429864..927cb389b 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -547,7 +547,7 @@ class MediaField(object): # Remove suffix. if style.suffix and isinstance(out, (str, unicode)): if out.endswith(style.suffix): - out = out[:len(style.suffix)] + out = out[:-len(style.suffix)] # MPEG-4 freeform frames are (should be?) encoded as UTF-8. if obj.type == 'mp4' and style.key.startswith('----:') and \ From 32bd7914e558a3da0dc13ac135bb97cfc984287d Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Tue, 1 Sep 2015 10:57:02 +0200 Subject: [PATCH 0002/2280] Implemented a much more robust way to check for a case sensitive filesystem --- beets/library.py | 13 +++++++++++-- docs/changelog.rst | 2 ++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 85c6e1b40..ca3428683 100644 --- a/beets/library.py +++ b/beets/library.py @@ -61,9 +61,8 @@ class PathQuery(dbcore.FieldQuery): """ super(PathQuery, self).__init__(field, pattern, fast) - # By default, the case sensitivity depends on the platform. if case_sensitive is None: - case_sensitive = platform.system() != 'Windows' + case_sensitive = self.is_filesystem_case_sensitive() self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. @@ -75,6 +74,16 @@ class PathQuery(dbcore.FieldQuery): # As a directory (prefix). self.dir_path = util.bytestring_path(os.path.join(self.file_path, b'')) + @staticmethod + def is_filesystem_case_sensitive(): + library_path = beets.config['directory'].get() + if os.path.exists(library_path): + # Check if the path to the library exists in lower and upper case + return not (os.path.exists(library_path.lower()) and + os.path.exists(library_path.upper())) + # By default, the case sensitivity depends on the platform. + return platform.system() != 'Windows' + @classmethod def is_path_query(cls, query_part): """Try to guess whether a unicode query part is a path query. diff --git a/docs/changelog.rst b/docs/changelog.rst index 344702e34..a9e92709a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ Fixes: option. * The :ref:`list-cmd` command's help output now has a small query and format string example. Thanks to :user:`pkess`. :bug:`1582` +* The check whether the file system is case sensitive or not could lead to + wrong results. It is much more robust now. 1.3.14 (August 2, 2015) From 6ad53e146617d4302ba987b077e364ce1b7df098 Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Wed, 2 Sep 2015 21:17:03 +0200 Subject: [PATCH 0003/2280] Improved version of case sensitivity checking and move method to beets.util --- beets/library.py | 14 ++------------ beets/util/__init__.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/beets/library.py b/beets/library.py index ca3428683..0f9fddafe 100644 --- a/beets/library.py +++ b/beets/library.py @@ -24,7 +24,6 @@ import unicodedata import time import re from unidecode import unidecode -import platform from beets import logging from beets.mediafile import MediaFile, MutagenError, UnreadableFileError @@ -62,7 +61,8 @@ class PathQuery(dbcore.FieldQuery): super(PathQuery, self).__init__(field, pattern, fast) if case_sensitive is None: - case_sensitive = self.is_filesystem_case_sensitive() + case_sensitive = beets.util.is_filesystem_case_sensitive( + beets.config['directory'].get()) self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. @@ -74,16 +74,6 @@ class PathQuery(dbcore.FieldQuery): # As a directory (prefix). self.dir_path = util.bytestring_path(os.path.join(self.file_path, b'')) - @staticmethod - def is_filesystem_case_sensitive(): - library_path = beets.config['directory'].get() - if os.path.exists(library_path): - # Check if the path to the library exists in lower and upper case - return not (os.path.exists(library_path.lower()) and - os.path.exists(library_path.upper())) - # By default, the case sensitivity depends on the platform. - return platform.system() != 'Windows' - @classmethod def is_path_query(cls, query_part): """Try to guess whether a unicode query part is a path query. diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 61a95baa2..f0304fc45 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -759,3 +759,41 @@ def interactive_open(target, command=None): command.append(target) return os.execlp(*command) + + +def is_filesystem_case_sensitive(path): + if os.path.exists(path): + # Check if the path to the library exists in lower and upper case + if os.path.exists(path.lower()) and \ + os.path.exists(path.upper()): + # All the paths may exist on the file system. Check if they + # refer to different files + if platform.system() != 'Windows': + # os.path.samefile is only available on Unix systems for + # python < 3.0 + return not os.path.samefile(path.lower(), + path.upper()) + # On windows we create a file with a lower case name + # and try to find the file using an upper case name. + base_file_name = 'beetsCaseSensitivityCheck' + lower = os.path.join(path, base_file_name.lower()) + upper = os.path.join(path, base_file_name.upper()) + # Check if one of the files (upper and lower case) do exist + # already + i = 0 + while os.path.exists(lower) or os.path.exists(upper): + file_name = '{0}{1}'.format(base_file_name, i) + lower = os.path.join(path, file_name.lower()) + upper = os.path.join(path, file_name.upper()) + # Create the file using a lower case name + with open(lower, 'w'): + pass + # Check if the file can be found using the upper cas name + case_sensitive = not os.path.exists(upper) + # Remove the temporary file + os.remove(lower) + return case_sensitive + else: + return True + # By default, the case sensitivity depends on the platform. + return platform.system() != 'Windows' From cd56286e86d93da86a9804513460bfd11b392f72 Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Thu, 3 Sep 2015 22:10:32 +0200 Subject: [PATCH 0004/2280] Added some documentation --- beets/library.py | 2 ++ beets/util/__init__.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/beets/library.py b/beets/library.py index 0f9fddafe..9d2a1b857 100644 --- a/beets/library.py +++ b/beets/library.py @@ -60,6 +60,8 @@ class PathQuery(dbcore.FieldQuery): """ super(PathQuery, self).__init__(field, pattern, fast) + # By default, the case sensitivity depends on the filesystem + # the library is located on. if case_sensitive is None: case_sensitive = beets.util.is_filesystem_case_sensitive( beets.config['directory'].get()) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index f0304fc45..ed1320807 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -762,6 +762,13 @@ def interactive_open(target, command=None): def is_filesystem_case_sensitive(path): + """Checks if the filesystem at the given path is case sensitive. + If the path does not exist, a case sensitive file system is + assumed if the system is not windows. + + :param path: The path to check for case sensitivity. + :return: True if the file system is case sensitive, False else. + """ if os.path.exists(path): # Check if the path to the library exists in lower and upper case if os.path.exists(path.lower()) and \ From 58ddecf7af017b3ea7774e436a71c7ce9f096e08 Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Fri, 4 Sep 2015 18:34:43 +0200 Subject: [PATCH 0005/2280] Added a Patch decorator for the os.path.samefile function to repair some previously failed test cases. --- test/test_query.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 04235906d..8507eb312 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -376,12 +376,17 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.i.store() self.lib.add_album([self.i]) - self.patcher = patch('beets.library.os.path.exists') - self.patcher.start().return_value = True + self.patcher_exists = patch('beets.library.os.path.exists') + self.patcher_exists.start().return_value = True + + self.patcher_samefile = patch('beets.library.os.path.samefile') + self.patcher_samefile.start().return_value = True def tearDown(self): super(PathQueryTest, self).tearDown() - self.patcher.stop() + + self.patcher_samefile.stop() + self.patcher_exists.stop() def test_path_exact_match(self): q = 'path:/a/b/c.mp3' @@ -504,13 +509,17 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_items_matched(results, ['path item', 'caps path']) # test platform-aware default sensitivity - with _common.system_mock('Darwin'): - q = makeq() - self.assertEqual(q.case_sensitive, True) + self.patcher_exists.stop() + try: + with _common.system_mock('Darwin'): + q = makeq() + self.assertEqual(q.case_sensitive, True) - with _common.system_mock('Windows'): - q = makeq() - self.assertEqual(q.case_sensitive, False) + with _common.system_mock('Windows'): + q = makeq() + self.assertEqual(q.case_sensitive, False) + finally: + self.patcher_exists.start() @patch('beets.library.os') def test_path_sep_detection(self, mock_os): @@ -526,7 +535,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): def test_path_detection(self): # cover existence test - self.patcher.stop() + self.patcher_exists.stop() is_path = beets.library.PathQuery.is_path_query try: @@ -546,7 +555,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): finally: os.chdir(cur_dir) finally: - self.patcher.start() + self.patcher_exists.start() class IntQueryTest(unittest.TestCase, TestHelper): From 42f99999f23d075cb85a9674fd06b42ed181abfb Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Mon, 7 Sep 2015 12:28:19 +0200 Subject: [PATCH 0006/2280] Improved the case sensitivity detection test. --- test/test_query.py | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 8507eb312..4dcf52a21 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -508,18 +508,36 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): results = self.lib.items(makeq(case_sensitive=False)) self.assert_items_matched(results, ['path item', 'caps path']) - # test platform-aware default sensitivity - self.patcher_exists.stop() - try: - with _common.system_mock('Darwin'): - q = makeq() - self.assertEqual(q.case_sensitive, True) + # Check for correct case sensitivity selection (this check + # only works for non-windows os) + with _common.system_mock('Darwin'): + # exists = True and samefile = True => Case insensitive + q = makeq() + self.assertEqual(q.case_sensitive, False) - with _common.system_mock('Windows'): - q = makeq() - self.assertEqual(q.case_sensitive, False) - finally: - self.patcher_exists.start() + self.patcher_samefile.stop() + self.patcher_samefile.start().return_value = False + + # exists = True and samefile = False => Case sensitive + q = makeq() + self.assertEqual(q.case_sensitive, True) + + self.patcher_samefile.stop() + self.patcher_samefile.start().return_value = True + + # test platform-aware default sensitivity when the library + # path does not exist (exist = False) + self.patcher_exists.stop() + self.patcher_exists.start().return_value = False + with _common.system_mock('Darwin'): + q = makeq() + self.assertEqual(q.case_sensitive, True) + + with _common.system_mock('Windows'): + q = makeq() + self.assertEqual(q.case_sensitive, False) + self.patcher_exists.stop() + self.patcher_exists.start().return_value = True @patch('beets.library.os') def test_path_sep_detection(self, mock_os): From 88ece413f3aa98f5880bc6cccdbd574d8272eb0c Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 04:49:50 +0100 Subject: [PATCH 0007/2280] Add Hook plugin to run commands on events This plugin allows users to execute scripts on different events, as well as forward any arguments from the events to the script. --- beetsplug/hook.py | 100 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 beetsplug/hook.py diff --git a/beetsplug/hook.py b/beetsplug/hook.py new file mode 100644 index 000000000..98ab73239 --- /dev/null +++ b/beetsplug/hook.py @@ -0,0 +1,100 @@ +# This file is part of beets. +# Copyright 2015, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Allows custom commands to be run when an event is emitted by beets""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +import subprocess +import sys + +from beets.plugins import BeetsPlugin + + +def create_hook_function(command, shell, substitute_args): + + # TODO: Find a better way of piping STDOUT/STDERR/STDIN between the process + # and the user. + # + # The issue with our current method is that we can only pesudo-pipe + # one (two if we count STDERR being piped to STDOUT) stream at a + # time, meaning we can't have both output and input simultaneously. + # This is due to how Popen.std(out/err) works, as + # Popen.std(out/err).readline() waits until a newline has been output + # to the stream before returning. + + def hook_function(**kwargs): + hook_command = command + + for key in kwargs: + if key in substitute_args: + hook_command = hook_command.replace(substitute_args[key], + str(kwargs[key])) + + process = subprocess.Popen(hook_command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + shell=shell) + + while process.poll() is None: + sys.stdout.write(process.stdout.readline()) + + # Ensure there's nothing left in the stream + sys.stdout.write(process.stdout.readline()) + + return hook_function + + +class HookPlugin(BeetsPlugin): + """Allows custom commands to be run when an event is emitted by beets""" + def __init__(self): + super(HookPlugin, self).__init__() + + self.config.add({ + 'hooks': [], + 'substitute_event': '%EVENT%', + 'shell': True + }) + + hooks = self.config['hooks'].get(list) + global_substitute_event = self.config['substitute_event'].get() + global_shell = self.config['shell'].get(bool) + + for hook_index in range(len(hooks)): + hook = self.config['hooks'][hook_index] + + hook_event = hook['event'].get() + hook_command = hook['command'].get() + + if 'substitute_event' in hook: + original = hook['substitute_event'].get() + else: + original = global_substitute_event + + if 'shell' in hook: + shell = hook['shell'].get(bool) + else: + shell = global_shell + + if 'substitute_args' in hook: + substitute_args = hook['substitute_args'].get(dict) + else: + substitute_args = {} + + hook_command = hook_command.replace(original, hook_event) + hook_function = create_hook_function(hook_command, + shell, + substitute_args) + + self.register_listener(hook_event, hook_function) From 4c249ac25bf81e8d9f3750b59f0c97253fc2422d Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Fri, 11 Sep 2015 12:35:41 +0200 Subject: [PATCH 0008/2280] Using GetLongPathNameW to determine file names to check for case sensitivity on windows instead of creating a file. --- beets/util/__init__.py | 45 +++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index a32c44908..1f9279b25 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -16,6 +16,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) +import ctypes import os import sys @@ -781,26 +782,30 @@ def is_filesystem_case_sensitive(path): # python < 3.0 return not os.path.samefile(path.lower(), path.upper()) - # On windows we create a file with a lower case name - # and try to find the file using an upper case name. - base_file_name = 'beetsCaseSensitivityCheck' - lower = os.path.join(path, base_file_name.lower()) - upper = os.path.join(path, base_file_name.upper()) - # Check if one of the files (upper and lower case) do exist - # already - i = 0 - while os.path.exists(lower) or os.path.exists(upper): - file_name = '{0}{1}'.format(base_file_name, i) - lower = os.path.join(path, file_name.lower()) - upper = os.path.join(path, file_name.upper()) - # Create the file using a lower case name - with open(lower, 'w'): - pass - # Check if the file can be found using the upper cas name - case_sensitive = not os.path.exists(upper) - # Remove the temporary file - os.remove(lower) - return case_sensitive + + # On windows we use GetLongPathNameW to determine the real path + # using the actual case. + def get_long_path_name(short_path): + if not isinstance(short_path, unicode): + short_path = unicode(short_path) + buf = ctypes.create_unicode_buffer(260) + get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW + return_value = get_long_path_name_w(short_path, buf, 260) + if return_value == 0 or return_value > 260: + # An error occurred + return short_path + else: + long_path = buf.value + # GetLongPathNameW does not change the case of the drive + # letter. + if len(long_path) > 1 and long_path[1] == ':': + long_path = long_path[0].upper() + long_path[1:] + return long_path + + lower = get_long_path_name(path.lower()) + upper = get_long_path_name(path.upper()) + + return lower != upper else: return True # By default, the case sensitivity depends on the platform. From 2d0c217252700af696bc3315ac9db56c3650032a Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 15:16:44 +0100 Subject: [PATCH 0009/2280] Improve the way substitute_args is iterated Iterate substitute_args instead of kwargs, as we ignore anything that is not in substitute_args already. Fix an issue where a hook argument containing non-ascii characters caused an exception. --- beetsplug/hook.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 98ab73239..c0747bce5 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -34,13 +34,18 @@ def create_hook_function(command, shell, substitute_args): # Popen.std(out/err).readline() waits until a newline has been output # to the stream before returning. + # TODO: Find a better way of converting arguments to strings, as I + # currently have a feeling that forcing everything to utf-8 might + # end up causing a mess. + def hook_function(**kwargs): hook_command = command - for key in kwargs: - if key in substitute_args: + for key in substitute_args: + if key in kwargs: hook_command = hook_command.replace(substitute_args[key], - str(kwargs[key])) + unicode(kwargs[key], + "utf-8")) process = subprocess.Popen(hook_command, stdout=subprocess.PIPE, From 1378351c07d57f1e08635f20a98ee6874c4545da Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 15:24:29 +0100 Subject: [PATCH 0010/2280] Add documentation for hook plugin --- docs/plugins/hook.rst | 77 ++++++++++++++++++++++++++++++++++++++++++ docs/plugins/index.rst | 2 ++ 2 files changed, 79 insertions(+) create mode 100644 docs/plugins/hook.rst diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst new file mode 100644 index 000000000..25010f111 --- /dev/null +++ b/docs/plugins/hook.rst @@ -0,0 +1,77 @@ +Hook Plugin +=============== + +Internally, beets sends events to plugins when an action finishes. These can +range from importing a song (``import``) to beets exiting (``cli_exit``), and +provide a very flexible way to perform actions based on the events. This plugin +allows you to run commands when an event is emitted by beets, such as syncing +your library with another drive when the library is updated. + +Hooks are currently run in the order defined in the configuration, however this +is dependent on beets itself (may change in the future) and cannot be controlled +by this plugin. + +.. _hook-configuration: + +Configuration +------------- + +To configure the plugin, make a ``hook:`` section in your configuration +file. The available options are: + +- **hooks**: A list of events and the commands to run (see :ref:`individual-hook-configuration`) + Default: Empty. +- **substitute_event**: The string to replace in each command with the name of + the event executing it. This can be used to allow one script to act + differently depending on the event it was called by. Can be individually + overridden (see :ref:`individual-hook-configuration`). + Default: ``%EVENT%`` +- **shell**: Run each command in a shell. Can be individually + overridden (see :ref:`individual-hook-configuration`). + Default: ``yes`` + +.. _individual-hook-configuration: + +Individual Hook Configuration +----------------------------- + +Each element of the ``hooks`` configuration option can be configured separately. +The available options are: + +- **event** (required): The name of the event that should cause this hook to execute. See + :ref:`Plugin Events ` for a list of possible values. +- **command** (required): The command to run when this hook executes. +- **substitute_event**: Hook-level override for ``substitute_event`` option in + :ref:`hook-configuration`. + Default: Value of top level ``substitute_event`` option (see :ref:`hook-configuration`) +- **shell**: Hook-level override for ``shell`` option in :ref:`hook-configuration`. + Default: Value of top level ``shell`` option (see :ref:`hook-configuration`). +- **substitute_args**: A key/value set where the key is the name of the an + argument passed to the event (see :ref:`Plugin Events ` for + a list of arguments for each event) and the value is the string to replace + in the command with the value of the argument. Note that any arguments that + are not strings will be converted to strings (e.g. Python objects). + Default: Empty. + +Example Configuration +--------------------- + +.. code-block:: yaml + + hook: + hooks: + # Output on exit: + # beets just exited! + # have a nice day! + - event: cli_exit + command: echo "beets just exited!" + - event: cli_exit + command: echo "have a nice day!" + + # Output on write + # writing to "" + # Where is the file being written to + - event: write + command echo "writing to \"%FILE_NAME%\"" + substitute_args: + path: %FILE_NAME% diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 3f9fbb7af..cc8a58c2e 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -46,6 +46,7 @@ Each plugin has its own set of options that can be defined in a section bearing ftintitle fuzzy freedesktop + hook ihate importadded importfeeds @@ -154,6 +155,7 @@ Miscellaneous a different directory. * :doc:`duplicates`: List duplicate tracks or albums. * :doc:`fuzzy`: Search albums and tracks with fuzzy string matching. +* :doc:`hook`: Run a command when an event is emitted by beets. * :doc:`ihate`: Automatically skip albums and tracks during the import process. * :doc:`info`: Print music files' tags to the console. * :doc:`mbcollection`: Maintain your MusicBrainz collection list. From 8fea1e65c50c4366ce166690d4eb09a297efe070 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:01:36 +0100 Subject: [PATCH 0011/2280] Add logging for hook plugin --- beetsplug/hook.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index c0747bce5..5d15a55aa 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -22,7 +22,7 @@ import sys from beets.plugins import BeetsPlugin -def create_hook_function(command, shell, substitute_args): +def create_hook_function(log, event, command, shell, substitute_args): # TODO: Find a better way of piping STDOUT/STDERR/STDIN between the process # and the user. @@ -47,6 +47,8 @@ def create_hook_function(command, shell, substitute_args): unicode(kwargs[key], "utf-8")) + log.debug('Running command {0} for event {1}', hook_command, event) + process = subprocess.Popen(hook_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, @@ -98,8 +100,8 @@ class HookPlugin(BeetsPlugin): substitute_args = {} hook_command = hook_command.replace(original, hook_event) - hook_function = create_hook_function(hook_command, - shell, - substitute_args) + hook_function = create_hook_function(self._log, hook_event, + hook_command, shell, + substitute_args) self.register_listener(hook_event, hook_function) From 0af47bff446fb5477a4e554f00138e9efc14c1d9 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:08:54 +0100 Subject: [PATCH 0012/2280] Add tests for hook plugin --- test/test_hook.py | 134 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 test/test_hook.py diff --git a/test/test_hook.py b/test/test_hook.py new file mode 100644 index 000000000..7f6665ec2 --- /dev/null +++ b/test/test_hook.py @@ -0,0 +1,134 @@ +# This file is part of beets. +# Copyright 2015, Thomas Scholtes. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +import os.path +import tempfile + +from test import _common +from test._common import unittest +from test.helper import TestHelper + +from beets import config, logging +from beets import plugins + + +def get_temporary_path(): + temporary_directory = tempfile._get_default_tempdir() + temporary_name = next(tempfile._get_candidate_names()) + + return os.path.join(temporary_directory, temporary_name) + + +# TODO: Find a good way to test shell option +class HookTest(_common.TestCase, TestHelper): + TEST_HOOK_COUNT = 5 + + def setUp(self): + self.setup_beets() # Converter is threaded + + def tearDown(self): + self.unload_plugins() + self.teardown_beets() + + def _add_hook(self, event, command, substitute_event=None, shell=None, + substitute_args=None): + + hook = { + 'event': event, + 'command': command + } + + if substitute_event is not None: + hook['substitute_event'] = substitute_event + + if shell is not None: + hook['shell'] = shell + + if substitute_args is not None: + hook['substitute_args'] = substitute_args + + hooks = config['hook']['hooks'].get(list) if 'hook' in config else [] + hooks.append(hook) + + config['hook']['hooks'] = hooks + + def test_hook_no_arguments(self): + temporary_paths = [ + get_temporary_path() for i in range(self.TEST_HOOK_COUNT) + ] + + for index, path in enumerate(temporary_paths): + self._add_hook('test_event_{0}'.format(index), + 'echo > "{0}"'.format(path)) + + self.load_plugins('hook') + + for index in range(len(temporary_paths)): + plugins.send('test_event_{0}'.format(index)) + + for path in temporary_paths: + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + def test_hook_event_substitution(self): + + temporary_directory = tempfile._get_default_tempdir() + event_names = ['test_event_{0}'.format(i) for i in + range(self.TEST_HOOK_COUNT)] + + for event in event_names: + self._add_hook(event, + 'echo > "{0}"'.format( + os.path.join(temporary_directory, '%EVENT%') + )) + + self.load_plugins('hook') + + for event in event_names: + plugins.send(event) + + for event in event_names: + path = os.path.join(temporary_directory, event) + + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + def test_hook_argument_substitution(self): + temporary_paths = [ + get_temporary_path() for i in range(self.TEST_HOOK_COUNT) + ] + + for index, path in enumerate(temporary_paths): + self._add_hook('test_event_{0}'.format(index), + 'echo > "%PATH%"'.format(path), + substitute_args = { 'path': '%PATH%' }) + + self.load_plugins('hook') + + for index, path in enumerate(temporary_paths): + plugins.send('test_event_{0}'.format(index), path = path) + + for path in temporary_paths: + self.assertTrue(os.path.isfile(path)) + os.remove(path) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') From 6a56677c7cc65c46408d9773f5b04d0142c67c10 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:23:15 +0100 Subject: [PATCH 0013/2280] Move line break to correct position --- docs/plugins/hook.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst index 25010f111..4d0c5d6b9 100644 --- a/docs/plugins/hook.rst +++ b/docs/plugins/hook.rst @@ -26,8 +26,8 @@ file. The available options are: differently depending on the event it was called by. Can be individually overridden (see :ref:`individual-hook-configuration`). Default: ``%EVENT%`` -- **shell**: Run each command in a shell. Can be individually - overridden (see :ref:`individual-hook-configuration`). +- **shell**: Run each command in a shell. Can be individually overridden (see + :ref:`individual-hook-configuration`). Default: ``yes`` .. _individual-hook-configuration: From 553dd1f39dbcb21c3bf4e088f1a12715dce9eeae Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:23:29 +0100 Subject: [PATCH 0014/2280] Add missing colon for configuration --- docs/plugins/hook.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst index 4d0c5d6b9..9ede5e998 100644 --- a/docs/plugins/hook.rst +++ b/docs/plugins/hook.rst @@ -72,6 +72,6 @@ Example Configuration # writing to "" # Where is the file being written to - event: write - command echo "writing to \"%FILE_NAME%\"" + command: echo "writing to \"%FILE_NAME%\"" substitute_args: path: %FILE_NAME% From 276c5da913ba2cb121de81986386197c0098b0f2 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:37:20 +0100 Subject: [PATCH 0015/2280] Remove unused logging import --- test/test_hook.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_hook.py b/test/test_hook.py index 7f6665ec2..0a9ff8b1b 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -22,7 +22,7 @@ from test import _common from test._common import unittest from test.helper import TestHelper -from beets import config, logging +from beets import config from beets import plugins From 8b7af7fe23dffef479e817d05e329472c7c88d56 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:38:30 +0100 Subject: [PATCH 0016/2280] Fix indentation for wrapped method call --- beetsplug/hook.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 5d15a55aa..ed6fa4e93 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -101,7 +101,7 @@ class HookPlugin(BeetsPlugin): hook_command = hook_command.replace(original, hook_event) hook_function = create_hook_function(self._log, hook_event, - hook_command, shell, - substitute_args) + hook_command, shell, + substitute_args) self.register_listener(hook_event, hook_function) From 46e5f9d4c879f05a37afcd0f1ff81ed993d74f0a Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 18:39:12 +0100 Subject: [PATCH 0017/2280] Update tests to follow PEP 8 coding style --- test/test_hook.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_hook.py b/test/test_hook.py index 0a9ff8b1b..f6b8b4941 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -115,12 +115,12 @@ class HookTest(_common.TestCase, TestHelper): for index, path in enumerate(temporary_paths): self._add_hook('test_event_{0}'.format(index), 'echo > "%PATH%"'.format(path), - substitute_args = { 'path': '%PATH%' }) + substitute_args={'path': '%PATH%'}) self.load_plugins('hook') - for index, path in enumerate(temporary_paths): - plugins.send('test_event_{0}'.format(index), path = path) + for index, path in enumerate(temporary_paths): + plugins.send('test_event_{0}'.format(index), path=path) for path in temporary_paths: self.assertTrue(os.path.isfile(path)) From 5832e8730ee1b7b104eb1cf40a3aa2638c993886 Mon Sep 17 00:00:00 2001 From: Malte Ried Date: Fri, 11 Sep 2015 20:38:53 +0200 Subject: [PATCH 0018/2280] Changed the documentation of the PathQueries to reflect the usage of the file system cas-sensitivity. --- docs/reference/query.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index e2091bb14..e3ce68004 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -202,8 +202,8 @@ Note that this only matches items that are *already in your library*, so a path query won't necessarily find *all* the audio files in a directory---just the ones you've already added to your beets library. -Path queries are case-sensitive on most platforms but case-insensitive on -Windows. +Path queries are case-sensitive if the file system the library is located on +is case-sensitive, case-insensitive otherwise. .. _query-sort: From 3d058f4b6c66dd9915650f783a7f7187e6c3f96f Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 11 Sep 2015 20:36:12 +0100 Subject: [PATCH 0019/2280] Changelog for #1603 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index dec5bc28a..1df9f45d3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,8 @@ The new features: trigger a "lots of music" warning. :bug:`1577` * :doc:`/plugins/plexupdate`: A new ``library_name`` option allows you to select which Plex library to update. :bug:`1572` :bug:`1595` +* New :doc:`/plugins/hook` that allows commands to be executed when an event is + emitted by beets. :bug:`1561` :bug:`1603` Fixes: From ae2ff6185fa4b11a8fbbd8aebfaf1a037b9aa205 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sat, 12 Sep 2015 02:09:19 +0100 Subject: [PATCH 0020/2280] Use default stdout and stderr streams for hook processes --- beetsplug/hook.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index ed6fa4e93..67595a1b3 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -50,15 +50,9 @@ def create_hook_function(log, event, command, shell, substitute_args): log.debug('Running command {0} for event {1}', hook_command, event) process = subprocess.Popen(hook_command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, shell=shell) - while process.poll() is None: - sys.stdout.write(process.stdout.readline()) - - # Ensure there's nothing left in the stream - sys.stdout.write(process.stdout.readline()) + process.wait() return hook_function From 0dff24eb96870de8479ca1b21405311a47fa236b Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sat, 12 Sep 2015 02:14:33 +0100 Subject: [PATCH 0021/2280] Move Popen call to a single line --- beetsplug/hook.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 67595a1b3..95d330ac1 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -49,10 +49,7 @@ def create_hook_function(log, event, command, shell, substitute_args): log.debug('Running command {0} for event {1}', hook_command, event) - process = subprocess.Popen(hook_command, - shell=shell) - - process.wait() + subprocess.Popen(hook_command, shell=shell).wait() return hook_function From 417a724e42017952dd6c326d5d35807ba724b9b9 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sat, 12 Sep 2015 02:15:11 +0100 Subject: [PATCH 0022/2280] Remove unused sys import and use correct platform encoding --- beetsplug/hook.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 95d330ac1..af411f20f 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -17,8 +17,8 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import subprocess -import sys +from beets.ui import _arg_encoding from beets.plugins import BeetsPlugin @@ -45,7 +45,7 @@ def create_hook_function(log, event, command, shell, substitute_args): if key in kwargs: hook_command = hook_command.replace(substitute_args[key], unicode(kwargs[key], - "utf-8")) + _arg_encoding())) log.debug('Running command {0} for event {1}', hook_command, event) From 55bd513278caedc3b0e1bd2662dc6fdf41c95df0 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sat, 12 Sep 2015 02:16:22 +0100 Subject: [PATCH 0023/2280] Remove completed TODO comments --- beetsplug/hook.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index af411f20f..7925b16c8 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -23,21 +23,6 @@ from beets.plugins import BeetsPlugin def create_hook_function(log, event, command, shell, substitute_args): - - # TODO: Find a better way of piping STDOUT/STDERR/STDIN between the process - # and the user. - # - # The issue with our current method is that we can only pesudo-pipe - # one (two if we count STDERR being piped to STDOUT) stream at a - # time, meaning we can't have both output and input simultaneously. - # This is due to how Popen.std(out/err) works, as - # Popen.std(out/err).readline() waits until a newline has been output - # to the stream before returning. - - # TODO: Find a better way of converting arguments to strings, as I - # currently have a feeling that forcing everything to utf-8 might - # end up causing a mess. - def hook_function(**kwargs): hook_command = command From 5fd836b173e3ffe525340a75f90393660d65a6ed Mon Sep 17 00:00:00 2001 From: Aaron Cruz Date: Wed, 7 Oct 2015 12:15:09 +0200 Subject: [PATCH 0024/2280] Remove yaml keys without sublists --- beetsplug/lastgenre/genres-tree.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 8e9eb12eb..c1b1a081b 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -494,8 +494,8 @@ - lyrical hip hop - merenrap - midwest hip hop: - - chicago hip hop: - - detroit hip hop: + - chicago hip hop + - detroit hip hop - horrorcore - st. louis hip hop - twin cities hip hop @@ -652,7 +652,7 @@ - glam rock - hard rock - heavy metal: - - alternative metal: + - alternative metal - black metal: - viking metal - christian metal From fe1fab9aeea942826425fb1890fc1c957b95abb8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 15:32:07 -0700 Subject: [PATCH 0025/2280] For #1617, fix laziness with a new subclass --- beets/__init__.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 4c8fa25df..e507ea2af 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -24,14 +24,23 @@ __author__ = 'Adrian Sampson ' Library = beets.library.Library -config = confit.LazyConfig('beets', __name__) -try: - included_filenames = config['include'].get(list) -except confit.NotFoundError: - included_filenames = [] +class IncludeLazyConfig(confit.LazyConfig): + """A version of Confit's LazyConfig that also merges in data from + YAML files specified in an `include` setting. + """ + def read(self, user=True, defaults=True): + super(IncludeLazyConfig, self).read(user, defaults) -for filename in included_filenames: - filename = os.path.join(config.config_dir(), filename) - if os.path.isfile(filename): - config.set_file(filename) + try: + included_filenames = self['include'].get(list) + except confit.NotFoundError: + included_filenames = [] + + for filename in included_filenames: + filename = os.path.join(self.config_dir(), filename) + if os.path.isfile(filename): + self.set_file(filename) + + +config = IncludeLazyConfig('beets', __name__) From 9f1c1134765d09df6c10e4e1f1147f2a6166f812 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 15:36:31 -0700 Subject: [PATCH 0026/2280] For #1617: Use Confit's built-in path resolution Has the side effect of raising more reasonable errors when the type is wrong. --- beets/__init__.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index e507ea2af..867ead368 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -33,14 +33,12 @@ class IncludeLazyConfig(confit.LazyConfig): super(IncludeLazyConfig, self).read(user, defaults) try: - included_filenames = self['include'].get(list) + for view in self['include'].all_contents(): + filename = view.as_filename() + if os.path.isfile(filename): + self.set_file(filename) except confit.NotFoundError: - included_filenames = [] - - for filename in included_filenames: - filename = os.path.join(self.config_dir(), filename) - if os.path.isfile(filename): - self.set_file(filename) + pass config = IncludeLazyConfig('beets', __name__) From 9bf95bf6348166639ee12fc1c806cf173d54c620 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 15:46:49 -0700 Subject: [PATCH 0027/2280] Some test code cleanup for #1586 --- test/test_query.py | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 4dcf52a21..0515c2910 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -509,35 +509,39 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_items_matched(results, ['path item', 'caps path']) # Check for correct case sensitivity selection (this check - # only works for non-windows os) + # only works on non-Windows OSes). with _common.system_mock('Darwin'): # exists = True and samefile = True => Case insensitive q = makeq() self.assertEqual(q.case_sensitive, False) + # exists = True and samefile = False => Case sensitive self.patcher_samefile.stop() self.patcher_samefile.start().return_value = False + try: + q = makeq() + self.assertEqual(q.case_sensitive, True) + finally: + self.patcher_samefile.stop() + self.patcher_samefile.start().return_value = True - # exists = True and samefile = False => Case sensitive - q = makeq() - self.assertEqual(q.case_sensitive, True) - - self.patcher_samefile.stop() - self.patcher_samefile.start().return_value = True - - # test platform-aware default sensitivity when the library - # path does not exist (exist = False) + # Test platform-aware default sensitivity when the library path + # does not exist. For the duration of this check, we change the + # `os.path.exists` mock to return False. self.patcher_exists.stop() self.patcher_exists.start().return_value = False - with _common.system_mock('Darwin'): - q = makeq() - self.assertEqual(q.case_sensitive, True) + try: + with _common.system_mock('Darwin'): + q = makeq() + self.assertEqual(q.case_sensitive, True) - with _common.system_mock('Windows'): - q = makeq() - self.assertEqual(q.case_sensitive, False) - self.patcher_exists.stop() - self.patcher_exists.start().return_value = True + with _common.system_mock('Windows'): + q = makeq() + self.assertEqual(q.case_sensitive, False) + finally: + # Restore the `os.path.exists` mock to its original state. + self.patcher_exists.stop() + self.patcher_exists.start().return_value = True @patch('beets.library.os') def test_path_sep_detection(self, mock_os): From 9e5e9a23ab828fa84d0f6025345ac7ed5acc2a3d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 15:53:26 -0700 Subject: [PATCH 0028/2280] Query case sensitivity depends on the query (#1586) This could match intuition a little more closely and also avoids a coupling with the configuration. --- beets/library.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beets/library.py b/beets/library.py index 18b739902..d1952f691 100644 --- a/beets/library.py +++ b/beets/library.py @@ -53,18 +53,18 @@ class PathQuery(dbcore.FieldQuery): escape_char = b'\\' def __init__(self, field, pattern, fast=True, case_sensitive=None): - """Create a path query. + """Create a path query. `pattern` must be a path, either to a + file or a directory. `case_sensitive` can be a bool or `None`, indicating that the - behavior should depend on the platform (the default). + behavior should depend on the filesystem. """ super(PathQuery, self).__init__(field, pattern, fast) # By default, the case sensitivity depends on the filesystem - # the library is located on. + # that the query path is located on. if case_sensitive is None: - case_sensitive = beets.util.is_filesystem_case_sensitive( - beets.config['directory'].get()) + case_sensitive = beets.util.is_filesystem_case_sensitive(pattern) self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. From 4677903844c9d81d880870f34f77327f0a4eefdb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 16:31:59 -0700 Subject: [PATCH 0029/2280] Reorganize case sensitivity check function Just a little readability enhancement. --- beets/library.py | 2 +- beets/util/__init__.py | 91 ++++++++++++++++++++++-------------------- 2 files changed, 49 insertions(+), 44 deletions(-) diff --git a/beets/library.py b/beets/library.py index d1952f691..220859f05 100644 --- a/beets/library.py +++ b/beets/library.py @@ -64,7 +64,7 @@ class PathQuery(dbcore.FieldQuery): # By default, the case sensitivity depends on the filesystem # that the query path is located on. if case_sensitive is None: - case_sensitive = beets.util.is_filesystem_case_sensitive(pattern) + case_sensitive = beets.util.case_sensitive(pattern) self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 1f9279b25..6d439f727 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -763,50 +763,55 @@ def interactive_open(targets, command=None): return os.execlp(*command) -def is_filesystem_case_sensitive(path): - """Checks if the filesystem at the given path is case sensitive. - If the path does not exist, a case sensitive file system is - assumed if the system is not windows. - - :param path: The path to check for case sensitivity. - :return: True if the file system is case sensitive, False else. +def _windows_long_path_name(short_path): + """Use Windows' `GetLongPathNameW` via ctypes to get the canonical, + long path given a short filename. """ - if os.path.exists(path): - # Check if the path to the library exists in lower and upper case - if os.path.exists(path.lower()) and \ - os.path.exists(path.upper()): - # All the paths may exist on the file system. Check if they - # refer to different files - if platform.system() != 'Windows': - # os.path.samefile is only available on Unix systems for - # python < 3.0 - return not os.path.samefile(path.lower(), - path.upper()) + if not isinstance(short_path, unicode): + short_path = unicode(short_path) + buf = ctypes.create_unicode_buffer(260) + get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW + return_value = get_long_path_name_w(short_path, buf, 260) + if return_value == 0 or return_value > 260: + # An error occurred + return short_path + else: + long_path = buf.value + # GetLongPathNameW does not change the case of the drive + # letter. + if len(long_path) > 1 and long_path[1] == ':': + long_path = long_path[0].upper() + long_path[1:] + return long_path - # On windows we use GetLongPathNameW to determine the real path - # using the actual case. - def get_long_path_name(short_path): - if not isinstance(short_path, unicode): - short_path = unicode(short_path) - buf = ctypes.create_unicode_buffer(260) - get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW - return_value = get_long_path_name_w(short_path, buf, 260) - if return_value == 0 or return_value > 260: - # An error occurred - return short_path - else: - long_path = buf.value - # GetLongPathNameW does not change the case of the drive - # letter. - if len(long_path) > 1 and long_path[1] == ':': - long_path = long_path[0].upper() + long_path[1:] - return long_path - lower = get_long_path_name(path.lower()) - upper = get_long_path_name(path.upper()) +def case_sensitive(path): + """Check whether the filesystem at the given path is case sensitive. - return lower != upper - else: - return True - # By default, the case sensitivity depends on the platform. - return platform.system() != 'Windows' + To work best, the path should point to a file or a directory. If the path + does not exist, assume a case sensitive file system on every platform + except Windows. + """ + # A fallback in case the path does not exist. + if not os.path.exists(path): + # By default, the case sensitivity depends on the platform. + return platform.system() != 'Windows' + + # If an upper-case version of the path exists but a lower-case + # version does not, then the filesystem must be case-sensitive. + # (Otherwise, we have more work to do.) + if not (os.path.exists(path.lower()) and + os.path.exists(path.upper())): + return True + + # Both versions of the path exist on the file system. Check whether + # they refer to different files by their inodes. Alas, + # `os.path.samefile` is only available on Unix systems on Python 2. + if platform.system() != 'Windows': + return not os.path.samefile(path.lower(), + path.upper()) + + # On Windows, we check whether the canonical, long filenames for the + # files are the same. + lower = _windows_long_path_name(path.lower()) + upper = _windows_long_path_name(path.upper()) + return lower != upper From a0a9af261c5ce82c846c3f5cb3c5e7914d92371a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 16:33:29 -0700 Subject: [PATCH 0030/2280] Use `syspath` in case sensitivity check (#1586) --- beets/util/__init__.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 6d439f727..61e2f4ac8 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -792,23 +792,23 @@ def case_sensitive(path): except Windows. """ # A fallback in case the path does not exist. - if not os.path.exists(path): + if not os.path.exists(syspath(path)): # By default, the case sensitivity depends on the platform. return platform.system() != 'Windows' # If an upper-case version of the path exists but a lower-case # version does not, then the filesystem must be case-sensitive. # (Otherwise, we have more work to do.) - if not (os.path.exists(path.lower()) and - os.path.exists(path.upper())): + if not (os.path.exists(syspath(path.lower())) and + os.path.exists(syspath(path.upper()))): return True # Both versions of the path exist on the file system. Check whether # they refer to different files by their inodes. Alas, # `os.path.samefile` is only available on Unix systems on Python 2. if platform.system() != 'Windows': - return not os.path.samefile(path.lower(), - path.upper()) + return not os.path.samefile(syspath(path.lower()), + syspath(path.upper())) # On Windows, we check whether the canonical, long filenames for the # files are the same. From d29cc7b2c050f8091d493a1f2b9638fc7ea57fb5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 16:36:12 -0700 Subject: [PATCH 0031/2280] Refine docs for #1586 --- docs/changelog.rst | 5 +++-- docs/reference/query.rst | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 825a8a36e..ce5a68c48 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -46,8 +46,9 @@ Fixes: written to files. Thanks to :user:`jdetrey`. :bug:`1303` :bug:`1589` * :doc:`/plugins/replaygain`: Avoid a crash when the PyAudioTools backend encounters an error. :bug:`1592` -* The check whether the file system is case sensitive or not could lead to - wrong results. It is much more robust now. +* The case sensitivity of path queries is more useful now: rather than just + guessing based on the platform, we now check the case sensitivity of your + particular filesystem. :bug:`1586` * Case-insensitive path queries might have returned nothing because of a wrong SQL query. * Fix a crash when a query contains a "+" or "-" alone in a component. diff --git a/docs/reference/query.rst b/docs/reference/query.rst index e3ce68004..452681c35 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -202,8 +202,8 @@ Note that this only matches items that are *already in your library*, so a path query won't necessarily find *all* the audio files in a directory---just the ones you've already added to your beets library. -Path queries are case-sensitive if the file system the library is located on -is case-sensitive, case-insensitive otherwise. +Path queries are case sensitive if the queried path is on a case-sensitive +filesystem. .. _query-sort: From 3c8823db9680301d9fd5f76bf405c4a02c2839ca Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Oct 2015 16:38:27 -0700 Subject: [PATCH 0032/2280] Run case sensitivity check (#1586) on bytestring This should avoid problems when querying for Unicode paths. --- beets/library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 220859f05..186a674e7 100644 --- a/beets/library.py +++ b/beets/library.py @@ -64,7 +64,8 @@ class PathQuery(dbcore.FieldQuery): # By default, the case sensitivity depends on the filesystem # that the query path is located on. if case_sensitive is None: - case_sensitive = beets.util.case_sensitive(pattern) + path = util.bytestring_path(util.normpath(pattern)) + case_sensitive = beets.util.case_sensitive(path) self.case_sensitive = case_sensitive # Use a normalized-case pattern for case-insensitive matches. From 13fede597f6c839c5c7d7a2a7fc5c8a07bb31174 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 8 Oct 2015 10:40:18 -0700 Subject: [PATCH 0033/2280] Fix my fix for #1586: iterate over views --- beets/__init__.py | 2 +- beets/util/confit.py | 26 ++++++++++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 867ead368..fbd4e10c3 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -33,7 +33,7 @@ class IncludeLazyConfig(confit.LazyConfig): super(IncludeLazyConfig, self).read(user, defaults) try: - for view in self['include'].all_contents(): + for view in self['include']: filename = view.as_filename() if os.path.isfile(filename): self.set_file(filename) diff --git a/beets/util/confit.py b/beets/util/confit.py index 4c5b30cb6..2614f7ed7 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -215,10 +215,28 @@ class ConfigView(object): return '<{}: {}>'.format(self.__class__.__name__, self.name) def __iter__(self): - # Prevent list(config) from using __getitem__ and entering an - # infinite loop. - raise TypeError(u"{!r} object is not " - u"iterable".format(self.__class__.__name__)) + """Iterate over the keys of a dictionary view or the *subviews* + of a list view. + """ + # Try getting the keys, if this is a dictionary view. + try: + keys = self.keys() + for key in keys: + yield key + + except ConfigTypeError: + # Otherwise, try iterating over a list. + collection = self.get() + if not isinstance(collection, (list, tuple)): + raise ConfigTypeError( + '{0} must be a dictionary or a list, not {1}'.format( + self.name, type(collection).__name__ + ) + ) + + # Yield all the indices in the list. + for index in range(len(collection)): + yield self[index] def __getitem__(self, key): """Get a subview of this view.""" From 9f51e46baeec622d7d73d16390d34c40de4d5aa6 Mon Sep 17 00:00:00 2001 From: Adrian Kowalski Date: Fri, 9 Oct 2015 18:41:42 +0200 Subject: [PATCH 0034/2280] Add whitelist feature to zero plugin --- beetsplug/zero.py | 53 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 14 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index abccde36f..9f56b1cac 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -41,26 +41,51 @@ class ZeroPlugin(BeetsPlugin): self.config.add({ 'fields': [], - 'update_database': False, + 'keep_fields': [], + 'update_database': False }) self.patterns = {} self.warned = False - for field in self.config['fields'].as_str_seq(): - if field in ('id', 'path', 'album_id'): - self._log.warn(u'field \'{0}\' ignored, zeroing ' - u'it would be dangerous', field) - continue - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue + if self.config['fields'] and self.config['keep_fields']: + self._log.warn(u'cannot blacklist and whitelist at the same time') - try: - self.patterns[field] = self.config[field].as_str_seq() - except confit.NotFoundError: - # Matches everything - self.patterns[field] = True + if self.config['fields']: + for field in self.config['fields'].as_str_seq(): + if field in ('id', 'path', 'album_id'): + self._log.warn(u'field \'{0}\' ignored, zeroing ' + u'it would be dangerous', field) + continue + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + continue + + try: + self.patterns[field] = self.config[field].as_str_seq() + except confit.NotFoundError: + # Matches everything + self.patterns[field] = True + + if self.config['keep_fields']: + for field in self.config['keep_fields'].as_str_seq(): + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + continue + + for field in MediaFile.fields(): + if field in self.config['keep_fields'].as_str_seq(): + continue + + try: + self.patterns[field] = self.config[field].as_str_seq() + except: + self.patterns[field] = True + + # These fields should be preserved + if 'id' in self.patterns: del self.patterns['id'] + if 'path' in self.patterns: del self.patterns['path'] + if 'album_id' in self.patterns: del self.patterns['album_id'] def import_task_choice_event(self, session, task): """Listen for import_task_choice event.""" From 158486319fde3685fe097cecbc2e47ab4fbc5f97 Mon Sep 17 00:00:00 2001 From: Adrian Kowalski Date: Fri, 9 Oct 2015 21:23:59 +0200 Subject: [PATCH 0035/2280] Improve code quality, separate shared logic into functions --- beetsplug/zero.py | 57 +++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 9f56b1cac..b97c37bcd 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -48,44 +48,43 @@ class ZeroPlugin(BeetsPlugin): self.patterns = {} self.warned = False - if self.config['fields'] and self.config['keep_fields']: - self._log.warn(u'cannot blacklist and whitelist at the same time') - if self.config['fields']: + self.validate_config('fields') for field in self.config['fields'].as_str_seq(): - if field in ('id', 'path', 'album_id'): - self._log.warn(u'field \'{0}\' ignored, zeroing ' - u'it would be dangerous', field) - continue - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue - - try: - self.patterns[field] = self.config[field].as_str_seq() - except confit.NotFoundError: - # Matches everything - self.patterns[field] = True + self.write_patterns(field) - if self.config['keep_fields']: - for field in self.config['keep_fields'].as_str_seq(): - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue + elif self.config['keep_fields']: + self.validate_config('keep_fields') for field in MediaFile.fields(): if field in self.config['keep_fields'].as_str_seq(): continue - - try: - self.patterns[field] = self.config[field].as_str_seq() - except: - self.patterns[field] = True + self.write_patterns(field) # These fields should be preserved - if 'id' in self.patterns: del self.patterns['id'] - if 'path' in self.patterns: del self.patterns['path'] - if 'album_id' in self.patterns: del self.patterns['album_id'] + for key in ('id', 'path', 'album_id'): + if key in self.patterns: + del self.patterns[key] + + def validate_config(self, mode): + """Check if fields written in config are correct.""" + if self.config['fields'] and self.config['keep_fields']: + self._log.warn(u'cannot blacklist and whitelist at the same time') + for field in self.config[mode].as_str_seq(): + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + continue + if mode == 'fields' and field in ('id', 'path', 'album_id'): + self._log.warn(u'field \'{0}\' ignored, zeroing ' + u'it would be dangerous', field) + continue + + def write_patterns(self, field): + try: + self.patterns[field] = self.config[field].as_str_seq() + except confit.NotFoundError: + # Matches everything + self.patterns[field] = True def import_task_choice_event(self, session, task): """Listen for import_task_choice event.""" From 84da4b89a53b092d48f756d932ef58578b717494 Mon Sep 17 00:00:00 2001 From: Adrian Kowalski Date: Fri, 9 Oct 2015 21:38:38 +0200 Subject: [PATCH 0036/2280] Update documentation for zero plugin --- docs/plugins/zero.rst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 2682ee6ca..360c737a5 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -2,8 +2,10 @@ Zero Plugin =========== The ``zero`` plugin allows you to null fields in files' metadata tags. Fields -can be nulled unconditionally or conditioned on a pattern match. For example, -the plugin can strip useless comments like "ripped by MyGreatRipper." +can be nulled unconditionally or conditioned on a pattern match. It works in +two independent modes - blacklist and whitelist. You can only choose one option, +however blacklist is the default. For example, the plugin can strip useless +comments like "ripped by MyGreatRipper." To use the ``zero`` plugin, enable the plugin in your configuration (see :ref:`using-plugins`). @@ -18,6 +20,9 @@ fields to nullify and the conditions for nullifying them: get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images embedded in the media file. +* Set ``keep_fields`` respectively to list of fields that plugin should + preserve. That way ``zero`` cleans anything other than fields written in this + option. * To conditionally filter a field, use ``field: [regexp, regexp]`` to specify regular expressions. * By default this plugin only affects files' tags ; the beets database is left From da655534ae5f36defbc9c4eafe82e3e09b931ee6 Mon Sep 17 00:00:00 2001 From: Adrian Kowalski Date: Mon, 12 Oct 2015 09:39:20 +0200 Subject: [PATCH 0037/2280] Change function name and correct documentation style --- beetsplug/zero.py | 11 +++++++---- docs/plugins/zero.rst | 16 +++++++++------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index b97c37bcd..561430ddc 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -42,7 +42,7 @@ class ZeroPlugin(BeetsPlugin): self.config.add({ 'fields': [], 'keep_fields': [], - 'update_database': False + 'update_database': False, }) self.patterns = {} @@ -51,7 +51,7 @@ class ZeroPlugin(BeetsPlugin): if self.config['fields']: self.validate_config('fields') for field in self.config['fields'].as_str_seq(): - self.write_patterns(field) + self.set_pattern(field) elif self.config['keep_fields']: self.validate_config('keep_fields') @@ -59,7 +59,7 @@ class ZeroPlugin(BeetsPlugin): for field in MediaFile.fields(): if field in self.config['keep_fields'].as_str_seq(): continue - self.write_patterns(field) + self.set_pattern(field) # These fields should be preserved for key in ('id', 'path', 'album_id'): @@ -79,7 +79,10 @@ class ZeroPlugin(BeetsPlugin): u'it would be dangerous', field) continue - def write_patterns(self, field): + def set_pattern(self, field): + """Set a field in `self.patterns` to a string list corresponding to + the configuration, or `True` if the field has no specific configuration. + """ try: self.patterns[field] = self.config[field].as_str_seq() except confit.NotFoundError: diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 360c737a5..cc70e6675 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -2,10 +2,8 @@ Zero Plugin =========== The ``zero`` plugin allows you to null fields in files' metadata tags. Fields -can be nulled unconditionally or conditioned on a pattern match. It works in -two independent modes - blacklist and whitelist. You can only choose one option, -however blacklist is the default. For example, the plugin can strip useless -comments like "ripped by MyGreatRipper." +can be nulled unconditionally or conditioned on a pattern match. For example, +the plugin can strip useless comments like "ripped by MyGreatRipper." To use the ``zero`` plugin, enable the plugin in your configuration (see :ref:`using-plugins`). @@ -20,9 +18,9 @@ fields to nullify and the conditions for nullifying them: get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images embedded in the media file. -* Set ``keep_fields`` respectively to list of fields that plugin should - preserve. That way ``zero`` cleans anything other than fields written in this - option. +* Set ``keep_fields`` to *invert* the logic of the plugin. Only these fields + will be kept; other fields will be removed. Remember to set only + ``fields`` or ``keep_fields``, not both! * To conditionally filter a field, use ``field: [regexp, regexp]`` to specify regular expressions. * By default this plugin only affects files' tags ; the beets database is left @@ -36,6 +34,10 @@ For example:: genre: [rnb, 'power metal'] update_database: true +The plugin can work in one of two modes. The first mode, the default, +is a blacklist, where you choose the tags you want to remove. The second mode +is a whitelist where you instead specify the tags you want to keep. + If a custom pattern is not defined for a given field, the field will be nulled unconditionally. From d180d42ddb7658ee2a3d1f980c2c9c4e1bc563c4 Mon Sep 17 00:00:00 2001 From: Adrian Kowalski Date: Mon, 12 Oct 2015 09:50:12 +0200 Subject: [PATCH 0038/2280] Fix flake8 complaint about line length --- beetsplug/zero.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 561430ddc..b538d6167 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -81,7 +81,8 @@ class ZeroPlugin(BeetsPlugin): def set_pattern(self, field): """Set a field in `self.patterns` to a string list corresponding to - the configuration, or `True` if the field has no specific configuration. + the configuration, or `True` if the field has no specific + configuration. """ try: self.patterns[field] = self.config[field].as_str_seq() From 3ab99320594893feb3896284b7b02733783dcc18 Mon Sep 17 00:00:00 2001 From: Joe LaSala Date: Wed, 7 Oct 2015 23:46:35 -0500 Subject: [PATCH 0039/2280] Add Genius as a lyric source Makes use of the Genius API and genius-api.com, a separate resource that provides readable lyrics. --- beetsplug/lyrics.py | 71 ++++++++++++++++++++++++++++++++++++++++- docs/changelog.rst | 1 + docs/plugins/lyrics.rst | 3 +- 3 files changed, 73 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 59937d480..2f1e3529e 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -224,6 +224,70 @@ class MusiXmatch(SymbolsReplaced): return lyrics.strip(',"').replace('\\n', '\n') +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(unicode) + self.headers = {'Authorization': "Bearer %s" % self.api_key} + + def search_genius(self, artist, title): + query = u"%s %s" % (artist, title) + url = u'https://api.genius.com/search?q=%s' \ + % (urllib.quote(query.encode('utf8'))) + + data = requests.get( + url, + headers=self.headers, + allow_redirects=True + ).content + + return json.loads(data) + + def get_lyrics(self, link): + url = u'http://genius-api.com/api/lyricsInfo' + + data = requests.post( + url, + data={'link': link}, + headers=self.headers, + allow_redirects=True + ).content + + return json.loads(data) + + def build_lyric_string(self, lyrics): + if 'lyrics' not in lyrics: + return + sections = lyrics['lyrics']['sections'] + + lyrics_list = [] + for section in sections: + lyrics_list.append(section['name']) + lyrics_list.append('\n') + for verse in section['verses']: + if 'content' in verse: + lyrics_list.append(verse['content']) + + return ''.join(lyrics_list) + + def fetch(self, artist, title): + search_data = self.search_genius(artist, title) + + if not search_data['meta']['status'] == 200: + return + else: + records = search_data['response']['hits'] + if not records: + return + + record_url = records[0]['result']['url'] + lyric_data = self.get_lyrics(record_url) + lyrics = self.build_lyric_string(lyric_data) + + return lyrics + + class LyricsWiki(SymbolsReplaced): """Fetch lyrics from LyricsWiki.""" URL_PATTERN = 'http://lyrics.wikia.com/%s:%s' @@ -444,12 +508,13 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] + SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch', 'genius'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, 'lyrics.com': LyricsCom, 'musixmatch': MusiXmatch, + 'genius': Genius, } def __init__(self): @@ -459,12 +524,16 @@ class LyricsPlugin(plugins.BeetsPlugin): 'auto': True, 'google_API_key': None, 'google_engine_ID': u'009217259823014548361:lndtuqkycfu', + 'genius_api_key': + "Ryq93pUGm8bM6eUWwD_M3NOFFDAtp2yEE7W" + "76V-uFL5jks5dNvcGCdarqFjDhP9c", 'fallback': None, 'force': False, 'sources': self.SOURCES, }) self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True + self.config['genius_api_key'].redact = True available_sources = list(self.SOURCES) if not self.config['google_API_key'].get() and \ diff --git a/docs/changelog.rst b/docs/changelog.rst index ce5a68c48..be0efbd5d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,7 @@ The new features: * :doc:`/plugins/plexupdate`: A new ``library_name`` option allows you to select which Plex library to update. :bug:`1572` :bug:`1595` * Add new `include` config option to allow including external config files. +* :doc:`/plugins/lyrics`: Genius.com is now a source for lyrics. Fixes: diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 1d91a00eb..b174751db 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -3,11 +3,12 @@ Lyrics Plugin The ``lyrics`` plugin fetches and stores song lyrics from databases on the Web. Namely, the current version of the plugin uses `Lyric Wiki`_, `Lyrics.com`_, -`Musixmatch`_, and, optionally, the Google custom search API. +`Musixmatch`_, `Genius.com`_, and, optionally, the Google custom search API. .. _Lyric Wiki: http://lyrics.wikia.com/ .. _Lyrics.com: http://www.lyrics.com/ .. _Musixmatch: https://www.musixmatch.com/ +.. _Genius.com: http://genius.com/ Fetch Lyrics During Import From 8c35a24073e981ca7eccd6b6790c4eecdeb1a1b5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 14:39:53 -0700 Subject: [PATCH 0040/2280] zero: Check for conflicts only once (#1641) The old version would trigger the warning twice. --- beetsplug/zero.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index b538d6167..8fe61a0b8 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -48,11 +48,17 @@ class ZeroPlugin(BeetsPlugin): self.patterns = {} self.warned = False + # We'll only handle `fields` or `keep_fields`, but not both. + if self.config['fields'] and self.config['keep_fields']: + self._log.warn(u'cannot blacklist and whitelist at the same time') + + # Blacklist mode. if self.config['fields']: self.validate_config('fields') for field in self.config['fields'].as_str_seq(): self.set_pattern(field) + # Whitelist mode. elif self.config['keep_fields']: self.validate_config('keep_fields') @@ -61,15 +67,17 @@ class ZeroPlugin(BeetsPlugin): continue self.set_pattern(field) - # These fields should be preserved + # These fields should always be preserved. for key in ('id', 'path', 'album_id'): if key in self.patterns: del self.patterns[key] def validate_config(self, mode): - """Check if fields written in config are correct.""" - if self.config['fields'] and self.config['keep_fields']: - self._log.warn(u'cannot blacklist and whitelist at the same time') + """Check whether fields in the configuration are valid. + + `mode` should either be "fields" or "keep_fields", indicating + the section of the configuration to validate. + """ for field in self.config[mode].as_str_seq(): if field not in MediaFile.fields(): self._log.error(u'invalid field: {0}', field) From 7c6f7b2fa7df090377eb6be956ce92eaf43bf246 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 14:43:16 -0700 Subject: [PATCH 0041/2280] Doc tweaks and changelog for #1641 (fix #1621) --- docs/changelog.rst | 4 ++++ docs/plugins/zero.rst | 10 +++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ce5a68c48..c3b57df03 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,10 @@ The new features: * :doc:`/plugins/plexupdate`: A new ``library_name`` option allows you to select which Plex library to update. :bug:`1572` :bug:`1595` * Add new `include` config option to allow including external config files. +* :doc:`/plugins/zero`: The plugin can now use a "whitelist" policy as an + alternative to the (default) "blacklist" mode. Thanks to :user:`adkow`. + :bug:`1621` :bug:`1641` + Fixes: diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index cc70e6675..ecaa60a3d 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -5,6 +5,10 @@ The ``zero`` plugin allows you to null fields in files' metadata tags. Fields can be nulled unconditionally or conditioned on a pattern match. For example, the plugin can strip useless comments like "ripped by MyGreatRipper." +The plugin can work in one of two modes. The first mode, the default, is a +blacklist, where you choose the tags you want to remove. The second mode is a +whitelist, where you instead specify the tags you want to keep. + To use the ``zero`` plugin, enable the plugin in your configuration (see :ref:`using-plugins`). @@ -20,7 +24,7 @@ fields to nullify and the conditions for nullifying them: embedded in the media file. * Set ``keep_fields`` to *invert* the logic of the plugin. Only these fields will be kept; other fields will be removed. Remember to set only - ``fields`` or ``keep_fields``, not both! + ``fields`` or ``keep_fields``---not both! * To conditionally filter a field, use ``field: [regexp, regexp]`` to specify regular expressions. * By default this plugin only affects files' tags ; the beets database is left @@ -34,10 +38,6 @@ For example:: genre: [rnb, 'power metal'] update_database: true -The plugin can work in one of two modes. The first mode, the default, -is a blacklist, where you choose the tags you want to remove. The second mode -is a whitelist where you instead specify the tags you want to keep. - If a custom pattern is not defined for a given field, the field will be nulled unconditionally. From 0b3ecfc6e8d0db537df20d9239121a0b588f9495 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 14:52:29 -0700 Subject: [PATCH 0042/2280] Doc tweaks for #1639 --- docs/changelog.rst | 3 ++- docs/plugins/lyrics.rst | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f819a6b53..fa07ceba8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -26,7 +26,8 @@ The new features: * :doc:`/plugins/zero`: The plugin can now use a "whitelist" policy as an alternative to the (default) "blacklist" mode. Thanks to :user:`adkow`. :bug:`1621` :bug:`1641` -* :doc:`/plugins/lyrics`: Genius.com is now a source for lyrics. +* :doc:`/plugins/lyrics`: Genius.com is now a source for lyrics. Thanks to + :user:`sadatay`. :bug:`1626` :bug:`1639` Fixes: diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index b174751db..1b3ca0c2f 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -52,9 +52,9 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all sources. - *google* source will be automatically deactivated if no ``google_API_key`` is - setup. + Default: ``google lyricwiki lyrics.com musixmatch genius``, i.e., all + sources. The *google* source will be automatically deactivated if no + ``google_API_key`` is setup. Here's an example of ``config.yaml``:: From 9524ddcfe39f4e5e6e170438095dbfc707171bb5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 17:44:34 -0700 Subject: [PATCH 0043/2280] Clean up changelog for 1.3.15 release --- docs/changelog.rst | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index fa07ceba8..a5cb913a3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,32 +4,36 @@ Changelog 1.3.15 (in development) ----------------------- -The new features: +This release adds a new plugin for checking file quality and a new source for +lyrics. The larger features are: + +* A new :doc:`/plugins/badfiles` helps you scan for corruption in your music + collection. Thanks to :user:`fxthomas`. :bug:`1568` +* :doc:`/plugins/lyrics`: You can now fetch lyrics from Genius.com. + Thanks to :user:`sadatay`. :bug:`1626` :bug:`1639` +* :doc:`/plugins/zero`: The plugin can now use a "whitelist" policy as an + alternative to the (default) "blacklist" mode. Thanks to :user:`adkow`. + :bug:`1621` :bug:`1641` + +And there are smaller new features too: * Add new color aliases for standard terminal color names (e.g., cyan and magenta). Thanks to :user:`mathstuf`. :bug:`1548` * :doc:`/plugins/play`: A new ``--args`` option lets you specify options for the player command. :bug:`1532` -* A new :doc:`/plugins/badfiles` helps you scan for corruption in your music - collection. Thanks to :user:`fxthomas`. :bug:`1568` * :doc:`/plugins/play`: A new ``raw`` configuration option lets the command work with players (such as VLC) that expect music filenames as arguments, rather than in a playlist. Thanks to :user:`nathdwek`. :bug:`1578` +* :doc:`/plugins/play`: You can now configure the number of tracks that + trigger a "lots of music" warning. :bug:`1577` * :doc:`/plugins/embedart`: A new ``remove_art_file`` option lets you clean up if you prefer *only* embedded album art. Thanks to :user:`jackwilsdon`. :bug:`1591` :bug:`733` -* :doc:`/plugins/play`: You can now configure the number of tracks that - trigger a "lots of music" warning. :bug:`1577` * :doc:`/plugins/plexupdate`: A new ``library_name`` option allows you to select which Plex library to update. :bug:`1572` :bug:`1595` -* Add new `include` config option to allow including external config files. -* :doc:`/plugins/zero`: The plugin can now use a "whitelist" policy as an - alternative to the (default) "blacklist" mode. Thanks to :user:`adkow`. - :bug:`1621` :bug:`1641` -* :doc:`/plugins/lyrics`: Genius.com is now a source for lyrics. Thanks to - :user:`sadatay`. :bug:`1626` :bug:`1639` +* A new ``include`` option lets you import external configuration files. -Fixes: +This release has plenty of fixes: * :doc:`/plugins/lastgenre`: Fix a bug that prevented tag popularity from being considered. Thanks to :user:`svoos`. :bug:`1559` @@ -53,12 +57,13 @@ Fixes: encounters an error. :bug:`1592` * The case sensitivity of path queries is more useful now: rather than just guessing based on the platform, we now check the case sensitivity of your - particular filesystem. :bug:`1586` + filesystem. :bug:`1586` * Case-insensitive path queries might have returned nothing because of a wrong SQL query. * Fix a crash when a query contains a "+" or "-" alone in a component. :bug:`1605` -* Fixed unit of file size to MiB, GiB, etc. instead of MB, GB, etc. :bug:`1623` +* Fixed unit of file size to powers of two (MiB, GiB, etc.) instead of powers + of ten (MB, GB, etc.). :bug:`1623` 1.3.14 (August 2, 2015) From 60e5e388cc7273b97bac1dbb2f9fb5cecc136b2c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 17:45:21 -0700 Subject: [PATCH 0044/2280] Add date for 1.3.15 release --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index a5cb913a3..3b6a18be5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.15 (in development) ------------------------ +1.3.15 (October 17, 2015) +------------------------- This release adds a new plugin for checking file quality and a new source for lyrics. The larger features are: From ef26d4c9268e2fb477f47d5c95efcc7c07634d89 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Oct 2015 17:45:46 -0700 Subject: [PATCH 0045/2280] Version bump for 1.3.16 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index fbd4e10c3..8447ef96f 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os import beets.library from beets.util import confit -__version__ = '1.3.15' +__version__ = '1.3.16' __author__ = 'Adrian Sampson ' Library = beets.library.Library diff --git a/docs/changelog.rst b/docs/changelog.rst index 3b6a18be5..1494bd9c9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.3.16 (in development) +----------------------- + +Changelog goes here! + + 1.3.15 (October 17, 2015) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index ac5124435..24ea6742d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -12,7 +12,7 @@ project = u'beets' copyright = u'2012, Adrian Sampson' version = '1.3' -release = '1.3.15' +release = '1.3.16' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index f5e2cbbcf..94a1c7d27 100755 --- a/setup.py +++ b/setup.py @@ -55,7 +55,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.15', + version='1.3.16', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 054b9728b541d9a3e3fa077732ce0bcba6c4f5f5 Mon Sep 17 00:00:00 2001 From: Marc Plano-Lesay Date: Sun, 18 Oct 2015 13:46:39 +0200 Subject: [PATCH 0046/2280] Fix example of Types plugin documentation --- docs/plugins/types.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/types.rst b/docs/plugins/types.rst index 67742ee0f..9847fec44 100644 --- a/docs/plugins/types.rst +++ b/docs/plugins/types.rst @@ -23,4 +23,4 @@ queries ` to filter them.:: beet ls rating:4..5 beet modify --album "My favorite album" rating=5 - beet modify --album rating:4..5 + beet ls --album rating:4..5 From a4ae7fa891b6d5be72ab9b972221796a85a20237 Mon Sep 17 00:00:00 2001 From: Alex Nerten Date: Mon, 19 Oct 2015 15:24:59 +0300 Subject: [PATCH 0047/2280] Update plexupdate.py Fix #1649 --- beetsplug/plexupdate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 340bcdf4d..8cb1d375d 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -28,7 +28,7 @@ def get_music_section(host, port, token, library_name): r = requests.get(url) # Parse xml tree and extract music section key. - tree = ET.fromstring(r.text) + tree = ET.fromstring(r.content) for child in tree.findall('Directory'): if child.get('title') == library_name: return child.get('key') From e937ca5c15c84c6ae4b8db7eeedd0893441e1073 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 19 Oct 2015 11:12:26 -0700 Subject: [PATCH 0048/2280] Fix grammar in a docstring --- beets/importer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index 844b66086..b529f8d67 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -612,7 +612,7 @@ class ImportTask(BaseImportTask): return duplicates def align_album_level_fields(self): - """Make the some album fields equal across `self.items` + """Make some album fields equal across `self.items`. """ changes = {} From 10dc42d1d2c08337348757dac3ac9505e6753987 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 19 Oct 2015 13:27:29 -0700 Subject: [PATCH 0049/2280] Changelog for #1649 --- docs/changelog.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1494bd9c9..080a88384 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,10 @@ Changelog 1.3.16 (in development) ----------------------- -Changelog goes here! +Fixes: + +* :doc:`/plugins/plexupdate`: Fix a crash when Plex libraries use non-ASCII + collection names. :bug:`1649` 1.3.15 (October 17, 2015) From f4a617e64130b3e14f4aa28f7ab6bb51f275d468 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 19 Oct 2015 13:44:52 -0700 Subject: [PATCH 0050/2280] Move `color` option in config example (fix #1653) --- docs/reference/config.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index e01711111..2d91bac14 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -789,7 +789,8 @@ Here's an example file:: plugins: bpd pluginpath: ~/beets/myplugins threaded: yes - color: yes + ui: + color: yes paths: default: $genre/$albumartist/$album/$track $title From f784cd1a226fa1161ee3aacb44ddd3a1475b8af9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 12:07:40 -0700 Subject: [PATCH 0051/2280] Fix #1656, maybe: encode Discogs token strings --- beetsplug/discogs.py | 13 +++++++------ docs/changelog.rst | 2 ++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 80b7ae3df..904220685 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -39,7 +39,8 @@ import os urllib3_logger = logging.getLogger('requests.packages.urllib3') urllib3_logger.setLevel(logging.CRITICAL) -USER_AGENT = u'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) +USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) \ + .encode('utf8') # Exceptions that discogs_client should really handle but does not. CONNECTION_ERRORS = (ConnectionError, socket.error, httplib.HTTPException, @@ -65,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(unicode) - c_secret = self.config['apisecret'].get(unicode) + c_key = self.config['apikey'].get(unicode).encode('utf8') + c_secret = self.config['apisecret'].get(unicode).encode('utf8') # Get the OAuth token from a file or log in. try: @@ -76,8 +77,8 @@ class DiscogsPlugin(BeetsPlugin): # No token yet. Generate one. token, secret = self.authenticate(c_key, c_secret) else: - token = tokendata['token'] - secret = tokendata['secret'] + token = tokendata['token'].encode('utf8') + secret = tokendata['secret'].encode('utf8') self.discogs_client = Client(USER_AGENT, c_key, c_secret, token, secret) @@ -120,7 +121,7 @@ class DiscogsPlugin(BeetsPlugin): with open(self._tokenfile(), 'w') as f: json.dump({'token': token, 'secret': secret}, f) - return token, secret + return token.encode('utf8'), secret.encode('utf8') def album_distance(self, items, album_info, mapping): """Returns the album distance. diff --git a/docs/changelog.rst b/docs/changelog.rst index 080a88384..b263c1da9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,8 @@ Fixes: * :doc:`/plugins/plexupdate`: Fix a crash when Plex libraries use non-ASCII collection names. :bug:`1649` +* :doc:`/plugins/discogs`: Maybe fix a crash when using some versions of the + ``requests`` library. :bug:`1656` 1.3.15 (October 17, 2015) From 15190794dcbd91ef7908f0de4ff8f8555df49f43 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 12:39:27 -0700 Subject: [PATCH 0052/2280] Log more details about duplicates Part of the investigation into #1652. --- beets/importer.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/beets/importer.py b/beets/importer.py index b529f8d67..224e6d255 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1306,6 +1306,12 @@ def resolve_duplicates(session, task): ident = task.chosen_ident() found_duplicates = task.find_duplicates(session.lib) if ident in session.seen_idents or found_duplicates: + log.debug( + 'resolving duplicates; in database: {}, in queue: {}'.format( + len(found_duplicates), + ident in session.seen_idents, + ) + ) session.resolve_duplicate(task, found_duplicates) session.log_choice(task, True) session.seen_idents.add(ident) From cc5aba82947312741a7fd61c0109da9866f94cba Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 12:46:27 -0700 Subject: [PATCH 0053/2280] Roll back PR #1358: regression on recent duplicate This should fix #1652, which found that this code did the wrong thing when there were *no* `found_duplicates`: that is, when the duplicate actually came from the `seen_keys` list, so the album is not in the database yet. This handling was confusing "no non-empty duplicates" with "no in-database duplicates", and incorrectly bypassing the duplicates prompt. Since having empty albums in the database is a rare case (it should be impossible!), and we should no longer *crash* when it happens, I am considering it unnecessary to handle it specially. The user will now just see "Old: 0 items" and that's that. --- beets/ui/commands.py | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index f3386cf71..348d12c88 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -761,16 +761,6 @@ class TerminalImportSession(importer.ImportSession): log.warn(u"This {0} is already in the library!", ("album" if task.is_album else "item")) - # skip empty albums (coming from a previous failed import session) - if task.is_album: - real_duplicates = [dup for dup in found_duplicates if dup.items()] - if not real_duplicates: - log.info("All duplicates are empty, we ignore them") - task.should_remove_duplicates = True - return - else: - real_duplicates = found_duplicates - if config['import']['quiet']: # In quiet mode, don't prompt -- just skip. log.info(u'Skipping.') @@ -778,17 +768,12 @@ class TerminalImportSession(importer.ImportSession): else: # Print some detail about the existing and new items so the # user can make an informed decision. - for duplicate in real_duplicates: + for duplicate in found_duplicates: print_("Old: " + summarize_items( list(duplicate.items()) if task.is_album else [duplicate], not task.is_album, )) - if real_duplicates != found_duplicates: # there's empty albums - count = len(found_duplicates) - len(real_duplicates) - print_("Old: {0} empty album{1}".format( - count, "s" if count > 1 else "")) - print_("New: " + summarize_items( task.imported_items(), not task.is_album, From 079822b893c4c1a6c3357c6202fe3aa5f2fab860 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 13:03:26 -0700 Subject: [PATCH 0054/2280] Importer: no separate stage for applying metadata It's cheaper and easier to just apply metadata in the UI thread. The advantage, then, is that we no longer need to keep track of anything in-memory to enumerate data that has been seen by the user but not added to the database yet! In the next step, I'll remove `seen_idents` altogether. --- beets/importer.py | 16 ++++++++++------ docs/dev/plugins.rst | 7 ++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 224e6d255..7be755eb4 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -294,13 +294,16 @@ class ImportSession(object): # Split directory tasks into one task for each album. stages += [group_albums(self)] + # These stages either talk to the user to get a decision or, + # in the case of a non-autotagged import, just choose to + # import everything as-is. In *both* cases, these stages + # also add the music to the library database, so later + # stages need to read and write data from there. if self.config['autotag']: stages += [lookup_candidates(self), user_query(self)] else: stages += [import_asis(self)] - stages += [apply_choices(self)] - # Plugin stages. for stage_func in plugins.import_stages(): stages.append(plugin_stage(self, stage_func)) @@ -1295,6 +1298,7 @@ def user_query(session, task): return pipeline.multiple(ipl.pull()) resolve_duplicates(session, task) + apply_choice(session, task) return task @@ -1329,12 +1333,12 @@ def import_asis(session, task): log.info('{}', displayable_path(task.paths)) task.set_choice(action.ASIS) + apply_choice(session, task) -@pipeline.mutator_stage -def apply_choices(session, task): - """A coroutine for applying changes to albums and singletons during - the autotag process. +def apply_choice(session, task): + """Apply the task's choice to the Album or Item it contains and add + it to the library. """ if task.skip: return diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index b1cf2deca..798b6894c 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -188,7 +188,10 @@ The events currently available are: Parameters: ``task`` and ``session``. * *import_task_apply*: called after metadata changes have been applied in an - import task. Parameters: ``task`` and ``session``. + import task. This is called on the same thread as the UI, so use this + sparingly and only for tasks that can be done quickly. For most plugins, an + import pipeline stage is a better choice (see :ref:`plugin-stage`). + Parameters: ``task`` and ``session``. * *import_task_choice*: called after a decision has been made about an import task. This event can be used to initiate further interaction with the user. @@ -378,6 +381,8 @@ Here's an example plugin that provides a meaningless new field "foo":: # The "foo" tag of the file is now "ham" +.. _plugin-stage: + Add Import Pipeline Stages ^^^^^^^^^^^^^^^^^^^^^^^^^^ From 4c6dbe67805ed6994b371c7ba119e774fd94466f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 13:06:16 -0700 Subject: [PATCH 0055/2280] Remove `seen_idents` set This was used since time immemorial to keep track of recently-imported music that hasn't hit the database yet. I created it when the importer only added music to the database at the end of the pipeline, after doing all the work to manipulate the metadata. Now, for several reasons, we add the music immediately after the user sees it and then manipulate the records *in the database*. With the latest change, which gets rid of the last separation between UI and database-adding, we no longer need to do this. --- beets/importer.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 7be755eb4..95163b6fd 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -186,7 +186,6 @@ class ImportSession(object): self.logger = self._setup_logging(loghandler) self.paths = paths self.query = query - self.seen_idents = set() self._is_resuming = dict() # Normalize the paths. @@ -1307,18 +1306,13 @@ def resolve_duplicates(session, task): and ask the session to resolve this. """ if task.choice_flag in (action.ASIS, action.APPLY): - ident = task.chosen_ident() found_duplicates = task.find_duplicates(session.lib) - if ident in session.seen_idents or found_duplicates: - log.debug( - 'resolving duplicates; in database: {}, in queue: {}'.format( - len(found_duplicates), - ident in session.seen_idents, - ) - ) + if found_duplicates: + log.debug('found duplicates: {}'.format( + [o.id for o in found_duplicates] + )) session.resolve_duplicate(task, found_duplicates) session.log_choice(task, True) - session.seen_idents.add(ident) @pipeline.mutator_stage From 2537c06ac75b2ca7c8588af9d32dc6ecd81e2ae0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 24 Oct 2015 13:09:15 -0700 Subject: [PATCH 0056/2280] Changelog for #1652 fix --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index b263c1da9..c247aa429 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,10 @@ Fixes: collection names. :bug:`1649` * :doc:`/plugins/discogs`: Maybe fix a crash when using some versions of the ``requests`` library. :bug:`1656` +* Fix a race in the importer when importing two albums with the same artist + and name in quick succession. The importer would fail to detect them as + duplicates, claiming that there were "empty albums" in the database even + when there were not. :bug:`1652` 1.3.15 (October 17, 2015) From 004fb7d1c8998660da0064e24cb803f40e7fb0d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 04:44:15 +0100 Subject: [PATCH 0057/2280] lastgenre: Fix up `ragga jungle`. * Move `ragga jungle` to beneath `oldschool jungle`. * Remove `ragga-jungle` which isn't recognised by the genre whitelist. https://en.wikipedia.org/wiki/Ragga_jungle --- beetsplug/lastgenre/genres-tree.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index c1b1a081b..4ee1475ea 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -291,7 +291,7 @@ - neurofunk - oldschool jungle: - darkside jungle - - ragga-jungle + - ragga jungle - raggacore - sambass - techstep @@ -740,7 +740,6 @@ - dancehall - dub - lovers rock - - ragga jungle - - polish reggae + - polish reggae - reggae fusion - rocksteady From b187251a7e6d7ab06e5fc3b9eb38437cf7c6e6aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 04:53:14 +0100 Subject: [PATCH 0058/2280] lastgenre: Remove `dance hall` and `polish reggae`. Neither of the two are recognised in the genres.txt whitelist. --- beetsplug/lastgenre/genres-tree.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 4ee1475ea..2f6a049ab 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -133,7 +133,6 @@ - chutney - chutney soca - compas - - dance hall - mambo - merengue - méringue @@ -740,6 +739,5 @@ - dancehall - dub - lovers rock - - polish reggae - reggae fusion - rocksteady From 1678c1d847b9f50bd54f775c050a08af86ac2ec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 04:55:57 +0100 Subject: [PATCH 0059/2280] =?UTF-8?q?lastgenre:=20Replace=20top-level=20ge?= =?UTF-8?q?nre=20`ska`=20with=20`reggae`=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit … and move relevant genres from the tree to be children of the `reggae` top-level genre as well as add `roots reggae` to the list. See discussion at https://github.com/sampsyo/beets/issues/1661 --- beetsplug/lastgenre/genres-tree.yaml | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 2f6a049ab..955f921a0 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -147,7 +147,6 @@ - punta - punta rock - rasin - - reggae - reggaeton - salsa - soca @@ -504,12 +503,10 @@ - new school hip hop - old school hip hop - political hip hop - - ragga - rap opera - rap rock: - rap metal - rapcore - - reggae español/spanish reggae - songo-salsa - southern hip hop: - atlanta hip hop: @@ -734,10 +731,14 @@ - surf rock - visual kei: - nagoya kei -- ska: - - 2 tone - - dancehall - - dub - - lovers rock +- reggae: + - roots reggae - reggae fusion - - rocksteady + - reggae español/spanish reggae + - lovers rock + - ragga + - dancehall + - ska: + - 2 tone + - dub + - rocksteady From 1aa808f37beccc33c6a29fcff8f0f098122a95ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 04:58:44 +0100 Subject: [PATCH 0060/2280] lastgenre: Add `raggamuffin`. Already recognised by the genres.txt whitelist, and is a more proper term for `ragga`. https://en.wikipedia.org/wiki/Ragga --- beetsplug/lastgenre/genres-tree.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 955f921a0..616058eff 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -736,7 +736,8 @@ - reggae fusion - reggae español/spanish reggae - lovers rock - - ragga + - raggamuffin: + - ragga - dancehall - ska: - 2 tone From 5f5365021d0745c7c696ba31daf221ba1d3c0703 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 05:00:33 +0100 Subject: [PATCH 0061/2280] lastgenre: Clean up Spanish reggae in the genre list. * Add missing subgenres to whitelist and tree. * Use proper terminology. * Add English term as child of Spanish one. Source: https://en.wikipedia.org/wiki/Reggae_en_Espa%C3%B1ol --- beetsplug/lastgenre/genres-tree.yaml | 6 +++++- beetsplug/lastgenre/genres.txt | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastgenre/genres-tree.yaml b/beetsplug/lastgenre/genres-tree.yaml index 616058eff..a09f7e6b3 100644 --- a/beetsplug/lastgenre/genres-tree.yaml +++ b/beetsplug/lastgenre/genres-tree.yaml @@ -734,7 +734,11 @@ - reggae: - roots reggae - reggae fusion - - reggae español/spanish reggae + - reggae en español: + - spanish reggae + - reggae 110 + - reggae bultrón + - romantic flow - lovers rock - raggamuffin: - ragga diff --git a/beetsplug/lastgenre/genres.txt b/beetsplug/lastgenre/genres.txt index 64e583bfa..914ee1290 100644 --- a/beetsplug/lastgenre/genres.txt +++ b/beetsplug/lastgenre/genres.txt @@ -1224,6 +1224,9 @@ rebetiko red dirt reel reggae +reggae 110 +reggae bultrón +reggae en español reggae fusion reggae highlife reggaefusion @@ -1247,6 +1250,7 @@ rock opera rockabilly rocksteady rococo +romantic flow romantic period in music rondeaux ronggeng From 41cbb47918d61465b005cec142129c5d3a4f7cfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Thu, 29 Oct 2015 05:04:59 +0100 Subject: [PATCH 0062/2280] Add changelog entry for #1661. --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index c247aa429..4eafe9c90 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,8 @@ Fixes: and name in quick succession. The importer would fail to detect them as duplicates, claiming that there were "empty albums" in the database even when there were not. :bug:`1652` +* :doc:`plugins/lastgenre`: Clean up the reggae related genres somewhat. + Thanks to :user:`Freso`. :bug:`1661` 1.3.15 (October 17, 2015) From 16ad174d298ab3f6bd926d93dbd7e409367069f4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 29 Oct 2015 17:43:31 -0400 Subject: [PATCH 0063/2280] A debug message for ReplayGain --- beetsplug/replaygain.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 8186b42f4..d57533e75 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -317,6 +317,7 @@ class CommandBackend(Backend): the album gain """ if len(items) == 0: + self._log.debug('no supported tracks to analyze') return [] """Compute ReplayGain values and return a list of results From 0ed98515adc8b83add36e1d847b5848831cb68a4 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 30 Oct 2015 17:04:11 +0100 Subject: [PATCH 0064/2280] Embedart: remove_art_file on import Should fix #1662. I think the fix is easy. Don't know if it's clean though. Did some tests (+/- 10 albums), all successful. This is the first time I'm using python so please let me know what I should improve:) --- beetsplug/embedart.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 10b30af0f..9fb575429 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -141,3 +141,10 @@ class EmbedCoverArtPlugin(BeetsPlugin): art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool)) + if self.config['remove_art_file'] and album.artpath is not None: + if os.path.isfile(album.artpath): + self._log.debug(u'Removing album art file ' + u'for {0}', album) + os.remove(album.artpath) + album.artpath = None + album.store() From 0257b1077f682715f2b6785e9eebdfa0e1d1e312 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 30 Oct 2015 17:49:57 +0100 Subject: [PATCH 0065/2280] Simplify some code --- beetsplug/embedart.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 9fb575429..9afcf9cf4 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -80,7 +80,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): art.embed_album(self._log, album, maxwidth, False, compare_threshold, ifempty) - if remove_art_file and album.artpath is not None: + if remove_art_file and album.artpath: if os.path.isfile(album.artpath): self._log.debug(u'Removing album art file ' u'for {0}', album) @@ -141,7 +141,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool)) - if self.config['remove_art_file'] and album.artpath is not None: + if self.config['remove_art_file'] and album.artpath: if os.path.isfile(album.artpath): self._log.debug(u'Removing album art file ' u'for {0}', album) From 5f5a8946c3c9476f3fb6070120d3297e33fc949b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 30 Oct 2015 15:25:01 -0400 Subject: [PATCH 0066/2280] convert: Debug log when embedding images To help diagnose #1671. --- beetsplug/convert.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 4c39c52a9..3183f80f5 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -291,6 +291,8 @@ class ConvertPlugin(BeetsPlugin): if self.config['embed']: album = item.get_album() if album and album.artpath: + self._log.debug('embedding album art from {}', + util.displayable_path(album.artpath)) art.embed_item(self._log, item, album.artpath, itempath=converted) From c617033476f455ef1578238087097e8e732f08fd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 1 Nov 2015 11:01:40 -0800 Subject: [PATCH 0067/2280] convert: Add some comments --- beetsplug/convert.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 3183f80f5..ca28d7ffd 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -396,15 +396,22 @@ class ConvertPlugin(BeetsPlugin): fmt = self.config['format'].get(unicode).lower() if should_transcode(item, fmt): command, ext = get_format() + + # Create a temporary file for the conversion. tmpdir = self.config['tmpdir'].get() fd, dest = tempfile.mkstemp('.' + ext, dir=tmpdir) - dest = util.bytestring_path(dest) os.close(fd) + dest = util.bytestring_path(dest) _temp_files.append(dest) # Delete the transcode later. + + # Convert. try: self.encode(command, item.path, dest) except subprocess.CalledProcessError: return + + # Change the newly-imported database entry to point to the + # converted file. item.path = dest item.write() item.read() # Load new audio information data. From 629a80a1d12818cfa0de0b8b8b8a0e24d753215a Mon Sep 17 00:00:00 2001 From: reiv Date: Sun, 1 Nov 2015 01:43:48 +0100 Subject: [PATCH 0068/2280] Importer: Delete orphaned album art on re-imports First step towards fixing #314. --- beets/importer.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/beets/importer.py b/beets/importer.py index 95163b6fd..ba1c47c94 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -547,6 +547,23 @@ class ImportTask(BaseImportTask): items = self.imported_items() + # If any original album art files were reused, leave them untouched. + for item in items: + album = item.get_album() + if album: + self.old_art_paths.discard(album.artpath) + + # Delete remaining original album art files. + for old_art_path in self.old_art_paths: + log.debug('Deleting orphaned album art: {0}', old_art_path) + util.remove(syspath(old_art_path), True) + # XXX: Ideally the directory would get pruned with self.prune() + # below, but when calling `beet import -L`, self.toppath is set + # to None, making self.prune() a no-op; hence this workaround of + # calling util.prune_dirs() directly. + util.prune_dirs(os.path.dirname(old_art_path), + clutter=config['clutter'].as_str_seq()) + # When copying and deleting originals, delete old files. if copy and delete: new_paths = [os.path.realpath(item.path) for item in items] @@ -652,6 +669,11 @@ class ImportTask(BaseImportTask): # Save the original paths of all items for deletion and pruning # in the next step (finalization). self.old_paths = [item.path for item in items] + + # Keep track of paths of all original album art for the same reason. + self.old_art_paths = set(filter(bool, + (album.artpath for album in self.replaced_albums.values()))) + for item in items: if move or copy or link: # In copy and link modes, treat re-imports specially: From 413fe6bbfd695725c9ca7d306dfe408d20ad3904 Mon Sep 17 00:00:00 2001 From: reiv Date: Sun, 1 Nov 2015 04:33:36 +0100 Subject: [PATCH 0069/2280] PEP8 amendments --- beets/importer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index ba1c47c94..8aecf54a3 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -671,8 +671,8 @@ class ImportTask(BaseImportTask): self.old_paths = [item.path for item in items] # Keep track of paths of all original album art for the same reason. - self.old_art_paths = set(filter(bool, - (album.artpath for album in self.replaced_albums.values()))) + self.old_art_paths = set(filter( + bool, (album.artpath for album in self.replaced_albums.values()))) for item in items: if move or copy or link: From 269d0e5403471b8dd96da5eb4d797ce7d538d9fe Mon Sep 17 00:00:00 2001 From: reiv Date: Sat, 31 Oct 2015 20:07:13 +0100 Subject: [PATCH 0070/2280] fetchart: Check if album art file actually exists Fixes #1126. --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b807891e0..5ab07ce96 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -567,7 +567,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): fetchart CLI command. """ for album in albums: - if album.artpath and not force: + if album.artpath and not force and os.path.isfile(album.artpath): message = ui.colorize('text_highlight_minor', 'has album art') else: # In ordinary invocations, look for images on the From 3250fa80ae7b5f7af97309c9a876e94246ac59dc Mon Sep 17 00:00:00 2001 From: reiv Date: Sun, 1 Nov 2015 02:18:19 +0100 Subject: [PATCH 0071/2280] fetchart: Only resize when necessary Fixes #1264: When a re-import triggers fetchart, the existing album art is no longer resized if it already has the correct dimensions. This avoids creating new album art files with unique filenames ("cover.n.jpg"). --- beetsplug/fetchart.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b807891e0..be7efe68a 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -41,6 +41,9 @@ IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' +CANDIDATE_BAD = 0 +CANDIDATE_EXACT = 1 +CANDIDATE_DOWNSCALE = 2 def _logged_get(log, *args, **kwargs): """Like `requests.get`, but logs the effective URL to the specified @@ -506,10 +509,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): def _is_valid_image_candidate(self, candidate): if not candidate: - return False + return CANDIDATE_BAD if not (self.enforce_ratio or self.minwidth): - return True + return CANDIDATE_EXACT # get_size returns None if no local imaging backend is available size = ArtResizer.shared.get_size(candidate) @@ -519,10 +522,14 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): u'documentation for dependencies. ' u'The configuration options `minwidth` and ' u'`enforce_ratio` may be violated.') - return True + return CANDIDATE_EXACT - return size and size[0] >= self.minwidth and \ - (not self.enforce_ratio or size[0] == size[1]) + if size[0] >= self.minwidth and ( + not self.enforce_ratio or size[0] == size[1]): + if size[0] > self.maxwidth: + return CANDIDATE_DOWNSCALE + return CANDIDATE_EXACT + return CANDIDATE_BAD def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the @@ -532,6 +539,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): are made. """ out = None + check = None # Local art. cover_names = self.config['cover_names'].as_str_seq() @@ -540,7 +548,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if paths: for path in paths: candidate = self.fs_source.get(path, cover_names, cautious) - if self._is_valid_image_candidate(candidate): + check = self._is_valid_image_candidate(candidate) + if check: out = candidate self._log.debug('found local image {}', out) break @@ -552,12 +561,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if self.maxwidth: url = ArtResizer.shared.proxy_url(self.maxwidth, url) candidate = self._fetch_image(url) - if self._is_valid_image_candidate(candidate): + check = self._is_valid_image_candidate(candidate) + if check: out = candidate self._log.debug('using remote image {}', out) break - if self.maxwidth and out: + if check == CANDIDATE_DOWNSCALE: out = ArtResizer.shared.resize(self.maxwidth, out) return out From 9182fd8f04ddfc42efa84f91d93ef3546749346b Mon Sep 17 00:00:00 2001 From: reiv Date: Sun, 1 Nov 2015 04:33:36 +0100 Subject: [PATCH 0072/2280] PEP8 amendments --- beetsplug/fetchart.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index be7efe68a..5eae63278 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -45,6 +45,7 @@ CANDIDATE_BAD = 0 CANDIDATE_EXACT = 1 CANDIDATE_DOWNSCALE = 2 + def _logged_get(log, *args, **kwargs): """Like `requests.get`, but logs the effective URL to the specified `log` at the `DEBUG` level. @@ -525,7 +526,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): return CANDIDATE_EXACT if size[0] >= self.minwidth and ( - not self.enforce_ratio or size[0] == size[1]): + not self.enforce_ratio or size[0] == size[1]): if size[0] > self.maxwidth: return CANDIDATE_DOWNSCALE return CANDIDATE_EXACT @@ -567,7 +568,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self._log.debug('using remote image {}', out) break - if check == CANDIDATE_DOWNSCALE: + if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: out = ArtResizer.shared.resize(self.maxwidth, out) return out From d0cfb3e990452c6b44754c9b02a7dd539a962723 Mon Sep 17 00:00:00 2001 From: reiv Date: Mon, 2 Nov 2015 02:20:09 +0100 Subject: [PATCH 0073/2280] fetchart: add test for re-fetching deleted art This test addresses #1126. --- test/test_art.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index 3cc24a7a4..1a24209cf 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -30,6 +30,7 @@ from beets import library from beets import importer from beets import config from beets import logging +from beets import util from beets.util.artresizer import ArtResizer, WEBPROXY @@ -357,6 +358,18 @@ class ArtImporterTest(UseThePlugin): self.afa_response = artdest self._fetch_art(True) + def test_fetch_art_if_imported_file_deleted(self): + # See #1126. Test the following scenario: + # - Album art imported, `album.artpath` set. + # - Imported album art file subsequently deleted (by user or other + # program). + # `fetchart` should import album art again instead of printing the + # message " has album art". + self._fetch_art(True) + util.remove(self.album.artpath) + self.plugin.batch_fetch_art(self.lib, self.lib.albums(), force=False) + self.assertExists(self.album.artpath) + class ArtForAlbumTest(UseThePlugin): """ Tests that fetchart.art_for_album respects the size From b76597bc43f43fe0d48d52a74d8e5917a2982815 Mon Sep 17 00:00:00 2001 From: reiv Date: Mon, 2 Nov 2015 02:36:15 +0100 Subject: [PATCH 0074/2280] Changelog for #1126 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4eafe9c90..8b821174f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,6 +16,9 @@ Fixes: when there were not. :bug:`1652` * :doc:`plugins/lastgenre`: Clean up the reggae related genres somewhat. Thanks to :user:`Freso`. :bug:`1661` +* :doc:`plugins/fetchart`: Fix a bug where a database reference to a + non-existent album art file would prevent the command from fetching new art. + :bug:`1126` 1.3.15 (October 17, 2015) From db08896d8cff2a0333f7cc21395d5570b8532f26 Mon Sep 17 00:00:00 2001 From: reiv Date: Mon, 2 Nov 2015 03:02:11 +0100 Subject: [PATCH 0075/2280] fetchart: add docstring to helper function _is_valid_image_candidate() now has three different return values. These are documented here. --- beetsplug/fetchart.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 5eae63278..9da781e6c 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -509,6 +509,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): return None def _is_valid_image_candidate(self, candidate): + """Determine whether the given candidate artwork is valid based on + its dimensions (width and ratio). + + Return `CANDIDATE_BAD` if the file is unusable. + Return `CANDIDATE_EXACT` if the file is usable as-is. + Return `CANDIDATE_DOWNSCALE` if the file must be resized. + """ if not candidate: return CANDIDATE_BAD From a18506f4713d98e7ff189befe9b690a1c58a8026 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Nov 2015 11:03:43 -0800 Subject: [PATCH 0076/2280] Fix #1686: thumbnails using unicode paths --- beetsplug/thumbnails.py | 4 ++-- docs/changelog.rst | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index ce3382fc8..6fd8c8cbe 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -39,8 +39,8 @@ from beets.util.artresizer import ArtResizer, has_IM, has_PIL BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") -NORMAL_DIR = os.path.join(BASE_DIR, "normal") -LARGE_DIR = os.path.join(BASE_DIR, "large") +NORMAL_DIR = util.bytestring_path(os.path.join(BASE_DIR, "normal")) +LARGE_DIR = util.bytestring_path(os.path.join(BASE_DIR, "large")) class ThumbnailsPlugin(BeetsPlugin): diff --git a/docs/changelog.rst b/docs/changelog.rst index 8b821174f..070dfeaf7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -19,6 +19,7 @@ Fixes: * :doc:`plugins/fetchart`: Fix a bug where a database reference to a non-existent album art file would prevent the command from fetching new art. :bug:`1126` +* :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` 1.3.15 (October 17, 2015) From fe012eae774c97699fe89ae6bd8a9022f8b09e05 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 21:13:58 +0100 Subject: [PATCH 0077/2280] new plugin yamleditor --- beetsplug/yamleditor.py | 329 ++++++++++++++++++++++++++++++++++++ docs/plugins/yamleditor.rst | 79 +++++++++ 2 files changed, 408 insertions(+) create mode 100644 beetsplug/yamleditor.py create mode 100644 docs/plugins/yamleditor.rst diff --git a/beetsplug/yamleditor.py b/beetsplug/yamleditor.py new file mode 100644 index 000000000..963be9829 --- /dev/null +++ b/beetsplug/yamleditor.py @@ -0,0 +1,329 @@ +# This file is part of beets. +# Copyright 2015 +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""open tags of items in texteditor,change them and save back to the items. +""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from beets import plugins +from beets.ui import Subcommand, decargs, library, print_ +import subprocess +import difflib +import yaml +import collections +import webbrowser +from sys import exit +from beets import config +from beets import ui +from tempfile import NamedTemporaryFile + + +class yamleditorPlugin(plugins.BeetsPlugin): + + def __init__(self): + super(yamleditorPlugin, self).__init__() + + self.config.add({ + 'style': 'yaml', + 'editor': '', + 'diff_method': '', + 'html_viewer': '', + 'editor_args': '', + 'html_args': '', + 'albumfields': 'album albumartist', + 'itemfields': 'track title artist album ', + 'not_fields': 'path', + 'separator': '-' + + }) + + def commands(self): + yamleditor_command = Subcommand( + 'yamleditor', + help='send items to yamleditor for editing tags') + yamleditor_command.parser.add_option( + '-e', '--extra', + action='store', + help='add additional fields to edit', + ) + yamleditor_command.parser.add_all_common_options() + yamleditor_command.func = self.editor_music + return[yamleditor_command] + + def editor_music(self, lib, opts, args): + """edit tags in a textfile in yaml-style + """ + self.style = self.config['style'].get() + """the editor field in the config lets you specify your editor. + Defaults to open with webrowser module""" + self.editor = self.config['editor'].get() + """the editor_args field in your config lets you specify + additional args for your editor""" + self.editor_args = self.config['editor_args'].get().split() + """the html_viewer field in your config lets you specify + your htmlviewer. Defaults to open with webrowser module""" + self.html_viewer = self.config['html_viewer'].get() + """the html_args field in your config lets you specify + additional args for your viewer""" + self.html_args = self.config['html_args'].get().split() + """the diff_method field in your config picks the way to see your + changes. Options are: + 'ndiff'(2 files with differences), + 'unified'(just the different lines and a few lines of context), + 'html'(view in html-format), + 'vimdiff'(view in VIM)""" + self.diff_method = self.config['diff_method'].get() + """the albumfields field in your config sets the tags that + you want to see/change for albums. + Defaults to album albumartist. + the ID tag will always be listed as it is used to identify the item""" + self.albumfields = self.config['albumfields'].get().split() + """the itemfields field in your config sets the tags that + you want to see/change or items. + Defaults to track title artist album. + the ID tag will always be listed as it is used to identify the item""" + self.itemfields = self.config['itemfields'].get().split() + '''the not_fields field in your config sets the tags that + will not be changed. + If you happen to change them, they will be restored to the original + value. The ID of an item will never be changed.''' + self.not_fields = self.config['not_fields'].get().split() + '''the separator in your config sets the separator that will be used + between fields in your terminal. Defaults to -''' + self.separator = self.config['separator'].get() + + query = decargs(args) + self.print_items = { + 'yaml': self.print_to_yaml} + self.diffresults = { + 'ndiff': self.ndiff, + 'unified': self.unified, + 'html': self.html, + 'vimdiff': self.vimdiff} + self.make_dict = { + 'all': self.get_all_fields, + "selected": self.get_selected_fields} + self.string_to_dict = { + 'yaml': self.yaml_to_dict} + + objs = self._get_objs(lib, opts, query) + if not objs: + print_('nothing found') + return + fmt = self.get_fields_from(objs, opts) + print_(fmt) + [print_(format(item, fmt)) for item in objs] + if not ui.input_yn(ui.colorize('action_default', "Edit?(n/y)"), True): + return + dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) + newyaml, oldyaml = self.change_objs(dict_from_objs) + changed_objs = self.check_diff(newyaml, oldyaml) + if not changed_objs: + print_("nothing to change") + return + self.save_items(changed_objs, lib, fmt, opts) + + '''from object to yaml''' + def print_to_yaml(self, arg): + return yaml.safe_dump_all( + arg, + allow_unicode=True, + default_flow_style=False) + + '''from yaml to object''' + def yaml_to_dict(self, yam): + return yaml.load_all(yam) + + def _get_objs(self, lib, opts, query): + if opts.album: + return list(lib.albums(query)) + else: + return list(lib.items(query)) + + def get_fields_from(self, objs, opts): + cl = ui.colorize('action', self.separator) + self.fields = self.albumfields if opts.album else self.itemfields + if opts.format: + self.fields = [] + self.fields.extend((opts.format).replace('$', "").split()) + if opts.extra: + fi = (opts.extra).replace('$', "").split() + self.fields.extend([f for f in fi if f not in self.fields]) + if 'id' not in self.fields: + self.fields.insert(0, 'id') + if "_all" in self.fields: + self.fields = None + self.pick = "all" + print_(ui.colorize('text_warning', "edit all fields from ...")) + if opts.album: + fmt = cl + cl.join(['$albumartist', '$album']) + else: + fmt = cl + cl.join(['$title', '$artist']) + else: + for it in self.fields: + if opts.album: + if it not in library.Album.all_keys(): + print_( + "{} not in albumfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + self.fields.remove(it) + else: + if it not in library.Item.all_keys(): + print_( + "{} not in itemfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + self.fields.remove(it) + self.pick = "selected" + fmtfields = ["$" + it for it in self.fields] + fmt = cl + cl.join(fmtfields[1:]) + + return fmt + + '''get the fields we want and make a dic from them''' + def get_selected_fields(self, myfields, objs, opts): + a = [] + for mod in objs: + a.append([{fi: mod[fi]}for fi in myfields]) + return a + + def get_all_fields(self, myfields, objs, opts): + a = [] + for mod in objs: + a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) + return a + + def change_objs(self, dict_items): + oldyaml = self.print_items[self.style](dict_items) + newyaml = self.print_items[self.style](dict_items) + new = NamedTemporaryFile(suffix='.yaml', delete=False) + new.write(newyaml) + new.close() + if not self.editor: + webbrowser.open(new.name, new=2, autoraise=True) + if self.editor and not self.editor_args: + subprocess.check_call([self.editor, new.name]) + elif self.editor and self.editor_args: + subprocess.check_call( + [self.editor, new.name, self.editor_args]) + + if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): + with open(new.name) as f: + newyaml = f.read() + return newyaml, oldyaml + else: + exit() + + def save_items(self, oldnewlist, lib, fmt, opts): + oldset = [] + newset = [] + for old, new in oldnewlist: + oldset.append(old) + newset.append(new) + + no = [] + for newitem in range(0, len(newset)): + ordict = collections.OrderedDict() + for each in newset[newitem]: + ordict.update(each) + no.append(ordict) + + changedob = [] + for each in no: + if not opts.album: + ob = lib.get_item(each['id']) + else: + ob = lib.get_album(each['id']) + ob.update(each) + changedob.append(ob) + + if self.diff_method: + ostr = self.print_items[self.style](oldset) + nwstr = self.print_items[self.style](newset) + self.diffresults[self.diff_method](ostr, nwstr) + else: + for obj in changedob: + ui.show_model_changes(obj) + self.save_write(changedob) + + def save_write(self, changedob): + if not ui.input_yn('really modify? (y/n)'): + return + + for ob in changedob: + if config['import']['write'].get(bool): + ob.try_sync() + else: + ob.store() + print("changed: {0}".format(ob)) + + return + + def check_diff(self, newyaml, oldyaml): + nl = self.string_to_dict[self.style](newyaml) + ol = self.string_to_dict[self.style](oldyaml) + return filter(None, map(self.reduce_it, ol, nl)) + + '''if there is a forbidden field it gathers them here(check_ids)''' + def reduce_it(self, ol, nl): + if ol != nl: + for x in range(0, len(nl)): + if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: + nl[x] = ol[x] + print_("reset forbidden field.") + if ol != nl: + return ol, nl + + def ndiff(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.ndiff(newlines, oldlines) + print_('\n'.join(list(diff))) + return + + def unified(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.unified_diff(newlines, oldlines, lineterm='') + print_('\n'.join(list(diff))) + return + + def html(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.HtmlDiff() + df = diff.make_file(newlines, oldlines) + ht = NamedTemporaryFile('w', suffix='.html', delete=False) + ht.write(df) + hdn = ht.name + if not self.html_viewer: + webbrowser.open(hdn, new=2, autoraise=True) + else: + callmethod = [self.html_viewer] + callmethod.extend(self.html_args) + callmethod.append(hdn) + subprocess.call(callmethod) + return + + def vimdiff(self, newstringstr, oldstringstr): + + newdiff = NamedTemporaryFile(suffix='.old.yaml', delete=False) + newdiff.write(newstringstr) + newdiff.close() + olddiff = NamedTemporaryFile(suffix='.new.yaml', delete=False) + olddiff.write(oldstringstr) + olddiff.close() + subprocess.call(['vimdiff', newdiff.name, olddiff.name]) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst new file mode 100644 index 000000000..a81a58827 --- /dev/null +++ b/docs/plugins/yamleditor.rst @@ -0,0 +1,79 @@ +Yamleditor Plugin +================ +The ``yamleditor`` plugin lets you open the tags, fields from a group of items +, edit them in a text-editor and save them back. + +You simply put in a query like you normally do in beets. + + beet yamleditor beatles + beet yamleditor beatles -a + beet yamleditor beatles -f'$title-$lyrics' + + +You get a list of hits and then you can edit them. +The ``yamleditor`` opens your standard text-editor with a list of your hits +and for each hit a bunch of fields. + +Without anything specified in your ``config.yaml`` for ``yamleditor:`` +you will get + + track-$title-$artist-$album for items +and + + $album-$albumartist for albums + +you can get more fields from the cmdline by adding + + -f '$genre $added' +or + + -e '$year $comments' + +If you use ``-f '$field $field'`` you get *only* what you specified. + +If you use ``-e '$field $field'`` you get what you specified *extra*. + + -f or -e '$_all' gets you all the fields + +After you edit the values in your text-editor - *and you may only edit the values, +no deleting fields or adding fields!* - you save the file, answer with y on ``Done`` and +you get a summary of your changes. +Check em, answer y or n and the changes are written to your library. + +Configuration +------------ + +Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` + + yamleditor: + editor: # specify the editor you like + editor_args: # additional arguments for editor + diff_method: ndiff # 4 different ways to view your changes + diff_method: unified # Pick one. See ex https://pymotw.com/2/difflib/ + diff_method: html # for details or just try it :) + diff_method: vimdiff # this opens up vim diff + html_viewer: # viewer to see the diff_method html + html_args : # additional arguments for the viewer + albumfields: genre album # a list of albumfields to edit + itemfields: track artist # a list of itemfields to edit + not_fields: id path # list of not-wanted fields + separator: "|>" # something that separates printed fields + +* You can pick 1 of the diff-methods (or none and you get the beet way). +If you pick ``html`` you can specify a viewer for it. If not the systems-default +will be picked. + +* The ``albumfields`` and ``itemfields`` let you put in a list of fields you want to change. +``albumfields`` gets picked if you put -a in your search query else ``itemfields``. For a list of fields +do the ``beet fields``. + +* The ``not_fields`` always contain ``id`` and standard also the ``path``. +Don't want to mess with them. + +* The default ``separator`` prints like: + + -02-The Night Before-The Beatles-Help! + + but with ex "|>" it will look like: + + |>02|>The Night Before|>The Beatles|>Help! From 6c08aae3a4b02f6350e7af873aa021a9098bb21e Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 21:42:58 +0100 Subject: [PATCH 0078/2280] Update changelog.rst added yamleditor(a new plugin) entry --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 070dfeaf7..72f37bbf7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,6 +3,10 @@ Changelog 1.3.16 (in development) ----------------------- +* A new :doc:`/plugins/yamleditor` helps you manually edit fields from items. + You search for items in the normal beets way.Then yamleditor opens a texteditor + with the items and the fields of the items you want to edit. Afterwards you can + review your changes save them back into the items. Fixes: From d5c9be44d466026af5a960dfd90887431700d49f Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 22:02:20 +0100 Subject: [PATCH 0079/2280] Update changelog.rst --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 72f37bbf7..8182bdd69 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,7 +3,7 @@ Changelog 1.3.16 (in development) ----------------------- -* A new :doc:`/plugins/yamleditor` helps you manually edit fields from items. +* A new plugin yamleditor helps you manually edit fields from items. You search for items in the normal beets way.Then yamleditor opens a texteditor with the items and the fields of the items you want to edit. Afterwards you can review your changes save them back into the items. From e3e81502779e7a1cdee5bfd20221bf40494a21f0 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 22:07:59 +0100 Subject: [PATCH 0080/2280] Update yamleditor.rst polishing --- docs/plugins/yamleditor.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index a81a58827..2c51cb2ec 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -1,5 +1,5 @@ Yamleditor Plugin -================ +================= The ``yamleditor`` plugin lets you open the tags, fields from a group of items , edit them in a text-editor and save them back. @@ -41,7 +41,7 @@ you get a summary of your changes. Check em, answer y or n and the changes are written to your library. Configuration ------------- +------------- Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` From a3ee1d0d3795235a33c31d65cee9cef1889889aa Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 22:21:03 +0100 Subject: [PATCH 0081/2280] Update yamleditor.rst more polishing --- docs/plugins/yamleditor.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index 2c51cb2ec..fbb9f4eda 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -18,6 +18,7 @@ Without anything specified in your ``config.yaml`` for ``yamleditor:`` you will get track-$title-$artist-$album for items + and $album-$albumartist for albums @@ -25,6 +26,7 @@ and you can get more fields from the cmdline by adding -f '$genre $added' + or -e '$year $comments' From 151c1f3fbd591900f92c807baf0f19b87e35ad5a Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 23:00:02 +0100 Subject: [PATCH 0082/2280] Update yamleditor.rst polishing --- docs/plugins/yamleditor.rst | 70 +++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index fbb9f4eda..7317c3411 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -5,9 +5,12 @@ The ``yamleditor`` plugin lets you open the tags, fields from a group of items You simply put in a query like you normally do in beets. - beet yamleditor beatles - beet yamleditor beatles -a - beet yamleditor beatles -f'$title-$lyrics' + `beet yamleditor beatles` + + `beet yamleditor beatles -a` + + `beet yamleditor beatles -f'$title-$lyrics'` + You get a list of hits and then you can edit them. @@ -17,25 +20,25 @@ and for each hit a bunch of fields. Without anything specified in your ``config.yaml`` for ``yamleditor:`` you will get - track-$title-$artist-$album for items + `track-$title-$artist-$album` for items and - $album-$albumartist for albums + `$album-$albumartist` for albums you can get more fields from the cmdline by adding - -f '$genre $added' + `-f '$genre $added'` or - -e '$year $comments' + `-e '$year $comments'` If you use ``-f '$field $field'`` you get *only* what you specified. If you use ``-e '$field $field'`` you get what you specified *extra*. - -f or -e '$_all' gets you all the fields + ``-f or -e '$_all'`` gets you all the fields After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file, answer with y on ``Done`` and @@ -48,34 +51,39 @@ Configuration Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` yamleditor: - editor: # specify the editor you like - editor_args: # additional arguments for editor - diff_method: ndiff # 4 different ways to view your changes - diff_method: unified # Pick one. See ex https://pymotw.com/2/difflib/ - diff_method: html # for details or just try it :) - diff_method: vimdiff # this opens up vim diff - html_viewer: # viewer to see the diff_method html - html_args : # additional arguments for the viewer - albumfields: genre album # a list of albumfields to edit - itemfields: track artist # a list of itemfields to edit - not_fields: id path # list of not-wanted fields - separator: "|>" # something that separates printed fields - -* You can pick 1 of the diff-methods (or none and you get the beet way). -If you pick ``html`` you can specify a viewer for it. If not the systems-default -will be picked. - + * editor: nano + * editor_args: + * diff_method: ndiff + * html_viewer:firefox + * html_args : + * albumfields: genre album + * itemfields: track artist + * not_fields: id path + * separator: "|>" + +* editor: you can pick your own texteditor. Defaults to systems default. +* editor_args: in case you need extra arguments for your text-editor. +* diff_method: 4 choices + * ndiff: you see original and the changed yaml files with the changes + * unified: you see the changes with a bit of context. Simple and compact. + * html: a html file that you can open in a browser. Looks nice. + * vimdiff: gives you VIM with the diffs + with no diff_method you get the beets way of showing differences. +* html_viewer: + If you pick ``html`` you can specify a viewer for it. If not the systems-default + will be picked. +* html_args: in case your html_viewer needs arguments * The ``albumfields`` and ``itemfields`` let you put in a list of fields you want to change. -``albumfields`` gets picked if you put -a in your search query else ``itemfields``. For a list of fields -do the ``beet fields``. + ``albumfields`` gets picked if you put -a in your search query else ``itemfields``. For a list of fields + do the ``beet fields``. * The ``not_fields`` always contain ``id`` and standard also the ``path``. -Don't want to mess with them. + Don't want to mess with them. * The default ``separator`` prints like: - -02-The Night Before-The Beatles-Help! + ``-02-The Night Before-The Beatles-Help!`` - but with ex "|>" it will look like: + but with ex "|>" it will look like: - |>02|>The Night Before|>The Beatles|>Help! + ``|>02|>The Night Before|>The Beatles|>Help!`` From 149dd8676a351d9f8437a0845c677478859f5065 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 23:09:50 +0100 Subject: [PATCH 0083/2280] Update yamleditor.rst polishing --- docs/plugins/yamleditor.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index 7317c3411..21321ca08 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -59,7 +59,7 @@ Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` * albumfields: genre album * itemfields: track artist * not_fields: id path - * separator: "|>" + * separator: "<>" * editor: you can pick your own texteditor. Defaults to systems default. * editor_args: in case you need extra arguments for your text-editor. @@ -84,6 +84,6 @@ Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` ``-02-The Night Before-The Beatles-Help!`` - but with ex "|>" it will look like: + but with ex "<>" it will look like: - ``|>02|>The Night Before|>The Beatles|>Help!`` + ``<>02<>The Night Before<>The Beatles<>Help!`` From fdbf9e59e7d11b2462646ff12f81ff31f6520bf6 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 23:11:42 +0100 Subject: [PATCH 0084/2280] Update yamleditor.py polishing --- beetsplug/yamleditor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/yamleditor.py b/beetsplug/yamleditor.py index 963be9829..1124edd0e 100644 --- a/beetsplug/yamleditor.py +++ b/beetsplug/yamleditor.py @@ -1,5 +1,5 @@ # This file is part of beets. -# Copyright 2015 +# Copyright 2015, Jean-Marie Winters # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the From 3741e28947f0edf2080d6a3ba662e21733b1e68c Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 23:23:57 +0100 Subject: [PATCH 0085/2280] Update yamleditor.rst polishing --- docs/plugins/yamleditor.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index 21321ca08..863a34bfb 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -63,12 +63,12 @@ Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` * editor: you can pick your own texteditor. Defaults to systems default. * editor_args: in case you need extra arguments for your text-editor. -* diff_method: 4 choices +* diff_method: 4 choices with no diff_method you get the beets way of showing differences. * ndiff: you see original and the changed yaml files with the changes * unified: you see the changes with a bit of context. Simple and compact. * html: a html file that you can open in a browser. Looks nice. * vimdiff: gives you VIM with the diffs - with no diff_method you get the beets way of showing differences. + * html_viewer: If you pick ``html`` you can specify a viewer for it. If not the systems-default will be picked. From 69b0ae974599a9e00339a8eeeccc1ccbb03feb4d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Nov 2015 14:40:00 -0800 Subject: [PATCH 0086/2280] Add an FAQ about changing music directories --- docs/faq.rst | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/faq.rst b/docs/faq.rst index 447be45e1..050461587 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -208,6 +208,23 @@ Use the ``%asciify{}`` function in your path formats. See :ref:`template-functions`. +.. _move-dir: + +…point beets at a new music directory? +-------------------------------------- + +If you want to move your music from one directory to another, the best way is +to let beets do it for you. First, edit your configuration and set the +``directory`` setting to the new place. Then, type ``beet move`` to have beets +move all your files. + +If you've already moved your music *outside* of beets, you have a few options: + +- Move the music back (with an ordinary ``mv``) and then use the above steps. +- Delete your database and re-create it from the new paths using ``beet import -AWMC``. +- Resort to manually modifying the SQLite database (not recommended). + + Why does beets… =============== From bcef3a71232ab66384f1ff532c334ef111eb9175 Mon Sep 17 00:00:00 2001 From: kooimens Date: Mon, 2 Nov 2015 23:56:38 +0100 Subject: [PATCH 0087/2280] Create function remove_artfile Damn it, that was really hard for me:D. First time seriously using python. Please review it carefuly. --- beetsplug/embedart.py | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 9afcf9cf4..df7f95d1d 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -79,14 +79,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): for album in lib.albums(decargs(args)): art.embed_album(self._log, album, maxwidth, False, compare_threshold, ifempty) - - if remove_art_file and album.artpath: - if os.path.isfile(album.artpath): - self._log.debug(u'Removing album art file ' - u'for {0}', album) - os.remove(album.artpath) - album.artpath = None - album.store() + self.remove_artfile(album) embed_cmd.func = embed_func @@ -141,10 +134,12 @@ class EmbedCoverArtPlugin(BeetsPlugin): art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool)) - if self.config['remove_art_file'] and album.artpath: - if os.path.isfile(album.artpath): - self._log.debug(u'Removing album art file ' - u'for {0}', album) - os.remove(album.artpath) - album.artpath = None - album.store() + self.remove_artfile(album) + def remove_artfile(self, album) + if self.config['remove_art_file'] and album.artpath: + if os.path.isfile(album.artpath): + self._log.debug(u'Removing album art file ' + u'for {0}', album) + os.remove(album.artpath) + album.artpath = None + album.store() From f0040370ec47bc7295ecccde0eae9df45beb4377 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Mon, 2 Nov 2015 23:57:11 +0100 Subject: [PATCH 0088/2280] Update yamleditor.rst polishing --- docs/plugins/yamleditor.rst | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst index 863a34bfb..d5f3641ba 100644 --- a/docs/plugins/yamleditor.rst +++ b/docs/plugins/yamleditor.rst @@ -1,7 +1,6 @@ Yamleditor Plugin ================= -The ``yamleditor`` plugin lets you open the tags, fields from a group of items -, edit them in a text-editor and save them back. +The ``yamleditor`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. You simply put in a query like you normally do in beets. @@ -13,20 +12,19 @@ You simply put in a query like you normally do in beets. -You get a list of hits and then you can edit them. -The ``yamleditor`` opens your standard text-editor with a list of your hits -and for each hit a bunch of fields. +You get a list of hits and then you can edit them. The ``yamleditor`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. -Without anything specified in your ``config.yaml`` for ``yamleditor:`` -you will get +Without anything specified in your ``config.yaml`` for ``yamleditor:`` you will get - `track-$title-$artist-$album` for items +for items + + `track-$title-$artist-$album` -and +and for albums - `$album-$albumartist` for albums + `$album-$albumartist` -you can get more fields from the cmdline by adding +you can get fields from the cmdline by adding `-f '$genre $added'` @@ -34,16 +32,13 @@ or `-e '$year $comments'` -If you use ``-f '$field $field'`` you get *only* what you specified. +If you use ``-f '$field ...'`` you get *only* what you specified. -If you use ``-e '$field $field'`` you get what you specified *extra*. +If you use ``-e '$field ...'`` you get what you specified *extra*. - ``-f or -e '$_all'`` gets you all the fields +If you use ``-f or -e '$_all'`` you get all the fields. -After you edit the values in your text-editor - *and you may only edit the values, -no deleting fields or adding fields!* - you save the file, answer with y on ``Done`` and -you get a summary of your changes. -Check em, answer y or n and the changes are written to your library. +After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file, answer with y on ``Done`` and you get a summary of your changes. Check em, answer y or n and the changes are written to your library. Configuration ------------- From e84414c822a073848152787868c41bd97f713551 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Nov 2015 16:44:02 -0800 Subject: [PATCH 0089/2280] Fix syntax (and unused variable) in #1675 --- beetsplug/embedart.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index df7f95d1d..01f11d3a3 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -63,7 +63,6 @@ class EmbedCoverArtPlugin(BeetsPlugin): maxwidth = self.config['maxwidth'].get(int) compare_threshold = self.config['compare_threshold'].get(int) ifempty = self.config['ifempty'].get(bool) - remove_art_file = self.config['remove_art_file'].get(bool) def embed_func(lib, opts, args): if opts.file: @@ -135,7 +134,8 @@ class EmbedCoverArtPlugin(BeetsPlugin): self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool)) self.remove_artfile(album) - def remove_artfile(self, album) + + def remove_artfile(self, album): if self.config['remove_art_file'] and album.artpath: if os.path.isfile(album.artpath): self._log.debug(u'Removing album art file ' From d79d11fb15d95810824843cffca9072381d83eff Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Nov 2015 16:45:45 -0800 Subject: [PATCH 0090/2280] Docstring and rewrap for #1675 --- beetsplug/embedart.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 01f11d3a3..9c0efa51e 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -136,10 +136,12 @@ class EmbedCoverArtPlugin(BeetsPlugin): self.remove_artfile(album) def remove_artfile(self, album): + """Possibly delete the album art file for an album (if the + appropriate configuration option is enabled. + """ if self.config['remove_art_file'] and album.artpath: if os.path.isfile(album.artpath): - self._log.debug(u'Removing album art file ' - u'for {0}', album) + self._log.debug('Removing album art file for {0}', album) os.remove(album.artpath) album.artpath = None album.store() From bfa2fbf6afbcdb45689da8c664067a118bf1957b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Nov 2015 16:46:32 -0800 Subject: [PATCH 0091/2280] Changelog for #1675 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 070dfeaf7..7e4564978 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,8 @@ Fixes: non-existent album art file would prevent the command from fetching new art. :bug:`1126` * :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` +* :doc:`/plugins/embedart`: The ``remove_art_file`` option now works on import + (as well as with the explicit command). :bug:`1662` :bug:`1675` 1.3.15 (October 17, 2015) From 93009911e00b29ae378ac27785873e71cb00c2a5 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 02:17:21 +0100 Subject: [PATCH 0092/2280] fetchart: Add test for image resizing This test ensures that images are resized if and only if they are wider than the maxwidth setting. --- test/test_art.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index 3cc24a7a4..fa8406c58 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -21,6 +21,7 @@ import os import shutil import responses +from mock import patch from test import _common from test._common import unittest @@ -409,6 +410,12 @@ class ArtForAlbumTest(UseThePlugin): else: self.assertIsNone(local_artpath) + def _assertImageResized(self, image_file, should_resize): + self.image_file = image_file + with patch.object(ArtResizer.shared, 'resize') as mock_resize: + self.plugin.art_for_album(None, [''], True) + self.assertEqual(mock_resize.called, should_resize) + def _require_backend(self): """Skip the test if the art resizer doesn't have ImageMagick or PIL (so comparisons and measurements are unavailable). @@ -432,6 +439,12 @@ class ArtForAlbumTest(UseThePlugin): self.plugin.enforce_ratio = False self._assertImageIsValidArt(self.IMG_500x490, True) + def test_resize_if_necessary(self): + self._require_backend() + self.plugin.maxwidth = 300 + self._assertImageResized(self.IMG_225x225, False) + self._assertImageResized(self.IMG_348x348, True) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 19dcc25a93689883d6b210e831af722eda16ff05 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 02:19:47 +0100 Subject: [PATCH 0093/2280] fetchart: Improve validation of image dimensions This avoids images being resized unnecessarily if the dimensions are correct. --- beetsplug/fetchart.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 9da781e6c..df0eb84ac 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -519,7 +519,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if not candidate: return CANDIDATE_BAD - if not (self.enforce_ratio or self.minwidth): + if not (self.enforce_ratio or self.minwidth or self.maxwidth): return CANDIDATE_EXACT # get_size returns None if no local imaging backend is available @@ -532,9 +532,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): u'`enforce_ratio` may be violated.') return CANDIDATE_EXACT - if size[0] >= self.minwidth and ( + if (not self.minwidth or size[0] >= self.minwidth) and ( not self.enforce_ratio or size[0] == size[1]): - if size[0] > self.maxwidth: + if not self.maxwidth or size[0] > self.maxwidth: return CANDIDATE_DOWNSCALE return CANDIDATE_EXACT return CANDIDATE_BAD From 5d0048c03d800683379fbcb3840fb4554a66e068 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 02:38:02 +0100 Subject: [PATCH 0094/2280] Changelog for #1683 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4eafe9c90..7ad738c84 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,6 +16,8 @@ Fixes: when there were not. :bug:`1652` * :doc:`plugins/lastgenre`: Clean up the reggae related genres somewhat. Thanks to :user:`Freso`. :bug:`1661` +* :doc:`plugins/fetchart`: The plugin now only resizes album art if necessary, + rather than always by default. :bug:`1264` 1.3.15 (October 17, 2015) From 33ea9f1c101183ff1d8fba68950120b967cf14a8 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 11:25:04 +0100 Subject: [PATCH 0095/2280] Revert all changes on this branch thus far Revert "PEP8 amendments" This reverts commit 413fe6bbfd695725c9ca7d306dfe408d20ad3904. Revert "Importer: Delete orphaned album art on..." This reverts commit 629a80a1d12818cfa0de0b8b8b8a0e24d753215a. --- beets/importer.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 8aecf54a3..95163b6fd 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -547,23 +547,6 @@ class ImportTask(BaseImportTask): items = self.imported_items() - # If any original album art files were reused, leave them untouched. - for item in items: - album = item.get_album() - if album: - self.old_art_paths.discard(album.artpath) - - # Delete remaining original album art files. - for old_art_path in self.old_art_paths: - log.debug('Deleting orphaned album art: {0}', old_art_path) - util.remove(syspath(old_art_path), True) - # XXX: Ideally the directory would get pruned with self.prune() - # below, but when calling `beet import -L`, self.toppath is set - # to None, making self.prune() a no-op; hence this workaround of - # calling util.prune_dirs() directly. - util.prune_dirs(os.path.dirname(old_art_path), - clutter=config['clutter'].as_str_seq()) - # When copying and deleting originals, delete old files. if copy and delete: new_paths = [os.path.realpath(item.path) for item in items] @@ -669,11 +652,6 @@ class ImportTask(BaseImportTask): # Save the original paths of all items for deletion and pruning # in the next step (finalization). self.old_paths = [item.path for item in items] - - # Keep track of paths of all original album art for the same reason. - self.old_art_paths = set(filter( - bool, (album.artpath for album in self.replaced_albums.values()))) - for item in items: if move or copy or link: # In copy and link modes, treat re-imports specially: From 2d77861e4d6867093873c516e8ca39bea94f5f34 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 13:55:08 +0100 Subject: [PATCH 0096/2280] renamed and updated editplugin --- beetsplug/edit.py | 357 ++++++++++++++++++++++++++++++++++++++++++ docs/plugins/edit.rst | 88 +++++++++++ 2 files changed, 445 insertions(+) create mode 100644 beetsplug/edit.py create mode 100644 docs/plugins/edit.rst diff --git a/beetsplug/edit.py b/beetsplug/edit.py new file mode 100644 index 000000000..00de0f444 --- /dev/null +++ b/beetsplug/edit.py @@ -0,0 +1,357 @@ +# This file is part of beets. +# Copyright 2015 jean-marie winters +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""open tags of items in texteditor,change them and save back to the items. +""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from beets import plugins +from beets.ui import Subcommand, decargs, library, print_ +import subprocess +import difflib +import yaml +import collections +import webbrowser +from sys import exit +from beets import config +from beets import ui +from tempfile import NamedTemporaryFile + + +class EditPlugin(plugins.BeetsPlugin): + + def __init__(self): + super(EditPlugin, self).__init__() + + self.config.add({ + 'style': 'yaml', + 'editor': '', + 'diff_method': '', + 'browser': '', + 'albumfields': 'album albumartist', + 'itemfields': 'track title artist album ', + 'not_fields': 'path', + 'separator': '-' + + }) + self.style = self.config['style'].get(unicode) + """the editor field in the config lets you specify your editor. + Defaults to open with webrowser module""" + self.editor = self.config['editor'].as_str_seq() + """the html_viewer field in your config lets you specify + your htmlviewer. Defaults to open with webrowser module""" + self.browser = self.config['browser'].as_str_seq() + """the diff_method field in your config picks the way to see your + changes. Options are: + 'ndiff'(2 files with differences), + 'unified'(just the different lines and a few lines of context), + 'html'(view in html-format), + 'vimdiff'(view in VIM)""" + self.diff_method = self.config['diff_method'].get(unicode) + """the albumfields field in your config sets the tags that + you want to see/change for albums. + Defaults to album albumartist. + the ID tag will always be listed as it is used to identify the item""" + self.albumfields = self.config['albumfields'].as_str_seq() + """the itemfields field in your config sets the tags that + you want to see/change or items. + Defaults to track title artist album. + the ID tag will always be listed as it is used to identify the item""" + self.itemfields = self.config['itemfields'].as_str_seq() + '''the not_fields field in your config sets the tags that + will not be changed. + If you happen to change them, they will be restored to the original + value. The ID of an item will never be changed.''' + self.not_fields = self.config['not_fields'].as_str_seq() + '''the separator in your config sets the separator that will be used + between fields in your terminal. Defaults to -''' + self.separator = self.config['separator'].get(unicode) + self.ed = None + self.ed_args = None + self.brw = None + self.brw_args = None + + def commands(self): + edit_command = Subcommand( + 'edit', + help='send items to yamleditor for editing tags') + edit_command.parser.add_option( + '-e', '--extra', + action='store', + help='add additional fields to edit', + ) + edit_command.parser.add_option( + '--all', + action='store_true', dest='all', + help='add all fields to edit', + ) + edit_command.parser.add_all_common_options() + edit_command.func = self.editor_music + return[edit_command] + + def editor_music(self, lib, opts, args): + if self.editor: + self.ed_args = self.editor[1:] if len(self.editor) > 1 else None + self.ed = self.editor[0] if self.editor else None + if self.browser: + self.brw_args = self.browser[1:] if len(self.browser) > 1 else None + self.brw = self.browser[0] if self.browser else None + + # edit tags in a textfile in yaml-style + query = decargs(args) + # makes a string representation of an object + # for now yaml but we could add html,pprint,toml + self.print_items = { + 'yaml': self.print_to_yaml} + # makes an object from a string representation + # for now yaml but we could add html,pprint,toml + self.string_to_dict = { + 'yaml': self.yaml_to_dict} + # 4 ways to view the changes in objects + self.diffresults = { + 'ndiff': self.ndiff, + 'unified': self.unified, + 'html': self.html, + 'vimdiff': self.vimdiff} + # make a dictionary from the chosen fields + # you can do em all or a selection + self.make_dict = { + 'all': self.get_all_fields, + "selected": self.get_selected_fields} + + objs = self._get_objs(lib, opts, query) + if not objs: + print_('nothing found') + return + fmt = self.get_fields_from(objs, opts) + print_(fmt) + [print_(format(item, fmt)) for item in objs] + if not ui.input_yn(ui.colorize('action_default', "Edit?(n/y)"), True): + return + dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) + newyaml, oldyaml = self.change_objs(dict_from_objs) + changed_objs = self.check_diff(newyaml, oldyaml) + if not changed_objs: + print_("nothing to change") + return + self.save_items(changed_objs, lib, fmt, opts) + + def print_to_yaml(self, arg): + # from object to yaml + return yaml.safe_dump_all( + arg, + allow_unicode=True, + default_flow_style=False) + + def yaml_to_dict(self, yam): + # from yaml to object + return yaml.load_all(yam) + + def _get_objs(self, lib, opts, query): + # get objects from a query + if opts.album: + return list(lib.albums(query)) + else: + return list(lib.items(query)) + + def get_fields_from(self, objs, opts): + # construct a list of fields we need + cl = ui.colorize('action', self.separator) + # see if we need album or item fields + self.fields = self.albumfields if opts.album else self.itemfields + # if opts.format is given only use those fields + if opts.format: + self.fields = [] + self.fields.extend((opts.format).replace('$', "").split()) + # if opts.extra is given add those + if opts.extra: + fi = (opts.extra).replace('$', "").split() + self.fields.extend([f for f in fi if f not in self.fields]) + # make sure we got the id for identification + if 'id' not in self.fields: + self.fields.insert(0, 'id') + # we need all the fields + if opts.all: + self.fields = None + self.pick = "all" + print_(ui.colorize('text_warning', "edit all fields from:")) + if opts.album: + fmt = cl + cl.join(['$albumartist', '$album']) + else: + fmt = cl + cl.join(['$title', '$artist']) + else: + for it in self.fields: + if opts.album: + if it not in library.Album.all_keys(): + print_( + "{} not in albumfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + self.fields.remove(it) + else: + if it not in library.Item.all_keys(): + print_( + "{} not in itemfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + self.fields.remove(it) + self.pick = "selected" + fmtfields = ["$" + it for it in self.fields] + fmt = cl + cl.join(fmtfields[1:]) + + return fmt + + def get_selected_fields(self, myfields, objs, opts): + a = [] + for mod in objs: + a.append([{fi: mod[fi]}for fi in myfields]) + return a + + def get_all_fields(self, myfields, objs, opts): + a = [] + for mod in objs: + a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) + return a + + def change_objs(self, dict_items): + # construct a yaml from the original object-fields + # and make a yaml that we can change in the text-editor + oldyaml = self.print_items[self.style](dict_items) + newyaml = self.print_items[self.style](dict_items) + new = NamedTemporaryFile(suffix='.yaml', delete=False) + new.write(newyaml) + new.close() + if not self.ed: + webbrowser.open(new.name, new=2, autoraise=True) + else: + callmethod = [self.ed] + if self.ed_args: + callmethod.extend(self.ed_args) + callmethod.append(new.name) + subprocess.check_call(callmethod) + + if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): + with open(new.name) as f: + newyaml = f.read() + return newyaml, oldyaml + else: + exit() + + def save_items(self, oldnewlist, lib, fmt, opts): + oldset = [] + newset = [] + for old, new in oldnewlist: + oldset.append(old) + newset.append(new) + + no = [] + for newitem in range(0, len(newset)): + ordict = collections.OrderedDict() + for each in newset[newitem]: + ordict.update(each) + no.append(ordict) + + changedob = [] + for each in no: + if not opts.album: + ob = lib.get_item(each['id']) + else: + ob = lib.get_album(each['id']) + ob.update(each) + changedob.append(ob) + + if self.diff_method: + ostr = self.print_items[self.style](oldset) + nwstr = self.print_items[self.style](newset) + pprint.pprint(self.diff_method) + pprint.pprint(type(self.diff_method)) + self.diffresults[self.diff_method](ostr, nwstr) + else: + for obj in changedob: + ui.show_model_changes(obj) + self.save_write(changedob) + + def save_write(self, changedob): + if not ui.input_yn('really modify? (y/n)'): + return + + for ob in changedob: + if config['import']['write'].get(bool): + ob.try_sync() + else: + ob.store() + print("changed: {0}".format(ob)) + + return + + def check_diff(self, newyaml, oldyaml): + # get the changed objects + nl = self.string_to_dict[self.style](newyaml) + ol = self.string_to_dict[self.style](oldyaml) + return filter(None, map(self.reduce_it, ol, nl)) + + def reduce_it(self, ol, nl): + # if there is a forbidden field it resets them + if ol != nl: + for x in range(0, len(nl)): + if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: + nl[x] = ol[x] + print_("reset forbidden field.") + if ol != nl: + return ol, nl + + def ndiff(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.ndiff(newlines, oldlines) + print_('\n'.join(list(diff))) + return + + def unified(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.unified_diff(newlines, oldlines, lineterm='') + print_('\n'.join(list(diff))) + return + + def html(self, newfilestr, oldfilestr): + newlines = newfilestr.splitlines() + oldlines = oldfilestr.splitlines() + diff = difflib.HtmlDiff() + pprint.pprint("here in html") + df = diff.make_file(newlines, oldlines) + ht = NamedTemporaryFile('w', suffix='.html', delete=False) + ht.write(df) + ht.flush() + hdn = ht.name + if not self.brw: + webbrowser.open(hdn, new=2, autoraise=True) + else: + callmethod = [self.brw] + if self.brw_args: + callmethod.extend(self.brw_args) + callmethod.append(hdn) + subprocess.call(callmethod) + return + + def vimdiff(self, newstringstr, oldstringstr): + + newdiff = NamedTemporaryFile(suffix='.old.yaml', delete=False) + newdiff.write(newstringstr) + newdiff.close() + olddiff = NamedTemporaryFile(suffix='.new.yaml', delete=False) + olddiff.write(oldstringstr) + olddiff.close() + subprocess.call(['vimdiff', newdiff.name, olddiff.name]) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst new file mode 100644 index 000000000..68ec7a056 --- /dev/null +++ b/docs/plugins/edit.rst @@ -0,0 +1,88 @@ +editPlugin +============ +The ``edit`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. +Add the ``edit`` plugin to your ``plugins:`` in your ``config.yaml``. Then +you simply put in a query like you normally do. +:: + + beet yamleditor beatles + beet yamleditor beatles -a + beet yamleditor beatles -f '$title $lyrics' + + + +You get a list of hits and then you can edit them. The ``edit`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. + +Without anything specified in your ``config.yaml`` for ``edit:`` you will see + +for items +:: + + $track-$title-$artist-$album + +and for albums +:: + + $album-$albumartist + +You can get fields from the cmdline by adding +:: + + -f '$genre $added' + +or + +:: + + -e '$year $comments' + +If you use ``-f '$field ...'`` you get *only* what you specified. + +If you use ``-e '$field ...'`` you get what you specified *extra*. + +If you add ``--all`` you get all the fields. + +After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file, answer with ``y`` on ``Done?`` and you get a summary of your changes. Check em, answer ``y`` or ``n`` and the changes are written to your library. + +Configuration +------------- + +Make a ``edit:`` section in your config.yaml ``(beet config -e)`` +:: + + edit: + editor: nano -w -p + diff_method: html + browser: firefox -private-window + albumfields: genre album + itemfields: track artist + not_fields: id path + separator: "<>" + +* ``editor:`` pick your own texteditor; add arguments if needed. If no``editor:`` then your system opens the file-extension. + +* ``diff_method:`` 4 choices. With no ``diff_method:`` you get the beets way of showing differences. + - ``ndiff``: you see original and the changed yamls with the changes. + - ``unified``: you see the changes with a bit of context. Simple and compact. + - ``html``: a html file that you can open in a browser. Looks nice. + - ``vimdiff``: gives you VIM with the diffs.You need VIM for this. + +* ``browser:`` + If you pick ``diff_method:html`` you can specify a viewer for it (if needed add arguments). If not, let your system open the file-extension. + +* The ``albumfields:`` and ``itemfields:`` lets you list the fields you want to change. + ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields + do the ``beet fields`` command. + +* The ``not_fields:``. Fields that you put in here will not be changed. You can see them but not change them. It always contains ``id`` and standard also the ``path``. + Don't want to mess with them. + +* The default ``separator:`` prints like: +:: + + -02-The Night Before-The Beatles-Help! + +but you can pick anything else. With "<>" it will look like: +:: + + <>02<>The Night Before<>The Beatles<>Help! From 91f67146f942afeb22c99d321b3a2728f1598420 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 14:04:39 +0100 Subject: [PATCH 0097/2280] Delete yamleditor.rst --- docs/plugins/yamleditor.rst | 84 ------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 docs/plugins/yamleditor.rst diff --git a/docs/plugins/yamleditor.rst b/docs/plugins/yamleditor.rst deleted file mode 100644 index d5f3641ba..000000000 --- a/docs/plugins/yamleditor.rst +++ /dev/null @@ -1,84 +0,0 @@ -Yamleditor Plugin -================= -The ``yamleditor`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. - -You simply put in a query like you normally do in beets. - - `beet yamleditor beatles` - - `beet yamleditor beatles -a` - - `beet yamleditor beatles -f'$title-$lyrics'` - - - -You get a list of hits and then you can edit them. The ``yamleditor`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. - -Without anything specified in your ``config.yaml`` for ``yamleditor:`` you will get - -for items - - `track-$title-$artist-$album` - -and for albums - - `$album-$albumartist` - -you can get fields from the cmdline by adding - - `-f '$genre $added'` - -or - - `-e '$year $comments'` - -If you use ``-f '$field ...'`` you get *only* what you specified. - -If you use ``-e '$field ...'`` you get what you specified *extra*. - -If you use ``-f or -e '$_all'`` you get all the fields. - -After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file, answer with y on ``Done`` and you get a summary of your changes. Check em, answer y or n and the changes are written to your library. - -Configuration -------------- - -Make a ``yamleditor:`` section in your config.yaml ``(beet config -e)`` - - yamleditor: - * editor: nano - * editor_args: - * diff_method: ndiff - * html_viewer:firefox - * html_args : - * albumfields: genre album - * itemfields: track artist - * not_fields: id path - * separator: "<>" - -* editor: you can pick your own texteditor. Defaults to systems default. -* editor_args: in case you need extra arguments for your text-editor. -* diff_method: 4 choices with no diff_method you get the beets way of showing differences. - * ndiff: you see original and the changed yaml files with the changes - * unified: you see the changes with a bit of context. Simple and compact. - * html: a html file that you can open in a browser. Looks nice. - * vimdiff: gives you VIM with the diffs - -* html_viewer: - If you pick ``html`` you can specify a viewer for it. If not the systems-default - will be picked. -* html_args: in case your html_viewer needs arguments -* The ``albumfields`` and ``itemfields`` let you put in a list of fields you want to change. - ``albumfields`` gets picked if you put -a in your search query else ``itemfields``. For a list of fields - do the ``beet fields``. - -* The ``not_fields`` always contain ``id`` and standard also the ``path``. - Don't want to mess with them. - -* The default ``separator`` prints like: - - ``-02-The Night Before-The Beatles-Help!`` - - but with ex "<>" it will look like: - - ``<>02<>The Night Before<>The Beatles<>Help!`` From 5a8a534a3ff1fac2e4e5d7004c4fcc7b1908207f Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 14:05:06 +0100 Subject: [PATCH 0098/2280] Delete yamleditor.py --- beetsplug/yamleditor.py | 329 ---------------------------------------- 1 file changed, 329 deletions(-) delete mode 100644 beetsplug/yamleditor.py diff --git a/beetsplug/yamleditor.py b/beetsplug/yamleditor.py deleted file mode 100644 index 1124edd0e..000000000 --- a/beetsplug/yamleditor.py +++ /dev/null @@ -1,329 +0,0 @@ -# This file is part of beets. -# Copyright 2015, Jean-Marie Winters -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - -"""open tags of items in texteditor,change them and save back to the items. -""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) - -from beets import plugins -from beets.ui import Subcommand, decargs, library, print_ -import subprocess -import difflib -import yaml -import collections -import webbrowser -from sys import exit -from beets import config -from beets import ui -from tempfile import NamedTemporaryFile - - -class yamleditorPlugin(plugins.BeetsPlugin): - - def __init__(self): - super(yamleditorPlugin, self).__init__() - - self.config.add({ - 'style': 'yaml', - 'editor': '', - 'diff_method': '', - 'html_viewer': '', - 'editor_args': '', - 'html_args': '', - 'albumfields': 'album albumartist', - 'itemfields': 'track title artist album ', - 'not_fields': 'path', - 'separator': '-' - - }) - - def commands(self): - yamleditor_command = Subcommand( - 'yamleditor', - help='send items to yamleditor for editing tags') - yamleditor_command.parser.add_option( - '-e', '--extra', - action='store', - help='add additional fields to edit', - ) - yamleditor_command.parser.add_all_common_options() - yamleditor_command.func = self.editor_music - return[yamleditor_command] - - def editor_music(self, lib, opts, args): - """edit tags in a textfile in yaml-style - """ - self.style = self.config['style'].get() - """the editor field in the config lets you specify your editor. - Defaults to open with webrowser module""" - self.editor = self.config['editor'].get() - """the editor_args field in your config lets you specify - additional args for your editor""" - self.editor_args = self.config['editor_args'].get().split() - """the html_viewer field in your config lets you specify - your htmlviewer. Defaults to open with webrowser module""" - self.html_viewer = self.config['html_viewer'].get() - """the html_args field in your config lets you specify - additional args for your viewer""" - self.html_args = self.config['html_args'].get().split() - """the diff_method field in your config picks the way to see your - changes. Options are: - 'ndiff'(2 files with differences), - 'unified'(just the different lines and a few lines of context), - 'html'(view in html-format), - 'vimdiff'(view in VIM)""" - self.diff_method = self.config['diff_method'].get() - """the albumfields field in your config sets the tags that - you want to see/change for albums. - Defaults to album albumartist. - the ID tag will always be listed as it is used to identify the item""" - self.albumfields = self.config['albumfields'].get().split() - """the itemfields field in your config sets the tags that - you want to see/change or items. - Defaults to track title artist album. - the ID tag will always be listed as it is used to identify the item""" - self.itemfields = self.config['itemfields'].get().split() - '''the not_fields field in your config sets the tags that - will not be changed. - If you happen to change them, they will be restored to the original - value. The ID of an item will never be changed.''' - self.not_fields = self.config['not_fields'].get().split() - '''the separator in your config sets the separator that will be used - between fields in your terminal. Defaults to -''' - self.separator = self.config['separator'].get() - - query = decargs(args) - self.print_items = { - 'yaml': self.print_to_yaml} - self.diffresults = { - 'ndiff': self.ndiff, - 'unified': self.unified, - 'html': self.html, - 'vimdiff': self.vimdiff} - self.make_dict = { - 'all': self.get_all_fields, - "selected": self.get_selected_fields} - self.string_to_dict = { - 'yaml': self.yaml_to_dict} - - objs = self._get_objs(lib, opts, query) - if not objs: - print_('nothing found') - return - fmt = self.get_fields_from(objs, opts) - print_(fmt) - [print_(format(item, fmt)) for item in objs] - if not ui.input_yn(ui.colorize('action_default', "Edit?(n/y)"), True): - return - dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) - newyaml, oldyaml = self.change_objs(dict_from_objs) - changed_objs = self.check_diff(newyaml, oldyaml) - if not changed_objs: - print_("nothing to change") - return - self.save_items(changed_objs, lib, fmt, opts) - - '''from object to yaml''' - def print_to_yaml(self, arg): - return yaml.safe_dump_all( - arg, - allow_unicode=True, - default_flow_style=False) - - '''from yaml to object''' - def yaml_to_dict(self, yam): - return yaml.load_all(yam) - - def _get_objs(self, lib, opts, query): - if opts.album: - return list(lib.albums(query)) - else: - return list(lib.items(query)) - - def get_fields_from(self, objs, opts): - cl = ui.colorize('action', self.separator) - self.fields = self.albumfields if opts.album else self.itemfields - if opts.format: - self.fields = [] - self.fields.extend((opts.format).replace('$', "").split()) - if opts.extra: - fi = (opts.extra).replace('$', "").split() - self.fields.extend([f for f in fi if f not in self.fields]) - if 'id' not in self.fields: - self.fields.insert(0, 'id') - if "_all" in self.fields: - self.fields = None - self.pick = "all" - print_(ui.colorize('text_warning', "edit all fields from ...")) - if opts.album: - fmt = cl + cl.join(['$albumartist', '$album']) - else: - fmt = cl + cl.join(['$title', '$artist']) - else: - for it in self.fields: - if opts.album: - if it not in library.Album.all_keys(): - print_( - "{} not in albumfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - self.fields.remove(it) - else: - if it not in library.Item.all_keys(): - print_( - "{} not in itemfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - self.fields.remove(it) - self.pick = "selected" - fmtfields = ["$" + it for it in self.fields] - fmt = cl + cl.join(fmtfields[1:]) - - return fmt - - '''get the fields we want and make a dic from them''' - def get_selected_fields(self, myfields, objs, opts): - a = [] - for mod in objs: - a.append([{fi: mod[fi]}for fi in myfields]) - return a - - def get_all_fields(self, myfields, objs, opts): - a = [] - for mod in objs: - a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) - return a - - def change_objs(self, dict_items): - oldyaml = self.print_items[self.style](dict_items) - newyaml = self.print_items[self.style](dict_items) - new = NamedTemporaryFile(suffix='.yaml', delete=False) - new.write(newyaml) - new.close() - if not self.editor: - webbrowser.open(new.name, new=2, autoraise=True) - if self.editor and not self.editor_args: - subprocess.check_call([self.editor, new.name]) - elif self.editor and self.editor_args: - subprocess.check_call( - [self.editor, new.name, self.editor_args]) - - if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): - with open(new.name) as f: - newyaml = f.read() - return newyaml, oldyaml - else: - exit() - - def save_items(self, oldnewlist, lib, fmt, opts): - oldset = [] - newset = [] - for old, new in oldnewlist: - oldset.append(old) - newset.append(new) - - no = [] - for newitem in range(0, len(newset)): - ordict = collections.OrderedDict() - for each in newset[newitem]: - ordict.update(each) - no.append(ordict) - - changedob = [] - for each in no: - if not opts.album: - ob = lib.get_item(each['id']) - else: - ob = lib.get_album(each['id']) - ob.update(each) - changedob.append(ob) - - if self.diff_method: - ostr = self.print_items[self.style](oldset) - nwstr = self.print_items[self.style](newset) - self.diffresults[self.diff_method](ostr, nwstr) - else: - for obj in changedob: - ui.show_model_changes(obj) - self.save_write(changedob) - - def save_write(self, changedob): - if not ui.input_yn('really modify? (y/n)'): - return - - for ob in changedob: - if config['import']['write'].get(bool): - ob.try_sync() - else: - ob.store() - print("changed: {0}".format(ob)) - - return - - def check_diff(self, newyaml, oldyaml): - nl = self.string_to_dict[self.style](newyaml) - ol = self.string_to_dict[self.style](oldyaml) - return filter(None, map(self.reduce_it, ol, nl)) - - '''if there is a forbidden field it gathers them here(check_ids)''' - def reduce_it(self, ol, nl): - if ol != nl: - for x in range(0, len(nl)): - if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: - nl[x] = ol[x] - print_("reset forbidden field.") - if ol != nl: - return ol, nl - - def ndiff(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.ndiff(newlines, oldlines) - print_('\n'.join(list(diff))) - return - - def unified(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.unified_diff(newlines, oldlines, lineterm='') - print_('\n'.join(list(diff))) - return - - def html(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.HtmlDiff() - df = diff.make_file(newlines, oldlines) - ht = NamedTemporaryFile('w', suffix='.html', delete=False) - ht.write(df) - hdn = ht.name - if not self.html_viewer: - webbrowser.open(hdn, new=2, autoraise=True) - else: - callmethod = [self.html_viewer] - callmethod.extend(self.html_args) - callmethod.append(hdn) - subprocess.call(callmethod) - return - - def vimdiff(self, newstringstr, oldstringstr): - - newdiff = NamedTemporaryFile(suffix='.old.yaml', delete=False) - newdiff.write(newstringstr) - newdiff.close() - olddiff = NamedTemporaryFile(suffix='.new.yaml', delete=False) - olddiff.write(oldstringstr) - olddiff.close() - subprocess.call(['vimdiff', newdiff.name, olddiff.name]) From 76509e168224d91b40660cea15417fedd02cdb88 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 14:37:34 +0100 Subject: [PATCH 0099/2280] Update edit.rst polishing --- docs/plugins/edit.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 68ec7a056..771d600fd 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -1,11 +1,11 @@ -editPlugin +Edit Plugin ============ The ``edit`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. Add the ``edit`` plugin to your ``plugins:`` in your ``config.yaml``. Then you simply put in a query like you normally do. :: - beet yamleditor beatles + beet yamleditor beatles beet yamleditor beatles -a beet yamleditor beatles -f '$title $lyrics' @@ -82,6 +82,7 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` -02-The Night Before-The Beatles-Help! + but you can pick anything else. With "<>" it will look like: :: From 1f3a42faf0a2e5435e37e61f42568823b937cd01 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 14:57:07 +0100 Subject: [PATCH 0100/2280] Update edit.py --- beetsplug/edit.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 00de0f444..8fc57e087 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -275,8 +275,6 @@ class EditPlugin(plugins.BeetsPlugin): if self.diff_method: ostr = self.print_items[self.style](oldset) nwstr = self.print_items[self.style](newset) - pprint.pprint(self.diff_method) - pprint.pprint(type(self.diff_method)) self.diffresults[self.diff_method](ostr, nwstr) else: for obj in changedob: @@ -330,7 +328,6 @@ class EditPlugin(plugins.BeetsPlugin): newlines = newfilestr.splitlines() oldlines = oldfilestr.splitlines() diff = difflib.HtmlDiff() - pprint.pprint("here in html") df = diff.make_file(newlines, oldlines) ht = NamedTemporaryFile('w', suffix='.html', delete=False) ht.write(df) From 8b23c893187f2d2734791d747c57c9db6d9a1f38 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 15:03:14 +0100 Subject: [PATCH 0101/2280] Update edit.rst polishing --- docs/plugins/edit.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 771d600fd..125f7ce0b 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -78,6 +78,7 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` Don't want to mess with them. * The default ``separator:`` prints like: + :: -02-The Night Before-The Beatles-Help! From 67a46b6e080ee4347a2ab4c5adc52a48a433932b Mon Sep 17 00:00:00 2001 From: jmwatte Date: Tue, 3 Nov 2015 15:13:01 +0100 Subject: [PATCH 0102/2280] Update changelog.rst change name from yamleditor to edit --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8182bdd69..9282b099c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,8 +3,8 @@ Changelog 1.3.16 (in development) ----------------------- -* A new plugin yamleditor helps you manually edit fields from items. - You search for items in the normal beets way.Then yamleditor opens a texteditor +* A new plugin edit helps you manually edit fields from items. + You search for items in the normal beets way.Then edit opens a texteditor with the items and the fields of the items you want to edit. Afterwards you can review your changes save them back into the items. From 2293e1e09d384b2e289f95efd18dc9ec364e2790 Mon Sep 17 00:00:00 2001 From: kooimens Date: Tue, 3 Nov 2015 20:03:24 +0100 Subject: [PATCH 0103/2280] Discogs: option to change 'various' album artist to 'Various Artists' (Musicbrainz naming) Just a simple config option to change 'various' album artist to the one that MusicBrainz uses: Various Artists. --- beetsplug/discogs.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 904220685..4afdcd6fe 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -57,6 +57,7 @@ class DiscogsPlugin(BeetsPlugin): 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', 'source_weight': 0.5, + 'change_va': False, }) self.config['apikey'].redact = True self.config['apisecret'].redact = True @@ -224,6 +225,8 @@ class DiscogsPlugin(BeetsPlugin): albumtype = ', '.join( result.data['formats'][0].get('descriptions', [])) or None va = result.data['artists'][0]['name'].lower() == 'various' + if va and self.config['change_va']: + artist = 'Various Artists' year = result.data['year'] label = result.data['labels'][0]['name'] mediums = len(set(t.medium for t in tracks)) From 21f926fb8928bc6a45a5c6879521095b337658d9 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 22:38:13 +0100 Subject: [PATCH 0104/2280] Add test for #314 Ensure that album art is preserved when an album is re-imported. --- test/test_importer.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/test_importer.py b/test/test_importer.py index 7b07ea331..b01a93459 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1592,6 +1592,18 @@ class ReimportTest(unittest.TestCase, ImportHelper): self.importer.run() self.assertEqual(self._item().added, 4747.0) + def test_reimported_item_preserves_art(self): + self._setup_session() + artpath = os.path.join(_common.RSRC, 'abbey.jpg') + replaced_album = self._album() + replaced_album.set_art(artpath) + replaced_album.store() + self.importer.run() + new_album = self._album() + new_artpath = new_album.art_destination(artpath) + self.assertEqual(new_album.artpath, new_artpath) + self.assertTrue(os.path.exists(new_artpath)) + class ImportPretendTest(_common.TestCase, ImportHelper): """ Test the pretend commandline option From 32934bd16a61b8b676e54a8c2699ccf936ae6e50 Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 22:43:05 +0100 Subject: [PATCH 0105/2280] Preserve album art on re-import (fixes #314) Copy the replaced album's artpath attribute to the new album. This causes the image file to be moved along with the music files. --- beets/importer.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/importer.py b/beets/importer.py index 95163b6fd..85d6e0824 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -718,6 +718,7 @@ class ImportTask(BaseImportTask): if replaced_album: self.album.added = replaced_album.added self.album.update(replaced_album._values_flex) + self.album.artpath = replaced_album.artpath self.album.store() log.debug( u'Reimported album: added {0}, flexible ' From 314dd0e6bc13870f954f80c316ac6b93436e3eab Mon Sep 17 00:00:00 2001 From: reiv Date: Tue, 3 Nov 2015 23:10:01 +0100 Subject: [PATCH 0106/2280] Update re-import test to leave no orphaned art Make sure that when an album is re-imported and its files are moved, the artwork isn't left behind in the old folder. --- test/test_importer.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index b01a93459..675ac7796 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1594,15 +1594,18 @@ class ReimportTest(unittest.TestCase, ImportHelper): def test_reimported_item_preserves_art(self): self._setup_session() - artpath = os.path.join(_common.RSRC, 'abbey.jpg') + art_source = os.path.join(_common.RSRC, 'abbey.jpg') replaced_album = self._album() - replaced_album.set_art(artpath) + replaced_album.set_art(art_source) replaced_album.store() + old_artpath = replaced_album.artpath self.importer.run() new_album = self._album() - new_artpath = new_album.art_destination(artpath) + new_artpath = new_album.art_destination(art_source) self.assertEqual(new_album.artpath, new_artpath) self.assertTrue(os.path.exists(new_artpath)) + if new_artpath != old_artpath: + self.assertFalse(os.path.exists(old_artpath)) class ImportPretendTest(_common.TestCase, ImportHelper): From 023a33ca3147a5448c3377bf818422008dee5602 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 3 Nov 2015 22:29:33 -0800 Subject: [PATCH 0107/2280] Revert "Fix #1656, maybe: encode Discogs token strings" This reverts commit f784cd1a226fa1161ee3aacb44ddd3a1475b8af9. --- beetsplug/discogs.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 904220685..80b7ae3df 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -39,8 +39,7 @@ import os urllib3_logger = logging.getLogger('requests.packages.urllib3') urllib3_logger.setLevel(logging.CRITICAL) -USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) \ - .encode('utf8') +USER_AGENT = u'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) # Exceptions that discogs_client should really handle but does not. CONNECTION_ERRORS = (ConnectionError, socket.error, httplib.HTTPException, @@ -66,8 +65,8 @@ class DiscogsPlugin(BeetsPlugin): def setup(self, session=None): """Create the `discogs_client` field. Authenticate if necessary. """ - c_key = self.config['apikey'].get(unicode).encode('utf8') - c_secret = self.config['apisecret'].get(unicode).encode('utf8') + c_key = self.config['apikey'].get(unicode) + c_secret = self.config['apisecret'].get(unicode) # Get the OAuth token from a file or log in. try: @@ -77,8 +76,8 @@ class DiscogsPlugin(BeetsPlugin): # No token yet. Generate one. token, secret = self.authenticate(c_key, c_secret) else: - token = tokendata['token'].encode('utf8') - secret = tokendata['secret'].encode('utf8') + token = tokendata['token'] + secret = tokendata['secret'] self.discogs_client = Client(USER_AGENT, c_key, c_secret, token, secret) @@ -121,7 +120,7 @@ class DiscogsPlugin(BeetsPlugin): with open(self._tokenfile(), 'w') as f: json.dump({'token': token, 'secret': secret}, f) - return token.encode('utf8'), secret.encode('utf8') + return token, secret def album_distance(self, items, album_info, mapping): """Returns the album distance. From a735a6b4a20b9d65c294834518f76e0b74b5212b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 3 Nov 2015 22:38:31 -0800 Subject: [PATCH 0108/2280] discogs: Better exception logging Might have helped diagnose #1669 more easily. --- beetsplug/discogs.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 80b7ae3df..d8568bfd1 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -150,8 +150,8 @@ class DiscogsPlugin(BeetsPlugin): return self.candidates(items, artist, album, va_likely) else: return [] - except CONNECTION_ERRORS as e: - self._log.debug(u'HTTP Connection Error: {0}', e) + except CONNECTION_ERRORS: + self._log.debug('Connection error in album search', exc_info=True) return [] def album_for_id(self, album_id): @@ -181,8 +181,8 @@ class DiscogsPlugin(BeetsPlugin): self.reset_auth() return self.album_for_id(album_id) return None - except CONNECTION_ERRORS as e: - self._log.debug(u'HTTP Connection Error: {0}', e) + except CONNECTION_ERRORS: + self._log.debug('Connection error in album lookup', exc_info=True) return None return self.get_album_info(result) @@ -203,9 +203,9 @@ class DiscogsPlugin(BeetsPlugin): try: releases = self.discogs_client.search(query, type='release').page(1) - except CONNECTION_ERRORS as exc: - self._log.debug("Communication error while searching for {0!r}: " - "{1}".format(query, exc)) + except CONNECTION_ERRORS: + self._log.debug("Communication error while searching for {0!r}", + query, exc_info=True) return [] return [self.get_album_info(release) for release in releases[:5]] From afedfbf2aa3f22fc87f3c3d9885cb6c0a63102f9 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Wed, 4 Nov 2015 09:11:46 +0100 Subject: [PATCH 0109/2280] Update index.rst added the edit plugin --- docs/plugins/index.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 0c95f366f..a4767cc22 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -40,6 +40,7 @@ Each plugin has its own set of options that can be defined in a section bearing discogs duplicates echonest + edit embedart fetchart fromfilename @@ -95,6 +96,7 @@ Metadata * :doc:`bpm`: Measure tempo using keystrokes. * :doc:`echonest`: Automatically fetch `acoustic attributes`_ from `the Echo Nest`_ (tempo, energy, danceability, ...). +* :doc:`edit`: Edit metadata from a texteditor. * :doc:`embedart`: Embed album art images into files' metadata. * :doc:`fetchart`: Fetch album cover art from various sources. * :doc:`ftintitle`: Move "featured" artists from the artist field to the title From 0ebc4c799d8f50da3c986723f8b2a9fa25f3f826 Mon Sep 17 00:00:00 2001 From: reiv Date: Wed, 4 Nov 2015 15:08:42 +0100 Subject: [PATCH 0110/2280] fetchart: in auto, ignore albums with art When re-importing an album, we don't want fetchart to interfere with any existing album art. --- beetsplug/fetchart.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b807891e0..2c20dd698 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -430,6 +430,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): def fetch_art(self, session, task): """Find art for the album being imported.""" if task.is_album: # Only fetch art for full albums. + if task.album.artpath and os.path.isfile(task.album.artpath): + # Album already has art (probably a re-import); skip it. + return if task.choice_flag == importer.action.ASIS: # For as-is imports, don't search Web sources for art. local = True From e32dda78b892289de4e4d4790144bdffe1b6b69f Mon Sep 17 00:00:00 2001 From: reiv Date: Wed, 4 Nov 2015 18:33:52 +0100 Subject: [PATCH 0111/2280] Changelog for #1681 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4eafe9c90..d71efac17 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,6 +16,10 @@ Fixes: when there were not. :bug:`1652` * :doc:`plugins/lastgenre`: Clean up the reggae related genres somewhat. Thanks to :user:`Freso`. :bug:`1661` +* The importer now correctly moves album art files when re-importing. + :bug:`314` +* :doc:`/plugins/fetchart`: In auto mode, skips albums that already have + art attached to them so as not to interfere with re-imports. :bug:`314` 1.3.15 (October 17, 2015) From be499558843450a23649a49a9508bbea0ee6fe4e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 4 Nov 2015 20:07:49 -0800 Subject: [PATCH 0112/2280] metasync: More precise exception catching (#1700) --- beetsplug/metasync/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 380c72707..fd40590bb 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -111,11 +111,13 @@ class MetaSyncPlugin(BeetsPlugin): # Instantiate the meta sources for player in sources: try: - meta_source_instances[player] = \ - META_SOURCES[player](self.config, self._log) + cls = META_SOURCES[player] except KeyError: self._log.error(u'Unknown metadata source \'{0}\''.format( player)) + + try: + meta_source_instances[player] = cls(self.config, self._log) except (ImportError, ConfigValueError) as e: self._log.error(u'Failed to instantiate metadata source ' u'\'{0}\': {1}'.format(player, e)) From 19cf37263db792f979be1bc5951be4b3651b82fa Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 4 Nov 2015 20:11:58 -0800 Subject: [PATCH 0113/2280] Fix #1700: Tolerate missing Location in iTunes --- beetsplug/metasync/itunes.py | 3 ++- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index b2795f9a4..17139f549 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -94,7 +94,8 @@ class Itunes(MetaSource): # Make the iTunes library queryable using the path self.collection = {_norm_itunes_path(track['Location']): track - for track in raw_library['Tracks'].values()} + for track in raw_library['Tracks'].values() + if 'Location' in track} def sync_from_source(self, item): result = self.collection.get(util.bytestring_path(item.path).lower()) diff --git a/docs/changelog.rst b/docs/changelog.rst index 666a76641..eb423079e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,6 +28,8 @@ Fixes: * :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` * :doc:`/plugins/embedart`: The ``remove_art_file`` option now works on import (as well as with the explicit command). :bug:`1662` :bug:`1675` +* :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of + iTunes. :bug:`1700` 1.3.15 (October 17, 2015) From 7d52fa72aef6c94fa99b10489531693312cec5f9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 4 Nov 2015 20:25:17 -0800 Subject: [PATCH 0114/2280] Fix #1699: Outdated API call get_fields() was removed in 54205998391b284801dba4cd1d595a591f23282a. --- beetsplug/duplicates.py | 2 +- docs/changelog.rst | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 991fec935..a8ad4ac90 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -271,7 +271,7 @@ class DuplicatesPlugin(BeetsPlugin): Return same number of items, with the head item modified. """ - fields = [f for sublist in Item.get_fields() for f in sublist] + fields = Item.all_keys() for f in fields: for o in objs[1:]: if getattr(objs[0], f, None) in (None, ''): diff --git a/docs/changelog.rst b/docs/changelog.rst index eb423079e..ac4202561 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -30,6 +30,7 @@ Fixes: (as well as with the explicit command). :bug:`1662` :bug:`1675` * :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of iTunes. :bug:`1700` +* :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` 1.3.15 (October 17, 2015) From da0360bd902f9418f27adfeb8dbb032f9626643a Mon Sep 17 00:00:00 2001 From: kooimens Date: Thu, 5 Nov 2015 14:50:40 +0100 Subject: [PATCH 0115/2280] Update discogs.py --- beetsplug/discogs.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 4afdcd6fe..8d0f12e44 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -57,7 +57,7 @@ class DiscogsPlugin(BeetsPlugin): 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', 'source_weight': 0.5, - 'change_va': False, + 'va_name': 'Various Artists', }) self.config['apikey'].redact = True self.config['apisecret'].redact = True @@ -225,8 +225,8 @@ class DiscogsPlugin(BeetsPlugin): albumtype = ', '.join( result.data['formats'][0].get('descriptions', [])) or None va = result.data['artists'][0]['name'].lower() == 'various' - if va and self.config['change_va']: - artist = 'Various Artists' + if va: + artist = self.config['va_name'].get() year = result.data['year'] label = result.data['labels'][0]['name'] mediums = len(set(t.medium for t in tracks)) From 1708939f99c6706a7854ff45f83e6054ba0eba04 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Fri, 22 May 2015 04:19:50 +0200 Subject: [PATCH 0116/2280] - Added hooks to manipulate fetched album and track info - Integrated support for plugins - Added documentation - Updated changelog --- beets/autotag/hooks.py | 28 ++++++++++++++++++++++++---- docs/changelog.rst | 4 ++++ docs/dev/plugins.rst | 16 ++++++++++++++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 5c4ce082e..abb474dcd 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -511,7 +511,10 @@ def album_for_mbid(release_id): if the ID is not found. """ try: - return mb.album_for_id(release_id) + album = mb.album_for_id(release_id) + if album: + plugins.send('albuminfo_received', info=album) + return album except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -521,7 +524,10 @@ def track_for_mbid(recording_id): if the ID is not found. """ try: - return mb.track_for_id(recording_id) + track = mb.track_for_id(recording_id) + if track: + plugins.send('trackinfo_received', info=track) + return track except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -529,14 +535,20 @@ def track_for_mbid(recording_id): def albums_for_id(album_id): """Get a list of albums for an ID.""" candidates = [album_for_mbid(album_id)] - candidates.extend(plugins.album_for_id(album_id)) + plugin_albums = plugins.album_for_id(album_id) + for a in plugin_albums: + plugins.send('trackinfo_received', info=a) + candidates.extend(plugin_albums) return filter(None, candidates) def tracks_for_id(track_id): """Get a list of tracks for an ID.""" candidates = [track_for_mbid(track_id)] - candidates.extend(plugins.track_for_id(track_id)) + plugin_tracks = plugins.track_for_id(track_id) + for t in plugin_tracks: + plugins.send('trackinfo_received', info=t) + candidates.extend(plugin_tracks) return filter(None, candidates) @@ -566,6 +578,10 @@ def album_candidates(items, artist, album, va_likely): # Candidates from plugins. out.extend(plugins.candidates(items, artist, album, va_likely)) + # Notify subscribed plugins about fetched album info + for a in out: + plugins.send('albuminfo_received', info=a) + return out @@ -586,4 +602,8 @@ def item_candidates(item, artist, title): # Plugin candidates. out.extend(plugins.item_candidates(item, artist, title)) + # Notify subscribed plugins about fetched album info + for i in out: + plugins.send('trackinfo_received', info=i) + return out diff --git a/docs/changelog.rst b/docs/changelog.rst index ac4202561..1b270ce4d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -125,6 +125,10 @@ The new features: :bug:`1104` :bug:`1493` * :doc:`/plugins/plexupdate`: A new ``token`` configuration option lets you specify a key for Plex Home setups. Thanks to :user:`edcarroll`. :bug:`1494` +* :doc:`/dev/plugins`: New hooks ``albuminfo_received`` and + ``trackinfo_received`` have been added for developers who would like to + intercept fetched meta data, before they are applied in tag manipulation + operations. :bug:`872` Fixes: diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 798b6894c..59936725e 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -214,6 +214,22 @@ The events currently available are: * *import_begin*: called just before a ``beet import`` session starts up. Parameter: ``session``. +* *trackinfo_received*: called after meta data for a track item has been fetched + from disparate sources, such as MusicBrainz. Gives a developer the option to + intercept the fetched TrackInfo object. Can be used to modify tags on a ``beet + import`` operation or during later adjustments, such as ``mbsync``. Can be + slow, as event is fired for any fetched possible match *before* user or + autotagger selection was made. + Parameter: ``info``. + +* *albuminfo_received*: called after meta data for an album item has been + fetched from disparate sources, such as MusicBrainz. Gives a developer the + option to intercept the fetched AlbumInfo object. Can be used to modify tags + on a ``beet import`` operation or during later adjustments, such as + ``mbsync``. Can be slow, as event is fired for any fetched possible match + *before* user or autotagger selection was made. + Parameter: ``info``. + The included ``mpdupdate`` plugin provides an example use case for event listeners. Extend the Autotagger From 17a32e33c5a8cfe9d908682eaa7cead007382a45 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Thu, 5 Nov 2015 15:30:01 +0100 Subject: [PATCH 0117/2280] added grouping of fields and "$BROWSER" and "$EDITOR" --- beetsplug/edit.py | 186 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 137 insertions(+), 49 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 8fc57e087..aa8ede708 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -1,5 +1,5 @@ # This file is part of beets. -# Copyright 2015 jean-marie winters +# Copyright 2015 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -28,6 +28,7 @@ from sys import exit from beets import config from beets import ui from tempfile import NamedTemporaryFile +import os class EditPlugin(plugins.BeetsPlugin): @@ -42,8 +43,8 @@ class EditPlugin(plugins.BeetsPlugin): 'browser': '', 'albumfields': 'album albumartist', 'itemfields': 'track title artist album ', - 'not_fields': 'path', - 'separator': '-' + 'not_fields': 'id path', + 'sep': '-' }) self.style = self.config['style'].get(unicode) @@ -77,7 +78,7 @@ class EditPlugin(plugins.BeetsPlugin): self.not_fields = self.config['not_fields'].as_str_seq() '''the separator in your config sets the separator that will be used between fields in your terminal. Defaults to -''' - self.separator = self.config['separator'].get(unicode) + self.sep = self.config['sep'].get(unicode) self.ed = None self.ed_args = None self.brw = None @@ -97,6 +98,11 @@ class EditPlugin(plugins.BeetsPlugin): action='store_true', dest='all', help='add all fields to edit', ) + edit_command.parser.add_option( + '--sum', + action='store_true', dest='sum', + help='groups fields with the same value', + ) edit_command.parser.add_all_common_options() edit_command.func = self.editor_music return[edit_command] @@ -142,7 +148,7 @@ class EditPlugin(plugins.BeetsPlugin): return dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) newyaml, oldyaml = self.change_objs(dict_from_objs) - changed_objs = self.check_diff(newyaml, oldyaml) + changed_objs = self.check_diff(newyaml, oldyaml, opts) if not changed_objs: print_("nothing to change") return @@ -168,7 +174,7 @@ class EditPlugin(plugins.BeetsPlugin): def get_fields_from(self, objs, opts): # construct a list of fields we need - cl = ui.colorize('action', self.separator) + cl = ui.colorize('action', self.sep) # see if we need album or item fields self.fields = self.albumfields if opts.album else self.itemfields # if opts.format is given only use those fields @@ -215,15 +221,37 @@ class EditPlugin(plugins.BeetsPlugin): def get_selected_fields(self, myfields, objs, opts): a = [] - for mod in objs: - a.append([{fi: mod[fi]}for fi in myfields]) - return a + if opts.sum: + for field in myfields: + if field not in self.not_fields: + d = collections.defaultdict(str) + for obj in objs: + d[obj[field]] += (" " + str(obj['id'])) + a.append([field, [{f: i} for f, i in d.items()]]) + return a + else: + for mod in objs: + a.append([{fi: mod[fi]}for fi in myfields]) + return a def get_all_fields(self, myfields, objs, opts): a = [] - for mod in objs: - a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) - return a + if opts.sum: + fields = (library.Album.all_keys() if opts.album + else library.Item.all_keys()) + for field in sorted(fields): + # for every field get a dict + d = collections.defaultdict(str) + for obj in objs: + # put all the ob-ids in the dict[field] as a string + d[obj[field]] += (" " + str(obj['id'])) + # for the field, we get the value and the users + a.append([field, [{f: i} for f, i in sorted(d.items())]]) + return a + else: + for mod in objs: + a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) + return a def change_objs(self, dict_items): # construct a yaml from the original object-fields @@ -233,48 +261,82 @@ class EditPlugin(plugins.BeetsPlugin): new = NamedTemporaryFile(suffix='.yaml', delete=False) new.write(newyaml) new.close() - if not self.ed: - webbrowser.open(new.name, new=2, autoraise=True) - else: - callmethod = [self.ed] - if self.ed_args: - callmethod.extend(self.ed_args) - callmethod.append(new.name) - subprocess.check_call(callmethod) + self.get_editor(new.name) if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): - with open(new.name) as f: - newyaml = f.read() + while True: + try: + with open(new.name) as f: + newyaml = f.read() + list(yaml.load_all(newyaml)) + break + except yaml.YAMLError as e: + print_(ui.colorize('text_warning', + "change this fault: {}".format(e))) + print_("correct format for empty = - '' :") + if ui.input_yn( + ui.colorize('action_default', "fix?(y)"), True): + self.get_editor(new.name) + if ui.input_yn(ui.colorize( + 'action_default', "ok.fixed.(y)"), True): + pass + return newyaml, oldyaml else: exit() - def save_items(self, oldnewlist, lib, fmt, opts): - oldset = [] - newset = [] - for old, new in oldnewlist: - oldset.append(old) - newset.append(new) - - no = [] - for newitem in range(0, len(newset)): - ordict = collections.OrderedDict() - for each in newset[newitem]: - ordict.update(each) - no.append(ordict) - - changedob = [] - for each in no: - if not opts.album: - ob = lib.get_item(each['id']) + def get_editor(self, name): + if not self.ed: + editor = os.getenv('EDITOR') + if editor: + os.system(editor + " " + name) else: - ob = lib.get_album(each['id']) - ob.update(each) - changedob.append(ob) + webbrowser.open(name, new=2, autoraise=True) + else: + callmethod = [self.ed] + if self.ed_args: + callmethod.extend(self.ed_args) + callmethod.append(name) + subprocess.check_call(callmethod) + def same_format(self, newset, opts): + alld = collections.defaultdict(dict) + if opts.sum: + for o in newset: + for so in o: + ids = set((so[1].values()[0].split())) + for id in ids: + alld[id].update( + {so[0].items()[0][1]: so[1].items()[0][0]}) + else: + for o in newset: + for so in o: + alld[o[0].values()[0]].update(so) + return alld + + def save_items(self, oldnewlist, lib, fmt, opts): + + oldset, newset = zip(*oldnewlist) + no = self.same_format(newset, opts) + oo = self.same_format(oldset, opts) + ono = zip(oo.items(), no.items()) + nl = [] + ol = [] + changedob = [] + for o, n in ono: + if not opts.album: + ob = lib.get_item(n[0]) + else: + ob = lib.get_album(n[0]) + # change id to item-string + ol.append((format(ob),) + o[1:]) + ob.update(n[1]) + nl.append((format(ob),) + n[1:]) + changedob.append(ob) + # see the changes we made if self.diff_method: - ostr = self.print_items[self.style](oldset) - nwstr = self.print_items[self.style](newset) + ostr = self.print_items[self.style](ol) + nwstr = self.print_items[self.style](nl) self.diffresults[self.diff_method](ostr, nwstr) else: for obj in changedob: @@ -294,11 +356,33 @@ class EditPlugin(plugins.BeetsPlugin): return - def check_diff(self, newyaml, oldyaml): - # get the changed objects + def check_diff(self, newyaml, oldyaml, opts): + # make python objs from yamlstrings nl = self.string_to_dict[self.style](newyaml) ol = self.string_to_dict[self.style](oldyaml) - return filter(None, map(self.reduce_it, ol, nl)) + if opts.sum: + return filter(None, map(self.reduce_sum, ol, nl)) + else: + return filter(None, map(self.reduce_it, ol, nl)) + + def reduce_sum(self, ol, nl): + # only get the changed objs + if ol != nl: + sol = [i for i in ol[1]] + snl = [i for i in nl[1]] + a = filter(None, map(self.reduce_sub, sol, snl)) + header = {"field": ol[0]} + ol = [[header, b[0]] for b in a] + nl = [[header, b[1]] for b in a] + return ol, nl + + def reduce_sub(self, sol, snl): + # if the keys have changed resets them + if sol != snl: + if snl.values() != sol.values(): + snl[snl.keys()[0]] = sol[sol.keys()[0]] + if sol != snl: + return sol, snl def reduce_it(self, ol, nl): # if there is a forbidden field it resets them @@ -334,7 +418,11 @@ class EditPlugin(plugins.BeetsPlugin): ht.flush() hdn = ht.name if not self.brw: - webbrowser.open(hdn, new=2, autoraise=True) + browser = os.getenv('BROWSER') + if browser: + os.system(browser + " " + hdn) + else: + webbrowser.open(hdn, new=2, autoraise=True) else: callmethod = [self.brw] if self.brw_args: From ae0babb17e136a2abe9e596b5b895bf601827dd3 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Thu, 5 Nov 2015 16:17:19 +0100 Subject: [PATCH 0118/2280] Less duplicated text in documentation --- docs/dev/plugins.rst | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 59936725e..8c6e45c6d 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -222,13 +222,9 @@ The events currently available are: autotagger selection was made. Parameter: ``info``. -* *albuminfo_received*: called after meta data for an album item has been - fetched from disparate sources, such as MusicBrainz. Gives a developer the - option to intercept the fetched AlbumInfo object. Can be used to modify tags - on a ``beet import`` operation or during later adjustments, such as - ``mbsync``. Can be slow, as event is fired for any fetched possible match - *before* user or autotagger selection was made. - Parameter: ``info``. +* *albuminfo_received*: Like *trackinfo_received*, the event indicates new meta + data for album items, but supplies an *AlbumInfo* object instead of a + *TrackInfo*. The included ``mpdupdate`` plugin provides an example use case for event listeners. From 5e4c41ffe82bc0fed8cae19d25486594e82f7593 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Thu, 5 Nov 2015 16:37:35 +0100 Subject: [PATCH 0119/2280] Clarified documentation --- docs/dev/plugins.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 8c6e45c6d..f63d75aba 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -217,9 +217,9 @@ The events currently available are: * *trackinfo_received*: called after meta data for a track item has been fetched from disparate sources, such as MusicBrainz. Gives a developer the option to intercept the fetched TrackInfo object. Can be used to modify tags on a ``beet - import`` operation or during later adjustments, such as ``mbsync``. Can be - slow, as event is fired for any fetched possible match *before* user or - autotagger selection was made. + import`` operation or during later adjustments, such as ``mbsync``. Slow + handlers of the event can impact the operation, since the event is fired for + any fetched possible match *before* user or autotagger selection was made. Parameter: ``info``. * *albuminfo_received*: Like *trackinfo_received*, the event indicates new meta From 17b38a6be859f9021312159de6ddbed5a123730e Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Thu, 5 Nov 2015 16:43:28 +0100 Subject: [PATCH 0120/2280] Minor layout fixes to documentation --- docs/dev/plugins.rst | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index f63d75aba..9a59351e3 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -216,15 +216,16 @@ The events currently available are: * *trackinfo_received*: called after meta data for a track item has been fetched from disparate sources, such as MusicBrainz. Gives a developer the option to - intercept the fetched TrackInfo object. Can be used to modify tags on a ``beet - import`` operation or during later adjustments, such as ``mbsync``. Slow - handlers of the event can impact the operation, since the event is fired for - any fetched possible match *before* user or autotagger selection was made. + intercept the fetched ``TrackInfo`` object. Can be used to modify tags on a + ``beet import`` operation or during later adjustments, such as ``mbsync``. + Slow handlers of the event can impact the operation, since the event is fired + for any fetched possible match *before* user or autotagger selection was made. Parameter: ``info``. * *albuminfo_received*: Like *trackinfo_received*, the event indicates new meta - data for album items, but supplies an *AlbumInfo* object instead of a - *TrackInfo*. + data for album items, but supplies an ``AlbumInfo`` object instead of a + ``TrackInfo``. + Parameter: ``info``. The included ``mpdupdate`` plugin provides an example use case for event listeners. From f95611dde4b2610790923d2922c0c0a1c6a547f2 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Thu, 5 Nov 2015 16:51:33 +0100 Subject: [PATCH 0121/2280] fixed albumid needs to be int --- beetsplug/edit.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index aa8ede708..3166ce15d 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -101,7 +101,7 @@ class EditPlugin(plugins.BeetsPlugin): edit_command.parser.add_option( '--sum', action='store_true', dest='sum', - help='groups fields with the same value', + help='list fields with the same value', ) edit_command.parser.add_all_common_options() edit_command.func = self.editor_music @@ -324,10 +324,10 @@ class EditPlugin(plugins.BeetsPlugin): ol = [] changedob = [] for o, n in ono: - if not opts.album: - ob = lib.get_item(n[0]) + if opts.album: + ob = lib.get_album(int(n[0])) else: - ob = lib.get_album(n[0]) + ob = lib.get_item(n[0]) # change id to item-string ol.append((format(ob),) + o[1:]) ob.update(n[1]) From 33d3ebf53ff2134f02f20045e5c211df272f064b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 5 Nov 2015 18:31:16 -0800 Subject: [PATCH 0122/2280] Link to a 3rd-party plugin: beets-usertag (#1694) --- docs/plugins/index.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 0c95f366f..529a74da5 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -215,6 +215,8 @@ Here are a few of the plugins written by the beets community: * `whatlastgenre`_ fetches genres from various music sites. +* `beets-usertag`_ lets you use keywords to tag and organize your music. + .. _beets-check: https://github.com/geigerzaehler/beets-check .. _copyartifacts: https://github.com/sbarakat/beets-copyartifacts .. _dsedivec: https://github.com/dsedivec/beets-plugins @@ -231,3 +233,4 @@ Here are a few of the plugins written by the beets community: .. _beets-setlister: https://github.com/tomjaspers/beets-setlister .. _beets-noimport: https://github.com/ttsda/beets-noimport .. _whatlastgenre: https://github.com/YetAnotherNerd/whatlastgenre/tree/master/plugin/beets +.. _beets-usertag: https://github.com/igordertigor/beets-usertag From d84c776dc18ccbdd8e21028edf8a697360aa29ed Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Fri, 6 Nov 2015 13:44:38 +0100 Subject: [PATCH 0123/2280] list options in alphabetic order --- docs/plugins/duplicates.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/duplicates.rst b/docs/plugins/duplicates.rst index a0369a95e..4d8b35376 100644 --- a/docs/plugins/duplicates.rst +++ b/docs/plugins/duplicates.rst @@ -67,9 +67,6 @@ file. The available options mirror the command-line options: - **full**: List every track or album that has duplicates, not just the duplicates themselves. Default: ``no`` -- **strict**: Do not report duplicate matches if some of the - attributes are not defined (ie. null or empty). - Default: ``no`` - **keys**: Define in which track or album fields duplicates are to be searched. By default, the plugin uses the musicbrainz track and album IDs for this purpose. Using the ``keys`` option (as a YAML list in the configuration @@ -83,6 +80,9 @@ file. The available options mirror the command-line options: Default: none (disabled). - **path**: Output the path instead of metadata when listing duplicates. Default: ``no``. +- **strict**: Do not report duplicate matches if some of the + attributes are not defined (ie. null or empty). + Default: ``no`` - **tag**: A ``key=value`` pair. The plugin will add a new ``key`` attribute with ``value`` value as a flexattr to the database for duplicate items. Default: ``no``. From 414ae131a5c0c1656abcdf1af20a84edac633888 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 6 Nov 2015 19:27:36 +0100 Subject: [PATCH 0124/2280] Fix style error --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 8d0f12e44..78a5ee4aa 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -226,7 +226,7 @@ class DiscogsPlugin(BeetsPlugin): result.data['formats'][0].get('descriptions', [])) or None va = result.data['artists'][0]['name'].lower() == 'various' if va: - artist = self.config['va_name'].get() + artist = self.config['va_name'].get() year = result.data['year'] label = result.data['labels'][0]['name'] mediums = len(set(t.medium for t in tracks)) From b11533b98f69349dfeeb23d7294cff031aed44a7 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 6 Nov 2015 19:45:05 +0100 Subject: [PATCH 0125/2280] Update discogs docs --- docs/plugins/discogs.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index 038718f9b..2961bb3bb 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -25,6 +25,14 @@ MusicBrainz. If you have a Discogs ID for an album you want to tag, you can also enter it at the "enter Id" prompt in the importer. +Configuration +------------- +To configure the plugin, make a ``discogs:`` section in your configuration +file. The available options are: + +- **va_name**: Change the name of the albumartist if an album is V.A. + Default: ``'Various Artists'`` (Same as MusicBrainz). + Troubleshooting --------------- From c20479515373fbd0f899be635b88c5ce84568479 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 6 Nov 2015 19:56:19 +0100 Subject: [PATCH 0126/2280] Update changelog --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 7c5b91217..a522b4ce3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ Fixes: * :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` * :doc:`/plugins/embedart`: The ``remove_art_file`` option now works on import (as well as with the explicit command). :bug:`1662` :bug:`1675` +* :doc:`/plugins/discogs`: New config option to change the default album + artist name if album is V.A. The default is changed to 'Various Artists' to + be the same as for MusicBrainz. 1.3.15 (October 17, 2015) From 7d02d7da29c6ea27234860a2490e1c1635a76817 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 6 Nov 2015 20:00:36 +0100 Subject: [PATCH 0127/2280] Update changelog.rst --- docs/changelog.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index a522b4ce3..1257c9132 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,9 +24,9 @@ Fixes: * :doc:`/plugins/thumbnails`: Fix a crash with Unicode paths. :bug:`1686` * :doc:`/plugins/embedart`: The ``remove_art_file`` option now works on import (as well as with the explicit command). :bug:`1662` :bug:`1675` -* :doc:`/plugins/discogs`: New config option to change the default album - artist name if album is V.A. The default is changed to 'Various Artists' to - be the same as for MusicBrainz. +* :doc:`/plugins/discogs`: New config option (va_name) to change the default + album artist name if album is V.A. The default is changed to 'Various Artists' + to be the same as for MusicBrainz. 1.3.15 (October 17, 2015) From 1150f65ee3752c73e6ccbda4f2b1465c413ed9b5 Mon Sep 17 00:00:00 2001 From: kooimens Date: Fri, 6 Nov 2015 20:01:56 +0100 Subject: [PATCH 0128/2280] Update changelog.rst --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1257c9132..84b79b723 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -26,7 +26,7 @@ Fixes: (as well as with the explicit command). :bug:`1662` :bug:`1675` * :doc:`/plugins/discogs`: New config option (va_name) to change the default album artist name if album is V.A. The default is changed to 'Various Artists' - to be the same as for MusicBrainz. + to be the same as MusicBrainz. 1.3.15 (October 17, 2015) From 1f6a26d2b4aae907eb78d9a44e6abd9bd8f3e421 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 6 Nov 2015 13:04:06 -0800 Subject: [PATCH 0129/2280] Spruce up the docs for #1692 --- docs/changelog.rst | 6 +++--- docs/plugins/discogs.rst | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index c85644062..c04f246ff 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,9 +31,9 @@ Fixes: * :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of iTunes. :bug:`1700` * :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` -* :doc:`/plugins/discogs`: New config option (va_name) to change the default - album artist name if album is V.A. The default is changed to 'Various Artists' - to be the same as MusicBrainz. +* :doc:`/plugins/discogs`: A new option, ``va_name``, controls the album + artist name for various-artists albums. The default is now "Various + Artists," to match MusicBrainz. 1.3.15 (October 17, 2015) diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index 2961bb3bb..a7983e7e0 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -27,11 +27,13 @@ at the "enter Id" prompt in the importer. Configuration ------------- + To configure the plugin, make a ``discogs:`` section in your configuration file. The available options are: -- **va_name**: Change the name of the albumartist if an album is V.A. - Default: ``'Various Artists'`` (Same as MusicBrainz). +- **va_name**: The albumartist name to use when an album is marked as being by + "various" artists. + Default: "Various Artists" (matching the MusicBrainz convention). Troubleshooting --------------- From e9ddb92c2d601276557d1a1d7b2ea74d1426ee87 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Thu, 5 Nov 2015 17:09:33 +0100 Subject: [PATCH 0130/2280] - Simplified code - Fixed wrong event being emitted --- beets/autotag/hooks.py | 30 +++++++----------------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index abb474dcd..d53961a6c 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -511,10 +511,7 @@ def album_for_mbid(release_id): if the ID is not found. """ try: - album = mb.album_for_id(release_id) - if album: - plugins.send('albuminfo_received', info=album) - return album + return mb.album_for_id(release_id) except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -524,10 +521,7 @@ def track_for_mbid(recording_id): if the ID is not found. """ try: - track = mb.track_for_id(recording_id) - if track: - plugins.send('trackinfo_received', info=track) - return track + return mb.track_for_id(recording_id) except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -535,20 +529,18 @@ def track_for_mbid(recording_id): def albums_for_id(album_id): """Get a list of albums for an ID.""" candidates = [album_for_mbid(album_id)] - plugin_albums = plugins.album_for_id(album_id) - for a in plugin_albums: - plugins.send('trackinfo_received', info=a) - candidates.extend(plugin_albums) + candidates.extend(plugins.album_for_id(album_id)) + for a in candidates: + plugins.send('albuminfo_received', info=a) return filter(None, candidates) def tracks_for_id(track_id): """Get a list of tracks for an ID.""" candidates = [track_for_mbid(track_id)] - plugin_tracks = plugins.track_for_id(track_id) - for t in plugin_tracks: + candidates.extend(plugins.track_for_id(track_id)) + for t in candidates: plugins.send('trackinfo_received', info=t) - candidates.extend(plugin_tracks) return filter(None, candidates) @@ -578,10 +570,6 @@ def album_candidates(items, artist, album, va_likely): # Candidates from plugins. out.extend(plugins.candidates(items, artist, album, va_likely)) - # Notify subscribed plugins about fetched album info - for a in out: - plugins.send('albuminfo_received', info=a) - return out @@ -602,8 +590,4 @@ def item_candidates(item, artist, title): # Plugin candidates. out.extend(plugins.item_candidates(item, artist, title)) - # Notify subscribed plugins about fetched album info - for i in out: - plugins.send('trackinfo_received', info=i) - return out From b2efd60162eb81f025c015df2160b4099dc957ad Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sat, 7 Nov 2015 17:51:44 +0100 Subject: [PATCH 0131/2280] Needed to find new spot to emit events because hooks.*_for_id -methods are only called when searching for explicit IDs --- beets/autotag/hooks.py | 4 ---- beets/autotag/match.py | 12 ++++++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index d53961a6c..5c4ce082e 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -530,8 +530,6 @@ def albums_for_id(album_id): """Get a list of albums for an ID.""" candidates = [album_for_mbid(album_id)] candidates.extend(plugins.album_for_id(album_id)) - for a in candidates: - plugins.send('albuminfo_received', info=a) return filter(None, candidates) @@ -539,8 +537,6 @@ def tracks_for_id(track_id): """Get a list of tracks for an ID.""" candidates = [track_for_mbid(track_id)] candidates.extend(plugins.track_for_id(track_id)) - for t in candidates: - plugins.send('trackinfo_received', info=t) return filter(None, candidates) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index c747f47c2..bd15368d2 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -350,6 +350,10 @@ def _add_candidate(items, results, info): log.debug(u'Ignored. Missing required tag: {0}', req_tag) return + # Notify subscribed plugins about fetched album info and let them perform + # their manipulations + plugins.send('albuminfo_received', info=info) + # Find mapping between the items and the track info. mapping, extra_items, extra_tracks = assign_items(items, info.tracks) @@ -459,6 +463,10 @@ def tag_item(item, search_artist=None, search_title=None, if trackid: log.debug(u'Searching for track ID: {0}', trackid) for track_info in hooks.tracks_for_id(trackid): + # Notify subscribed plugins about fetched track info and let them perform + # their manipulations + plugins.send('trackinfo_received', info=track_info) + dist = track_distance(item, track_info, incl_artist=True) candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) @@ -482,6 +490,10 @@ def tag_item(item, search_artist=None, search_title=None, # Get and evaluate candidate metadata. for track_info in hooks.item_candidates(item, search_artist, search_title): + # Notify subscribed plugins about fetched track info and let them perform + # their manipulations + plugins.send('trackinfo_received', info=track_info) + dist = track_distance(item, track_info, incl_artist=True) candidates[track_info.track_id] = hooks.TrackMatch(dist, track_info) From d8851b97b8a039dc4974974583652131a1e77d74 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sat, 7 Nov 2015 17:59:25 +0100 Subject: [PATCH 0132/2280] Fixed Travis errors --- beets/autotag/match.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index bd15368d2..a892d48cc 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -463,8 +463,8 @@ def tag_item(item, search_artist=None, search_title=None, if trackid: log.debug(u'Searching for track ID: {0}', trackid) for track_info in hooks.tracks_for_id(trackid): - # Notify subscribed plugins about fetched track info and let them perform - # their manipulations + # Notify subscribed plugins about fetched track info and let them + # perform their manipulations plugins.send('trackinfo_received', info=track_info) dist = track_distance(item, track_info, incl_artist=True) @@ -490,8 +490,8 @@ def tag_item(item, search_artist=None, search_title=None, # Get and evaluate candidate metadata. for track_info in hooks.item_candidates(item, search_artist, search_title): - # Notify subscribed plugins about fetched track info and let them perform - # their manipulations + # Notify subscribed plugins about fetched track info and let them + # perform their manipulations plugins.send('trackinfo_received', info=track_info) dist = track_distance(item, track_info, incl_artist=True) From 6e980a977ec03dc46fb5fb9036666d9677ecf22e Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sat, 7 Nov 2015 19:02:08 +0100 Subject: [PATCH 0133/2280] Reverted to original approach --- beets/autotag/hooks.py | 28 ++++++++++++++++++++++++---- beets/autotag/match.py | 12 ------------ 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 5c4ce082e..b2b635ad2 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -511,7 +511,10 @@ def album_for_mbid(release_id): if the ID is not found. """ try: - return mb.album_for_id(release_id) + album = mb.album_for_id(release_id) + if album: + plugins.send('albuminfo_received', info=album) + return album except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -521,7 +524,10 @@ def track_for_mbid(recording_id): if the ID is not found. """ try: - return mb.track_for_id(recording_id) + track = mb.track_for_id(recording_id) + if track: + plugins.send('trackinfo_received', info=track) + return track except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -529,14 +535,20 @@ def track_for_mbid(recording_id): def albums_for_id(album_id): """Get a list of albums for an ID.""" candidates = [album_for_mbid(album_id)] - candidates.extend(plugins.album_for_id(album_id)) + plugin_albums = plugins.album_for_id(album_id) + for a in plugin_albums: + plugins.send('albuminfo_received', info=a) + candidates.extend(plugin_albums) return filter(None, candidates) def tracks_for_id(track_id): """Get a list of tracks for an ID.""" candidates = [track_for_mbid(track_id)] - candidates.extend(plugins.track_for_id(track_id)) + plugin_tracks = plugins.track_for_id(track_id) + for t in plugin_tracks: + plugins.send('trackinfo_received', info=t) + candidates.extend(plugin_tracks) return filter(None, candidates) @@ -566,6 +578,10 @@ def album_candidates(items, artist, album, va_likely): # Candidates from plugins. out.extend(plugins.candidates(items, artist, album, va_likely)) + # Notify subscribed plugins about fetched album info + for a in out: + plugins.send('albuminfo_received', info=a) + return out @@ -586,4 +602,8 @@ def item_candidates(item, artist, title): # Plugin candidates. out.extend(plugins.item_candidates(item, artist, title)) + # Notify subscribed plugins about fetched track info + for i in out: + plugins.send('trackinfo_received', info=i) + return out diff --git a/beets/autotag/match.py b/beets/autotag/match.py index a892d48cc..c747f47c2 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -350,10 +350,6 @@ def _add_candidate(items, results, info): log.debug(u'Ignored. Missing required tag: {0}', req_tag) return - # Notify subscribed plugins about fetched album info and let them perform - # their manipulations - plugins.send('albuminfo_received', info=info) - # Find mapping between the items and the track info. mapping, extra_items, extra_tracks = assign_items(items, info.tracks) @@ -463,10 +459,6 @@ def tag_item(item, search_artist=None, search_title=None, if trackid: log.debug(u'Searching for track ID: {0}', trackid) for track_info in hooks.tracks_for_id(trackid): - # Notify subscribed plugins about fetched track info and let them - # perform their manipulations - plugins.send('trackinfo_received', info=track_info) - dist = track_distance(item, track_info, incl_artist=True) candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) @@ -490,10 +482,6 @@ def tag_item(item, search_artist=None, search_title=None, # Get and evaluate candidate metadata. for track_info in hooks.item_candidates(item, search_artist, search_title): - # Notify subscribed plugins about fetched track info and let them - # perform their manipulations - plugins.send('trackinfo_received', info=track_info) - dist = track_distance(item, track_info, incl_artist=True) candidates[track_info.track_id] = hooks.TrackMatch(dist, track_info) From 4baf9eba564f89ce24904b64a71df3543eda1d02 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:07:17 -0800 Subject: [PATCH 0134/2280] Move changelog entry for #1499 --- docs/changelog.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 944307246..fce5d6552 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,13 @@ Changelog 1.3.16 (in development) ----------------------- +For developers: + +* :doc:`/dev/plugins`: New hooks ``albuminfo_received`` and + ``trackinfo_received`` have been added for developers who would like to + intercept fetched meta data, before they are applied in tag manipulation + operations. :bug:`872` + Fixes: * :doc:`/plugins/plexupdate`: Fix a crash when Plex libraries use non-ASCII @@ -128,10 +135,6 @@ The new features: :bug:`1104` :bug:`1493` * :doc:`/plugins/plexupdate`: A new ``token`` configuration option lets you specify a key for Plex Home setups. Thanks to :user:`edcarroll`. :bug:`1494` -* :doc:`/dev/plugins`: New hooks ``albuminfo_received`` and - ``trackinfo_received`` have been added for developers who would like to - intercept fetched meta data, before they are applied in tag manipulation - operations. :bug:`872` Fixes: From 4e20ddcef9971b984b00d79e6c719e12515fb537 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:11:05 -0800 Subject: [PATCH 0135/2280] Doc refinements for #1499 --- docs/changelog.rst | 7 +++---- docs/dev/plugins.rst | 18 +++++++++--------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index fce5d6552..5864d5c38 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,10 +6,9 @@ Changelog For developers: -* :doc:`/dev/plugins`: New hooks ``albuminfo_received`` and - ``trackinfo_received`` have been added for developers who would like to - intercept fetched meta data, before they are applied in tag manipulation - operations. :bug:`872` +* :doc:`/dev/plugins`: Two new hooks, ``albuminfo_received`` and + ``trackinfo_received``, let plugins intercept metadata as soon as it is + received, before it is applied to music in the database. :bug:`872` Fixes: diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 9a59351e3..bf5f3d4a9 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -214,17 +214,17 @@ The events currently available are: * *import_begin*: called just before a ``beet import`` session starts up. Parameter: ``session``. -* *trackinfo_received*: called after meta data for a track item has been fetched - from disparate sources, such as MusicBrainz. Gives a developer the option to - intercept the fetched ``TrackInfo`` object. Can be used to modify tags on a - ``beet import`` operation or during later adjustments, such as ``mbsync``. - Slow handlers of the event can impact the operation, since the event is fired - for any fetched possible match *before* user or autotagger selection was made. +* *trackinfo_received*: called after metadata for a track item has been + fetched from a data source, such as MusicBrainz. You can modify the tags + that the rest of the pipeline sees on a ``beet import`` operation or during + later adjustments, such as ``mbsync``. Slow handlers of the event can impact + the operation, since the event is fired for any fetched possible match + *before* the user (or the autotagger machinery) gets to see the match. Parameter: ``info``. -* *albuminfo_received*: Like *trackinfo_received*, the event indicates new meta - data for album items, but supplies an ``AlbumInfo`` object instead of a - ``TrackInfo``. +* *albuminfo_received*: like *trackinfo_received*, the event indicates new + metadata for album items. The parameter is an ``AlbumInfo`` object instead + of a ``TrackInfo``. Parameter: ``info``. The included ``mpdupdate`` plugin provides an example use case for event listeners. From cb6edb46efe8380990fe0ff6718204ad66ad3f5d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:12:48 -0800 Subject: [PATCH 0136/2280] Use ` instead of * for plugin event names --- docs/dev/plugins.rst | 46 ++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index bf5f3d4a9..885ef2222 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -133,39 +133,39 @@ registration process in this case:: The events currently available are: -* *pluginload*: called after all the plugins have been loaded after the ``beet`` +* `pluginload`: called after all the plugins have been loaded after the ``beet`` command starts -* *import*: called after a ``beet import`` command finishes (the ``lib`` keyword +* `import`: called after a ``beet import`` command finishes (the ``lib`` keyword argument is a Library object; ``paths`` is a list of paths (strings) that were imported) -* *album_imported*: called with an ``Album`` object every time the ``import`` +* `album_imported`: called with an ``Album`` object every time the ``import`` command finishes adding an album to the library. Parameters: ``lib``, ``album`` -* *item_copied*: called with an ``Item`` object whenever its file is copied. +* `item_copied`: called with an ``Item`` object whenever its file is copied. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_imported*: called with an ``Item`` object every time the importer adds a +* `item_imported`: called with an ``Item`` object every time the importer adds a singleton to the library (not called for full-album imports). Parameters: ``lib``, ``item`` -* *before_item_moved*: called with an ``Item`` object immediately before its +* `before_item_moved`: called with an ``Item`` object immediately before its file is moved. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_moved*: called with an ``Item`` object whenever its file is moved. +* `item_moved`: called with an ``Item`` object whenever its file is moved. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_linked*: called with an ``Item`` object whenever a symlink is created +* `item_linked`: called with an ``Item`` object whenever a symlink is created for a file. Parameters: ``item``, ``source`` path, ``destination`` path -* *item_removed*: called with an ``Item`` object every time an item (singleton +* `item_removed`: called with an ``Item`` object every time an item (singleton or album's part) is removed from the library (even when its file is not deleted from disk). -* *write*: called with an ``Item`` object, a ``path``, and a ``tags`` +* `write`: called with an ``Item`` object, a ``path``, and a ``tags`` dictionary just before a file's metadata is written to disk (i.e., just before the file on disk is opened). Event handlers may change the ``tags`` dictionary to customize the tags that are written to the @@ -174,55 +174,55 @@ The events currently available are: operation. Beets will catch that exception, print an error message and continue. -* *after_write*: called with an ``Item`` object after a file's metadata is +* `after_write`: called with an ``Item`` object after a file's metadata is written to disk (i.e., just after the file on disk is closed). -* *import_task_created*: called immediately after an import task is +* `import_task_created`: called immediately after an import task is initialized. Plugins can use this to, for example, change imported files of a task before anything else happens. It's also possible to replace the task with another task by returning a list of tasks. This list can contain zero or more `ImportTask`s. Returning an empty list will stop the task. Parameters: ``task`` (an `ImportTask`) and ``session`` (an `ImportSession`). -* *import_task_start*: called when before an import task begins processing. +* `import_task_start`: called when before an import task begins processing. Parameters: ``task`` and ``session``. -* *import_task_apply*: called after metadata changes have been applied in an +* `import_task_apply`: called after metadata changes have been applied in an import task. This is called on the same thread as the UI, so use this sparingly and only for tasks that can be done quickly. For most plugins, an import pipeline stage is a better choice (see :ref:`plugin-stage`). Parameters: ``task`` and ``session``. -* *import_task_choice*: called after a decision has been made about an import +* `import_task_choice`: called after a decision has been made about an import task. This event can be used to initiate further interaction with the user. Use ``task.choice_flag`` to determine or change the action to be taken. Parameters: ``task`` and ``session``. -* *import_task_files*: called after an import task finishes manipulating the +* `import_task_files`: called after an import task finishes manipulating the filesystem (copying and moving files, writing metadata tags). Parameters: ``task`` and ``session``. -* *library_opened*: called after beets starts up and initializes the main +* `library_opened`: called after beets starts up and initializes the main Library object. Parameter: ``lib``. -* *database_change*: a modification has been made to the library database. The +* `database_change`: a modification has been made to the library database. The change might not be committed yet. Parameters: ``lib`` and ``model``. -* *cli_exit*: called just before the ``beet`` command-line program exits. +* `cli_exit`: called just before the ``beet`` command-line program exits. Parameter: ``lib``. -* *import_begin*: called just before a ``beet import`` session starts up. +* `import_begin`: called just before a ``beet import`` session starts up. Parameter: ``session``. -* *trackinfo_received*: called after metadata for a track item has been +* `trackinfo_received`: called after metadata for a track item has been fetched from a data source, such as MusicBrainz. You can modify the tags that the rest of the pipeline sees on a ``beet import`` operation or during later adjustments, such as ``mbsync``. Slow handlers of the event can impact the operation, since the event is fired for any fetched possible match - *before* the user (or the autotagger machinery) gets to see the match. + `before` the user (or the autotagger machinery) gets to see the match. Parameter: ``info``. -* *albuminfo_received*: like *trackinfo_received*, the event indicates new +* `albuminfo_received`: like `trackinfo_received`, the event indicates new metadata for album items. The parameter is an ``AlbumInfo`` object instead of a ``TrackInfo``. Parameter: ``info``. From fefb2e9914381ac022b88bbd78ee2abe2dca073c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:36:22 -0800 Subject: [PATCH 0137/2280] A little cleanup for legibility and style --- beetsplug/edit.py | 69 ++++++++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 30 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 3166ce15d..597cf6b6f 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -12,7 +12,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""open tags of items in texteditor,change them and save back to the items. +"""Open metadata information in a text editor to let the user change +them directly. """ from __future__ import (division, absolute_import, print_function, unicode_literals) @@ -42,43 +43,51 @@ class EditPlugin(plugins.BeetsPlugin): 'diff_method': '', 'browser': '', 'albumfields': 'album albumartist', - 'itemfields': 'track title artist album ', + 'itemfields': 'track title artist album', 'not_fields': 'id path', - 'sep': '-' - + 'sep': '-', }) + self.style = self.config['style'].get(unicode) - """the editor field in the config lets you specify your editor. - Defaults to open with webrowser module""" + + # The editor field in the config lets you specify your editor. + # Defaults to open with webrowser module. self.editor = self.config['editor'].as_str_seq() - """the html_viewer field in your config lets you specify - your htmlviewer. Defaults to open with webrowser module""" + + # the html_viewer field in your config lets you specify + # your htmlviewer. Defaults to open with webrowser module self.browser = self.config['browser'].as_str_seq() - """the diff_method field in your config picks the way to see your - changes. Options are: - 'ndiff'(2 files with differences), - 'unified'(just the different lines and a few lines of context), - 'html'(view in html-format), - 'vimdiff'(view in VIM)""" + + # the diff_method field in your config picks the way to see your + # changes. Options are: + # 'ndiff'(2 files with differences), + # 'unified'(just the different lines and a few lines of context), + # 'html'(view in html-format), + # 'vimdiff'(view in VIM) self.diff_method = self.config['diff_method'].get(unicode) - """the albumfields field in your config sets the tags that - you want to see/change for albums. - Defaults to album albumartist. - the ID tag will always be listed as it is used to identify the item""" + + # the albumfields field in your config sets the tags that + # you want to see/change for albums. + # Defaults to album albumartist. + # the ID tag will always be listed as it is used to identify the item self.albumfields = self.config['albumfields'].as_str_seq() - """the itemfields field in your config sets the tags that - you want to see/change or items. - Defaults to track title artist album. - the ID tag will always be listed as it is used to identify the item""" + + # the itemfields field in your config sets the tags that + # you want to see/change or items. + # Defaults to track title artist album. + # the ID tag will always be listed as it is used to identify the item self.itemfields = self.config['itemfields'].as_str_seq() - '''the not_fields field in your config sets the tags that - will not be changed. - If you happen to change them, they will be restored to the original - value. The ID of an item will never be changed.''' + + # the not_fields field in your config sets the tags that + # will not be changed. + # If you happen to change them, they will be restored to the original + # value. The ID of an item will never be changed. self.not_fields = self.config['not_fields'].as_str_seq() - '''the separator in your config sets the separator that will be used - between fields in your terminal. Defaults to -''' + + # the separator in your config sets the separator that will be used + # between fields in your terminal. Defaults to - self.sep = self.config['sep'].get(unicode) + self.ed = None self.ed_args = None self.brw = None @@ -87,7 +96,7 @@ class EditPlugin(plugins.BeetsPlugin): def commands(self): edit_command = Subcommand( 'edit', - help='send items to yamleditor for editing tags') + help='interactively edit metadata') edit_command.parser.add_option( '-e', '--extra', action='store', @@ -96,7 +105,7 @@ class EditPlugin(plugins.BeetsPlugin): edit_command.parser.add_option( '--all', action='store_true', dest='all', - help='add all fields to edit', + help='edit all fields', ) edit_command.parser.add_option( '--sum', From 7de33c83c4eacc5b02f0cf99dd121f63f9d440d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:39:31 -0800 Subject: [PATCH 0138/2280] Remove an unused parameter --- beetsplug/edit.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 597cf6b6f..be4354594 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -161,7 +161,7 @@ class EditPlugin(plugins.BeetsPlugin): if not changed_objs: print_("nothing to change") return - self.save_items(changed_objs, lib, fmt, opts) + self.save_items(changed_objs, lib, opts) def print_to_yaml(self, arg): # from object to yaml @@ -323,7 +323,7 @@ class EditPlugin(plugins.BeetsPlugin): alld[o[0].values()[0]].update(so) return alld - def save_items(self, oldnewlist, lib, fmt, opts): + def save_items(self, oldnewlist, lib, opts): oldset, newset = zip(*oldnewlist) no = self.same_format(newset, opts) From 519df6da047d447b761e63a9219fb1fed7383b48 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:45:39 -0800 Subject: [PATCH 0139/2280] Use standard output format for confirmation --- beetsplug/edit.py | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index be4354594..6c20dc41d 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -150,11 +150,14 @@ class EditPlugin(plugins.BeetsPlugin): if not objs: print_('nothing found') return - fmt = self.get_fields_from(objs, opts) - print_(fmt) - [print_(format(item, fmt)) for item in objs] - if not ui.input_yn(ui.colorize('action_default', "Edit?(n/y)"), True): + self.get_fields_from(objs, opts) + + # Confirm. + for obj in objs: + print_(format(obj)) + if not ui.input_yn(ui.colorize('action_default', "Edit? (y/n)"), True): return + dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) newyaml, oldyaml = self.change_objs(dict_from_objs) changed_objs = self.check_diff(newyaml, oldyaml, opts) @@ -183,7 +186,6 @@ class EditPlugin(plugins.BeetsPlugin): def get_fields_from(self, objs, opts): # construct a list of fields we need - cl = ui.colorize('action', self.sep) # see if we need album or item fields self.fields = self.albumfields if opts.album else self.itemfields # if opts.format is given only use those fields @@ -202,10 +204,6 @@ class EditPlugin(plugins.BeetsPlugin): self.fields = None self.pick = "all" print_(ui.colorize('text_warning', "edit all fields from:")) - if opts.album: - fmt = cl + cl.join(['$albumartist', '$album']) - else: - fmt = cl + cl.join(['$title', '$artist']) else: for it in self.fields: if opts.album: @@ -223,10 +221,6 @@ class EditPlugin(plugins.BeetsPlugin): 'text_warning', it))) self.fields.remove(it) self.pick = "selected" - fmtfields = ["$" + it for it in self.fields] - fmt = cl + cl.join(fmtfields[1:]) - - return fmt def get_selected_fields(self, myfields, objs, opts): a = [] From 417eb5e58892f01cf9bb993e95b475dd59143c72 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:46:35 -0800 Subject: [PATCH 0140/2280] Remove use of nonexistent option --- beetsplug/edit.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 6c20dc41d..549f21929 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -188,10 +188,6 @@ class EditPlugin(plugins.BeetsPlugin): # construct a list of fields we need # see if we need album or item fields self.fields = self.albumfields if opts.album else self.itemfields - # if opts.format is given only use those fields - if opts.format: - self.fields = [] - self.fields.extend((opts.format).replace('$', "").split()) # if opts.extra is given add those if opts.extra: fi = (opts.extra).replace('$', "").split() From 331ced3cca607d1ea9a8255a054c5b8f67adb77f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 12:51:22 -0800 Subject: [PATCH 0141/2280] Use existing query mechanism --- beetsplug/edit.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 549f21929..28e6eaf70 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -20,6 +20,7 @@ from __future__ import (division, absolute_import, print_function, from beets import plugins from beets.ui import Subcommand, decargs, library, print_ +from beets.ui.commands import _do_query import subprocess import difflib import yaml @@ -124,8 +125,15 @@ class EditPlugin(plugins.BeetsPlugin): self.brw_args = self.browser[1:] if len(self.browser) > 1 else None self.brw = self.browser[0] if self.browser else None - # edit tags in a textfile in yaml-style + # Get the objects to edit. query = decargs(args) + items, albums = _do_query(lib, query, opts.album, False) + objs = albums if opts.album else items + if not objs: + print_('Nothing to edit.') + return + + # edit tags in a textfile in yaml-style # makes a string representation of an object # for now yaml but we could add html,pprint,toml self.print_items = { @@ -146,10 +154,6 @@ class EditPlugin(plugins.BeetsPlugin): 'all': self.get_all_fields, "selected": self.get_selected_fields} - objs = self._get_objs(lib, opts, query) - if not objs: - print_('nothing found') - return self.get_fields_from(objs, opts) # Confirm. @@ -177,13 +181,6 @@ class EditPlugin(plugins.BeetsPlugin): # from yaml to object return yaml.load_all(yam) - def _get_objs(self, lib, opts, query): - # get objects from a query - if opts.album: - return list(lib.albums(query)) - else: - return list(lib.items(query)) - def get_fields_from(self, objs, opts): # construct a list of fields we need # see if we need album or item fields From 5b761f029e72d67b4229585bcfeb0004ea9410e5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 13:14:33 -0800 Subject: [PATCH 0142/2280] A new `should_write` configuration wrapper The idea is that it is so common to check whether we need to write tags (or move files), and we're constantly re-implementing the same logic everywhere. It's not even the prettiest logic, as it commingles the importer settings with general settings. So it's important that we encapsulate the decision so we can make it better in the future. --- beets/ui/__init__.py | 27 ++++++++++++++++++++++++++- beets/ui/commands.py | 6 ++---- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 768eb76c7..a4c4c376b 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -70,7 +70,7 @@ class UserError(Exception): """ -# Utilities. +# Encoding utilities. def _out_encoding(): """Get the encoding to use for *outputting* strings to the console. @@ -137,6 +137,27 @@ def print_(*strings, **kwargs): sys.stdout.write(txt) +# Configuration wrappers. + +def _bool_fallback(opt, view): + """Given a boolean or None, return the original value or a + configuration option as a fallback. + """ + if opt is None: + return view.get(bool) + else: + return opt + + +def should_write(write_opt): + """Decide whether a command that updates metadata should also write tags, + using the importer configuration as the default. + """ + return _bool_fallback(write_opt, config['import']['write']) + + +# Input prompts. + def input_(prompt=None): """Like `raw_input`, but decodes the result to a Unicode string. Raises a UserError if stdin is not available. The prompt is sent to @@ -327,6 +348,8 @@ def input_yn(prompt, require=False): return sel == 'y' +# Human output formatting. + 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'] @@ -374,6 +397,8 @@ def human_seconds_short(interval): return u'%i:%02i' % (interval // 60, interval % 60) +# Colorization. + # ANSI terminal colorization code heavily inspired by pygments: # http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py # (pygments is by Tim Hatch, Armin Ronacher, et al.) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 348d12c88..69213ea97 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1293,10 +1293,8 @@ 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') - write = opts.write if opts.write is not None else \ - config['import']['write'].get(bool) - modify_items(lib, mods, dels, query, write, opts.move, opts.album, - not opts.yes) + modify_items(lib, mods, dels, query, ui.should_write(opts.write), + opts.move, opts.album, not opts.yes) modify_cmd = ui.Subcommand( From 9f7aa866bd5d1b9d382e258ab4053bb6ebfc8750 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 13:20:09 -0800 Subject: [PATCH 0143/2280] Use `ui.should_write` everywhere There sure are a lot of plugins that want to write metadata! --- beets/ui/__init__.py | 2 +- beetsplug/chroma.py | 3 +-- beetsplug/echonest.py | 4 ++-- beetsplug/embedart.py | 2 +- beetsplug/ftintitle.py | 3 +-- beetsplug/keyfinder.py | 4 +--- beetsplug/lastgenre/__init__.py | 3 +-- beetsplug/lyrics.py | 4 ++-- beetsplug/mbsync.py | 5 ++--- beetsplug/replaygain.py | 3 +-- 10 files changed, 13 insertions(+), 20 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index a4c4c376b..e2af8593b 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -149,7 +149,7 @@ def _bool_fallback(opt, view): return opt -def should_write(write_opt): +def should_write(write_opt=None): """Decide whether a command that updates metadata should also write tags, using the importer configuration as the default. """ diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index f1ca233e0..3446661d3 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -194,8 +194,7 @@ class AcoustidPlugin(plugins.BeetsPlugin): def fingerprint_cmd_func(lib, opts, args): for item in lib.items(ui.decargs(args)): - fingerprint_item(self._log, item, - write=config['import']['write'].get(bool)) + fingerprint_item(self._log, item, write=ui.should_write()) fingerprint_cmd.func = fingerprint_cmd_func return [submit_cmd, fingerprint_cmd] diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index 2c8a35c69..312a8b620 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -24,7 +24,7 @@ import tempfile from string import Template import subprocess -from beets import util, config, plugins, ui +from beets import util, plugins, ui from beets.dbcore import types import pyechonest import pyechonest.song @@ -472,7 +472,7 @@ class EchonestMetadataPlugin(plugins.BeetsPlugin): def fetch_func(lib, opts, args): self.config.set_args(opts) - write = config['import']['write'].get(bool) + write = ui.should_write() for item in lib.items(ui.decargs(args)): self._log.info(u'{0}', item) if self.config['force'] or self.requires_update(item): diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 9c0efa51e..6dc235979 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -128,7 +128,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): def process_album(self, album): """Automatically embed art after art has been set """ - if self.config['auto'] and config['import']['write']: + if self.config['auto'] and ui.should_write(): max_width = self.config['maxwidth'].get(int) art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 8c435865c..d2369bf52 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -22,7 +22,6 @@ import re from beets import plugins from beets import ui from beets.util import displayable_path -from beets import config def split_on_feat(artist): @@ -102,7 +101,7 @@ class FtInTitlePlugin(plugins.BeetsPlugin): def func(lib, opts, args): self.config.set_args(opts) drop_feat = self.config['drop'].get(bool) - write = config['import']['write'].get(bool) + write = ui.should_write() for item in lib.items(ui.decargs(args)): self.ft_in_title(item, drop_feat) diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index e3e9a86ba..d76448a4c 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -23,7 +23,6 @@ import subprocess from beets import ui from beets import util from beets.plugins import BeetsPlugin -from beets import config class KeyFinderPlugin(BeetsPlugin): @@ -46,8 +45,7 @@ class KeyFinderPlugin(BeetsPlugin): return [cmd] def command(self, lib, opts, args): - self.find_key(lib.items(ui.decargs(args)), - write=config['import']['write'].get(bool)) + self.find_key(lib.items(ui.decargs(args)), write=ui.should_write()) def imported(self, session, task): self.find_key(task.items) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index eab6ab440..85bd87f9b 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -31,7 +31,6 @@ import traceback from beets import plugins from beets import ui from beets.util import normpath, plurality -from beets import config from beets import library @@ -336,7 +335,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): ) def lastgenre_func(lib, opts, args): - write = config['import']['write'].get(bool) + write = ui.should_write() self.config.set_args(opts) for album in lib.albums(ui.decargs(args)): diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 2f1e3529e..16f669f53 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -29,7 +29,7 @@ import warnings from HTMLParser import HTMLParseError from beets import plugins -from beets import config, ui +from beets import ui DIV_RE = re.compile(r'<(/?)div>?', re.I) @@ -557,7 +557,7 @@ class LyricsPlugin(plugins.BeetsPlugin): def func(lib, opts, args): # The "write to files" option corresponds to the # import_write config value. - write = config['import']['write'].get(bool) + write = ui.should_write() for item in lib.items(ui.decargs(args)): self.fetch_item_lyrics( lib, item, write, diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 974f7e894..03b79a48e 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -20,7 +20,6 @@ from __future__ import (division, absolute_import, print_function, from beets.plugins import BeetsPlugin from beets import autotag, library, ui, util from beets.autotag import hooks -from beets import config from collections import defaultdict @@ -50,7 +49,7 @@ class MBSyncPlugin(BeetsPlugin): default=True, dest='move', help="don't move files in library") cmd.parser.add_option('-W', '--nowrite', action='store_false', - default=config['import']['write'], dest='write', + default=None, dest='write', help="don't write updated metadata to files") cmd.parser.add_format_option() cmd.func = self.func @@ -61,7 +60,7 @@ class MBSyncPlugin(BeetsPlugin): """ move = opts.move pretend = opts.pretend - write = opts.write + write = ui.should_write(opts.write) query = ui.decargs(args) self.singletons(lib, query, move, pretend, write) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index d57533e75..75f2ab947 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -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 -from beets import config # Utilities. @@ -926,7 +925,7 @@ class ReplayGainPlugin(BeetsPlugin): def func(lib, opts, args): self._log.setLevel(logging.INFO) - write = config['import']['write'].get(bool) + write = ui.should_write() if opts.album: for album in lib.albums(ui.decargs(args)): From d78ee1cf28de87d3db01ce1e28cad9b21fc65358 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 13:26:21 -0800 Subject: [PATCH 0144/2280] Add a corresponding `should_move` wrapper --- beets/ui/__init__.py | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index e2af8593b..4c99b937a 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -139,21 +139,39 @@ def print_(*strings, **kwargs): # Configuration wrappers. -def _bool_fallback(opt, view): - """Given a boolean or None, return the original value or a - configuration option as a fallback. +def _bool_fallback(a, b): + """Given a boolean or None, return the original value or a fallback. """ - if opt is None: - return view.get(bool) + if a is None: + assert isinstance(b, bool) + return b else: - return opt + assert isinstance(a, bool) + return a def should_write(write_opt=None): - """Decide whether a command that updates metadata should also write tags, - using the importer configuration as the default. + """Decide whether a command that updates metadata should also write + tags, using the importer configuration as the default. """ - return _bool_fallback(write_opt, config['import']['write']) + return _bool_fallback(write_opt, config['import']['write'].get(bool)) + + +def should_move(move_opt=None): + """Decide whether a command that updates metadata should also move + files when they're inside the library, using the importer + configuration as the default. + + Specifically, commands should move files after metadata updates only + when the importer is configured *either* to move *or* to copy files. + They should avoid moving files when the importer is configured not + to touch any filenames. + """ + return _bool_fallback( + move_opt, + config['import']['move'].get(bool) or + config['import']['copy'].get(bool) + ) # Input prompts. From 80bfd186ae8dd9033f0417d7d87e74902a4f028f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 13:34:47 -0800 Subject: [PATCH 0145/2280] Use `should_write` for modify, update, and mbsync This should address the surprising situation in #1697, where `import` went fine but then `update` unexpectedly changed filenames. --- beets/ui/commands.py | 17 +++++++++++++---- beetsplug/mbsync.py | 7 +++++-- docs/changelog.rst | 11 +++++++++++ docs/reference/config.rst | 4 ++++ 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 69213ea97..fa2fc84af 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1055,7 +1055,8 @@ def update_items(lib, query, album, move, pretend): def update_func(lib, opts, args): - update_items(lib, decargs(args), opts.album, opts.move, opts.pretend) + update_items(lib, decargs(args), opts.album, ui.should_move(opts.move), + opts.pretend) update_cmd = ui.Subcommand( @@ -1064,7 +1065,11 @@ update_cmd = ui.Subcommand( update_cmd.parser.add_album_option() update_cmd.parser.add_format_option() update_cmd.parser.add_option( - '-M', '--nomove', action='store_false', default=True, dest='move', + '-m', '--move', action='store_true', dest='move', + help="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" ) update_cmd.parser.add_option( @@ -1294,14 +1299,18 @@ def modify_func(lib, opts, args): if not mods and not dels: raise ui.UserError('no modifications specified') modify_items(lib, mods, dels, query, ui.should_write(opts.write), - opts.move, opts.album, not opts.yes) + ui.should_move(opts.move), opts.album, not opts.yes) modify_cmd = ui.Subcommand( 'modify', help='change metadata fields', aliases=('mod',) ) modify_cmd.parser.add_option( - '-M', '--nomove', action='store_false', default=True, dest='move', + '-m', '--move', action='store_true', dest='move', + help="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" ) modify_cmd.parser.add_option( diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 03b79a48e..d44f8f773 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -45,8 +45,11 @@ class MBSyncPlugin(BeetsPlugin): help='update metadata from musicbrainz') cmd.parser.add_option('-p', '--pretend', action='store_true', help='show all changes but do nothing') + cmd.parser.add_option('-m', '--move', action='store_true', + dest='move', + help="move files in the library directory") cmd.parser.add_option('-M', '--nomove', action='store_false', - default=True, dest='move', + dest='move', help="don't move files in library") cmd.parser.add_option('-W', '--nowrite', action='store_false', default=None, dest='write', @@ -58,7 +61,7 @@ class MBSyncPlugin(BeetsPlugin): def func(self, lib, opts, args): """Command handler for the mbsync function. """ - move = opts.move + move = ui.should_move(opts.move) pretend = opts.pretend write = ui.should_write(opts.write) query = ui.decargs(args) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5864d5c38..1c1fb0db6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,17 @@ Changelog 1.3.16 (in development) ----------------------- +New: + +* Three commands, ``modify``, ``update``, and ``mbsync``, would previously + move files by default after changing their metadata. Now, these commands + will only move files if you have the :ref:`config-import-copy` or + :ref:`config-import-move` options enabled in your importer configuration. + This way, if you configure the importer not to touch your filenames, other + commands will respect that decision by default too. Each command also + sprouted a ``--move`` command-line option to override this default (in + addition to the ``--nomove`` flag they already had). :bug:`1697` + For developers: * :doc:`/dev/plugins`: Two new hooks, ``albuminfo_received`` and diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 2d91bac14..7970d746c 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -370,6 +370,8 @@ Either ``yes`` or ``no``, controlling whether metadata (e.g., ID3) tags are written to files when using ``beet import``. Defaults to ``yes``. The ``-w`` and ``-W`` command-line options override this setting. +.. _config-import-copy: + copy ~~~~ @@ -380,6 +382,8 @@ overridden with the ``-c`` and ``-C`` command-line options. The option is ignored if ``move`` is enabled (i.e., beets can move or copy files but it doesn't make sense to do both). +.. _config-import-move: + move ~~~~ From 57cf7026681127f31fcc16f30d8673f6f88caeb0 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sat, 7 Nov 2015 23:18:30 +0100 Subject: [PATCH 0146/2280] Update index.rst --- docs/plugins/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 529a74da5..a45e0be5f 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -13,7 +13,7 @@ Using Plugins ------------- To use one of the plugins included with beets (see the rest of this page for a -list), just use the `plugins` option in your :doc:`config.yaml `: file, like so:: +list), just use the `plugins` option in your :doc:`config.yaml ` file, like so:: plugins: inline convert web From 34e6e39fe55cf1579701198638841954b231299e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Nov 2015 15:37:13 -0800 Subject: [PATCH 0147/2280] mbsync: Debug logging Log *something* for each album, so you can tell that it's doing something even when there are no changes. To help diagnose #1707. --- beetsplug/mbsync.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index d44f8f773..6e7c208a7 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -139,6 +139,7 @@ class MBSyncPlugin(BeetsPlugin): break # Apply. + self._log.debug('applying changes to {}', album_formatted) with lib.transaction(): autotag.apply_metadata(album_info, mapping) changed = False From a71b2e1046277dbf1551f4f9fc23196231c72759 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 8 Nov 2015 16:09:41 +0100 Subject: [PATCH 0148/2280] editor: update plugin name on examples on docs --- docs/plugins/edit.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 125f7ce0b..3b48635c4 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -5,9 +5,9 @@ Add the ``edit`` plugin to your ``plugins:`` in your ``config.yaml``. Then you simply put in a query like you normally do. :: - beet yamleditor beatles - beet yamleditor beatles -a - beet yamleditor beatles -f '$title $lyrics' + beet edit beatles + beet edit beatles -a + beet edit beatles -f '$title $lyrics' From 485870f2888bc42fd2b521847fac802640524a0b Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sun, 8 Nov 2015 16:22:36 +0100 Subject: [PATCH 0149/2280] Made various artist title configurable --- beets/autotag/mb.py | 2 ++ beets/config_default.yaml | 1 + beetsplug/discogs.py | 6 +++--- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 8589a62aa..78c5fb2f4 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -259,6 +259,8 @@ def album_info(release): data_url=album_url(release['id']), ) info.va = info.artist_id == VARIOUS_ARTISTS_ID + if info.va: + info.artist = config['va_name'].get(unicode) info.asin = release.get('asin') info.releasegroup_id = release['release-group']['id'] info.country = release.get('country') diff --git a/beets/config_default.yaml b/beets/config_default.yaml index f708702a8..ba58debe7 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -47,6 +47,7 @@ verbose: 0 terminal_encoding: original_date: no id3v23: no +va_name: "Various Artists" ui: terminal_width: 80 diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index c19e65a2f..2a90cdafe 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -20,6 +20,7 @@ from __future__ import (division, absolute_import, print_function, import beets.ui from beets import logging +from beets import config from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance from beets.plugins import BeetsPlugin from beets.util import confit @@ -55,8 +56,7 @@ class DiscogsPlugin(BeetsPlugin): 'apikey': 'rAzVUQYRaoFjeBjyWuWZ', 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', - 'source_weight': 0.5, - 'va_name': 'Various Artists', + 'source_weight': 0.5 }) self.config['apikey'].redact = True self.config['apisecret'].redact = True @@ -225,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 = self.config['va_name'].get() + artist = config['va_name'].get(unicode) year = result.data['year'] label = result.data['labels'][0]['name'] mediums = len(set(t.medium for t in tracks)) From 95b80b37aa79610a321244d07b3b49ca0fd93592 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sun, 8 Nov 2015 17:04:36 +0100 Subject: [PATCH 0150/2280] Updated documentation --- docs/changelog.rst | 7 ++++--- docs/plugins/discogs.rst | 10 ---------- docs/reference/config.rst | 9 +++++++++ 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1c1fb0db6..67be6cb0f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -48,9 +48,10 @@ Fixes: * :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of iTunes. :bug:`1700` * :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` -* :doc:`/plugins/discogs`: A new option, ``va_name``, controls the album - artist name for various-artists albums. The default is now "Various - Artists," to match MusicBrainz. +* A new global option, ``va_name``, controls the album artist name for + various-artists albums. Defaults to "Various Artists" (MusicBrainz standard). + In order to match MusicBrainz, :doc:`/plugins/discogs` adapts to this, too. + 1.3.15 (October 17, 2015) diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index a7983e7e0..038718f9b 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -25,16 +25,6 @@ MusicBrainz. If you have a Discogs ID for an album you want to tag, you can also enter it at the "enter Id" prompt in the importer. -Configuration -------------- - -To configure the plugin, make a ``discogs:`` section in your configuration -file. The available options are: - -- **va_name**: The albumartist name to use when an album is marked as being by - "various" artists. - Default: "Various Artists" (matching the MusicBrainz convention). - Troubleshooting --------------- diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 7970d746c..1d8edf595 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -304,6 +304,15 @@ By default, beets writes MP3 tags using the ID3v2.4 standard, the latest version of ID3. Enable this option to instead use the older ID3v2.3 standard, which is preferred by certain older software such as Windows Media Player. +.. _va_name: + +va_name +~~~~~~~ + +Sets the albumartist for various-artist compilations. Defaults to ``'Various +Artists'`` (MusicBrainz standard). Affects other sources, such as +:doc:`/plugins/discogs`, too. + UI Options ---------- From 57faf015d9259ecbcd68005cea436346b1d4f000 Mon Sep 17 00:00:00 2001 From: Manfred Urban Date: Sun, 8 Nov 2015 17:28:55 +0100 Subject: [PATCH 0151/2280] Adapted va_name in other files --- beets/importer.py | 3 +-- beetsplug/lastgenre/__init__.py | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 85d6e0824..5bdcaff8f 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -48,7 +48,6 @@ action = Enum('action', QUEUE_SIZE = 128 SINGLE_ARTIST_THRESH = 0.25 -VARIOUS_ARTISTS = u'Various Artists' PROGRESS_KEY = 'tagprogress' HISTORY_KEY = 'taghistory' @@ -631,7 +630,7 @@ class ImportTask(BaseImportTask): changes['comp'] = False else: # VA. - changes['albumartist'] = VARIOUS_ARTISTS + changes['albumartist'] = config['va_name'].get(unicode) changes['comp'] = True elif self.choice_flag == action.APPLY: diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 85bd87f9b..f276fe4f1 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -30,6 +30,7 @@ import traceback from beets import plugins from beets import ui +from beets import config from beets.util import normpath, plurality from beets import library @@ -291,7 +292,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): result = None if isinstance(obj, library.Item): result = self.fetch_artist_genre(obj) - elif obj.albumartist != 'Various Artists': + elif obj.albumartist != config['va_name'].get(unicode): result = self.fetch_album_artist_genre(obj) else: # For "Various Artists", pick the most popular track genre. From 1c09eeb714f31e275e46288bcfd0edafc1522bd2 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 8 Nov 2015 19:26:35 +0100 Subject: [PATCH 0152/2280] edit: delete temporary files, minor style fixes * Delete NamedTemporaryFiles once they are not needed on several functions (change_objs(), vimdiff(), html()). * Fix use of reserved word "id" on same_format(). * Colorize "really modify" prompt with action_default. --- beetsplug/edit.py | 57 ++++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 28e6eaf70..62dcd8bdc 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -26,6 +26,7 @@ import difflib import yaml import collections import webbrowser +from contextlib import nested from sys import exit from beets import config from beets import ui @@ -265,6 +266,7 @@ class EditPlugin(plugins.BeetsPlugin): with open(new.name) as f: newyaml = f.read() list(yaml.load_all(newyaml)) + os.remove(new.name) break except yaml.YAMLError as e: print_(ui.colorize('text_warning', @@ -279,6 +281,7 @@ class EditPlugin(plugins.BeetsPlugin): return newyaml, oldyaml else: + os.remove(new.name) exit() def get_editor(self, name): @@ -301,8 +304,8 @@ class EditPlugin(plugins.BeetsPlugin): for o in newset: for so in o: ids = set((so[1].values()[0].split())) - for id in ids: - alld[id].update( + for id_ in ids: + alld[id_].update( {so[0].items()[0][1]: so[1].items()[0][0]}) else: for o in newset: @@ -340,7 +343,8 @@ class EditPlugin(plugins.BeetsPlugin): self.save_write(changedob) def save_write(self, changedob): - if not ui.input_yn('really modify? (y/n)'): + if not ui.input_yn(ui.colorize('action_default', + 'really modify? (y/n)')): return for ob in changedob: @@ -409,30 +413,31 @@ class EditPlugin(plugins.BeetsPlugin): oldlines = oldfilestr.splitlines() diff = difflib.HtmlDiff() df = diff.make_file(newlines, oldlines) - ht = NamedTemporaryFile('w', suffix='.html', delete=False) - ht.write(df) - ht.flush() - hdn = ht.name - if not self.brw: - browser = os.getenv('BROWSER') - if browser: - os.system(browser + " " + hdn) + + with NamedTemporaryFile('w', suffix='.html', bufsize=0) as ht: + # TODO: if webbrowser.open() is not blocking, ht might be deleted + # too soon - need to test + ht.write(df) + if not self.brw: + browser = os.getenv('BROWSER') + if browser: + os.system(browser + " " + ht.name) + else: + webbrowser.open(ht.name, new=2, autoraise=True) else: - webbrowser.open(hdn, new=2, autoraise=True) - else: - callmethod = [self.brw] - if self.brw_args: - callmethod.extend(self.brw_args) - callmethod.append(hdn) - subprocess.call(callmethod) + callmethod = [self.brw] + if self.brw_args: + callmethod.extend(self.brw_args) + callmethod.append(ht.name) + subprocess.call(callmethod) + return def vimdiff(self, newstringstr, oldstringstr): - - newdiff = NamedTemporaryFile(suffix='.old.yaml', delete=False) - newdiff.write(newstringstr) - newdiff.close() - olddiff = NamedTemporaryFile(suffix='.new.yaml', delete=False) - olddiff.write(oldstringstr) - olddiff.close() - subprocess.call(['vimdiff', newdiff.name, olddiff.name]) + with nested(NamedTemporaryFile(suffix='.old.yaml', + bufsize=0), + NamedTemporaryFile(suffix='.new.yaml', + bufsize=0)) as (newdiff, olddiff): + newdiff.write(newstringstr) + olddiff.write(oldstringstr) + subprocess.call(['vimdiff', newdiff.name, olddiff.name]) From 9165b7cf452748081b3c307d08a61c5f1604b592 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 8 Nov 2015 13:02:07 -0800 Subject: [PATCH 0153/2280] Trailing comma (#1708) --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 2a90cdafe..7ab2d217b 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -56,7 +56,7 @@ class DiscogsPlugin(BeetsPlugin): 'apikey': 'rAzVUQYRaoFjeBjyWuWZ', 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', - 'source_weight': 0.5 + 'source_weight': 0.5, }) self.config['apikey'].redact = True self.config['apisecret'].redact = True From 98f48237f560dcc85cfac77a651e63bf9c52d31c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 8 Nov 2015 13:04:26 -0800 Subject: [PATCH 0154/2280] Tiny docs tweaks for #1708 --- docs/changelog.rst | 9 +++++---- docs/reference/config.rst | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 67be6cb0f..247e0efda 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,11 @@ New: commands will respect that decision by default too. Each command also sprouted a ``--move`` command-line option to override this default (in addition to the ``--nomove`` flag they already had). :bug:`1697` +* A new configuration option, ``va_name``, controls the album artist name for + various-artists albums. The setting defaults to "Various Artists," the + MusicBrainz standard. In order to match MusicBrainz, the + :doc:`/plugins/discogs` also adopts the same setting. + For developers: @@ -48,10 +53,6 @@ Fixes: * :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of iTunes. :bug:`1700` * :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` -* A new global option, ``va_name``, controls the album artist name for - various-artists albums. Defaults to "Various Artists" (MusicBrainz standard). - In order to match MusicBrainz, :doc:`/plugins/discogs` adapts to this, too. - 1.3.15 (October 17, 2015) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 1d8edf595..84e4368d6 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -310,7 +310,7 @@ va_name ~~~~~~~ Sets the albumartist for various-artist compilations. Defaults to ``'Various -Artists'`` (MusicBrainz standard). Affects other sources, such as +Artists'`` (the MusicBrainz standard). Affects other sources, such as :doc:`/plugins/discogs`, too. From 41b4987990e3965524ad8c951af4465c78e83a6d Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 9 Nov 2015 20:43:40 +0100 Subject: [PATCH 0155/2280] edit: add initial black-box tests * Add tests for the edit plugin, including a helper for bypassing the manual yaml editing. Tests are focused on "black-box" functionality, running the command and making assertions on the changes made to the library. --- test/test_edit.py | 172 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 test/test_edit.py diff --git a/test/test_edit.py b/test/test_edit.py new file mode 100644 index 000000000..90048b96a --- /dev/null +++ b/test/test_edit.py @@ -0,0 +1,172 @@ +# This file is part of beets. +# Copyright 2015, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import (division, absolute_import, print_function, + unicode_literals) +import codecs + +from mock import Mock, patch +from test._common import unittest +from test.helper import TestHelper, control_stdin + +from beets import library +from beetsplug.edit import EditPlugin + + +class ModifyFileMocker(object): + """Helper for modifying a file, replacing or editing its contents. Used for + mocking the calls to the external editor during testing.""" + + def __init__(self, contents=None, replacements=None): + """ `self.contents` and `self.replacements` are initalized here, in + order to keep the rest of the functions of this class with the same + signature as `EditPlugin.get_editor()`, making mocking easier. + - `contents`: string with the contents of the file to be used for + `overwrite_contents()` + - `replacement`: dict with the in-place replacements to be used for + `replace_contents()`, in the form {'previous string': 'new string'} + + TODO: check if it can be solved more elegantly with a decorator + """ + self.contents = contents + self.replacements = replacements + self.action = self.overwrite_contents + if replacements: + self.action = self.replace_contents + + def overwrite_contents(self, filename): + """Modify `filename`, replacing its contents with `self.contents`. If + `self.contents` is empty, the file remains unchanged. + """ + if self.contents: + with codecs.open(filename, 'w', encoding='utf8') as f: + f.write(self.contents) + + def replace_contents(self, filename): + """Modify `filename`, reading its contents and replacing the strings + specified in `self.replacements`. + """ + with codecs.open(filename, 'r', encoding='utf8') as f: + contents = f.read() + for old, new_ in self.replacements.iteritems(): + contents = contents.replace(old, new_) + with codecs.open(filename, 'w', encoding='utf8') as f: + f.write(contents) + + +class EditCommandTest(unittest.TestCase, TestHelper): + """ Black box tests for `beetsplug.edit`. Command line interaction is + simulated using `test.helper.control_stdin()`, and yaml editing via an + external editor is simulated using `ModifyFileMocker`. + """ + ALBUM_COUNT = 1 + TRACK_COUNT = 10 + + def setUp(self): + self.setup_beets() + self.load_plugins('edit') + # make sure that we avoid invoking the editor except for making changes + self.config['edit']['diff_method'] = '' + # add an album + self.add_album_fixture(track_count=self.TRACK_COUNT) + # keep track of write()s + library.Item.write = Mock() + + def tearDown(self): + self.teardown_beets() + self.unload_plugins() + + def run_mocked_command(self, modify_file_args={}, stdin=[]): + """Run the edit command, with mocked stdin and yaml writing.""" + m = ModifyFileMocker(**modify_file_args) + with patch.object(EditPlugin, 'get_editor', side_effect=m.action): + with control_stdin('\n'.join(stdin)): + self.run_command('edit') + + def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, + write_call_count=TRACK_COUNT, title_starts_with=''): + """Several common assertions on Album, Track and call counts.""" + self.assertEqual(len(self.lib.albums()), album_count) + self.assertEqual(len(self.lib.items()), track_count) + self.assertEqual(library.Item.write.call_count, write_call_count) + self.assertTrue(all(i.title.startswith(title_starts_with) + for i in self.lib.items())) + + def test_title_edit_discard(self): + """Edit title for all items in the library, then discard changes-""" + # edit titles + self.run_mocked_command({'replacements': {u't\u00eftle': + u'modified t\u00eftle'}}, + # edit? y, done? y, modify? n + ['y', 'y', 'n']) + + self.assertCounts(write_call_count=0, + title_starts_with=u't\u00eftle') + + def test_title_edit_apply(self): + """Edit title for all items in the library, then apply changes.""" + # edit titles + self.run_mocked_command({'replacements': {u't\u00eftle': + u'modified t\u00eftle'}}, + # edit? y, done? y, modify? y + ['y', 'y', 'y']) + + self.assertCounts(write_call_count=self.TRACK_COUNT, + title_starts_with=u'modified t\u00eftle') + + def test_noedit(self): + """Do not edit anything.""" + # do not edit anything + self.run_mocked_command({'contents': None}, + # edit? n -> "no changes found" + ['n']) + + self.assertCounts(write_call_count=0, + title_starts_with=u't\u00eftle') + + def test_malformed_yaml_discard(self): + """Edit the yaml file incorrectly (resulting in a malformed yaml + document), then discard changes. + + TODO: this test currently fails, on purpose. User gets into an endless + "fix?" -> "ok.fixed." prompt loop unless he is able to provide a + well-formed yaml.""" + # edit the yaml file to an invalid file + self.run_mocked_command({'contents': '!MALFORMED'}, + # edit? n, done? y, fix? n + ['y', 'y', 'n']) + + self.assertCounts(write_call_count=0, + title_starts_with=u't\u00eftle') + + def test_invalid_yaml_discard(self): + """Edit the yaml file incorrectly (resulting in a well-formed but + invalid yaml document), then discard changes. + + TODO: this test currently fails, on purpose. `check_diff()` chokes + ungracefully""" + # edit the yaml file to an invalid file + self.run_mocked_command({'contents': 'wellformed: yes, but invalid'}, + # edit? n, done? y + ['y', 'y']) + + self.assertCounts(write_call_count=0, + title_starts_with=u't\u00eftle') + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') From 48637f22e970288e23741dff46191f7a59f951db Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Nov 2015 21:52:10 -0800 Subject: [PATCH 0156/2280] smartplaylist: Handle exceptional cases in setup --- beetsplug/smartplaylist.py | 70 ++++++++++++++++++++++---------------- docs/changelog.rst | 2 ++ 2 files changed, 42 insertions(+), 30 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 8889a2534..c88fe38c5 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -23,7 +23,7 @@ from beets import ui from beets.util import mkdirall, normpath, syspath from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery -from beets.dbcore.query import MultipleSort +from beets.dbcore.query import MultipleSort, ParsingError import os @@ -93,36 +93,46 @@ class SmartPlaylistPlugin(BeetsPlugin): self._matched_playlists = set() for playlist in self.config['playlists'].get(list): - playlist_data = (playlist['name'],) - for key, Model in (('query', Item), ('album_query', Album)): - qs = playlist.get(key) - if qs is None: - query_and_sort = None, None - elif isinstance(qs, basestring): - query_and_sort = parse_query_string(qs, Model) - elif len(qs) == 1: - query_and_sort = parse_query_string(qs[0], Model) - else: - # multiple queries and sorts - queries, sorts = zip(*(parse_query_string(q, Model) - for q in qs)) - query = OrQuery(queries) - final_sorts = [] - for s in sorts: - if s: - if isinstance(s, MultipleSort): - final_sorts += s.sorts - else: - final_sorts.append(s) - if not final_sorts: - sort = None - elif len(final_sorts) == 1: - sort, = final_sorts - else: - sort = MultipleSort(final_sorts) - query_and_sort = query, sort + if 'name' not in playlist: + self._log.warn("playlist configuration is missing name") + continue - playlist_data += (query_and_sort,) + playlist_data = (playlist['name'],) + try: + for key, Model in (('query', Item), ('album_query', Album)): + qs = playlist.get(key) + if qs is None: + query_and_sort = None, None + elif isinstance(qs, basestring): + query_and_sort = parse_query_string(qs, Model) + elif len(qs) == 1: + query_and_sort = parse_query_string(qs[0], Model) + else: + # multiple queries and sorts + queries, sorts = zip(*(parse_query_string(q, Model) + for q in qs)) + query = OrQuery(queries) + final_sorts = [] + for s in sorts: + if s: + if isinstance(s, MultipleSort): + final_sorts += s.sorts + else: + final_sorts.append(s) + if not final_sorts: + sort = None + elif len(final_sorts) == 1: + sort, = final_sorts + else: + sort = MultipleSort(final_sorts) + query_and_sort = query, sort + + playlist_data += (query_and_sort,) + + except ParsingError as exc: + self._log.warn("invalid query in playlist {}: {}", + playlist['name'], exc) + continue self._unmatched_playlists.add(playlist_data) diff --git a/docs/changelog.rst b/docs/changelog.rst index 247e0efda..d86137b0e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -53,6 +53,8 @@ Fixes: * :doc:`/plugins/metasync`: Fix a crash when syncing with recent versions of iTunes. :bug:`1700` * :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` +* :doc:`/plugins/smartplaylist`: More gracefully handle malformed queries and + missing configuration. 1.3.15 (October 17, 2015) From 4b2b9fe2cee204e3eda0871764f2d4e090554aa8 Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Thu, 5 Nov 2015 09:46:01 +0100 Subject: [PATCH 0157/2280] Added embyupdate plugin Its a simple plugin that triggers a library refresh after the library got changed. It does the same thing like the plexupdate plugin. --- beetsplug/embyupdate.py | 133 ++++++++++++++++++++++ docs/changelog.rst | 5 +- docs/plugins/embyupdate.rst | 33 ++++++ docs/plugins/index.rst | 3 + test/test_embyupdate.py | 212 ++++++++++++++++++++++++++++++++++++ 5 files changed, 385 insertions(+), 1 deletion(-) create mode 100644 beetsplug/embyupdate.py create mode 100644 docs/plugins/embyupdate.rst create mode 100644 test/test_embyupdate.py diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py new file mode 100644 index 000000000..ffca7c30c --- /dev/null +++ b/beetsplug/embyupdate.py @@ -0,0 +1,133 @@ +"""Updates the Emby Library whenever the beets library is changed. + + emby: + host: localhost + port: 8096 + username: user + password: password +""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from beets import config +from beets.plugins import BeetsPlugin +from urllib import urlencode +from urlparse import urljoin, parse_qs, urlsplit, urlunsplit +import hashlib +import requests + + +def api_url(host, port, endpoint): + """Returns a joined url. + """ + joined = urljoin('http://{0}:{1}'.format(host, port), endpoint) + scheme, netloc, path, query_string, fragment = urlsplit(joined) + query_params = parse_qs(query_string) + + query_params['format'] = ['json'] + new_query_string = urlencode(query_params, doseq=True) + + return urlunsplit((scheme, netloc, path, new_query_string, fragment)) + + +def password_data(username, password): + """Returns a dict with username and its encoded password. + """ + return { + 'username': username, + 'password': hashlib.sha1(password).hexdigest(), + 'passwordMd5': hashlib.md5(password).hexdigest() + } + + +def create_headers(user_id, token=None): + """Return header dict that is needed to talk to the Emby API. + """ + headers = { + 'Authorization': 'MediaBrowser', + 'UserId': user_id, + 'Client': 'other', + 'Device': 'empy', + 'DeviceId': 'beets', + 'Version': '0.0.0' + } + + if token: + headers['X-MediaBrowser-Token'] = token + + return headers + + +def get_token(host, port, headers, auth_data): + """Return token for a user. + """ + url = api_url(host, port, '/Users/AuthenticateByName') + r = requests.post(url, headers=headers, data=auth_data) + + return r.json().get('AccessToken') + + +def get_user(host, port, username): + """Return user dict from server or None if there is no user. + """ + url = api_url(host, port, '/Users/Public') + r = requests.get(url) + user = [i for i in r.json() if i['Name'] == username] + + return user + + +class EmbyUpdate(BeetsPlugin): + def __init__(self): + super(EmbyUpdate, self).__init__() + + # Adding defaults. + config['emby'].add({ + u'host': u'localhost', + u'port': 8096 + }) + + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update for the end. + """ + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to Emby. + """ + self._log.info(u'Updating Emby library...') + + host = config['emby']['host'].get() + port = config['emby']['port'].get() + username = config['emby']['username'].get() + password = config['emby']['password'].get() + + # Get user information from the Emby API. + user = get_user(host, port, username) + if not user: + self._log.warning(u'User {0} could not be found.'.format(username)) + return + + # Create Authentication data and headers. + auth_data = password_data(username, password) + headers = create_headers(user[0]['Id']) + + # Get authentication token. + token = get_token(host, port, headers, auth_data) + if not token: + self._log.warning( + u'Couldnt not get token for user {0}'.format(username)) + return + + # Recreate headers with a token. + headers = create_headers(user[0]['Id'], token=token) + + # Trigger the Update. + url = api_url(host, port, '/Library/Refresh') + r = requests.post(url, headers=headers) + if r.status_code != 204: + self._log.warning(u'Update could not be triggered') + else: + self._log.info(u'Update triggered.') diff --git a/docs/changelog.rst b/docs/changelog.rst index d86137b0e..27567f283 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,7 +18,8 @@ New: various-artists albums. The setting defaults to "Various Artists," the MusicBrainz standard. In order to match MusicBrainz, the :doc:`/plugins/discogs` also adopts the same setting. - +* :doc:`/plugins/embyupdate`: A plugin to trigger a library refresh on a + `Emby Server`_ if database changed. For developers: @@ -56,6 +57,8 @@ Fixes: * :doc:`/plugins/smartplaylist`: More gracefully handle malformed queries and missing configuration. +.. _Emby Server: http://emby.media + 1.3.15 (October 17, 2015) ------------------------- diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst new file mode 100644 index 000000000..2a47826ae --- /dev/null +++ b/docs/plugins/embyupdate.rst @@ -0,0 +1,33 @@ +EmbyUpdate Plugin +================= + +``embyupdate`` is a plugin that lets you automatically update `Emby`_'s library whenever you change your beets library. + +To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll probably want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: + + emby: + host: localhost + port: 8096 + username: user + password: password + +To use the ``embyupdate`` plugin you need to install the `requests`_ library with:: + + pip install requests + +With that all in place, you'll see beets send the "update" command to your Emby server every time you change your beets library. + +.. _Emby: http://emby.media/ +.. _requests: http://docs.python-requests.org/en/latest/ + +Configuration +------------- + +The available options under the ``emby:`` section are: + +- **host**: The Emby server name. + Default: ``localhost`` +- **port**: The Emby server port. + Defailt: 8096 +- **username**: A username of a Emby user that is allowed to refresh the library. +- **password**: That users password. diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index a45e0be5f..d09139837 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -41,6 +41,7 @@ Each plugin has its own set of options that can be defined in a section bearing duplicates echonest embedart + embyupdate fetchart fromfilename ftintitle @@ -131,6 +132,7 @@ Path Formats Interoperability ---------------- +* :doc:`embyupdate`: Automatically notifies `Emby`_ whenever the beets library changes. * :doc:`importfeeds`: Keep track of imported files via ``.m3u`` playlist file(s) or symlinks. * :doc:`ipfs`: Import libraries from friends and get albums from them via ipfs. * :doc:`mpdupdate`: Automatically notifies `MPD`_ whenever the beets library @@ -143,6 +145,7 @@ Interoperability * :doc:`badfiles`: Check audio file integrity. +.. _Emby: http://emby.media .. _Plex: http://plex.tv Miscellaneous diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py new file mode 100644 index 000000000..d21c19987 --- /dev/null +++ b/test/test_embyupdate.py @@ -0,0 +1,212 @@ +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from test._common import unittest +from test.helper import TestHelper +from beetsplug import embyupdate +import responses + + +class EmbyUpdateTest(unittest.TestCase, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('embyupdate') + + self.config['emby'] = { + u'host': u'localhost', + u'port': 8096, + u'username': u'username', + u'password': u'password' + } + + def tearDown(self): + self.teardown_beets() + self.unload_plugins() + + def test_api_url(self): + self.assertEqual( + embyupdate.api_url(self.config['emby']['host'].get(), + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'http://localhost:8096/Library/Refresh?format=json' + ) + + def test_password_data(self): + self.assertEqual( + embyupdate.password_data(self.config['emby']['username'].get(), + self.config['emby']['password'].get()), + { + 'username': 'username', + 'password': '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', + 'passwordMd5': '5f4dcc3b5aa765d61d8327deb882cf99' + } + ) + + def test_create_header_no_token(self): + self.assertEqual( + embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721'), + { + 'Authorization': 'MediaBrowser', + 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', + 'Client': 'other', + 'Device': 'empy', + 'DeviceId': 'beets', + 'Version': '0.0.0' + } + ) + + def test_create_header_with_token(self): + self.assertEqual( + embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721', + token='abc123'), + { + 'Authorization': 'MediaBrowser', + 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', + 'Client': 'other', + 'Device': 'empy', + 'DeviceId': 'beets', + 'Version': '0.0.0', + 'X-MediaBrowser-Token': 'abc123' + } + ) + + @responses.activate + def test_get_token(self): + body = ('{"User":{"Name":"username", ' + '"ServerId":"1efa5077976bfa92bc71652404f646ec",' + '"Id":"2ec276a2642e54a19b612b9418a8bd3b","HasPassword":true,' + '"HasConfiguredPassword":true,' + '"HasConfiguredEasyPassword":false,' + '"LastLoginDate":"2015-11-09T08:35:03.6357440Z",' + '"LastActivityDate":"2015-11-09T08:35:03.6665060Z",' + '"Configuration":{"AudioLanguagePreference":"",' + '"PlayDefaultAudioTrack":true,"SubtitleLanguagePreference":"",' + '"DisplayMissingEpisodes":false,' + '"DisplayUnairedEpisodes":false,' + '"GroupMoviesIntoBoxSets":false,' + '"DisplayChannelsWithinViews":[],' + '"ExcludeFoldersFromGrouping":[],"GroupedFolders":[],' + '"SubtitleMode":"Default","DisplayCollectionsView":true,' + '"DisplayFoldersView":false,"EnableLocalPassword":false,' + '"OrderedViews":[],"IncludeTrailersInSuggestions":true,' + '"EnableCinemaMode":true,"LatestItemsExcludes":[],' + '"PlainFolderViews":[],"HidePlayedInLatest":true,' + '"DisplayChannelsInline":false},' + '"Policy":{"IsAdministrator":true,"IsHidden":false,' + '"IsDisabled":false,"BlockedTags":[],' + '"EnableUserPreferenceAccess":true,"AccessSchedules":[],' + '"BlockUnratedItems":[],' + '"EnableRemoteControlOfOtherUsers":false,' + '"EnableSharedDeviceControl":true,' + '"EnableLiveTvManagement":true,"EnableLiveTvAccess":true,' + '"EnableMediaPlayback":true,' + '"EnableAudioPlaybackTranscoding":true,' + '"EnableVideoPlaybackTranscoding":true,' + '"EnableContentDeletion":false,' + '"EnableContentDownloading":true,"EnableSync":true,' + '"EnableSyncTranscoding":true,"EnabledDevices":[],' + '"EnableAllDevices":true,"EnabledChannels":[],' + '"EnableAllChannels":true,"EnabledFolders":[],' + '"EnableAllFolders":true,"InvalidLoginAttemptCount":0,' + '"EnablePublicSharing":true}},' + '"SessionInfo":{"SupportedCommands":[],' + '"QueueableMediaTypes":[],"PlayableMediaTypes":[],' + '"Id":"89f3b33f8b3a56af22088733ad1d76b3",' + '"UserId":"2ec276a2642e54a19b612b9418a8bd3b",' + '"UserName":"username","AdditionalUsers":[],' + '"ApplicationVersion":"Unknown version",' + '"Client":"Unknown app",' + '"LastActivityDate":"2015-11-09T08:35:03.6665060Z",' + '"DeviceName":"Unknown device","DeviceId":"Unknown device id",' + '"SupportsRemoteControl":false,"PlayState":{"CanSeek":false,' + '"IsPaused":false,"IsMuted":false,"RepeatMode":"RepeatNone"}},' + '"AccessToken":"4b19180cf02748f7b95c7e8e76562fc8",' + '"ServerId":"1efa5077976bfa92bc71652404f646ec"}') + + responses.add(responses.POST, + ('http://localhost:8096' + '/Users/AuthenticateByName'), + body=body, + status=200, + content_type='application/json') + + headers = { + 'Authorization': 'MediaBrowser', + 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', + 'Client': 'other', + 'Device': 'empy', + 'DeviceId': 'beets', + 'Version': '0.0.0' + } + + auth_data = { + 'username': 'username', + 'password': '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', + 'passwordMd5': '5f4dcc3b5aa765d61d8327deb882cf99' + } + + self.assertEqual( + embyupdate.get_token('localhost', 8096, headers, auth_data), + '4b19180cf02748f7b95c7e8e76562fc8') + + @responses.activate + def test_get_user(self): + body = ('[{"Name":"username",' + '"ServerId":"1efa5077976bfa92bc71652404f646ec",' + '"Id":"2ec276a2642e54a19b612b9418a8bd3b","HasPassword":true,' + '"HasConfiguredPassword":true,' + '"HasConfiguredEasyPassword":false,' + '"LastLoginDate":"2015-11-09T08:35:03.6357440Z",' + '"LastActivityDate":"2015-11-09T08:42:39.3693220Z",' + '"Configuration":{"AudioLanguagePreference":"",' + '"PlayDefaultAudioTrack":true,"SubtitleLanguagePreference":"",' + '"DisplayMissingEpisodes":false,' + '"DisplayUnairedEpisodes":false,' + '"GroupMoviesIntoBoxSets":false,' + '"DisplayChannelsWithinViews":[],' + '"ExcludeFoldersFromGrouping":[],"GroupedFolders":[],' + '"SubtitleMode":"Default","DisplayCollectionsView":true,' + '"DisplayFoldersView":false,"EnableLocalPassword":false,' + '"OrderedViews":[],"IncludeTrailersInSuggestions":true,' + '"EnableCinemaMode":true,"LatestItemsExcludes":[],' + '"PlainFolderViews":[],"HidePlayedInLatest":true,' + '"DisplayChannelsInline":false},' + '"Policy":{"IsAdministrator":true,"IsHidden":false,' + '"IsDisabled":false,"BlockedTags":[],' + '"EnableUserPreferenceAccess":true,"AccessSchedules":[],' + '"BlockUnratedItems":[],' + '"EnableRemoteControlOfOtherUsers":false,' + '"EnableSharedDeviceControl":true,' + '"EnableLiveTvManagement":true,"EnableLiveTvAccess":true,' + '"EnableMediaPlayback":true,' + '"EnableAudioPlaybackTranscoding":true,' + '"EnableVideoPlaybackTranscoding":true,' + '"EnableContentDeletion":false,' + '"EnableContentDownloading":true,' + '"EnableSync":true,"EnableSyncTranscoding":true,' + '"EnabledDevices":[],"EnableAllDevices":true,' + '"EnabledChannels":[],"EnableAllChannels":true,' + '"EnabledFolders":[],"EnableAllFolders":true,' + '"InvalidLoginAttemptCount":0,"EnablePublicSharing":true}}]') + + responses.add(responses.GET, + 'http://localhost:8096/Users/Public', + body=body, + status=200, + content_type='application/json') + + response = embyupdate.get_user('localhost', 8096, 'username') + + self.assertEqual(response[0]['Id'], + '2ec276a2642e54a19b612b9418a8bd3b') + + self.assertEqual(response[0]['Name'], + 'username') + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') From 6e6aa9700db6a6dee2ad1fa45a16a10e9cf360be Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 10 Nov 2015 19:16:04 +0100 Subject: [PATCH 0158/2280] edit: more assertions on existing tests, new tests * Modify existing tests in order to explicitely check for differences (or lack of) in the items fields, with the intention to ensure that no unintended changes slip through. * Added tests for modifying a single item from a list of items, and for editing the album field of the items (stub for discussing whether the actual album should be updated, etc). --- test/test_edit.py | 58 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 90048b96a..702830613 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -78,8 +78,12 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.load_plugins('edit') # make sure that we avoid invoking the editor except for making changes self.config['edit']['diff_method'] = '' - # add an album - self.add_album_fixture(track_count=self.TRACK_COUNT) + # add an album, storing the original fields for comparison + self.album = self.add_album_fixture(track_count=self.TRACK_COUNT) + self.album_orig = {f: self.album[f] for f in self.album._fields} + self.items_orig = [{f: item[f] for f in item._fields} for + item in self.album.items()] + # keep track of write()s library.Item.write = Mock() @@ -103,6 +107,20 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertTrue(all(i.title.startswith(title_starts_with) for i in self.lib.items())) + def assertItemFieldsModified(self, library_items, items, fields=[]): + """Assert that items in the library (`lib_items`) have different values + on the specified `fields` (and *only* on those fields), compared to + `items`. + An empty `fields` list results in asserting that no modifications have + been performed. + """ + changed_fields = [] + for lib_item, item in zip(library_items, items): + changed_fields.append([field for field in lib_item._fields + if lib_item[field] != item[field]]) + self.assertTrue(all(diff_fields == fields for diff_fields in + changed_fields)) + def test_title_edit_discard(self): """Edit title for all items in the library, then discard changes-""" # edit titles @@ -113,6 +131,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, []) def test_title_edit_apply(self): """Edit title for all items in the library, then apply changes.""" @@ -124,6 +143,23 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['title']) + + def test_single_title_edit_apply(self): + """Edit title for on items in the library, then apply changes.""" + # edit title + self.run_mocked_command({'replacements': {u't\u00eftle 9': + u'modified t\u00eftle 9'}}, + # edit? y, done? y, modify? y + ['y', 'y', 'y']) + + self.assertCounts(write_call_count=1,) + # no changes except on last item + self.assertItemFieldsModified(list(self.album.items())[:-1], + self.items_orig[:-1], []) + self.assertEqual(list(self.album.items())[-1].title, + u'modified t\u00eftle 9') def test_noedit(self): """Do not edit anything.""" @@ -134,6 +170,24 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') + self.assertItemFieldsModified(self.album.items(), self.items_orig, []) + + def test_album_edit_apply(self): + """Edit the album field for all items in the library, apply changes + + TODO: decide if the plugin should be wise enough to update the album, + and handle other complex cases (create new albums, etc). At the moment + this test only checks for modifications on items. + """ + # edit album + self.run_mocked_command({'replacements': {u'\u00e4lbum': + u'modified \u00e4lbum'}}, + # edit? y, done? y, modify? y + ['y', 'y', 'y']) + + self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['album']) def test_malformed_yaml_discard(self): """Edit the yaml file incorrectly (resulting in a malformed yaml From 17dcc7ab214886c37ec903322f05c18c036b582f Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Wed, 11 Nov 2015 08:54:58 +0100 Subject: [PATCH 0159/2280] Fixed two typos in the embyupdate docs --- docs/plugins/embyupdate.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index 2a47826ae..3e4c9687f 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -28,6 +28,6 @@ The available options under the ``emby:`` section are: - **host**: The Emby server name. Default: ``localhost`` - **port**: The Emby server port. - Defailt: 8096 + Default: 8096 - **username**: A username of a Emby user that is allowed to refresh the library. -- **password**: That users password. +- **password**: That user's password. From d9ebb3409a335dec386763c2f6c61adf70018ef7 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 11 Nov 2015 15:50:32 +0100 Subject: [PATCH 0160/2280] edit: add album query tests, revise failing ones * Add tests for executing the command with album queries (-a), testing the edit of album and albumartist fields. * Revise invalid and malformed yaml tests so they return a failure instead of an error. --- test/test_edit.py | 65 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 14 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 702830613..f853df6a3 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -22,6 +22,7 @@ from test.helper import TestHelper, control_stdin from beets import library from beetsplug.edit import EditPlugin +from beets.ui import UserError class ModifyFileMocker(object): @@ -91,12 +92,13 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def run_mocked_command(self, modify_file_args={}, stdin=[]): - """Run the edit command, with mocked stdin and yaml writing.""" + def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]): + """Run the edit command, with mocked stdin and yaml writing, and + passing `args` to `run_command`.""" m = ModifyFileMocker(**modify_file_args) with patch.object(EditPlugin, 'get_editor', side_effect=m.action): with control_stdin('\n'.join(stdin)): - self.run_command('edit') + self.run_command('edit', *args) def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, write_call_count=TRACK_COUNT, title_starts_with=''): @@ -173,11 +175,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertItemFieldsModified(self.album.items(), self.items_orig, []) def test_album_edit_apply(self): - """Edit the album field for all items in the library, apply changes - - TODO: decide if the plugin should be wise enough to update the album, - and handle other complex cases (create new albums, etc). At the moment - this test only checks for modifications on items. + """Edit the album field for all items in the library, apply changes. + By design, the album should not be updated."" """ # edit album self.run_mocked_command({'replacements': {u'\u00e4lbum': @@ -188,6 +187,37 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) + # ensure album is *not* modified + self.album.load() + self.assertEqual(self.album.album, u'\u00e4lbum') + + def test_a_album_edit_apply(self): + """Album query (-a), edit album field, apply changes.""" + self.run_mocked_command({'replacements': {u'\u00e4lbum': + u'modified \u00e4lbum'}}, + # edit? y, done? y, modify? y + ['y', 'y', 'y'], + args=['-a']) + + self.album.load() + self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertEqual(self.album.album, u'modified \u00e4lbum') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['album']) + + def test_a_albumartist_edit_apply(self): + """Album query (-a), edit albumartist field, apply changes.""" + self.run_mocked_command({'replacements': {u'album artist': + u'modified album artist'}}, + # edit? y, done? y, modify? y + ['y', 'y', 'y'], + args=['-a']) + + self.album.load() + self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertEqual(self.album.albumartist, u'the modified album artist') + self.assertItemFieldsModified(self.album.items(), self.items_orig, + ['albumartist']) def test_malformed_yaml_discard(self): """Edit the yaml file incorrectly (resulting in a malformed yaml @@ -197,9 +227,12 @@ class EditCommandTest(unittest.TestCase, TestHelper): "fix?" -> "ok.fixed." prompt loop unless he is able to provide a well-formed yaml.""" # edit the yaml file to an invalid file - self.run_mocked_command({'contents': '!MALFORMED'}, - # edit? n, done? y, fix? n - ['y', 'y', 'n']) + try: + self.run_mocked_command({'contents': '!MALFORMED'}, + # edit? y, done? y, fix? n + ['y', 'y', 'n']) + except UserError as e: + self.fail(repr(e)) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') @@ -211,9 +244,13 @@ class EditCommandTest(unittest.TestCase, TestHelper): TODO: this test currently fails, on purpose. `check_diff()` chokes ungracefully""" # edit the yaml file to an invalid file - self.run_mocked_command({'contents': 'wellformed: yes, but invalid'}, - # edit? n, done? y - ['y', 'y']) + try: + self.run_mocked_command({'contents': + 'wellformed: yes, but invalid'}, + # edit? y, done? y + ['y', 'y']) + except KeyError as e: + self.fail(repr(e)) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') From 386578d69c1b92646397de2af3fed5d44b0c2811 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Fri, 13 Nov 2015 11:24:19 +0100 Subject: [PATCH 0161/2280] change opts.extra to type choice --- beetsplug/edit.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 62dcd8bdc..406cffc65 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -101,7 +101,10 @@ class EditPlugin(plugins.BeetsPlugin): help='interactively edit metadata') edit_command.parser.add_option( '-e', '--extra', - action='store', + action='append', + type='choice', + choices=library.Item.all_keys() + + library.Album.all_keys(), help='add additional fields to edit', ) edit_command.parser.add_option( @@ -188,8 +191,7 @@ class EditPlugin(plugins.BeetsPlugin): self.fields = self.albumfields if opts.album else self.itemfields # if opts.extra is given add those if opts.extra: - fi = (opts.extra).replace('$', "").split() - self.fields.extend([f for f in fi if f not in self.fields]) + self.fields.extend([f for f in opts.extra if f not in self.fields]) # make sure we got the id for identification if 'id' not in self.fields: self.fields.insert(0, 'id') From 024ab0159b1768b1bc8e3b3325713215d0106b9f Mon Sep 17 00:00:00 2001 From: jmwatte Date: Fri, 13 Nov 2015 15:03:27 +0100 Subject: [PATCH 0162/2280] remove webbrowser for opening default editor/browser --- beetsplug/edit.py | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 406cffc65..1d982a04c 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -12,8 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""Open metadata information in a text editor to let the user change -them directly. +"""Open metadata information in a text editor to let the user edit it. """ from __future__ import (division, absolute_import, print_function, unicode_literals) @@ -25,13 +24,13 @@ import subprocess import difflib import yaml import collections -import webbrowser from contextlib import nested from sys import exit from beets import config from beets import ui from tempfile import NamedTemporaryFile import os +import sys class EditPlugin(plugins.BeetsPlugin): @@ -98,7 +97,8 @@ class EditPlugin(plugins.BeetsPlugin): def commands(self): edit_command = Subcommand( 'edit', - help='interactively edit metadata') + help='interactively edit metadata' + ) edit_command.parser.add_option( '-e', '--extra', action='append', @@ -286,14 +286,25 @@ class EditPlugin(plugins.BeetsPlugin): os.remove(new.name) exit() + def open_file(self, startcmd): + # opens a file in the standard program on all systems + subprocess.call(('cmd /c start "" "' + startcmd + '"') + if os.name is 'nt' else ( + 'open' if sys.platform.startswith('darwin') else + 'xdg-open', startcmd)) + def get_editor(self, name): if not self.ed: + # if not specified in config use $EDITOR from system editor = os.getenv('EDITOR') if editor: os.system(editor + " " + name) else: - webbrowser.open(name, new=2, autoraise=True) + # let the system handle the file + self.open_file(name) + # webbrowser.open(name, new=2, autoraise=True) else: + # use the editor specified in config callmethod = [self.ed] if self.ed_args: callmethod.extend(self.ed_args) @@ -416,17 +427,22 @@ class EditPlugin(plugins.BeetsPlugin): diff = difflib.HtmlDiff() df = diff.make_file(newlines, oldlines) - with NamedTemporaryFile('w', suffix='.html', bufsize=0) as ht: + with NamedTemporaryFile( + 'w', suffix='.html', bufsize=0, delete=False) as ht: # TODO: if webbrowser.open() is not blocking, ht might be deleted - # too soon - need to test + # too soon - need to test aded delete=false otherwise file is gone + # before the browser picks it up ht.write(df) if not self.brw: + # if browser not in config get $BROWSER browser = os.getenv('BROWSER') if browser: os.system(browser + " " + ht.name) else: - webbrowser.open(ht.name, new=2, autoraise=True) + # let the system handle it + self.open_file(ht.name) else: + # use browser specified in config callmethod = [self.brw] if self.brw_args: callmethod.extend(self.brw_args) From 5eca75321e27f4cab3a76e84ee70ff0a79b4ea0d Mon Sep 17 00:00:00 2001 From: jmwatte Date: Fri, 13 Nov 2015 17:56:03 +0100 Subject: [PATCH 0163/2280] simplify by removing sum-option and renaming for clarity --- beetsplug/edit.py | 179 ++++++++++++++-------------------------------- 1 file changed, 54 insertions(+), 125 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 1d982a04c..d39c1ca6b 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -39,18 +39,14 @@ class EditPlugin(plugins.BeetsPlugin): super(EditPlugin, self).__init__() self.config.add({ - 'style': 'yaml', 'editor': '', 'diff_method': '', 'browser': '', 'albumfields': 'album albumartist', 'itemfields': 'track title artist album', 'not_fields': 'id path', - 'sep': '-', }) - self.style = self.config['style'].get(unicode) - # The editor field in the config lets you specify your editor. # Defaults to open with webrowser module. self.editor = self.config['editor'].as_str_seq() @@ -85,10 +81,6 @@ class EditPlugin(plugins.BeetsPlugin): # value. The ID of an item will never be changed. self.not_fields = self.config['not_fields'].as_str_seq() - # the separator in your config sets the separator that will be used - # between fields in your terminal. Defaults to - - self.sep = self.config['sep'].get(unicode) - self.ed = None self.ed_args = None self.brw = None @@ -112,11 +104,6 @@ class EditPlugin(plugins.BeetsPlugin): action='store_true', dest='all', help='edit all fields', ) - edit_command.parser.add_option( - '--sum', - action='store_true', dest='sum', - help='list fields with the same value', - ) edit_command.parser.add_all_common_options() edit_command.func = self.editor_music return[edit_command] @@ -129,23 +116,6 @@ class EditPlugin(plugins.BeetsPlugin): self.brw_args = self.browser[1:] if len(self.browser) > 1 else None self.brw = self.browser[0] if self.browser else None - # Get the objects to edit. - query = decargs(args) - items, albums = _do_query(lib, query, opts.album, False) - objs = albums if opts.album else items - if not objs: - print_('Nothing to edit.') - return - - # edit tags in a textfile in yaml-style - # makes a string representation of an object - # for now yaml but we could add html,pprint,toml - self.print_items = { - 'yaml': self.print_to_yaml} - # makes an object from a string representation - # for now yaml but we could add html,pprint,toml - self.string_to_dict = { - 'yaml': self.yaml_to_dict} # 4 ways to view the changes in objects self.diffresults = { 'ndiff': self.ndiff, @@ -157,16 +127,24 @@ class EditPlugin(plugins.BeetsPlugin): self.make_dict = { 'all': self.get_all_fields, "selected": self.get_selected_fields} - + # main program flow + # Get the objects to edit. + query = decargs(args) + items, albums = _do_query(lib, query, opts.album, False) + objs = albums if opts.album else items + if not objs: + print_('Nothing to edit.') + return + # get the fields the user wants self.get_fields_from(objs, opts) - - # Confirm. + # Confirmation from user about the queryresult for obj in objs: print_(format(obj)) if not ui.input_yn(ui.colorize('action_default', "Edit? (y/n)"), True): return - + # get the fields from the objects dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) + # present the yaml to the user and let her change it newyaml, oldyaml = self.change_objs(dict_from_objs) changed_objs = self.check_diff(newyaml, oldyaml, opts) if not changed_objs: @@ -203,6 +181,7 @@ class EditPlugin(plugins.BeetsPlugin): else: for it in self.fields: if opts.album: + # check if it is really an albumfield if it not in library.Album.all_keys(): print_( "{} not in albumfields.Removed it.".format( @@ -210,6 +189,7 @@ class EditPlugin(plugins.BeetsPlugin): 'text_warning', it))) self.fields.remove(it) else: + # if it is not an itemfield remove it if it not in library.Item.all_keys(): print_( "{} not in itemfields.Removed it.".format( @@ -219,58 +199,34 @@ class EditPlugin(plugins.BeetsPlugin): self.pick = "selected" def get_selected_fields(self, myfields, objs, opts): - a = [] - if opts.sum: - for field in myfields: - if field not in self.not_fields: - d = collections.defaultdict(str) - for obj in objs: - d[obj[field]] += (" " + str(obj['id'])) - a.append([field, [{f: i} for f, i in d.items()]]) - return a - else: - for mod in objs: - a.append([{fi: mod[fi]}for fi in myfields]) - return a + return [[{field: obj[field]}for field in myfields]for obj in objs] def get_all_fields(self, myfields, objs, opts): - a = [] - if opts.sum: - fields = (library.Album.all_keys() if opts.album - else library.Item.all_keys()) - for field in sorted(fields): - # for every field get a dict - d = collections.defaultdict(str) - for obj in objs: - # put all the ob-ids in the dict[field] as a string - d[obj[field]] += (" " + str(obj['id'])) - # for the field, we get the value and the users - a.append([field, [{f: i} for f, i in sorted(d.items())]]) - return a - else: - for mod in objs: - a.append([{fi: mod[fi]} for fi in sorted(mod._fields)]) - return a + return [[{field: obj[field]}for field in sorted(obj._fields)] + for obj in objs] def change_objs(self, dict_items): # construct a yaml from the original object-fields # and make a yaml that we can change in the text-editor - oldyaml = self.print_items[self.style](dict_items) - newyaml = self.print_items[self.style](dict_items) + oldyaml = self.print_to_yaml(dict_items) # our backup + newyaml = self.print_to_yaml(dict_items) # goes to user new = NamedTemporaryFile(suffix='.yaml', delete=False) new.write(newyaml) new.close() self.get_editor(new.name) - + # wait for user to edit yaml and continue if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): while True: try: + # reading the yaml back in with open(new.name) as f: newyaml = f.read() list(yaml.load_all(newyaml)) os.remove(new.name) break except yaml.YAMLError as e: + # some error-correcting mainly for empty-values + # not being well-formated print_(ui.colorize('text_warning', "change this fault: {}".format(e))) print_("correct format for empty = - '' :") @@ -280,7 +236,7 @@ class EditPlugin(plugins.BeetsPlugin): if ui.input_yn(ui.colorize( 'action_default', "ok.fixed.(y)"), True): pass - + # only continue when all the mistakes are corrected return newyaml, oldyaml else: os.remove(new.name) @@ -311,53 +267,48 @@ class EditPlugin(plugins.BeetsPlugin): callmethod.append(name) subprocess.check_call(callmethod) - def same_format(self, newset, opts): - alld = collections.defaultdict(dict) - if opts.sum: - for o in newset: - for so in o: - ids = set((so[1].values()[0].split())) - for id_ in ids: - alld[id_].update( - {so[0].items()[0][1]: so[1].items()[0][0]}) - else: - for o in newset: - for so in o: - alld[o[0].values()[0]].update(so) - return alld + def nice_format(self, newset): + # format the results so that we have an ID at the top + # that we can change to a userfrienly title/artist format + # when we present our results + wellformed = collections.defaultdict(dict) + for item in newset: + for field in item: + wellformed[item[0].values()[0]].update(field) + return wellformed def save_items(self, oldnewlist, lib, opts): oldset, newset = zip(*oldnewlist) - no = self.same_format(newset, opts) - oo = self.same_format(oldset, opts) - ono = zip(oo.items(), no.items()) - nl = [] - ol = [] - changedob = [] - for o, n in ono: + niceNewSet = self.nice_format(newset) + niceOldSet = self.nice_format(oldset) + niceCombiSet = zip(niceOldSet.items(), niceNewSet.items()) + newSetTitled = [] + oldSetTitled = [] + changedObjs = [] + for o, n in niceCombiSet: if opts.album: ob = lib.get_album(int(n[0])) else: ob = lib.get_item(n[0]) # change id to item-string - ol.append((format(ob),) + o[1:]) - ob.update(n[1]) - nl.append((format(ob),) + n[1:]) - changedob.append(ob) + oldSetTitled.append((format(ob),) + o[1:]) + ob.update(n[1]) # update the object + newSetTitled.append((format(ob),) + n[1:]) + changedObjs.append(ob) # see the changes we made if self.diff_method: - ostr = self.print_items[self.style](ol) - nwstr = self.print_items[self.style](nl) + ostr = self.print_to_yaml(oldSetTitled) + nwstr = self.print_to_yaml(newSetTitled) self.diffresults[self.diff_method](ostr, nwstr) else: - for obj in changedob: + for obj in changedObjs: ui.show_model_changes(obj) - self.save_write(changedob) + self.save_write(changedObjs) def save_write(self, changedob): - if not ui.input_yn(ui.colorize('action_default', - 'really modify? (y/n)')): + if not ui.input_yn( + ui.colorize('action_default', 'really modify? (y/n)')): return for ob in changedob: @@ -371,31 +322,9 @@ class EditPlugin(plugins.BeetsPlugin): def check_diff(self, newyaml, oldyaml, opts): # make python objs from yamlstrings - nl = self.string_to_dict[self.style](newyaml) - ol = self.string_to_dict[self.style](oldyaml) - if opts.sum: - return filter(None, map(self.reduce_sum, ol, nl)) - else: - return filter(None, map(self.reduce_it, ol, nl)) - - def reduce_sum(self, ol, nl): - # only get the changed objs - if ol != nl: - sol = [i for i in ol[1]] - snl = [i for i in nl[1]] - a = filter(None, map(self.reduce_sub, sol, snl)) - header = {"field": ol[0]} - ol = [[header, b[0]] for b in a] - nl = [[header, b[1]] for b in a] - return ol, nl - - def reduce_sub(self, sol, snl): - # if the keys have changed resets them - if sol != snl: - if snl.values() != sol.values(): - snl[snl.keys()[0]] = sol[sol.keys()[0]] - if sol != snl: - return sol, snl + nl = self.yaml_to_dict(newyaml) + ol = self.yaml_to_dict(oldyaml) + return filter(None, map(self.reduce_it, ol, nl)) def reduce_it(self, ol, nl): # if there is a forbidden field it resets them @@ -404,7 +333,7 @@ class EditPlugin(plugins.BeetsPlugin): if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: nl[x] = ol[x] print_("reset forbidden field.") - if ol != nl: + if ol != nl: # only keep objects that have changed return ol, nl def ndiff(self, newfilestr, oldfilestr): From 9c968456c1bc1e855d17d204be256c0df3a67afe Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 13 Nov 2015 12:21:36 -0800 Subject: [PATCH 0164/2280] Fix #1666: malformed binary data in SoundCheck --- beets/mediafile.py | 4 ++-- docs/changelog.rst | 2 ++ test/rsrc/soundcheck-nonascii.m4a | Bin 0 -> 5862 bytes test/test_mediafile_edge.py | 15 +++++++++++---- 4 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 test/rsrc/soundcheck-nonascii.m4a diff --git a/beets/mediafile.py b/beets/mediafile.py index 64ab49ac2..5fe1fa308 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -215,9 +215,9 @@ def _sc_decode(soundcheck): # SoundCheck tags consist of 10 numbers, each represented by 8 # characters of ASCII hex preceded by a space. try: - soundcheck = soundcheck.replace(' ', '').decode('hex') + soundcheck = soundcheck.replace(b' ', b'').decode('hex') soundcheck = struct.unpack(b'!iiiiiiiiii', soundcheck) - except (struct.error, TypeError, UnicodeEncodeError): + except (struct.error, TypeError): # SoundCheck isn't in the format we expect, so return default # values. return 0.0, 0.0 diff --git a/docs/changelog.rst b/docs/changelog.rst index 27567f283..700a16d6d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -56,6 +56,8 @@ Fixes: * :doc:`/plugins/duplicates`: Fix a crash when merging items. :bug:`1699` * :doc:`/plugins/smartplaylist`: More gracefully handle malformed queries and missing configuration. +* Fix a crash with some files with unreadable iTunes SoundCheck metadata. + :bug:`1666` .. _Emby Server: http://emby.media diff --git a/test/rsrc/soundcheck-nonascii.m4a b/test/rsrc/soundcheck-nonascii.m4a new file mode 100644 index 0000000000000000000000000000000000000000..29f5de5310f799d5f17514d280f32d4cab82f9cd GIT binary patch literal 5862 zcmZQzU{FXasVwj{aa3SnU|;~zxdkRhnZ^0JAU*>FPgib!ei;J;Lr!j4MhZymh|kOT zBR=mL7#P;LFfi<3U|<9zkQ4+nLMS+i#&>{AU}Z2dFfcWi6eVUeFfhcFWP|NwN7xCn z4Ww@eh=60T6<`7`gytv)22^{QWOGw86G8sZO#$1%fUpDNuh1i4vy?JYa*Dt#1_p-W z{L(xa8%8r;&dtnAV_;wqD9(kL1eH-qfr!hb6s3aXLBb$6@{|_kfI=G-ZqtiPl5!Xr z7}ASNiov1F0C9JCZh;BNbuc|3nt_3dK>)-6xsQQ?!8o-zr5MC#ZfIywVqjokX=rE= zaS&yYU|?X7t6*UG#lYIo(7+_b!Pd~wz{teFz#vgvQUcZjwMLJDfdyoOMsZ1TGKj$d zvIOD;QK%YbkjYT?nc|Y-DyTXTr3aPcV_;w~f?|0F1_qF8KvGpD$Ofq_A0WnLmE`-r3@ zf^~x;ogu9>2c%kQrDISC0|SE;vRp|NhVmg%F6O0uqo&&lJj#5@{3bJiBWN7 zVonkR1A`>Gn#7!>Qjpb(E7Ma!DHTIOdTL%#Dk#~P6lH@HNI*@1_yQFBp!jBBkW0xd z24z7pGG6|h+xQk0mSjm2JzBnt~8 zQ*%>Y1B*mcT@w>iBi%&vM04Hbq$G<(LsMhJG)qt*lWngfC^=)X*D}?@+}Og@Qr99e z(L~q8+|ocd$I%R3XsEA!2kp- zU0fgxM`sAb#MsyzEMj72;0$6ISsEFcfEh*x&c+~yfw`NT8w$hF&Dq=uBx2}l>IzD# z@AvOzU|`rosyl;y1DqHb7+NshX<%RgGT*?!!UW1NHU~Qo3Ag=->} z0V?WO=2U`;B#Z(rr?MzB8C2P*tW3_uRiNdj=7B3Dm6hp5pt3;**+-yaF}*0iv>-Dt z9aJ$SLW)iWbT!~Y4_<&W-$*M;1*JMr(K3ohLtr!nhD8W4i;U*$VG)s|o}gL?uxsR| zB$hB-U|?sI6K#GIv)a(m`iKqd0frx<%}Y!qTKE?vcuq)rkUBk1{K0#<{s0yO3eLF z=H-ZN>wbDgX5yDv<_~^8{U;SBH-PLo6yVYjB5*XTQL<+P*9HO)-TX7K}H6^E+E&Kz6Cx5h zw#}Sz@@Js+>H`~Rbi8=L@J+ONk&;3S-#IqUzUvHJpVJtt3pqK;qb46&U|hwxKTTQF z?`EMo$R!|U{Mo0A#P;62wwO0vuz&eq^(n7-L^Uh5md&{JZMV*bb6YFe7K-tKYy~SW z;%##hhzN5Ndh^CSFXQ|&8NYcoRjOZ7MGY82Q`fET;hqDszR5|Vg`XupLDKSR{-O_F zYh9`g)@y$H@lfivp!-qg(xOcdz^)GBP?VVM$g*PjJz-v`))byCkr*AR<|5%TzID>acNlQM(vF`GMyG6 zQ;!%6C>APU#o(E-TyDF1`Bo*6ue~x*I^smIQJrd*mc+?Krr1 zsgT5J@8z0-nyyVBzuK|+Z#wj4eejiK>>y>wlq8e`IB%yEoR*ru|F+S~wROd}Ph5WA zs~+&~jqO>rKZ-ISRYwBc8EpCt{O-z} zp@Uy1hr79O&y`&^jce>)d^oH2{_wnIUdFXkV}()z8$=qwK3J6CwqSvUr}ngMR*4U% zSsN@pZkH=#XMNvy-`m^$^RM$R)fY+!8Mvgtu7TlRQgCvnO6W)n|+N} zN~mve)PAAXlBUppO@pBT9PdH~iYW(}7fo7k#jm=^d4r{>)8==4+OhwPquQi*zDV{e zYCFWTjj#3-yl2vh`iz7Ai!I85_Nuq;)iGk&uNy>f~w=17nQzdsR ze71E7ucNMEO6C12#!KQBK$4J>g3=oXw@2k~_WWwm*~+}5sO#UFtYXzE^Dn(EzL_>J zwZL`{$el|P+<6+991c9bWNQClk3_=M8$yjIh0pqKI`Qq;-$JpB@1D1{6T5zAR^MyG0$BXzl(kSRtdP z`8HTab=omg_M%sN7v>xNJvA%RmZ+TSjom<>4UoPdky;C=ePcQ_w;{5rBR7o z+0i(EO+^Kk0~R2~O9~`f*bC$pST;Nme0f^3#5t{Dl}+EB$h@-wiGPCLiWYB`;#<6} z%}{*Kyv$=doI5~z7A3e#FthI5UsYxI^m5tjR*gIV|GP(eZE3ZgA-yR7dCu{0kg6rd z3Ia|{7mV+)1ZGJ1Tsx+s|EfL7=6l`dtro9;-##}hxOZ)yR@T>u)T7tUCn*cCh&=%3 zJSB}5K8G9Z!n}?tD+II-C43gFzp4JPW6i;J$@$yu!hQ=qPvlYCs=7c1Y)67y6Yrvp zPwrPdu4UO_^P1_@pR@qMXro)qh5QjxPxR`$)IGNrfN~4Cv|1veb@|4uYwEAMj-L#g zS;ZKgfA{j5w~0+H`=&%34>l4lPzM+K$BYCN7l^RDjQVh|V$;@rKi~XPS-C$fZ;NV{ z#^*4p1LBa_aBFI8_|`Yqt<7O}a&7Gg=R?9qc9OSkjy?A`U97k>@Sc8pkxTyvkljlX zIRu=T9!P(YXcsYJ?%Wcr5huMainTwb{zLV$fW{^BS?fA)-kz~+q8S%M@GfwPxkyBz zMNlU}bdRoKx!*ko#{-gQr$hvJXDlrDzRjvEEX-^m6SO9BW5irtu!|QZxK7|wI_jBQ zxWuk}(Fwz1(`v Date: Sat, 14 Nov 2015 12:50:53 -0800 Subject: [PATCH 0165/2280] Remove some communication through fields This is the first of many changes to reduce the use of `self.x` where plain parameter passing can make things more clear. --- beetsplug/edit.py | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index d39c1ca6b..6f7b7a419 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -106,7 +106,7 @@ class EditPlugin(plugins.BeetsPlugin): ) edit_command.parser.add_all_common_options() edit_command.func = self.editor_music - return[edit_command] + return [edit_command] def editor_music(self, lib, opts, args): if self.editor: @@ -122,11 +122,7 @@ class EditPlugin(plugins.BeetsPlugin): 'unified': self.unified, 'html': self.html, 'vimdiff': self.vimdiff} - # make a dictionary from the chosen fields - # you can do em all or a selection - self.make_dict = { - 'all': self.get_all_fields, - "selected": self.get_selected_fields} + # main program flow # Get the objects to edit. query = decargs(args) @@ -135,17 +131,21 @@ class EditPlugin(plugins.BeetsPlugin): if not objs: print_('Nothing to edit.') return - # get the fields the user wants - self.get_fields_from(objs, opts) # Confirmation from user about the queryresult for obj in objs: print_(format(obj)) if not ui.input_yn(ui.colorize('action_default', "Edit? (y/n)"), True): return + # get the fields from the objects - dict_from_objs = self.make_dict[self.pick](self.fields, objs, opts) + if opts.all: + data = self.get_all_fields(objs) + else: + fields = self.get_fields_from(objs, opts) + data = self.get_selected_fields(fields, objs, opts) + # present the yaml to the user and let her change it - newyaml, oldyaml = self.change_objs(dict_from_objs) + newyaml, oldyaml = self.change_objs(data) changed_objs = self.check_diff(newyaml, oldyaml, opts) if not changed_objs: print_("nothing to change") @@ -166,20 +166,19 @@ class EditPlugin(plugins.BeetsPlugin): def get_fields_from(self, objs, opts): # construct a list of fields we need # see if we need album or item fields - self.fields = self.albumfields if opts.album else self.itemfields + fields = self.albumfields if opts.album else self.itemfields # if opts.extra is given add those if opts.extra: - self.fields.extend([f for f in opts.extra if f not in self.fields]) + fields.extend([f for f in opts.extra if f not in fields]) # make sure we got the id for identification - if 'id' not in self.fields: - self.fields.insert(0, 'id') + if 'id' not in fields: + fields.insert(0, 'id') # we need all the fields if opts.all: - self.fields = None - self.pick = "all" + fields = None print_(ui.colorize('text_warning', "edit all fields from:")) else: - for it in self.fields: + for it in fields: if opts.album: # check if it is really an albumfield if it not in library.Album.all_keys(): @@ -187,7 +186,7 @@ class EditPlugin(plugins.BeetsPlugin): "{} not in albumfields.Removed it.".format( ui.colorize( 'text_warning', it))) - self.fields.remove(it) + fields.remove(it) else: # if it is not an itemfield remove it if it not in library.Item.all_keys(): @@ -195,13 +194,14 @@ class EditPlugin(plugins.BeetsPlugin): "{} not in itemfields.Removed it.".format( ui.colorize( 'text_warning', it))) - self.fields.remove(it) - self.pick = "selected" + fields.remove(it) + + return fields def get_selected_fields(self, myfields, objs, opts): return [[{field: obj[field]}for field in myfields]for obj in objs] - def get_all_fields(self, myfields, objs, opts): + def get_all_fields(self, objs): return [[{field: obj[field]}for field in sorted(obj._fields)] for obj in objs] From d7d609442ec60d9fd0ed4892a489ed162a2b2328 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 12:53:45 -0800 Subject: [PATCH 0166/2280] Remove diff_method option Our built-in "diff"-like functionality is pretty good because it's aware of beets' data structures and types. This makes it more legible, in my opinion, than an ordinary textual diff. So for now, I'm making this the only option (in the spirit of making the plugin as straightforward as humanly possible). --- beetsplug/edit.py | 27 ++++----------------------- docs/plugins/edit.rst | 7 ------- 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 6f7b7a419..9ef37bd17 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -40,7 +40,6 @@ class EditPlugin(plugins.BeetsPlugin): self.config.add({ 'editor': '', - 'diff_method': '', 'browser': '', 'albumfields': 'album albumartist', 'itemfields': 'track title artist album', @@ -55,14 +54,6 @@ class EditPlugin(plugins.BeetsPlugin): # your htmlviewer. Defaults to open with webrowser module self.browser = self.config['browser'].as_str_seq() - # the diff_method field in your config picks the way to see your - # changes. Options are: - # 'ndiff'(2 files with differences), - # 'unified'(just the different lines and a few lines of context), - # 'html'(view in html-format), - # 'vimdiff'(view in VIM) - self.diff_method = self.config['diff_method'].get(unicode) - # the albumfields field in your config sets the tags that # you want to see/change for albums. # Defaults to album albumartist. @@ -116,13 +107,6 @@ class EditPlugin(plugins.BeetsPlugin): self.brw_args = self.browser[1:] if len(self.browser) > 1 else None self.brw = self.browser[0] if self.browser else None - # 4 ways to view the changes in objects - self.diffresults = { - 'ndiff': self.ndiff, - 'unified': self.unified, - 'html': self.html, - 'vimdiff': self.vimdiff} - # main program flow # Get the objects to edit. query = decargs(args) @@ -296,14 +280,11 @@ class EditPlugin(plugins.BeetsPlugin): ob.update(n[1]) # update the object newSetTitled.append((format(ob),) + n[1:]) changedObjs.append(ob) + # see the changes we made - if self.diff_method: - ostr = self.print_to_yaml(oldSetTitled) - nwstr = self.print_to_yaml(newSetTitled) - self.diffresults[self.diff_method](ostr, nwstr) - else: - for obj in changedObjs: - ui.show_model_changes(obj) + for obj in changedObjs: + ui.show_model_changes(obj) + self.save_write(changedObjs) def save_write(self, changedob): diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 3b48635c4..144d71b74 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -52,7 +52,6 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` edit: editor: nano -w -p - diff_method: html browser: firefox -private-window albumfields: genre album itemfields: track artist @@ -61,12 +60,6 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` * ``editor:`` pick your own texteditor; add arguments if needed. If no``editor:`` then your system opens the file-extension. -* ``diff_method:`` 4 choices. With no ``diff_method:`` you get the beets way of showing differences. - - ``ndiff``: you see original and the changed yamls with the changes. - - ``unified``: you see the changes with a bit of context. Simple and compact. - - ``html``: a html file that you can open in a browser. Looks nice. - - ``vimdiff``: gives you VIM with the diffs.You need VIM for this. - * ``browser:`` If you pick ``diff_method:html`` you can specify a viewer for it (if needed add arguments). If not, let your system open the file-extension. From e235cb7c42fd236a03aa4608d8c5db7de012fed5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 12:56:31 -0800 Subject: [PATCH 0167/2280] Remove vestiges of diff_method option --- beetsplug/edit.py | 67 ------------------------------------------- docs/plugins/edit.rst | 6 +--- 2 files changed, 1 insertion(+), 72 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 9ef37bd17..f68523129 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -21,10 +21,8 @@ from beets import plugins from beets.ui import Subcommand, decargs, library, print_ from beets.ui.commands import _do_query import subprocess -import difflib import yaml import collections -from contextlib import nested from sys import exit from beets import config from beets import ui @@ -40,20 +38,14 @@ class EditPlugin(plugins.BeetsPlugin): self.config.add({ 'editor': '', - 'browser': '', 'albumfields': 'album albumartist', 'itemfields': 'track title artist album', 'not_fields': 'id path', }) # The editor field in the config lets you specify your editor. - # Defaults to open with webrowser module. self.editor = self.config['editor'].as_str_seq() - # the html_viewer field in your config lets you specify - # your htmlviewer. Defaults to open with webrowser module - self.browser = self.config['browser'].as_str_seq() - # the albumfields field in your config sets the tags that # you want to see/change for albums. # Defaults to album albumartist. @@ -74,8 +66,6 @@ class EditPlugin(plugins.BeetsPlugin): self.ed = None self.ed_args = None - self.brw = None - self.brw_args = None def commands(self): edit_command = Subcommand( @@ -103,9 +93,6 @@ class EditPlugin(plugins.BeetsPlugin): if self.editor: self.ed_args = self.editor[1:] if len(self.editor) > 1 else None self.ed = self.editor[0] if self.editor else None - if self.browser: - self.brw_args = self.browser[1:] if len(self.browser) > 1 else None - self.brw = self.browser[0] if self.browser else None # main program flow # Get the objects to edit. @@ -242,7 +229,6 @@ class EditPlugin(plugins.BeetsPlugin): else: # let the system handle the file self.open_file(name) - # webbrowser.open(name, new=2, autoraise=True) else: # use the editor specified in config callmethod = [self.ed] @@ -316,56 +302,3 @@ class EditPlugin(plugins.BeetsPlugin): print_("reset forbidden field.") if ol != nl: # only keep objects that have changed return ol, nl - - def ndiff(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.ndiff(newlines, oldlines) - print_('\n'.join(list(diff))) - return - - def unified(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.unified_diff(newlines, oldlines, lineterm='') - print_('\n'.join(list(diff))) - return - - def html(self, newfilestr, oldfilestr): - newlines = newfilestr.splitlines() - oldlines = oldfilestr.splitlines() - diff = difflib.HtmlDiff() - df = diff.make_file(newlines, oldlines) - - with NamedTemporaryFile( - 'w', suffix='.html', bufsize=0, delete=False) as ht: - # TODO: if webbrowser.open() is not blocking, ht might be deleted - # too soon - need to test aded delete=false otherwise file is gone - # before the browser picks it up - ht.write(df) - if not self.brw: - # if browser not in config get $BROWSER - browser = os.getenv('BROWSER') - if browser: - os.system(browser + " " + ht.name) - else: - # let the system handle it - self.open_file(ht.name) - else: - # use browser specified in config - callmethod = [self.brw] - if self.brw_args: - callmethod.extend(self.brw_args) - callmethod.append(ht.name) - subprocess.call(callmethod) - - return - - def vimdiff(self, newstringstr, oldstringstr): - with nested(NamedTemporaryFile(suffix='.old.yaml', - bufsize=0), - NamedTemporaryFile(suffix='.new.yaml', - bufsize=0)) as (newdiff, olddiff): - newdiff.write(newstringstr) - olddiff.write(oldstringstr) - subprocess.call(['vimdiff', newdiff.name, olddiff.name]) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 144d71b74..85d7343fc 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -52,7 +52,6 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` edit: editor: nano -w -p - browser: firefox -private-window albumfields: genre album itemfields: track artist not_fields: id path @@ -60,9 +59,6 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` * ``editor:`` pick your own texteditor; add arguments if needed. If no``editor:`` then your system opens the file-extension. -* ``browser:`` - If you pick ``diff_method:html`` you can specify a viewer for it (if needed add arguments). If not, let your system open the file-extension. - * The ``albumfields:`` and ``itemfields:`` lets you list the fields you want to change. ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields do the ``beet fields`` command. @@ -76,7 +72,7 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` -02-The Night Before-The Beatles-Help! - + but you can pick anything else. With "<>" it will look like: :: From d5b7ce64da65dcacd99207bcdf11fc6f2703d879 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:05:06 -0800 Subject: [PATCH 0168/2280] Move EDITOR discovery to a util function --- beets/ui/commands.py | 2 +- beets/util/__init__.py | 42 +++++++++++++++++++++++++----------------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index fa2fc84af..307945a03 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1473,7 +1473,7 @@ def config_edit(): An empty config file is created if no existing config file exists. """ path = config.user_config_path() - editor = os.environ.get('EDITOR') + editor = util.editor_command() try: if not os.path.isfile(path): open(path, 'w+').close() diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 61e2f4ac8..a2a5688b5 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -736,28 +736,36 @@ def open_anything(): return base_cmd -def interactive_open(targets, command=None): - """Open the files in `targets` by `exec`ing a new command. (The new - program takes over, and Python execution ends: this does not fork a - subprocess.) +def editor_command(): + """Get a command for opening a text file. - If `command` is provided, use it. Otherwise, use an OS-specific - command (from `open_anything`) to open the file. + Use the `EDITOR` environment variable by default. If it is not + present, fall back to `open_anything()`, the platform-specific tool + for opening files in general. + """ + editor = os.environ.get('EDITOR') + if editor: + return editor + return open_anything() + + +def interactive_open(targets, command): + """Open the files in `targets` by `exec`ing a new `command`, given + as a Unicode string. (The new program takes over, and Python + execution ends: this does not fork a subprocess.) Can raise `OSError`. """ - if command: - command = command.encode('utf8') - try: - command = [c.decode('utf8') - for c in shlex.split(command)] - except ValueError: # Malformed shell tokens. - command = [command] - command.insert(0, command[0]) # for argv[0] - else: - base_cmd = open_anything() - command = [base_cmd, base_cmd] + # Split the command string into its arguments. + command = command.encode('utf8') + try: + command = [c.decode('utf8') + for c in shlex.split(command)] + except ValueError: # Malformed shell tokens. + command = [command] + command.insert(0, command[0]) # for argv[0] + # Add the explicit arguments. command += targets return os.execlp(*command) From 3a5dd47e3a1edd641d1dd328a349e9d8c66287c7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:17:44 -0800 Subject: [PATCH 0169/2280] Factor out shlex.split workaround --- beets/library.py | 8 +------- beets/util/__init__.py | 25 +++++++++++++++++++++---- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/beets/library.py b/beets/library.py index 186a674e7..cad39c232 100644 --- a/beets/library.py +++ b/beets/library.py @@ -19,7 +19,6 @@ from __future__ import (division, absolute_import, print_function, import os import sys -import shlex import unicodedata import time import re @@ -1139,13 +1138,8 @@ def parse_query_string(s, model_cls): The string is split into components using shell-like syntax. """ assert isinstance(s, unicode), "Query is not unicode: {0!r}".format(s) - - # A bug in Python < 2.7.3 prevents correct shlex splitting of - # Unicode strings. - # http://bugs.python.org/issue6988 - s = s.encode('utf8') try: - parts = [p.decode('utf8') for p in shlex.split(s)] + parts = util.shlex_split(s) except ValueError as exc: raise dbcore.InvalidQueryError(s, exc) return parse_query_parts(parts, model_cls) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index a2a5688b5..2a861ce88 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -749,6 +749,26 @@ def editor_command(): return open_anything() +def shlex_split(s): + """Split a Unicode or bytes string according to shell lexing rules. + + Raise `ValueError` if the string is not a well-formed shell string. + This is a workaround for a bug in some versions of Python. + """ + if isinstance(s, bytes): + # Shlex works fine. + return shlex.split(s) + + elif isinstance(s, unicode): + # Work around a Python bug. + # http://bugs.python.org/issue6988 + bs = s.encode('utf8') + return [c.decode('utf8') for c in shlex.split(bs)] + + else: + raise TypeError('shlex_split called with non-string') + + def interactive_open(targets, command): """Open the files in `targets` by `exec`ing a new `command`, given as a Unicode string. (The new program takes over, and Python @@ -757,15 +777,12 @@ def interactive_open(targets, command): Can raise `OSError`. """ # Split the command string into its arguments. - command = command.encode('utf8') try: - command = [c.decode('utf8') - for c in shlex.split(command)] + command = shlex_split(command) except ValueError: # Malformed shell tokens. command = [command] command.insert(0, command[0]) # for argv[0] - # Add the explicit arguments. command += targets return os.execlp(*command) From e3f7da54676da58e46424d86ac872184b044d6cd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:26:04 -0800 Subject: [PATCH 0170/2280] Update test for simpler interactive_open --- test/test_util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_util.py b/test/test_util.py index 324a4d589..b72410c9c 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -43,7 +43,7 @@ class UtilTest(unittest.TestCase): @patch('beets.util.open_anything') def test_interactive_open(self, mock_open, mock_execlp): mock_open.return_value = 'tagada' - util.interactive_open(['foo']) + util.interactive_open(['foo'], util.open_anything()) mock_execlp.assert_called_once_with('tagada', 'tagada', 'foo') mock_execlp.reset_mock() From 2d8350ef030e5f9267768124f29b0d7c11f0ffce Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:31:42 -0800 Subject: [PATCH 0171/2280] Use standard machinery for opening editor --- beetsplug/edit.py | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index f68523129..63763b7d9 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -18,7 +18,9 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) from beets import plugins -from beets.ui import Subcommand, decargs, library, print_ +from beets import util +from beets import library +from beets.ui import Subcommand, decargs, print_ from beets.ui.commands import _do_query import subprocess import yaml @@ -28,7 +30,14 @@ from beets import config from beets import ui from tempfile import NamedTemporaryFile import os -import sys + + +def edit(filename): + """Open `filename` in a test editor. + """ + cmd = util.shlex_split(util.editor_command()) + cmd.append(filename) + subprocess.call(cmd) class EditPlugin(plugins.BeetsPlugin): @@ -184,7 +193,7 @@ class EditPlugin(plugins.BeetsPlugin): new = NamedTemporaryFile(suffix='.yaml', delete=False) new.write(newyaml) new.close() - self.get_editor(new.name) + edit(new.name) # wait for user to edit yaml and continue if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): while True: @@ -203,7 +212,7 @@ class EditPlugin(plugins.BeetsPlugin): print_("correct format for empty = - '' :") if ui.input_yn( ui.colorize('action_default', "fix?(y)"), True): - self.get_editor(new.name) + edit(new.name) if ui.input_yn(ui.colorize( 'action_default', "ok.fixed.(y)"), True): pass @@ -213,30 +222,6 @@ class EditPlugin(plugins.BeetsPlugin): os.remove(new.name) exit() - def open_file(self, startcmd): - # opens a file in the standard program on all systems - subprocess.call(('cmd /c start "" "' + startcmd + '"') - if os.name is 'nt' else ( - 'open' if sys.platform.startswith('darwin') else - 'xdg-open', startcmd)) - - def get_editor(self, name): - if not self.ed: - # if not specified in config use $EDITOR from system - editor = os.getenv('EDITOR') - if editor: - os.system(editor + " " + name) - else: - # let the system handle the file - self.open_file(name) - else: - # use the editor specified in config - callmethod = [self.ed] - if self.ed_args: - callmethod.extend(self.ed_args) - callmethod.append(name) - subprocess.check_call(callmethod) - def nice_format(self, newset): # format the results so that we have an ID at the top # that we can change to a userfrienly title/artist format From b593d01100499fcfb214afb675e5089551d3aad9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:33:02 -0800 Subject: [PATCH 0172/2280] Use qualified names for `ui` utilities --- beetsplug/edit.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 63763b7d9..6fb9be732 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -20,7 +20,7 @@ from __future__ import (division, absolute_import, print_function, from beets import plugins from beets import util from beets import library -from beets.ui import Subcommand, decargs, print_ +from beets import ui from beets.ui.commands import _do_query import subprocess import yaml @@ -77,7 +77,7 @@ class EditPlugin(plugins.BeetsPlugin): self.ed_args = None def commands(self): - edit_command = Subcommand( + edit_command = ui.Subcommand( 'edit', help='interactively edit metadata' ) @@ -105,15 +105,15 @@ class EditPlugin(plugins.BeetsPlugin): # main program flow # Get the objects to edit. - query = decargs(args) + query = ui.decargs(args) items, albums = _do_query(lib, query, opts.album, False) objs = albums if opts.album else items if not objs: - print_('Nothing to edit.') + ui.print_('Nothing to edit.') return # Confirmation from user about the queryresult for obj in objs: - print_(format(obj)) + ui.print_(format(obj)) if not ui.input_yn(ui.colorize('action_default', "Edit? (y/n)"), True): return @@ -128,7 +128,7 @@ class EditPlugin(plugins.BeetsPlugin): newyaml, oldyaml = self.change_objs(data) changed_objs = self.check_diff(newyaml, oldyaml, opts) if not changed_objs: - print_("nothing to change") + ui.print_("nothing to change") return self.save_items(changed_objs, lib, opts) @@ -156,13 +156,13 @@ class EditPlugin(plugins.BeetsPlugin): # we need all the fields if opts.all: fields = None - print_(ui.colorize('text_warning', "edit all fields from:")) + ui.print_(ui.colorize('text_warning', "edit all fields from:")) else: for it in fields: if opts.album: # check if it is really an albumfield if it not in library.Album.all_keys(): - print_( + ui.print_( "{} not in albumfields.Removed it.".format( ui.colorize( 'text_warning', it))) @@ -170,7 +170,7 @@ class EditPlugin(plugins.BeetsPlugin): else: # if it is not an itemfield remove it if it not in library.Item.all_keys(): - print_( + ui.print_( "{} not in itemfields.Removed it.".format( ui.colorize( 'text_warning', it))) @@ -207,9 +207,9 @@ class EditPlugin(plugins.BeetsPlugin): except yaml.YAMLError as e: # some error-correcting mainly for empty-values # not being well-formated - print_(ui.colorize('text_warning', + ui.print_(ui.colorize('text_warning', "change this fault: {}".format(e))) - print_("correct format for empty = - '' :") + ui.print_("correct format for empty = - '' :") if ui.input_yn( ui.colorize('action_default', "fix?(y)"), True): edit(new.name) @@ -284,6 +284,6 @@ class EditPlugin(plugins.BeetsPlugin): for x in range(0, len(nl)): if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: nl[x] = ol[x] - print_("reset forbidden field.") + ui.print_("reset forbidden field.") if ol != nl: # only keep objects that have changed return ol, nl From b33a024549dd8e37991024e37e29d9ddefab46ae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:37:17 -0800 Subject: [PATCH 0173/2280] Simplify write logic --- beetsplug/edit.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 6fb9be732..6d36e1fa3 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -26,8 +26,6 @@ import subprocess import yaml import collections from sys import exit -from beets import config -from beets import ui from tempfile import NamedTemporaryFile import os @@ -208,7 +206,7 @@ class EditPlugin(plugins.BeetsPlugin): # some error-correcting mainly for empty-values # not being well-formated ui.print_(ui.colorize('text_warning', - "change this fault: {}".format(e))) + "change this fault: {}".format(e))) ui.print_("correct format for empty = - '' :") if ui.input_yn( ui.colorize('action_default', "fix?(y)"), True): @@ -264,11 +262,8 @@ class EditPlugin(plugins.BeetsPlugin): return for ob in changedob: - if config['import']['write'].get(bool): - ob.try_sync() - else: - ob.store() - print("changed: {0}".format(ob)) + self._log.debug('saving changes to {}', ob) + ob.try_sync(ui.should_write()) return From de6813eab5dc31a64feadbc105a9dc506bcec43f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:38:41 -0800 Subject: [PATCH 0174/2280] Remove vestigial `editor` config option We now just use $EDITOR. --- beetsplug/edit.py | 11 ----------- docs/plugins/edit.rst | 3 --- 2 files changed, 14 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 6d36e1fa3..4c4d7e1ca 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -44,15 +44,11 @@ class EditPlugin(plugins.BeetsPlugin): super(EditPlugin, self).__init__() self.config.add({ - 'editor': '', 'albumfields': 'album albumartist', 'itemfields': 'track title artist album', 'not_fields': 'id path', }) - # The editor field in the config lets you specify your editor. - self.editor = self.config['editor'].as_str_seq() - # the albumfields field in your config sets the tags that # you want to see/change for albums. # Defaults to album albumartist. @@ -71,9 +67,6 @@ class EditPlugin(plugins.BeetsPlugin): # value. The ID of an item will never be changed. self.not_fields = self.config['not_fields'].as_str_seq() - self.ed = None - self.ed_args = None - def commands(self): edit_command = ui.Subcommand( 'edit', @@ -97,10 +90,6 @@ class EditPlugin(plugins.BeetsPlugin): return [edit_command] def editor_music(self, lib, opts, args): - if self.editor: - self.ed_args = self.editor[1:] if len(self.editor) > 1 else None - self.ed = self.editor[0] if self.editor else None - # main program flow # Get the objects to edit. query = ui.decargs(args) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 85d7343fc..224988fc5 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -51,14 +51,11 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` :: edit: - editor: nano -w -p albumfields: genre album itemfields: track artist not_fields: id path separator: "<>" -* ``editor:`` pick your own texteditor; add arguments if needed. If no``editor:`` then your system opens the file-extension. - * The ``albumfields:`` and ``itemfields:`` lets you list the fields you want to change. ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields do the ``beet fields`` command. From f27c4863895916a020b20824b02b047f3a0800b0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:39:30 -0800 Subject: [PATCH 0175/2280] Remove `separator` and `not_fields` from docs The `separator` option has already been removed. `not_fields` is an internal detail and doesn't need to be documented (yet). --- docs/plugins/edit.rst | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 224988fc5..45dd042e7 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -53,22 +53,11 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` edit: albumfields: genre album itemfields: track artist - not_fields: id path - separator: "<>" * The ``albumfields:`` and ``itemfields:`` lets you list the fields you want to change. ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields do the ``beet fields`` command. -* The ``not_fields:``. Fields that you put in here will not be changed. You can see them but not change them. It always contains ``id`` and standard also the ``path``. - Don't want to mess with them. - -* The default ``separator:`` prints like: - -:: - - -02-The Night Before-The Beatles-Help! - but you can pick anything else. With "<>" it will look like: :: From ce31c2df233f45526b3c9c14b2b28ed14a297ed7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:43:58 -0800 Subject: [PATCH 0176/2280] Remove some dead code and hoist utility functions --- beetsplug/edit.py | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 4c4d7e1ca..41f4606ae 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -38,6 +38,22 @@ def edit(filename): subprocess.call(cmd) +def dump(self, arg): + """Dump an object as YAML for editing. + """ + return yaml.safe_dump_all( + arg, + allow_unicode=True, + default_flow_style=False, + ) + + +def load(self, yam): + """Read a YAML string back to an object. + """ + return yaml.load_all(yam) + + class EditPlugin(plugins.BeetsPlugin): def __init__(self): @@ -119,17 +135,6 @@ class EditPlugin(plugins.BeetsPlugin): return self.save_items(changed_objs, lib, opts) - def print_to_yaml(self, arg): - # from object to yaml - return yaml.safe_dump_all( - arg, - allow_unicode=True, - default_flow_style=False) - - def yaml_to_dict(self, yam): - # from yaml to object - return yaml.load_all(yam) - def get_fields_from(self, objs, opts): # construct a list of fields we need # see if we need album or item fields @@ -175,8 +180,8 @@ class EditPlugin(plugins.BeetsPlugin): def change_objs(self, dict_items): # construct a yaml from the original object-fields # and make a yaml that we can change in the text-editor - oldyaml = self.print_to_yaml(dict_items) # our backup - newyaml = self.print_to_yaml(dict_items) # goes to user + oldyaml = dump(dict_items) # our backup + newyaml = dump(dict_items) # goes to user new = NamedTemporaryFile(suffix='.yaml', delete=False) new.write(newyaml) new.close() @@ -225,8 +230,6 @@ class EditPlugin(plugins.BeetsPlugin): niceNewSet = self.nice_format(newset) niceOldSet = self.nice_format(oldset) niceCombiSet = zip(niceOldSet.items(), niceNewSet.items()) - newSetTitled = [] - oldSetTitled = [] changedObjs = [] for o, n in niceCombiSet: if opts.album: @@ -234,9 +237,7 @@ class EditPlugin(plugins.BeetsPlugin): else: ob = lib.get_item(n[0]) # change id to item-string - oldSetTitled.append((format(ob),) + o[1:]) ob.update(n[1]) # update the object - newSetTitled.append((format(ob),) + n[1:]) changedObjs.append(ob) # see the changes we made @@ -258,8 +259,8 @@ class EditPlugin(plugins.BeetsPlugin): def check_diff(self, newyaml, oldyaml, opts): # make python objs from yamlstrings - nl = self.yaml_to_dict(newyaml) - ol = self.yaml_to_dict(oldyaml) + nl = load(newyaml) + ol = load(oldyaml) return filter(None, map(self.reduce_it, ol, nl)) def reduce_it(self, ol, nl): From 3c01c49a2c5f035ff8f017fb9b18737583ed1828 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 13:53:25 -0800 Subject: [PATCH 0177/2280] Less chatty interface Removed three prompts: 1. The "really edit?" prompt. If you don't want to edit, you can just not make any changes. 2. The "done?" loop. This seems unnecessary; we'll confirm afterward anyway. 3. The YAML checker. This removal could indeed make things inconvenient, since your changes get thrown away if you make a YAML mistake. For the moment, simplicity is taking priority. --- beetsplug/edit.py | 78 +++++++++++++++-------------------------------- 1 file changed, 25 insertions(+), 53 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 41f4606ae..27023ad7c 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -25,7 +25,6 @@ from beets.ui.commands import _do_query import subprocess import yaml import collections -from sys import exit from tempfile import NamedTemporaryFile import os @@ -38,7 +37,7 @@ def edit(filename): subprocess.call(cmd) -def dump(self, arg): +def dump(arg): """Dump an object as YAML for editing. """ return yaml.safe_dump_all( @@ -48,10 +47,10 @@ def dump(self, arg): ) -def load(self, yam): +def load(s): """Read a YAML string back to an object. """ - return yaml.load_all(yam) + return yaml.load_all(s) class EditPlugin(plugins.BeetsPlugin): @@ -106,7 +105,6 @@ class EditPlugin(plugins.BeetsPlugin): return [edit_command] def editor_music(self, lib, opts, args): - # main program flow # Get the objects to edit. query = ui.decargs(args) items, albums = _do_query(lib, query, opts.album, False) @@ -114,25 +112,22 @@ class EditPlugin(plugins.BeetsPlugin): if not objs: ui.print_('Nothing to edit.') return - # Confirmation from user about the queryresult - for obj in objs: - ui.print_(format(obj)) - if not ui.input_yn(ui.colorize('action_default', "Edit? (y/n)"), True): - return - # get the fields from the objects + # Get the content to edit as raw data structures. if opts.all: data = self.get_all_fields(objs) else: fields = self.get_fields_from(objs, opts) data = self.get_selected_fields(fields, objs, opts) - # present the yaml to the user and let her change it - newyaml, oldyaml = self.change_objs(data) - changed_objs = self.check_diff(newyaml, oldyaml, opts) - if not changed_objs: - ui.print_("nothing to change") + # Present the YAML to the user and let her change it. + new_data = self.change_objs(data) + changed_objs = self.check_diff(data, new_data) + if changed_objs is None: + # Editing failed. return + + # Save the new data. self.save_items(changed_objs, lib, opts) def get_fields_from(self, objs, opts): @@ -178,41 +173,21 @@ class EditPlugin(plugins.BeetsPlugin): for obj in objs] def change_objs(self, dict_items): - # construct a yaml from the original object-fields - # and make a yaml that we can change in the text-editor - oldyaml = dump(dict_items) # our backup - newyaml = dump(dict_items) # goes to user + # Ask the user to edit the data. new = NamedTemporaryFile(suffix='.yaml', delete=False) - new.write(newyaml) + new.write(dump(dict_items)) new.close() edit(new.name) - # wait for user to edit yaml and continue - if ui.input_yn(ui.colorize('action_default', "done?(y)"), True): - while True: - try: - # reading the yaml back in - with open(new.name) as f: - newyaml = f.read() - list(yaml.load_all(newyaml)) - os.remove(new.name) - break - except yaml.YAMLError as e: - # some error-correcting mainly for empty-values - # not being well-formated - ui.print_(ui.colorize('text_warning', - "change this fault: {}".format(e))) - ui.print_("correct format for empty = - '' :") - if ui.input_yn( - ui.colorize('action_default', "fix?(y)"), True): - edit(new.name) - if ui.input_yn(ui.colorize( - 'action_default', "ok.fixed.(y)"), True): - pass - # only continue when all the mistakes are corrected - return newyaml, oldyaml - else: - os.remove(new.name) - exit() + + # Parse the updated data. + with open(new.name) as f: + new_str = f.read() + os.remove(new.name) + try: + return load(new_str) + except yaml.YAMLError as e: + ui.print_("Invalid YAML: {}".format(e)) + return None def nice_format(self, newset): # format the results so that we have an ID at the top @@ -257,11 +232,8 @@ class EditPlugin(plugins.BeetsPlugin): return - def check_diff(self, newyaml, oldyaml, opts): - # make python objs from yamlstrings - nl = load(newyaml) - ol = load(oldyaml) - return filter(None, map(self.reduce_it, ol, nl)) + def check_diff(self, old_data, new_data): + return filter(None, map(self.reduce_it, old_data, new_data)) def reduce_it(self, ol, nl): # if there is a forbidden field it resets them From 105cd73906e7a85a2c8416a9827a8b682e9a9c5f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:05:40 -0800 Subject: [PATCH 0178/2280] Start expunging `opts` carry-through A dedicated command function takes care of the options and turns them into normal variables. --- beetsplug/edit.py | 89 ++++++++++++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 36 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 27023ad7c..041fe0f4e 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -101,10 +101,12 @@ class EditPlugin(plugins.BeetsPlugin): help='edit all fields', ) edit_command.parser.add_all_common_options() - edit_command.func = self.editor_music + edit_command.func = self._edit_command return [edit_command] - def editor_music(self, lib, opts, args): + def _edit_command(self, lib, opts, args): + """The CLI command function for the `beet edit` command. + """ # Get the objects to edit. query = ui.decargs(args) items, albums = _do_query(lib, query, opts.album, False) @@ -113,12 +115,29 @@ class EditPlugin(plugins.BeetsPlugin): ui.print_('Nothing to edit.') return - # Get the content to edit as raw data structures. + # Get the fields to edit. if opts.all: - data = self.get_all_fields(objs) + fields = None else: - fields = self.get_fields_from(objs, opts) - data = self.get_selected_fields(fields, objs, opts) + fields = self.get_fields_from(objs, opts.album, opts.extra) + # TODO + # fields.extend([f for f in opts.extra if f not in fields]) + + self.edit(lib, opts.album, objs, fields) + + def edit(self, lib, album, objs, fields): + """The core editor logic. + + - `lib`: The `Library` object. + - `album`: A flag indicating whether we're editing Items or Albums. + - `objs`: The `Item`s or `Album`s to edit. + - `fields`: The set of field names to edit. + """ + # Get the content to edit as raw data structures. + if fields: + data = self.get_selected_fields(fields, objs) + else: + data = self.get_all_fields(objs) # Present the YAML to the user and let her change it. new_data = self.change_objs(data) @@ -128,44 +147,42 @@ class EditPlugin(plugins.BeetsPlugin): return # Save the new data. - self.save_items(changed_objs, lib, opts) + self.save_items(changed_objs, lib, album) - def get_fields_from(self, objs, opts): + def get_fields_from(self, objs, album, extra): # construct a list of fields we need # see if we need album or item fields - fields = self.albumfields if opts.album else self.itemfields + fields = self.albumfields if album else self.itemfields + # if opts.extra is given add those - if opts.extra: - fields.extend([f for f in opts.extra if f not in fields]) + if extra: + fields.extend([f for f in extra if f not in fields]) + # make sure we got the id for identification if 'id' not in fields: fields.insert(0, 'id') - # we need all the fields - if opts.all: - fields = None - ui.print_(ui.colorize('text_warning', "edit all fields from:")) - else: - for it in fields: - if opts.album: - # check if it is really an albumfield - if it not in library.Album.all_keys(): - ui.print_( - "{} not in albumfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - fields.remove(it) - else: - # if it is not an itemfield remove it - if it not in library.Item.all_keys(): - ui.print_( - "{} not in itemfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - fields.remove(it) + + for it in fields: + if album: + # check if it is really an albumfield + if it not in library.Album.all_keys(): + ui.print_( + "{} not in albumfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + fields.remove(it) + else: + # if it is not an itemfield remove it + if it not in library.Item.all_keys(): + ui.print_( + "{} not in itemfields.Removed it.".format( + ui.colorize( + 'text_warning', it))) + fields.remove(it) return fields - def get_selected_fields(self, myfields, objs, opts): + def get_selected_fields(self, myfields, objs): return [[{field: obj[field]}for field in myfields]for obj in objs] def get_all_fields(self, objs): @@ -199,7 +216,7 @@ class EditPlugin(plugins.BeetsPlugin): wellformed[item[0].values()[0]].update(field) return wellformed - def save_items(self, oldnewlist, lib, opts): + def save_items(self, oldnewlist, lib, album): oldset, newset = zip(*oldnewlist) niceNewSet = self.nice_format(newset) @@ -207,7 +224,7 @@ class EditPlugin(plugins.BeetsPlugin): niceCombiSet = zip(niceOldSet.items(), niceNewSet.items()) changedObjs = [] for o, n in niceCombiSet: - if opts.album: + if album: ob = lib.get_album(int(n[0])) else: ob = lib.get_item(n[0]) From 9848b51008c823b85649e0c696d30dbb0da1bc49 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:19:09 -0800 Subject: [PATCH 0179/2280] Simplify field selection --- beetsplug/edit.py | 71 ++++++++++++++--------------------------------- 1 file changed, 21 insertions(+), 50 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 041fe0f4e..bd41eb573 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -64,18 +64,6 @@ class EditPlugin(plugins.BeetsPlugin): 'not_fields': 'id path', }) - # the albumfields field in your config sets the tags that - # you want to see/change for albums. - # Defaults to album albumartist. - # the ID tag will always be listed as it is used to identify the item - self.albumfields = self.config['albumfields'].as_str_seq() - - # the itemfields field in your config sets the tags that - # you want to see/change or items. - # Defaults to track title artist album. - # the ID tag will always be listed as it is used to identify the item - self.itemfields = self.config['itemfields'].as_str_seq() - # the not_fields field in your config sets the tags that # will not be changed. # If you happen to change them, they will be restored to the original @@ -119,19 +107,35 @@ class EditPlugin(plugins.BeetsPlugin): if opts.all: fields = None else: - fields = self.get_fields_from(objs, opts.album, opts.extra) - # TODO - # fields.extend([f for f in opts.extra if f not in fields]) - + fields = self._get_fields(opts.album, opts.extra) self.edit(lib, opts.album, objs, fields) + def _get_fields(self, album, extra): + """Get the set of fields to edit. + """ + # Start with the configured base fields. + if album: + fields = self.config['albumfields'].as_str_seq() + else: + fields = self.config['itemfields'].as_str_seq() + + # Add the requested extra fields. + if extra: + fields += extra + + # Ensure we always have the `id` field for identification. + fields.append('id') + + return set(fields) + def edit(self, lib, album, objs, fields): """The core editor logic. - `lib`: The `Library` object. - `album`: A flag indicating whether we're editing Items or Albums. - `objs`: The `Item`s or `Album`s to edit. - - `fields`: The set of field names to edit. + - `fields`: The set of field names to edit (or None to edit + everything). """ # Get the content to edit as raw data structures. if fields: @@ -149,39 +153,6 @@ class EditPlugin(plugins.BeetsPlugin): # Save the new data. self.save_items(changed_objs, lib, album) - def get_fields_from(self, objs, album, extra): - # construct a list of fields we need - # see if we need album or item fields - fields = self.albumfields if album else self.itemfields - - # if opts.extra is given add those - if extra: - fields.extend([f for f in extra if f not in fields]) - - # make sure we got the id for identification - if 'id' not in fields: - fields.insert(0, 'id') - - for it in fields: - if album: - # check if it is really an albumfield - if it not in library.Album.all_keys(): - ui.print_( - "{} not in albumfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - fields.remove(it) - else: - # if it is not an itemfield remove it - if it not in library.Item.all_keys(): - ui.print_( - "{} not in itemfields.Removed it.".format( - ui.colorize( - 'text_warning', it))) - fields.remove(it) - - return fields - def get_selected_fields(self, myfields, objs): return [[{field: obj[field]}for field in myfields]for obj in objs] From 5096653483ede2f0a9537d2ffa1bdd092399b1ff Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:23:57 -0800 Subject: [PATCH 0180/2280] Simpler serialization Just use a dictionary instead of a list of tiny one-key dictionaries. Still need to update the deserialization. --- beetsplug/edit.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index bd41eb573..4a15df696 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -53,6 +53,18 @@ def load(s): return yaml.load_all(s) +def flatten(obj, fields): + """Represent `obj`, a `dbcore.Model` object, as a dictionary for + serialization. Only include the given `fields` if provided; + otherwise, include everything. + """ + d = dict(obj) + if fields: + return {k: v for k, v in d.items() if k in fields} + else: + return d + + class EditPlugin(plugins.BeetsPlugin): def __init__(self): @@ -138,13 +150,10 @@ class EditPlugin(plugins.BeetsPlugin): everything). """ # Get the content to edit as raw data structures. - if fields: - data = self.get_selected_fields(fields, objs) - else: - data = self.get_all_fields(objs) + data = [flatten(o, fields) for o in objs] # Present the YAML to the user and let her change it. - new_data = self.change_objs(data) + new_data = self.edit_data(data) changed_objs = self.check_diff(data, new_data) if changed_objs is None: # Editing failed. @@ -153,14 +162,7 @@ class EditPlugin(plugins.BeetsPlugin): # Save the new data. self.save_items(changed_objs, lib, album) - def get_selected_fields(self, myfields, objs): - return [[{field: obj[field]}for field in myfields]for obj in objs] - - def get_all_fields(self, objs): - return [[{field: obj[field]}for field in sorted(obj._fields)] - for obj in objs] - - def change_objs(self, dict_items): + def edit_data(self, dict_items): # Ask the user to edit the data. new = NamedTemporaryFile(suffix='.yaml', delete=False) new.write(dump(dict_items)) From 029915814b16e30793690f434e230a904d4f5905 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:28:00 -0800 Subject: [PATCH 0181/2280] Abort if nothing changed --- beetsplug/edit.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 4a15df696..2827cbfed 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -154,25 +154,39 @@ class EditPlugin(plugins.BeetsPlugin): # Present the YAML to the user and let her change it. new_data = self.edit_data(data) - changed_objs = self.check_diff(data, new_data) - if changed_objs is None: + if new_data is None: # Editing failed. return + changed_objs = self.check_diff(data, new_data) + # Save the new data. self.save_items(changed_objs, lib, album) - def edit_data(self, dict_items): + def edit_data(self, data): + """Dump a data structure to a file as text, ask the user to edit + it, and then read back the updated data. + + If something goes wrong during editing, return None to indicate + the process should abort. + """ # Ask the user to edit the data. new = NamedTemporaryFile(suffix='.yaml', delete=False) - new.write(dump(dict_items)) + old_str = dump(data) + new.write(old_str) new.close() edit(new.name) - # Parse the updated data. + # Read the data back after editing and check whether anything + # changed. with open(new.name) as f: new_str = f.read() os.remove(new.name) + if new_str == old_str: + ui.print_("No changes; aborting.") + return None + + # Parse the updated data. try: return load(new_str) except yaml.YAMLError as e: From 58205e1befbb70b391e6981fc222469fbb3eb97c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:33:04 -0800 Subject: [PATCH 0182/2280] Simplify data filtering --- beetsplug/edit.py | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 2827cbfed..2b2da91b2 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -71,16 +71,13 @@ class EditPlugin(plugins.BeetsPlugin): super(EditPlugin, self).__init__() self.config.add({ + # The default fields to edit. 'albumfields': 'album albumartist', 'itemfields': 'track title artist album', - 'not_fields': 'id path', - }) - # the not_fields field in your config sets the tags that - # will not be changed. - # If you happen to change them, they will be restored to the original - # value. The ID of an item will never be changed. - self.not_fields = self.config['not_fields'].as_str_seq() + # Silently ignore any changes to these fields. + 'ignore_fields': 'id path', + }) def commands(self): edit_command = ui.Subcommand( @@ -158,10 +155,16 @@ class EditPlugin(plugins.BeetsPlugin): # Editing failed. return - changed_objs = self.check_diff(data, new_data) + # Filter out any forbidden fields so we can avoid clobbering + # `id` and such by mistake. + ignore_fields = self.config['ignore_fields'].as_str_seq() + for d in data: + for key in list(d): + if key in ignore_fields: + del d[key] # Save the new data. - self.save_items(changed_objs, lib, album) + self.save_items(data, lib, album) def edit_data(self, data): """Dump a data structure to a file as text, ask the user to edit @@ -235,16 +238,3 @@ class EditPlugin(plugins.BeetsPlugin): ob.try_sync(ui.should_write()) return - - def check_diff(self, old_data, new_data): - return filter(None, map(self.reduce_it, old_data, new_data)) - - def reduce_it(self, ol, nl): - # if there is a forbidden field it resets them - if ol != nl: - for x in range(0, len(nl)): - if ol[x] != nl[x] and ol[x].keys()[0]in self.not_fields: - nl[x] = ol[x] - ui.print_("reset forbidden field.") - if ol != nl: # only keep objects that have changed - return ol, nl From eb1bb132b1d276265afcc4d0109d48c013c12af1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:48:10 -0800 Subject: [PATCH 0183/2280] Simplify metadata application --- beetsplug/edit.py | 67 ++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 2b2da91b2..481b33f62 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -24,7 +24,6 @@ from beets import ui from beets.ui.commands import _do_query import subprocess import yaml -import collections from tempfile import NamedTemporaryFile import os @@ -155,16 +154,11 @@ class EditPlugin(plugins.BeetsPlugin): # Editing failed. return - # Filter out any forbidden fields so we can avoid clobbering - # `id` and such by mistake. - ignore_fields = self.config['ignore_fields'].as_str_seq() - for d in data: - for key in list(d): - if key in ignore_fields: - del d[key] + # Apply the updated metadata to the objects. + self.apply_data(objs, new_data) # Save the new data. - self.save_items(data, lib, album) + self.save_write(objs) def edit_data(self, data): """Dump a data structure to a file as text, ask the user to edit @@ -196,39 +190,40 @@ class EditPlugin(plugins.BeetsPlugin): ui.print_("Invalid YAML: {}".format(e)) return None - def nice_format(self, newset): - # format the results so that we have an ID at the top - # that we can change to a userfrienly title/artist format - # when we present our results - wellformed = collections.defaultdict(dict) - for item in newset: - for field in item: - wellformed[item[0].values()[0]].update(field) - return wellformed + def apply_data(self, objs, new_data): + """Take potentially-updated data and apply it to a set of Model + objects. - def save_items(self, oldnewlist, lib, album): + The objects are not written back to the database, so the changes + are temporary. + """ + obj_by_id = {o.id: o for o in objs} + ignore_fields = self.config['ignore_fields'].as_str_seq() + for d in new_data: + id = d.get('id') - oldset, newset = zip(*oldnewlist) - niceNewSet = self.nice_format(newset) - niceOldSet = self.nice_format(oldset) - niceCombiSet = zip(niceOldSet.items(), niceNewSet.items()) - changedObjs = [] - for o, n in niceCombiSet: - if album: - ob = lib.get_album(int(n[0])) - else: - ob = lib.get_item(n[0]) - # change id to item-string - ob.update(n[1]) # update the object - changedObjs.append(ob) + if not isinstance(id, int): + self._log.warn('skipping data with missing ID') + continue + if id not in obj_by_id: + self._log.warn('skipping unmatched ID {}', id) + continue - # see the changes we made - for obj in changedObjs: - ui.show_model_changes(obj) + obj = obj_by_id[d['id']] - self.save_write(changedObjs) + # Filter out any forbidden fields so we can avoid + # clobbering `id` and such by mistake. + for key in list(d): + if key in ignore_fields: + del d[key] + + obj.update(d) def save_write(self, changedob): + # see the changes we made + for obj in changedob: + ui.show_model_changes(obj) + if not ui.input_yn( ui.colorize('action_default', 'really modify? (y/n)')): return From 1c44969255ce8f4ec1772fa3515e9e63e08787a4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:50:24 -0800 Subject: [PATCH 0184/2280] Simplify interfaces and add docs --- beetsplug/edit.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 481b33f62..43f56e94e 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -116,7 +116,7 @@ class EditPlugin(plugins.BeetsPlugin): fields = None else: fields = self._get_fields(opts.album, opts.extra) - self.edit(lib, opts.album, objs, fields) + self.edit(opts.album, objs, fields) def _get_fields(self, album, extra): """Get the set of fields to edit. @@ -136,10 +136,9 @@ class EditPlugin(plugins.BeetsPlugin): return set(fields) - def edit(self, lib, album, objs, fields): + def edit(self, album, objs, fields): """The core editor logic. - - `lib`: The `Library` object. - `album`: A flag indicating whether we're editing Items or Albums. - `objs`: The `Item`s or `Album`s to edit. - `fields`: The set of field names to edit (or None to edit @@ -219,17 +218,16 @@ class EditPlugin(plugins.BeetsPlugin): obj.update(d) - def save_write(self, changedob): - # see the changes we made - for obj in changedob: + def save_write(self, objs): + """Save a list of updated Model objects to the database. + """ + # Display and confirm the changes. + for obj in objs: ui.show_model_changes(obj) - - if not ui.input_yn( - ui.colorize('action_default', 'really modify? (y/n)')): + if not ui.input_yn('Apply changes? (y/n)'): return - for ob in changedob: + # Save to the database and possibly write tags. + for ob in objs: self._log.debug('saving changes to {}', ob) ob.try_sync(ui.should_write()) - - return From 80facbab6fe2ebda8191a2f6600a3a4c2bb292f0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:57:32 -0800 Subject: [PATCH 0185/2280] More robust forbidden-change detection --- beetsplug/edit.py | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 43f56e94e..5cbf19ea2 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -49,7 +49,7 @@ def dump(arg): def load(s): """Read a YAML string back to an object. """ - return yaml.load_all(s) + return list(yaml.load_all(s)) def flatten(obj, fields): @@ -154,7 +154,7 @@ class EditPlugin(plugins.BeetsPlugin): return # Apply the updated metadata to the objects. - self.apply_data(objs, new_data) + self.apply_data(objs, data, new_data) # Save the new data. self.save_write(objs) @@ -189,34 +189,33 @@ class EditPlugin(plugins.BeetsPlugin): ui.print_("Invalid YAML: {}".format(e)) return None - def apply_data(self, objs, new_data): + def apply_data(self, objs, old_data, new_data): """Take potentially-updated data and apply it to a set of Model objects. The objects are not written back to the database, so the changes are temporary. """ + if len(old_data) != len(new_data): + self._log.warn('number of objects changed from {} to {}', + len(old_data), len(new_data)) + obj_by_id = {o.id: o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() - for d in new_data: - id = d.get('id') - - if not isinstance(id, int): - self._log.warn('skipping data with missing ID') - continue - if id not in obj_by_id: - self._log.warn('skipping unmatched ID {}', id) - continue - - obj = obj_by_id[d['id']] - - # Filter out any forbidden fields so we can avoid + for old_dict, new_dict in zip(old_data, new_data): + # Prohibit any changes to forbidden fields to avoid # clobbering `id` and such by mistake. - for key in list(d): - if key in ignore_fields: - del d[key] + forbidden = False + for key in ignore_fields: + if old_dict.get(key) != new_dict.get(key): + self._log.warn('ignoring object where {} changed', key) + forbidden = True + break + if forbidden: + continue - obj.update(d) + obj = obj_by_id[old_dict['id']] + obj.update(new_dict) def save_write(self, objs): """Save a list of updated Model objects to the database. From cfba04bc9d1c9f9acf723aa99e60319ae0aa2b18 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Nov 2015 14:58:53 -0800 Subject: [PATCH 0186/2280] Don't ask for confirmation if nothing changed --- beetsplug/edit.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 5cbf19ea2..3a22d014e 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -221,8 +221,12 @@ class EditPlugin(plugins.BeetsPlugin): """Save a list of updated Model objects to the database. """ # Display and confirm the changes. + changed = False for obj in objs: - ui.show_model_changes(obj) + changed |= ui.show_model_changes(obj) + if not changed: + ui.print_('No changes to apply.') + return if not ui.input_yn('Apply changes? (y/n)'): return From 61e992fd47fb434cf44e17f6acad70d099e94b92 Mon Sep 17 00:00:00 2001 From: Kai Date: Sun, 15 Nov 2015 04:25:42 +0100 Subject: [PATCH 0187/2280] Replace PIL with Pillow --- docs/plugins/embedart.rst | 4 ++-- docs/plugins/fetchart.rst | 12 ++++++------ docs/plugins/thumbnails.rst | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index 41cfaa87c..94e91d995 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -66,9 +66,9 @@ file. The available options are: Default: ``no``. Note: ``compare_threshold`` option requires `ImageMagick`_, and ``maxwidth`` -requires either `ImageMagick`_ or `PIL`_. +requires either `ImageMagick`_ or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ .. _PHASH: http://www.fmwconcepts.com/misc_tests/perceptual_hash_test_results_510/ diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 21d58fed4..c04517b11 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -54,9 +54,9 @@ file. The available options are: the cost of some speed. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ -or `PIL`_. +or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ Here's an example that makes plugin select only images that contain *front* or @@ -87,8 +87,8 @@ be processed; otherwise, the command processes every album in your library. Image Resizing -------------- -Beets can resize images using `PIL`_, `ImageMagick`_, or a server-side resizing -proxy. If either PIL or ImageMagick is installed, beets will use those; +Beets can resize images using `Pillow`_, `ImageMagick`_, or a server-side resizing +proxy. If either Pillow or ImageMagick is installed, beets will use those; otherwise, it falls back to the resizing proxy. If the resizing proxy is used, no resizing is performed for album art found on the filesystem---only downloaded art is resized. Server-side resizing can also be slower than local resizing, so @@ -97,9 +97,9 @@ consider installing one of the two backends for better performance. When using ImageMagic, beets looks for the ``convert`` executable in your path. On some versions of Windows, the program can be shadowed by a system-provided ``convert.exe``. On these systems, you may need to modify your ``%PATH%`` -environment variable so that ImageMagick comes first or use PIL instead. +environment variable so that ImageMagick comes first or use Pillow instead. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ Album Art Sources diff --git a/docs/plugins/thumbnails.rst b/docs/plugins/thumbnails.rst index 267c149cf..67f83ce98 100644 --- a/docs/plugins/thumbnails.rst +++ b/docs/plugins/thumbnails.rst @@ -10,9 +10,9 @@ as the :doc:`/plugins/fetchart`. You'll need 2 additional python packages: `pyxdg` and `pathlib`. ``thumbnails`` needs to resize the covers, and therefore requires either -`ImageMagick`_ or `PIL`_. +`ImageMagick`_ or `Pillow`_. -.. _PIL: http://www.pythonware.com/products/pil/ +.. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ Configuration From ecbd337c472bf58b25575dedeecb92f697413267 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 15 Nov 2015 14:51:12 +0100 Subject: [PATCH 0188/2280] Added file encoding definition to badfiles.py --- beetsplug/badfiles.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index d27208724..7079fb4e8 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, François-Xavier Thomas. # From 5f2e5d73ccb50f8a99a92f025344f9c75d79595a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 15 Nov 2015 18:09:20 +0100 Subject: [PATCH 0189/2280] edit: update unit tests * Update unit tests in order to reflect the changes on the last refactor of edit.py (patch edit.edit instead of EditPlugin.get_editor, revise stdin strings to match current version, remove TODO on docstrings from malformed and invalid yaml tests). --- test/test_edit.py | 68 ++++++++++++++++++----------------------------- 1 file changed, 26 insertions(+), 42 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index f853df6a3..a48b20856 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -21,8 +21,6 @@ from test._common import unittest from test.helper import TestHelper, control_stdin from beets import library -from beetsplug.edit import EditPlugin -from beets.ui import UserError class ModifyFileMocker(object): @@ -96,7 +94,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Run the edit command, with mocked stdin and yaml writing, and passing `args` to `run_command`.""" m = ModifyFileMocker(**modify_file_args) - with patch.object(EditPlugin, 'get_editor', side_effect=m.action): + with patch('beetsplug.edit.edit', side_effect=m.action): with control_stdin('\n'.join(stdin)): self.run_command('edit', *args) @@ -128,8 +126,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit titles self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, - # edit? y, done? y, modify? n - ['y', 'y', 'n']) + # Apply changes? n + ['n']) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') @@ -140,8 +138,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit titles self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, - # edit? y, done? y, modify? y - ['y', 'y', 'y']) + # Apply changes? y + ['y']) self.assertCounts(write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') @@ -149,12 +147,12 @@ class EditCommandTest(unittest.TestCase, TestHelper): ['title']) def test_single_title_edit_apply(self): - """Edit title for on items in the library, then apply changes.""" + """Edit title for one item in the library, then apply changes.""" # edit title self.run_mocked_command({'replacements': {u't\u00eftle 9': u'modified t\u00eftle 9'}}, - # edit? y, done? y, modify? y - ['y', 'y', 'y']) + # Apply changes? y + ['y']) self.assertCounts(write_call_count=1,) # no changes except on last item @@ -167,8 +165,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Do not edit anything.""" # do not edit anything self.run_mocked_command({'contents': None}, - # edit? n -> "no changes found" - ['n']) + # no stdin + []) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') @@ -181,8 +179,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit album self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, - # edit? y, done? y, modify? y - ['y', 'y', 'y']) + # Apply changes? y + ['y']) self.assertCounts(write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, @@ -195,8 +193,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Album query (-a), edit album field, apply changes.""" self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, - # edit? y, done? y, modify? y - ['y', 'y', 'y'], + # Apply changes? y + ['y'], args=['-a']) self.album.load() @@ -209,8 +207,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Album query (-a), edit albumartist field, apply changes.""" self.run_mocked_command({'replacements': {u'album artist': u'modified album artist'}}, - # edit? y, done? y, modify? y - ['y', 'y', 'y'], + # Apply changes? y + ['y'], args=['-a']) self.album.load() @@ -219,38 +217,24 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertItemFieldsModified(self.album.items(), self.items_orig, ['albumartist']) - def test_malformed_yaml_discard(self): + def test_malformed_yaml(self): """Edit the yaml file incorrectly (resulting in a malformed yaml - document), then discard changes. - - TODO: this test currently fails, on purpose. User gets into an endless - "fix?" -> "ok.fixed." prompt loop unless he is able to provide a - well-formed yaml.""" + document).""" # edit the yaml file to an invalid file - try: - self.run_mocked_command({'contents': '!MALFORMED'}, - # edit? y, done? y, fix? n - ['y', 'y', 'n']) - except UserError as e: - self.fail(repr(e)) + self.run_mocked_command({'contents': '!MALFORMED'}, + # no stdin + []) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') - def test_invalid_yaml_discard(self): + def test_invalid_yaml(self): """Edit the yaml file incorrectly (resulting in a well-formed but - invalid yaml document), then discard changes. - - TODO: this test currently fails, on purpose. `check_diff()` chokes - ungracefully""" + invalid yaml document).""" # edit the yaml file to an invalid file - try: - self.run_mocked_command({'contents': - 'wellformed: yes, but invalid'}, - # edit? y, done? y - ['y', 'y']) - except KeyError as e: - self.fail(repr(e)) + self.run_mocked_command({'contents': 'wellformed: yes, but invalid'}, + # no stdin + []) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') From 2adf70209f8e8a2c6a68332c0d6fc620a1604d76 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 15 Nov 2015 18:36:24 +0100 Subject: [PATCH 0190/2280] edit: add test for extra fields on user yaml * Add test_invalid_yaml_extra_field, testing the handling of user appended fields (in particular, a non existing field) during the yaml editing. --- test/test_edit.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/test_edit.py b/test/test_edit.py index a48b20856..d3a38e7e5 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -239,6 +239,18 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') + def test_invalid_yaml_extra_field(self): + """Edit the yaml file incorrectly (resulting in a well-formed but + invalid yaml document), appending an extra field to the first item.""" + # append "foo: bar" to item with id == 1 + self.run_mocked_command({'replacements': {u'id: 1': + u'id: 1\nfoo: bar'}}, + # no stdin + []) + + self.assertCounts(write_call_count=0, + title_starts_with=u't\u00eftle') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From e31680123bd27f46dadaa297a792057c74d1d34e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 16 Nov 2015 14:46:13 +0100 Subject: [PATCH 0191/2280] edit: update extra fields in yaml test * Update test for extra fields in edited yaml, allowing the user to add fields while editing. Rename the test to test_single_edit_add_field to reflect its purpose more accurately. --- test/test_edit.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index d3a38e7e5..c72eeee73 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -189,6 +189,19 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.album.load() self.assertEqual(self.album.album, u'\u00e4lbum') + def test_single_edit_add_field(self): + """Edit the yaml file appending an extra field to the first item, then + apply changes.""" + # append "foo: bar" to item with id == 1 + self.run_mocked_command({'replacements': {u'id: 1': + u'id: 1\nfoo: bar'}}, + # Apply changes? y + ['y']) + + self.assertEqual(self.lib.items('id:1')[0].foo, 'bar') + self.assertCounts(write_call_count=1, + title_starts_with=u't\u00eftle') + def test_a_album_edit_apply(self): """Album query (-a), edit album field, apply changes.""" self.run_mocked_command({'replacements': {u'\u00e4lbum': @@ -239,18 +252,6 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') - def test_invalid_yaml_extra_field(self): - """Edit the yaml file incorrectly (resulting in a well-formed but - invalid yaml document), appending an extra field to the first item.""" - # append "foo: bar" to item with id == 1 - self.run_mocked_command({'replacements': {u'id: 1': - u'id: 1\nfoo: bar'}}, - # no stdin - []) - - self.assertCounts(write_call_count=0, - title_starts_with=u't\u00eftle') - def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 917628340e1abf92cd8f27171c7c48fba2f0b875 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 16 Nov 2015 14:48:05 +0100 Subject: [PATCH 0192/2280] edit: save only items with changes * Modify save_write() so only the items that do have pending changes (ie. dirty items) are saved to the database. --- beetsplug/edit.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 3a22d014e..292d606f6 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -232,5 +232,6 @@ class EditPlugin(plugins.BeetsPlugin): # Save to the database and possibly write tags. for ob in objs: - self._log.debug('saving changes to {}', ob) - ob.try_sync(ui.should_write()) + if ob._dirty: + self._log.debug('saving changes to {}', ob) + ob.try_sync(ui.should_write()) From bb39cd509de56c2dc94beeee67c794b12e2b80c6 Mon Sep 17 00:00:00 2001 From: jmwatte Date: Sun, 15 Nov 2015 12:17:50 +0100 Subject: [PATCH 0193/2280] cleaned up edit.rst --- beetsplug/edit.py | 2 +- docs/plugins/edit.rst | 30 +++++++----------------------- 2 files changed, 8 insertions(+), 24 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 3a22d014e..8e7b0b8d3 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -29,7 +29,7 @@ import os def edit(filename): - """Open `filename` in a test editor. + """Open `filename` in a text editor. """ cmd = util.shlex_split(util.editor_command()) cmd.append(filename) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 45dd042e7..28ac21681 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -2,7 +2,7 @@ Edit Plugin ============ The ``edit`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. Add the ``edit`` plugin to your ``plugins:`` in your ``config.yaml``. Then -you simply put in a query like you normally do. +simply do a query. :: beet edit beatles @@ -11,8 +11,7 @@ you simply put in a query like you normally do. -You get a list of hits and then you can edit them. The ``edit`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. - +You get a list of hits to edit.``edit`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. Without anything specified in your ``config.yaml`` for ``edit:`` you will see for items @@ -25,24 +24,15 @@ and for albums $album-$albumartist -You can get fields from the cmdline by adding +You can get extra fields from the cmdline by adding :: - -f '$genre $added' + -e year -e comments -or - -:: - - -e '$year $comments' - -If you use ``-f '$field ...'`` you get *only* what you specified. - -If you use ``-e '$field ...'`` you get what you specified *extra*. If you add ``--all`` you get all the fields. -After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file, answer with ``y`` on ``Done?`` and you get a summary of your changes. Check em, answer ``y`` or ``n`` and the changes are written to your library. +After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file and you get a summary of your changes. Check em. Apply the changes into your library. Configuration ------------- @@ -54,12 +44,6 @@ Make a ``edit:`` section in your config.yaml ``(beet config -e)`` albumfields: genre album itemfields: track artist -* The ``albumfields:`` and ``itemfields:`` lets you list the fields you want to change. +* The ``albumfields:`` and ``itemfields:`` is a list of fields you want to change. ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields - do the ``beet fields`` command. - - -but you can pick anything else. With "<>" it will look like: -:: - - <>02<>The Night Before<>The Beatles<>Help! + do the ``beet fields`` command. Or put in a faulty one, hit enter and you get a list of available field. From feabf1a6ef03a0d5800f7cd2f20198639c0fe076 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 16 Nov 2015 12:27:32 -0800 Subject: [PATCH 0194/2280] Offer a chance to fix YAML parse errors An alternative to 749ef8563847ef25c1a2816e2097e4e90e69069f by @jmwatte. --- beetsplug/edit.py | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 8e7b0b8d3..16f770b1c 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -166,28 +166,38 @@ class EditPlugin(plugins.BeetsPlugin): If something goes wrong during editing, return None to indicate the process should abort. """ - # Ask the user to edit the data. + # Set up a temporary file with the initial data for editi new = NamedTemporaryFile(suffix='.yaml', delete=False) old_str = dump(data) new.write(old_str) new.close() - edit(new.name) - # Read the data back after editing and check whether anything - # changed. - with open(new.name) as f: - new_str = f.read() - os.remove(new.name) - if new_str == old_str: - ui.print_("No changes; aborting.") - return None - - # Parse the updated data. + # Loop until we have parseable data. try: - return load(new_str) - except yaml.YAMLError as e: - ui.print_("Invalid YAML: {}".format(e)) - return None + while True: + # Ask the user to edit the data. + edit(new.name) + + # Read the data back after editing and check whether anything + # changed. + with open(new.name) as f: + new_str = f.read() + if new_str == old_str: + ui.print_("No changes; aborting.") + return None + + # Parse the updated data. + try: + return load(new_str) + except yaml.YAMLError as e: + ui.print_("Invalid YAML: {}".format(e)) + if not ui.input_yn("Edit again to fix? (Y/n)", True): + return None + + # Remove the temporary file before returning. + finally: + os.remove(new.name) + def apply_data(self, objs, old_data, new_data): """Take potentially-updated data and apply it to a set of Model From f2c8e9ff07846e4578bf9d9f185b136334843645 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 16 Nov 2015 21:15:48 +0100 Subject: [PATCH 0195/2280] Add "not" query operator, initial draft * Add support for user friendly "not" operator in queries without requiring to use regular expressions, via adding NotQuery to beets.dbcore.query. * Update the prefix list at library.parse_query_parts() and the query parsing mechanisms in order to create a NotQuery when the prefix is found. * Add two TestCases, NotQueryMatchTest as the negated version of MatchTest, and the more generic NotQueryTest for testing the integration of the NotQuery with the rest of the existing Query subclasses. --- beets/dbcore/query.py | 18 ++++ beets/dbcore/queryparse.py | 22 +++- beets/library.py | 4 +- test/test_query.py | 200 +++++++++++++++++++++++++++++++++++++ 4 files changed, 240 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index c04e734b8..4681f2044 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -447,6 +447,24 @@ class OrQuery(MutableCollectionQuery): return any([q.match(item) for q in self.subqueries]) +class NotQuery(MutableCollectionQuery): + """A query that matches the negation of its `subquery`, as a shorcut for + performing `not(subquery)` without using regular expressions. + + TODO: revise class hierarchy, probably limiting to one subquery + """ + def clause(self): + clause, subvals = self.clause_with_joiner('TODO') + if clause: + return 'not ({0})'.format(clause), subvals + else: + # special case for RegexpQuery, (None, ()) + return clause, subvals + + def match(self, item): + return not all([q.match(item) for q in self.subqueries]) + + class TrueQuery(Query): """A query that always matches.""" def clause(self): diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 89b7bd64a..88bcbd601 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -96,17 +96,33 @@ def construct_query_part(model_cls, prefixes, query_part): key, pattern, query_class = \ parse_query_part(query_part, query_classes, prefixes) + # Handle negation: set negation flag, and recover the original query_class. + negate = query_class is query.NotQuery + if negate: + query_class = query_classes.get(key, query.SubstringQuery) + # No key specified. if key is None: if issubclass(query_class, query.FieldQuery): # The query type matches a specific field, but none was # specified. So we use a version of the query that matches # any field. - return query.AnyFieldQuery(pattern, model_cls._search_fields, - query_class) + q = query.AnyFieldQuery(pattern, model_cls._search_fields, + query_class) + if negate: + return query.NotQuery([q]) + else: + return q else: # Other query type. - return query_class(pattern) + if negate: + return query.NotQuery([query_class(pattern)]) + else: + return query_class(pattern) + else: + if negate: + return query.NotQuery([query_class(key.lower(), pattern, + key in model_cls._fields)]) key = key.lower() return query_class(key.lower(), pattern, key in model_cls._fields) diff --git a/beets/library.py b/beets/library.py index cad39c232..37ab005b8 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1105,7 +1105,9 @@ def parse_query_parts(parts, model_cls): special path query detection. """ # Get query types and their prefix characters. - prefixes = {':': dbcore.query.RegexpQuery} + prefixes = {':': dbcore.query.RegexpQuery, + # TODO: decide on a better symbol, or other syntax + u'\u00ac': dbcore.query.NotQuery} prefixes.update(plugins.queries()) # Special-case path-like queries, which are non-field queries diff --git a/test/test_query.py b/test/test_query.py index 0515c2910..68558c054 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -714,6 +714,206 @@ class NoneQueryTest(unittest.TestCase, TestHelper): self.assertInResult(item, matched) +class NotQueryMatchTest(_common.TestCase): + """Test `query.NotQuery` matching against a single item, using the same + cases and assertions as on `MatchTest`, plus assertion on the negated + queries (ie. assertTrue(q) -> assertFalse(NotQuery(q))). + """ + def setUp(self): + super(NotQueryMatchTest, self).setUp() + self.item = _common.item() + + def test_regex_match_positive(self): + q = dbcore.query.RegexpQuery('album', '^the album$') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_regex_match_negative(self): + q = dbcore.query.RegexpQuery('album', '^album$') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_regex_match_non_string_value(self): + q = dbcore.query.RegexpQuery('disc', '^6$') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_substring_match_positive(self): + q = dbcore.query.SubstringQuery('album', 'album') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_substring_match_negative(self): + q = dbcore.query.SubstringQuery('album', 'ablum') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_substring_match_non_string_value(self): + q = dbcore.query.SubstringQuery('disc', '6') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_year_match_positive(self): + q = dbcore.query.NumericQuery('year', '1') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_year_match_negative(self): + q = dbcore.query.NumericQuery('year', '10') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_bitrate_range_positive(self): + q = dbcore.query.NumericQuery('bitrate', '100000..200000') + self.assertTrue(q.match(self.item)) + self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_bitrate_range_negative(self): + q = dbcore.query.NumericQuery('bitrate', '200000..300000') + self.assertFalse(q.match(self.item)) + self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + + def test_open_range(self): + q = dbcore.query.NumericQuery('bitrate', '100000..') + dbcore.query.NotQuery((q,)) + + +class NotQueryTest(DummyDataTestCase): + """Test `query.NotQuery` against the dummy data: + - `test_type_xxx`: tests for the negation of a particular XxxQuery class. + + TODO: add test_type_bytes, for ByteQuery? + """ + def assertNegationProperties(self, q): + """Given a Query `q`, assert that: + - q OR not(q) == all items + - q AND not(q) == 0 + - not(not(q)) == q + """ + not_q = dbcore.query.NotQuery([q]) + # assert using OrQuery, AndQuery + q_or = dbcore.query.OrQuery([q, not_q]) + q_and = dbcore.query.AndQuery([q, not_q]) + self.assert_items_matched_all(self.lib.items(q_or)) + self.assert_items_matched(self.lib.items(q_and), []) + + # assert manually checking the item titles + all_titles = set([i.title for i in self.lib.items()]) + q_results = set([i.title for i in self.lib.items(q)]) + not_q_results = set([i.title for i in self.lib.items(not_q)]) + self.assertEqual(q_results.union(not_q_results), all_titles) + self.assertEqual(q_results.intersection(not_q_results), set()) + + # round trip + not_not_q = dbcore.query.NotQuery([not_q]) + self.assertEqual([i.title for i in self.lib.items(q)], + [i.title for i in self.lib.items(not_not_q)]) + + def test_type_and(self): + # not(a and b) <-> not(a) or not(b) + q = dbcore.query.AndQuery([dbcore.query.BooleanQuery('comp', True), + dbcore.query.NumericQuery('year', '2002')]) + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['foo bar', 'beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_anyfield(self): + q = dbcore.query.AnyFieldQuery('foo', ['title', 'artist', 'album'], + dbcore.query.SubstringQuery) + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['baz qux']) + self.assertNegationProperties(q) + + def test_type_boolean(self): + q = dbcore.query.BooleanQuery('comp', True) + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_date(self): + q = dbcore.query.DateQuery('mtime', '0.0') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, []) + self.assertNegationProperties(q) + + def test_type_false(self): + q = dbcore.query.FalseQuery() + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched_all(not_results) + self.assertNegationProperties(q) + + def test_type_match(self): + q = dbcore.query.MatchQuery('year', '2003') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['foo bar', 'baz qux']) + self.assertNegationProperties(q) + + def test_type_none(self): + q = dbcore.query.NoneQuery('rg_track_gain') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, []) + self.assertNegationProperties(q) + + def test_type_numeric(self): + q = dbcore.query.NumericQuery('year', '2001..2002') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_or(self): + # not(a or b) <-> not(a) and not(b) + q = dbcore.query.OrQuery([dbcore.query.BooleanQuery('comp', True), + dbcore.query.NumericQuery('year', '2002')]) + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_regexp(self): + q = dbcore.query.RegexpQuery('artist', '^t') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['foo bar']) + self.assertNegationProperties(q) + + def test_type_substring(self): + q = dbcore.query.SubstringQuery('album', 'ba') + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, ['beets 4 eva']) + self.assertNegationProperties(q) + + def test_type_true(self): + q = dbcore.query.TrueQuery() + not_results = self.lib.items(dbcore.query.NotQuery([q])) + self.assert_items_matched(not_results, []) + self.assertNegationProperties(q) + + def test_fast_vs_slow(self): + """Test that the results are the same regardless of the `fast` flag + for negated `FieldQuery`s. + + TODO: investigate NoneQuery(fast=False), as it is raising + AttributeError: type object 'NoneQuery' has no attribute 'field' + at NoneQuery.match() (due to being @classmethod, and no self?) + """ + classes = [(dbcore.query.DateQuery, ['mtime', '0.0']), + (dbcore.query.MatchQuery, ['artist', 'one']), + # (dbcore.query.NoneQuery, ['rg_track_gain']), + (dbcore.query.NumericQuery, ['year', '2002']), + (dbcore.query.StringFieldQuery, ['year', '2001']), + (dbcore.query.RegexpQuery, ['album', '^.a']), + (dbcore.query.SubstringQuery, ['title', 'x'])] + + for klass, args in classes: + q_fast = dbcore.query.NotQuery([klass(*(args + [True]))]) + q_slow = dbcore.query.NotQuery([klass(*(args + [False]))]) + + try: + self.assertEqual([i.title for i in self.lib.items(q_fast)], + [i.title for i in self.lib.items(q_slow)]) + except NotImplementedError: + # ignore classes that do not provide `fast` implementation + pass + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From d87a7474776d6f498e952c230a1b4ade96ca9e06 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 16 Nov 2015 12:43:59 -0800 Subject: [PATCH 0196/2280] Condense edit plugin documentation Also avoided adding some unused command-line options. --- beetsplug/edit.py | 2 +- docs/plugins/edit.rst | 59 +++++++++++++++++-------------------------- 2 files changed, 24 insertions(+), 37 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index b31f4c5f5..e444ad3de 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -96,7 +96,7 @@ class EditPlugin(plugins.BeetsPlugin): action='store_true', dest='all', help='edit all fields', ) - edit_command.parser.add_all_common_options() + edit_command.parser.add_album_option() edit_command.func = self._edit_command return [edit_command] diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 28ac21681..5f3083948 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -1,49 +1,36 @@ Edit Plugin -============ -The ``edit`` plugin lets you open the tags, fields from a group of items, edit them in a text-editor and save them back. -Add the ``edit`` plugin to your ``plugins:`` in your ``config.yaml``. Then -simply do a query. -:: +=========== - beet edit beatles - beet edit beatles -a - beet edit beatles -f '$title $lyrics' +The ``edit`` plugin lets you modify music metadata using your favorite text +editor. +Enable the ``edit`` plugin in your configuration (see :ref:`using-plugins`) and +then type:: + beet edit QUERY -You get a list of hits to edit.``edit`` opens your standard text-editor with a list of your hits and for each hit a bunch of fields. -Without anything specified in your ``config.yaml`` for ``edit:`` you will see +Your text editor (i.e., the command in your ``$EDITOR`` environment variable) +will open with a list of tracks to edit. Make your changes and exit your text +editor to apply them to your music. -for items -:: +Command-Line Options +-------------------- - $track-$title-$artist-$album +The ``edit`` command has these command-line options: -and for albums -:: - - $album-$albumartist - -You can get extra fields from the cmdline by adding -:: - - -e year -e comments - - -If you add ``--all`` you get all the fields. - -After you edit the values in your text-editor - *and you may only edit the values, no deleting fields or adding fields!* - you save the file and you get a summary of your changes. Check em. Apply the changes into your library. +- ``-a`` or ``--album``: Edit albums instead of individual items. +- ``-e FIELD`` or ``--extra FIELD``: Specify an additional field to edit + (in addition to the defaults set in the configuration). +- ``--all``: Edit *all* available fields. Configuration ------------- -Make a ``edit:`` section in your config.yaml ``(beet config -e)`` -:: +To configure the plugin, make an ``edit:`` section in your configuration +file. The available options are: - edit: - albumfields: genre album - itemfields: track artist - -* The ``albumfields:`` and ``itemfields:`` is a list of fields you want to change. - ``albumfields:`` gets picked if you put ``-a`` in your search query, else ``itemfields:``. For a list of fields - do the ``beet fields`` command. Or put in a faulty one, hit enter and you get a list of available field. +- **itemfields**: A space-separated list of item fields to include in the + editor by default. + Default: ``track title artist album`` +- **albumfields**: The same when editing albums (with the ``-a`` option). + Default: ``album albumartist`` From f767f1c2a36d71c8adc4d042ec6d782207840e79 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 16 Nov 2015 13:01:24 -0800 Subject: [PATCH 0197/2280] New confirmation prompt We now ask for a trinary edit/apply/cancel confirmation *after* showing the updates. This lets you decide whether you're done based on a "preview" of the changes and keep editing if they don't look right. --- beetsplug/edit.py | 76 +++++++++++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 35 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index e444ad3de..3a5f180ce 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -137,42 +137,36 @@ class EditPlugin(plugins.BeetsPlugin): return set(fields) def edit(self, album, objs, fields): - """The core editor logic. + """The core editor function. - `album`: A flag indicating whether we're editing Items or Albums. - `objs`: The `Item`s or `Album`s to edit. - `fields`: The set of field names to edit (or None to edit everything). """ - # Get the content to edit as raw data structures. - data = [flatten(o, fields) for o in objs] - # Present the YAML to the user and let her change it. - new_data = self.edit_data(data) - if new_data is None: - # Editing failed. - return - - # Apply the updated metadata to the objects. - self.apply_data(objs, data, new_data) + success = self.edit_objects(objs, fields) # Save the new data. - self.save_write(objs) + if success: + self.save_write(objs) - def edit_data(self, data): - """Dump a data structure to a file as text, ask the user to edit - it, and then read back the updated data. + def edit_objects(self, objs, fields): + """Dump a set of Model objects to a file as text, ask the user + to edit it, and apply any changes to the objects. - If something goes wrong during editing, return None to indicate - the process should abort. + Return a boolean indicating whether the edit succeeded. """ - # Set up a temporary file with the initial data for editi + # Get the content to edit as raw data structures. + old_data = [flatten(o, fields) for o in objs] + + # Set up a temporary file with the initial data for editing. new = NamedTemporaryFile(suffix='.yaml', delete=False) - old_str = dump(data) + old_str = dump(old_data) new.write(old_str) new.close() - # Loop until we have parseable data. + # Loop until we have parseable data and the user confirms. try: while True: # Ask the user to edit the data. @@ -184,21 +178,43 @@ class EditPlugin(plugins.BeetsPlugin): new_str = f.read() if new_str == old_str: ui.print_("No changes; aborting.") - return None + return False # Parse the updated data. try: - return load(new_str) + new_data = load(new_str) except yaml.YAMLError as e: ui.print_("Invalid YAML: {}".format(e)) - if not ui.input_yn("Edit again to fix? (Y/n)", True): - return None + if ui.input_yn("Edit again to fix? (Y/n)", True): + continue + else: + return False + + # Show the changes. + self.apply_data(objs, old_data, new_data) + changed = False + for obj in objs: + changed |= ui.show_model_changes(obj) + if not changed: + ui.print_('No changes to apply.') + return False + + # Confirm the changes. + choice = ui.input_options(('continue Editing', 'apply', 'cancel')) + if choice == 'a': # Apply. + return True + elif choice == 'c': # Cancel. + return False + elif choice == 'e': # Keep editing. + # Reset the temporary changes to the objects. + for objs in objs: + obj.read() + continue # Remove the temporary file before returning. finally: os.remove(new.name) - def apply_data(self, objs, old_data, new_data): """Take potentially-updated data and apply it to a set of Model objects. @@ -230,16 +246,6 @@ class EditPlugin(plugins.BeetsPlugin): def save_write(self, objs): """Save a list of updated Model objects to the database. """ - # Display and confirm the changes. - changed = False - for obj in objs: - changed |= ui.show_model_changes(obj) - if not changed: - ui.print_('No changes to apply.') - return - if not ui.input_yn('Apply changes? (y/n)'): - return - # Save to the database and possibly write tags. for ob in objs: if ob._dirty: From 4db91c8bd252dbd8d175604c3d0b09e14ee25f09 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 16 Nov 2015 13:03:50 -0800 Subject: [PATCH 0198/2280] Fix a too-long line --- beetsplug/edit.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 3a5f180ce..92436d867 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -200,7 +200,9 @@ class EditPlugin(plugins.BeetsPlugin): return False # Confirm the changes. - choice = ui.input_options(('continue Editing', 'apply', 'cancel')) + choice = ui.input_options( + ('continue Editing', 'apply', 'cancel') + ) if choice == 'a': # Apply. return True elif choice == 'c': # Cancel. From 0d459752d9214c3a8462fb0e64a819d70b25863a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 16 Nov 2015 13:55:12 -0800 Subject: [PATCH 0199/2280] Update edit plugin tests --- test/test_edit.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index c72eeee73..0b7b76254 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -126,8 +126,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit titles self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, - # Apply changes? n - ['n']) + # Cancel. + ['c']) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') @@ -138,8 +138,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit titles self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, - # Apply changes? y - ['y']) + # Apply changes. + ['a']) self.assertCounts(write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') @@ -151,8 +151,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit title self.run_mocked_command({'replacements': {u't\u00eftle 9': u'modified t\u00eftle 9'}}, - # Apply changes? y - ['y']) + # Apply changes. + ['a']) self.assertCounts(write_call_count=1,) # no changes except on last item @@ -179,8 +179,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # edit album self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, - # Apply changes? y - ['y']) + # Apply changes. + ['a']) self.assertCounts(write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, @@ -195,8 +195,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): # append "foo: bar" to item with id == 1 self.run_mocked_command({'replacements': {u'id: 1': u'id: 1\nfoo: bar'}}, - # Apply changes? y - ['y']) + # Apply changes. + ['a']) self.assertEqual(self.lib.items('id:1')[0].foo, 'bar') self.assertCounts(write_call_count=1, @@ -206,8 +206,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Album query (-a), edit album field, apply changes.""" self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, - # Apply changes? y - ['y'], + # Apply changes. + ['a'], args=['-a']) self.album.load() @@ -220,8 +220,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Album query (-a), edit albumartist field, apply changes.""" self.run_mocked_command({'replacements': {u'album artist': u'modified album artist'}}, - # Apply changes? y - ['y'], + # Apply changes. + ['a'], args=['-a']) self.album.load() @@ -235,8 +235,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): document).""" # edit the yaml file to an invalid file self.run_mocked_command({'contents': '!MALFORMED'}, - # no stdin - []) + # Edit again to fix? No. + ['n']) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') From 8e9d335a87a9741ed1ed4f0eb0c409cc72f422fa Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 17 Nov 2015 10:26:36 -0800 Subject: [PATCH 0200/2280] Tear down Item.write mock --- test/test_edit.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 0b7b76254..56a13525a 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -16,12 +16,10 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import codecs -from mock import Mock, patch +from mock import patch from test._common import unittest from test.helper import TestHelper, control_stdin -from beets import library - class ModifyFileMocker(object): """Helper for modifying a file, replacing or editing its contents. Used for @@ -84,9 +82,11 @@ class EditCommandTest(unittest.TestCase, TestHelper): item in self.album.items()] # keep track of write()s - library.Item.write = Mock() + self.write_patcher = patch('beets.library.Item.write') + self.mock_write = self.write_patcher.start() def tearDown(self): + self.write_patcher.stop() self.teardown_beets() self.unload_plugins() @@ -103,7 +103,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Several common assertions on Album, Track and call counts.""" self.assertEqual(len(self.lib.albums()), album_count) self.assertEqual(len(self.lib.items()), track_count) - self.assertEqual(library.Item.write.call_count, write_call_count) + self.assertEqual(self.mock_write.call_count, write_call_count) self.assertTrue(all(i.title.startswith(title_starts_with) for i in self.lib.items())) From f68dc4652aa7d505e18c151f255992592d92507d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 17 Nov 2015 13:14:15 -0800 Subject: [PATCH 0201/2280] Fix a typo --- beetsplug/edit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 92436d867..63cdef815 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -209,7 +209,7 @@ class EditPlugin(plugins.BeetsPlugin): return False elif choice == 'e': # Keep editing. # Reset the temporary changes to the objects. - for objs in objs: + for obj in objs: obj.read() continue From b33d25a0adf79957a0798fc729a6dedafcb03ece Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 17 Nov 2015 14:39:40 -0800 Subject: [PATCH 0202/2280] --extra option can use any field Not just the built-in fields. --- beetsplug/edit.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 63cdef815..3cd014402 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -19,7 +19,6 @@ from __future__ import (division, absolute_import, print_function, from beets import plugins from beets import util -from beets import library from beets import ui from beets.ui.commands import _do_query import subprocess @@ -85,11 +84,9 @@ class EditPlugin(plugins.BeetsPlugin): ) edit_command.parser.add_option( '-e', '--extra', + metavar='FIELD', action='append', - type='choice', - choices=library.Item.all_keys() + - library.Album.all_keys(), - help='add additional fields to edit', + help='edit this field also', ) edit_command.parser.add_option( '--all', From 775a48eb28ce6e505a25ec2744448f2dbfee294a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 17 Nov 2015 14:40:52 -0800 Subject: [PATCH 0203/2280] --extra/-e is now --field/-f --- beetsplug/edit.py | 4 ++-- docs/plugins/edit.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 3cd014402..719fbd032 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -83,7 +83,7 @@ class EditPlugin(plugins.BeetsPlugin): help='interactively edit metadata' ) edit_command.parser.add_option( - '-e', '--extra', + '-f', '--field', metavar='FIELD', action='append', help='edit this field also', @@ -112,7 +112,7 @@ class EditPlugin(plugins.BeetsPlugin): if opts.all: fields = None else: - fields = self._get_fields(opts.album, opts.extra) + fields = self._get_fields(opts.album, opts.field) self.edit(opts.album, objs, fields) def _get_fields(self, album, extra): diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 5f3083948..507d56950 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -19,7 +19,7 @@ Command-Line Options The ``edit`` command has these command-line options: - ``-a`` or ``--album``: Edit albums instead of individual items. -- ``-e FIELD`` or ``--extra FIELD``: Specify an additional field to edit +- ``-f FIELD`` or ``--field FIELD``: Specify an additional field to edit (in addition to the defaults set in the configuration). - ``--all``: Edit *all* available fields. From dd8b80e32004129c587134ee51a916155cdbf811 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 18 Nov 2015 14:54:20 +0100 Subject: [PATCH 0204/2280] Make NotQuery subclass Query, update tests * Modify NotQuery so it subclasses Query instead of MutableCollectionQuery. * Update instances where NotQuery objects are created on tests and queryparse, as NotQuery expects a single Query as a parameter to the constructor instead of a list of Queries. --- beets/dbcore/query.py | 22 +++++++++++----- beets/dbcore/queryparse.py | 13 +++++---- test/test_query.py | 54 +++++++++++++++++++------------------- 3 files changed, 49 insertions(+), 40 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 4681f2044..b4c1d1445 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -447,14 +447,14 @@ class OrQuery(MutableCollectionQuery): return any([q.match(item) for q in self.subqueries]) -class NotQuery(MutableCollectionQuery): +class NotQuery(Query): """A query that matches the negation of its `subquery`, as a shorcut for - performing `not(subquery)` without using regular expressions. + performing `not(subquery)` without using regular expressions.""" + def __init__(self, subquery): + self.subquery = subquery - TODO: revise class hierarchy, probably limiting to one subquery - """ def clause(self): - clause, subvals = self.clause_with_joiner('TODO') + clause, subvals = self.subquery.clause() if clause: return 'not ({0})'.format(clause), subvals else: @@ -462,7 +462,17 @@ class NotQuery(MutableCollectionQuery): return clause, subvals def match(self, item): - return not all([q.match(item) for q in self.subqueries]) + return not self.subquery.match(item) + + def __repr__(self): + return "{0.__class__.__name__}({0.subquery})".format(self) + + def __eq__(self, other): + return super(NotQuery, self).__eq__(other) and \ + self.subquery == other.subquery + + def __hash__(self): + return hash(('not', hash(self.subquery))) class TrueQuery(Query): diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 88bcbd601..565fe26f1 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -110,22 +110,21 @@ def construct_query_part(model_cls, prefixes, query_part): q = query.AnyFieldQuery(pattern, model_cls._search_fields, query_class) if negate: - return query.NotQuery([q]) + return query.NotQuery(q) else: return q else: # Other query type. if negate: - return query.NotQuery([query_class(pattern)]) + return query.NotQuery(query_class(pattern)) else: return query_class(pattern) - else: - if negate: - return query.NotQuery([query_class(key.lower(), pattern, - key in model_cls._fields)]) key = key.lower() - return query_class(key.lower(), pattern, key in model_cls._fields) + q = query_class(key.lower(), pattern, key in model_cls._fields) + if negate: + return query.NotQuery(q) + return q def query_from_strings(query_cls, model_cls, prefixes, query_parts): diff --git a/test/test_query.py b/test/test_query.py index 68558c054..ae5a84b88 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -726,56 +726,56 @@ class NotQueryMatchTest(_common.TestCase): def test_regex_match_positive(self): q = dbcore.query.RegexpQuery('album', '^the album$') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_regex_match_negative(self): q = dbcore.query.RegexpQuery('album', '^album$') self.assertFalse(q.match(self.item)) - self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_regex_match_non_string_value(self): q = dbcore.query.RegexpQuery('disc', '^6$') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_positive(self): q = dbcore.query.SubstringQuery('album', 'album') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_negative(self): q = dbcore.query.SubstringQuery('album', 'ablum') self.assertFalse(q.match(self.item)) - self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_non_string_value(self): q = dbcore.query.SubstringQuery('disc', '6') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_year_match_positive(self): q = dbcore.query.NumericQuery('year', '1') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_year_match_negative(self): q = dbcore.query.NumericQuery('year', '10') self.assertFalse(q.match(self.item)) - self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_bitrate_range_positive(self): q = dbcore.query.NumericQuery('bitrate', '100000..200000') self.assertTrue(q.match(self.item)) - self.assertFalse(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_bitrate_range_negative(self): q = dbcore.query.NumericQuery('bitrate', '200000..300000') self.assertFalse(q.match(self.item)) - self.assertTrue(dbcore.query.NotQuery((q,)).match(self.item)) + self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_open_range(self): q = dbcore.query.NumericQuery('bitrate', '100000..') - dbcore.query.NotQuery((q,)) + dbcore.query.NotQuery(q) class NotQueryTest(DummyDataTestCase): @@ -790,7 +790,7 @@ class NotQueryTest(DummyDataTestCase): - q AND not(q) == 0 - not(not(q)) == q """ - not_q = dbcore.query.NotQuery([q]) + not_q = dbcore.query.NotQuery(q) # assert using OrQuery, AndQuery q_or = dbcore.query.OrQuery([q, not_q]) q_and = dbcore.query.AndQuery([q, not_q]) @@ -805,7 +805,7 @@ class NotQueryTest(DummyDataTestCase): self.assertEqual(q_results.intersection(not_q_results), set()) # round trip - not_not_q = dbcore.query.NotQuery([not_q]) + not_not_q = dbcore.query.NotQuery(not_q) self.assertEqual([i.title for i in self.lib.items(q)], [i.title for i in self.lib.items(not_not_q)]) @@ -813,50 +813,50 @@ class NotQueryTest(DummyDataTestCase): # not(a and b) <-> not(a) or not(b) q = dbcore.query.AndQuery([dbcore.query.BooleanQuery('comp', True), dbcore.query.NumericQuery('year', '2002')]) - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['foo bar', 'beets 4 eva']) self.assertNegationProperties(q) def test_type_anyfield(self): q = dbcore.query.AnyFieldQuery('foo', ['title', 'artist', 'album'], dbcore.query.SubstringQuery) - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['baz qux']) self.assertNegationProperties(q) def test_type_boolean(self): q = dbcore.query.BooleanQuery('comp', True) - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['beets 4 eva']) self.assertNegationProperties(q) def test_type_date(self): q = dbcore.query.DateQuery('mtime', '0.0') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, []) self.assertNegationProperties(q) def test_type_false(self): q = dbcore.query.FalseQuery() - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched_all(not_results) self.assertNegationProperties(q) def test_type_match(self): q = dbcore.query.MatchQuery('year', '2003') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['foo bar', 'baz qux']) self.assertNegationProperties(q) def test_type_none(self): q = dbcore.query.NoneQuery('rg_track_gain') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, []) self.assertNegationProperties(q) def test_type_numeric(self): q = dbcore.query.NumericQuery('year', '2001..2002') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['beets 4 eva']) self.assertNegationProperties(q) @@ -864,25 +864,25 @@ class NotQueryTest(DummyDataTestCase): # not(a or b) <-> not(a) and not(b) q = dbcore.query.OrQuery([dbcore.query.BooleanQuery('comp', True), dbcore.query.NumericQuery('year', '2002')]) - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['beets 4 eva']) self.assertNegationProperties(q) def test_type_regexp(self): q = dbcore.query.RegexpQuery('artist', '^t') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['foo bar']) self.assertNegationProperties(q) def test_type_substring(self): q = dbcore.query.SubstringQuery('album', 'ba') - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, ['beets 4 eva']) self.assertNegationProperties(q) def test_type_true(self): q = dbcore.query.TrueQuery() - not_results = self.lib.items(dbcore.query.NotQuery([q])) + not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, []) self.assertNegationProperties(q) @@ -903,8 +903,8 @@ class NotQueryTest(DummyDataTestCase): (dbcore.query.SubstringQuery, ['title', 'x'])] for klass, args in classes: - q_fast = dbcore.query.NotQuery([klass(*(args + [True]))]) - q_slow = dbcore.query.NotQuery([klass(*(args + [False]))]) + q_fast = dbcore.query.NotQuery(klass(*(args + [True]))) + q_slow = dbcore.query.NotQuery(klass(*(args + [False]))) try: self.assertEqual([i.title for i in self.lib.items(q_fast)], From 0293504a24c2265c41e3ef235bf23b8b314b2c89 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 18 Nov 2015 16:59:50 +0100 Subject: [PATCH 0205/2280] Update negation query syntax, prefix always first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update the negation query sintax so that the negation prefix ("-" or "¬") is always the first part of a query, instead of after the ":" separator. * Modify queryparse, so that the detection of the negation is done inside parse_query_part() (using the modified PARSE_QUERY_PART_REGEX, and returning the negation flag) instead of construct_query_part. * Revert the prefixes dict on beets.library to the original dict (only one item, with the RegexpQuery prefix). --- beets/dbcore/queryparse.py | 22 +++++++++++----------- beets/library.py | 4 +--- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 565fe26f1..ca01f0433 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -23,6 +23,10 @@ import beets PARSE_QUERY_PART_REGEX = re.compile( # Non-capturing optional segment for the keyword. + r'(?:' + ur'(-|\u00ac)' # Negation prefixes + r')?' + r'(?:' r'(\S+?)' # The field key. r'(? Date: Wed, 18 Nov 2015 17:27:22 +0100 Subject: [PATCH 0206/2280] Add NotQuery syntax tests * Add tests to NotQueryTest for testing the results of using queries with negation. * Fix issue on test_dbcore due to the modifications on the tuple returned by parse_query_part (the number of elements was changed from 3 to 4). --- test/test_dbcore.py | 2 +- test/test_query.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 6fc07d0f6..04fe60d46 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -351,7 +351,7 @@ class QueryParseTest(unittest.TestCase): part, {'year': dbcore.query.NumericQuery}, {':': dbcore.query.RegexpQuery}, - ) + )[:-1] # remove the negate flag def test_one_basic_term(self): q = 'test' diff --git a/test/test_query.py b/test/test_query.py index ae5a84b88..64328233f 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -781,6 +781,7 @@ class NotQueryMatchTest(_common.TestCase): class NotQueryTest(DummyDataTestCase): """Test `query.NotQuery` against the dummy data: - `test_type_xxx`: tests for the negation of a particular XxxQuery class. + - `test_get_yyy`: tests on query strings (similar to `GetTest`) TODO: add test_type_bytes, for ByteQuery? """ @@ -886,6 +887,44 @@ class NotQueryTest(DummyDataTestCase): self.assert_items_matched(not_results, []) self.assertNegationProperties(q) + def test_get_prefixes_keyed(self): + """Test both negation prefixes on a keyed query.""" + q0 = '-title:qux' + q1 = '\u00actitle:qux' + results0 = self.lib.items(q0) + results1 = self.lib.items(q1) + self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(results1, ['foo bar', 'beets 4 eva']) + + def test_get_prefixes_unkeyed(self): + """Test both negation prefixes on an unkeyed query.""" + q0 = '-qux' + q1 = '\u00acqux' + results0 = self.lib.items(q0) + results1 = self.lib.items(q1) + self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(results1, ['foo bar', 'beets 4 eva']) + + def test_get_keyed_regexp(self): + q = r'-artist::t.+r' + results = self.lib.items(q) + self.assert_items_matched(results, ['foo bar', 'baz qux']) + + def test_get_one_unkeyed_regexp(self): + q = r'-:x$' + results = self.lib.items(q) + self.assert_items_matched(results, ['foo bar', 'beets 4 eva']) + + def test_get_multiple_terms(self): + q = 'baz -bar' + results = self.lib.items(q) + self.assert_items_matched(results, ['baz qux']) + + def test_get_mixed_terms(self): + q = 'baz -title:bar' + results = self.lib.items(q) + self.assert_items_matched(results, ['baz qux']) + def test_fast_vs_slow(self): """Test that the results are the same regardless of the `fast` flag for negated `FieldQuery`s. From e69b3b3c5d38a36868fdafaa2f540f65e1227c71 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 18 Nov 2015 17:40:47 +0100 Subject: [PATCH 0207/2280] Fix NotQuery assertion by using sets, not lists * Fix issue with an assertion that was order-sensitive and caused a problem on some tox runs. --- test/test_query.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 64328233f..5720c65cf 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -807,8 +807,8 @@ class NotQueryTest(DummyDataTestCase): # round trip not_not_q = dbcore.query.NotQuery(not_q) - self.assertEqual([i.title for i in self.lib.items(q)], - [i.title for i in self.lib.items(not_not_q)]) + self.assertEqual(set([i.title for i in self.lib.items(q)]), + set([i.title for i in self.lib.items(not_not_q)])) def test_type_and(self): # not(a and b) <-> not(a) or not(b) From 40bfed756b8cef2ce52b9449602511f78cab8e11 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 19 Nov 2015 18:04:47 +0100 Subject: [PATCH 0208/2280] Revise not query syntax, cleanup, modify docstring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Revise the NotQuery syntax, replacing the '¬' character with '^'. Fix tests to conform to this change, and cleanup the PARSE_QUERY_PART_REGEX. * Modify parse_query_part() docstring to mention the negate parameter on the returned tuple, and added an example. --- beets/dbcore/queryparse.py | 17 ++++++++--------- test/test_query.py | 6 +++--- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index ca01f0433..c7b75a90c 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -23,9 +23,7 @@ import beets PARSE_QUERY_PART_REGEX = re.compile( # Non-capturing optional segment for the keyword. - r'(?:' - ur'(-|\u00ac)' # Negation prefixes - r')?' + r'(-|\^)?' # Negation prefixes. r'(?:' r'(\S+?)' # The field key. @@ -41,9 +39,9 @@ PARSE_QUERY_PART_REGEX = re.compile( def parse_query_part(part, query_classes={}, prefixes={}, default_class=query.SubstringQuery): """Take a query in the form of a key/value pair separated by a - colon and return a tuple of `(key, value, cls)`. `key` may be None, + colon and return a tuple of `(key, value, cls, negate)`. `key` may be None, indicating that any field may be matched. `cls` is a subclass of - `FieldQuery`. + `FieldQuery`. `negate` is a boolean indicating if the query is negated. The optional `query_classes` parameter maps field names to default query types; `default_class` is the fallback. `prefixes` is a map @@ -57,10 +55,11 @@ def parse_query_part(part, query_classes={}, prefixes={}, class is available, `default_class` is used. For instance, - 'stapler' -> (None, 'stapler', SubstringQuery) - 'color:red' -> ('color', 'red', SubstringQuery) - ':^Quiet' -> (None, '^Quiet', RegexpQuery) - 'color::b..e' -> ('color', 'b..e', RegexpQuery) + 'stapler' -> (None, 'stapler', SubstringQuery, False) + 'color:red' -> ('color', 'red', SubstringQuery, False) + ':^Quiet' -> (None, '^Quiet', RegexpQuery, False) + 'color::b..e' -> ('color', 'b..e', RegexpQuery, False) + '-color:red' -> ('color', 'red', SubstringQuery, True) Prefixes may be "escaped" with a backslash to disable the keying behavior. diff --git a/test/test_query.py b/test/test_query.py index 5720c65cf..c415b7f1c 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -890,7 +890,7 @@ class NotQueryTest(DummyDataTestCase): def test_get_prefixes_keyed(self): """Test both negation prefixes on a keyed query.""" q0 = '-title:qux' - q1 = '\u00actitle:qux' + q1 = '^title:qux' results0 = self.lib.items(q0) results1 = self.lib.items(q1) self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) @@ -899,13 +899,13 @@ class NotQueryTest(DummyDataTestCase): def test_get_prefixes_unkeyed(self): """Test both negation prefixes on an unkeyed query.""" q0 = '-qux' - q1 = '\u00acqux' + q1 = '^qux' results0 = self.lib.items(q0) results1 = self.lib.items(q1) self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) self.assert_items_matched(results1, ['foo bar', 'beets 4 eva']) - def test_get_keyed_regexp(self): + def test_get_one_keyed_regexp(self): q = r'-artist::t.+r' results = self.lib.items(q) self.assert_items_matched(results, ['foo bar', 'baz qux']) From 3eb8008b1128cd0aa5273b714e9281a5b328d59f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 19 Nov 2015 18:41:01 +0100 Subject: [PATCH 0209/2280] added encoding as comment in files added line like # -*- coding: utf-8 -*- to all files with correct license in header --- beets/__init__.py | 1 + beets/art.py | 1 + beets/autotag/__init__.py | 1 + beets/autotag/hooks.py | 1 + beets/autotag/match.py | 1 + beets/autotag/mb.py | 1 + beets/dbcore/__init__.py | 1 + beets/dbcore/db.py | 1 + beets/dbcore/query.py | 1 + beets/dbcore/queryparse.py | 1 + beets/dbcore/types.py | 1 + beets/importer.py | 1 + beets/library.py | 1 + beets/logging.py | 1 + beets/mediafile.py | 1 + beets/plugins.py | 1 + beets/ui/__init__.py | 1 + beets/ui/commands.py | 1 + beets/util/__init__.py | 1 + beets/util/artresizer.py | 1 + beets/util/confit.py | 1 + beets/util/enumeration.py | 1 + beets/util/functemplate.py | 1 + beets/util/pipeline.py | 1 + beets/vfs.py | 1 + beetsplug/__init__.py | 1 + beetsplug/bench.py | 1 + beetsplug/bpd/__init__.py | 1 + beetsplug/bpd/gstplayer.py | 1 + beetsplug/bpm.py | 1 + beetsplug/bucket.py | 1 + beetsplug/chroma.py | 1 + beetsplug/convert.py | 1 + beetsplug/cue.py | 1 + beetsplug/discogs.py | 1 + beetsplug/duplicates.py | 1 + beetsplug/echonest.py | 1 + beetsplug/embedart.py | 1 + beetsplug/fetchart.py | 1 + beetsplug/filefilter.py | 1 + beetsplug/freedesktop.py | 1 + beetsplug/fromfilename.py | 1 + beetsplug/ftintitle.py | 1 + beetsplug/fuzzy.py | 1 + beetsplug/ihate.py | 1 + beetsplug/importfeeds.py | 1 + beetsplug/info.py | 1 + beetsplug/inline.py | 1 + beetsplug/ipfs.py | 1 + beetsplug/keyfinder.py | 1 + beetsplug/lastgenre/__init__.py | 1 + beetsplug/lastimport.py | 1 + beetsplug/lyrics.py | 1 + beetsplug/mbcollection.py | 1 + beetsplug/mbsync.py | 1 + beetsplug/metasync/__init__.py | 1 + beetsplug/metasync/amarok.py | 1 + beetsplug/metasync/itunes.py | 1 + beetsplug/missing.py | 1 + beetsplug/mpdstats.py | 2 +- beetsplug/mpdupdate.py | 1 + beetsplug/play.py | 1 + beetsplug/random.py | 1 + beetsplug/replaygain.py | 1 + beetsplug/rewrite.py | 1 + beetsplug/scrub.py | 1 + beetsplug/smartplaylist.py | 1 + beetsplug/the.py | 1 + beetsplug/types.py | 1 + beetsplug/web/__init__.py | 1 + beetsplug/zero.py | 1 + setup.py | 1 + test/_common.py | 1 + test/helper.py | 1 + test/lyrics_download_samples.py | 1 + test/test_art.py | 1 + test/test_autotag.py | 1 + test/test_convert.py | 1 + test/test_datequery.py | 1 + test/test_dbcore.py | 1 + test/test_echonest.py | 1 + test/test_embedart.py | 1 + test/test_fetchart.py | 1 + test/test_filefilter.py | 1 + test/test_files.py | 1 + test/test_ftintitle.py | 1 + test/test_importadded.py | 1 + test/test_importer.py | 1 + test/test_info.py | 1 + test/test_ipfs.py | 1 + test/test_keyfinder.py | 1 + test/test_lastgenre.py | 1 + test/test_lyrics.py | 1 + test/test_mb.py | 1 + test/test_mbsync.py | 1 + test/test_mediafile.py | 1 + test/test_mediafile_edge.py | 1 + test/test_metasync.py | 1 + test/test_mpdstats.py | 1 + test/test_pipeline.py | 1 + test/test_player.py | 1 + test/test_plugins.py | 1 + test/test_query.py | 1 + test/test_replaygain.py | 1 + test/test_smartplaylist.py | 1 + test/test_sort.py | 1 + test/test_template.py | 2 +- test/test_thumbnails.py | 1 + test/test_types_plugin.py | 1 + test/test_ui.py | 1 + test/test_ui_commands.py | 2 +- test/test_ui_importer.py | 1 + test/test_ui_init.py | 2 +- test/test_util.py | 1 + test/test_vfs.py | 1 + test/testall.py | 1 + 116 files changed, 116 insertions(+), 4 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 8447ef96f..0b64ac388 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/art.py b/beets/art.py index 79bdfefe4..9f280ca01 100644 --- a/beets/art.py +++ b/beets/art.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 6ccd59d09..9ad02b8eb 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index b2b635ad2..6b654573f 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/autotag/match.py b/beets/autotag/match.py index c747f47c2..f9146d027 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 78c5fb2f4..f823f7211 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/dbcore/__init__.py b/beets/dbcore/__init__.py index 093591882..059f1fc4f 100644 --- a/beets/dbcore/__init__.py +++ b/beets/dbcore/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index df796a134..d54e3a0d3 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index c04e734b8..0a67cbdae 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 89b7bd64a..34eea6b16 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 7f3b2e39e..40183c059 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/importer.py b/beets/importer.py index 5bdcaff8f..c26fbcbec 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/library.py b/beets/library.py index cad39c232..870c46856 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/logging.py b/beets/logging.py index dee5faf35..b1b0ad73c 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/mediafile.py b/beets/mediafile.py index 5fe1fa308..f2dc1027d 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/plugins.py b/beets/plugins.py index d06debe22..cf4c76036 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 4c99b937a..c51c3acb6 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 307945a03..2d943eee1 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 2a861ce88..ec8eec9c4 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 741ebda1b..c5dcb6055 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte # diff --git a/beets/util/confit.py b/beets/util/confit.py index 2614f7ed7..7dca300d7 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of Confit. # Copyright 2015, Adrian Sampson. # diff --git a/beets/util/enumeration.py b/beets/util/enumeration.py index dc0a6fa42..c7761be89 100644 --- a/beets/util/enumeration.py +++ b/beets/util/enumeration.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 3d5b0e871..e2854e205 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index a0bb6af38..62772540f 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beets/vfs.py b/beets/vfs.py index e3cebafb1..e7b7970d2 100644 --- a/beets/vfs.py +++ b/beets/vfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/__init__.py b/beetsplug/__init__.py index 811ee0539..6aba6481a 100644 --- a/beetsplug/__init__.py +++ b/beetsplug/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/bench.py b/beetsplug/bench.py index ebb9f981f..278704aa0 100644 --- a/beetsplug/bench.py +++ b/beetsplug/bench.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index ef02574fa..2b1f4a272 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index adac1f5a4..80f6622a6 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index 85c8d6636..f8074005a 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, aroquen # diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index d673b0bd4..32c25ed93 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte. # diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 3446661d3..028ba5ce1 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/convert.py b/beetsplug/convert.py index ca28d7ffd..fd82e80f2 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Jakob Schnitzer. # diff --git a/beetsplug/cue.py b/beetsplug/cue.py index 25205f8e8..59e27072e 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # Copyright 2015 Bruno Cauet # Split an album-file in tracks thanks a cue file diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 7ab2d217b..e9c912afb 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index a8ad4ac90..83bc492e5 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Pedro Silva. # diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index 312a8b620..0075cc835 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 6dc235979..632952dd8 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 6847d8828..e3769a260 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index 432388c5a..b3c26ff79 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Malte Ried. # diff --git a/beetsplug/freedesktop.py b/beetsplug/freedesktop.py index 675061925..7660d13fb 100644 --- a/beetsplug/freedesktop.py +++ b/beetsplug/freedesktop.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Matt Lichtenberg. # diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index dc040a0a2..bb3363bfe 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Jan-Erik Dahlin # diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index d2369bf52..71be9630a 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Verrus, # diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index d017ff0c2..cf6440438 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Philippe Mongeau. # diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index b4a877fbc..d795da130 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Blemjhoo Tezoulbr . # diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 6b0a46778..cdf59c122 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte. # diff --git a/beetsplug/info.py b/beetsplug/info.py index 82bcbe965..d6988d097 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/inline.py b/beetsplug/inline.py index fb99e729a..0f7279ecc 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index f785a582b..6e5a5c7d4 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # # Permission is hereby granted, free of charge, to any person obtaining diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index d76448a4c..33bfd4764 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index f276fe4f1..8242d9453 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index c2ba976fa..f0469c91c 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 16f669f53..0bd49589c 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 6dc724636..2e24ae59e 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # Copyright (c) 2011, Jeffrey Aylesworth # # Permission to use, copy, modify, and/or distribute this software for any diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 6e7c208a7..99456da2c 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Jakob Schnitzer. # diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index fd40590bb..7ddbb3091 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Heinz Wiesinger. # diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index b544c22ec..a591cf923 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Heinz Wiesinger. # diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index 17139f549..75a612c28 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Tom Jaspers. # diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 75b3e58e8..648b202ba 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Pedro Silva. # diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index fce04440a..dcf43ec62 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -1,4 +1,4 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Peter Schnebel and Johann Klähn. # diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index a6e14e48e..8b072ecf3 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/play.py b/beetsplug/play.py index eb04faeaa..a33074312 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, David Hamp-Gonsalves # diff --git a/beetsplug/random.py b/beetsplug/random.py index 43fb7957c..7f3317b81 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Philippe Mongeau. # diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 75f2ab947..422c345d8 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte, Yevgeny Bezman, and Adrian Sampson. # diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index fd6346f9b..b08fb1fb6 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index ac0017474..4636b477d 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index c88fe38c5..f404d98d1 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Dang Mai . # diff --git a/beetsplug/the.py b/beetsplug/the.py index 538b81245..d13eb1aca 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Blemjhoo Tezoulbr . # diff --git a/beetsplug/types.py b/beetsplug/types.py index dad892bc9..a203834d5 100644 --- a/beetsplug/types.py +++ b/beetsplug/types.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 18750ebb3..a6e6f55c9 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 8fe61a0b8..8e81473db 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Blemjhoo Tezoulbr . # diff --git a/setup.py b/setup.py index 94a1c7d27..c7e4af3a0 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. diff --git a/test/_common.py b/test/_common.py index 4588dbb41..9e6ec0f85 100644 --- a/test/_common.py +++ b/test/_common.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/helper.py b/test/helper.py index c23e036e4..0c9e2befa 100644 --- a/test/helper.py +++ b/test/helper.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index f144263fa..c340b3f05 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte # diff --git a/test/test_art.py b/test/test_art.py index e4a070b1a..04bfe3eed 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_autotag.py b/test/test_autotag.py index 59c564066..46059d461 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_convert.py b/test/test_convert.py index 034d8a465..86c6e5d2a 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_datequery.py b/test/test_datequery.py index 0533846bf..ba23b910d 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 6fc07d0f6..49fca2bb3 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_echonest.py b/test/test_echonest.py index 1289decd2..143d2633d 100644 --- a/test/test_echonest.py +++ b/test/test_echonest.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes # diff --git a/test/test_embedart.py b/test/test_embedart.py index a4c88a429..3cd67b54e 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_fetchart.py b/test/test_fetchart.py index b199e7139..0c8911c55 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_filefilter.py b/test/test_filefilter.py index a8a046a37..1b1d326f1 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Malte Ried. # diff --git a/test/test_files.py b/test/test_files.py index 27aa93cd8..e78c50511 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index 67b952a51..663cf2b68 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte. # diff --git a/test/test_importadded.py b/test/test_importadded.py index f070b1e60..7ca61318e 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Stig Inge Lea Bjornsen. # diff --git a/test/test_importer.py b/test/test_importer.py index 675ac7796..dd093377d 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_info.py b/test/test_info.py index e382f4872..797950be3 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_ipfs.py b/test/test_ipfs.py index cfb74f203..2b2acdc2d 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # # Permission is hereby granted, free of charge, to any person obtaining diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 95c06754a..8a3bfe4e3 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 4b1a50207..d61738fc5 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte. # diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 960a94e33..33b8c6bb5 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Fabrice Laporte. # diff --git a/test/test_mb.py b/test/test_mb.py index 7662e0722..d68be7e4d 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_mbsync.py b/test/test_mbsync.py index ff6e01cf3..47517f4ee 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_mediafile.py b/test/test_mediafile.py index cd149e7e4..784703f2c 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 7886abdd2..87b2b7c1f 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_metasync.py b/test/test_metasync.py index 8e2669c41..e37ef3364 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Tom Jaspers. # diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index c2db78f1f..b07da5e32 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015 # diff --git a/test/test_pipeline.py b/test/test_pipeline.py index aaa12d2a3..8c9191293 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_player.py b/test/test_player.py index 6115b92c2..6afa0ba21 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_plugins.py b/test/test_plugins.py index 2e8bedca1..8e6689c6d 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_query.py b/test/test_query.py index 0515c2910..36df04fd0 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 3eb93520f..e85c4504b 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes # diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index ddfa8a156..4d9826539 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Bruno Cauet. # diff --git a/test/test_sort.py b/test/test_sort.py index e763b6167..7fadc54b2 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_template.py b/test/test_template.py index 1a0daa42e..318c2d5b5 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -1,4 +1,4 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 0b4eddd05..2468e30b5 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Bruno Cauet # diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 7e0e6e082..57bfb2282 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # diff --git a/test/test_ui.py b/test/test_ui.py index c1c853e03..78e4f5891 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index dd8eb47a3..c8995aedf 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -1,4 +1,4 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 2c571925f..e8e43a6f7 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_ui_init.py b/test/test_ui_init.py index f31deefe7..667b0a56d 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -1,4 +1,4 @@ -# -*- coding: utf8 -*- +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_util.py b/test/test_util.py index b72410c9c..6dacb7f57 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/test_vfs.py b/test/test_vfs.py index 0d6b280e5..e1569b2c3 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/test/testall.py b/test/testall.py index 320e2c677..3e6255f6d 100755 --- a/test/testall.py +++ b/test/testall.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. From 6b408507f6e5cd8e94b598b794042b4ac5377665 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 19 Nov 2015 18:52:57 +0100 Subject: [PATCH 0210/2280] added encoding as comment in files added line like # -*- coding: utf-8 -*- to all files without license --- beets/util/bluelet.py | 2 ++ beetsplug/embyupdate.py | 2 ++ beetsplug/importadded.py | 2 ++ beetsplug/permissions.py | 2 ++ beetsplug/plexupdate.py | 2 ++ beetsplug/spotify.py | 2 ++ docs/conf.py | 2 ++ test/__init__.py | 2 ++ test/rsrc/beetsplug/test.py | 2 ++ test/test_config_command.py | 2 ++ test/test_embyupdate.py | 2 ++ test/test_ihate.py | 2 ++ test/test_importfeeds.py | 2 ++ test/test_logging.py | 2 ++ test/test_permissions.py | 2 ++ test/test_plexupdate.py | 2 ++ test/test_spotify.py | 2 ++ test/test_the.py | 2 ++ test/test_web.py | 2 ++ test/test_zero.py | 2 ++ 20 files changed, 40 insertions(+) diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index 2fa10a57c..e736bab27 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Extremely simple pure-Python implementation of coroutine-style asynchronous socket I/O. Inspired by, but inferior to, Eventlet. Bluelet can also be thought of as a less-terrible replacement for diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index ffca7c30c..3953afe2c 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Updates the Emby Library whenever the beets library is changed. emby: diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 19d4ecfe8..70be1089e 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Populate an item's `added` and `mtime` fields by using the file modification time (mtime) of the item's source file before import. diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 44757be5b..8a4ab960b 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 8cb1d375d..51ee4fd85 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Updates an Plex library whenever the beets library is changed. Plex Home users enter the Plex Token to enable updating. diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 42683d4cb..f77756dbc 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/docs/conf.py b/docs/conf.py index 24ea6742d..d952b410e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + AUTHOR = u'Adrian Sampson' # General configuration diff --git a/test/__init__.py b/test/__init__.py index 52514cb73..72fb5d544 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -1 +1,3 @@ +# -*- coding: utf-8 -*- + # Make python -m testall.py work. diff --git a/test/rsrc/beetsplug/test.py b/test/rsrc/beetsplug/test.py index 79f787ae0..85c6eb0c2 100644 --- a/test/rsrc/beetsplug/test.py +++ b/test/rsrc/beetsplug/test.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_config_command.py b/test/test_config_command.py index 18463cb2a..60cf9de25 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index d21c19987..dad438491 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_ihate.py b/test/test_ihate.py index eb14ccdc3..1ce4800b9 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'ihate' plugin""" from __future__ import (division, absolute_import, print_function, diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index 061f7a7a4..276a26ff2 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_logging.py b/test/test_logging.py index bc52edf59..81df95a78 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Stupid tests that ensure logging works as expected""" from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_permissions.py b/test/test_permissions.py index b2a8adcb8..479c5e5af 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'permissions' plugin. """ from __future__ import (division, absolute_import, print_function, diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index 58388f728..27a24ea30 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from __future__ import (division, absolute_import, print_function, unicode_literals) diff --git a/test/test_spotify.py b/test/test_spotify.py index 61da6a378..895106845 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'spotify' plugin""" from __future__ import (division, absolute_import, print_function, diff --git a/test/test_the.py b/test/test_the.py index e04db1aec..9cfb34d63 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'the' plugin""" from __future__ import (division, absolute_import, print_function, diff --git a/test/test_web.py b/test/test_web.py index 9a8cb55e8..0299e82d4 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'web' plugin""" from __future__ import (division, absolute_import, print_function, diff --git a/test/test_zero.py b/test/test_zero.py index a23b47d1c..623a7801b 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + """Tests for the 'zero' plugin""" from __future__ import (division, absolute_import, print_function, From f5eca77117b21924d8b4d58e97c20e598e6904dc Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 19 Nov 2015 18:54:02 +0100 Subject: [PATCH 0211/2280] added encoding as comment last file for encoding check python3 file without license --- extra/release.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extra/release.py b/extra/release.py index de4d55029..302a5f3de 100755 --- a/extra/release.py +++ b/extra/release.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +# -*- coding: utf-8 -*- + """A utility script for automating the beets release process. """ import click From 7233173507f44b671fb4e294cd41c2a280370b46 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 10:08:37 -0800 Subject: [PATCH 0212/2280] Fix some outdated comments --- beets/dbcore/query.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index c04e734b8..2aa27a2b8 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -60,9 +60,8 @@ class Query(object): """ def clause(self): """Generate an SQLite expression implementing the query. - Return a clause string, a sequence of substitution values for - the clause, and a Query object representing the "remainder" - Returns (clause, subvals) where clause is a valid sqlite + + Return (clause, subvals) where clause is a valid sqlite WHERE clause implementing the query and subvals is a list of items to be substituted for ?s in the clause. """ @@ -353,7 +352,7 @@ class CollectionQuery(Query): return item in self.subqueries def clause_with_joiner(self, joiner): - """Returns a clause created by joining together the clauses of + """Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces). """ clause_parts = [] From 0e5a1e6b00b4c7ce48dcf750c810b9d8f41751cc Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 19 Nov 2015 19:09:11 +0100 Subject: [PATCH 0213/2280] added encoding to beet itself --- beet | 1 + 1 file changed, 1 insertion(+) diff --git a/beet b/beet index e30c8b6eb..1c49295a1 100755 --- a/beet +++ b/beet @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. From 27b5b407c2e9599759dc6f7cef51a6730a5cbee1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 10:10:17 -0800 Subject: [PATCH 0214/2280] Fix #1732 by importing ctypes on demand --- beets/util/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 2a861ce88..7cd238334 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -16,8 +16,6 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) -import ctypes - import os import sys import re @@ -794,9 +792,12 @@ def _windows_long_path_name(short_path): """ if not isinstance(short_path, unicode): short_path = unicode(short_path) + + import ctypes buf = ctypes.create_unicode_buffer(260) get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW return_value = get_long_path_name_w(short_path, buf, 260) + if return_value == 0 or return_value > 260: # An error occurred return short_path From 3176b83cd76807cfc48773cc282f0ee021a62c70 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 15:25:49 -0800 Subject: [PATCH 0215/2280] Use type-based formatting and parsing All editable values are now strings and are parsed from strings. This closely matches the behavior of the `modify` command, for example. --- beets/dbcore/db.py | 5 +++++ beetsplug/edit.py | 21 +++++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index df796a134..b5da1c89e 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -466,6 +466,11 @@ class Model(object): return cls._type(key).parse(string) + def set_parse(self, key, string): + """Set the object's key to a value represented by a string. + """ + self[key] = self._parse(key, string) + # Database controller and supporting interfaces. diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 719fbd032..2798c162c 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -55,14 +55,27 @@ def flatten(obj, fields): """Represent `obj`, a `dbcore.Model` object, as a dictionary for serialization. Only include the given `fields` if provided; otherwise, include everything. + + The resulting dictionary's keys are all human-readable strings. """ - d = dict(obj) + d = dict(obj.formatted()) if fields: return {k: v for k, v in d.items() if k in fields} else: return d +def apply(obj, data): + """Set the fields of a `dbcore.Model` object according to a + dictionary. + + This is the opposite of `flatten`. The `data` dictionary should have + strings as values. + """ + for key, value in data.items(): + obj.set_parse(key, value) + + class EditPlugin(plugins.BeetsPlugin): def __init__(self): @@ -233,14 +246,14 @@ class EditPlugin(plugins.BeetsPlugin): forbidden = False for key in ignore_fields: if old_dict.get(key) != new_dict.get(key): - self._log.warn('ignoring object where {} changed', key) + self._log.warn('ignoring object whose {} changed', key) forbidden = True break if forbidden: continue - obj = obj_by_id[old_dict['id']] - obj.update(new_dict) + id = int(old_dict['id']) + apply(obj_by_id[id], new_dict) def save_write(self, objs): """Save a list of updated Model objects to the database. From 0873d314197448fabd02d43b8c50a7b6a487956a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 15:34:49 -0800 Subject: [PATCH 0216/2280] Catch unexpected YAML type We need a sequence of dictionaries back; validate this assumption. --- beetsplug/edit.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 2798c162c..9b86ca94a 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -27,6 +27,12 @@ from tempfile import NamedTemporaryFile import os +class ParseError(Exception): + """The modified file is unreadable. The user should be offered a chance to + fix the error. + """ + + def edit(filename): """Open `filename` in a text editor. """ @@ -36,7 +42,7 @@ def edit(filename): def dump(arg): - """Dump an object as YAML for editing. + """Dump a sequence of dictionaries as YAML for editing. """ return yaml.safe_dump_all( arg, @@ -46,9 +52,23 @@ def dump(arg): def load(s): - """Read a YAML string back to an object. + """Read a sequence of YAML documents back to a list of dictionaries. + + Can raise a `ParseError`. """ - return list(yaml.load_all(s)) + try: + out = [] + for d in yaml.load_all(s): + if not isinstance(d, dict): + raise ParseError( + 'each entry must be a dictionary; found {}'.format( + type(d).__name__ + ) + ) + out.append(d) + except yaml.YAMLError as e: + raise ParseError('invalid YAML: {}'.format(e)) + return out def flatten(obj, fields): @@ -193,8 +213,8 @@ class EditPlugin(plugins.BeetsPlugin): # Parse the updated data. try: new_data = load(new_str) - except yaml.YAMLError as e: - ui.print_("Invalid YAML: {}".format(e)) + except ParseError as e: + ui.print_("Could not read data: {}".format(e)) if ui.input_yn("Edit again to fix? (Y/n)", True): continue else: From 0e20770cc3ffa56d6466d9df8faae215dcdd6773 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 15:38:20 -0800 Subject: [PATCH 0217/2280] Convert YAML keys and values back to strings I hadn't quite realized before that the user could also change the *keys* to be non-strings too! This also prevents against that by just reinterpreting everything as strings. --- beetsplug/edit.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 9b86ca94a..f1cf85095 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -52,7 +52,8 @@ def dump(arg): def load(s): - """Read a sequence of YAML documents back to a list of dictionaries. + """Read a sequence of YAML documents back to a list of dictionaries + with string keys and values. Can raise a `ParseError`. """ @@ -65,7 +66,12 @@ def load(s): type(d).__name__ ) ) - out.append(d) + + # Convert all keys and values to strings. They started out + # as strings, but the user may have inadvertently messed + # this up. + out.append({unicode(k): unicode(v) for k, v in d.items()}) + except yaml.YAMLError as e: raise ParseError('invalid YAML: {}'.format(e)) return out From 6a99eaae35897518ed2090616e86d842c92dff73 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 15:45:06 -0800 Subject: [PATCH 0218/2280] Fix a test for the new output format --- test/test_edit.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 56a13525a..8e6ac6e7d 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -193,8 +193,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Edit the yaml file appending an extra field to the first item, then apply changes.""" # append "foo: bar" to item with id == 1 - self.run_mocked_command({'replacements': {u'id: 1': - u'id: 1\nfoo: bar'}}, + self.run_mocked_command({'replacements': {u"id: '1'": + u"id: '1'\nfoo: bar"}}, # Apply changes. ['a']) From 437959018cc9b41c546200cf31a6143a261e83d8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 16:07:20 -0800 Subject: [PATCH 0219/2280] Pass through certain "safe" types to YAML This avoids some round-tripping problems with types (such as ScaledInt) that are not represented in strings with 100% fidelity. It also makes the syntax nicer when editing numbers and booleans: they no longer appear to be needlessly surrounded by quotes in the YAML. --- beetsplug/edit.py | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index f1cf85095..9cc1d44bc 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -20,6 +20,7 @@ from __future__ import (division, absolute_import, print_function, from beets import plugins from beets import util from beets import ui +from beets.dbcore import types from beets.ui.commands import _do_query import subprocess import yaml @@ -27,6 +28,11 @@ from tempfile import NamedTemporaryFile import os +# These "safe" types can avoid the format/parse cycle that most fields go +# through: they are safe to edit with native YAML types. +SAFE_TYPES = (types.Float, types.Integer, types.Boolean) + + class ParseError(Exception): """The modified file is unreadable. The user should be offered a chance to fix the error. @@ -53,7 +59,7 @@ def dump(arg): def load(s): """Read a sequence of YAML documents back to a list of dictionaries - with string keys and values. + with string keys. Can raise a `ParseError`. """ @@ -67,10 +73,9 @@ def load(s): ) ) - # Convert all keys and values to strings. They started out - # as strings, but the user may have inadvertently messed - # this up. - out.append({unicode(k): unicode(v) for k, v in d.items()}) + # Convert all keys to strings. They started out as strings, + # but the user may have inadvertently messed this up. + out.append({unicode(k): v for k, v in d.items()}) except yaml.YAMLError as e: raise ParseError('invalid YAML: {}'.format(e)) @@ -82,9 +87,21 @@ def flatten(obj, fields): serialization. Only include the given `fields` if provided; otherwise, include everything. - The resulting dictionary's keys are all human-readable strings. + The resulting dictionary's keys are strings and the values are + safely YAML-serializable types. """ - d = dict(obj.formatted()) + # Format each value. + d = {} + for key, value in obj.items(): + typ = obj._type(key) + if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): + # A safe value that is faithfully representable in YAML. + d[key] = value + else: + # A value that should be edited as a string. + d[key] = obj.formatted()[key] + + # Possibly filter field names. if fields: return {k: v for k, v in d.items() if k in fields} else: @@ -99,7 +116,15 @@ def apply(obj, data): strings as values. """ for key, value in data.items(): - obj.set_parse(key, value) + typ = obj._type(key) + if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): + # A safe value *stayed* represented as a safe type. Assign it + # directly. + obj[key] = value + else: + # Either the field was stringified originally or the user changed + # it from a safe type to an unsafe one. Parse it as a string. + obj.set_parse(key, unicode(value)) class EditPlugin(plugins.BeetsPlugin): From f995ab38db14e6376e96d8383a193852c41895f2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 16:11:45 -0800 Subject: [PATCH 0220/2280] Fix a test and a bug revealed by a test --- beetsplug/edit.py | 3 ++- test/test_edit.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 9cc1d44bc..d93678b5e 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -92,8 +92,9 @@ def flatten(obj, fields): """ # Format each value. d = {} - for key, value in obj.items(): + for key in obj.keys(): typ = obj._type(key) + value = obj[key] if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): # A safe value that is faithfully representable in YAML. d[key] = value diff --git a/test/test_edit.py b/test/test_edit.py index 8e6ac6e7d..ae0500029 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -193,8 +193,8 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Edit the yaml file appending an extra field to the first item, then apply changes.""" # append "foo: bar" to item with id == 1 - self.run_mocked_command({'replacements': {u"id: '1'": - u"id: '1'\nfoo: bar"}}, + self.run_mocked_command({'replacements': {u"id: 1": + u"id: 1\nfoo: bar"}}, # Apply changes. ['a']) From 69ffb83453b01fda373c91eb8a1527cf71c2eeb9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Nov 2015 16:26:27 -0800 Subject: [PATCH 0221/2280] Eliminate some copypasta --- beetsplug/edit.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index d93678b5e..8d6b168f5 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -82,6 +82,17 @@ def load(s): return out +def _safe_value(obj, key, value): + """Check whether the `value` is safe to represent in YAML and trust as + returned from parsed YAML. + + This ensures that values do not change their type when the user edits their + YAML representation. + """ + typ = obj._type(key) + return isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type) + + def flatten(obj, fields): """Represent `obj`, a `dbcore.Model` object, as a dictionary for serialization. Only include the given `fields` if provided; @@ -93,9 +104,8 @@ def flatten(obj, fields): # Format each value. d = {} for key in obj.keys(): - typ = obj._type(key) value = obj[key] - if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): + if _safe_value(obj, key, value): # A safe value that is faithfully representable in YAML. d[key] = value else: @@ -117,8 +127,7 @@ def apply(obj, data): strings as values. """ for key, value in data.items(): - typ = obj._type(key) - if isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type): + if _safe_value(obj, key, value): # A safe value *stayed* represented as a safe type. Assign it # directly. obj[key] = value From 51bf6a1c9ffd7f8c4e10511eb58a5284248594ec Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 20 Nov 2015 18:06:22 +0100 Subject: [PATCH 0222/2280] Add documentation for NotQuery, cleanup * Add changelog and query.rst documentation entries for the usage of negated queries. * Cleanup NotQuery class as suggested during code review (PEP conforming docstring, clarification on empty clause match behaviour). --- beets/dbcore/query.py | 6 ++++-- docs/changelog.rst | 4 ++++ docs/reference/query.rst | 29 +++++++++++++++++++++++++++++ test/test_query.py | 2 -- 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index b4c1d1445..348394f0a 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -449,7 +449,8 @@ class OrQuery(MutableCollectionQuery): class NotQuery(Query): """A query that matches the negation of its `subquery`, as a shorcut for - performing `not(subquery)` without using regular expressions.""" + performing `not(subquery)` without using regular expressions. + """ def __init__(self, subquery): self.subquery = subquery @@ -458,7 +459,8 @@ class NotQuery(Query): if clause: return 'not ({0})'.format(clause), subvals else: - # special case for RegexpQuery, (None, ()) + # If there is no clause, there is nothing to negate. All the logic + # is handled by match() for slow queries. return clause, subvals def match(self, item): diff --git a/docs/changelog.rst b/docs/changelog.rst index 700a16d6d..81dcdd2b7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,10 @@ New: :doc:`/plugins/discogs` also adopts the same setting. * :doc:`/plugins/embyupdate`: A plugin to trigger a library refresh on a `Emby Server`_ if database changed. +* Queries can now use "not" logic: if you prepend a query term with "-" or + "^", items or albums matching that term will be excluded from the results. + For example, ``beet ls foo ^artist:bar`` will get all the items matching + `foo` but whose artist do not match `bar`. See :ref:`not_query`. :bug:`819` For developers: diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 452681c35..6d83537d1 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -181,6 +181,35 @@ Find all items with a file modification time between 2008-12-01 and $ beet ls 'mtime:2008-12-01..2008-12-02' +.. _not_query: + +Query Term Negation +------------------- + +Query terms can also be negated, acting like a Boolean "not", by prepending +them with ``-`` or ``^``. This has the effect of returning all the items that +do **not** match the query term. For example, this command:: + + $ beet list ^love + +matches all the songs in the library that do not have "love" in any of their +fields. + +Negation can be combined with the rest of the query mechanisms, allowing to +negate specific fields, regular expressions, etc. For example, this command:: + + $ beet list -a artist:dylan ^year:1980..1990 "^album::the(y)?" + +matches all the albums with an artist containing "dylan", but excluding those +released on the eighties and those that have "the" or "they" on the title. + +Note that the ``-`` character is treated by most shells as a reserved character +for passing arguments, and as such needs to be escaped if using it for query +negation. In most UNIX derivatives shells, using a double dash ``--`` +(indicating that everything after that point should not be treated as +arguments) before the query terms should prevent conflicts, such as:: + + $ beet list -a -- artist:dylan -year:1980..1990 "-album::the(y)?" .. _pathquery: diff --git a/test/test_query.py b/test/test_query.py index c415b7f1c..e6b2d0499 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -782,8 +782,6 @@ class NotQueryTest(DummyDataTestCase): """Test `query.NotQuery` against the dummy data: - `test_type_xxx`: tests for the negation of a particular XxxQuery class. - `test_get_yyy`: tests on query strings (similar to `GetTest`) - - TODO: add test_type_bytes, for ByteQuery? """ def assertNegationProperties(self, q): """Given a Query `q`, assert that: From fd2cacbc25ecd1dec5a60c1e3995ea7b031c3614 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Nov 2015 10:07:29 -0800 Subject: [PATCH 0223/2280] Minor docs refinements for #1728 - Use a marginally more realistic example in the changelog. - The -- convention is actually not the purview of shells; it's just a de facto standard for command-line parsers. Fortunately, argparse supports it out of the box. --- docs/changelog.rst | 8 ++++---- docs/reference/query.rst | 16 +++++++--------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 81dcdd2b7..474e4c4a7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,10 +20,10 @@ New: :doc:`/plugins/discogs` also adopts the same setting. * :doc:`/plugins/embyupdate`: A plugin to trigger a library refresh on a `Emby Server`_ if database changed. -* Queries can now use "not" logic: if you prepend a query term with "-" or - "^", items or albums matching that term will be excluded from the results. - For example, ``beet ls foo ^artist:bar`` will get all the items matching - `foo` but whose artist do not match `bar`. See :ref:`not_query`. :bug:`819` +* Queries can now use "not" logic. Type a ``^`` before part of a query to + *exclude* matching music from the results. For example, ``beet list -a + beatles ^album:1`` will find all your albums by the Beatles except for their + singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` For developers: diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 6d83537d1..2cb3aec87 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -186,7 +186,7 @@ Find all items with a file modification time between 2008-12-01 and Query Term Negation ------------------- -Query terms can also be negated, acting like a Boolean "not", by prepending +Query terms can also be negated, acting like a Boolean "not," by prefixing them with ``-`` or ``^``. This has the effect of returning all the items that do **not** match the query term. For example, this command:: @@ -195,19 +195,17 @@ do **not** match the query term. For example, this command:: matches all the songs in the library that do not have "love" in any of their fields. -Negation can be combined with the rest of the query mechanisms, allowing to +Negation can be combined with the rest of the query mechanisms, so you can negate specific fields, regular expressions, etc. For example, this command:: - $ beet list -a artist:dylan ^year:1980..1990 "^album::the(y)?" + $ beet list -a artist:dylan ^year:1980..1989 "^album::the(y)?" matches all the albums with an artist containing "dylan", but excluding those -released on the eighties and those that have "the" or "they" on the title. +released in the eighties and those that have "the" or "they" on the title. -Note that the ``-`` character is treated by most shells as a reserved character -for passing arguments, and as such needs to be escaped if using it for query -negation. In most UNIX derivatives shells, using a double dash ``--`` -(indicating that everything after that point should not be treated as -arguments) before the query terms should prevent conflicts, such as:: +The syntax supports both ``^`` and ``-`` as synonyms because the latter +indicates flags on the command line. To use a minus sign in a command-line +query, use a double dash ``--`` to separate the options from the query:: $ beet list -a -- artist:dylan -year:1980..1990 "-album::the(y)?" From 530b42156b0e4eb1814093c2735edff73881e920 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Nov 2015 10:55:25 -0800 Subject: [PATCH 0224/2280] Thumbnails: Declare more interface types Seems to address a segfault indicated in #1433, but there are still crashes lurking. --- beetsplug/thumbnails.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 6fd8c8cbe..b5aa05b17 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -234,8 +234,13 @@ class GioURI(URIGetter): self.available = bool(self.libgio) if self.available: self.libgio.g_type_init() # for glib < 2.36 + + self.libgio.g_file_get_uri.argtypes = [ctypes.c_char_p] self.libgio.g_file_new_for_path.restype = ctypes.c_void_p + self.libgio.g_file_get_uri.argtypes = [ctypes.c_void_p] + self.libgio.g_file_get_uri.restype = ctypes.c_char_p + self.libgio.g_object_unref.argtypes = [ctypes.c_void_p] def get_library(self): From 6c0f43cf1c5a46ad84c85502f5ea2d9ed9c81147 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Nov 2015 11:26:35 -0800 Subject: [PATCH 0225/2280] Thumbnails: Fix string memory management Should fix #1433. The problem now was that we were freeing the string memory that Python expected to be managing in a string object held by the `uri` variable. Now, we do a silly dance to copy the memory out of the buffer returned by the library and return that instead. --- beetsplug/thumbnails.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index b5aa05b17..fef512dc8 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -224,6 +224,17 @@ class PathlibURI(URIGetter): return PurePosixPath(path).as_uri() +def copy_c_string(c_string): + """Copy a `ctypes.POINTER(ctypes.c_char)` value into a new Python + string and return it. The old memory is then safe to free. + """ + # This is a pretty dumb way to get a string copy, but it seems to + # work. A more surefire way would be to allocate a ctypes buffer and copy + # the data with `memcpy` or somesuch. + s = ctypes.cast(c_string, ctypes.c_char_p).value + return '' + s + + class GioURI(URIGetter): """Use gio URI function g_file_get_uri. Paths must be utf-8 encoded. """ @@ -239,7 +250,7 @@ class GioURI(URIGetter): self.libgio.g_file_new_for_path.restype = ctypes.c_void_p self.libgio.g_file_get_uri.argtypes = [ctypes.c_void_p] - self.libgio.g_file_get_uri.restype = ctypes.c_char_p + self.libgio.g_file_get_uri.restype = ctypes.POINTER(ctypes.c_char) self.libgio.g_object_unref.argtypes = [ctypes.c_void_p] @@ -270,7 +281,7 @@ class GioURI(URIGetter): "{0}".format(util.displayable_path(path))) try: - uri = ctypes.c_char_p(uri_ptr).value + uri = copy_c_string(uri_ptr) except: raise finally: From 9702011884f7db81ec6d17362e68a1d4a930bb7f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Nov 2015 11:28:51 -0800 Subject: [PATCH 0226/2280] Changelog for #1433 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 474e4c4a7..87b7819e5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -62,6 +62,8 @@ Fixes: missing configuration. * Fix a crash with some files with unreadable iTunes SoundCheck metadata. :bug:`1666` +* :doc:`/plugins/thumbnails`: Fix a nasty segmentation fault crash that arose + with some library versions. :bug:`1433` .. _Emby Server: http://emby.media From eb68177feeaae63e5a8c7facaeb9c01a45f1f6e7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 21 Nov 2015 12:40:45 -0800 Subject: [PATCH 0227/2280] Fix #1735: `convert --pretend` encoding error --- beetsplug/convert.py | 2 +- docs/changelog.rst | 2 ++ test/test_convert.py | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index fd82e80f2..a262f216d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -189,7 +189,7 @@ class ConvertPlugin(BeetsPlugin): }) if pretend: - self._log.info(' '.join(args)) + self._log.info(' '.join(ui.decargs(args))) return try: diff --git a/docs/changelog.rst b/docs/changelog.rst index 87b7819e5..ce707ab88 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -64,6 +64,8 @@ Fixes: :bug:`1666` * :doc:`/plugins/thumbnails`: Fix a nasty segmentation fault crash that arose with some library versions. :bug:`1433` +* :doc:`/plugins/convert`: Fix a crash with Unicode paths in ``--pretend`` + mode. :bug:`1735` .. _Emby Server: http://emby.media diff --git a/test/test_convert.py b/test/test_convert.py index 86c6e5d2a..7cd565b3a 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -180,6 +180,11 @@ class ConvertCliTest(unittest.TestCase, TestHelper): with open(converted, 'r') as f: self.assertEqual(f.read(), 'XXX') + def test_pretend(self): + self.run_command('convert', '--pretend', self.item.path) + converted = os.path.join(self.convert_dest, 'converted.mp3') + self.assertFalse(os.path.exists(converted)) + class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): """Test the effect of the `never_convert_lossy_files` option. From e55b01c2bbaa4900c46dc07bcb26e0a8d31fadfb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 21 Nov 2015 12:52:19 -0800 Subject: [PATCH 0228/2280] Better artresizer error logging Should help diagnose #1721. --- beets/util/artresizer.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index c5dcb6055..d420e2c0e 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -113,18 +113,21 @@ def pil_getsize(path_in): try: im = Image.open(util.syspath(path_in)) return im.size - except IOError: - log.error(u"PIL cannot compute size of '{0}'", - util.displayable_path(path_in)) + except IOError as exc: + log.error(u"PIL could not read file {}: {}", + util.displayable_path(path_in), exc) def im_getsize(path_in): + cmd = [b'identify', b'-format', b'%w %h', util.syspath(path_in)] try: - out = util.command_output([b'identify', b'-format', b'%w %h', - util.syspath(path_in)]) - except subprocess.CalledProcessError: - log.warn(u'IM cannot compute size of {0}', - util.displayable_path(path_in)) + out = util.command_output(cmd) + except subprocess.CalledProcessError as exc: + log.warn( + 'ImageMagick invocation failed when ' + 'getting size with command {}: {}: cannot compute size of {0}', + cmd, exc + ) return try: return tuple(map(int, out.split(b' '))) From 1d0984a2941855104907b676046822c088770d94 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 21 Nov 2015 12:54:50 -0800 Subject: [PATCH 0229/2280] Slight log rewording --- beetsplug/fetchart.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index e3769a260..333d29a89 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -530,8 +530,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): size = ArtResizer.shared.get_size(candidate) if not size: - self._log.warning(u'could not verify size of image: please see ' - u'documentation for dependencies. ' + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies). ' u'The configuration options `minwidth` and ' u'`enforce_ratio` may be violated.') return CANDIDATE_EXACT From 0a719a015257de76ed06f68177f8b0e56238adfb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 22 Nov 2015 10:30:20 -0800 Subject: [PATCH 0230/2280] Fix formatting in logging for #1721 --- beets/util/artresizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index d420e2c0e..775679568 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -125,7 +125,7 @@ def im_getsize(path_in): except subprocess.CalledProcessError as exc: log.warn( 'ImageMagick invocation failed when ' - 'getting size with command {}: {}: cannot compute size of {0}', + 'getting size with command {}: {}', cmd, exc ) return From c90ca1096c0dde4ca88bfdb4d4963b7b7cddc8d6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 23 Nov 2015 17:30:09 -0800 Subject: [PATCH 0231/2280] fetchart: Log reasons for rejecting art --- beetsplug/fetchart.py | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 333d29a89..1b2089b58 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -528,6 +528,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # get_size returns None if no local imaging backend is available size = ArtResizer.shared.get_size(candidate) + self._log.debug('image size: {}', size) if not size: self._log.warning(u'Could not get size of image (please see ' @@ -536,12 +537,25 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): u'`enforce_ratio` may be violated.') return CANDIDATE_EXACT - if (not self.minwidth or size[0] >= self.minwidth) and ( - not self.enforce_ratio or size[0] == size[1]): - if not self.maxwidth or size[0] > self.maxwidth: - return CANDIDATE_DOWNSCALE - return CANDIDATE_EXACT - return CANDIDATE_BAD + # Check minimum size. + if self.minwidth and size[0] < self.minwidth: + self._log.debug('image too small ({} < {})', + size[0], self.minwidth) + return CANDIDATE_BAD + + # Check aspect ratio. + if self.enforce_ratio and size[0] != size[1]: + self._log.debug('image is not square ({} != {})', + size[0], size[1]) + return CANDIDATE_BAD + + # Check maximum size. + if self.maxwidth and size[0] > self.maxwidth: + self._log.debug('image needs resizing ({} > {})', + size[0], self.maxwidth) + return CANDIDATE_DOWNSCALE + + return CANDIDATE_EXACT def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the From 4ccf81534e74096e507e622047c860219a3420dd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 23 Nov 2015 22:47:52 -0800 Subject: [PATCH 0232/2280] Even more ImageMagick error logging (#1721) --- beets/util/__init__.py | 1 + beets/util/artresizer.py | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5ea021bdd..e2d09c3ab 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -700,6 +700,7 @@ def command_output(cmd, shell=False): raise subprocess.CalledProcessError( returncode=proc.returncode, cmd=b' '.join(cmd), + output=stdout + stderr, ) return stdout diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 775679568..6ef7770f8 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -123,10 +123,11 @@ def im_getsize(path_in): try: out = util.command_output(cmd) except subprocess.CalledProcessError as exc: - log.warn( - 'ImageMagick invocation failed when ' - 'getting size with command {}: {}', - cmd, exc + log.warn('ImageMagick size query failed') + log.debug( + '`convert` exited with (status {}) when ' + 'getting size with command {}:\n{}', + exc.returncode, cmd, exc.output.strip() ) return try: From 6958f83dd6e3807427aa4a08ae0133d14f1aa071 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 23 Nov 2015 22:55:51 -0800 Subject: [PATCH 0233/2280] Fix test for richer CalledProcessError --- test/test_util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_util.py b/test/test_util.py index 6dacb7f57..db68ed885 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -108,7 +108,7 @@ class UtilTest(unittest.TestCase): def test_command_output(self, mock_popen): def popen_fail(*args, **kwargs): m = Mock(returncode=1) - m.communicate.return_value = None, None + m.communicate.return_value = 'foo', 'bar' return m mock_popen.side_effect = popen_fail From 1ef407672a5575f9a2f769b6e0456593d7899838 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 24 Nov 2015 16:31:01 +0100 Subject: [PATCH 0234/2280] info: add item format and length format arguments * Add custom output formatting via a format string to InfoPlugin. The command accepts a formatting string via the "-f" parameter, which is handled by its CommonOptionsParser and applied during print_data(). * Modify the emitters in order to include an Item into the list of fields, that is formatted according to the format string if specified. * Add an argument to allow the user to choose if track lengths are displayed as raw floats or using a human-readable form (mm:ss), defaulting to human-readable form. --- beetsplug/info.py | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index d6988d097..e8c6d987f 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -25,6 +25,7 @@ import re from beets.plugins import BeetsPlugin from beets import ui from beets import mediafile +from beets.library import Item from beets.util import displayable_path, normpath, syspath @@ -52,7 +53,11 @@ def tag_data_emitter(path): tags[field] = getattr(mf, field) tags['art'] = mf.art is not None tags['path'] = displayable_path(path) + # create a temporary Item to take advantage of __format__ + tags['item'] = Item(db=None, **tags) + return tags + return emitter @@ -65,6 +70,7 @@ def library_data_emitter(item): def emitter(): data = dict(item.formatted()) data['path'] = displayable_path(item.path) + data['item'] = item return data return emitter @@ -78,14 +84,36 @@ def update_summary(summary, tags): return summary -def print_data(data): +def print_data(data, fmt=None, human_length=True): + """Print, with optional formatting, the fields of a single item. + + If no format string `fmt` is passed, the entries on `data` are printed one + in each line, with the format 'field: value'. If `fmt` is not `None`, the + item is printed according to `fmt`, using the `Item.__format__` machinery. + + If `raw_length` is `True`, the `length` field is displayed using its raw + value (float with the number of seconds and miliseconds). If not, a human + readable form is displayed instead (mm:ss). + """ + item = data.pop('item', None) + if fmt: + # use fmt specified by the user, prettifying length if needed + if human_length and '$length' in fmt: + item['humanlength'] = ui.human_seconds_short(item.length) + fmt = fmt.replace('$length', '$humanlength') + ui.print_(format(item, fmt)) + return + path = data.pop('path', None) formatted = {} for key, value in data.iteritems(): if isinstance(value, list): formatted[key] = u'; '.join(value) if value is not None: - formatted[key] = value + if human_length and key == 'length': + formatted[key] = ui.human_seconds_short(float(value)) + else: + formatted[key] = value if len(formatted) == 0: return @@ -115,6 +143,10 @@ class InfoPlugin(BeetsPlugin): cmd.parser.add_option('-i', '--include-keys', default=[], action='append', dest='included_keys', help='comma separated list of keys to show') + cmd.parser.add_option('-r', '--raw-length', action='store_true', + default=False, + help='display length as seconds') + cmd.parser.add_format_option(target='item') return [cmd] def run(self, lib, opts, args): @@ -151,18 +183,20 @@ class InfoPlugin(BeetsPlugin): continue path = data.get('path') + item = data.get('item') data = key_filter(data) data['path'] = path # always show path + data['item'] = item # always include item, to avoid filtering if opts.summarize: update_summary(summary, data) else: if not first: ui.print_() - print_data(data) + print_data(data, opts.format, not opts.raw_length) first = False if opts.summarize: - print_data(summary) + print_data(summary, human_length=not opts.raw_length) def make_key_filter(include): From 8d9db9ffe6e4eebfabd1d4f338c6530770ae05ab Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 24 Nov 2015 16:41:56 +0100 Subject: [PATCH 0235/2280] info: minor cleanups * Rename filter() function to avoid warning of reserved built-in symbol. * Remove mediafile fixture on two tests. --- beetsplug/info.py | 4 ++-- test/test_info.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index e8c6d987f..b719723bc 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -215,14 +215,14 @@ def make_key_filter(include): key = key.replace(r'\*', '.*') matchers.append(re.compile(key + '$')) - def filter(data): + def filter_(data): filtered = dict() for key, value in data.items(): if any(map(lambda m: m.match(key), matchers)): filtered[key] = value return filtered - return filter + return filter_ def identity(val): diff --git a/test/test_info.py b/test/test_info.py index 797950be3..bb8ffcccc 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -52,6 +52,7 @@ class InfoTest(unittest.TestCase, TestHelper): self.assertIn('disctitle: DDD', out) self.assertIn('genres: a; b; c', out) self.assertNotIn('composer:', out) + self.remove_mediafile_fixtures() def test_item_query(self): item1, item2 = self.add_item_fixtures(count=2) @@ -93,6 +94,7 @@ class InfoTest(unittest.TestCase, TestHelper): self.assertIn(u'album: AAA', out) self.assertIn(u'tracktotal: 5', out) self.assertIn(u'title: [various]', out) + self.remove_mediafile_fixtures() def test_include_pattern(self): item, = self.add_item_fixtures() From 67af8af7dd5eb482bd2d6a694992d74de30efb09 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 24 Nov 2015 17:16:14 +0100 Subject: [PATCH 0236/2280] info: add unit tests * Add tests for length (human/raw, library/path) and custom format. --- test/test_info.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/test_info.py b/test/test_info.py index bb8ffcccc..395382b34 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -107,6 +107,44 @@ class InfoTest(unittest.TestCase, TestHelper): self.assertNotIn(u'title:', out) self.assertIn(u'album: xxxx', out) + def test_length_human_library(self): + item, = self.add_item_fixtures() + item.album = 'loool' + item.length = 123.4 + item.write() + item.store() + + out = self.run_with_output('--library') + self.assertIn(u'length: 2:03', out) + + def test_length_raw_library(self): + item, = self.add_item_fixtures() + item.album = 'loool' + item.length = 123.4 + item.write() + item.store() + + out = self.run_with_output('--library', '--raw-length') + self.assertIn(u'length: 123.4', out) + + def test_length_human_path(self): + path = self.create_mediafile_fixture() + out = self.run_with_output(path) + self.assertIn(u'length: 0:01', out) + self.remove_mediafile_fixtures() + + def test_length_raw_path(self): + path = self.create_mediafile_fixture() + out = self.run_with_output(path, '--raw-length') + self.assertIn(u'length: 1.071', out) + self.remove_mediafile_fixtures() + + def test_custom_format(self): + self.add_item_fixtures() + out = self.run_with_output('--library', '--format', + '$track. $title - $artist ($length)') + self.assertEqual(u'02. tïtle 0 - the artist (0:01)\n', out) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 455fd0e352df3872b91cb5ae394019f8bea2139b Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 24 Nov 2015 18:47:49 +0100 Subject: [PATCH 0237/2280] Fix sorting by nonexistent field (#1734), tests * Fix crash when sorting by nonexistent field. * Add tests for queries with nonexistient fields for sorting. --- beets/dbcore/query.py | 2 +- test/test_sort.py | 63 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 424d51e7c..f0adac665 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -767,7 +767,7 @@ class FieldSort(Sort): # attributes with different types without falling over. def key(item): - field_val = getattr(item, self.field) + field_val = item.get(self.field, '') if self.case_insensitive and isinstance(field_val, unicode): field_val = field_val.lower() return field_val diff --git a/test/test_sort.py b/test/test_sort.py index 7fadc54b2..9413e7d7b 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -469,6 +469,69 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): self.assertEqual(results[-1].track, 10) +class NonExistingFieldTest(DummyDataTestCase): + """Test sorting by non-existing fields""" + + def test_non_existing_fields_not_fail(self): + qs = ['foo+', 'foo-', '--', '-+', '+-', '++', '-foo-', '-foo+', '---'] + + q0 = 'foo+' + results0 = list(self.lib.items(q0)) + for q1 in qs: + results1 = list(self.lib.items(q1)) + for r1, r2 in zip(results0, results1): + self.assertEqual(r1.id, r2.id) + + def test_combined_non_existing_field_asc(self): + all_results = list(self.lib.items('id+')) + q = 'foo+ id+' + results = list(self.lib.items(q)) + self.assertEqual(len(all_results), len(results)) + for r1, r2 in zip(all_results, results): + self.assertEqual(r1.id, r2.id) + + def test_combined_non_existing_field_desc(self): + all_results = list(self.lib.items('id+')) + q = 'foo- id+' + results = list(self.lib.items(q)) + self.assertEqual(len(all_results), len(results)) + for r1, r2 in zip(all_results, results): + self.assertEqual(r1.id, r2.id) + + def test_field_present_in_some_items(self): + """Test ordering by a field not present on all items.""" + # append 'foo' to two to items (1,2) + items = self.lib.items('id+') + ids = [i.id for i in items] + items[1].foo = 'bar1' + items[2].foo = 'bar2' + items[1].store() + items[2].store() + + results_asc = list(self.lib.items('foo+ id+')) + self.assertEqual([i.id for i in results_asc], + # items without field first + [ids[0], ids[3], ids[1], ids[2]]) + results_desc = list(self.lib.items('foo- id+')) + self.assertEqual([i.id for i in results_desc], + # items without field last + [ids[2], ids[1], ids[0], ids[3]]) + + def test_negation_interaction(self): + """Test the handling of negation and sorting together. + + If a string ends with a sorting suffix, it takes precedence over the + NotQuery parsing. + """ + query, sort = beets.library.parse_query_string('-bar+', + beets.library.Item) + self.assertEqual(len(query.subqueries), 1) + self.assertTrue(isinstance(query.subqueries[0], + dbcore.query.TrueQuery)) + self.assertTrue(isinstance(sort, dbcore.query.SlowFieldSort)) + self.assertEqual(sort.field, '-bar') + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 0ed3f4067af5e8112ee97a371128e71b9ae57621 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 24 Nov 2015 19:43:48 +0100 Subject: [PATCH 0238/2280] Add changelog entry for nonexistent fields sorting --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index ce707ab88..54c70f370 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -66,6 +66,7 @@ Fixes: with some library versions. :bug:`1433` * :doc:`/plugins/convert`: Fix a crash with Unicode paths in ``--pretend`` mode. :bug:`1735` +* Fix a crash when sorting by nonexistent fields on queries. :bug:`1734` .. _Emby Server: http://emby.media From 83279ebe5b16ed9fdf8c30aa3378c6280cea7c80 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 25 Nov 2015 16:06:19 +0100 Subject: [PATCH 0239/2280] info: revert human_length changes * Remove human length changes from the plugin and the tests, as they will eventually be handled at a higher level. --- beetsplug/info.py | 21 ++++----------------- test/test_info.py | 34 +--------------------------------- 2 files changed, 5 insertions(+), 50 deletions(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index b719723bc..854a2441b 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -90,17 +90,10 @@ def print_data(data, fmt=None, human_length=True): If no format string `fmt` is passed, the entries on `data` are printed one in each line, with the format 'field: value'. If `fmt` is not `None`, the item is printed according to `fmt`, using the `Item.__format__` machinery. - - If `raw_length` is `True`, the `length` field is displayed using its raw - value (float with the number of seconds and miliseconds). If not, a human - readable form is displayed instead (mm:ss). """ item = data.pop('item', None) if fmt: - # use fmt specified by the user, prettifying length if needed - if human_length and '$length' in fmt: - item['humanlength'] = ui.human_seconds_short(item.length) - fmt = fmt.replace('$length', '$humanlength') + # use fmt specified by the user ui.print_(format(item, fmt)) return @@ -110,10 +103,7 @@ def print_data(data, fmt=None, human_length=True): if isinstance(value, list): formatted[key] = u'; '.join(value) if value is not None: - if human_length and key == 'length': - formatted[key] = ui.human_seconds_short(float(value)) - else: - formatted[key] = value + formatted[key] = value if len(formatted) == 0: return @@ -143,9 +133,6 @@ class InfoPlugin(BeetsPlugin): cmd.parser.add_option('-i', '--include-keys', default=[], action='append', dest='included_keys', help='comma separated list of keys to show') - cmd.parser.add_option('-r', '--raw-length', action='store_true', - default=False, - help='display length as seconds') cmd.parser.add_format_option(target='item') return [cmd] @@ -192,11 +179,11 @@ class InfoPlugin(BeetsPlugin): else: if not first: ui.print_() - print_data(data, opts.format, not opts.raw_length) + print_data(data, opts.format) first = False if opts.summarize: - print_data(summary, human_length=not opts.raw_length) + print_data(summary) def make_key_filter(include): diff --git a/test/test_info.py b/test/test_info.py index 395382b34..aaabed980 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -107,43 +107,11 @@ class InfoTest(unittest.TestCase, TestHelper): self.assertNotIn(u'title:', out) self.assertIn(u'album: xxxx', out) - def test_length_human_library(self): - item, = self.add_item_fixtures() - item.album = 'loool' - item.length = 123.4 - item.write() - item.store() - - out = self.run_with_output('--library') - self.assertIn(u'length: 2:03', out) - - def test_length_raw_library(self): - item, = self.add_item_fixtures() - item.album = 'loool' - item.length = 123.4 - item.write() - item.store() - - out = self.run_with_output('--library', '--raw-length') - self.assertIn(u'length: 123.4', out) - - def test_length_human_path(self): - path = self.create_mediafile_fixture() - out = self.run_with_output(path) - self.assertIn(u'length: 0:01', out) - self.remove_mediafile_fixtures() - - def test_length_raw_path(self): - path = self.create_mediafile_fixture() - out = self.run_with_output(path, '--raw-length') - self.assertIn(u'length: 1.071', out) - self.remove_mediafile_fixtures() - def test_custom_format(self): self.add_item_fixtures() out = self.run_with_output('--library', '--format', '$track. $title - $artist ($length)') - self.assertEqual(u'02. tïtle 0 - the artist (0:01)\n', out) + self.assertEqual(u'02. tïtle 0 - the artist (1.1)\n', out) def suite(): From ca63311101ed1bef5253375d90ecce493df1d78c Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 25 Nov 2015 17:36:51 +0100 Subject: [PATCH 0240/2280] info: revert human_length changes 2 * Remove human_length parameter from print_data() --- beetsplug/info.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index 854a2441b..f13434a5b 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -84,7 +84,7 @@ def update_summary(summary, tags): return summary -def print_data(data, fmt=None, human_length=True): +def print_data(data, fmt=None): """Print, with optional formatting, the fields of a single item. If no format string `fmt` is passed, the entries on `data` are printed one From be5138376bfc100e7cf2eed0c7d3dfb489b7ee4e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 25 Nov 2015 18:04:49 +0100 Subject: [PATCH 0241/2280] info: add changelog entry for format option --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index ce707ab88..746ede4a6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,8 @@ New: *exclude* matching music from the results. For example, ``beet list -a beatles ^album:1`` will find all your albums by the Beatles except for their singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` +* :doc:`/plugins/info`: The plugin now accepts the ``-f/--format`` option for + customizing how items are displayed. :bug:`1737` For developers: From a8f9f016d842d2a0698d36bf5e1c62c20815d115 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 25 Nov 2015 18:12:04 +0100 Subject: [PATCH 0242/2280] info: add format note to docs --- docs/plugins/info.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plugins/info.rst b/docs/plugins/info.rst index 5bfde0b41..b36e69051 100644 --- a/docs/plugins/info.rst +++ b/docs/plugins/info.rst @@ -36,6 +36,10 @@ Additional command-line options include: * ``--summarize`` or ``-s``: Merge all the information from multiple files into a single list of values. If the tags differ across the files, print ``[various]``. +* ``--format`` or ``-f``: Specify a specific format with which to print every + item. This uses the same template syntax as beets’ :doc:`path formats + `. + .. _id3v2: http://id3v2.sourceforge.net .. _mp3info: http://www.ibiblio.org/mp3info/ From 47ceb492dcd8fc87c2f1b40e24ecf72b8941613f Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 25 Nov 2015 19:15:01 +0100 Subject: [PATCH 0243/2280] Add docs note for custom-field sorting, fix typo * Add note about ordering when sorting by custom-fields on query.rst. * Fix typo on inline.rst. --- docs/plugins/inline.rst | 4 ++-- docs/reference/query.rst | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/plugins/inline.rst b/docs/plugins/inline.rst index ebe298ae7..4dfca261d 100644 --- a/docs/plugins/inline.rst +++ b/docs/plugins/inline.rst @@ -6,9 +6,9 @@ it, you can define template fields in your beets configuration file and refer to them from your template strings in the ``paths:`` section (see :doc:`/reference/config/`). -To use the `ìnline`` plugin, enable it in your configuration +To use the ``inline`` plugin, enable it in your configuration (see :ref:`using-plugins`). -Then, make a `item_fields:`` block in your config file. Under this key, every line defines a +Then, make a ``item_fields:`` block in your config file. Under this key, every line defines a new template field; the key is the name of the field (you'll use the name to refer to the field in your templates) and the value is a Python expression or function body. The Python code has all of a track's fields in scope, so you can diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 2cb3aec87..1349d755e 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -261,5 +261,9 @@ sort order: ``Bar foo Qux``. This behavior can be changed with the result in lower-case values being placed after upper-case values, e.g., ``Bar Qux foo``. +Note that when sorting by fields that are not present on all items (such as +flexible fields, or those defined by plugins) in *ascending* order, the items +that lack that particular field will be listed at the *beginning* of the list. + You can set the default sorting behavior with the :ref:`sort_item` and :ref:`sort_album` configuration options. From 3cdcaa45a87431e4738f4d08a3bcab1c4ca01985 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 26 Nov 2015 15:55:00 +0100 Subject: [PATCH 0244/2280] info: modify emitter output, clearer path handling * Make emitters produce a pair (dict, Item), in order to preserve the output at print_data (dict is used if no custom format is specified, Item otherwise). * Simplify the handling of the paths, printed at the top of print_data. The path key is removed from the dict entirely and fetched from the Item. --- beetsplug/info.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index f13434a5b..5f68336e9 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -52,12 +52,10 @@ def tag_data_emitter(path): for field in fields: tags[field] = getattr(mf, field) tags['art'] = mf.art is not None - tags['path'] = displayable_path(path) # create a temporary Item to take advantage of __format__ - tags['item'] = Item(db=None, **tags) - - return tags + item = Item.from_path(syspath(path)) + return tags, item return emitter @@ -69,9 +67,9 @@ def library_data(lib, args): def library_data_emitter(item): def emitter(): data = dict(item.formatted()) - data['path'] = displayable_path(item.path) - data['item'] = item - return data + data.pop('path', None) # path is fetched from item + + return data, item return emitter @@ -84,20 +82,20 @@ def update_summary(summary, tags): return summary -def print_data(data, fmt=None): - """Print, with optional formatting, the fields of a single item. +def print_data(data, item=None, fmt=None): + """Print, with optional formatting, the fields of a single element. If no format string `fmt` is passed, the entries on `data` are printed one in each line, with the format 'field: value'. If `fmt` is not `None`, the - item is printed according to `fmt`, using the `Item.__format__` machinery. + `item` is printed according to `fmt`, using the `Item.__format__` + machinery. """ - item = data.pop('item', None) if fmt: # use fmt specified by the user ui.print_(format(item, fmt)) return - path = data.pop('path', None) + path = displayable_path(item.path) if item else None formatted = {} for key, value in data.iteritems(): if isinstance(value, list): @@ -164,22 +162,18 @@ class InfoPlugin(BeetsPlugin): summary = {} for data_emitter in data_collector(lib, ui.decargs(args)): try: - data = data_emitter() + data, item = data_emitter() except (mediafile.UnreadableFileError, IOError) as ex: self._log.error(u'cannot read file: {0}', ex) continue - path = data.get('path') - item = data.get('item') data = key_filter(data) - data['path'] = path # always show path - data['item'] = item # always include item, to avoid filtering if opts.summarize: update_summary(summary, data) else: if not first: ui.print_() - print_data(data, opts.format) + print_data(data, item, opts.format) first = False if opts.summarize: From 5c8acc9a4960211fdf48b4972d57091d6d6aa6c1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 30 Nov 2015 08:00:34 +0100 Subject: [PATCH 0245/2280] Fix #1721 by disabling \\?\ prefix for IM --- beets/util/artresizer.py | 8 +++++--- docs/changelog.rst | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 6ef7770f8..a392ee5d2 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -92,8 +92,9 @@ def im_resize(maxwidth, path_in, path_out=None): # compatibility. try: util.command_output([ - b'convert', util.syspath(path_in), - b'-resize', b'{0}x^>'.format(maxwidth), path_out + b'convert', util.syspath(path_in, prefix=False), + b'-resize', b'{0}x^>'.format(maxwidth), + util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: log.warn(u'artresizer: IM convert failed for {0}', @@ -119,7 +120,8 @@ def pil_getsize(path_in): def im_getsize(path_in): - cmd = [b'identify', b'-format', b'%w %h', util.syspath(path_in)] + cmd = [b'identify', b'-format', b'%w %h', + util.syspath(path_in, prefix=False)] try: out = util.command_output(cmd) except subprocess.CalledProcessError as exc: diff --git a/docs/changelog.rst b/docs/changelog.rst index ac6ded79c..a78bfb727 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -69,6 +69,8 @@ Fixes: * :doc:`/plugins/convert`: Fix a crash with Unicode paths in ``--pretend`` mode. :bug:`1735` * Fix a crash when sorting by nonexistent fields on queries. :bug:`1734` +* Probably fix some mysterious errors when dealing with images using + ImageMagick on Windows. :bug:`1721` .. _Emby Server: http://emby.media From de7d9d6b0d7908afe8279a00f2207c385a787895 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 2 Dec 2015 22:04:07 +0100 Subject: [PATCH 0246/2280] Tried to fix test on windows test_slashed_query_matches_path (test.test_query.PathQueryTest) --- test/test_query.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test_query.py b/test/test_query.py index dae752581..c815b48fc 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -380,7 +380,10 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.patcher_exists = patch('beets.library.os.path.exists') self.patcher_exists.start().return_value = True - self.patcher_samefile = patch('beets.library.os.path.samefile') + #We have to create function samefile as it does not exist on + # Windows and python 2.7 + self.patcher_samefile = patch('beets.library.os.path.samefile', + create=True) self.patcher_samefile.start().return_value = True def tearDown(self): From 4937cc7e9e1d937f801a6d775e17984e61e886c0 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 2 Dec 2015 22:13:38 +0100 Subject: [PATCH 0247/2280] fixed format --- test/test_query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_query.py b/test/test_query.py index c815b48fc..8b3ad9821 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -380,7 +380,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.patcher_exists = patch('beets.library.os.path.exists') self.patcher_exists.start().return_value = True - #We have to create function samefile as it does not exist on + # We have to create function samefile as it does not exist on # Windows and python 2.7 self.patcher_samefile = patch('beets.library.os.path.samefile', create=True) From 67eb0ed54c60d2cab69616238aa802e98838cdcf Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 4 Dec 2015 20:51:25 +0100 Subject: [PATCH 0248/2280] Format track duration as H:MM instead of seconds * Modify library.Item in order to have length formatted as H:MM instead of the raw number of seconds by using a types.Float subclass (DurationType). * Add library.DurationType, with custom format() and parse() methods that handle the conversion. * Add dbcore.query.DurationQuery as a NumericQuery subclass that _convert()s the ranges specified by the user to floats, delegating the rest of the functionality in the parent NumericQuery class. * Add ui.raw_seconds_short() as the reverse of human_seconds_short(). This function uses a regular expression in order to allow any number of minutes, and always required SS to have two digits. --- beets/dbcore/query.py | 29 +++++++++++++++++++++++++++++ beets/library.py | 21 ++++++++++++++++++++- beets/ui/__init__.py | 13 +++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f0adac665..9308ba0b3 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -653,6 +653,35 @@ class DateQuery(FieldQuery): return clause, subvals +class DurationQuery(NumericQuery): + """NumericQuery that allow human-friendly (M:SS) time interval formats. + + Converts the range(s) to a float value, and delegates on NumericQuery. + + Raises InvalidQueryError when the pattern does not represent an int, float + or M:SS time interval. + """ + def _convert(self, s): + """Convert a M:SS or numeric string to a float. + + Return None if `s` is empty. + Raise an InvalidQueryError if the string cannot be converted. + """ + if not s: + return None + try: + # TODO: tidy up circular import + from beets.ui import raw_seconds_short + return raw_seconds_short(s) + except ValueError: + try: + return float(s) + except ValueError: + raise InvalidQueryArgumentTypeError( + s, + "a M:SS string or a float") + + # Sorting. class Sort(object): diff --git a/beets/library.py b/beets/library.py index 870c46856..13b0b92fa 100644 --- a/beets/library.py +++ b/beets/library.py @@ -195,6 +195,25 @@ class MusicalKey(types.String): return self.parse(key) +class DurationType(types.Float): + """Human-friendly (M:SS) representation of a time interval.""" + query = dbcore.query.DurationQuery + + def format(self, value): + return beets.ui.human_seconds_short(value or 0.0) + + def parse(self, string): + try: + # Try to format back hh:ss to seconds. + return beets.ui.raw_seconds_short(value) + except ValueError: + # Fall back to a plain float.. + try: + return float(string) + except ValueError: + return self.null + + # Library-specific sort types. class SmartArtistSort(dbcore.query.Sort): @@ -426,7 +445,7 @@ class Item(LibModel): 'original_day': types.PaddedInt(2), 'initial_key': MusicalKey(), - 'length': types.FLOAT, + 'length': DurationType(), 'bitrate': types.ScaledInt(1000, u'kbps'), 'format': types.STRING, 'samplerate': types.ScaledInt(1000, u'kHz'), diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index c51c3acb6..10266b537 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -416,6 +416,19 @@ def human_seconds_short(interval): return u'%i:%02i' % (interval // 60, interval % 60) +def raw_seconds_short(string): + """Formats a human-readable M:SS string as a float (number of seconds). + + Raises ValueError if the conversion cannot take place due to `string` not + being in the right format. + """ + match = re.match('^(\d+):([0-5]\d)$', string) + if not match: + raise ValueError('String not in M:SS format') + minutes, seconds = map(int, match.groups()) + return float(minutes*60 + seconds) + + # Colorization. # ANSI terminal colorization code heavily inspired by pygments: From 8d2fda790bf72df06b05aa2a3125a1f0fcd33437 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sat, 5 Dec 2015 13:28:56 +0100 Subject: [PATCH 0249/2280] Add config option for human vs raw track duration * Add "format_raw_length" global configuration option to allow the user to toggle between human-readable (default) or raw formatting of track durations. --- beets/config_default.yaml | 1 + beets/library.py | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index ba58debe7..545fa9638 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -65,6 +65,7 @@ ui: format_item: $artist - $album - $title format_album: $albumartist - $album time_format: '%Y-%m-%d %H:%M:%S' +format_raw_length: no sort_album: albumartist+ album+ sort_item: artist+ album+ disc+ track+ diff --git a/beets/library.py b/beets/library.py index 13b0b92fa..77c4bf8ab 100644 --- a/beets/library.py +++ b/beets/library.py @@ -200,7 +200,11 @@ class DurationType(types.Float): query = dbcore.query.DurationQuery def format(self, value): - return beets.ui.human_seconds_short(value or 0.0) + # TODO: decide if documenting format_raw_length + if not beets.config['format_raw_length'].get(bool): + return beets.ui.human_seconds_short(value or 0.0) + else: + return value def parse(self, string): try: From 62ee915aac952d3d0af3a3bc22cda453cde721be Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sat, 5 Dec 2015 14:12:27 +0100 Subject: [PATCH 0250/2280] Fix pyflakes issues, variable name --- beets/dbcore/query.py | 4 ++-- beets/library.py | 2 +- beets/ui/__init__.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 9308ba0b3..a33a2946a 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -678,8 +678,8 @@ class DurationQuery(NumericQuery): return float(s) except ValueError: raise InvalidQueryArgumentTypeError( - s, - "a M:SS string or a float") + s, + "a M:SS string or a float") # Sorting. diff --git a/beets/library.py b/beets/library.py index 77c4bf8ab..d8eb9d5d3 100644 --- a/beets/library.py +++ b/beets/library.py @@ -209,7 +209,7 @@ class DurationType(types.Float): def parse(self, string): try: # Try to format back hh:ss to seconds. - return beets.ui.raw_seconds_short(value) + return beets.ui.raw_seconds_short(string) except ValueError: # Fall back to a plain float.. try: diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 10266b537..3a25a03ff 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -426,7 +426,7 @@ def raw_seconds_short(string): if not match: raise ValueError('String not in M:SS format') minutes, seconds = map(int, match.groups()) - return float(minutes*60 + seconds) + return float(minutes * 60 + seconds) # Colorization. From cca307c88b5721d91de720f98f6ff70b9f325d35 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sat, 5 Dec 2015 14:18:23 +0100 Subject: [PATCH 0251/2280] Fix test that was expecting raw length format --- test/test_info.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_info.py b/test/test_info.py index aaabed980..4a85b6dc9 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -111,7 +111,7 @@ class InfoTest(unittest.TestCase, TestHelper): self.add_item_fixtures() out = self.run_with_output('--library', '--format', '$track. $title - $artist ($length)') - self.assertEqual(u'02. tïtle 0 - the artist (1.1)\n', out) + self.assertEqual(u'02. tïtle 0 - the artist (0:01)\n', out) def suite(): From c086a634b6006b6a956c4e16dd439fe02e1f542a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 5 Dec 2015 14:58:03 +0100 Subject: [PATCH 0252/2280] Fixed testcase TestLibrary.test_no_write_permission on windows it is important to use syspath with functions to modify path --- test/test_library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index 30b0d6fc4..c6dfc3d20 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -36,6 +36,7 @@ from beets import util from beets import plugins from beets import config from beets.mediafile import MediaFile +from beets.util import syspath from test.helper import TestHelper # Shortcut to path normalization. @@ -1044,7 +1045,7 @@ class WriteTest(unittest.TestCase, TestHelper): def test_no_write_permission(self): item = self.add_item_fixture() - path = item.path + path = syspath(item.path) os.chmod(path, stat.S_IRUSR) try: From ceafad2651eb84447c9fae5a004281f6864ce493 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 5 Dec 2015 15:05:25 +0100 Subject: [PATCH 0253/2280] Fixed testcase TestLibrary.test_write_with_custom_path on windows it is important to use syspath with functions to modify path --- test/test_library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index c6dfc3d20..c544e007e 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1058,7 +1058,7 @@ class WriteTest(unittest.TestCase, TestHelper): def test_write_with_custom_path(self): item = self.add_item_fixture() custom_path = os.path.join(self.temp_dir, 'custom.mp3') - shutil.copy(item.path, custom_path) + shutil.copy(syspath(item.path), syspath(custom_path)) item['artist'] = 'new artist' self.assertNotEqual(MediaFile(custom_path).artist, 'new artist') From 0e6427599387a39d0f725f7a8e724b30ccbb9bd3 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:07:01 +0100 Subject: [PATCH 0254/2280] Add tests for library-specific field types --- test/test_library.py | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/test/test_library.py b/test/test_library.py index 30b0d6fc4..04fa863ae 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -25,6 +25,7 @@ import shutil import re import unicodedata import sys +import time from test import _common from test._common import unittest @@ -1126,6 +1127,56 @@ class ParseQueryTest(unittest.TestCase): beets.library.parse_query_string(b"query", None) +class LibraryFieldTypesTest(unittest.TestCase): + """Test format() and parse() for library-specific field types""" + def test_datetype(self): + t = beets.library.DateType() + + # format + self.assertEqual('1973-11-29 22:33:09', t.format(123456789)) + # parse + self.assertEqual(123456789.0, t.parse('1973-11-29 22:33:09')) + self.assertEqual(123456789.0, t.parse('123456789.0')) + self.assertEqual(t.null, t.parse('not123456789.0')) + self.assertEqual(t.null, t.parse('1973-11-29')) + + def test_pathtype(self): + t = beets.library.PathType() + + # format + self.assertEqual('/tmp', t.format('/tmp')) + self.assertEqual(u'/tmp/\xe4lbum', t.format(u'/tmp/\u00e4lbum')) + # parse + self.assertEqual(b'/tmp', t.parse('/tmp')) + self.assertEqual(b'/tmp/\xc3\xa4lbum', t.parse(u'/tmp/\u00e4lbum/')) + + def test_musicalkey(self): + t = beets.library.MusicalKey() + + # parse + self.assertEqual('C#m', t.parse('c#m')) + self.assertEqual('Gm', t.parse('g minor')) + self.assertEqual('Not c#m', t.parse('not C#m')) + + def test_durationtype(self): + t = beets.library.DurationType() + + # format + self.assertEqual('1:01', t.format(61.23)) + self.assertEqual('60:01', t.format(3601.23)) + self.assertEqual('0:00', t.format(None)) + # parse + self.assertEqual(61.0, t.parse('1:01')) + self.assertEqual(61.23, t.parse('61.23')) + self.assertEqual(3601.0, t.parse('60:01')) + self.assertEqual(t.null, t.parse('1:00:01')) + self.assertEqual(t.null, t.parse('not61.23')) + # config format_raw_length + beets.config['format_raw_length'] = True + self.assertEqual(61.23, t.format(61.23)) + self.assertEqual(3601.23, t.format(3601.23)) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 4afdbdfdf4e78ad9b8f55432cbb6f4ea564e7a8f Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:14:08 +0100 Subject: [PATCH 0255/2280] Move raw_seconds_short to beets.util --- beets/dbcore/query.py | 4 +--- beets/library.py | 2 +- beets/ui/__init__.py | 13 ------------- beets/util/__init__.py | 13 +++++++++++++ 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index a33a2946a..d8a3a0ea8 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -670,9 +670,7 @@ class DurationQuery(NumericQuery): if not s: return None try: - # TODO: tidy up circular import - from beets.ui import raw_seconds_short - return raw_seconds_short(s) + return util.raw_seconds_short(s) except ValueError: try: return float(s) diff --git a/beets/library.py b/beets/library.py index d8eb9d5d3..ed6b39280 100644 --- a/beets/library.py +++ b/beets/library.py @@ -209,7 +209,7 @@ class DurationType(types.Float): def parse(self, string): try: # Try to format back hh:ss to seconds. - return beets.ui.raw_seconds_short(string) + return util.raw_seconds_short(string) except ValueError: # Fall back to a plain float.. try: diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 3a25a03ff..c51c3acb6 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -416,19 +416,6 @@ def human_seconds_short(interval): return u'%i:%02i' % (interval // 60, interval % 60) -def raw_seconds_short(string): - """Formats a human-readable M:SS string as a float (number of seconds). - - Raises ValueError if the conversion cannot take place due to `string` not - being in the right format. - """ - match = re.match('^(\d+):([0-5]\d)$', string) - if not match: - raise ValueError('String not in M:SS format') - minutes, seconds = map(int, match.groups()) - return float(minutes * 60 + seconds) - - # Colorization. # ANSI terminal colorization code heavily inspired by pygments: diff --git a/beets/util/__init__.py b/beets/util/__init__.py index e2d09c3ab..55c599a05 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -843,3 +843,16 @@ def case_sensitive(path): lower = _windows_long_path_name(path.lower()) upper = _windows_long_path_name(path.upper()) return lower != upper + + +def raw_seconds_short(string): + """Formats a human-readable M:SS string as a float (number of seconds). + + Raises ValueError if the conversion cannot take place due to `string` not + being in the right format. + """ + match = re.match('^(\d+):([0-5]\d)$', string) + if not match: + raise ValueError('String not in M:SS format') + minutes, seconds = map(int, match.groups()) + return float(minutes * 60 + seconds) From a5ecc77663b806c75478c2af4e14f70a86db4b29 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:30:20 +0100 Subject: [PATCH 0256/2280] Add documentation for M:SS length --- beets/library.py | 3 +-- docs/changelog.rst | 5 +++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index ed6b39280..f8d226dbe 100644 --- a/beets/library.py +++ b/beets/library.py @@ -200,7 +200,6 @@ class DurationType(types.Float): query = dbcore.query.DurationQuery def format(self, value): - # TODO: decide if documenting format_raw_length if not beets.config['format_raw_length'].get(bool): return beets.ui.human_seconds_short(value or 0.0) else: @@ -211,7 +210,7 @@ class DurationType(types.Float): # Try to format back hh:ss to seconds. return util.raw_seconds_short(string) except ValueError: - # Fall back to a plain float.. + # Fall back to a plain float. try: return float(string) except ValueError: diff --git a/docs/changelog.rst b/docs/changelog.rst index a78bfb727..003319267 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -26,6 +26,11 @@ New: singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` * :doc:`/plugins/info`: The plugin now accepts the ``-f/--format`` option for customizing how items are displayed. :bug:`1737` +* Track length is now displayed as ``M:SS`` by default, instead of displaying + the raw number of seconds. Queries on track length also accept this format: + for example, ``beet list length:5:30..`` will find all your tracks that have + a duration over 5 minutes and 30 seconds. You can toggle this setting off + via the ``format_raw_length`` configuration option. :bug:`1749` For developers: From 2f2cdd24da39912db9588a98f54a7743d2d5a16e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:31:45 +0100 Subject: [PATCH 0257/2280] Fix unused import leftover on test_library --- test/test_library.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index 04fa863ae..072d7e195 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -25,7 +25,6 @@ import shutil import re import unicodedata import sys -import time from test import _common from test._common import unittest From 25cb556ea2fc74df1fe8060621275dd11e77246b Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:40:14 +0100 Subject: [PATCH 0258/2280] Fix test that depended on local time --- test/test_library.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index 072d7e195..41d2ec8f8 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -25,6 +25,7 @@ import shutil import re import unicodedata import sys +import time from test import _common from test._common import unittest @@ -1132,7 +1133,10 @@ class LibraryFieldTypesTest(unittest.TestCase): t = beets.library.DateType() # format - self.assertEqual('1973-11-29 22:33:09', t.format(123456789)) + self.assertEqual(time.strftime(beets.config['time_format']. + get(unicode), + time.localtime(123456789)), + t.format(123456789)) # parse self.assertEqual(123456789.0, t.parse('1973-11-29 22:33:09')) self.assertEqual(123456789.0, t.parse('123456789.0')) From 3e2d2479b5b08c0550fd3c158a63ba442a5aeb71 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 9 Dec 2015 16:42:47 +0100 Subject: [PATCH 0259/2280] Fix test that depended on local time, 2 --- test/test_library.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 41d2ec8f8..860227a13 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1133,12 +1133,11 @@ class LibraryFieldTypesTest(unittest.TestCase): t = beets.library.DateType() # format - self.assertEqual(time.strftime(beets.config['time_format']. - get(unicode), - time.localtime(123456789)), - t.format(123456789)) + time_local = time.strftime(beets.config['time_format'].get(unicode), + time.localtime(123456789)) + self.assertEqual(time_local, t.format(123456789)) # parse - self.assertEqual(123456789.0, t.parse('1973-11-29 22:33:09')) + self.assertEqual(123456789.0, t.parse(time_local)) self.assertEqual(123456789.0, t.parse('123456789.0')) self.assertEqual(t.null, t.parse('not123456789.0')) self.assertEqual(t.null, t.parse('1973-11-29')) From 659fab2ca9a262afa9d01804f246e4dd00950d98 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 10 Dec 2015 14:30:25 -0800 Subject: [PATCH 0260/2280] Fix #879 (again): update ID3 string encodings --- beets/mediafile.py | 8 +++++--- docs/changelog.rst | 2 ++ test/test_mediafile_edge.py | 22 +++++++++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index f2dc1027d..85f3d2e67 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -38,6 +38,7 @@ from __future__ import (division, absolute_import, print_function, import mutagen import mutagen.mp3 +import mutagen.id3 import mutagen.oggopus import mutagen.oggvorbis import mutagen.mp4 @@ -747,19 +748,20 @@ class MP3DescStorageStyle(MP3StorageStyle): if self.key != 'USLT': value = [value] - # try modifying in place + # Try modifying in place. found = False for frame in frames: if frame.desc.lower() == self.description.lower(): frame.text = value + frame.encoding = mutagen.id3.Encoding.UTF8 found = True - # need to make a new frame? + # Try creating a new frame. if not found: frame = mutagen.id3.Frames[self.key]( desc=bytes(self.description), text=value, - encoding=3 + encoding=mutagen.id3.Encoding.UTF8, ) if self.id3_lang: frame.lang = self.id3_lang diff --git a/docs/changelog.rst b/docs/changelog.rst index a78bfb727..eceda093c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -71,6 +71,8 @@ Fixes: * Fix a crash when sorting by nonexistent fields on queries. :bug:`1734` * Probably fix some mysterious errors when dealing with images using ImageMagick on Windows. :bug:`1721` +* Fix a crash when writing some Unicode comment strings to MP3s that used + older encodings. The encoding is now always updated to UTF-8. :bug:`879` .. _Emby Server: http://emby.media diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 87b2b7c1f..480fa2b59 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -199,7 +199,7 @@ class SideEffectsTest(unittest.TestCase): self.assertEqual(old_mtime, new_mtime) -class EncodingTest(unittest.TestCase, TestHelper): +class MP4EncodingTest(unittest.TestCase, TestHelper): def setUp(self): self.create_temp_dir() src = os.path.join(_common.RSRC, 'full.m4a') @@ -218,6 +218,26 @@ class EncodingTest(unittest.TestCase, TestHelper): self.assertEqual(new_mf.label, u'foo\xe8bar') +class MP3EncodingTest(unittest.TestCase, TestHelper): + def setUp(self): + self.create_temp_dir() + src = os.path.join(_common.RSRC, 'full.mp3') + self.path = os.path.join(self.temp_dir, 'test.mp3') + shutil.copy(src, self.path) + + self.mf = beets.mediafile.MediaFile(self.path) + + def test_comment_with_latin1_encoding(self): + # Set up the test file with a Latin1-encoded COMM frame. The encoding + # indices defined by MP3 are listed here: + # http://id3.org/id3v2.4.0-structure + self.mf.mgfile['COMM::eng'].encoding = 0 + + # Try to store non-Latin1 text. + self.mf.comments = u'\u2028' + self.mf.save() + + class ZeroLengthMediaFile(beets.mediafile.MediaFile): @property def length(self): From f7da8549675c82dd5439825f791ddc0dfe63bc58 Mon Sep 17 00:00:00 2001 From: Matija Date: Thu, 10 Dec 2015 23:40:45 +0100 Subject: [PATCH 0261/2280] fixed copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index cddcf9900..e81766650 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2010-2014 Adrian Sampson +Copyright (c) 2010-2015 Adrian Sampson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 0e454ad39c13cc19ba4d60e27f91fd87640c3d9f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 10 Dec 2015 18:04:44 -0800 Subject: [PATCH 0262/2280] Update Fedora instructions (#1658) --- docs/guides/main.rst | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 1358e7005..b43e0e9b1 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -38,16 +38,12 @@ dropped, and Python 3.x is not yet supported.) * For **Slackware**, there's a `SlackBuild`_ available. -* On **Fedora 21**, you there is a `copr`_ for beets, which you can install - using `DNF`_ like so:: +* On **Fedora** 22 or later, there is a `DNF package`_ (or three):: - $ yum install dnf dnf-plugins-core - $ dnf copr enable afreof/beets - $ yum update - $ yum install beets + $ sudo dnf install beets beets-plugins beets-doc .. _copr: https://copr.fedoraproject.org/coprs/afreof/beets/ -.. _dnf: http://fedoraproject.org/wiki/Features/DNF +.. _dnf package: https://apps.fedoraproject.org/packages/beets .. _SlackBuild: http://slackbuilds.org/repository/14.1/multimedia/beets/ .. _beets port: http://portsmon.freebsd.org/portoverview.py?category=audio&portname=beets .. _beets from AUR: https://aur.archlinux.org/packages/beets-git/ From a15dffad1d3ed1881acd691df9a050ae6088d5a9 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 11 Dec 2015 15:58:52 +0100 Subject: [PATCH 0263/2280] Add "before_choose_candidate" event * Add "before_choose_candidate" event, sent to the plugins during TerminalImportSession.choose_match(). This event allows plugins to append additional choice to the user prompt during importer. * The event is sent on the main loop of choose_match(), with session and task parameters. The plugins are responsible for checking the task status in order to append choices in a sensible way. * Add "ExtraChoice" namedtuple to improve readability and encapsulate the concept of a single extra choice. --- beets/ui/commands.py | 47 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 2d943eee1..5d6a556ce 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -22,6 +22,9 @@ from __future__ import (division, absolute_import, print_function, import os import re +from collections import namedtuple +from itertools import chain +from string import lowercase, whitespace import beets from beets import ui @@ -39,6 +42,7 @@ from beets import logging from beets.util.confit import _package_path VARIOUS_ARTISTS = u'Various Artists' +ExtraChoice = namedtuple('ExtraChoice', ['plugin', 'id', 'long', 'callback']) # Global logger. log = logging.getLogger('beets') @@ -471,7 +475,8 @@ def _summary_judment(rec): def choose_candidate(candidates, singleton, rec, cur_artist=None, - cur_album=None, item=None, itemcount=None): + cur_album=None, item=None, itemcount=None, + extra_choices=[]): """Given a sorted list of candidates, ask the user for a selection of which candidate to use. Applies to both full albums and singletons (tracks). Candidates are either AlbumMatch or TrackMatch @@ -489,6 +494,13 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, assert cur_artist is not None assert cur_album is not None + # Build helper variables for extra choices. + # TODO: move "abort" choice always to the end? + # TODO: add plugin name info on choices ("(mb) Print tracks")? + extra_opts = tuple([c.long for c in extra_choices]) + extra_actions = {c.long.strip(lowercase + whitespace)[0].lower(): c.id + for c in extra_choices} + # Zero candidates. if not candidates: if singleton: @@ -502,7 +514,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, 'http://beets.readthedocs.org/en/latest/faq.html#nomatch') opts = ('Use as-is', 'as Tracks', 'Group albums', 'Skip', 'Enter search', 'enter Id', 'aBort') - sel = ui.input_options(opts) + sel = ui.input_options(opts + extra_opts) if sel == 'u': return importer.action.ASIS elif sel == 't': @@ -518,6 +530,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.MANUAL_ID elif sel == 'g': return importer.action.ALBUMS + elif sel in extra_actions.keys(): + return extra_actions[sel] else: assert False @@ -571,7 +585,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, else: opts = ('Skip', 'Use as-is', 'as Tracks', 'Group albums', 'Enter search', 'enter Id', 'aBort') - sel = ui.input_options(opts, numrange=(1, len(candidates))) + sel = ui.input_options(opts + extra_opts, + numrange=(1, len(candidates))) if sel == 's': return importer.action.SKIP elif sel == 'u': @@ -589,6 +604,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.MANUAL_ID elif sel == 'g': return importer.action.ALBUMS + elif sel in extra_actions.keys(): + return extra_actions[sel] else: # Numerical selection. match = candidates[sel - 1] if sel != 1: @@ -623,7 +640,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, }) if default is None: require = True - sel = ui.input_options(opts, require=require, default=default) + sel = ui.input_options(opts + extra_opts, require=require, + default=default) if sel == 'a': return match elif sel == 'g': @@ -641,6 +659,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, raise importer.ImportAbort() elif sel == 'i': return importer.action.MANUAL_ID + elif sel in extra_actions.keys(): + return extra_actions[sel] def manual_search(singleton): @@ -684,10 +704,18 @@ class TerminalImportSession(importer.ImportSession): # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: + # Gather extra choices from plugins. + # TODO: check for conflicts in choices (duplicated letters, etc) + # TODO: provide a way to override summary_judment and/or non-timid + # mode? Might be useful for some plugins + extra_choices = list(chain(*plugins.send('before_choose_candidate', + session=self, task=task))) + extra_ops = {c.id: c.callback for c in extra_choices} + # Ask for a choice from the user. choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, - itemcount=len(task.items) + itemcount=len(task.items), extra_choices=extra_choices ) # Choose which tags to use. @@ -708,6 +736,15 @@ class TerminalImportSession(importer.ImportSession): _, _, candidates, rec = autotag.tag_album( task.items, search_id=search_id ) + elif choice in extra_ops.keys(): + # Allow extra ops to automatically set the post-choice. + # TODO: currently action.MANUAL and action.MANUAL_ID are not + # properly handled + post_choice = extra_ops[choice](self, task) + if post_choice in (importer.action.SKIP, importer.action.ASIS, + importer.action.TRACKS, + importer.action.ALBUMS): + return post_choice else: # We have a candidate! Finish tagging. Here, choice is an # AlbumMatch object. From 11f4add6873c7c089b5674415276a71b4c03cb42 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 11 Dec 2015 16:04:13 +0100 Subject: [PATCH 0264/2280] mbsubmit: add example mbsubmit plugin * Add example "mbsubmit" plugin, which allows the user to print the tracklist of an unmatched album during the import process in a format understood by MusicBrainz track parser. * The plugin listens for the before_choose_candidate event and appends the track printing options depending on the task status (candidates and recommendation). --- beetsplug/mbsubmit.py | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 beetsplug/mbsubmit.py diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py new file mode 100644 index 000000000..09be1eb5d --- /dev/null +++ b/beetsplug/mbsubmit.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2015, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Aid in submitting information to MusicBrainz. + +This plugin allows the user to print track information in a format that is +parseable by the MusicBrainz track parser. Programmatic submitting is not +implemented by MusicBrainz yet. +""" + +from __future__ import (division, absolute_import, print_function, + unicode_literals) + + +from beets.autotag import Recommendation +from beets.importer import action +from beets.plugins import BeetsPlugin +from beets.ui.commands import ExtraChoice +from beetsplug.info import print_data + + +class MBSubmitPlugin(BeetsPlugin): + def __init__(self): + super(MBSubmitPlugin, self).__init__() + + self.register_listener('before_choose_candidate', + self.before_choose_candidate_event) + + def before_choose_candidate_event(self, session, task): + # This intends to illustrate a simple plugin that adds choices + # depending on conditions. + # Plugins should return a list of ExtraChoices (basically, the + # "cosmetic" values and a callback function). This list is received and + # flattened on plugins.send('before_choose_candidate'). + if not task.candidates or task.rec == Recommendation.none: + return [ExtraChoice(self, 'PRINT', 'Print tracks', + self.print_tracks), + ExtraChoice(self, 'PRINT_SKIP', 'print tracks and sKip', + self.print_tracks_and_skip)] + + # Callbacks for choices. + def print_tracks(self, session, task): + for i in task.items: + print_data(None, i, '$track. $artist - $title ($length)') + + def print_tracks_and_skip(self, session, task): + # Example of a function that automatically sets the next action, + # avoiding the user to be prompted again. It has some drawbacks (for + # example, actions such as action.MANUAL are not handled properly, as + # they do not exit the main TerminalImportSession.choose_match loop). + # + # The idea is that if a callback function returns an action.X value, + # task.action is set to that value after the callback is processed. + for i in task.items: + print_data(None, i, '$track. $artist - $title ($length)') + return action.SKIP From 37250ef27b5b725744537177c854f033ba1c7f1c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 16:40:42 -0800 Subject: [PATCH 0265/2280] fetchart: Fix #1610: itunes install docs --- docs/plugins/fetchart.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index c04517b11..beaf7f951 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -126,10 +126,13 @@ iTunes Store To use the iTunes Store as an art source, install the `python-itunes`_ library. You can do this using `pip`_, like so:: - $ pip install python-itunes + $ pip install https://github.com/ocelma/python-itunes/archive/master.zip +(There's currently `a problem`_ that prevents a plain ``pip install +python-itunes`` from working.) Once the library is installed, the plugin will use it to search automatically. +.. _a problem: https://github.com/ocelma/python-itunes/issues/9 .. _python-itunes: https://github.com/ocelma/python-itunes .. _pip: http://pip.openplans.org/ From 3314db2f77cb6b4a5ac4639e990a6ade08472144 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 16:44:55 -0800 Subject: [PATCH 0266/2280] fetchart: Better logging for iTunes (#1760) --- beetsplug/fetchart.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 1b2089b58..81137dc28 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -196,11 +196,19 @@ class ITunesStore(ArtSource): try: # Isolate bugs in the iTunes library while searching. try: - itunes_album = itunes.search_album(search_string)[0] + results = itunes.search_album(search_string) except Exception as exc: self._log.debug('iTunes search failed: {0}', exc) return + # Get the first match. + if results: + itunes_album = results[0] + else: + self._log.debug('iTunes search for {:r} got no results', + search_string) + return + if itunes_album.get_artwork()['100']: small_url = itunes_album.get_artwork()['100'] big_url = small_url.replace('100x100', '1200x1200') From 5597313ea01201b1fddb688c1ae7c767f80aae58 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 16:47:00 -0800 Subject: [PATCH 0267/2280] fetchart: Remove Google backend (fix #1760) --- beetsplug/fetchart.py | 31 +------------------------------ docs/changelog.rst | 2 ++ docs/plugins/fetchart.rst | 19 +++++-------------- 3 files changed, 8 insertions(+), 44 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 81137dc28..a56f9f95a 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -157,34 +157,6 @@ class AlbumArtOrg(ArtSource): self._log.debug(u'no image found on page') -class GoogleImages(ArtSource): - URL = 'https://ajax.googleapis.com/ajax/services/search/images' - - def get(self, album): - """Return art URL from google.org given an album title and - interpreter. - """ - if not (album.albumartist and album.album): - return - search_string = (album.albumartist + ',' + album.album).encode('utf-8') - response = self.request(self.URL, params={ - 'v': '1.0', - 'q': search_string, - 'start': '0', - }) - - # Get results using JSON. - try: - results = response.json() - data = results['responseData'] - dataInfo = data['results'] - for myUrl in dataInfo: - yield myUrl['unescapedUrl'] - except: - self._log.debug(u'error scraping art page') - return - - class ITunesStore(ArtSource): # Art from the iTunes Store. def get(self, album): @@ -388,7 +360,7 @@ class FileSystem(ArtSource): # Try each source in turn. -SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', u'google', +SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', u'wikipedia'] ART_SOURCES = { @@ -396,7 +368,6 @@ ART_SOURCES = { u'itunes': ITunesStore, u'albumart': AlbumArtOrg, u'amazon': Amazon, - u'google': GoogleImages, u'wikipedia': Wikipedia, } diff --git a/docs/changelog.rst b/docs/changelog.rst index eceda093c..b1cddc59e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -73,6 +73,8 @@ Fixes: ImageMagick on Windows. :bug:`1721` * Fix a crash when writing some Unicode comment strings to MP3s that used older encodings. The encoding is now always updated to UTF-8. :bug:`879` +* :doc:`/plugins/fetchart`: The Google Images backend has been removed. It + used an API that has been shut down. :bug:`1760` .. _Emby Server: http://emby.media diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index beaf7f951..80149d478 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -50,7 +50,7 @@ file. The available options are: - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. Default: ``coverart itunes amazon albumart``, i.e., everything but - ``wikipedia`` and ``google``. Enable those two sources for more matches at + ``wikipedia``. Enable those two sources for more matches at the cost of some speed. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ @@ -94,7 +94,7 @@ no resizing is performed for album art found on the filesystem---only downloaded art is resized. Server-side resizing can also be slower than local resizing, so consider installing one of the two backends for better performance. -When using ImageMagic, beets looks for the ``convert`` executable in your path. +When using ImageMagick, beets looks for the ``convert`` executable in your path. On some versions of Windows, the program can be shadowed by a system-provided ``convert.exe``. On these systems, you may need to modify your ``%PATH%`` environment variable so that ImageMagick comes first or use Pillow instead. @@ -106,8 +106,9 @@ Album Art Sources ----------------- By default, this plugin searches for art in the local filesystem as well as on -the Cover Art Archive, the iTunes Store, Amazon, AlbumArt.org, -and Google Image Search, and Wikipedia, in that order. You can reorder the sources or remove +the Cover Art Archive, the iTunes Store, Amazon, and AlbumArt.org, in that +order. +You can reorder the sources or remove some to speed up the process using the ``sources`` configuration option. When looking for local album art, beets checks for image files located in the @@ -136,16 +137,6 @@ Once the library is installed, the plugin will use it to search automatically. .. _python-itunes: https://github.com/ocelma/python-itunes .. _pip: http://pip.openplans.org/ -Google Image Search -''''''''''''''''''' - -You can optionally search for cover art on `Google Images`_. This option uses -the first hit for a search query consisting of the artist and album name. It -is therefore approximate: "incorrect" image matches are possible (although -unlikely). - -.. _Google Images: http://images.google.com/ - Embedding Album Art ------------------- From b31f8cd802477171b0e224ec845ef7159fd903dc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 16:58:49 -0800 Subject: [PATCH 0268/2280] Remove tests for Google fetchart backend (#1760) --- test/test_art.py | 32 -------------------------------- 1 file changed, 32 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 04bfe3eed..cb29f3769 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -226,38 +226,6 @@ class AAOTest(_common.TestCase): self.assertEqual(list(res), []) -class GoogleImageTest(_common.TestCase): - - _google_url = 'https://ajax.googleapis.com/ajax/services/search/images' - - def setUp(self): - super(GoogleImageTest, self).setUp() - self.source = fetchart.GoogleImages(logger) - - @responses.activate - def run(self, *args, **kwargs): - super(GoogleImageTest, self).run(*args, **kwargs) - - def mock_response(self, url, json): - responses.add(responses.GET, url, body=json, - content_type='application/json') - - def test_google_art_finds_image(self): - album = _common.Bag(albumartist="some artist", album="some album") - json = b"""{"responseData": {"results": - [{"unescapedUrl": "url_to_the_image"}]}}""" - self.mock_response(self._google_url, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url)[0], 'url_to_the_image') - - def test_google_art_dont_finds_image(self): - album = _common.Bag(albumartist="some artist", album="some album") - json = b"""bla blup""" - self.mock_response(self._google_url, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url), []) - - class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() From 3855fa0766dfe54a11497afd29ab22b287018976 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 17:33:23 -0800 Subject: [PATCH 0269/2280] Doc refinements for #1749 --- docs/changelog.rst | 4 ++-- docs/reference/query.rst | 5 +++++ test/rsrc/unicode’d.mp3 | Bin 12820 -> 12820 bytes 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index e75764c30..2df44a999 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -29,8 +29,8 @@ New: * Track length is now displayed as ``M:SS`` by default, instead of displaying the raw number of seconds. Queries on track length also accept this format: for example, ``beet list length:5:30..`` will find all your tracks that have - a duration over 5 minutes and 30 seconds. You can toggle this setting off - via the ``format_raw_length`` configuration option. :bug:`1749` + a duration over 5 minutes and 30 seconds. You can turn off this new behavior + using the ``format_raw_length`` configuration option. :bug:`1749` For developers: diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 1349d755e..82a16869d 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -144,6 +144,11 @@ and this command finds MP3 files with bitrates of 128k or lower:: $ beet list format:MP3 bitrate:..128000 +The ``length`` field also lets you use a "M:SS" format. For example, this +query finds tracks that are less than four and a half minutes in length:: + + $ beet list length:..4:30 + .. _datequery: diff --git a/test/rsrc/unicode’d.mp3 b/test/rsrc/unicode’d.mp3 index ef732eba6268c44cbeee5f40246e156b259ad04a..a1418194129a59975c475decb4e845c71c2389a3 100644 GIT binary patch delta 47 zcmbP|G9_igBw6OvymW?=j8ui>{M_8sypm!DXMbN`1_p)<1_tJh>+dl!GH>okymW?=j8ui>{M_8sypm!DXMbN`1_p)<1_p+W>+dl!GHmW+Zqow* DgFO!Z From d11fe020cec06c14878e20fe11fe970295df3d2c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 18:03:12 -0800 Subject: [PATCH 0270/2280] snake_case variable names --- beetsplug/lyrics.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 0bd49589c..584891789 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -454,28 +454,28 @@ class Google(Backend): BY_TRANS = ['by', 'par', 'de', 'von'] LYRICS_TRANS = ['lyrics', 'paroles', 'letras', 'liedtexte'] - def is_page_candidate(self, urlLink, urlTitle, title, artist): + def is_page_candidate(self, url_link, url_title, title, artist): """Return True if the URL title makes it a good candidate to be a page that contains lyrics of title by artist. """ title = self.slugify(title.lower()) artist = self.slugify(artist.lower()) sitename = re.search(u"//([^/]+)/.*", - self.slugify(urlLink.lower())).group(1) - urlTitle = self.slugify(urlTitle.lower()) + self.slugify(url_link.lower())).group(1) + url_title = self.slugify(url_title.lower()) # Check if URL title contains song title (exact match) - if urlTitle.find(title) != -1: + if url_title.find(title) != -1: return True # or try extracting song title from URL title and check if # they are close enough tokens = [by + '_' + artist for by in self.BY_TRANS] + \ [artist, sitename, sitename.replace('www.', '')] + \ self.LYRICS_TRANS - songTitle = re.sub(u'(%s)' % u'|'.join(tokens), u'', urlTitle) - songTitle = songTitle.strip('_|') - typoRatio = .9 - ratio = difflib.SequenceMatcher(None, songTitle, title).ratio() - return ratio >= typoRatio + song_title = re.sub(u'(%s)' % u'|'.join(tokens), u'', url_title) + song_title = song_title.strip('_|') + typo_ratio = .9 + ratio = difflib.SequenceMatcher(None, song_title, title).ratio() + return ratio >= typo_ratio def fetch(self, artist, title): query = u"%s %s" % (artist, title) @@ -492,12 +492,12 @@ class Google(Backend): if 'items' in data.keys(): for item in data['items']: - urlLink = item['link'] - urlTitle = item.get('title', u'') - if not self.is_page_candidate(urlLink, urlTitle, + url_link = item['link'] + url_title = item.get('title', u'') + if not self.is_page_candidate(url_link, url_title, title, artist): continue - html = self.fetch_url(urlLink) + html = self.fetch_url(url_link) lyrics = scrape_lyrics_from_html(html) if not lyrics: continue From 5a285cc11f2456f63ed9a4f14d99b69813ad6a4e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 18:09:24 -0800 Subject: [PATCH 0271/2280] Fix #1673: Escape regex terms in lyrics --- beetsplug/lyrics.py | 4 ++++ docs/changelog.rst | 3 +++ test/test_lyrics.py | 11 +++++++++++ 3 files changed, 18 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 584891789..1af34df99 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -463,15 +463,19 @@ class Google(Backend): sitename = re.search(u"//([^/]+)/.*", self.slugify(url_link.lower())).group(1) url_title = self.slugify(url_title.lower()) + # Check if URL title contains song title (exact match) if url_title.find(title) != -1: return True + # or try extracting song title from URL title and check if # they are close enough tokens = [by + '_' + artist for by in self.BY_TRANS] + \ [artist, sitename, sitename.replace('www.', '')] + \ self.LYRICS_TRANS + tokens = [re.escape(t) for t in tokens] song_title = re.sub(u'(%s)' % u'|'.join(tokens), u'', url_title) + song_title = song_title.strip('_|') typo_ratio = .9 ratio = difflib.SequenceMatcher(None, song_title, title).ratio() diff --git a/docs/changelog.rst b/docs/changelog.rst index 305157bf0..88e74fe5a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -84,6 +84,9 @@ Fixes: older encodings. The encoding is now always updated to UTF-8. :bug:`879` * :doc:`/plugins/fetchart`: The Google Images backend has been removed. It used an API that has been shut down. :bug:`1760` +* :doc:`/plugins/lyrics`: Fix a crash in the Google backend when searching for + bands with regular-expression characters in their names, like Sunn O))). + :bug:`1673` .. _Emby Server: http://emby.media diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 33b8c6bb5..515e96587 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -376,6 +376,17 @@ class LyricsGooglePluginTest(unittest.TestCase): self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'], s['artist']), False, url) + def test_is_page_candidate_special_chars(self): + """Ensure that `is_page_candidate` doesn't crash when the artist + and such contain special regular expression characters. + """ + # https://github.com/sampsyo/beets/issues/1673 + s = self.source + url = s['url'] + s['path'] + url_title = u'foo' + + google.is_page_candidate(url, url_title, s['title'], 'Sunn O)))') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From f5448d15318c0acd0edbd3b3c85568101686091e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 18:20:05 -0800 Subject: [PATCH 0272/2280] scrub: Run on import in auto mode (#1657) --- beetsplug/scrub.py | 21 +++++++-------------- docs/changelog.rst | 3 +++ 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 4636b477d..550d32bee 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -45,9 +45,6 @@ _MUTAGEN_FORMATS = { } -scrubbing = False - - class ScrubPlugin(BeetsPlugin): """Removes extraneous metadata from files' tags.""" def __init__(self): @@ -55,15 +52,12 @@ class ScrubPlugin(BeetsPlugin): self.config.add({ 'auto': True, }) - self.register_listener("write", self.write_item) + + if self.config['auto']: + self.register_listener("import_task_files", self.import_task_files) def commands(self): def scrub_func(lib, opts, args): - # This is a little bit hacky, but we set a global flag to - # avoid autoscrubbing when we're also explicitly scrubbing. - global scrubbing - scrubbing = True - # Walk through matching files and remove tags. for item in lib.items(ui.decargs(args)): self._log.info(u'scrubbing: {0}', @@ -92,8 +86,6 @@ class ScrubPlugin(BeetsPlugin): mf.art = art mf.save() - scrubbing = False - scrub_cmd = ui.Subcommand('scrub', help='clean audio tags') scrub_cmd.parser.add_option('-W', '--nowrite', dest='write', action='store_false', default=True, @@ -140,8 +132,9 @@ class ScrubPlugin(BeetsPlugin): self._log.error(u'could not scrub {0}: {1}', util.displayable_path(path), exc) - def write_item(self, item, path, tags): - """Automatically embed art into imported albums.""" - if not scrubbing and self.config['auto']: + def import_task_files(self, session, task): + """Automatically scrub imported files.""" + for item in task.imported_items(): + path = item.path self._log.debug(u'auto-scrubbing {0}', util.displayable_path(path)) self._scrub(path) diff --git a/docs/changelog.rst b/docs/changelog.rst index 88e74fe5a..d6627089e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -87,6 +87,9 @@ Fixes: * :doc:`/plugins/lyrics`: Fix a crash in the Google backend when searching for bands with regular-expression characters in their names, like Sunn O))). :bug:`1673` +* :doc:`/plugins/scrub`: In ``auto`` mode, the plugin now *actually* only + scrubs files on import---not every time files were written, as it previously + did. :bug:`1657` .. _Emby Server: http://emby.media From d5c51dd816bfedb6a0721af3d29de55d22b665b1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 18:28:58 -0800 Subject: [PATCH 0273/2280] scrub: Restore tags & art in auto mode (#1657) --- beetsplug/scrub.py | 57 +++++++++++++++++++++++++--------------------- docs/changelog.rst | 2 ++ 2 files changed, 33 insertions(+), 26 deletions(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 550d32bee..13f2cfc2c 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -62,29 +62,7 @@ class ScrubPlugin(BeetsPlugin): for item in lib.items(ui.decargs(args)): self._log.info(u'scrubbing: {0}', util.displayable_path(item.path)) - - # Get album art if we need to restore it. - if opts.write: - try: - mf = mediafile.MediaFile(util.syspath(item.path), - config['id3v23'].get(bool)) - except IOError as exc: - self._log.error(u'could not open file to scrub: {0}', - exc) - art = mf.art - - # Remove all tags. - self._scrub(item.path) - - # Restore tags, if enabled. - if opts.write: - self._log.debug(u'writing new tags after scrub') - item.try_write() - if art: - self._log.info(u'restoring art') - mf = mediafile.MediaFile(util.syspath(item.path)) - mf.art = art - mf.save() + self._scrub_item(item, opts.write) scrub_cmd = ui.Subcommand('scrub', help='clean audio tags') scrub_cmd.parser.add_option('-W', '--nowrite', dest='write', @@ -132,9 +110,36 @@ class ScrubPlugin(BeetsPlugin): self._log.error(u'could not scrub {0}: {1}', util.displayable_path(path), exc) + def _scrub_item(self, item, restore=True): + """Remove tags from an Item's associated file and, if `restore` + is enabled, write the database's tags back to the file. + """ + # Get album art if we need to restore it. + if restore: + try: + mf = mediafile.MediaFile(util.syspath(item.path), + config['id3v23'].get(bool)) + except IOError as exc: + self._log.error(u'could not open file to scrub: {0}', + exc) + art = mf.art + + # Remove all tags. + self._scrub(item.path) + + # Restore tags, if enabled. + if restore: + self._log.debug(u'writing new tags after scrub') + item.try_write() + if art: + self._log.info(u'restoring art') + mf = mediafile.MediaFile(util.syspath(item.path)) + mf.art = art + mf.save() + def import_task_files(self, session, task): """Automatically scrub imported files.""" for item in task.imported_items(): - path = item.path - self._log.debug(u'auto-scrubbing {0}', util.displayable_path(path)) - self._scrub(path) + self._log.debug(u'auto-scrubbing {0}', + util.displayable_path(item.path)) + self._scrub_item(item) diff --git a/docs/changelog.rst b/docs/changelog.rst index d6627089e..7f07bbb1c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -90,6 +90,8 @@ Fixes: * :doc:`/plugins/scrub`: In ``auto`` mode, the plugin now *actually* only scrubs files on import---not every time files were written, as it previously did. :bug:`1657` +* :doc:`/plugins/scrub`: Also in ``auto`` mode, album art is now correctly + restored. :bug:`1657` .. _Emby Server: http://emby.media From 7749cba00e1968bbf1b80c8ffc2b87e1798e86e2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 12 Dec 2015 18:29:49 -0800 Subject: [PATCH 0274/2280] scrub: Demote a log message to debug This seems unnecessary in the `beet scrub` output. --- beetsplug/scrub.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 13f2cfc2c..4e37ad7ff 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -132,7 +132,7 @@ class ScrubPlugin(BeetsPlugin): self._log.debug(u'writing new tags after scrub') item.try_write() if art: - self._log.info(u'restoring art') + self._log.debug(u'restoring art') mf = mediafile.MediaFile(util.syspath(item.path)) mf.art = art mf.save() From 70cefb516f46b1aec4cfc6bca4f9a4b629ba8cb0 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 15 Dec 2015 18:33:09 +0100 Subject: [PATCH 0275/2280] Prompt event style changes and cleanup * Rename "ExtraChoice" to "PromptChoice", and add an attribute for the short letter used by the choice (short). * Add TerminalImportSession._get_plugin_options() for isolating the sending of the event and the processing of the returned values (flattening, check for letter conflicts). * Remove unnecessary TODO lines and other style cleanups. --- beets/ui/commands.py | 71 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 5d6a556ce..36f0fbf03 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -22,9 +22,8 @@ from __future__ import (division, absolute_import, print_function, import os import re -from collections import namedtuple +from collections import namedtuple, Counter from itertools import chain -from string import lowercase, whitespace import beets from beets import ui @@ -42,7 +41,8 @@ from beets import logging from beets.util.confit import _package_path VARIOUS_ARTISTS = u'Various Artists' -ExtraChoice = namedtuple('ExtraChoice', ['plugin', 'id', 'long', 'callback']) +PromptChoice = namedtuple('ExtraChoice', ['plugin', 'id', 'short', 'long', + 'callback']) # Global logger. log = logging.getLogger('beets') @@ -495,11 +495,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, assert cur_album is not None # Build helper variables for extra choices. - # TODO: move "abort" choice always to the end? - # TODO: add plugin name info on choices ("(mb) Print tracks")? - extra_opts = tuple([c.long for c in extra_choices]) - extra_actions = {c.long.strip(lowercase + whitespace)[0].lower(): c.id - for c in extra_choices} + extra_opts = tuple(c.long for c in extra_choices) + extra_actions = {c.short: c.id for c in extra_choices} # Zero candidates. if not candidates: @@ -705,11 +702,7 @@ class TerminalImportSession(importer.ImportSession): candidates, rec = task.candidates, task.rec while True: # Gather extra choices from plugins. - # TODO: check for conflicts in choices (duplicated letters, etc) - # TODO: provide a way to override summary_judment and/or non-timid - # mode? Might be useful for some plugins - extra_choices = list(chain(*plugins.send('before_choose_candidate', - session=self, task=task))) + extra_choices = self._get_plugin_options(task) extra_ops = {c.id: c.callback for c in extra_choices} # Ask for a choice from the user. @@ -738,10 +731,9 @@ class TerminalImportSession(importer.ImportSession): ) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. - # TODO: currently action.MANUAL and action.MANUAL_ID are not - # properly handled post_choice = extra_ops[choice](self, task) - if post_choice in (importer.action.SKIP, importer.action.ASIS, + if post_choice in (importer.action.SKIP, + importer.action.ASIS, importer.action.TRACKS, importer.action.ALBUMS): return post_choice @@ -838,6 +830,53 @@ class TerminalImportSession(importer.ImportSession): "was interrupted. Resume (Y/n)?" .format(displayable_path(path))) + def _get_plugin_options(self, task): + """Get the extra options appended to the plugins to the ui prompt. + + The `before_choose_candidate` event is sent to the plugins, with + session and task as its parameters. Plugins are responsible for + checking the right conditions and returning a list of `PromptChoice`s, + which is flattened and checked for conflicts. + + Raises `ValueError` if two of the choices have the same short letter. + + Returns a list of `PromptChoice`s. + """ + # Send the before_choose_candidate event and flatten list. + extra_choices = list(chain(*plugins.send('before_choose_candidate', + session=self, task=task))) + # Take into account default options, for duplicate checking. + all_choices = [PromptChoice(self, importer.action.SKIP, 's', 'Skip', + None), + PromptChoice(self, importer.action.ASIS, 'u', + 'Use as-is', None), + PromptChoice(self, importer.action.TRACKS, 't', + 'as Tracks', None), + PromptChoice(self, importer.action.ALBUMS, 'g', + 'Group albums', None), + PromptChoice(self, importer.action.MANUAL, 'e', + 'Enter search', None), + PromptChoice(self, importer.action.MANUAL_ID, 'i', + 'enter Id', None), + PromptChoice(self, '', 'b', 'aBort', None)] +\ + extra_choices + + short_letters = [c.short for c in all_choices] + if len(short_letters) != len(set(short_letters)): + # Duplicate short letter has been found. + duplicates = [i for i, count in Counter(short_letters).items() + if count > 1] + # Build informative message: 'x': classname:"long option",... + dup = {letter: ['%s:"%s"' % (type(c.plugin).__name__, c.long) + for c in all_choices if c.short == letter] + for letter in duplicates} + conflict_msg = '; '.join("'%s': %s" % (k, ', '.join(v)) + for (k, v) in dup.iteritems()) + raise ValueError("Prompt options have the same short letter\n%s" % + conflict_msg) + return extra_choices + + # The import command. From c94679e143268e4da993a248a356fe91ad6c666a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 15 Dec 2015 20:13:34 +0100 Subject: [PATCH 0276/2280] Add prompt event documentation * Add documentation for the before_choose_candidate event (add event to the event list and add section with example usage). --- docs/dev/plugins.rst | 67 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 885ef2222..8fa4871bf 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -227,12 +227,17 @@ The events currently available are: of a ``TrackInfo``. Parameter: ``info``. +* `before_choose_candidate`: called before the user is prompted for a decision + during a ``beet import`` interactive session. Plugins can use this event for + :ref:`appending choices to the prompt ` by returning a + list of ``PromptChoices``. Parameters: ``task`` and ``session``. + The included ``mpdupdate`` plugin provides an example use case for event listeners. Extend the Autotagger ^^^^^^^^^^^^^^^^^^^^^ -Plugins in can also enhance the functionality of the autotagger. For a +Plugins can also enhance the functionality of the autotagger. For a comprehensive example, try looking at the ``chroma`` plugin, which is included with beets. @@ -528,3 +533,63 @@ command and an import stage, but the command needs to print more messages than the import stage. (For example, you'll want to log "found lyrics for this song" when you're run explicitly as a command, but you don't want to noisily interrupt the importer interface when running automatically.) + +.. _append_prompt_choices: + +Append Prompt Choices +^^^^^^^^^^^^^^^^^^^^^ + +Plugins can also append choices to the prompt presented to the user during +an import session. + +To do so, add a listener for the ``before_choose_candidate`` event, and return +a list of ``PromptChoices`` that represent the additional choices that your +plugin shall expose to the user:: + + from beets.plugins import BeetsPlugin + + class ExamplePlugin(BeetsPlugin): + def __init__(self): + super(ExamplePlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.before_choose_candidate_event) + + def before_choose_candidate_event(self, session, task): + return [PromptChoice(self, 'PRINT_FOO', 'p', 'Print foo', self.foo), + PromptChoice(self, 'DO_BAR', 'd', 'Do bar', self.bar)] + + def foo(self, session, task): + print('User has chosen "Print foo"!') + + def bar(self, session, task): + print('User has chosen "do Bar"!') + +The previous example modifies the standard prompt:: + + # selection (default 1), Skip, Use as-is, as Tracks, Group albums, + Enter search, enter Id, aBort? + +by appending two additional options (``Print foo`` and ``Do bar``):: + + # selection (default 1), Skip, Use as-is, as Tracks, Group albums, + Enter search, enter Id, aBort, Print foo, Do bar? + +If the user selects a choice, the ``callback`` attribute of the corresponding +``PromptChoice`` will be called. It is the responsibility of the plugin to +check for the status of the import session and decide the choices to be +appended: for example, if a particular choice should only be presented if the +album has no candidates, the relevant checks against ``task.candidates`` should +be performed inside the plugin's ``before_choose_candidate_event`` accordingly. + +Please make sure that the short letter for each of the choices provided by the +plugin is not already in use: the importer will raise an exception if two or +more choices try to use the same short letter. As a reference, the following +characters are used by the choices on the core importer prompt, and hence +should not be used: ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. + +Additionally, the callback function can optionally specify the next action to +be performed by returning one of the values from ``importer.action``, which +will be passed to the main loop upon the callback has been processed. Note that +``action.MANUAL`` and ``action.MANUAL_ID`` will have no effect even if +returned by the callback, due to the current arquitecture of the import +process. From f5241f7c28d9547b3ffb2265ec795bc777f6b6c1 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 15 Dec 2015 20:15:42 +0100 Subject: [PATCH 0277/2280] mbsubmit: update to style changes, remove comments * Update mbsubmit plugin in order to use PromptChoice instead of the previous ExtraChoice. * Remove comments as they are now present on the pull request and documentation. --- beetsplug/mbsubmit.py | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 09be1eb5d..5e839b626 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -27,7 +27,7 @@ from __future__ import (division, absolute_import, print_function, from beets.autotag import Recommendation from beets.importer import action from beets.plugins import BeetsPlugin -from beets.ui.commands import ExtraChoice +from beets.ui.commands import PromptChoice from beetsplug.info import print_data @@ -39,16 +39,12 @@ class MBSubmitPlugin(BeetsPlugin): self.before_choose_candidate_event) def before_choose_candidate_event(self, session, task): - # This intends to illustrate a simple plugin that adds choices - # depending on conditions. - # Plugins should return a list of ExtraChoices (basically, the - # "cosmetic" values and a callback function). This list is received and - # flattened on plugins.send('before_choose_candidate'). if not task.candidates or task.rec == Recommendation.none: - return [ExtraChoice(self, 'PRINT', 'Print tracks', - self.print_tracks), - ExtraChoice(self, 'PRINT_SKIP', 'print tracks and sKip', - self.print_tracks_and_skip)] + return [PromptChoice(self, 'PRINT', 'p', 'Print tracks', + self.print_tracks), + PromptChoice(self, 'PRINT_SKIP', 'k', + 'print tracks and sKip', + self.print_tracks_and_skip)] # Callbacks for choices. def print_tracks(self, session, task): @@ -56,13 +52,6 @@ class MBSubmitPlugin(BeetsPlugin): print_data(None, i, '$track. $artist - $title ($length)') def print_tracks_and_skip(self, session, task): - # Example of a function that automatically sets the next action, - # avoiding the user to be prompted again. It has some drawbacks (for - # example, actions such as action.MANUAL are not handled properly, as - # they do not exit the main TerminalImportSession.choose_match loop). - # - # The idea is that if a callback function returns an action.X value, - # task.action is set to that value after the callback is processed. for i in task.items: print_data(None, i, '$track. $artist - $title ($length)') return action.SKIP From 393d404b6ec827ceaf971e709ecd018adb247f32 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 15 Dec 2015 13:43:35 -0800 Subject: [PATCH 0278/2280] Clean up changelog for edit plugin --- docs/changelog.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 7f07bbb1c..49f79f555 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3,13 +3,11 @@ Changelog 1.3.16 (in development) ----------------------- -* A new plugin edit helps you manually edit fields from items. - You search for items in the normal beets way.Then edit opens a texteditor - with the items and the fields of the items you want to edit. Afterwards you can - review your changes save them back into the items. New: +* A new :doc:`/plugins/edit` lets you manually edit your music's metadata + using your favorite text editor. :bug:`164` :bug:`1706` * Three commands, ``modify``, ``update``, and ``mbsync``, would previously move files by default after changing their metadata. Now, these commands will only move files if you have the :ref:`config-import-copy` or From fc08b4665d71d9be3933024ef476670afa3b7d0a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 16 Dec 2015 19:10:30 +0100 Subject: [PATCH 0279/2280] Prompt event cleanup, conflict solving, singleton * Simplify PromptChoice so "plugin" and "id" fields are removed, updating the loops and the rest of the code to reflect this change. * Solve short letter conflicts by keeping one of the choices and removing the rest, instead of by raising an Exception. * Misc cleanups as suggested on #1758 discussion. --- beets/ui/commands.py | 92 ++++++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 41 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 36f0fbf03..4f87ad84e 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -41,8 +41,7 @@ from beets import logging from beets.util.confit import _package_path VARIOUS_ARTISTS = u'Various Artists' -PromptChoice = namedtuple('ExtraChoice', ['plugin', 'id', 'short', 'long', - 'callback']) +PromptChoice = namedtuple('ExtraChoice', ['short', 'long', 'callback']) # Global logger. log = logging.getLogger('beets') @@ -484,8 +483,16 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, `cur_album`, and `itemcount` must be provided. For singletons, `item` must be provided. - Returns the result of the choice, which may SKIP, ASIS, TRACKS, or - MANUAL or a candidate (an AlbumMatch/TrackMatch object). + `extra_choices` is a list of `PromptChoice`s, containg the choices + appended by the plugins after receiving the `before_choose_candidate` + event. If not empty, the choices are appended to the prompt presented + to the user. + + Returns one of the following: + * the result of the choice, which may be SKIP, ASIS, TRACKS, or MANUAL + * a candidate (an AlbumMatch/TrackMatch object) + * the short letter of a `PromptChoice` (if the user selected one of + the `extra_choices`). """ # Sanity check. if singleton: @@ -496,7 +503,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Build helper variables for extra choices. extra_opts = tuple(c.long for c in extra_choices) - extra_actions = {c.short: c.id for c in extra_choices} + extra_actions = tuple(c.short for c in extra_choices) # Zero candidates. if not candidates: @@ -527,8 +534,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.MANUAL_ID elif sel == 'g': return importer.action.ALBUMS - elif sel in extra_actions.keys(): - return extra_actions[sel] + elif sel in extra_actions: + return sel else: assert False @@ -601,8 +608,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.MANUAL_ID elif sel == 'g': return importer.action.ALBUMS - elif sel in extra_actions.keys(): - return extra_actions[sel] + elif sel in extra_actions: + return sel else: # Numerical selection. match = candidates[sel - 1] if sel != 1: @@ -656,8 +663,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, raise importer.ImportAbort() elif sel == 'i': return importer.action.MANUAL_ID - elif sel in extra_actions.keys(): - return extra_actions[sel] + elif sel in extra_actions: + return sel def manual_search(singleton): @@ -702,8 +709,8 @@ class TerminalImportSession(importer.ImportSession): candidates, rec = task.candidates, task.rec while True: # Gather extra choices from plugins. - extra_choices = self._get_plugin_options(task) - extra_ops = {c.id: c.callback for c in extra_choices} + extra_choices = self._get_plugin_choices(task) + extra_ops = {c.short: c.callback for c in extra_choices} # Ask for a choice from the user. choice = choose_candidate( @@ -732,10 +739,8 @@ class TerminalImportSession(importer.ImportSession): elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) - if post_choice in (importer.action.SKIP, - importer.action.ASIS, - importer.action.TRACKS, - importer.action.ALBUMS): + if isinstance(post_choice, importer.action): + # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice else: # We have a candidate! Finish tagging. Here, choice is an @@ -761,8 +766,12 @@ class TerminalImportSession(importer.ImportSession): return action while True: + extra_choices = self._get_plugin_choices(task) + extra_ops = {c.short: c.callback for c in extra_choices} + # Ask for a choice. - choice = choose_candidate(candidates, True, rec, item=task.item) + choice = choose_candidate(candidates, True, rec, item=task.item, + extra_choices=extra_choices) if choice in (importer.action.SKIP, importer.action.ASIS): return choice @@ -779,6 +788,12 @@ class TerminalImportSession(importer.ImportSession): if search_id: candidates, rec = autotag.tag_item(task.item, search_id=search_id) + elif choice in extra_ops.keys(): + # Allow extra ops to automatically set the post-choice. + post_choice = extra_ops[choice](self, task) + if isinstance(post_choice, importer.action): + # MANUAL and MANUAL_ID have no effect, even if returned. + return post_choice else: # Chose a candidate. assert isinstance(choice, autotag.TrackMatch) @@ -830,8 +845,8 @@ class TerminalImportSession(importer.ImportSession): "was interrupted. Resume (Y/n)?" .format(displayable_path(path))) - def _get_plugin_options(self, task): - """Get the extra options appended to the plugins to the ui prompt. + def _get_plugin_choices(self, task): + """Get the extra choices appended to the plugins to the ui prompt. The `before_choose_candidate` event is sent to the plugins, with session and task as its parameters. Plugins are responsible for @@ -846,19 +861,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(self, importer.action.SKIP, 's', 'Skip', - None), - PromptChoice(self, importer.action.ASIS, 'u', - 'Use as-is', None), - PromptChoice(self, importer.action.TRACKS, 't', - 'as Tracks', None), - PromptChoice(self, importer.action.ALBUMS, 'g', - 'Group albums', None), - PromptChoice(self, importer.action.MANUAL, 'e', - 'Enter search', None), - PromptChoice(self, importer.action.MANUAL_ID, 'i', - 'enter Id', None), - PromptChoice(self, '', 'b', 'aBort', None)] +\ + 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)] +\ extra_choices short_letters = [c.short for c in all_choices] @@ -866,14 +876,14 @@ class TerminalImportSession(importer.ImportSession): # Duplicate short letter has been found. duplicates = [i for i, count in Counter(short_letters).items() if count > 1] - # Build informative message: 'x': classname:"long option",... - dup = {letter: ['%s:"%s"' % (type(c.plugin).__name__, c.long) - for c in all_choices if c.short == letter] - for letter in duplicates} - conflict_msg = '; '.join("'%s': %s" % (k, ', '.join(v)) - for (k, v) in dup.iteritems()) - raise ValueError("Prompt options have the same short letter\n%s" % - conflict_msg) + for short in duplicates: + # Keep the first of the choices, removing the rest. + dup_choices = [c for c in all_choices if c.short == short] + for c in dup_choices[1:]: + log.warn(u"Prompt choice '{0}' removed due to conflict " + u"with '{1}' (short letter: '{2}')", + c.long, dup_choices[0].long, c.short) + extra_choices.remove(c) return extra_choices From b7747013d34825d4c5df3961c445ebd56452bd7e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 16 Dec 2015 19:23:27 +0100 Subject: [PATCH 0280/2280] Prompt event unit tests * Add "before_choose_candidate" unit tests (PromptChoicesTest), containing tests for checking the addition of choices to ui.input_options (album and singletons), conflict resolution, and callback handling (regular and with return value). --- test/test_plugins.py | 158 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 154 insertions(+), 4 deletions(-) diff --git a/test/test_plugins.py b/test/test_plugins.py index 8e6689c6d..95d3c8fb8 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -17,17 +17,18 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import os -from mock import patch, Mock +from mock import patch, Mock, ANY import shutil import itertools from beets.importer import SingletonImportTask, SentinelImportTask, \ - ArchiveImportTask -from beets import plugins, config + ArchiveImportTask, action +from beets import plugins, config, ui from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile -from test.test_importer import ImportHelper +from test.test_importer import ImportHelper, AutotagStub +from test.test_ui_importer import TerminalImportSessionSetup from test._common import unittest, RSRC from test import helper @@ -401,6 +402,155 @@ class ListenersTest(unittest.TestCase, TestHelper): plugins.send('event9', foo=5) +class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper): + def setUp(self): + self.setup_plugin_loader() + self.setup_beets() + self._create_import_dir(3) + self._setup_import_session() + self.matcher = AutotagStub().install() + # keep track of ui.input_option() calls + self.input_options_patcher = patch('beets.ui.input_options', + side_effect=ui.input_options) + self.mock_input_options = self.input_options_patcher.start() + + def tearDown(self): + self.input_options_patcher.stop() + self.teardown_plugin_loader() + self.teardown_beets() + + def test_plugin_choices_in_ui_input_options_album(self): + """Test the presence of plugin choices on the prompt (album).""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', 'Foo', None), + ui.commands.PromptChoice('r', 'baR', None)] + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + 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') + ('Foo', 'baR') + + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def test_plugin_choices_in_ui_input_options_singleton(self): + """Test the presence of plugin choices on the prompt (singleton).""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', 'Foo', None), + ui.commands.PromptChoice('r', 'baR', None)] + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', + u'Enter search', + u'enter Id', u'aBort') + ('Foo', 'baR') + + config['import']['singletons'] = True + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_with(opts, default='a', + require=ANY) + + def test_choices_conflicts(self): + """Test the short letter conflict solving.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('a', 'A foo', None), # dupe + ui.commands.PromptChoice('z', 'baZ', None), # ok + ui.commands.PromptChoice('z', 'Zupe', None), # dupe + ui.commands.PromptChoice('z', 'Zoo', None)] # dupe + + self.register_plugin(DummyPlugin) + # Default options + not dupe extra choices by the plugin ('baZ') + 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') + ('baZ',) + self.importer.add_choice(action.SKIP) + self.importer.run() + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def test_plugin_callback(self): + """Test that plugin callbacks are being called upon user choice.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', 'Foo', self.foo)] + + def foo(self, session, task): + pass + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + 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') + ('Foo',) + + # DummyPlugin.foo() should be called once + with patch.object(DummyPlugin, 'foo', autospec=True) as mock_foo: + with helper.control_stdin('\n'.join(['f', 's'])): + self.importer.run() + self.assertEqual(mock_foo.call_count, 1) + + # input_options should be called twice, as foo() returns None + self.assertEqual(self.mock_input_options.call_count, 2) + self.mock_input_options.assert_called_with(opts, default='a', + require=ANY) + + def test_plugin_callback_return(self): + """Test that plugin callbacks that return a value exit the loop.""" + class DummyPlugin(plugins.BeetsPlugin): + def __init__(self): + super(DummyPlugin, self).__init__() + self.register_listener('before_choose_candidate', + self.return_choices) + + def return_choices(self, session, task): + return [ui.commands.PromptChoice('f', 'Foo', self.foo)] + + def foo(self, session, task): + return action.SKIP + + self.register_plugin(DummyPlugin) + # Default options + extra choices by the plugin ('Foo', 'Bar') + 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') + ('Foo',) + + # DummyPlugin.foo() should be called once + with helper.control_stdin('f\n'): + self.importer.run() + + # input_options should be called once, as foo() returns SKIP + self.mock_input_options.assert_called_once_with(opts, default='a', + require=ANY) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 6f8a1aa40a7d79bf849a77a2cd12b0e54addddb0 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 16 Dec 2015 19:26:39 +0100 Subject: [PATCH 0281/2280] Prompt event documentation and mbsubmit fixes * Fixes for documentation of the prompt event (missing reserved letter, typos). * Update sample mbsubmit plugin to conform to the new PromptChoice structure. --- beetsplug/mbsubmit.py | 6 ++---- docs/dev/plugins.rst | 11 ++++++----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 5e839b626..e86ca1ab7 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -40,10 +40,8 @@ class MBSubmitPlugin(BeetsPlugin): def before_choose_candidate_event(self, session, task): if not task.candidates or task.rec == Recommendation.none: - return [PromptChoice(self, 'PRINT', 'p', 'Print tracks', - self.print_tracks), - PromptChoice(self, 'PRINT_SKIP', 'k', - 'print tracks and sKip', + return [PromptChoice('p', 'Print tracks', self.print_tracks), + PromptChoice('k', 'print tracks and sKip', self.print_tracks_and_skip)] # Callbacks for choices. diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 8fa4871bf..3b3ad80a2 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -547,6 +547,7 @@ a list of ``PromptChoices`` that represent the additional choices that your plugin shall expose to the user:: from beets.plugins import BeetsPlugin + from beets.ui.commands import PromptChoice class ExamplePlugin(BeetsPlugin): def __init__(self): @@ -555,14 +556,14 @@ plugin shall expose to the user:: self.before_choose_candidate_event) def before_choose_candidate_event(self, session, task): - return [PromptChoice(self, 'PRINT_FOO', 'p', 'Print foo', self.foo), - PromptChoice(self, 'DO_BAR', 'd', 'Do bar', self.bar)] + return [PromptChoice('p', 'Print foo', self.foo), + PromptChoice('d', 'Do bar', self.bar)] def foo(self, session, task): print('User has chosen "Print foo"!') def bar(self, session, task): - print('User has chosen "do Bar"!') + print('User has chosen "Do bar"!') The previous example modifies the standard prompt:: @@ -585,11 +586,11 @@ Please make sure that the short letter for each of the choices provided by the plugin is not already in use: the importer will raise an exception if two or more choices try to use the same short letter. As a reference, the following characters are used by the choices on the core importer prompt, and hence -should not be used: ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. +should not be used: ``a``, ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. Additionally, the callback function can optionally specify the next action to be performed by returning one of the values from ``importer.action``, which will be passed to the main loop upon the callback has been processed. Note that ``action.MANUAL`` and ``action.MANUAL_ID`` will have no effect even if -returned by the callback, due to the current arquitecture of the import +returned by the callback, due to the current architecture of the import process. From 06ec01d225cf8cf9bd7ee950f9473f419a0feb9d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 22 Dec 2015 17:04:02 -0800 Subject: [PATCH 0282/2280] Changelog for #1758 --- docs/changelog.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 49f79f555..534a7d100 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -36,9 +36,11 @@ New: For developers: -* :doc:`/dev/plugins`: Two new hooks, ``albuminfo_received`` and +* Two new :ref:`plugin hooks `, ``albuminfo_received`` and ``trackinfo_received``, let plugins intercept metadata as soon as it is received, before it is applied to music in the database. :bug:`872` +* Plugins can now add options to the interactive importer prompts. See + :ref:`append_prompt_choices`. :bug:`1758` Fixes: From b25b4db9e1c4f72ec9fd23b6c946ce098371edea Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Dec 2015 22:40:13 -0800 Subject: [PATCH 0283/2280] replaygain: Dodge possible encoding issues In error reporting. May avoid the error in #1774, but it's hard to find out exactly what the Python types of these arguments are from the GStreamer documentation. --- beetsplug/replaygain.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 422c345d8..bb715f292 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -522,10 +522,9 @@ class GStreamerBackend(Backend): err, debug = message.parse_error() f = self._src.get_property("location") # A GStreamer error, either an unsupported format or a bug. - self._error = \ - ReplayGainError(u"Error {0} - {1} on file {2}".format(err, - debug, - f)) + self._error = ReplayGainError( + "Error {0!r} - {1!r} on file {2!r}".format(err, debug, f) + ) def _on_tag(self, bus, message): tags = message.parse_tag() From c14abe56a5e451cac23eb9a95fdf41b20a76633f Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Mon, 28 Dec 2015 23:16:12 +1030 Subject: [PATCH 0284/2280] fetchart: Add new google backend using google custom search Requires an API key from google similar to lyrics plugin. Limited to 100 queries/day. --- beetsplug/fetchart.py | 50 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a56f9f95a..89e6a04e4 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -96,8 +96,9 @@ class RequestMixin(object): # ART SOURCES ################################################################ class ArtSource(RequestMixin): - def __init__(self, log): + def __init__(self, log, config): self._log = log + self._config = config def get(self, album): raise NotImplementedError() @@ -157,6 +158,43 @@ class AlbumArtOrg(ArtSource): self._log.debug(u'no image found on page') +class GoogleImages(ArtSource): + URL = u'https://www.googleapis.com/customsearch/v1' + + def get(self, album): + """Return art URL from google custom search engine + given an album title and interpreter. + """ + self._log.debug('fetching art from google...') + api_key = self._config['google_api_key'].get() + engine_id = self._config['google_engine_ID'].get() + self._log.debug('API Key: ' + api_key) + self._log.debug('Engine ID: ' + engine_id) + if not api_key: + self._log.debug(u'google api key not set') + return + if not (album.albumartist and album.album): + return + search_string = (album.albumartist + ',' + album.album).encode('utf-8') + response = self.request(self.URL, params={ + 'key': api_key, + 'cx': engine_id, + 'q': search_string, + 'searchType': 'image' + }) + + # Get results using JSON. + data = response.json() + if 'error' in data: + reason = data['error']['errors'][0]['reason'] + self._log.debug(u'google fetchart error: {0}', reason) + return + + if 'items' in data.keys(): + for item in data['items']: + yield item['link'] + + class ITunesStore(ArtSource): # Art from the iTunes Store. def get(self, album): @@ -361,7 +399,7 @@ class FileSystem(ArtSource): # Try each source in turn. SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', - u'wikipedia'] + u'wikipedia', u'google'] ART_SOURCES = { u'coverart': CoverArtArchive, @@ -369,6 +407,7 @@ ART_SOURCES = { u'albumart': AlbumArtOrg, u'amazon': Amazon, u'wikipedia': Wikipedia, + u'google': GoogleImages, } # PLUGIN LOGIC ############################################################### @@ -387,7 +426,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], + 'google_API_key': None, + 'google_engine_ID': u'001442825323518660753:hrh5ch1gjzm', }) + self.config['google_API_key'].redact = True # Holds paths to downloaded images between fetching them and # placing them in the filesystem. @@ -407,8 +449,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'itunes') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.sources = [ART_SOURCES[s](self._log) for s in sources_name] - self.fs_source = FileSystem(self._log) + self.sources = [ART_SOURCES[s](self._log, self.config) for s in sources_name] + self.fs_source = FileSystem(self._log, self.config) # Asynchronous; after music is added to the library. def fetch_art(self, session, task): From ff15f4af9b5e8ac5ad3d17c036e3568d70c942c4 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Mon, 28 Dec 2015 23:42:11 +1030 Subject: [PATCH 0285/2280] fetchart: Use config singleton rather than passing object to each backend --- beetsplug/fetchart.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 89e6a04e4..9d05b55c4 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -96,9 +96,8 @@ class RequestMixin(object): # ART SOURCES ################################################################ class ArtSource(RequestMixin): - def __init__(self, log, config): + def __init__(self, log): self._log = log - self._config = config def get(self, album): raise NotImplementedError() @@ -166,8 +165,8 @@ class GoogleImages(ArtSource): given an album title and interpreter. """ self._log.debug('fetching art from google...') - api_key = self._config['google_api_key'].get() - engine_id = self._config['google_engine_ID'].get() + api_key = config['fetchart']['google_api_key'].get() + engine_id = config['fetchart']['google_engine_ID'].get() self._log.debug('API Key: ' + api_key) self._log.debug('Engine ID: ' + engine_id) if not api_key: @@ -449,8 +448,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'itunes') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.sources = [ART_SOURCES[s](self._log, self.config) for s in sources_name] - self.fs_source = FileSystem(self._log, self.config) + self.sources = [ART_SOURCES[s](self._log) for s in sources_name] + self.fs_source = FileSystem(self._log) # Asynchronous; after music is added to the library. def fetch_art(self, session, task): From b73cfb9f8d6e302dba65343a1923617351118661 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Mon, 28 Dec 2015 23:53:56 +1030 Subject: [PATCH 0286/2280] fetchart: Fix typo in google API config key --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 9d05b55c4..66273a3df 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -165,7 +165,7 @@ class GoogleImages(ArtSource): given an album title and interpreter. """ self._log.debug('fetching art from google...') - api_key = config['fetchart']['google_api_key'].get() + api_key = config['fetchart']['google_API_key'].get() engine_id = config['fetchart']['google_engine_ID'].get() self._log.debug('API Key: ' + api_key) self._log.debug('Engine ID: ' + engine_id) From deadc4d04964d1b1d71fff132a3aafcfe4ff1bfe Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Mon, 28 Dec 2015 23:57:03 +1030 Subject: [PATCH 0287/2280] fetchart: Automatically disable google backend if no API key is set --- beetsplug/fetchart.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 66273a3df..297db5d0d 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -169,9 +169,6 @@ class GoogleImages(ArtSource): engine_id = config['fetchart']['google_engine_ID'].get() self._log.debug('API Key: ' + api_key) self._log.debug('Engine ID: ' + engine_id) - if not api_key: - self._log.debug(u'google api key not set') - return if not (album.albumartist and album.album): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') @@ -446,6 +443,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources = list(SOURCES_ALL) if not HAVE_ITUNES and u'itunes' in available_sources: available_sources.remove(u'itunes') + if not self.config['google_API_key'].get() and \ + u'google' in available_sources: + available_sources.remove(u'google') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) self.sources = [ART_SOURCES[s](self._log) for s in sources_name] From 99fb656f52b128dccd300e1683b97012a879686f Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Mon, 28 Dec 2015 23:57:38 +1030 Subject: [PATCH 0288/2280] fetchart: Remove some debug logging from google backend --- beetsplug/fetchart.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 297db5d0d..7aab88567 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -164,11 +164,8 @@ class GoogleImages(ArtSource): """Return art URL from google custom search engine given an album title and interpreter. """ - self._log.debug('fetching art from google...') api_key = config['fetchart']['google_API_key'].get() engine_id = config['fetchart']['google_engine_ID'].get() - self._log.debug('API Key: ' + api_key) - self._log.debug('Engine ID: ' + engine_id) if not (album.albumartist and album.album): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') From 03a41e82da06e1d4abeec5705dee573a580d2817 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 00:02:41 +1030 Subject: [PATCH 0289/2280] fetchart: minor google backend refactor --- beetsplug/fetchart.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 7aab88567..9d971a3fc 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -164,14 +164,12 @@ class GoogleImages(ArtSource): """Return art URL from google custom search engine given an album title and interpreter. """ - api_key = config['fetchart']['google_API_key'].get() - engine_id = config['fetchart']['google_engine_ID'].get() if not (album.albumartist and album.album): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') response = self.request(self.URL, params={ - 'key': api_key, - 'cx': engine_id, + 'key': config['fetchart']['google_API_key'].get(), + 'cx': config['fetchart']['google_engine_ID'].get(), 'q': search_string, 'searchType': 'image' }) From 2e10b8c284c7577cff7542633d1d5db2dda05e02 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 01:37:53 +1030 Subject: [PATCH 0290/2280] fetchart: Pass config object to backends when initialized --- beetsplug/fetchart.py | 11 ++++++----- test/test_art.py | 8 ++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 9d971a3fc..392db9e47 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -96,8 +96,9 @@ class RequestMixin(object): # ART SOURCES ################################################################ class ArtSource(RequestMixin): - def __init__(self, log): + def __init__(self, log, config): self._log = log + self._config = config def get(self, album): raise NotImplementedError() @@ -168,8 +169,8 @@ class GoogleImages(ArtSource): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') response = self.request(self.URL, params={ - 'key': config['fetchart']['google_API_key'].get(), - 'cx': config['fetchart']['google_engine_ID'].get(), + 'key': self._config['google_API_key'].get(), + 'cx': self._config['google_engine_ID'].get(), 'q': search_string, 'searchType': 'image' }) @@ -443,8 +444,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'google') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.sources = [ART_SOURCES[s](self._log) for s in sources_name] - self.fs_source = FileSystem(self._log) + self.sources = [ART_SOURCES[s](self._log, self.config) for s in sources_name] + self.fs_source = FileSystem(self._log, self.config) # Asynchronous; after music is added to the library. def fetch_art(self, session, task): diff --git a/test/test_art.py b/test/test_art.py index cb29f3769..324c3fbb0 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -65,13 +65,13 @@ class FetchImageTest(UseThePlugin): self.assertNotEqual(artpath, None) -class FSArtTest(_common.TestCase): +class FSArtTest(UseThePlugin): def setUp(self): super(FSArtTest, self).setUp() self.dpath = os.path.join(self.temp_dir, 'arttest') os.mkdir(self.dpath) - self.source = fetchart.FileSystem(logger) + self.source = fetchart.FileSystem(logger, self.plugin.config) def test_finds_jpg_in_directory(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) @@ -190,13 +190,13 @@ class CombinedTest(UseThePlugin): self.assertEqual(len(responses.calls), 0) -class AAOTest(_common.TestCase): +class AAOTest(UseThePlugin): ASIN = 'xxxx' AAO_URL = 'http://www.albumart.org/index_detail.php?asin={0}'.format(ASIN) def setUp(self): super(AAOTest, self).setUp() - self.source = fetchart.AlbumArtOrg(logger) + self.source = fetchart.AlbumArtOrg(logger, self.plugin.config) @responses.activate def run(self, *args, **kwargs): From be64df640911da41678b968eceedd6bc755b8f4a Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 01:48:33 +1030 Subject: [PATCH 0291/2280] fetchart: Handle errors when parsing malformed JSON from google --- beetsplug/fetchart.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 392db9e47..7267f2e49 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -176,7 +176,12 @@ class GoogleImages(ArtSource): }) # Get results using JSON. - data = response.json() + try: + data = response.json() + except ValueError: + self._log.debug(u'google: error loading response: {}'.format(response.text)) + return + if 'error' in data: reason = data['error']['errors'][0]['reason'] self._log.debug(u'google fetchart error: {0}', reason) From f7b05729a3bcaeff2b14858a2338a9f6811226f5 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 01:49:07 +1030 Subject: [PATCH 0292/2280] fetchart: Add tests for google backend --- test/test_art.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index 324c3fbb0..e2ba9b89b 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -226,6 +226,41 @@ class AAOTest(UseThePlugin): self.assertEqual(list(res), []) +class GoogleImageTest(UseThePlugin): + def setUp(self): + super(GoogleImageTest, self).setUp() + self.source = fetchart.GoogleImages(logger, self.plugin.config) + + @responses.activate + def run(self, *args, **kwargs): + super(GoogleImageTest, self).run(*args, **kwargs) + + def mock_response(self, url, json): + responses.add(responses.GET, url, body=json, + content_type='application/json') + + def test_google_art_finds_image(self): + album = _common.Bag(albumartist="some artist", album="some album") + json = b'{"items": [{"link": "url_to_the_image"}]}' + self.mock_response(fetchart.GoogleImages.URL, json) + result_url = self.source.get(album) + self.assertEqual(list(result_url)[0], 'url_to_the_image') + + def test_google_art_returns_no_result_when_error_received(self): + album = _common.Bag(albumartist="some artist", album="some album") + json = b'{"error": {"errors": [{"reason": "some reason"}]}}' + self.mock_response(fetchart.GoogleImages.URL, json) + result_url = self.source.get(album) + self.assertEqual(list(result_url), []) + + def test_google_art_returns_no_result_with_malformed_response(self): + album = _common.Bag(albumartist="some artist", album="some album") + json = b"""bla blup""" + self.mock_response(fetchart.GoogleImages.URL, json) + result_url = self.source.get(album) + self.assertEqual(list(result_url), []) + + class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() From ed9b5ef9cb9a208a678a6c9ec516003ce313b15c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 15:28:27 -0800 Subject: [PATCH 0293/2280] Allow missing fields in %aunique (#1775) --- beets/library.py | 4 ++-- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index f8d226dbe..74b669c03 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1421,7 +1421,7 @@ class DefaultTemplateFunctions(object): # Find matching albums to disambiguate with. subqueries = [] for key in keys: - value = getattr(album, key) + value = album.get(key, '') subqueries.append(dbcore.MatchQuery(key, value)) albums = self.lib.albums(dbcore.AndQuery(subqueries)) @@ -1434,7 +1434,7 @@ class DefaultTemplateFunctions(object): # Find the first disambiguator that distinguishes the albums. for disambiguator in disam: # Get the value for each album for the current field. - disam_values = set([getattr(a, disambiguator) for a in albums]) + disam_values = set([a.get(disambiguator, '') for a in albums]) # If the set of unique values is equal to the number of # albums in the disambiguation set, we're done -- this is diff --git a/docs/changelog.rst b/docs/changelog.rst index 534a7d100..adc70a6bc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -92,6 +92,8 @@ Fixes: did. :bug:`1657` * :doc:`/plugins/scrub`: Also in ``auto`` mode, album art is now correctly restored. :bug:`1657` +* Possibly allow flexible attributes to be used with the ``%aunique`` template + function. :bug:`1775` .. _Emby Server: http://emby.media From 1a2ffd0426d6f8e7bec04bb983d377be3db901f0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:32:28 -0800 Subject: [PATCH 0294/2280] lyrics: Catch errors in Genius backend (fix #1770) The HTTP requests had no error handling. Now they have lots. --- beetsplug/lyrics.py | 50 +++++++++++++++++++++++++++++++++------------ docs/changelog.rst | 2 ++ 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 1af34df99..8d7132524 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -237,25 +237,45 @@ class Genius(Backend): url = u'https://api.genius.com/search?q=%s' \ % (urllib.quote(query.encode('utf8'))) - data = requests.get( - url, - headers=self.headers, - allow_redirects=True - ).content + self._log.debug('genius: requesting search {}', url) + try: + req = requests.get( + url, + headers=self.headers, + allow_redirects=True + ) + req.raise_for_status() + except requests.RequestException as exc: + self._log.debug('genius: request error: {}', exc) + return None - return json.loads(data) + try: + return req.json() + except ValueError: + self._log.debug('genius: invalid response: {}', req.text) + return None def get_lyrics(self, link): url = u'http://genius-api.com/api/lyricsInfo' - data = requests.post( - url, - data={'link': link}, - headers=self.headers, - allow_redirects=True - ).content + self._log.debug('genius: requesting lyrics for link {}', link) + try: + req = requests.post( + url, + data={'link': link}, + headers=self.headers, + allow_redirects=True + ) + req.raise_for_status() + except requests.RequestException as exc: + self._log.debug('genius: request error: {}', exc) + return None - return json.loads(data) + try: + return req.json() + except ValueError: + self._log.debug('genius: invalid response: {}', req.text) + return None def build_lyric_string(self, lyrics): if 'lyrics' not in lyrics: @@ -274,6 +294,8 @@ class Genius(Backend): def fetch(self, artist, title): search_data = self.search_genius(artist, title) + if not search_data: + return if not search_data['meta']['status'] == 200: return @@ -284,6 +306,8 @@ class Genius(Backend): record_url = records[0]['result']['url'] lyric_data = self.get_lyrics(record_url) + if not lyric_data: + return lyrics = self.build_lyric_string(lyric_data) return lyrics diff --git a/docs/changelog.rst b/docs/changelog.rst index adc70a6bc..1eb760615 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -94,6 +94,8 @@ Fixes: restored. :bug:`1657` * Possibly allow flexible attributes to be used with the ``%aunique`` template function. :bug:`1775` +* :doc:`/plugins/lyrics`: The Genius backend is now more robust to + communication errors. :bug:`1770` .. _Emby Server: http://emby.media From a976c371f6fda6626bf98f82abf1f782df64dbaa Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:35:39 -0800 Subject: [PATCH 0295/2280] lyrics: Disable Genius backend by default (#1770) --- beetsplug/lyrics.py | 2 +- docs/changelog.rst | 3 ++- docs/plugins/lyrics.rst | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 8d7132524..528d391ea 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -537,7 +537,7 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch', 'genius'] + SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, diff --git a/docs/changelog.rst b/docs/changelog.rst index 1eb760615..3120d19c8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -95,7 +95,8 @@ Fixes: * Possibly allow flexible attributes to be used with the ``%aunique`` template function. :bug:`1775` * :doc:`/plugins/lyrics`: The Genius backend is now more robust to - communication errors. :bug:`1770` + communication errors. The backend has also been disabled by default, since + the API it depends on is currently down. :bug:`1770` .. _Emby Server: http://emby.media diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 1b3ca0c2f..0d504733f 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -52,9 +52,9 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch genius``, i.e., all - sources. The *google* source will be automatically deactivated if no - ``google_API_key`` is setup. + Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all the + sources except for `genius`. The `google` source will be automatically + deactivated if no ``google_API_key`` is setup. Here's an example of ``config.yaml``:: From f6c6e95235d84512550f8120b145d1a358f5baa6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:44:29 -0800 Subject: [PATCH 0296/2280] Refine changelog for 1.3.16 release --- docs/changelog.rst | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3120d19c8..bb67ca19b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,10 +4,33 @@ Changelog 1.3.16 (in development) ----------------------- -New: +The big news in this release is a new :doc:`interactive editor plugin +`. It's really nifty: you can now change your music's metadata +by making changes in a visual text editor, which can sometimes be far more +efficient than the built-in :ref:`modify-cmd` command. No more carefully +retyping the same artist name with slight capitalization changes. + +This version also adds friendlier formatting (and querying!) of song +durations. + +Big new stuff: * A new :doc:`/plugins/edit` lets you manually edit your music's metadata using your favorite text editor. :bug:`164` :bug:`1706` +* Queries can now use "not" logic. Type a ``^`` before part of a query to + *exclude* matching music from the results. For example, ``beet list -a + beatles ^album:1`` will find all your albums by the Beatles except for their + singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` +* A new :doc:`/plugins/embyupdate` can trigger a library refresh on a `Emby + Server`_ when your beets database changes. +* Track length is now displayed as ``M:SS`` by default, instead of displaying + the raw number of seconds. Queries on track length also accept this format: + for example, ``beet list length:5:30..`` will find all your tracks that have + a duration over 5 minutes and 30 seconds. You can turn off this new behavior + using the ``format_raw_length`` configuration option. :bug:`1749` + +Smaller changes: + * Three commands, ``modify``, ``update``, and ``mbsync``, would previously move files by default after changing their metadata. Now, these commands will only move files if you have the :ref:`config-import-copy` or @@ -20,21 +43,11 @@ New: various-artists albums. The setting defaults to "Various Artists," the MusicBrainz standard. In order to match MusicBrainz, the :doc:`/plugins/discogs` also adopts the same setting. -* :doc:`/plugins/embyupdate`: A plugin to trigger a library refresh on a - `Emby Server`_ if database changed. -* Queries can now use "not" logic. Type a ``^`` before part of a query to - *exclude* matching music from the results. For example, ``beet list -a - beatles ^album:1`` will find all your albums by the Beatles except for their - singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` -* :doc:`/plugins/info`: The plugin now accepts the ``-f/--format`` option for - customizing how items are displayed. :bug:`1737` -* Track length is now displayed as ``M:SS`` by default, instead of displaying - the raw number of seconds. Queries on track length also accept this format: - for example, ``beet list length:5:30..`` will find all your tracks that have - a duration over 5 minutes and 30 seconds. You can turn off this new behavior - using the ``format_raw_length`` configuration option. :bug:`1749` +* :doc:`/plugins/info`: The ``info`` command now accepts a ``-f/--format`` + option for customizing how items are displayed, just like the built-in + ``list`` command. :bug:`1737` -For developers: +Some changes for developers: * Two new :ref:`plugin hooks `, ``albuminfo_received`` and ``trackinfo_received``, let plugins intercept metadata as soon as it is From 0a7f242f488584b4ae949815e0318d75300cbcc0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:53:07 -0800 Subject: [PATCH 0297/2280] More changelog proofreading --- docs/changelog.rst | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index bb67ca19b..9188aa831 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,10 +10,11 @@ by making changes in a visual text editor, which can sometimes be far more efficient than the built-in :ref:`modify-cmd` command. No more carefully retyping the same artist name with slight capitalization changes. -This version also adds friendlier formatting (and querying!) of song -durations. +This version also adds an oft-requested "not" operator to beets' queries, so +you can exclude music from any operation. It also brings friendlier formatting +(and querying!) of song durations. -Big new stuff: +The big new stuff: * A new :doc:`/plugins/edit` lets you manually edit your music's metadata using your favorite text editor. :bug:`164` :bug:`1706` @@ -21,13 +22,13 @@ Big new stuff: *exclude* matching music from the results. For example, ``beet list -a beatles ^album:1`` will find all your albums by the Beatles except for their singles compilation, "1." See :ref:`not_query`. :bug:`819` :bug:`1728` -* A new :doc:`/plugins/embyupdate` can trigger a library refresh on a `Emby - Server`_ when your beets database changes. -* Track length is now displayed as ``M:SS`` by default, instead of displaying - the raw number of seconds. Queries on track length also accept this format: - for example, ``beet list length:5:30..`` will find all your tracks that have - a duration over 5 minutes and 30 seconds. You can turn off this new behavior - using the ``format_raw_length`` configuration option. :bug:`1749` +* A new :doc:`/plugins/embyupdate` can trigger a library refresh on an `Emby`_ + server when your beets database changes. +* Track length is now displayed as "M:SS" rather than a raw number of seconds. + Queries on track length also accept this format: for example, ``beet list + length:5:30..`` will find all your tracks that have a duration over 5 + minutes and 30 seconds. You can turn off this new behavior using the + ``format_raw_length`` configuration option. :bug:`1749` Smaller changes: @@ -65,12 +66,13 @@ Fixes: and name in quick succession. The importer would fail to detect them as duplicates, claiming that there were "empty albums" in the database even when there were not. :bug:`1652` -* :doc:`plugins/lastgenre`: Clean up the reggae related genres somewhat. +* :doc:`plugins/lastgenre`: Clean up the reggae-related genres somewhat. Thanks to :user:`Freso`. :bug:`1661` * The importer now correctly moves album art files when re-importing. :bug:`314` -* :doc:`/plugins/fetchart`: In auto mode, skips albums that already have - art attached to them so as not to interfere with re-imports. :bug:`314` +* :doc:`/plugins/fetchart`: In auto mode, the plugin now skips albums that + already have art attached to them so as not to interfere with re-imports. + :bug:`314` * :doc:`plugins/fetchart`: The plugin now only resizes album art if necessary, rather than always by default. :bug:`1264` * :doc:`plugins/fetchart`: Fix a bug where a database reference to a @@ -101,8 +103,8 @@ Fixes: bands with regular-expression characters in their names, like Sunn O))). :bug:`1673` * :doc:`/plugins/scrub`: In ``auto`` mode, the plugin now *actually* only - scrubs files on import---not every time files were written, as it previously - did. :bug:`1657` + scrubs files on import, as the documentation always claimed it did---not + every time files were written, as it previously did. :bug:`1657` * :doc:`/plugins/scrub`: Also in ``auto`` mode, album art is now correctly restored. :bug:`1657` * Possibly allow flexible attributes to be used with the ``%aunique`` template @@ -111,7 +113,7 @@ Fixes: communication errors. The backend has also been disabled by default, since the API it depends on is currently down. :bug:`1770` -.. _Emby Server: http://emby.media +.. _Emby: http://emby.media 1.3.15 (October 17, 2015) From b93be00dfae7931747e900d405b570f2a08a3f0c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:56:28 -0800 Subject: [PATCH 0298/2280] Date for 1.3.16 release --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 9188aa831..71822e844 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.16 (in development) ------------------------ +1.3.16 (December 28, 2015) +-------------------------- The big news in this release is a new :doc:`interactive editor plugin `. It's really nifty: you can now change your music's metadata From fe8cb952ce0166a5e9b1d553da41ffd708bd8256 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 28 Dec 2015 16:56:54 -0800 Subject: [PATCH 0299/2280] Version bump: 1.3.17 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 0b64ac388..da15a1975 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -20,7 +20,7 @@ import os import beets.library from beets.util import confit -__version__ = '1.3.16' +__version__ = '1.3.17' __author__ = 'Adrian Sampson ' Library = beets.library.Library diff --git a/docs/changelog.rst b/docs/changelog.rst index 71822e844..f950e6149 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.3.17 (in development) +----------------------- + +Changelog goes here! + + 1.3.16 (December 28, 2015) -------------------------- diff --git a/docs/conf.py b/docs/conf.py index d952b410e..a63622079 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = u'beets' copyright = u'2012, Adrian Sampson' version = '1.3' -release = '1.3.16' +release = '1.3.17' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index c7e4af3a0..3b53afd5f 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.16', + version='1.3.17', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 7b273b431005f113d42202cb88277d94569a9307 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 17:29:17 +1030 Subject: [PATCH 0300/2280] fetchart: PEP8 fixes --- beetsplug/fetchart.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 7267f2e49..34690f275 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -179,7 +179,8 @@ class GoogleImages(ArtSource): try: data = response.json() except ValueError: - self._log.debug(u'google: error loading response: {}'.format(response.text)) + self._log.debug(u'google: error loading response: {}' + .format(response.text)) return if 'error' in data: @@ -449,7 +450,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'google') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.sources = [ART_SOURCES[s](self._log, self.config) for s in sources_name] + self.sources = [ART_SOURCES[s](self._log, self.config) + for s in sources_name] self.fs_source = FileSystem(self._log, self.config) # Asynchronous; after music is added to the library. From e771f34dfd177503cc3ec099ea96ef735317d6a1 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Tue, 29 Dec 2015 17:31:40 +1030 Subject: [PATCH 0301/2280] fetchart: Add documentation for new google backend --- docs/plugins/fetchart.rst | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 80149d478..61cd259d0 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -50,12 +50,18 @@ file. The available options are: - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. Default: ``coverart itunes amazon albumart``, i.e., everything but - ``wikipedia``. Enable those two sources for more matches at + ``wikipedia`` and ``google``. Enable those two sources for more matches at the cost of some speed. +- **google_API_key**: Your Google API key (to enable the Google Custom Search + backend). + Default: None. +- **google_engine_ID**: The custom search engine to use. + Default: The `beets custom search engine`_, which searches the entire web. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ or `Pillow`_. +.. _beets custom search engine: https://cse.google.com.au:443/cse/publicurl?cx=001442825323518660753:hrh5ch1gjzm .. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ @@ -137,6 +143,24 @@ Once the library is installed, the plugin will use it to search automatically. .. _python-itunes: https://github.com/ocelma/python-itunes .. _pip: http://pip.openplans.org/ +Google custom search +'''''''''''''''''''' + +To use the google image search backend you need to +`register for a Google API key`_. Set the ``google_API_key`` configuration +option to your key, then add ``google`` to the list of sources in your +configuration. + +.. _register for a Google API key: https://code.google.com/apis/console. + +Optionally, you can `define a custom search engine`_. Get your search engine's +token and use it for your ``google_engine_ID`` configuration option. The +default engine searches the entire web for cover art. + +.. _define a custom search engine: http://www.google.com/cse/all + +Note that the Google custom search API is limited to 100 queries per day. +After that, the fetchart plugin will fall back on other declared data sources. Embedding Album Art ------------------- From 8746869f7c8198b01e9306150abc1fcd47ed1892 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 29 Dec 2015 17:26:42 +0100 Subject: [PATCH 0302/2280] mbsubmit: cleanup, revise logic, config options * Cleanup the "mbsubmit" plugin to remove a choice ("print tracks and skip") and make the logic depend on the strength of the Recommendation. * Add configuration options for the Recommendation threshold that triggers the addition of the "Print tracks" choice and for the formatting string to be used for printing the items. * Include link to the official-ish MusicBrainz format page on the docstring. --- beetsplug/mbsubmit.py | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index e86ca1ab7..546656cee 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -16,8 +16,10 @@ """Aid in submitting information to MusicBrainz. This plugin allows the user to print track information in a format that is -parseable by the MusicBrainz track parser. Programmatic submitting is not +parseable by the MusicBrainz track parser [1]. Programmatic submitting is not implemented by MusicBrainz yet. + +[1] http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings """ from __future__ import (division, absolute_import, print_function, @@ -25,7 +27,6 @@ from __future__ import (division, absolute_import, print_function, from beets.autotag import Recommendation -from beets.importer import action from beets.plugins import BeetsPlugin from beets.ui.commands import PromptChoice from beetsplug.info import print_data @@ -35,21 +36,26 @@ class MBSubmitPlugin(BeetsPlugin): def __init__(self): super(MBSubmitPlugin, self).__init__() + self.config.add({ + 'mb_format': '$track. $title - $artist ($length)', + 'threshold': 'medium', + }) + + # validate and store threshold + self.threshold = self.config['threshold'].as_choice({ + 'none': Recommendation.none, + 'low': Recommendation.low, + 'medium': Recommendation.medium, + 'strong': Recommendation.strong + }) + self.register_listener('before_choose_candidate', self.before_choose_candidate_event) def before_choose_candidate_event(self, session, task): - if not task.candidates or task.rec == Recommendation.none: - return [PromptChoice('p', 'Print tracks', self.print_tracks), - PromptChoice('k', 'print tracks and sKip', - self.print_tracks_and_skip)] + if task.rec <= self.threshold: + return [PromptChoice('p', 'Print tracks', self.print_tracks)] - # Callbacks for choices. def print_tracks(self, session, task): for i in task.items: - print_data(None, i, '$track. $artist - $title ($length)') - - def print_tracks_and_skip(self, session, task): - for i in task.items: - print_data(None, i, '$track. $artist - $title ($length)') - return action.SKIP + print_data(None, i, self.config['mb_format'].get()) From 966746fd553ded4f61f87a97dacaa638d9a81522 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 29 Dec 2015 17:41:49 +0100 Subject: [PATCH 0303/2280] mbsubmit: add basic tests * Add basic unit tests for the mbsubmit plugin, covering the output of the "Print tracks" option on albums and singletons. --- test/test_mbsubmit.py | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 test/test_mbsubmit.py diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py new file mode 100644 index 000000000..37d1a9c80 --- /dev/null +++ b/test/test_mbsubmit.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2015, Adrian Sampson and Diego Moreda. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from test._common import unittest +from test.helper import capture_stdout, control_stdin, TestHelper +from test.test_importer import ImportHelper, AutotagStub +from test.test_ui_importer import TerminalImportSessionSetup + + +class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('mbsubmit') + self._create_import_dir(2) + self._setup_import_session() + self.matcher = AutotagStub().install() + + def tearDown(self): + self.unload_plugins() + self.teardown_beets() + + def test_xxxxprint_tracks_output(self): + """Test the output of the "print tracks" choice.""" + self.matcher.matching = AutotagStub.BAD + + with capture_stdout() as output: + with control_stdin('\n'.join(['p', 's'])): + # Print tracks; Skip + self.importer.run() + + # manually build the string for comparing the output + tracklist = ('Print tracks? ' + '01. Tag Title 1 - Tag Artist (0:01)\n' + '02. Tag Title 2 - Tag Artist (0:01)') + self.assertIn(tracklist, output.getvalue()) + + def test_xxprint_tracks_output_as_tracks(self): + """Test the output of the "print tracks" choice, as singletons.""" + self.matcher.matching = AutotagStub.BAD + + with capture_stdout() as output: + with control_stdin('\n'.join(['t', 's', 'p', 's'])): + # as Tracks; Skip; Print tracks; Skip + self.importer.run() + + # manually build the string for comparing the output + tracklist = ('Print tracks? ' + '02. Tag Title 2 - Tag Artist (0:01)') + self.assertIn(tracklist, output.getvalue()) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') From 0d16f764f2e9fc32f11c02f10d7eddab12fb0919 Mon Sep 17 00:00:00 2001 From: Lachlan Charlick Date: Wed, 30 Dec 2015 13:34:58 +1030 Subject: [PATCH 0304/2280] fetchart: Tidier google backend configuration keys --- beetsplug/fetchart.py | 12 ++++++------ docs/plugins/fetchart.rst | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 34690f275..b1ce11409 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -169,8 +169,8 @@ class GoogleImages(ArtSource): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') response = self.request(self.URL, params={ - 'key': self._config['google_API_key'].get(), - 'cx': self._config['google_engine_ID'].get(), + 'key': self._config['google_key'].get(), + 'cx': self._config['google_engine'].get(), 'q': search_string, 'searchType': 'image' }) @@ -424,10 +424,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], - 'google_API_key': None, - 'google_engine_ID': u'001442825323518660753:hrh5ch1gjzm', + 'google_key': None, + 'google_engine': u'001442825323518660753:hrh5ch1gjzm', }) - self.config['google_API_key'].redact = True + self.config['google_key'].redact = True # Holds paths to downloaded images between fetching them and # placing them in the filesystem. @@ -445,7 +445,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources = list(SOURCES_ALL) if not HAVE_ITUNES and u'itunes' in available_sources: available_sources.remove(u'itunes') - if not self.config['google_API_key'].get() and \ + if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') sources_name = plugins.sanitize_choices( diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 61cd259d0..e53dbc219 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -52,10 +52,10 @@ file. The available options are: Default: ``coverart itunes amazon albumart``, i.e., everything but ``wikipedia`` and ``google``. Enable those two sources for more matches at the cost of some speed. -- **google_API_key**: Your Google API key (to enable the Google Custom Search +- **google_key**: Your Google API key (to enable the Google Custom Search backend). Default: None. -- **google_engine_ID**: The custom search engine to use. +- **google_engine**: The custom search engine to use. Default: The `beets custom search engine`_, which searches the entire web. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ @@ -147,14 +147,14 @@ Google custom search '''''''''''''''''''' To use the google image search backend you need to -`register for a Google API key`_. Set the ``google_API_key`` configuration +`register for a Google API key`_. Set the ``google_key`` configuration option to your key, then add ``google`` to the list of sources in your configuration. .. _register for a Google API key: https://code.google.com/apis/console. Optionally, you can `define a custom search engine`_. Get your search engine's -token and use it for your ``google_engine_ID`` configuration option. The +token and use it for your ``google_engine`` configuration option. The default engine searches the entire web for cover art. .. _define a custom search engine: http://www.google.com/cse/all From d2d31b07a5e8bdd90d444d8037b626863a921245 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 29 Dec 2015 21:49:38 -0800 Subject: [PATCH 0305/2280] Changelog for #1778 --- docs/changelog.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f950e6149..dbcd7e399 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,11 @@ Changelog 1.3.17 (in development) ----------------------- -Changelog goes here! +New: + +* :doc:`/plugins/fetchart`: The Google Images backend has been restored. It + now requires an API key from Google. Thanks to :user:`lcharlick`. + :bug:`1778` 1.3.16 (December 28, 2015) From 12cd5306b77e951aedab49fa7ac6b9c8663acab8 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 30 Dec 2015 15:42:06 +0000 Subject: [PATCH 0306/2280] Update copyright dates to 2016 --- LICENSE | 2 +- beet | 2 +- beets/__init__.py | 2 +- beets/art.py | 2 +- beets/autotag/__init__.py | 2 +- beets/autotag/hooks.py | 2 +- beets/autotag/match.py | 2 +- beets/autotag/mb.py | 2 +- beets/dbcore/__init__.py | 2 +- beets/dbcore/db.py | 2 +- beets/dbcore/query.py | 2 +- beets/dbcore/queryparse.py | 2 +- beets/dbcore/types.py | 2 +- beets/importer.py | 2 +- beets/library.py | 2 +- beets/logging.py | 2 +- beets/mediafile.py | 2 +- beets/plugins.py | 2 +- beets/ui/__init__.py | 2 +- beets/ui/commands.py | 2 +- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 2 +- beets/util/confit.py | 2 +- beets/util/enumeration.py | 2 +- beets/util/functemplate.py | 2 +- beets/util/pipeline.py | 2 +- beets/vfs.py | 2 +- beetsplug/__init__.py | 2 +- beetsplug/badfiles.py | 2 +- beetsplug/bench.py | 2 +- beetsplug/bpd/__init__.py | 2 +- beetsplug/bpd/gstplayer.py | 2 +- beetsplug/bpm.py | 2 +- beetsplug/bucket.py | 2 +- beetsplug/chroma.py | 2 +- beetsplug/convert.py | 2 +- beetsplug/cue.py | 2 +- beetsplug/discogs.py | 2 +- beetsplug/duplicates.py | 2 +- beetsplug/echonest.py | 2 +- beetsplug/edit.py | 2 +- beetsplug/embedart.py | 2 +- beetsplug/fetchart.py | 2 +- beetsplug/filefilter.py | 2 +- beetsplug/freedesktop.py | 2 +- beetsplug/fromfilename.py | 2 +- beetsplug/ftintitle.py | 2 +- beetsplug/fuzzy.py | 2 +- beetsplug/ihate.py | 2 +- beetsplug/importfeeds.py | 2 +- beetsplug/info.py | 2 +- beetsplug/inline.py | 2 +- beetsplug/keyfinder.py | 2 +- beetsplug/lastgenre/__init__.py | 2 +- beetsplug/lastimport.py | 2 +- beetsplug/lyrics.py | 2 +- beetsplug/mbsubmit.py | 2 +- beetsplug/mbsync.py | 2 +- beetsplug/metasync/__init__.py | 2 +- beetsplug/metasync/amarok.py | 2 +- beetsplug/metasync/itunes.py | 2 +- beetsplug/missing.py | 2 +- beetsplug/mpdstats.py | 2 +- beetsplug/mpdupdate.py | 2 +- beetsplug/play.py | 2 +- beetsplug/random.py | 2 +- beetsplug/replaygain.py | 2 +- beetsplug/rewrite.py | 2 +- beetsplug/scrub.py | 2 +- beetsplug/smartplaylist.py | 2 +- beetsplug/the.py | 2 +- beetsplug/thumbnails.py | 2 +- beetsplug/types.py | 2 +- beetsplug/web/__init__.py | 2 +- beetsplug/web/static/jquery.js | 6 +++--- beetsplug/zero.py | 2 +- setup.py | 2 +- test/_common.py | 2 +- test/helper.py | 2 +- test/lyrics_download_samples.py | 2 +- test/test_art.py | 2 +- test/test_autotag.py | 2 +- test/test_bucket.py | 2 +- test/test_convert.py | 2 +- test/test_datequery.py | 2 +- test/test_dbcore.py | 2 +- test/test_echonest.py | 2 +- test/test_edit.py | 2 +- test/test_embedart.py | 2 +- test/test_fetchart.py | 2 +- test/test_filefilter.py | 2 +- test/test_files.py | 2 +- test/test_ftintitle.py | 2 +- test/test_importadded.py | 2 +- test/test_importer.py | 2 +- test/test_info.py | 2 +- test/test_keyfinder.py | 2 +- test/test_lastgenre.py | 2 +- test/test_library.py | 2 +- test/test_lyrics.py | 2 +- test/test_mb.py | 2 +- test/test_mbsync.py | 2 +- test/test_mediafile.py | 2 +- test/test_mediafile_edge.py | 2 +- test/test_metasync.py | 2 +- test/test_mpdstats.py | 2 +- test/test_pipeline.py | 2 +- test/test_player.py | 2 +- test/test_plugins.py | 2 +- test/test_query.py | 2 +- test/test_replaygain.py | 2 +- test/test_smartplaylist.py | 2 +- test/test_sort.py | 2 +- test/test_template.py | 2 +- test/test_thumbnails.py | 2 +- test/test_types_plugin.py | 2 +- test/test_ui.py | 2 +- test/test_ui_commands.py | 2 +- test/test_ui_importer.py | 2 +- test/test_ui_init.py | 2 +- test/test_util.py | 2 +- test/test_vfs.py | 2 +- test/testall.py | 2 +- 123 files changed, 125 insertions(+), 125 deletions(-) diff --git a/LICENSE b/LICENSE index e81766650..b45de0fcf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2010-2015 Adrian Sampson +Copyright (c) 2010-2016 Adrian Sampson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/beet b/beet index 1c49295a1..99dbd8cf5 100755 --- a/beet +++ b/beet @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/__init__.py b/beets/__init__.py index da15a1975..a1fa5c432 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/art.py b/beets/art.py index 9f280ca01..60f9dce88 100644 --- a/beets/art.py +++ b/beets/art.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 9ad02b8eb..924eb85f2 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 6b654573f..303ce3418 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/autotag/match.py b/beets/autotag/match.py index f9146d027..d4bad9e87 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index f823f7211..9403187ef 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/dbcore/__init__.py b/beets/dbcore/__init__.py index 059f1fc4f..78b53c192 100644 --- a/beets/dbcore/__init__.py +++ b/beets/dbcore/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 202cf006f..d784ddcae 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index d8a3a0ea8..f91992712 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 53b6a026e..b421ebf40 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 40183c059..e90fd9d9b 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/importer.py b/beets/importer.py index c26fbcbec..e0d69b968 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/library.py b/beets/library.py index 74b669c03..474279b30 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/logging.py b/beets/logging.py index b1b0ad73c..40748bc68 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/mediafile.py b/beets/mediafile.py index 85f3d2e67..5010f8797 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/plugins.py b/beets/plugins.py index cf4c76036..4233003ea 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index c51c3acb6..adc47d095 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 4f87ad84e..39501f361 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 55c599a05..28845e597 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index a392ee5d2..1b6a5903e 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte +# Copyright 2016, Fabrice Laporte # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/confit.py b/beets/util/confit.py index 7dca300d7..29b906cb6 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of Confit. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/enumeration.py b/beets/util/enumeration.py index c7761be89..9dddf7f64 100644 --- a/beets/util/enumeration.py +++ b/beets/util/enumeration.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index e2854e205..68cb4cd76 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 62772540f..deb431fa1 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beets/vfs.py b/beets/vfs.py index e7b7970d2..d99031c63 100644 --- a/beets/vfs.py +++ b/beets/vfs.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/__init__.py b/beetsplug/__init__.py index 6aba6481a..ea5e7fe40 100644 --- a/beetsplug/__init__.py +++ b/beetsplug/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 7079fb4e8..c6877205c 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, François-Xavier Thomas. +# Copyright 2016, François-Xavier Thomas. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/bench.py b/beetsplug/bench.py index 278704aa0..4d6c6a656 100644 --- a/beetsplug/bench.py +++ b/beetsplug/bench.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 2b1f4a272..7e8694bac 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 80f6622a6..fa22b999d 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index f8074005a..e0fc7f4f8 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, aroquen +# Copyright 2016, aroquen # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index 32c25ed93..7ddc90920 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 028ba5ce1..cb0eaf24a 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/convert.py b/beetsplug/convert.py index a262f216d..6145fdb74 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jakob Schnitzer. +# Copyright 2016, Jakob Schnitzer. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/cue.py b/beetsplug/cue.py index 59e27072e..3e545c9a8 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2015 Bruno Cauet +# Copyright 2016 Bruno Cauet # Split an album-file in tracks thanks a cue file import subprocess diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index e9c912afb..d340fb236 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 83bc492e5..3a04557ca 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Pedro Silva. +# Copyright 2016, Pedro Silva. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index 0075cc835..5e4522ff9 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 8d6b168f5..0aa56b885 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -1,5 +1,5 @@ # This file is part of beets. -# Copyright 2015 +# Copyright 2016 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 632952dd8..b27964874 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b1ce11409..fe32ab9ad 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index b3c26ff79..2481390f6 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Malte Ried. +# Copyright 2016, Malte Ried. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/freedesktop.py b/beetsplug/freedesktop.py index 7660d13fb..33104fa13 100644 --- a/beetsplug/freedesktop.py +++ b/beetsplug/freedesktop.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Matt Lichtenberg. +# Copyright 2016, Matt Lichtenberg. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index bb3363bfe..895cab9e4 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jan-Erik Dahlin +# Copyright 2016, Jan-Erik Dahlin # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 71be9630a..30892f0dc 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Verrus, +# Copyright 2016, Verrus, # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index cf6440438..4e167217f 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Philippe Mongeau. +# Copyright 2016, Philippe Mongeau. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index d795da130..7285c8482 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr . +# Copyright 2016, Blemjhoo Tezoulbr . # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index cdf59c122..c3d677572 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/info.py b/beetsplug/info.py index 5f68336e9..61f0c7971 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/inline.py b/beetsplug/inline.py index 0f7279ecc..5c0c81b80 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index 33bfd4764..fc9c7b148 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 8242d9453..554369ced 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index f0469c91c..ba1fd7de8 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Rafael Bodill http://github.com/rafi +# Copyright 2016, Rafael Bodill http://github.com/rafi # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 528d391ea..9e5e2fad6 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index e86ca1ab7..9f423e5af 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson and Diego Moreda. +# Copyright 2016, Adrian Sampson and Diego Moreda. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 99456da2c..00eb966fa 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Jakob Schnitzer. +# Copyright 2016, Jakob Schnitzer. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 7ddbb3091..219d73474 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Heinz Wiesinger. +# Copyright 2016, Heinz Wiesinger. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index a591cf923..78241dc1b 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Heinz Wiesinger. +# Copyright 2016, Heinz Wiesinger. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index 75a612c28..ead77cd39 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Tom Jaspers. +# Copyright 2016, Tom Jaspers. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 648b202ba..05e66b7a8 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Pedro Silva. +# Copyright 2016, Pedro Silva. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index dcf43ec62..326afe4da 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Peter Schnebel and Johann Klähn. +# Copyright 2016, Peter Schnebel and Johann Klähn. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 8b072ecf3..5e4e999aa 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/play.py b/beetsplug/play.py index a33074312..1d425e1c8 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, David Hamp-Gonsalves +# Copyright 2016, David Hamp-Gonsalves # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/random.py b/beetsplug/random.py index 7f3317b81..22ae23252 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Philippe Mongeau. +# Copyright 2016, Philippe Mongeau. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index bb715f292..db4d202a6 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte, Yevgeny Bezman, and Adrian Sampson. +# Copyright 2016, Fabrice Laporte, Yevgeny Bezman, and Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index b08fb1fb6..2327bc780 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 4e37ad7ff..34e6428ad 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index f404d98d1..cc988b22c 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Dang Mai . +# Copyright 2016, Dang Mai . # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/the.py b/beetsplug/the.py index d13eb1aca..b6ffc945f 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr . +# Copyright 2016, Blemjhoo Tezoulbr . # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index fef512dc8..ca2a942a9 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet +# Copyright 2016, Bruno Cauet # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/types.py b/beetsplug/types.py index a203834d5..4c5d20a45 100644 --- a/beetsplug/types.py +++ b/beetsplug/types.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index a6e6f55c9..377915626 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/beetsplug/web/static/jquery.js b/beetsplug/web/static/jquery.js index 5b43a3ece..e14142126 100644 --- a/beetsplug/web/static/jquery.js +++ b/beetsplug/web/static/jquery.js @@ -2,13 +2,13 @@ * jQuery JavaScript Library v1.7.1 * http://jquery.com/ * - * Copyright 2015, John Resig + * Copyright 2016, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ - * Copyright 2015, The Dojo Foundation + * Copyright 2016, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Mon Nov 21 21:11:03 2011 -0500 @@ -3851,7 +3851,7 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl /*! * Sizzle CSS Selector Engine - * Copyright 2015, The Dojo Foundation + * Copyright 2016, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 8e81473db..b427bbe8a 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Blemjhoo Tezoulbr . +# Copyright 2016, Blemjhoo Tezoulbr . # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/setup.py b/setup.py index 3b53afd5f..d6c1fb5f7 100755 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/_common.py b/test/_common.py index 9e6ec0f85..21c73858e 100644 --- a/test/_common.py +++ b/test/_common.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/helper.py b/test/helper.py index 0c9e2befa..e2bc42351 100644 --- a/test/helper.py +++ b/test/helper.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index c340b3f05..3a32577f9 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte +# Copyright 2016, Fabrice Laporte # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_art.py b/test/test_art.py index e2ba9b89b..e19c7d211 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_autotag.py b/test/test_autotag.py index 46059d461..2aecfb559 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_bucket.py b/test/test_bucket.py index 05b2a2a1f..81a5d4441 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_convert.py b/test/test_convert.py index 7cd565b3a..ab1fa2504 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_datequery.py b/test/test_datequery.py index ba23b910d..9ad741ee0 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 4e1f2dd37..a69ffedbe 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_echonest.py b/test/test_echonest.py index 143d2633d..cf460e19c 100644 --- a/test/test_echonest.py +++ b/test/test_echonest.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes +# Copyright 2016, Thomas Scholtes # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_edit.py b/test/test_edit.py index ae0500029..727de6d20 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -1,5 +1,5 @@ # This file is part of beets. -# Copyright 2015, Adrian Sampson and Diego Moreda. +# Copyright 2016, Adrian Sampson and Diego Moreda. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_embedart.py b/test/test_embedart.py index 3cd67b54e..8a21f55bc 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_fetchart.py b/test/test_fetchart.py index 0c8911c55..f0dda4fce 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_filefilter.py b/test/test_filefilter.py index 1b1d326f1..aec96977e 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Malte Ried. +# Copyright 2016, Malte Ried. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_files.py b/test/test_files.py index e78c50511..60bc8024a 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index 663cf2b68..c02424dbe 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_importadded.py b/test/test_importadded.py index 7ca61318e..b8801da60 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Stig Inge Lea Bjornsen. +# Copyright 2016, Stig Inge Lea Bjornsen. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_importer.py b/test/test_importer.py index dd093377d..b9f75f7ef 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_info.py b/test/test_info.py index 4a85b6dc9..fdf0b3861 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 8a3bfe4e3..898bc566e 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index d61738fc5..9f61107e9 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_library.py b/test/test_library.py index 9aeaad719..5fdb1f2ec 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 515e96587..d1f1f05a7 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Fabrice Laporte. +# Copyright 2016, Fabrice Laporte. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_mb.py b/test/test_mb.py index d68be7e4d..dae1003c9 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_mbsync.py b/test/test_mbsync.py index 47517f4ee..1cfdf96a1 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 784703f2c..ed5680982 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 480fa2b59..298cb6dc1 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_metasync.py b/test/test_metasync.py index e37ef3364..6404ea1d8 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Tom Jaspers. +# Copyright 2016, Tom Jaspers. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index b07da5e32..9d7d16881 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015 +# Copyright 2016 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 8c9191293..705a7eb73 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_player.py b/test/test_player.py index 6afa0ba21..4f2f6653a 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_plugins.py b/test/test_plugins.py index 95d3c8fb8..6f8035511 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_query.py b/test/test_query.py index 8b3ad9821..deb9f090f 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_replaygain.py b/test/test_replaygain.py index e85c4504b..2cb0446fd 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes +# Copyright 2016, Thomas Scholtes # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 4d9826539..c5ac4fb5b 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet. +# Copyright 2016, Bruno Cauet. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_sort.py b/test/test_sort.py index 9413e7d7b..dc4e6d2b2 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_template.py b/test/test_template.py index 318c2d5b5..96100bdfe 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 2468e30b5..60297c68e 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Bruno Cauet +# Copyright 2016, Bruno Cauet # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 57bfb2282..ba3fa54e1 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Thomas Scholtes. +# Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_ui.py b/test/test_ui.py index 78e4f5891..60cc122df 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index c8995aedf..ed7620725 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index e8e43a6f7..4f0de1c92 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 667b0a56d..d692868be 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_util.py b/test/test_util.py index db68ed885..6d4707273 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/test_vfs.py b/test/test_vfs.py index e1569b2c3..e11e04780 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/test/testall.py b/test/testall.py index 3e6255f6d..fa556e364 100755 --- a/test/testall.py +++ b/test/testall.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson. +# Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the From 798dd72bb6ae4e6b529901594de0a53a5ea55294 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 30 Dec 2015 20:19:03 +0100 Subject: [PATCH 0307/2280] mbsubmit: style fixes --- beetsplug/mbsubmit.py | 2 +- test/test_mbsubmit.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 546656cee..4306cc798 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -41,7 +41,7 @@ class MBSubmitPlugin(BeetsPlugin): 'threshold': 'medium', }) - # validate and store threshold + # Validate and store threshold. self.threshold = self.config['threshold'].as_choice({ 'none': Recommendation.none, 'low': Recommendation.low, diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index 37d1a9c80..7256a6296 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -35,7 +35,7 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, self.unload_plugins() self.teardown_beets() - def test_xxxxprint_tracks_output(self): + def test_print_tracks_output(self): """Test the output of the "print tracks" choice.""" self.matcher.matching = AutotagStub.BAD @@ -44,13 +44,13 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, # Print tracks; Skip self.importer.run() - # manually build the string for comparing the output + # Manually build the string for comparing the output. tracklist = ('Print tracks? ' '01. Tag Title 1 - Tag Artist (0:01)\n' '02. Tag Title 2 - Tag Artist (0:01)') self.assertIn(tracklist, output.getvalue()) - def test_xxprint_tracks_output_as_tracks(self): + def test_print_tracks_output_as_tracks(self): """Test the output of the "print tracks" choice, as singletons.""" self.matcher.matching = AutotagStub.BAD @@ -59,7 +59,7 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, # as Tracks; Skip; Print tracks; Skip self.importer.run() - # manually build the string for comparing the output + # Manually build the string for comparing the output. tracklist = ('Print tracks? ' '02. Tag Title 2 - Tag Artist (0:01)') self.assertIn(tracklist, output.getvalue()) From 85ad17d43103e912e65cacd15e27e48adbfff3bc Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 30 Dec 2015 20:29:58 +0100 Subject: [PATCH 0308/2280] mbsubmit: add documentation, changelog --- docs/changelog.rst | 3 +++ docs/plugins/index.rst | 2 ++ docs/plugins/mbsubmit.rst | 54 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 docs/plugins/mbsubmit.rst diff --git a/docs/changelog.rst b/docs/changelog.rst index dbcd7e399..b69288170 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,9 @@ New: * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It now requires an API key from Google. Thanks to :user:`lcharlick`. :bug:`1778` +* A new :doc:`/plugins/mbsubmit` lets you print the tracks of an album in a + format parseable by MusicBrainz track parser during an interactive import + session. :bug:`1779` 1.3.16 (December 28, 2015) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 5da5ee0be..d1cc41015 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -59,6 +59,7 @@ Each plugin has its own set of options that can be defined in a section bearing lastimport lyrics mbcollection + mbsubmit mbsync metasync missing @@ -162,6 +163,7 @@ Miscellaneous * :doc:`ihate`: Automatically skip albums and tracks during the import process. * :doc:`info`: Print music files' tags to the console. * :doc:`mbcollection`: Maintain your MusicBrainz collection list. +* :doc:`mbsubmit`: Print an album's tracks in a MusicBrainz-friendly format. * :doc:`missing`: List missing tracks. * :doc:`random`: Randomly choose albums and tracks from your library. * :doc:`filefilter`: Automatically skip files during the import process based diff --git a/docs/plugins/mbsubmit.rst b/docs/plugins/mbsubmit.rst new file mode 100644 index 000000000..9312eb785 --- /dev/null +++ b/docs/plugins/mbsubmit.rst @@ -0,0 +1,54 @@ +MusicBrainz Submit Plugin +========================= + +The ``mbsubmit`` plugin provides an extra prompt choice during an import +session that prints the tracks of the current album in a format that is +parseable by MusicBrainz's `track parser`_. + +.. _track parser: http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings + +Usage +----- + +Enable the ``mbsubmit`` plugin in your configuration (see :ref:`using-plugins`) +and select the ``Print tracks`` choice which is by default displayed when no +strong recommendations are found for the album:: + + No matching release found for 3 tracks. + For help, see: http://beets.readthedocs.org/en/latest/faq.html#nomatch + [U]se as-is, as Tracks, Group albums, Skip, Enter search, enter Id, aBort, + Print tracks? p + 01. An Obscure Track - An Obscure Artist (3:37) + 02. Another Obscure Track - An Obscure Artist (2:05) + 03. The Third Track - Another Obscure Artist (3:02) + + No matching release found for 3 tracks. + For help, see: http://beets.readthedocs.org/en/latest/faq.html#nomatch + [U]se as-is, as Tracks, Group albums, Skip, Enter search, enter Id, aBort, + Print tracks? + +As MusicBrainz currently does not support submitting albums programmatically, +the recommended workflow is to copy the output of the ``Print tracks`` choice +and paste it into the parser that can be found by clicking on the +"`Track Parser`" button on MusicBrainz "`Tracklist`" tab. + +Configuration +------------- + +To configure the plugin, make a ``mbsubmit:`` section in your configuration +file. The following options are available: + +- **mb_format**: The format used for printing the tracks, defined using the + same template syntax as beets’ :doc:`path formats `. + Default: ``$track. $title - $artist ($length)``. +- **threshold**: The minimum strength of the autotagger recommendation that + will cause the ``Print tracks`` choice to be displayed on the prompt. + Default: ``medium`` (causing the choice to be displayed for all albums that + have a recommendation of medium strength or lower). Valid values: ``none``, + ``low``, ``medium``, ``strong``. + +Please note that some values of the ``threshold`` configuration option might +require other ``beets`` command line switches to be enabled in order to work as +intended. In particular, setting a threshold of ``strong`` will only display +the prompt if ``timid`` mode is enabled. You can find more information about +how the recommendation system works on :ref:`match-config`. From 53ecec11e02131e42ce655a9da0c148d862ce960 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 30 Dec 2015 20:32:14 +0100 Subject: [PATCH 0309/2280] mbsubmit: bump copyright year --- test/test_mbsubmit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index 7256a6296..5047fd3d0 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2015, Adrian Sampson and Diego Moreda. +# Copyright 2016, Adrian Sampson and Diego Moreda. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the From ff81bbf8f5b7ce008ea49dd2c979ad7ba5be8f50 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Wed, 30 Dec 2015 22:03:50 -0600 Subject: [PATCH 0310/2280] ABrainz: Added first pass of plugin. Only prints MBID and response status code to console. --- beetsplug/acoustic.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 beetsplug/acoustic.py diff --git a/beetsplug/acoustic.py b/beetsplug/acoustic.py new file mode 100644 index 000000000..4eb7ea2de --- /dev/null +++ b/beetsplug/acoustic.py @@ -0,0 +1,38 @@ +from __future__ import (division, absolute_import, print_function, + unicode_literals) + + +from beets import plugins, ui +import requests + +ACOUSTIC_URL = "http://acousticbrainz.org/" +LEVEL = "/high-level" +PLUGIN_DESCRIPTION = "Fetch metadata from AcousticBrainz" + + +class AcousticPlugin(plugins.BeetsPlugin): + def __init__(self): + super(AcousticPlugin, self).__init__() + + def commands(self): + cmd = ui.Subcommand('acoustic', help=PLUGIN_DESCRIPTION) + + def func(lib, opts, args): + fetch_info(lib) + + cmd.func = func + return [cmd] + + +# Currently outputs MBID and corresponding request status code +def fetch_info(lib): + for item in lib.items(): + if item.mb_trackid: + r = requests.get(generate_url(item.mb_trackid)) + print(item.mb_trackid) + print(r.status_code) + + +# Generates url of AcousticBrainz end point for given MBID +def generate_url(mbid): + return ACOUSTIC_URL + mbid + LEVEL From c0dde8da2848eb1fd884a2edb54eb67c0334b928 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 30 Dec 2015 20:23:29 -0800 Subject: [PATCH 0311/2280] echonest: Fix capitalization in help text --- beetsplug/echonest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index 5e4522ff9..182c7f9a2 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -465,7 +465,7 @@ class EchonestMetadataPlugin(plugins.BeetsPlugin): def commands(self): fetch_cmd = ui.Subcommand('echonest', - help='Fetch metadata from the EchoNest') + help='fetch metadata from The Echo Nest') fetch_cmd.parser.add_option( '-f', '--force', dest='force', action='store_true', default=False, help='(re-)download information from the EchoNest' From 29e6cbedfe4fa3eb31ca033ef776c98eafa605c6 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Wed, 30 Dec 2015 22:27:53 -0600 Subject: [PATCH 0312/2280] ABrainz: Added copyright header, docstrings, and followed long line standards. --- beetsplug/acoustic.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/beetsplug/acoustic.py b/beetsplug/acoustic.py index 4eb7ea2de..99eb024a8 100644 --- a/beetsplug/acoustic.py +++ b/beetsplug/acoustic.py @@ -1,3 +1,20 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +""" Fetch various AcousticBrainz metadata using MBID +""" from __future__ import (division, absolute_import, print_function, unicode_literals) @@ -7,7 +24,6 @@ import requests ACOUSTIC_URL = "http://acousticbrainz.org/" LEVEL = "/high-level" -PLUGIN_DESCRIPTION = "Fetch metadata from AcousticBrainz" class AcousticPlugin(plugins.BeetsPlugin): @@ -15,7 +31,8 @@ class AcousticPlugin(plugins.BeetsPlugin): super(AcousticPlugin, self).__init__() def commands(self): - cmd = ui.Subcommand('acoustic', help=PLUGIN_DESCRIPTION) + cmd = ui.Subcommand('acoustic', + help="fetch metadata from AcousticBrainz") def func(lib, opts, args): fetch_info(lib) @@ -24,8 +41,9 @@ class AcousticPlugin(plugins.BeetsPlugin): return [cmd] -# Currently outputs MBID and corresponding request status code def fetch_info(lib): + """Currently outputs MBID and corresponding request status code + """ for item in lib.items(): if item.mb_trackid: r = requests.get(generate_url(item.mb_trackid)) @@ -33,6 +51,7 @@ def fetch_info(lib): print(r.status_code) -# Generates url of AcousticBrainz end point for given MBID def generate_url(mbid): + """Generates url of AcousticBrainz end point for given MBID + """ return ACOUSTIC_URL + mbid + LEVEL From 5369a60a2adadce59d0ead54eaab76c84e55b168 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 30 Dec 2015 21:21:30 -0800 Subject: [PATCH 0313/2280] More details on log levels (fix #1781) --- docs/dev/plugins.rst | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 3b3ad80a2..b7c5d82f9 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -517,16 +517,18 @@ str.format-style string formatting. So you can write logging calls like this:: When beets is in verbose mode, plugin messages are prefixed with the plugin name to make them easier to see. -What messages will be logged depends on the logging level and the action +Which messages will be logged depends on the logging level and the action performed: -* On import stages and event handlers, the default is ``WARNING`` messages and - above. -* On direct actions, the default is ``INFO`` or above, as with the rest of - beets. +* Inside import stages and event handlers, the default is ``WARNING`` messages + and above. +* Everywhere else, the default is ``INFO`` or above. -The verbosity can be increased with ``--verbose`` flags: each flags lowers the -level by a notch. +The verbosity can be increased with ``--verbose`` (``-v``) flags: each flags +lowers the level by a notch. That means that, with a single ``-v`` flag, event +handlers won't have their ``DEBUG`` messages displayed, but command functions +(for example) will. With ``-vv`` on the command line, ``DEBUG`` messages will +be displayed everywhere. This addresses a common pattern where plugins need to use the same code for a command and an import stage, but the command needs to print more messages than From 247e35161ea134dbd86ba57962acf66012eb4a86 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 30 Dec 2015 21:23:07 -0800 Subject: [PATCH 0314/2280] CLI help: say that -v can appear twice (#1781) --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index adc47d095..eaf79a0ce 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1172,7 +1172,7 @@ def _raw_main(args, lib=None): parser.add_option('-d', '--directory', dest='directory', help="destination music directory") parser.add_option('-v', '--verbose', dest='verbose', action='count', - help='print debugging information') + help='log more details (use twice for even more)') parser.add_option('-c', '--config', dest='config', help='path to configuration file') parser.add_option('-h', '--help', dest='help', action='store_true', From 9daa02b5b0b9726dec5b85c51e639646b256b1d3 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Wed, 30 Dec 2015 23:34:56 -0600 Subject: [PATCH 0315/2280] ABrainz: Added write for three attributes to metadata and easier dictionary traversal format. --- beetsplug/acoustic.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/beetsplug/acoustic.py b/beetsplug/acoustic.py index 99eb024a8..62ea8aa6f 100644 --- a/beetsplug/acoustic.py +++ b/beetsplug/acoustic.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2016, Adrian Sampson. +# Copyright 2016, Ohm Patel. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -18,9 +18,9 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) +import requests from beets import plugins, ui -import requests ACOUSTIC_URL = "http://acousticbrainz.org/" LEVEL = "/high-level" @@ -46,12 +46,32 @@ def fetch_info(lib): """ for item in lib.items(): if item.mb_trackid: - r = requests.get(generate_url(item.mb_trackid)) - print(item.mb_trackid) - print(r.status_code) + rs = requests.get(generate_url(item.mb_trackid)).json() + + item.abrainz_danceable = get_value(rs, ["highlevel", + "danceability", + "all", + "danceable"]) + item.abrainz_happy = get_value(rs, ["highlevel", + "mood_happy", + "all", + "happy"]) + item.abrainz_party = get_value(rs, ["highlevel", + "mood_party", + "all", + "party"]) + + item.write() + item.store() def generate_url(mbid): """Generates url of AcousticBrainz end point for given MBID """ return ACOUSTIC_URL + mbid + LEVEL + + +def get_value(data, map_path): + """Allows traversal of dictionary with cleaner formatting + """ + return reduce(lambda d, k: d[k], map_path, data) From 59a1333732c12cf32cf2408103cd98f579c9f7e7 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Wed, 30 Dec 2015 23:38:19 -0600 Subject: [PATCH 0316/2280] ABrainz: Renamed danceable to dance to match five character attribute --- beetsplug/acoustic.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/acoustic.py b/beetsplug/acoustic.py index 62ea8aa6f..eab5d2c72 100644 --- a/beetsplug/acoustic.py +++ b/beetsplug/acoustic.py @@ -48,10 +48,10 @@ def fetch_info(lib): if item.mb_trackid: rs = requests.get(generate_url(item.mb_trackid)).json() - item.abrainz_danceable = get_value(rs, ["highlevel", - "danceability", - "all", - "danceable"]) + item.abrainz_dance = get_value(rs, ["highlevel", + "danceability", + "all", + "danceable"]) item.abrainz_happy = get_value(rs, ["highlevel", "mood_happy", "all", From ed6d9087a9ac60224ac0029cb5cce8a965dc2ba8 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 00:50:49 -0600 Subject: [PATCH 0317/2280] ABrainz: Added error catching and renamed to abrainz --- beetsplug/{acoustic.py => abrainz.py} | 44 ++++++++++++++++----------- 1 file changed, 26 insertions(+), 18 deletions(-) rename beetsplug/{acoustic.py => abrainz.py} (54%) diff --git a/beetsplug/acoustic.py b/beetsplug/abrainz.py similarity index 54% rename from beetsplug/acoustic.py rename to beetsplug/abrainz.py index eab5d2c72..4ebc3d0d6 100644 --- a/beetsplug/acoustic.py +++ b/beetsplug/abrainz.py @@ -31,35 +31,40 @@ class AcousticPlugin(plugins.BeetsPlugin): super(AcousticPlugin, self).__init__() def commands(self): - cmd = ui.Subcommand('acoustic', + cmd = ui.Subcommand('abrainz', help="fetch metadata from AcousticBrainz") def func(lib, opts, args): - fetch_info(lib) + fetch_info(self, lib) cmd.func = func return [cmd] -def fetch_info(lib): +def fetch_info(self, lib): """Currently outputs MBID and corresponding request status code """ for item in lib.items(): if item.mb_trackid: - rs = requests.get(generate_url(item.mb_trackid)).json() + rs = requests.get(generate_url(item.mb_trackid)) - item.abrainz_dance = get_value(rs, ["highlevel", - "danceability", - "all", - "danceable"]) - item.abrainz_happy = get_value(rs, ["highlevel", - "mood_happy", - "all", - "happy"]) - item.abrainz_party = get_value(rs, ["highlevel", - "mood_party", - "all", - "party"]) + try: + rs.json() + except ValueError: + self._log.debug('abrainz: Invalid Response: {}', rs.text) + + item.danceable = get_value(self._log, rs.json(), ["highlevel", + "danceability", + "all", + "danceable"]) + item.mood_happy = get_value(self._log, rs.json(), ["highlevel", + "mood_happy", + "all", + "happy"]) + item.mood_party = get_value(self._log, rs.json(), ["highlevel", + "mood_party", + "all", + "party"]) item.write() item.store() @@ -71,7 +76,10 @@ def generate_url(mbid): return ACOUSTIC_URL + mbid + LEVEL -def get_value(data, map_path): +def get_value(log, data, map_path): """Allows traversal of dictionary with cleaner formatting """ - return reduce(lambda d, k: d[k], map_path, data) + try: + return reduce(lambda d, k: d[k], map_path, data) + except KeyError: + log.debug('Invalid Path: {}', map_path) From d15d7efbf4eda44b421e6f3a11e5cc86eb1b9acd Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 00:53:05 -0600 Subject: [PATCH 0318/2280] ABrainz: Removed repeated portion of error message --- beetsplug/abrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/abrainz.py b/beetsplug/abrainz.py index 4ebc3d0d6..615b2a2b8 100644 --- a/beetsplug/abrainz.py +++ b/beetsplug/abrainz.py @@ -51,7 +51,7 @@ def fetch_info(self, lib): try: rs.json() except ValueError: - self._log.debug('abrainz: Invalid Response: {}', rs.text) + self._log.debug('Invalid Response: {}', rs.text) item.danceable = get_value(self._log, rs.json(), ["highlevel", "danceability", From bcd4c6d556d6686af6d570afe9cb492df1e5e0a8 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 01:12:52 -0600 Subject: [PATCH 0319/2280] ABrainz: Added initial documentation --- docs/plugins/abrainz.rst | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 docs/plugins/abrainz.rst diff --git a/docs/plugins/abrainz.rst b/docs/plugins/abrainz.rst new file mode 100644 index 000000000..c53a1921b --- /dev/null +++ b/docs/plugins/abrainz.rst @@ -0,0 +1,16 @@ +ABrainz Plugin +=========== + +The ``abrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as +* ```danceable``` + + Predicts how easy the track is danceable to +* ```mood_happy``` + + Predicts the probability this track is played to invoke happiness +* ```mood_party``` + + Predicts the probability this track is played in a party environment + +Enable the ``abrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: + + $ beet abrainz + +Additional command-line options coming soon. \ No newline at end of file From 61830958e692ec9a7e0b4786a2cc3ca98d250f05 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 01:14:30 -0600 Subject: [PATCH 0320/2280] ABrainz: Fix slight bugs on Doc page --- docs/plugins/abrainz.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/plugins/abrainz.rst b/docs/plugins/abrainz.rst index c53a1921b..3739f9d24 100644 --- a/docs/plugins/abrainz.rst +++ b/docs/plugins/abrainz.rst @@ -2,11 +2,12 @@ ABrainz Plugin =========== The ``abrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as -* ```danceable``` + +* ``danceable`` + Predicts how easy the track is danceable to -* ```mood_happy``` +* ``mood_happy`` + Predicts the probability this track is played to invoke happiness -* ```mood_party``` +* ``mood_party`` + Predicts the probability this track is played in a party environment Enable the ``abrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: From fdd1534cf35dd803de72660a4e569113c7a227a2 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 01:19:28 -0600 Subject: [PATCH 0321/2280] ABrainz: Doc title underline too short --- docs/plugins/abrainz.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/abrainz.rst b/docs/plugins/abrainz.rst index 3739f9d24..471d31fcb 100644 --- a/docs/plugins/abrainz.rst +++ b/docs/plugins/abrainz.rst @@ -1,5 +1,5 @@ ABrainz Plugin -=========== +============== The ``abrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as From ff89716a4d6eb3fb0bc1a72c71fd097b09198273 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 01:23:44 -0600 Subject: [PATCH 0322/2280] ABrainz: Add abrainz doc to toctree --- docs/plugins/index.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 5da5ee0be..4b10275e8 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -31,6 +31,7 @@ Each plugin has its own set of options that can be defined in a section bearing .. toctree:: :hidden: + abrainz badfiles bpd bpm @@ -94,6 +95,7 @@ Autotagger Extensions Metadata -------- +* :doc:`abrainz`: Fetch various AcousticBrainz metadata * :doc:`bpm`: Measure tempo using keystrokes. * :doc:`echonest`: Automatically fetch `acoustic attributes`_ from `the Echo Nest`_ (tempo, energy, danceability, ...). From f685a59e716eb6b888b418ad61c1df59af7b2e2c Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Thu, 31 Dec 2015 13:40:48 +0100 Subject: [PATCH 0323/2280] play: remove dead code This piece of code won't ever execute because interactive open terminates python execution --- beetsplug/play.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 1d425e1c8..e366919fb 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -131,11 +131,6 @@ class PlayPlugin(BeetsPlugin): except OSError as exc: raise ui.UserError("Could not play the music playlist: " "{0}".format(exc)) - finally: - if not raw: - self._log.debug('Removing temporary playlist: {}', - open_args[0]) - util.remove(open_args[0]) def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. From 5201e1cde742935170040815d6cbda6237d03b4d Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 08:56:55 -0600 Subject: [PATCH 0324/2280] Rename --- beetsplug/{abrainz.py => acousticbrainz.py} | 0 docs/plugins/{abrainz.rst => acousticbrainz.rst} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename beetsplug/{abrainz.py => acousticbrainz.py} (100%) rename docs/plugins/{abrainz.rst => acousticbrainz.rst} (100%) diff --git a/beetsplug/abrainz.py b/beetsplug/acousticbrainz.py similarity index 100% rename from beetsplug/abrainz.py rename to beetsplug/acousticbrainz.py diff --git a/docs/plugins/abrainz.rst b/docs/plugins/acousticbrainz.rst similarity index 100% rename from docs/plugins/abrainz.rst rename to docs/plugins/acousticbrainz.rst From 6337b7ff084fdaf186b5eabc3cffa554b09a74d0 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 08:57:19 -0600 Subject: [PATCH 0325/2280] Rename commands and files --- beetsplug/acousticbrainz.py | 2 +- docs/plugins/acousticbrainz.rst | 8 ++++---- docs/plugins/index.rst | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 615b2a2b8..bb33e0515 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -31,7 +31,7 @@ class AcousticPlugin(plugins.BeetsPlugin): super(AcousticPlugin, self).__init__() def commands(self): - cmd = ui.Subcommand('abrainz', + cmd = ui.Subcommand('acousticbrainz', help="fetch metadata from AcousticBrainz") def func(lib, opts, args): diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 471d31fcb..f48104766 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -1,7 +1,7 @@ -ABrainz Plugin +Acousticbrainz Plugin ============== -The ``abrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as +The ``acoustricbrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as * ``danceable`` + Predicts how easy the track is danceable to @@ -10,8 +10,8 @@ The ``abrainz`` plugin provides a command that traverses through a library and t * ``mood_party`` + Predicts the probability this track is played in a party environment -Enable the ``abrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: +Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: $ beet abrainz -Additional command-line options coming soon. \ No newline at end of file +Additional command-line options coming soon. diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 4b10275e8..0c1c4ce11 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -31,7 +31,7 @@ Each plugin has its own set of options that can be defined in a section bearing .. toctree:: :hidden: - abrainz + acousticbrainz badfiles bpd bpm @@ -95,7 +95,7 @@ Autotagger Extensions Metadata -------- -* :doc:`abrainz`: Fetch various AcousticBrainz metadata +* :doc:`acousticbrainz`: Fetch various AcousticBrainz metadata * :doc:`bpm`: Measure tempo using keystrokes. * :doc:`echonest`: Automatically fetch `acoustic attributes`_ from `the Echo Nest`_ (tempo, energy, danceability, ...). From fa9039381cdb91a8ecb97c306eef3a406fa938b3 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 09:01:13 -0600 Subject: [PATCH 0326/2280] Update docs --- docs/plugins/acousticbrainz.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index f48104766..7019671a2 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -1,5 +1,5 @@ Acousticbrainz Plugin -============== +===================== The ``acoustricbrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as @@ -12,6 +12,6 @@ The ``acoustricbrainz`` plugin provides a command that traverses through a libra Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: - $ beet abrainz + $ beet acousticbrainz Additional command-line options coming soon. From ad57943819078d36843c2e0037edae4c9ebe2138 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Thu, 31 Dec 2015 09:35:01 -0600 Subject: [PATCH 0327/2280] Updated Copyright Year --- beetsplug/acousticbrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index bb33e0515..fa1d71b5f 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # This file is part of beets. -# Copyright 2016, Ohm Patel. +# Copyright 2015-2016, Ohm Patel. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the From 6f1e003a9bba7d88e305c2f2208e1ba1ed7a9a99 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:19:29 -0800 Subject: [PATCH 0328/2280] Changelog for #1784 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index dbcd7e399..e9c2befe9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,10 @@ New: * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It now requires an API key from Google. Thanks to :user:`lcharlick`. :bug:`1778` +* A new :doc:`/plugins/acousticbrainz` fetches acoustic-analysis information + from the `AcousticBrainz`_ project. Thanks to :user:`opatel99`. :bug:`1784` + +.. _AcousticBrainz: http://acousticbrainz.org/ 1.3.16 (December 28, 2015) From b29e386a1510200c185ad3e9a1912bfb2a337a38 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:24:32 -0800 Subject: [PATCH 0329/2280] Refine AcousticBrainz docs (#1784) --- docs/plugins/acousticbrainz.rst | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 7019671a2..71dc462d8 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -1,17 +1,22 @@ -Acousticbrainz Plugin +AcousticBrainz Plugin ===================== -The ``acoustricbrainz`` plugin provides a command that traverses through a library and tags tracks with valid MusicBrainz IDs with additional metadata such as +The ``acoustricbrainz`` plugin gets acoustic-analysis information from the +`AcousticBrainz`_ project. The spirit is similar to the +:doc:`/plugins/echonest`. -* ``danceable`` - + Predicts how easy the track is danceable to -* ``mood_happy`` - + Predicts the probability this track is played to invoke happiness -* ``mood_party`` - + Predicts the probability this track is played in a party environment +.. _AcousticBrainz: http://acousticbrainz.org/ -Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run with: +Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run it by typing:: $ beet acousticbrainz -Additional command-line options coming soon. +For all tracks with a MusicBrainz recording ID, the plugin currently sets +these fields: + +* ``danceable``: Predicts how easy the track is to dance to. +* ``mood_happy``: Predicts the probability this track will evoke happiness. +* ``mood_party``: Predicts the probability this track should be played at a + party. + +These three fields are all numbers between 0.0 and 1.0. From eb2b081dfd985e57c80bd98c59395197976658b9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:28:28 -0800 Subject: [PATCH 0330/2280] acousticbrainz: A bit more logging This way, the command shows you that it's making progress. --- beetsplug/acousticbrainz.py | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index fa1d71b5f..65a8f7d71 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -35,36 +35,40 @@ class AcousticPlugin(plugins.BeetsPlugin): help="fetch metadata from AcousticBrainz") def func(lib, opts, args): - fetch_info(self, lib) + fetch_info(self._log, lib) cmd.func = func return [cmd] -def fetch_info(self, lib): +def fetch_info(log, lib): """Currently outputs MBID and corresponding request status code """ for item in lib.items(): if item.mb_trackid: - rs = requests.get(generate_url(item.mb_trackid)) + log.info('getting data for: {}', item) + + url = generate_url(item.mb_trackid) + log.debug('fetching URL: {}', url) + rs = requests.get(url) try: rs.json() except ValueError: - self._log.debug('Invalid Response: {}', rs.text) + log.debug('Invalid Response: {}', rs.text) - item.danceable = get_value(self._log, rs.json(), ["highlevel", - "danceability", - "all", - "danceable"]) - item.mood_happy = get_value(self._log, rs.json(), ["highlevel", - "mood_happy", - "all", - "happy"]) - item.mood_party = get_value(self._log, rs.json(), ["highlevel", - "mood_party", - "all", - "party"]) + item.danceable = get_value(log, rs.json(), ["highlevel", + "danceability", + "all", + "danceable"]) + item.mood_happy = get_value(log, rs.json(), ["highlevel", + "mood_happy", + "all", + "happy"]) + item.mood_party = get_value(log, rs.json(), ["highlevel", + "mood_party", + "all", + "party"]) item.write() item.store() From 18e5b30d19dbd3a10e1dabf27a9f795b0be9fe09 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:29:57 -0800 Subject: [PATCH 0331/2280] acousticbrainz: Handle requests errors --- beetsplug/acousticbrainz.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 65a8f7d71..9c0c18260 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -48,10 +48,16 @@ def fetch_info(log, lib): if item.mb_trackid: log.info('getting data for: {}', item) + # Fetch the data from the AB API. url = generate_url(item.mb_trackid) log.debug('fetching URL: {}', url) - rs = requests.get(url) + try: + rs = requests.get(url) + except requests.RequestException as exc: + log.info('request error: {}', exc) + continue + # Parse the JSON response. try: rs.json() except ValueError: From 878161bb4f4099526321cd21bc8a8848438ffb60 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:31:32 -0800 Subject: [PATCH 0332/2280] acousticbrainz: Avoid re-parsing the JSON --- beetsplug/acousticbrainz.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 9c0c18260..acc08488b 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -59,22 +59,25 @@ def fetch_info(log, lib): # Parse the JSON response. try: - rs.json() + data = rs.json() except ValueError: log.debug('Invalid Response: {}', rs.text) - item.danceable = get_value(log, rs.json(), ["highlevel", - "danceability", - "all", - "danceable"]) - item.mood_happy = get_value(log, rs.json(), ["highlevel", - "mood_happy", - "all", - "happy"]) - item.mood_party = get_value(log, rs.json(), ["highlevel", - "mood_party", - "all", - "party"]) + item.danceable = get_value( + log, + data, + ["highlevel", "danceability", "all", "danceable"], + ) + item.mood_happy = get_value( + log, + data, + ["highlevel", "mood_happy", "all", "happy"], + ) + item.mood_party = get_value( + log, + data, + ["highlevel", "mood_party", "all", "party"], + ) item.write() item.store() From 5d89b7da67ba08e55462d2a351368d0d39d3cde0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:33:58 -0800 Subject: [PATCH 0333/2280] acousticbrainz: Allow filtering on a query Like other, similar commands. --- beetsplug/acousticbrainz.py | 10 ++++++---- docs/plugins/acousticbrainz.rst | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index acc08488b..badb5728d 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -35,16 +35,17 @@ class AcousticPlugin(plugins.BeetsPlugin): help="fetch metadata from AcousticBrainz") def func(lib, opts, args): - fetch_info(self._log, lib) + items = lib.items(ui.decargs(args)) + fetch_info(self._log, items, ui.should_write()) cmd.func = func return [cmd] -def fetch_info(log, lib): +def fetch_info(log, items, write): """Currently outputs MBID and corresponding request status code """ - for item in lib.items(): + for item in items: if item.mb_trackid: log.info('getting data for: {}', item) @@ -79,7 +80,8 @@ def fetch_info(log, lib): ["highlevel", "mood_party", "all", "party"], ) - item.write() + if write: + item.try_write() item.store() diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 71dc462d8..8e15716a5 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -9,7 +9,7 @@ The ``acoustricbrainz`` plugin gets acoustic-analysis information from the Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run it by typing:: - $ beet acousticbrainz + $ beet acousticbrainz [QUERY] For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: From 3a3dc8b3ae90189e87fa56566b9a545f3c6340a7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:35:14 -0800 Subject: [PATCH 0334/2280] acousticbrainz: Don't write tags Since we aren't updating any on-disk tags anyway. --- beetsplug/acousticbrainz.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index badb5728d..e4557106b 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -36,13 +36,13 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - fetch_info(self._log, items, ui.should_write()) + fetch_info(self._log, items) cmd.func = func return [cmd] -def fetch_info(log, items, write): +def fetch_info(log, items): """Currently outputs MBID and corresponding request status code """ for item in items: @@ -64,6 +64,7 @@ def fetch_info(log, items, write): except ValueError: log.debug('Invalid Response: {}', rs.text) + # Get each field and assign it on the item. item.danceable = get_value( log, data, @@ -80,8 +81,8 @@ def fetch_info(log, items, write): ["highlevel", "mood_party", "all", "party"], ) - if write: - item.try_write() + # Store the data. We only update flexible attributes, so we + # don't call `item.try_write()` here. item.store() From aad2cf1feb193acb7d5001efce692e47a95eb8f4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 31 Dec 2015 11:38:05 -0800 Subject: [PATCH 0335/2280] acousticbrainz: Log an error for missing data --- beetsplug/acousticbrainz.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index e4557106b..934531a3c 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -58,6 +58,11 @@ def fetch_info(log, items): log.info('request error: {}', exc) continue + # Check for missing tracks. + if rs.status_code == 404: + log.info('recording ID {} not found', item.mb_trackid) + continue + # Parse the JSON response. try: data = rs.json() From 775ac4ed8368758c77e5cfebcec885cdda60f300 Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Thu, 31 Dec 2015 21:49:03 +0100 Subject: [PATCH 0336/2280] play: Log exception from os call more accurately Depending on raw or not, we do not necessarily play a 'playlist'. Use 'query' generically instead. --- beetsplug/play.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index e366919fb..c943a5155 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -129,7 +129,7 @@ class PlayPlugin(BeetsPlugin): try: util.interactive_open(open_args, command_str) except OSError as exc: - raise ui.UserError("Could not play the music playlist: " + raise ui.UserError("Could not play the query: " "{0}".format(exc)) def _create_tmp_playlist(self, paths_list): From 26679f891e24b85c8d2b7de2132f66a6d49691c4 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Fri, 1 Jan 2016 01:01:14 -0600 Subject: [PATCH 0337/2280] ABrainz: Added acousticbrainz to autotagger and updated docs --- beetsplug/acousticbrainz.py | 12 ++++++++++++ docs/plugins/acousticbrainz.rst | 18 +++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 934531a3c..8f7bc6f5a 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -30,6 +30,11 @@ class AcousticPlugin(plugins.BeetsPlugin): def __init__(self): super(AcousticPlugin, self).__init__() + self.config.add({'auto': True}) + if self.config['auto']: + self.register_listener('import_task_files', + self.import_task_files) + def commands(self): cmd = ui.Subcommand('acousticbrainz', help="fetch metadata from AcousticBrainz") @@ -41,6 +46,13 @@ class AcousticPlugin(plugins.BeetsPlugin): cmd.func = func return [cmd] + def import_task_files(self, session, task): + """Automatically tag imported files + """ + + items = task.imported_items() + fetch_info(self._log, items) + def fetch_info(log, items): """Currently outputs MBID and corresponding request status code diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 8e15716a5..3cb0717e2 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -19,4 +19,20 @@ these fields: * ``mood_party``: Predicts the probability this track should be played at a party. -These three fields are all numbers between 0.0 and 1.0. +Automatic Tagging +----------------- + +To automatically tag files using AcousticBrainz data during import, just +enable the ``acousticbrainz`` plugin (see :ref:`using-plugins`). When importing +new files (with ``import.write`` turned on) or modifying files' tags with the +``beet modify`` command, beets will query the AcousticBrainz API using MBID and +set the appropriate metadata. + +Configuration +------------- + +To configure the plugin, make a ``acousticbrainz:`` section in your +configuration file. There is one option: + +- **auto**: Enable AcousticBrainz import during import. + Default: ``yes``. From 82709f1c1b1069b6aaba11170eefc54347113085 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Fri, 1 Jan 2016 01:28:17 -0600 Subject: [PATCH 0338/2280] ABrainz: Added more metadata for plugin to fetch and updated docs --- beetsplug/acousticbrainz.py | 52 ++++++++++++++++++++++++++++++++- docs/plugins/acousticbrainz.rst | 17 ++++++++--- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 8f7bc6f5a..c75849b12 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -87,6 +87,31 @@ def fetch_info(log, items): data, ["highlevel", "danceability", "all", "danceable"], ) + item.gender = get_value( + log, + data, + ["highlevel", "gender", "value"], + ) + item.genre_rosamerica = get_value( + log, + data, + ["highlevel", "genre_rosamerica", "value"], + ) + item.mood_acoustic = get_value( + log, + data, + ["highlevel", "mood_acoustic", "all", "acoustic"], + ) + item.mood_aggressive = get_value( + log, + data, + ["highlevel", "mood_aggresive", "all", "aggresive"], + ) + item.mood_electronic = get_value( + log, + data, + ["highlevel", "mood_electronic", "all", "electronic"], + ) item.mood_happy = get_value( log, data, @@ -97,7 +122,32 @@ def fetch_info(log, items): data, ["highlevel", "mood_party", "all", "party"], ) - + item.mood_relaxed = get_value( + log, + data, + ["highlevel", "mood_relaxed", "all", "relaxed"], + ) + item.mood_sad = get_value( + log, + data, + ["highlevel", "mood_sad", "all", "sad"], + ) + item.rhythm = get_value( + log, + data + ["highlevel", "ismir04_rhythm", "value"], + ) + item.tonal = get_value( + log, + data, + ["highlevel", "tonal_atonal", "all", "tonal"], + ) + item.voice_instrumental = get_value( + log, + data, + ["highlevel", "voice_instrumental", "value"], + ) + # Store the data. We only update flexible attributes, so we # don't call `item.try_write()` here. item.store() diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 3cb0717e2..b5f07d884 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -14,10 +14,19 @@ Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plug For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: -* ``danceable``: Predicts how easy the track is to dance to. -* ``mood_happy``: Predicts the probability this track will evoke happiness. -* ``mood_party``: Predicts the probability this track should be played at a - party. +* ``danceable`` +* ``gender`` +* ``genre_rosamerica`` +* ``mood_acoustic`` +* ``mood_aggressive`` +* ``mood_electronic`` +* ``mood_happy`` +* ``mood_party`` +* ``mood_relaxed`` +* ``mood_sad`` +* ``rhythm`` +* ``tonal`` +* ``voice_instrumental`` Automatic Tagging ----------------- From 52de2380768f9a5a35f40f535943949150d9fb39 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Fri, 1 Jan 2016 01:32:42 -0600 Subject: [PATCH 0339/2280] ABrainz: Removed PEP8 Whitespace violation --- beetsplug/acousticbrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index c75849b12..8ec719383 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -147,7 +147,7 @@ def fetch_info(log, items): data, ["highlevel", "voice_instrumental", "value"], ) - + # Store the data. We only update flexible attributes, so we # don't call `item.try_write()` here. item.store() From e9cfae9369fd628a1ca0679785ce025ec6b87163 Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Fri, 1 Jan 2016 12:17:12 +0100 Subject: [PATCH 0340/2280] play: Document #1785 --- docs/changelog.rst | 10 ++++++++++ docs/plugins/play.rst | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e9c2befe9..50699cadd 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,16 @@ New: .. _AcousticBrainz: http://acousticbrainz.org/ +Fixes: + +* :doc:`/plugins/play`: Remove dead code. From this point on, beets isn't + supposed and won't try to delete the playlists generated by ``beet play`` + (Note that although it was supposed to, beet didn't actually remove the + generated ``.m3u`` files beforehand either.). If this is an issue for you, you + might want to take a look at the ``raw`` config option of the + :doc:`/plugins/play`. :bug:`1785`, :bug:`1600` + + 1.3.16 (December 28, 2015) -------------------------- diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 9a7210b4e..5092ce846 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -82,3 +82,17 @@ example:: indicates that you need to insert extra arguments before specifying the playlist. + +Note on the Leakage of the Generated Playlists +_______________________________________________ + +Because the command that will open the generated ``.m3u`` files can be +arbitrarily configured by the user, beets won't try to delete those files. For +this reason, using this plugin will leave one or several playlist(s) in the +directory selected to create temporary files (Most likely ``/tmp/`` on Unix-like +systems. See `tempfile.tempdir`_.). Leaking those playlists until they are +externally wiped could be an issue for privacy or storage reasons. If this is +the case for you, you might want to use the ``raw`` config option described +above. + +.. _tempfile.tempdir: https://docs.python.org/2/library/tempfile.html#tempfile.tempdir From 50789e88fe6533e43e9d4593b3f91c3ac5b43522 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois-Xavier=20Thomas?= Date: Fri, 1 Jan 2016 17:19:10 +0100 Subject: [PATCH 0341/2280] Fix 1583: Move command only shows modified files --- beets/ui/commands.py | 7 ++++++- docs/changelog.rst | 2 ++ docs/reference/cli.rst | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 39501f361..4b756b5c8 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1427,11 +1427,16 @@ def move_items(lib, dest, query, copy, album, pretend): """ items, albums = _do_query(lib, query, album, False) objs = albums if album else items + isitemmoved = lambda item: item.path != item.destination(basedir=dest) + 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' entity = 'album' if album else 'item' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, - 's' if len(objs) > 1 else '') + 's' if len(objs) != 1 else '') + if len(objs) == 0: + return if pretend: if album: show_path_changes([(item.path, item.destination(basedir=dest)) diff --git a/docs/changelog.rst b/docs/changelog.rst index 50699cadd..bc15bef29 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,8 @@ Fixes: generated ``.m3u`` files beforehand either.). If this is an issue for you, you might want to take a look at the ``raw`` config option of the :doc:`/plugins/play`. :bug:`1785`, :bug:`1600` +* The :ref:`move-cmd` command does not display files whose path does not change + anymore. :bug:`1583` diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index f39dad393..5eb440316 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -256,7 +256,7 @@ anywhere in your filesystem. The ``-c`` option copies files instead of moving them. As with other commands, the ``-a`` option matches albums instead of items. To perform a "dry run", just use the ``-p`` (for "pretend") flag. This will -show you all how the files would be moved but won't actually change anything +show you a list of files that would be moved but won't actually change anything on disk. .. _update-cmd: From f582e045e9a5ff987e1265082a3abd3dad86358e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jan 2016 13:05:07 -0800 Subject: [PATCH 0342/2280] Add a comment for #1584 --- beets/ui/commands.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 4b756b5c8..25ed0425d 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1427,6 +1427,8 @@ def move_items(lib, dest, query, copy, album, pretend): """ items, albums = _do_query(lib, query, album, False) objs = albums if album else items + + # Filter out files that don't need to be moved. isitemmoved = lambda item: item.path != item.destination(basedir=dest) isalbummoved = lambda album: any(isitemmoved(i) for i in album.items()) objs = [o for o in objs if (isalbummoved if album else isitemmoved)(o)] @@ -1435,8 +1437,9 @@ def move_items(lib, dest, query, copy, album, pretend): entity = 'album' if album else 'item' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, 's' if len(objs) != 1 else '') - if len(objs) == 0: + if not objs: return + if pretend: if album: show_path_changes([(item.path, item.destination(basedir=dest)) From c5f25429e962f67c2150fa5483147ac472002cf7 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Fri, 1 Jan 2016 18:29:36 -0600 Subject: [PATCH 0343/2280] ABrainz: Fixed docstrings and documentation --- beetsplug/acousticbrainz.py | 10 +++++----- docs/plugins/acousticbrainz.rst | 5 ++--- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 8ec719383..f398fe8f2 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -""" Fetch various AcousticBrainz metadata using MBID +"""Fetch various AcousticBrainz metadata using MBID. """ from __future__ import (division, absolute_import, print_function, unicode_literals) @@ -47,7 +47,7 @@ class AcousticPlugin(plugins.BeetsPlugin): return [cmd] def import_task_files(self, session, task): - """Automatically tag imported files + """Function is called upon beet import. """ items = task.imported_items() @@ -55,7 +55,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def fetch_info(log, items): - """Currently outputs MBID and corresponding request status code + """Currently outputs MBID and corresponding request status code. """ for item in items: if item.mb_trackid: @@ -154,13 +154,13 @@ def fetch_info(log, items): def generate_url(mbid): - """Generates url of AcousticBrainz end point for given MBID + """Generates AcousticBrainz end point url for given MBID. """ return ACOUSTIC_URL + mbid + LEVEL def get_value(log, data, map_path): - """Allows traversal of dictionary with cleaner formatting + """Allows easier traversal of dictionary. """ try: return reduce(lambda d, k: d[k], map_path, data) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index b5f07d884..24938473f 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -33,8 +33,7 @@ Automatic Tagging To automatically tag files using AcousticBrainz data during import, just enable the ``acousticbrainz`` plugin (see :ref:`using-plugins`). When importing -new files (with ``import.write`` turned on) or modifying files' tags with the -``beet modify`` command, beets will query the AcousticBrainz API using MBID and +new files, beets will query the AcousticBrainz API using MBID and set the appropriate metadata. Configuration @@ -43,5 +42,5 @@ Configuration To configure the plugin, make a ``acousticbrainz:`` section in your configuration file. There is one option: -- **auto**: Enable AcousticBrainz import during import. +- **auto**: Enable AcousticBrainz during ``beet import``. Default: ``yes``. From 9bba782e9ceb30e844b42f75698468487cbcb643 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sat, 2 Jan 2016 13:32:52 +0100 Subject: [PATCH 0344/2280] mbsubmit: final style fixes (closes #1779) --- beetsplug/mbsubmit.py | 4 ++-- docs/plugins/mbsubmit.rst | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 7faedff44..947e4cfc6 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -37,7 +37,7 @@ class MBSubmitPlugin(BeetsPlugin): super(MBSubmitPlugin, self).__init__() self.config.add({ - 'mb_format': '$track. $title - $artist ($length)', + 'format': '$track. $title - $artist ($length)', 'threshold': 'medium', }) @@ -58,4 +58,4 @@ class MBSubmitPlugin(BeetsPlugin): def print_tracks(self, session, task): for i in task.items: - print_data(None, i, self.config['mb_format'].get()) + print_data(None, i, self.config['format'].get()) diff --git a/docs/plugins/mbsubmit.rst b/docs/plugins/mbsubmit.rst index 9312eb785..5c13375ba 100644 --- a/docs/plugins/mbsubmit.rst +++ b/docs/plugins/mbsubmit.rst @@ -30,7 +30,7 @@ strong recommendations are found for the album:: As MusicBrainz currently does not support submitting albums programmatically, the recommended workflow is to copy the output of the ``Print tracks`` choice and paste it into the parser that can be found by clicking on the -"`Track Parser`" button on MusicBrainz "`Tracklist`" tab. +"Track Parser" button on MusicBrainz "Tracklist" tab. Configuration ------------- @@ -38,7 +38,7 @@ Configuration To configure the plugin, make a ``mbsubmit:`` section in your configuration file. The following options are available: -- **mb_format**: The format used for printing the tracks, defined using the +- **format**: The format used for printing the tracks, defined using the same template syntax as beets’ :doc:`path formats `. Default: ``$track. $title - $artist ($length)``. - **threshold**: The minimum strength of the autotagger recommendation that @@ -51,4 +51,4 @@ Please note that some values of the ``threshold`` configuration option might require other ``beets`` command line switches to be enabled in order to work as intended. In particular, setting a threshold of ``strong`` will only display the prompt if ``timid`` mode is enabled. You can find more information about -how the recommendation system works on :ref:`match-config`. +how the recommendation system works at :ref:`match-config`. From 17dd7496a2cb12cbff0591ac409df5331ef84e85 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 11:33:19 -0600 Subject: [PATCH 0345/2280] ABrainz: Added low-level data and updated docs --- beetsplug/acousticbrainz.py | 72 ++++++++++++++++++++++----------- docs/plugins/acousticbrainz.rst | 4 ++ 2 files changed, 53 insertions(+), 23 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index f398fe8f2..652f86ce7 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -22,8 +22,7 @@ import requests from beets import plugins, ui -ACOUSTIC_URL = "http://acousticbrainz.org/" -LEVEL = "/high-level" +ACOUSTIC_BASE = "http://acousticbrainz.org/" class AcousticPlugin(plugins.BeetsPlugin): @@ -62,101 +61,128 @@ def fetch_info(log, items): log.info('getting data for: {}', item) # Fetch the data from the AB API. - url = generate_url(item.mb_trackid) - log.debug('fetching URL: {}', url) + high_url = generate_url(item.mb_trackid, "/high-level") + low_url = generate_url(item.mb_trackid, "/low-level") + log.debug('fetching URL: {}', high_url) + log.debug('fetching URL: {}', low_url) try: - rs = requests.get(url) + high = requests.get(high_url) + low = requests.get(low_url) except requests.RequestException as exc: log.info('request error: {}', exc) continue # Check for missing tracks. - if rs.status_code == 404: + if high.status_code == 404 or low.status_code == 404: log.info('recording ID {} not found', item.mb_trackid) continue # Parse the JSON response. try: - data = rs.json() + high_data = high.json() except ValueError: - log.debug('Invalid Response: {}', rs.text) + log.debug('Invalid Response: {}', high.text) + try: + low_data = low.json() + except ValueError: + log.debug('Invalid Response: {}', low.text) # Get each field and assign it on the item. item.danceable = get_value( log, - data, + high_data, ["highlevel", "danceability", "all", "danceable"], ) item.gender = get_value( log, - data, + high_data, ["highlevel", "gender", "value"], ) item.genre_rosamerica = get_value( log, - data, + high_data, ["highlevel", "genre_rosamerica", "value"], ) item.mood_acoustic = get_value( log, - data, + high_data, ["highlevel", "mood_acoustic", "all", "acoustic"], ) item.mood_aggressive = get_value( log, - data, + high_data, ["highlevel", "mood_aggresive", "all", "aggresive"], ) item.mood_electronic = get_value( log, - data, + high_data, ["highlevel", "mood_electronic", "all", "electronic"], ) item.mood_happy = get_value( log, - data, + high_data, ["highlevel", "mood_happy", "all", "happy"], ) item.mood_party = get_value( log, - data, + high_data, ["highlevel", "mood_party", "all", "party"], ) item.mood_relaxed = get_value( log, - data, + high_data, ["highlevel", "mood_relaxed", "all", "relaxed"], ) item.mood_sad = get_value( log, - data, + high_data, ["highlevel", "mood_sad", "all", "sad"], ) item.rhythm = get_value( log, - data + high_data, ["highlevel", "ismir04_rhythm", "value"], ) item.tonal = get_value( log, - data, + high_data, ["highlevel", "tonal_atonal", "all", "tonal"], ) item.voice_instrumental = get_value( log, - data, + high_data, ["highlevel", "voice_instrumental", "value"], ) + item.average_loudness = get_value( + log, + low_data, + ["lowlevel", "average_loudness"], + ) + item.key_key = get_value( + log, + low_data, + ["tonal", "key_key"], + ) + item.key_scale = get_value( + log, + low_data, + ["tonal", "key_scale"], + ) + item.key_strength = get_value( + log, + low_data, + ["tonal", "key_stength"], + ) # Store the data. We only update flexible attributes, so we # don't call `item.try_write()` here. item.store() -def generate_url(mbid): +def generate_url(mbid, level): """Generates AcousticBrainz end point url for given MBID. """ - return ACOUSTIC_URL + mbid + LEVEL + return ACOUSTIC_BASE + mbid + level def get_value(log, data, map_path): diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 24938473f..dcf35b493 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -14,9 +14,13 @@ Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plug For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: +* ``average_loudness``* * ``danceable`` * ``gender`` * ``genre_rosamerica`` +* ``key_key`` +* ``key_scale`` +* ``key_strength`` * ``mood_acoustic`` * ``mood_aggressive`` * ``mood_electronic`` From 3d64679be21517302b234bee408ec750f8b7520b Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 11:38:54 -0600 Subject: [PATCH 0346/2280] ABrainz: Corrected docs error --- docs/plugins/acousticbrainz.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index dcf35b493..ddd29e7d8 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -14,7 +14,7 @@ Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plug For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: -* ``average_loudness``* +* ``average_loudness`` * ``danceable`` * ``gender`` * ``genre_rosamerica`` From 4184f9dd13dec511361d9aa089f36e7e78770b48 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 12:03:07 -0600 Subject: [PATCH 0347/2280] ABrainz: Chords metadata from low_level --- beetsplug/acousticbrainz.py | 20 ++++++++++++++++++++ docs/plugins/acousticbrainz.rst | 4 ++++ 2 files changed, 24 insertions(+) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 652f86ce7..3d03feaae 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -158,6 +158,26 @@ def fetch_info(log, items): low_data, ["lowlevel", "average_loudness"], ) + item.chords_changes_rate = get_value( + log, + low_data, + ["tonal", "chords_changes_rate"], + ) + item.chords_key = get_value( + log, + low_data, + ["tonal", "chords_key"], + ) + item.chords_number_rate = get_value( + log, + low_data, + ["tonal", "chords_number_rate"], + ) + item.chords_scale = get_value( + log, + low_data, + ["tonal", "chords_scale"], + ) item.key_key = get_value( log, low_data, diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index ddd29e7d8..24232437a 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -15,6 +15,10 @@ For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: * ``average_loudness`` +* ``chords_changes_rate`` +* ``chords_key`` +* ``chords_number_rate`` +* ``chords_scale`` * ``danceable`` * ``gender`` * ``genre_rosamerica`` From 1bb55c5c13e1994ad77c0ffaf218b04887d58d35 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 14:55:34 -0600 Subject: [PATCH 0348/2280] ABrainz: Used existing initial_key variable --- beets/library.py | 1 + beetsplug/acousticbrainz.py | 19 ++++++------------- docs/plugins/acousticbrainz.rst | 3 +-- 3 files changed, 8 insertions(+), 15 deletions(-) diff --git a/beets/library.py b/beets/library.py index 474279b30..b42dd2c47 100644 --- a/beets/library.py +++ b/beets/library.py @@ -186,6 +186,7 @@ class MusicalKey(types.String): for flat, sharp in self.ENHARMONIC.items(): key = re.sub(flat, sharp, key) key = re.sub(r'[\W\s]+minor', 'm', key) + key = re.sub(r'[\W\s]+major', '', key) return key.capitalize() def normalize(self, key): diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 3d03feaae..79bce75c3 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -63,8 +63,7 @@ def fetch_info(log, items): # Fetch the data from the AB API. high_url = generate_url(item.mb_trackid, "/high-level") low_url = generate_url(item.mb_trackid, "/low-level") - log.debug('fetching URL: {}', high_url) - log.debug('fetching URL: {}', low_url) + log.debug('fetching URLs: {} and {}', high_url, low_url) try: high = requests.get(high_url) low = requests.get(low_url) @@ -81,11 +80,11 @@ def fetch_info(log, items): try: high_data = high.json() except ValueError: - log.debug('Invalid Response: {}', high.text) + log.debug('Invalid Response from high-level: {}', high.text) try: low_data = low.json() except ValueError: - log.debug('Invalid Response: {}', low.text) + log.debug('Invalid Response from low-level: {}', low.text) # Get each field and assign it on the item. item.danceable = get_value( @@ -178,15 +177,9 @@ def fetch_info(log, items): low_data, ["tonal", "chords_scale"], ) - item.key_key = get_value( - log, - low_data, - ["tonal", "key_key"], - ) - item.key_scale = get_value( - log, - low_data, - ["tonal", "key_scale"], + item.initial_key = '{} {}'.format( + get_value(log, low_data, ["tonal", "key_key"]), + get_value(log, low_data, ["tonal", "key_scale"]) ) item.key_strength = get_value( log, diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 24232437a..d782d3110 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -22,8 +22,7 @@ these fields: * ``danceable`` * ``gender`` * ``genre_rosamerica`` -* ``key_key`` -* ``key_scale`` +* ``initial_key`` * ``key_strength`` * ``mood_acoustic`` * ``mood_aggressive`` From 39b565d8d87d8145436a49c41b6fc318b5b91424 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 18:52:28 -0600 Subject: [PATCH 0349/2280] Refactor JesseW's suggestions --- beetsplug/acousticbrainz.py | 74 +++++++------------------------------ 1 file changed, 14 insertions(+), 60 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 79bce75c3..c4b169577 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -56,134 +56,97 @@ class AcousticPlugin(plugins.BeetsPlugin): def fetch_info(log, items): """Currently outputs MBID and corresponding request status code. """ + def get_value(map_path): + try: + return reduce(lambda d, k: d[k], map_path, data) + except KeyError: + log.debug('Invalid Path: {}', map_path) + for item in items: if item.mb_trackid: log.info('getting data for: {}', item) # Fetch the data from the AB API. - high_url = generate_url(item.mb_trackid, "/high-level") - low_url = generate_url(item.mb_trackid, "/low-level") - log.debug('fetching URLs: {} and {}', high_url, low_url) + urls = [generate_url(item.mb_trackid, path) for path in ["/low-level", "/high-level"]] + log.debug('fetching URLs: {}', urls) try: - high = requests.get(high_url) - low = requests.get(low_url) + responses = [requests.get(url) for url in urls] except requests.RequestException as exc: log.info('request error: {}', exc) continue # Check for missing tracks. - if high.status_code == 404 or low.status_code == 404: + if any(r.status_code == 404 for r in responses): log.info('recording ID {} not found', item.mb_trackid) continue # Parse the JSON response. try: - high_data = high.json() - except ValueError: - log.debug('Invalid Response from high-level: {}', high.text) - try: - low_data = low.json() + data = responses[0].json() + data.update(responses[1].json()) except ValueError: log.debug('Invalid Response from low-level: {}', low.text) # Get each field and assign it on the item. item.danceable = get_value( - log, - high_data, ["highlevel", "danceability", "all", "danceable"], ) item.gender = get_value( - log, - high_data, ["highlevel", "gender", "value"], ) item.genre_rosamerica = get_value( - log, - high_data, ["highlevel", "genre_rosamerica", "value"], ) item.mood_acoustic = get_value( - log, - high_data, ["highlevel", "mood_acoustic", "all", "acoustic"], ) item.mood_aggressive = get_value( - log, - high_data, ["highlevel", "mood_aggresive", "all", "aggresive"], ) item.mood_electronic = get_value( - log, - high_data, ["highlevel", "mood_electronic", "all", "electronic"], ) item.mood_happy = get_value( - log, - high_data, ["highlevel", "mood_happy", "all", "happy"], ) item.mood_party = get_value( - log, - high_data, ["highlevel", "mood_party", "all", "party"], ) item.mood_relaxed = get_value( - log, - high_data, ["highlevel", "mood_relaxed", "all", "relaxed"], ) item.mood_sad = get_value( - log, - high_data, ["highlevel", "mood_sad", "all", "sad"], ) item.rhythm = get_value( - log, - high_data, ["highlevel", "ismir04_rhythm", "value"], ) item.tonal = get_value( - log, - high_data, ["highlevel", "tonal_atonal", "all", "tonal"], ) item.voice_instrumental = get_value( - log, - high_data, ["highlevel", "voice_instrumental", "value"], ) item.average_loudness = get_value( - log, - low_data, ["lowlevel", "average_loudness"], ) item.chords_changes_rate = get_value( - log, - low_data, ["tonal", "chords_changes_rate"], ) item.chords_key = get_value( - log, - low_data, ["tonal", "chords_key"], ) item.chords_number_rate = get_value( - log, - low_data, ["tonal", "chords_number_rate"], ) item.chords_scale = get_value( - log, - low_data, ["tonal", "chords_scale"], ) item.initial_key = '{} {}'.format( - get_value(log, low_data, ["tonal", "key_key"]), - get_value(log, low_data, ["tonal", "key_scale"]) + get_value(["tonal", "key_key"]), + get_value(["tonal", "key_scale"]) ) item.key_strength = get_value( - log, - low_data, ["tonal", "key_stength"], ) @@ -196,12 +159,3 @@ def generate_url(mbid, level): """Generates AcousticBrainz end point url for given MBID. """ return ACOUSTIC_BASE + mbid + level - - -def get_value(log, data, map_path): - """Allows easier traversal of dictionary. - """ - try: - return reduce(lambda d, k: d[k], map_path, data) - except KeyError: - log.debug('Invalid Path: {}', map_path) From e5c46cf6ac7a2048520bf823bb36041071f7b27a Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 18:59:47 -0600 Subject: [PATCH 0350/2280] PEP-8 Cleanup --- beetsplug/acousticbrainz.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index c4b169577..187f10136 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -23,6 +23,7 @@ import requests from beets import plugins, ui ACOUSTIC_BASE = "http://acousticbrainz.org/" +LEVELS = ["/low-level", "/high-level"] class AcousticPlugin(plugins.BeetsPlugin): @@ -67,7 +68,7 @@ def fetch_info(log, items): log.info('getting data for: {}', item) # Fetch the data from the AB API. - urls = [generate_url(item.mb_trackid, path) for path in ["/low-level", "/high-level"]] + urls = [generate_url(item.mb_trackid, path) for path in LEVELS] log.debug('fetching URLs: {}', urls) try: responses = [requests.get(url) for url in urls] @@ -85,7 +86,8 @@ def fetch_info(log, items): data = responses[0].json() data.update(responses[1].json()) except ValueError: - log.debug('Invalid Response from low-level: {}', low.text) + log.debug('Invalid Response: {} & {}', + responses[0].text, responses[1].text) # Get each field and assign it on the item. item.danceable = get_value( From b5f71a88e87d07a8ed9e6bf99249e2aee7377de0 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 19:05:53 -0600 Subject: [PATCH 0351/2280] ABrainz: replace lambda with operator --- beetsplug/acousticbrainz.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 187f10136..b0700c119 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -19,6 +19,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import requests +import operator from beets import plugins, ui @@ -57,9 +58,10 @@ class AcousticPlugin(plugins.BeetsPlugin): def fetch_info(log, items): """Currently outputs MBID and corresponding request status code. """ + def get_value(map_path): try: - return reduce(lambda d, k: d[k], map_path, data) + return reduce(operator.getitem, map_path, data) except KeyError: log.debug('Invalid Path: {}', map_path) From a1db349bf960563656ce58bd9d4b539390b36567 Mon Sep 17 00:00:00 2001 From: Ohm Patel Date: Sat, 2 Jan 2016 19:20:20 -0600 Subject: [PATCH 0352/2280] ABrainz: Variable parameters --- beetsplug/acousticbrainz.py | 55 ++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index b0700c119..15584b03c 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -59,7 +59,7 @@ def fetch_info(log, items): """Currently outputs MBID and corresponding request status code. """ - def get_value(map_path): + def get_value(*map_path): try: return reduce(operator.getitem, map_path, data) except KeyError: @@ -73,85 +73,84 @@ def fetch_info(log, items): urls = [generate_url(item.mb_trackid, path) for path in LEVELS] log.debug('fetching URLs: {}', urls) try: - responses = [requests.get(url) for url in urls] + res = [requests.get(url) for url in urls] except requests.RequestException as exc: log.info('request error: {}', exc) continue # Check for missing tracks. - if any(r.status_code == 404 for r in responses): + if any(r.status_code == 404 for r in res): log.info('recording ID {} not found', item.mb_trackid) continue # Parse the JSON response. try: - data = responses[0].json() - data.update(responses[1].json()) + data = res[0].json() + data.update(res[1].json()) except ValueError: - log.debug('Invalid Response: {} & {}', - responses[0].text, responses[1].text) + log.debug('Invalid Response: {} & {}', [r.text for r in res]) # Get each field and assign it on the item. item.danceable = get_value( - ["highlevel", "danceability", "all", "danceable"], + "highlevel", "danceability", "all", "danceable", ) item.gender = get_value( - ["highlevel", "gender", "value"], + "highlevel", "gender", "value", ) item.genre_rosamerica = get_value( - ["highlevel", "genre_rosamerica", "value"], + "highlevel", "genre_rosamerica", "value" ) item.mood_acoustic = get_value( - ["highlevel", "mood_acoustic", "all", "acoustic"], + "highlevel", "mood_acoustic", "all", "acoustic" ) item.mood_aggressive = get_value( - ["highlevel", "mood_aggresive", "all", "aggresive"], + "highlevel", "mood_aggresive", "all", "aggresive" ) item.mood_electronic = get_value( - ["highlevel", "mood_electronic", "all", "electronic"], + "highlevel", "mood_electronic", "all", "electronic" ) item.mood_happy = get_value( - ["highlevel", "mood_happy", "all", "happy"], + "highlevel", "mood_happy", "all", "happy" ) item.mood_party = get_value( - ["highlevel", "mood_party", "all", "party"], + "highlevel", "mood_party", "all", "party" ) item.mood_relaxed = get_value( - ["highlevel", "mood_relaxed", "all", "relaxed"], + "highlevel", "mood_relaxed", "all", "relaxed" ) item.mood_sad = get_value( - ["highlevel", "mood_sad", "all", "sad"], + "highlevel", "mood_sad", "all", "sad" ) item.rhythm = get_value( - ["highlevel", "ismir04_rhythm", "value"], + "highlevel", "ismir04_rhythm", "value" ) item.tonal = get_value( - ["highlevel", "tonal_atonal", "all", "tonal"], + "highlevel", "tonal_atonal", "all", "tonal" ) item.voice_instrumental = get_value( - ["highlevel", "voice_instrumental", "value"], + "highlevel", "voice_instrumental", "value" ) item.average_loudness = get_value( - ["lowlevel", "average_loudness"], + "lowlevel", "average_loudness" ) item.chords_changes_rate = get_value( - ["tonal", "chords_changes_rate"], + "tonal", "chords_changes_rate" ) item.chords_key = get_value( - ["tonal", "chords_key"], + "tonal", "chords_key" ) item.chords_number_rate = get_value( - ["tonal", "chords_number_rate"], + "tonal", "chords_number_rate" ) item.chords_scale = get_value( - ["tonal", "chords_scale"], + "tonal", "chords_scale" ) item.initial_key = '{} {}'.format( - get_value(["tonal", "key_key"]), - get_value(["tonal", "key_scale"]) + get_value("tonal", "key_key"), + get_value("tonal", "key_scale") ) item.key_strength = get_value( - ["tonal", "key_stength"], + "tonal", "key_stength" ) # Store the data. We only update flexible attributes, so we From 7d5693f2d3d88529789e16af522158cca491c7da Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:20:43 -0800 Subject: [PATCH 0353/2280] Re-insert open_anything() if command is falsey Fixes d5b7ce64da65dcacd99207bcdf11fc6f2703d879 --- beets/util/__init__.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 28845e597..27dbbcd3b 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -776,11 +776,14 @@ def interactive_open(targets, command): Can raise `OSError`. """ - # Split the command string into its arguments. - try: - command = shlex_split(command) - except ValueError: # Malformed shell tokens. - command = [command] + if command: + # Split the command string into its arguments. + try: + command = shlex_split(command) + except ValueError: # Malformed shell tokens. + command = [command] + else: + command = [open_anything()] command.insert(0, command[0]) # for argv[0] command += targets From 25c31a75d97dabcb2fdb42e5f7b3fb4fd6662bf8 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:23:36 -0800 Subject: [PATCH 0354/2280] Avoid re-assigning command variable, for clarity --- beets/util/__init__.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 27dbbcd3b..584eb2e8a 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -779,16 +779,17 @@ def interactive_open(targets, command): if command: # Split the command string into its arguments. try: - command = shlex_split(command) + args = shlex_split(command) except ValueError: # Malformed shell tokens. - command = [command] + args = [command] else: - command = [open_anything()] - command.insert(0, command[0]) # for argv[0] + args = [open_anything()] - command += targets + args.insert(0, args[0]) # for argv[0] - return os.execlp(*command) + args += targets + + return os.execlp(*args) def _windows_long_path_name(short_path): From 246afda9c4181cff46511d3b4ca3d59095bb9006 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 13:07:27 -0800 Subject: [PATCH 0355/2280] Actually, push the job off on the caller --- beets/util/__init__.py | 15 +++++++-------- beetsplug/play.py | 2 ++ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 584eb2e8a..0da68efc7 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -776,14 +776,13 @@ def interactive_open(targets, command): Can raise `OSError`. """ - if command: - # Split the command string into its arguments. - try: - args = shlex_split(command) - except ValueError: # Malformed shell tokens. - args = [command] - else: - args = [open_anything()] + assert command + + # Split the command string into its arguments. + try: + args = shlex_split(command) + except ValueError: # Malformed shell tokens. + args = [command] args.insert(0, args[0]) # for argv[0] diff --git a/beetsplug/play.py b/beetsplug/play.py index c943a5155..52bf75aa5 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -63,6 +63,8 @@ class PlayPlugin(BeetsPlugin): command passing that playlist, at request insert optional arguments. """ command_str = config['play']['command'].get() + if not command_str: + command_str = util.open_anything() use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() raw = config['play']['raw'].get(bool) From 4041c3ceb2924728b405b752a5ecb63bdd18b715 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Jan 2016 14:14:10 -0800 Subject: [PATCH 0356/2280] acousticbrainz (#1787): Write tags Now that we modify the built-in field, this is necessary. --- beetsplug/acousticbrainz.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 15584b03c..b7359e612 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -42,7 +42,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - fetch_info(self._log, items) + fetch_info(self._log, items, ui.should_write()) cmd.func = func return [cmd] @@ -52,11 +52,11 @@ class AcousticPlugin(plugins.BeetsPlugin): """ items = task.imported_items() - fetch_info(self._log, items) + fetch_info(self._log, items, False) -def fetch_info(log, items): - """Currently outputs MBID and corresponding request status code. +def fetch_info(log, items, write): + """Get data from AcousticBrainz for the items. """ def get_value(*map_path): @@ -153,9 +153,10 @@ def fetch_info(log, items): "tonal", "key_stength" ) - # Store the data. We only update flexible attributes, so we - # don't call `item.try_write()` here. + # Store the data. item.store() + if write: + item.try_write() def generate_url(mbid, level): From 05e5a0ade339cd8a1e673788b8712c9ad20b4743 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Jan 2016 14:15:28 -0800 Subject: [PATCH 0357/2280] acousticbrainz (#1787): Docs note on initial_key --- docs/plugins/acousticbrainz.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index d782d3110..4e1bf7b27 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -22,7 +22,8 @@ these fields: * ``danceable`` * ``gender`` * ``genre_rosamerica`` -* ``initial_key`` +* ``initial_key`` (This is a built-in beets field, which can also be provided + by :doc:`/plugins/keyfinder`.) * ``key_strength`` * ``mood_acoustic`` * ``mood_aggressive`` From 04618f9aefb7a5bc0457d4348cebc81a18b1ab51 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Jan 2016 14:17:39 -0800 Subject: [PATCH 0358/2280] acousticbrainz (#1787): Fix typos in keys --- beetsplug/acousticbrainz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index b7359e612..49f01ea21 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -71,7 +71,7 @@ def fetch_info(log, items, write): # Fetch the data from the AB API. urls = [generate_url(item.mb_trackid, path) for path in LEVELS] - log.debug('fetching URLs: {}', urls) + log.debug('fetching URLs: {}', ' '.join(urls)) try: res = [requests.get(url) for url in urls] except requests.RequestException as exc: @@ -104,7 +104,7 @@ def fetch_info(log, items, write): "highlevel", "mood_acoustic", "all", "acoustic" ) item.mood_aggressive = get_value( - "highlevel", "mood_aggresive", "all", "aggresive" + "highlevel", "mood_aggressive", "all", "aggressive" ) item.mood_electronic = get_value( "highlevel", "mood_electronic", "all", "electronic" @@ -150,7 +150,7 @@ def fetch_info(log, items, write): get_value("tonal", "key_scale") ) item.key_strength = get_value( - "tonal", "key_stength" + "tonal", "key_strength" ) # Store the data. From 390263a6e87267412a9f5596f86a3ec265ced207 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Jan 2016 14:26:32 -0800 Subject: [PATCH 0359/2280] (Draft) changelog for #1793 --- docs/changelog.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index a6954ef2b..b18468d6d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,7 +27,8 @@ Fixes: :doc:`/plugins/play`. :bug:`1785`, :bug:`1600` * The :ref:`move-cmd` command does not display files whose path does not change anymore. :bug:`1583` - +* :doc:`/plugins/play`: Fix a regression in the last version where there was + no default command. :bug:`1793` 1.3.16 (December 28, 2015) From 25495d675c44a75d7dedfe123f30a858f9cd60be Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 21:39:37 -0800 Subject: [PATCH 0360/2280] Add minimal (no asserts) test for play plugin --- test/test_play.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 test/test_play.py diff --git a/test/test_play.py b/test/test_play.py new file mode 100644 index 000000000..8a37509cd --- /dev/null +++ b/test/test_play.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +"""Tests for the play plugin""" + +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from mock import patch, Mock + +from test._common import unittest +from test.helper import TestHelper + +from beetsplug.play import PlayPlugin + + +class PlayPluginTest(unittest.TestCase, TestHelper): + def setUp(self): + self.setup_beets() + self.load_plugins('play') + self.add_item(title='aNiceTitle') + + def tearDown(self): + self.teardown_beets() + self.unload_plugins() + + @patch('beetsplug.play.util.interactive_open', Mock()) + def test_basic(self): + self.run_command('play', 'title:aNiceTitle') + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') From 3807d4fc57be97bb72b24178d508f3f0f172c21b Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 21:50:13 -0800 Subject: [PATCH 0361/2280] fix flake8 warnings --- test/test_play.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 8a37509cd..68d8c2ea8 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -10,8 +10,6 @@ from mock import patch, Mock from test._common import unittest from test.helper import TestHelper -from beetsplug.play import PlayPlugin - class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): @@ -27,6 +25,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def test_basic(self): self.run_command('play', 'title:aNiceTitle') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From d15b996dc4a741390507a96d6facf113f8da0869 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 22:33:36 -0800 Subject: [PATCH 0362/2280] Verify that the generated playlist contains the path to the item --- test/test_play.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 68d8c2ea8..f1f1ba3ab 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -5,7 +5,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) -from mock import patch, Mock +from mock import patch, ANY from test._common import unittest from test.helper import TestHelper @@ -15,16 +15,21 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('play') - self.add_item(title='aNiceTitle') + self.item = self.add_item(title='aNiceTitle') def tearDown(self): self.teardown_beets() self.unload_plugins() - @patch('beetsplug.play.util.interactive_open', Mock()) - def test_basic(self): + @patch('beetsplug.play.util.interactive_open') + def test_basic(self, open_mock): self.run_command('play', 'title:aNiceTitle') + open_mock.assert_called_once_with(ANY, None) + playlist = open(open_mock.call_args[0][0][0], 'r') + self.assertEqual(self.item.path.decode('utf-8') + '\n', + playlist.read().decode('utf-8')) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 362d625f6975451b140d124ef419a1f99b6b4a0c Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:33:36 -0800 Subject: [PATCH 0363/2280] add test for --args option --- test/test_play.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/test_play.py b/test/test_play.py index f1f1ba3ab..4a57decfb 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -30,6 +30,16 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.assertEqual(self.item.path.decode('utf-8') + '\n', playlist.read().decode('utf-8')) + @patch('beetsplug.play.util.interactive_open') + def test_args_option(self, open_mock): + self.config['play']['command'] = 'true' + self.run_command('play', '-A', 'foo', 'title:aNiceTitle') + + open_mock.assert_called_once_with(ANY, 'true foo') + playlist = open(open_mock.call_args[0][0][0], 'r') + self.assertEqual(self.item.path.decode('utf-8') + '\n', + playlist.read().decode('utf-8')) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 3ad02e1a748531329484ec066c6caea008b1f7f6 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:35:38 -0800 Subject: [PATCH 0364/2280] Remove duplicate code --- test/test_play.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 4a57decfb..53f108343 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -26,9 +26,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', 'title:aNiceTitle') open_mock.assert_called_once_with(ANY, None) - playlist = open(open_mock.call_args[0][0][0], 'r') - self.assertEqual(self.item.path.decode('utf-8') + '\n', - playlist.read().decode('utf-8')) + self.assertPlaylistCorrect(open_mock) @patch('beetsplug.play.util.interactive_open') def test_args_option(self, open_mock): @@ -36,9 +34,13 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', '-A', 'foo', 'title:aNiceTitle') open_mock.assert_called_once_with(ANY, 'true foo') + self.assertPlaylistCorrect(open_mock) + + def assertPlaylistCorrect(self, open_mock): playlist = open(open_mock.call_args[0][0][0], 'r') self.assertEqual(self.item.path.decode('utf-8') + '\n', playlist.read().decode('utf-8')) + def suite(): From 6b49b0ff238b2f52f6f061e60d385f4bae11c4a9 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:40:52 -0800 Subject: [PATCH 0365/2280] add test for $args --- test/test_play.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/test_play.py b/test/test_play.py index 53f108343..99382a00a 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -36,11 +36,18 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_called_once_with(ANY, 'true foo') self.assertPlaylistCorrect(open_mock) + @patch('beetsplug.play.util.interactive_open') + def test_args_option_in_middle(self, open_mock): + self.config['play']['command'] = 'true $args other' + self.run_command('play', '-A', 'foo', 'title:aNiceTitle') + + open_mock.assert_called_once_with(ANY, 'true foo other') + self.assertPlaylistCorrect(open_mock) + def assertPlaylistCorrect(self, open_mock): playlist = open(open_mock.call_args[0][0][0], 'r') self.assertEqual(self.item.path.decode('utf-8') + '\n', playlist.read().decode('utf-8')) - def suite(): From a47de98653d2ff62ee6780983c48078a10d83d5c Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 2 Jan 2016 23:54:29 -0800 Subject: [PATCH 0366/2280] add relative_to test --- test/test_play.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 99382a00a..07bf64c0d 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -30,23 +30,32 @@ class PlayPluginTest(unittest.TestCase, TestHelper): @patch('beetsplug.play.util.interactive_open') def test_args_option(self, open_mock): - self.config['play']['command'] = 'true' + self.config['play']['command'] = 'echo' self.run_command('play', '-A', 'foo', 'title:aNiceTitle') - open_mock.assert_called_once_with(ANY, 'true foo') + open_mock.assert_called_once_with(ANY, 'echo foo') self.assertPlaylistCorrect(open_mock) @patch('beetsplug.play.util.interactive_open') def test_args_option_in_middle(self, open_mock): - self.config['play']['command'] = 'true $args other' + self.config['play']['command'] = 'echo $args other' self.run_command('play', '-A', 'foo', 'title:aNiceTitle') - open_mock.assert_called_once_with(ANY, 'true foo other') + open_mock.assert_called_once_with(ANY, 'echo foo other') self.assertPlaylistCorrect(open_mock) - def assertPlaylistCorrect(self, open_mock): + @patch('beetsplug.play.util.interactive_open') + def test_relative_to(self, open_mock): + self.config['play']['command'] = 'echo' + self.config['play']['relative_to'] = '/something' + self.run_command('play', 'title:aNiceTitle') + + open_mock.assert_called_once_with(ANY, 'echo') + self.assertPlaylistCorrect(open_mock, '..{}\n') + + def assertPlaylistCorrect(self, open_mock, expected='{}\n'): playlist = open(open_mock.call_args[0][0][0], 'r') - self.assertEqual(self.item.path.decode('utf-8') + '\n', + self.assertEqual(expected.format(self.item.path.decode('utf-8')), playlist.read().decode('utf-8')) From 6ad0c8a490f87cb46899f0a1c11ca6e4000c2afb Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 00:05:49 -0800 Subject: [PATCH 0367/2280] Add album option test --- test/test_play.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 07bf64c0d..d007978f4 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -11,24 +11,30 @@ from test._common import unittest from test.helper import TestHelper +@patch('beetsplug.play.util.interactive_open') class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('play') - self.item = self.add_item(title='aNiceTitle') + self.item = self.add_item(album='a nice älbum', title='aNiceTitle') + self.lib.add_album([self.item]) def tearDown(self): self.teardown_beets() self.unload_plugins() - @patch('beetsplug.play.util.interactive_open') def test_basic(self, open_mock): self.run_command('play', 'title:aNiceTitle') open_mock.assert_called_once_with(ANY, None) self.assertPlaylistCorrect(open_mock) - @patch('beetsplug.play.util.interactive_open') + def test_album_option(self, open_mock): + self.run_command('play', '-a', 'nice') + + open_mock.assert_called_once_with(ANY, None) + self.assertPlaylistCorrect(open_mock) + def test_args_option(self, open_mock): self.config['play']['command'] = 'echo' self.run_command('play', '-A', 'foo', 'title:aNiceTitle') @@ -36,7 +42,6 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_called_once_with(ANY, 'echo foo') self.assertPlaylistCorrect(open_mock) - @patch('beetsplug.play.util.interactive_open') def test_args_option_in_middle(self, open_mock): self.config['play']['command'] = 'echo $args other' self.run_command('play', '-A', 'foo', 'title:aNiceTitle') @@ -44,7 +49,6 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_called_once_with(ANY, 'echo foo other') self.assertPlaylistCorrect(open_mock) - @patch('beetsplug.play.util.interactive_open') def test_relative_to(self, open_mock): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' From 4a1a70e23d2db0f5a51adbba092fb28ebd24c13f Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 00:18:02 -0800 Subject: [PATCH 0368/2280] add 3 more tests --- test/test_play.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/test_play.py b/test/test_play.py index d007978f4..4166c895f 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -5,6 +5,8 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) +import os + from mock import patch, ANY from test._common import unittest @@ -35,6 +37,16 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_called_once_with(ANY, None) self.assertPlaylistCorrect(open_mock) + def test_use_folders(self, open_mock): + self.config['play']['use_folders'] = True + self.run_command('play', '-a', 'nice') + + open_mock.assert_called_once_with(ANY, None) + playlist = open(open_mock.call_args[0][0][0], 'r') + self.assertEqual('{}\n'.format( + os.path.dirname(self.item.path.decode('utf-8'))), + playlist.read().decode('utf-8')) + def test_args_option(self, open_mock): self.config['play']['command'] = 'echo' self.run_command('play', '-A', 'foo', 'title:aNiceTitle') @@ -57,6 +69,16 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_called_once_with(ANY, 'echo') self.assertPlaylistCorrect(open_mock, '..{}\n') + def test_raw(self, open_mock): + self.config['play']['raw'] = True + self.run_command('play', 'nice') + + open_mock.assert_called_once_with([self.item.path], None) + + def test_not_found(self, open_mock): + self.run_command('play', 'not found') + open_mock.assert_not_called() + def assertPlaylistCorrect(self, open_mock, expected='{}\n'): playlist = open(open_mock.call_args[0][0][0], 'r') self.assertEqual(expected.format(self.item.path.decode('utf-8')), From 7f372a6a59c748992b58c4d419c1b0ddb8ec018e Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 09:48:22 -0800 Subject: [PATCH 0369/2280] Add last 2 tests -- 100% line coverage --- test/test_play.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/test/test_play.py b/test/test_play.py index 4166c895f..6d0986102 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -10,8 +10,9 @@ import os from mock import patch, ANY from test._common import unittest -from test.helper import TestHelper +from test.helper import TestHelper, control_stdin +from beets.ui import UserError @patch('beetsplug.play.util.interactive_open') class PlayPluginTest(unittest.TestCase, TestHelper): @@ -79,6 +80,19 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', 'not found') open_mock.assert_not_called() + def test_warning_threshold(self, open_mock): + self.config['play']['warning_treshold'] = 1 + item2 = self.add_item(title='another NiceTitle') + with control_stdin("a"): + self.run_command('play', 'nice') + + open_mock.assert_not_called() + + def test_command_failed(self, open_mock): + open_mock.side_effect = OSError("some reason") + with self.assertRaises(UserError): + self.run_command('play', 'title:aNiceTitle') + def assertPlaylistCorrect(self, open_mock, expected='{}\n'): playlist = open(open_mock.call_args[0][0][0], 'r') self.assertEqual(expected.format(self.item.path.decode('utf-8')), From 989b4719a6108c0d9fea6c7fafde198a2b2a34e3 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 11:07:02 -0800 Subject: [PATCH 0370/2280] Rearrange test_play.py to minimize duplication --- test/test_play.py | 64 +++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 35 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 6d0986102..cccf1fbc1 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -26,17 +26,35 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def test_basic(self, open_mock): - self.run_command('play', 'title:aNiceTitle') + def do_test(self, open_mock, args=('title:aNiceTitle',), expected_cmd=None, expected_playlist='{}\n'): + self.run_command('play', *args) - open_mock.assert_called_once_with(ANY, None) - self.assertPlaylistCorrect(open_mock) + open_mock.assert_called_once_with(ANY, expected_cmd) + expected_playlist_content = expected_playlist.format(self.item.path.decode('utf-8')) + with open(open_mock.call_args[0][0][0], 'r') as playlist: + self.assertEqual(expected_playlist_content, playlist.read().decode('utf-8')) + + def test_basic(self, open_mock): + self.do_test(open_mock) def test_album_option(self, open_mock): - self.run_command('play', '-a', 'nice') + self.do_test(open_mock, ['-a', 'nice']) - open_mock.assert_called_once_with(ANY, None) - self.assertPlaylistCorrect(open_mock) + def test_args_option(self, open_mock): + self.config['play']['command'] = 'echo' + + self.do_test(open_mock, ['-A', 'foo', 'title:aNiceTitle'], 'echo foo') + + def test_args_option_in_middle(self, open_mock): + self.config['play']['command'] = 'echo $args other' + + self.do_test(open_mock, ['-A', 'foo', 'title:aNiceTitle'], 'echo foo other') + + def test_relative_to(self, open_mock): + self.config['play']['command'] = 'echo' + self.config['play']['relative_to'] = '/something' + + self.do_test(open_mock, expected_cmd='echo', expected_playlist='..{}\n') def test_use_folders(self, open_mock): self.config['play']['use_folders'] = True @@ -48,41 +66,22 @@ class PlayPluginTest(unittest.TestCase, TestHelper): os.path.dirname(self.item.path.decode('utf-8'))), playlist.read().decode('utf-8')) - def test_args_option(self, open_mock): - self.config['play']['command'] = 'echo' - self.run_command('play', '-A', 'foo', 'title:aNiceTitle') - - open_mock.assert_called_once_with(ANY, 'echo foo') - self.assertPlaylistCorrect(open_mock) - - def test_args_option_in_middle(self, open_mock): - self.config['play']['command'] = 'echo $args other' - self.run_command('play', '-A', 'foo', 'title:aNiceTitle') - - open_mock.assert_called_once_with(ANY, 'echo foo other') - self.assertPlaylistCorrect(open_mock) - - def test_relative_to(self, open_mock): - self.config['play']['command'] = 'echo' - self.config['play']['relative_to'] = '/something' - self.run_command('play', 'title:aNiceTitle') - - open_mock.assert_called_once_with(ANY, 'echo') - self.assertPlaylistCorrect(open_mock, '..{}\n') - def test_raw(self, open_mock): self.config['play']['raw'] = True + self.run_command('play', 'nice') open_mock.assert_called_once_with([self.item.path], None) def test_not_found(self, open_mock): self.run_command('play', 'not found') + open_mock.assert_not_called() def test_warning_threshold(self, open_mock): self.config['play']['warning_treshold'] = 1 item2 = self.add_item(title='another NiceTitle') + with control_stdin("a"): self.run_command('play', 'nice') @@ -90,15 +89,10 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def test_command_failed(self, open_mock): open_mock.side_effect = OSError("some reason") + with self.assertRaises(UserError): self.run_command('play', 'title:aNiceTitle') - def assertPlaylistCorrect(self, open_mock, expected='{}\n'): - playlist = open(open_mock.call_args[0][0][0], 'r') - self.assertEqual(expected.format(self.item.path.decode('utf-8')), - playlist.read().decode('utf-8')) - - def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 4d55c5bf7e234e15a118b9376af3cad269fc9813 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 11:14:24 -0800 Subject: [PATCH 0371/2280] Do patching in setUp --- test/test_play.py | 52 ++++++++++++++++++++++++----------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index cccf1fbc1..3c04ab269 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -14,81 +14,83 @@ from test.helper import TestHelper, control_stdin from beets.ui import UserError -@patch('beetsplug.play.util.interactive_open') class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('play') self.item = self.add_item(album='a nice älbum', title='aNiceTitle') self.lib.add_album([self.item]) + self.open_patcher = patch('beetsplug.play.util.interactive_open') + self.open_mock = self.open_patcher.start() def tearDown(self): + self.open_patcher.stop() self.teardown_beets() self.unload_plugins() - def do_test(self, open_mock, args=('title:aNiceTitle',), expected_cmd=None, expected_playlist='{}\n'): + def do_test(self, args=('title:aNiceTitle',), expected_cmd=None, expected_playlist='{}\n'): self.run_command('play', *args) - open_mock.assert_called_once_with(ANY, expected_cmd) + self.open_mock.assert_called_once_with(ANY, expected_cmd) expected_playlist_content = expected_playlist.format(self.item.path.decode('utf-8')) - with open(open_mock.call_args[0][0][0], 'r') as playlist: + with open(self.open_mock.call_args[0][0][0], 'r') as playlist: self.assertEqual(expected_playlist_content, playlist.read().decode('utf-8')) - def test_basic(self, open_mock): - self.do_test(open_mock) + def test_basic(self): + self.do_test() - def test_album_option(self, open_mock): - self.do_test(open_mock, ['-a', 'nice']) + def test_album_option(self): + self.do_test(['-a', 'nice']) - def test_args_option(self, open_mock): + def test_args_option(self): self.config['play']['command'] = 'echo' - self.do_test(open_mock, ['-A', 'foo', 'title:aNiceTitle'], 'echo foo') + self.do_test(['-A', 'foo', 'title:aNiceTitle'], 'echo foo') - def test_args_option_in_middle(self, open_mock): + def test_args_option_in_middle(self): self.config['play']['command'] = 'echo $args other' - self.do_test(open_mock, ['-A', 'foo', 'title:aNiceTitle'], 'echo foo other') + self.do_test(['-A', 'foo', 'title:aNiceTitle'], 'echo foo other') - def test_relative_to(self, open_mock): + def test_relative_to(self): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' - self.do_test(open_mock, expected_cmd='echo', expected_playlist='..{}\n') + self.do_test(expected_cmd='echo', expected_playlist='..{}\n') - def test_use_folders(self, open_mock): + def test_use_folders(self): self.config['play']['use_folders'] = True self.run_command('play', '-a', 'nice') - open_mock.assert_called_once_with(ANY, None) - playlist = open(open_mock.call_args[0][0][0], 'r') + self.open_mock.assert_called_once_with(ANY, None) + playlist = open(self.open_mock.call_args[0][0][0], 'r') self.assertEqual('{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), playlist.read().decode('utf-8')) - def test_raw(self, open_mock): + def test_raw(self): self.config['play']['raw'] = True self.run_command('play', 'nice') - open_mock.assert_called_once_with([self.item.path], None) + self.open_mock.assert_called_once_with([self.item.path], None) - def test_not_found(self, open_mock): + def test_not_found(self): self.run_command('play', 'not found') - open_mock.assert_not_called() + self.open_mock.assert_not_called() - def test_warning_threshold(self, open_mock): + def test_warning_threshold(self): self.config['play']['warning_treshold'] = 1 item2 = self.add_item(title='another NiceTitle') with control_stdin("a"): self.run_command('play', 'nice') - open_mock.assert_not_called() + self.open_mock.assert_not_called() - def test_command_failed(self, open_mock): - open_mock.side_effect = OSError("some reason") + def test_command_failed(self): + self.open_mock.side_effect = OSError("some reason") with self.assertRaises(UserError): self.run_command('play', 'title:aNiceTitle') From dfce9e19aaf9af7088b344b518392fec0e50650e Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 13:11:30 -0800 Subject: [PATCH 0372/2280] Fix tests due to change in default command behavior --- test/test_play.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 3c04ab269..6d1f977f3 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -13,6 +13,7 @@ from test._common import unittest from test.helper import TestHelper, control_stdin from beets.ui import UserError +from beets.util import open_anything class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): @@ -22,13 +23,14 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.lib.add_album([self.item]) self.open_patcher = patch('beetsplug.play.util.interactive_open') self.open_mock = self.open_patcher.start() + self.config['play']['command'] = 'echo' def tearDown(self): self.open_patcher.stop() self.teardown_beets() self.unload_plugins() - def do_test(self, args=('title:aNiceTitle',), expected_cmd=None, expected_playlist='{}\n'): + def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', expected_playlist='{}\n'): self.run_command('play', *args) self.open_mock.assert_called_once_with(ANY, expected_cmd) @@ -43,8 +45,6 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.do_test(['-a', 'nice']) def test_args_option(self): - self.config['play']['command'] = 'echo' - self.do_test(['-A', 'foo', 'title:aNiceTitle'], 'echo foo') def test_args_option_in_middle(self): @@ -59,10 +59,11 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.do_test(expected_cmd='echo', expected_playlist='..{}\n') def test_use_folders(self): + self.config['play']['command'] = None self.config['play']['use_folders'] = True self.run_command('play', '-a', 'nice') - self.open_mock.assert_called_once_with(ANY, None) + self.open_mock.assert_called_once_with(ANY, open_anything()) playlist = open(self.open_mock.call_args[0][0][0], 'r') self.assertEqual('{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), @@ -73,7 +74,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', 'nice') - self.open_mock.assert_called_once_with([self.item.path], None) + self.open_mock.assert_called_once_with([self.item.path], 'echo') def test_not_found(self): self.run_command('play', 'not found') From 875876fd1d8738f4c901ba63f849f5c3b71c0b02 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 16:49:51 -0800 Subject: [PATCH 0373/2280] flake8 fixes --- test/test_play.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 6d1f977f3..f17d72840 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -15,6 +15,7 @@ from test.helper import TestHelper, control_stdin from beets.ui import UserError from beets.util import open_anything + class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() @@ -30,13 +31,14 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', expected_playlist='{}\n'): + def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', + expected_playlist='{}\n'): self.run_command('play', *args) self.open_mock.assert_called_once_with(ANY, expected_cmd) - expected_playlist_content = expected_playlist.format(self.item.path.decode('utf-8')) + exp_playlist = expected_playlist.format(self.item.path.decode('utf-8')) with open(self.open_mock.call_args[0][0][0], 'r') as playlist: - self.assertEqual(expected_playlist_content, playlist.read().decode('utf-8')) + self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) def test_basic(self): self.do_test() @@ -83,7 +85,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def test_warning_threshold(self): self.config['play']['warning_treshold'] = 1 - item2 = self.add_item(title='another NiceTitle') + self.add_item(title='another NiceTitle') with control_stdin("a"): self.run_command('play', 'nice') @@ -96,6 +98,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): with self.assertRaises(UserError): self.run_command('play', 'title:aNiceTitle') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 6ba92be18db9a195c61a0e6b4633fc6a1ae2ec8a Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 3 Jan 2016 23:34:16 -0800 Subject: [PATCH 0374/2280] Add std license header --- test/test_play.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/test_play.py b/test/test_play.py index f17d72840..d25d7b657 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Jesse Weinstein +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. """Tests for the play plugin""" From 4d07e45732848f79d6614181ff7bc1d1b29b5576 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Mon, 4 Jan 2016 01:51:49 -0800 Subject: [PATCH 0375/2280] Bring test_ftintitle up to 94% Just need a test for importing. --- test/test_ftintitle.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index c02424dbe..481917f85 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -36,6 +36,7 @@ class FtInTitlePluginFunctional(unittest.TestCase, TestHelper): def _ft_add_item(self, path, artist, title, aartist): return self.add_item(path=path, artist=artist, + artist_sort=artist, title=title, albumartist=aartist) @@ -51,6 +52,14 @@ class FtInTitlePluginFunctional(unittest.TestCase, TestHelper): self.assertEqual(item['artist'], u'Alice') self.assertEqual(item['title'], u'Song 1') + def test_functional_not_found(self): + item = self._ft_add_item('/', u'Alice ft Bob', u'Song 1', u'George') + self.run_command('ftintitle', '-d') + item.load() + # item should be unchanged + self.assertEqual(item['artist'], u'Alice ft Bob') + self.assertEqual(item['title'], u'Song 1') + def test_functional_custom_format(self): self._ft_set_config('feat. {0}') item = self._ft_add_item('/', u'Alice ft Bob', u'Song 1', u'Alice') @@ -126,6 +135,11 @@ class FtInTitlePluginTest(unittest.TestCase): 'album_artist': 'Bob', 'feat_part': 'Alice' }, + { + 'artist': 'Alice ft. Carol', + 'album_artist': 'Bob', + 'feat_part': None + }, ] for test_case in test_cases: From 0a6983b7595497ecea375890d7acb021f0ce0994 Mon Sep 17 00:00:00 2001 From: Ben Ockmore Date: Mon, 4 Jan 2016 17:29:08 +0000 Subject: [PATCH 0376/2280] Replaced custom requests in fetch_tracks with pylast Also changed from using the library.getTracks API method to user.getTopTracks, since Last.fm has broken the former. --- beetsplug/lastimport.py | 108 +++++++++++++++++++++++++++++++++------- 1 file changed, 89 insertions(+), 19 deletions(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index ba1fd7de8..2b4ac5035 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -16,7 +16,8 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) -import requests +import pylast +from pylast import TopItem, _extract, _number from beets import ui from beets import dbcore from beets import config @@ -52,6 +53,63 @@ class LastImportPlugin(plugins.BeetsPlugin): return [cmd] +class CustomUser(pylast.User): + """ Custom user class derived from pylast.User, and overriding the + _get_things method to return MBID and album. Also introduces new + get_top_tracks_by_page method to allow access to more than one page of top + tracks. + """ + def __init__(self, *args, **kwargs): + super(CustomUser, self).__init__(*args, **kwargs) + + def _get_things(self, method, thing, thing_type, params=None, + cacheable=True): + """Returns a list of the most played thing_types by this thing, in a + tuple with the total number of pages of results. Includes an MBID, if + found. + """ + doc = self._request( + self.ws_prefix + "." + method, cacheable, params) + + toptracks_node = doc.getElementsByTagName('toptracks')[0] + total_pages = int(toptracks_node.getAttribute('totalPages')) + + seq = [] + for node in doc.getElementsByTagName(thing): + title = _extract(node, "name") + artist = _extract(node, "name", 1) + mbid = _extract(node, "mbid") + playcount = _number(_extract(node, "playcount")) + + thing = thing_type(artist, title, self.network) + thing.mbid = mbid + seq.append(TopItem(thing, playcount)) + + return seq, total_pages + + def get_top_tracks_by_page(self, period=pylast.PERIOD_OVERALL, limit=None, + page=1, cacheable=True): + """Returns the top tracks played by a user, in a tuple with the total + number of pages of results. + * period: The period of time. Possible values: + o PERIOD_OVERALL + o PERIOD_7DAYS + o PERIOD_1MONTH + o PERIOD_3MONTHS + o PERIOD_6MONTHS + o PERIOD_12MONTHS + """ + + params = self._get_params() + params['period'] = period + params['page'] = page + if limit: + params['limit'] = limit + + return self._get_things( + "getTopTracks", "track", pylast.Track, params, cacheable) + + def import_lastfm(lib, log): user = config['lastfm']['user'].get(unicode) per_page = config['lastimport']['per_page'].get(int) @@ -73,23 +131,19 @@ def import_lastfm(lib, log): '/{}'.format(page_total) if page_total > 1 else '') for retry in range(0, retry_limit): - page = fetch_tracks(user, page_current + 1, per_page) - if 'tracks' in page: - # Let us the reveal the holy total pages! - page_total = int(page['tracks']['@attr']['totalPages']) - if page_total < 1: - # It means nothing to us! - raise ui.UserError('Last.fm reported no data.') + tracks, page_total = fetch_tracks(user, page_current + 1, per_page) + if page_total < 1: + # It means nothing to us! + raise ui.UserError('Last.fm reported no data.') - track = page['tracks']['track'] - found, unknown = process_tracks(lib, track, log) + if tracks: + found, unknown = process_tracks(lib, tracks, log) found_total += found unknown_total += unknown break else: log.error('ERROR: unable to read page #{0}', page_current + 1) - log.debug('API response: {}', page) if retry < retry_limit: log.info( 'Retrying page #{0}... ({1}/{2} retry)', @@ -107,14 +161,30 @@ def import_lastfm(lib, log): def fetch_tracks(user, page, limit): - return requests.get(API_URL, params={ - 'method': 'library.gettracks', - 'user': user, - 'api_key': plugins.LASTFM_KEY, - 'page': bytes(page), - 'limit': bytes(limit), - 'format': 'json', - }).json() + """ JSON format: + [ + { + "mbid": "...", + "artist": "...", + "title": "...", + "playcount": "..." + } + ] + """ + network = pylast.LastFMNetwork(api_key=config['lastfm']['api_key']) + user_obj = CustomUser(user, network) + results, total_pages =\ + user_obj.get_top_tracks_by_page(limit=limit, page=page) + return [ + { + "mbid": track.item.mbid if track.item.mbid else '', + "artist": { + "name": track.item.artist.name + }, + "name": track.item.title, + "playcount": track.weight + } for track in results + ], total_pages def process_tracks(lib, tracks, log): From e2a8bdb23d0d377590104475e6e762058461d612 Mon Sep 17 00:00:00 2001 From: Ben Ockmore Date: Mon, 4 Jan 2016 17:33:03 +0000 Subject: [PATCH 0377/2280] Changed initial value of song variable to None, which is clearer --- beetsplug/lastimport.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 2b4ac5035..a85a1a30d 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -194,7 +194,7 @@ def process_tracks(lib, tracks, log): log.info('Received {0} tracks in this page, processing...', total) for num in xrange(0, total): - song = '' + song = None trackid = tracks[num]['mbid'].strip() artist = tracks[num]['artist'].get('name', '').strip() title = tracks[num]['name'].strip() @@ -211,7 +211,7 @@ def process_tracks(lib, tracks, log): ).get() # Otherwise try artist/title/album - if not song: + if song is None: log.debug(u'no match for mb_trackid {0}, trying by ' u'artist/title/album', trackid) query = dbcore.AndQuery([ @@ -222,7 +222,7 @@ def process_tracks(lib, tracks, log): song = lib.items(query).get() # If not, try just artist/title - if not song: + if song is None: log.debug(u'no album match, trying by artist/title') query = dbcore.AndQuery([ dbcore.query.SubstringQuery('artist', artist), @@ -231,7 +231,7 @@ def process_tracks(lib, tracks, log): song = lib.items(query).get() # Last resort, try just replacing to utf-8 quote - if not song: + if song is None: title = title.replace("'", u'\u2019') log.debug(u'no title match, trying utf-8 single quote') query = dbcore.AndQuery([ @@ -240,7 +240,7 @@ def process_tracks(lib, tracks, log): ]) song = lib.items(query).get() - if song: + if song is not None: count = int(song.get('play_count', 0)) new_count = int(tracks[num]['playcount']) log.debug(u'match: {0} - {1} ({2}) ' From c074ed37f14b0ff58526effcf45c02e2cfca2d26 Mon Sep 17 00:00:00 2001 From: Ben Ockmore Date: Mon, 4 Jan 2016 17:36:30 +0000 Subject: [PATCH 0378/2280] Album is never present in user.getTopTracks, so this is now redundant --- beetsplug/lastimport.py | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index a85a1a30d..38b5bfc10 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -210,17 +210,6 @@ def process_tracks(lib, tracks, log): dbcore.query.MatchQuery('mb_trackid', trackid) ).get() - # Otherwise try artist/title/album - if song is None: - log.debug(u'no match for mb_trackid {0}, trying by ' - u'artist/title/album', trackid) - query = dbcore.AndQuery([ - dbcore.query.SubstringQuery('artist', artist), - dbcore.query.SubstringQuery('title', title), - dbcore.query.SubstringQuery('album', album) - ]) - song = lib.items(query).get() - # If not, try just artist/title if song is None: log.debug(u'no album match, trying by artist/title') From 70c399f0b122cd7fa5fa66562a4ef932f1cb0dc9 Mon Sep 17 00:00:00 2001 From: Ben Ockmore Date: Mon, 4 Jan 2016 17:42:15 +0000 Subject: [PATCH 0379/2280] Updated lastimport installation instructions --- docs/plugins/lastimport.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index 7d8ede891..cfa66bbef 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -9,10 +9,12 @@ with this field. Installation ------------ -To use the ``lastimport`` plugin, first enable it in your configuration (see -:ref:`using-plugins`). Then install the `requests`_ library by typing:: +The plugin requires `pylast`_, which you can install using `pip`_ by typing:: - pip install requests + pip install pylast + +After you have pylast installed, enable the ``lastimport`` plugin in your +configuration (see :ref:`using-plugins`). Next, add your Last.fm username to your beets configuration file:: From a218da1414d18042b03eca46d86353da8da478cf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 4 Jan 2016 11:26:57 -0800 Subject: [PATCH 0380/2280] A bunch of docs on query parsing (fix #1794) --- beets/dbcore/queryparse.py | 89 +++++++++++++++++++++++++------------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index b421ebf40..fbc4626f5 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -39,32 +39,49 @@ PARSE_QUERY_PART_REGEX = re.compile( def parse_query_part(part, query_classes={}, prefixes={}, default_class=query.SubstringQuery): - """Take a query in the form of a key/value pair separated by a - colon and return a tuple of `(key, value, cls, negate)`. `key` may be None, - indicating that any field may be matched. `cls` is a subclass of - `FieldQuery`. `negate` is a boolean indicating if the query is negated. + """Parse a single *query part*, which is a chunk of a complete query + string representing a single criterion. - The optional `query_classes` parameter maps field names to default - query types; `default_class` is the fallback. `prefixes` is a map - from query prefix markers and query types. Prefix-indicated queries - take precedence over type-based queries. + A query part is a string consisting of: + - A *pattern*: the value to look for. + - Optionally, a *field name* preceding the pattern, separated by a + colon. So in `foo:bar`, `foo` is the field name and `bar` is the + pattern. + - Optionally, a *query prefix* just before the field (and after the + optional colon) indicating the type of query that should be used. For + example, in `~foo`, `~` might be a prefix. (The set of prefixes to + look for is given in the `prefixes` parameter.) + - Optionally, a negation indicator, `-` or `^`, at the very beginning. - To determine the query class, two factors are used: prefixes and - field types. For example, the colon prefix denotes a regular - expression query and a type map might provide a special kind of - query for numeric values. If neither a prefix nor a specific query - class is available, `default_class` is used. + Both prefixes and the separating `:` character may be escaped with a + backslash to avoid their normal meaning. - For instance, - 'stapler' -> (None, 'stapler', SubstringQuery, False) - 'color:red' -> ('color', 'red', SubstringQuery, False) - ':^Quiet' -> (None, '^Quiet', RegexpQuery, False) - 'color::b..e' -> ('color', 'b..e', RegexpQuery, False) - '-color:red' -> ('color', 'red', SubstringQuery, True) + The function returns a tuple consisting of: + - The field name: a string or None if it's not present. + - The pattern, a string. + - The query class to use, which inherits from the base + :class:`Query` type. + - A negation flag, a bool. - Prefixes may be "escaped" with a backslash to disable the keying - behavior. + The three optional parameters determine which query class is used (i.e., + the third return value). They are: + - `query_classes`, which maps field names to query classes. These + are used when no explicit prefix is present. + - `prefixes`, which maps prefix strings to query classes. + - `default_class`, the fallback when neither the field nor a prefix + indicates a query class. + + So the precedence for determining which query class to return is: + prefix, followed by field, and finally the default. + + For example, assuming the `:` prefix is used for `RegexpQuery`: + - `'stapler'` -> `(None, 'stapler', SubstringQuery, False)` + - `'color:red'` -> `('color', 'red', SubstringQuery, False)` + - `':^Quiet'` -> `(None, '^Quiet', RegexpQuery, False)` + - `'color::b..e'` -> `('color', 'b..e', RegexpQuery, False)` + - `'-color:red'` -> `('color', 'red', SubstringQuery, True)` """ + # Apply the regular expression and extract the components. part = part.strip() match = PARSE_QUERY_PART_REGEX.match(part) @@ -73,25 +90,36 @@ def parse_query_part(part, query_classes={}, prefixes={}, key = match.group(2) term = match.group(3).replace('\:', ':') - # Match the search term against the list of prefixes. + # Check whether there's a prefix in the query and use the + # corresponding query type. for pre, query_class in prefixes.items(): if term.startswith(pre): return key, term[len(pre):], query_class, negate - # No matching prefix: use type-based or fallback/default query. + # No matching prefix, so use either the query class determined by + # the field or the default as a fallback. query_class = query_classes.get(key, default_class) return key, term, query_class, negate def construct_query_part(model_cls, prefixes, query_part): - """Create a query from a single query component, `query_part`, for - querying instances of `model_cls`. Return a `Query` instance. + """Parse a *query part* string and return a :class:`Query` object. + + :param model_cls: The :class:`Model` class that this is a query for. + This is used to determine the appropriate query types for the + model's fields. + :param prefixes: A map from prefix strings to :class:`Query` types. + :param query_part: The string to parse. + + See the documentation for `parse_query_part` for more information on + query part syntax. """ - # Shortcut for empty query parts. + # A shortcut for empty query parts. if not query_part: return query.TrueQuery() - # Get the query classes for each possible field. + # Use `model_cls` to build up a map from field names to `Query` + # classes. query_classes = {} for k, t in itertools.chain(model_cls._fields.items(), model_cls._types.items()): @@ -101,7 +129,8 @@ def construct_query_part(model_cls, prefixes, query_part): key, pattern, query_class, negate = \ parse_query_part(query_part, query_classes, prefixes) - # No key specified. + # If there's no key (field name) specified, this is a "match + # anything" query. if key is None: if issubclass(query_class, query.FieldQuery): # The query type matches a specific field, but none was @@ -114,12 +143,14 @@ def construct_query_part(model_cls, prefixes, query_part): else: return q else: - # Other query type. + # Non-field query type. if negate: return query.NotQuery(query_class(pattern)) else: return query_class(pattern) + # Otherwise, this must be a `FieldQuery`. Use the field name to + # construct the query object. key = key.lower() q = query_class(key.lower(), pattern, key in model_cls._fields) if negate: From ed3d6b81a50fcee2b298609bfcb771f0100511fa Mon Sep 17 00:00:00 2001 From: Ben Ockmore Date: Mon, 4 Jan 2016 21:15:25 +0000 Subject: [PATCH 0381/2280] Fixed documentation build error, and added lastimport fix info to changelog --- docs/changelog.rst | 4 ++++ docs/plugins/lastimport.rst | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b18468d6d..5b35a66b6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -29,6 +29,10 @@ Fixes: anymore. :bug:`1583` * :doc:`/plugins/play`: Fix a regression in the last version where there was no default command. :bug:`1793` +* :doc:`/plugins/lastimport`: Switched API method from library.getTracks to + user.getTopTracks. This fixes :bug:`1574`, which was caused by the former API + method being removed. Also moved from custom HTTP requests to using pylast + library. 1.3.16 (December 28, 2015) diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index cfa66bbef..a38447083 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -6,6 +6,8 @@ library into beets' database. You can later create :doc:`smart playlists ` by querying ``play_count`` and do other fun stuff with this field. +.. _Last.fm: http://last.fm + Installation ------------ @@ -21,8 +23,8 @@ Next, add your Last.fm username to your beets configuration file:: lastfm: user: beetsfanatic -.. _requests: http://docs.python-requests.org/en/latest/ -.. _Last.fm: http://last.fm +.. _pip: http://www.pip-installer.org/ +.. _pylast: http://code.google.com/p/pylast/ Importing Play Counts --------------------- From d064f191298415e21285637bc98f53aa388cc292 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 4 Jan 2016 18:49:14 -0800 Subject: [PATCH 0382/2280] Fix wrong word in docstring (#1794) --- beets/dbcore/queryparse.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index fbc4626f5..99218d625 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -47,7 +47,7 @@ def parse_query_part(part, query_classes={}, prefixes={}, - Optionally, a *field name* preceding the pattern, separated by a colon. So in `foo:bar`, `foo` is the field name and `bar` is the pattern. - - Optionally, a *query prefix* just before the field (and after the + - Optionally, a *query prefix* just before the pattern (and after the optional colon) indicating the type of query that should be used. For example, in `~foo`, `~` might be a prefix. (The set of prefixes to look for is given in the `prefixes` parameter.) From dd66ca51f96c954504c43a134e63a203b2793d20 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 4 Jan 2016 22:08:27 -0800 Subject: [PATCH 0383/2280] Detail on example (#1794) --- beets/dbcore/queryparse.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 99218d625..bc9cc77ec 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -77,7 +77,8 @@ def parse_query_part(part, query_classes={}, prefixes={}, For example, assuming the `:` prefix is used for `RegexpQuery`: - `'stapler'` -> `(None, 'stapler', SubstringQuery, False)` - `'color:red'` -> `('color', 'red', SubstringQuery, False)` - - `':^Quiet'` -> `(None, '^Quiet', RegexpQuery, False)` + - `':^Quiet'` -> `(None, '^Quiet', RegexpQuery, False)`, because + the `^` follows the `:` - `'color::b..e'` -> `('color', 'b..e', RegexpQuery, False)` - `'-color:red'` -> `('color', 'red', SubstringQuery, True)` """ From edefc1373e0ecc27e0f33ed2cbf24443df421141 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Mon, 4 Jan 2016 23:42:14 -0800 Subject: [PATCH 0384/2280] Bring test_permissions.py up to 100% --- test/test_permissions.py | 54 +++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index 479c5e5af..eb2c49f42 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -5,6 +5,9 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) +import os +from mock import patch, Mock + from test._common import unittest from test.helper import TestHelper from beetsplug.permissions import (check_permissions, @@ -26,45 +29,40 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.unload_plugins() def test_permissions_on_album_imported(self): - self.importer = self.create_importer() - self.importer.run() - item = self.lib.items().get() - - file_perm = self.config['permissions']['file'].get() - file_perm = convert_perm(file_perm) - - dir_perm = self.config['permissions']['dir'].get() - dir_perm = convert_perm(dir_perm) - - music_dirs = dirs_in_library(self.lib.directory, item.path) - - self.assertTrue(check_permissions(item.path, file_perm)) - self.assertFalse(check_permissions(item.path, convert_perm(644))) - - for path in music_dirs: - self.assertTrue(check_permissions(path, dir_perm)) - self.assertFalse(check_permissions(path, convert_perm(644))) + self.do_test(True) def test_permissions_on_item_imported(self): self.config['import']['singletons'] = True + self.do_test(True) + + @patch("os.chmod", Mock()) + def test_failing_to_set_permissions(self): + self.do_test(False) + + def do_test(self, expectSuccess): self.importer = self.create_importer() self.importer.run() item = self.lib.items().get() - file_perm = self.config['permissions']['file'].get() - file_perm = convert_perm(file_perm) + exp_perms = {k: convert_perm(self.config['permissions'][k].get()) + for k in ['file', 'dir']} - dir_perm = self.config['permissions']['dir'].get() - dir_perm = convert_perm(dir_perm) + self.assertPerms(item.path, convert_perm(644), + exp_perms['file'], expectSuccess) - music_dirs = dirs_in_library(self.lib.directory, item.path) + for path in dirs_in_library(self.lib.directory, item.path): + self.assertPerms(path, convert_perm(755), + exp_perms['dir'], expectSuccess) - self.assertTrue(check_permissions(item.path, file_perm)) - self.assertFalse(check_permissions(item.path, convert_perm(644))) + def assertPerms(self, path, old_perms, new_perms, expectSuccess): + for x in [(True, new_perms if expectSuccess else old_perms, '!='), + (False, old_perms if expectSuccess else new_perms, '==')]: + self.assertEqual(x[0], check_permissions(path, x[1]), + msg='{} : {} {} {}'.format( + path, oct(os.stat(path).st_mode), x[2], oct(x[1]))) - for path in music_dirs: - self.assertTrue(check_permissions(path, dir_perm)) - self.assertFalse(check_permissions(path, convert_perm(644))) + def test_convert_perm_from_string(self): + self.assertEqual(convert_perm('10'), 8) def suite(): From 28257db654b07cd39ce77b260b92ebac4970144d Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 5 Jan 2016 00:03:34 -0800 Subject: [PATCH 0385/2280] Add test for help command --- test/test_ui.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index 60cc122df..f774b1f13 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1129,6 +1129,16 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): '--format-album', '$albumartist', 'ls', '-a') self.assertEqual(l, 'the album artist\n') + def test_help(self): + l = self.run_with_output('help') + self.assertIn('Usage:', l) + + l = self.run_with_output('help', 'list') + self.assertIn('Usage:', l) + + with self.assertRaises(ui.UserError): + self.run_command('help', 'this.is.not.a.real.command') + class CommonOptionsParserTest(unittest.TestCase, TestHelper): def setUp(self): From cce2d5450fd91d17033ecdf8cfa4049ccddfc311 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 5 Jan 2016 00:28:43 -0800 Subject: [PATCH 0386/2280] Adjust test_permissions to handle different starting perms --- test/test_permissions.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index eb2c49f42..74c9585a4 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -40,23 +40,28 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.do_test(False) def do_test(self, expectSuccess): + def get_stat(v): + return os.stat( + os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777 self.importer = self.create_importer() + typs = ['file', 'dir'] + self.exp_perms = { + True: {k: convert_perm(self.config['permissions'][k].get()) + for k in typs}, + False: {k: get_stat(v) + for (k, v) in zip(typs, (('album 0', 'track 0.mp3'), ()))}} + self.importer.run() item = self.lib.items().get() - exp_perms = {k: convert_perm(self.config['permissions'][k].get()) - for k in ['file', 'dir']} - - self.assertPerms(item.path, convert_perm(644), - exp_perms['file'], expectSuccess) + self.assertPerms(item.path, 'file', expectSuccess) for path in dirs_in_library(self.lib.directory, item.path): - self.assertPerms(path, convert_perm(755), - exp_perms['dir'], expectSuccess) + self.assertPerms(path, 'dir', expectSuccess) - def assertPerms(self, path, old_perms, new_perms, expectSuccess): - for x in [(True, new_perms if expectSuccess else old_perms, '!='), - (False, old_perms if expectSuccess else new_perms, '==')]: + def assertPerms(self, path, typ, expectSuccess): + for x in [(True, self.exp_perms[expectSuccess][typ], '!='), + (False, self.exp_perms[not expectSuccess][typ], '==')]: self.assertEqual(x[0], check_permissions(path, x[1]), msg='{} : {} {} {}'.format( path, oct(os.stat(path).st_mode), x[2], oct(x[1]))) From 78b81fc8b85bcd62d074c635b5e95a8799649d68 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 5 Jan 2016 00:35:01 -0800 Subject: [PATCH 0387/2280] apparently do_test is a magic name. Who knew? --- test/test_permissions.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index 74c9585a4..c1777ed59 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -29,17 +29,17 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.unload_plugins() def test_permissions_on_album_imported(self): - self.do_test(True) + self.do_thing(True) def test_permissions_on_item_imported(self): self.config['import']['singletons'] = True - self.do_test(True) + self.do_thing(True) @patch("os.chmod", Mock()) def test_failing_to_set_permissions(self): - self.do_test(False) + self.do_thing(False) - def do_test(self, expectSuccess): + def do_thing(self, expectSuccess): def get_stat(v): return os.stat( os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777 From 72056e8e073dabbacb229f2542ccbd47180df010 Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Wed, 6 Jan 2016 09:16:46 +0100 Subject: [PATCH 0388/2280] play: Fix typo treshold > threshold: We should warn users that the corresponding config key changed accordingly. --- beetsplug/play.py | 6 +++--- docs/plugins/play.rst | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 52bf75aa5..b622713c0 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -41,7 +41,7 @@ class PlayPlugin(BeetsPlugin): 'use_folders': False, 'relative_to': None, 'raw': False, - 'warning_treshold': 100, + 'warning_threshold': 100, }) def commands(self): @@ -68,7 +68,7 @@ class PlayPlugin(BeetsPlugin): use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() raw = config['play']['raw'].get(bool) - warning_treshold = config['play']['warning_treshold'].get(int) + warning_threshold = config['play']['warning_threshold'].get(int) if relative_to: relative_to = util.normpath(relative_to) @@ -110,7 +110,7 @@ class PlayPlugin(BeetsPlugin): return # Warn user before playing any huge playlists. - if warning_treshold and len(selection) > warning_treshold: + if warning_threshold and len(selection) > warning_threshold: ui.print_(ui.colorize( 'text_warning', 'You are about to queue {0} {1}.'.format(len(selection), diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 5092ce846..55733cbaa 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -47,7 +47,7 @@ configuration file. The available options are: - **raw**: Instead of creating a temporary m3u playlist and then opening it, simply call the command with the paths returned by the query as arguments. Default: ``no``. -- **warning_treshold**: Set the minimum number of files to play which will +- **warning_threshold**: Set the minimum number of files to play which will trigger a warning to be emitted. If set to ``no``, warning are never issued. Default: 100. From 42ef57f57188f8f3cfc89fd76c31eb99e8fcbb56 Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Wed, 6 Jan 2016 09:49:19 +0100 Subject: [PATCH 0389/2280] play: Fix typo treshold -> threshold My bad, rebased before I pushed and forgot to check the tests after the rebase --- test/test_play.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_play.py b/test/test_play.py index d25d7b657..2c2c076de 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -97,7 +97,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.open_mock.assert_not_called() def test_warning_threshold(self): - self.config['play']['warning_treshold'] = 1 + self.config['play']['warning_threshold'] = 1 self.add_item(title='another NiceTitle') with control_stdin("a"): From 1111ab9fdfef49661c4c667ec051e8a05c293a2b Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Wed, 6 Jan 2016 01:02:07 -0800 Subject: [PATCH 0390/2280] Add tests for stats and version --- test/test_ui.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index f774b1f13..b32a4c452 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1139,6 +1139,22 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): with self.assertRaises(ui.UserError): self.run_command('help', 'this.is.not.a.real.command') + def test_stats(self): + l = self.run_with_output('stats') + self.assertIn('Approximate total size:', l) + + # # Need to have more realistic library setup for this to work + # l = self.run_with_output('stats', '-e') + # self.assertIn('Total size:', l) + + def test_version(self): + l = self.run_with_output('version') + self.assertIn('no plugins loaded', l) + + # # Need to have plugin loaded + # l = self.run_with_output('version') + # self.assertIn('plugins: ', l) + class CommonOptionsParserTest(unittest.TestCase, TestHelper): def setUp(self): From 1e72ba75c7c53f1b11d8fbf0333c4fb8ea779785 Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Wed, 6 Jan 2016 10:12:45 +0100 Subject: [PATCH 0391/2280] play: Preserve backwards compat when fixing typos --- beetsplug/play.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index b622713c0..5b923f075 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -41,7 +41,9 @@ class PlayPlugin(BeetsPlugin): 'use_folders': False, 'relative_to': None, 'raw': False, - 'warning_threshold': 100, + # Backwards compatibility. See #1803 and line 74 + 'warning_threshold': -2, + 'warning_treshold': 100, }) def commands(self): @@ -69,6 +71,17 @@ class PlayPlugin(BeetsPlugin): relative_to = config['play']['relative_to'].get() raw = config['play']['raw'].get(bool) warning_threshold = config['play']['warning_threshold'].get(int) + # We use -2 as a default value for warning_threshold to detect if it is + # set or not. We can't use a falsey value because it has an actual in + # the configuration of this pluginmeaning, and we do not use -1 because + # some people might use it as a value to obtain no warning, which + # which wouldn't be that bad of a practice. + if warning_threshold == -2: + # if warning_threshold has not been set by user, look for + # warning_treshold, to preserve backwards compatibility. See #1803. + # warning_treshold has the correct default value of 100. + warning_threshold = config['play']['warning_treshold'].get(int) + if relative_to: relative_to = util.normpath(relative_to) From d4ccc106676331ca5a603273cf86158d0fc5112d Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Wed, 6 Jan 2016 00:27:55 -0800 Subject: [PATCH 0392/2280] Fix typo: judment -> judgement --- beets/ui/commands.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 25ed0425d..72c345c68 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -440,7 +440,7 @@ def summarize_items(items, singleton): return ', '.join(summary_parts) -def _summary_judment(rec): +def _summary_judgment(rec): """Determines whether a decision should be made without even asking the user. This occurs in quiet mode and when an action is chosen for NONE recommendations. Return an action or None if the user should be @@ -697,7 +697,7 @@ class TerminalImportSession(importer.ImportSession): u' ({0} items)'.format(len(task.items))) # Take immediate action if appropriate. - action = _summary_judment(task.rec) + action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = task.candidates[0] show_change(task.cur_artist, task.cur_album, match) @@ -757,7 +757,7 @@ class TerminalImportSession(importer.ImportSession): candidates, rec = task.candidates, task.rec # Take immediate action if appropriate. - action = _summary_judment(task.rec) + action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = candidates[0] show_item_change(task.item, match) From 7370cdfd39e0f4669b11247e5a3dbbe449bdfb36 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Wed, 6 Jan 2016 01:34:52 -0800 Subject: [PATCH 0393/2280] Add test for backwards compat --- test/test_play.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/test_play.py b/test/test_play.py index 2c2c076de..d0371cf15 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -105,6 +105,15 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.open_mock.assert_not_called() + def test_warning_threshold_backwards_compat(self): + self.config['play']['warning_treshold'] = 1 + self.add_item(title='another NiceTitle') + + with control_stdin("a"): + self.run_command('play', 'nice') + + self.open_mock.assert_not_called() + def test_command_failed(self): self.open_mock.side_effect = OSError("some reason") From 6e2b249c5484a5ffe9b250cec4b80cccce32301a Mon Sep 17 00:00:00 2001 From: "nath@laptop" Date: Wed, 6 Jan 2016 11:17:49 +0100 Subject: [PATCH 0394/2280] fix-typos: Write changelog Also stealth-reformulate a recent comment of mine which contained another (!) typo --- beetsplug/play.py | 6 +++--- docs/changelog.rst | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 5b923f075..b52b7e635 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -72,9 +72,9 @@ class PlayPlugin(BeetsPlugin): raw = config['play']['raw'].get(bool) warning_threshold = config['play']['warning_threshold'].get(int) # We use -2 as a default value for warning_threshold to detect if it is - # set or not. We can't use a falsey value because it has an actual in - # the configuration of this pluginmeaning, and we do not use -1 because - # some people might use it as a value to obtain no warning, which + # set or not. We can't use a falsey value because it would have an + # actual meaning in the configuration of this plugin, and we do not use + # -1 because some people might use it as a value to obtain no warning, # which wouldn't be that bad of a practice. if warning_threshold == -2: # if warning_threshold has not been set by user, look for diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b35a66b6..fa792bbc2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -33,6 +33,12 @@ Fixes: user.getTopTracks. This fixes :bug:`1574`, which was caused by the former API method being removed. Also moved from custom HTTP requests to using pylast library. +* Fix typos. For the :doc:`/plugins/play`, the recommended configuration option + to set the warning threshold is now ``warning_threshold`` (instead of + ``warning_treshold``) but backwards compatibility is preserved until the next + major version so ``warning_treshold`` will still work. Thanks to + :user:`JesseWeinstein`. :bug:`1802` :bug:`1803` + 1.3.16 (December 28, 2015) From 36ad0cf70df87dc03711216870cbb487e1a6c449 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 6 Jan 2016 14:29:51 -0800 Subject: [PATCH 0395/2280] lyrics: Re-enable genius backend (#1770) --- beetsplug/lyrics.py | 2 +- docs/changelog.rst | 1 + docs/plugins/lyrics.rst | 7 ++++--- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 9e5e2fad6..5b30184a0 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -537,7 +537,7 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] + SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch', 'genius'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, diff --git a/docs/changelog.rst b/docs/changelog.rst index fa792bbc2..b39355700 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -38,6 +38,7 @@ Fixes: ``warning_treshold``) but backwards compatibility is preserved until the next major version so ``warning_treshold`` will still work. Thanks to :user:`JesseWeinstein`. :bug:`1802` :bug:`1803` +* :doc:`/plugins/lyrics`: The Genius backend has been re-enabled. diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 0d504733f..4f1569c38 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -52,9 +52,10 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all the - sources except for `genius`. The `google` source will be automatically - deactivated if no ``google_API_key`` is setup. + Default: ``google lyricwiki lyrics.com musixmatch genius``, i.e., all + sources. + The `google` source will be automatically deactivated if no + ``google_API_key`` is setup. Here's an example of ``config.yaml``:: From 963a66a40c51a2fecae8f21daa01097e8457e4ca Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 14:56:52 -0800 Subject: [PATCH 0396/2280] Refactor `try_sync` to also include moving This will remove a bunch of duplication we currently have for moving files *inside the library directory* when their metadata changes. --- beets/library.py | 41 +++++++++++++++++++++++++---------------- beets/ui/commands.py | 12 ++++-------- beetsplug/edit.py | 6 +++--- 3 files changed, 32 insertions(+), 27 deletions(-) diff --git a/beets/library.py b/beets/library.py index b42dd2c47..59a20cabf 100644 --- a/beets/library.py +++ b/beets/library.py @@ -630,20 +630,26 @@ class Item(LibModel): log.error("{0}", exc) return False - def try_sync(self, write=None): - """Synchronize the item with the database and the media file - tags, updating them with this object's current state. + def try_sync(self, write, move, with_album=True): + """Synchronize the item with the database and, possibly, updates its + tags on disk and its path (by moving the file). - By default, the current `path` for the item is used to write - tags. If `write` is `False`, no tags are written. If `write` is - a path, tags are written to that file instead. + `write` indicates whether to write new tags into the file. Similarly, + `move` controls whether the path should be updated. In the + latter case, files are *only* moved when they are inside their + library's directory (if any). - Similar to calling :meth:`write` and :meth:`store`. + Similar to calling :meth:`write`, :meth:`move`, and :meth:`store` + (conditionally). """ - if write is True: - write = None - if write is not False: - self.try_write(path=write) + if write: + self.try_write() + if move: + # Check whether this file is inside the library directory. + if self._db and self._db.directory in util.ancestry(self.path): + log.debug('moving {0} to synchronize path', + util.displayable_path(self.path)) + self.move(with_album=with_album) self.store() # Files themselves. @@ -1108,15 +1114,18 @@ class Album(LibModel): item[key] = value item.store() - def try_sync(self, write=True): - """Synchronize the album and its items with the database and - their files by updating them with this object's current state. + def try_sync(self, write, move): + """Synchronize the album and its items with the database. + Optionally, also write any new tags into the files and update + their paths. - `write` indicates whether to write tags to the item files. + `write` indicates whether to write tags to the item files, and + `move` controls whether files (both audio and album art) are + moved. """ self.store() for item in self.items(): - item.try_sync(bool(write)) + item.try_sync(write, move) # Query construction helpers. diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 72c345c68..773c10cae 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1353,13 +1353,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): # Apply changes to database and files with lib.transaction(): for obj in changed: - if move: - cur_path = obj.path - if lib.directory in ancestry(cur_path): # In library? - log.debug(u'moving object {0}', displayable_path(cur_path)) - obj.move() - - obj.try_sync(write) + obj.try_sync(write, move) def modify_parse_args(args): @@ -1510,7 +1504,9 @@ def write_items(lib, query, pretend, force): changed = ui.show_model_changes(item, clean_item, library.Item._media_tag_fields, force) if (changed or force) and not pretend: - item.try_sync() + # We use `try_sync` here to keep the mtime up to date in the + # database. + item.try_sync(True, False) def write_func(lib, opts, args): diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 0aa56b885..b72b033df 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -220,7 +220,7 @@ class EditPlugin(plugins.BeetsPlugin): # Save the new data. if success: - self.save_write(objs) + self.save_changes(objs) def edit_objects(self, objs, fields): """Dump a set of Model objects to a file as text, ask the user @@ -316,11 +316,11 @@ class EditPlugin(plugins.BeetsPlugin): id = int(old_dict['id']) apply(obj_by_id[id], new_dict) - def save_write(self, objs): + def save_changes(self, objs): """Save a list of updated Model objects to the database. """ # Save to the database and possibly write tags. for ob in objs: if ob._dirty: self._log.debug('saving changes to {}', ob) - ob.try_sync(ui.should_write()) + ob.try_sync(ui.should_write(), False) From 635052e2ffd9e7b02b50e261c42ef239b93ccaae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 15:22:28 -0800 Subject: [PATCH 0397/2280] Fix #1804: edit plugin moves files --- beetsplug/edit.py | 2 +- docs/changelog.rst | 2 ++ test/test_edit.py | 16 +++++++++------- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index b72b033df..29676fa08 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -323,4 +323,4 @@ class EditPlugin(plugins.BeetsPlugin): for ob in objs: if ob._dirty: self._log.debug('saving changes to {}', ob) - ob.try_sync(ui.should_write(), False) + ob.try_sync(ui.should_write(), ui.should_move()) diff --git a/docs/changelog.rst b/docs/changelog.rst index b39355700..1110a3043 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -39,6 +39,8 @@ Fixes: major version so ``warning_treshold`` will still work. Thanks to :user:`JesseWeinstein`. :bug:`1802` :bug:`1803` * :doc:`/plugins/lyrics`: The Genius backend has been re-enabled. +* :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate + (like the :ref:`modify-cmd` command). :bug:`1804` diff --git a/test/test_edit.py b/test/test_edit.py index 727de6d20..522437eaa 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -107,19 +107,21 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertTrue(all(i.title.startswith(title_starts_with) for i in self.lib.items())) - def assertItemFieldsModified(self, library_items, items, fields=[]): + def assertItemFieldsModified(self, library_items, items, fields=[], + allowed=['path']): """Assert that items in the library (`lib_items`) have different values on the specified `fields` (and *only* on those fields), compared to `items`. + An empty `fields` list results in asserting that no modifications have - been performed. + been performed. `allowed` is a list of field changes that are ignored + (they may or may not have changed; the assertion doesn't care). """ - changed_fields = [] for lib_item, item in zip(library_items, items): - changed_fields.append([field for field in lib_item._fields - if lib_item[field] != item[field]]) - self.assertTrue(all(diff_fields == fields for diff_fields in - changed_fields)) + diff_fields = [field for field in lib_item._fields + if lib_item[field] != item[field]] + self.assertEqual(set(diff_fields).difference(allowed), + set(fields)) def test_title_edit_discard(self): """Edit title for all items in the library, then discard changes-""" From 0301bb517dd2fd5c1ec82be9f00c865615c1d5d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 16:26:13 -0800 Subject: [PATCH 0398/2280] Update links for our new domain --- README.rst | 2 +- beets/autotag/mb.py | 2 +- beetsplug/discogs.py | 2 +- docs/changelog.rst | 4 ++-- docs/guides/advanced.rst | 4 ++-- docs/guides/main.rst | 2 +- docs/index.rst | 2 +- extra/_beet | 2 +- setup.py | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/README.rst b/README.rst index eec817f94..2b012db02 100644 --- a/README.rst +++ b/README.rst @@ -79,7 +79,7 @@ news and updates. You can install beets by typing ``pip install beets``. Then check out the `Getting Started`_ guide. -.. _its Web site: http://beets.radbox.org/ +.. _its Web site: http://beets.io/ .. _Getting Started: http://beets.readthedocs.org/page/guides/main.html .. _@b33ts: http://twitter.com/b33ts/ diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 9403187ef..cc1780365 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -33,7 +33,7 @@ VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' BASE_URL = 'http://musicbrainz.org/' musicbrainzngs.set_useragent('beets', beets.__version__, - 'http://beets.radbox.org/') + 'http://beets.io/') class MusicBrainzAPIError(util.HumanReadableException): diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index d340fb236..d3088d218 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -41,7 +41,7 @@ import os urllib3_logger = logging.getLogger('requests.packages.urllib3') urllib3_logger.setLevel(logging.CRITICAL) -USER_AGENT = u'beets/{0} +http://beets.radbox.org/'.format(beets.__version__) +USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) # Exceptions that discogs_client should really handle but does not. CONNECTION_ERRORS = (ConnectionError, socket.error, httplib.HTTPException, diff --git a/docs/changelog.rst b/docs/changelog.rst index 1110a3043..479546068 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1435,7 +1435,7 @@ previous versions would spit out a warning and then list your entire library. There's more detail than you could ever need `on the beets blog`_. -.. _on the beets blog: http://beets.radbox.org/blog/flexattr.html +.. _on the beets blog: http://beets.io/blog/flexattr.html 1.2.2 (August 27, 2013) @@ -2023,7 +2023,7 @@ begins today on features for version 1.1. unintentionally loading the plugins they contain. .. _The Echo Nest: http://the.echonest.com/ -.. _Tomahawk resolver: http://beets.radbox.org/blog/tomahawk-resolver.html +.. _Tomahawk resolver: http://beets.io/blog/tomahawk-resolver.html .. _mp3gain: http://mp3gain.sourceforge.net/download.php .. _aacgain: http://aacgain.altosdesign.com diff --git a/docs/guides/advanced.rst b/docs/guides/advanced.rst index c83c39f27..119139c50 100644 --- a/docs/guides/advanced.rst +++ b/docs/guides/advanced.rst @@ -78,7 +78,7 @@ including a beets server. Just download Tomahawk and open its settings to connect it to beets. `A post on the beets blog`_ has a more detailed guide. .. _A post on the beets blog: - http://beets.radbox.org/blog/tomahawk-resolver.html + http://beets.io/blog/tomahawk-resolver.html .. _Tomahawk: http://www.tomahawk-player.org @@ -132,7 +132,7 @@ And, unlike :ref:`built-in fields `, such fields can be removed:: Read more than you ever wanted to know about the *flexible attributes* feature `on the beets blog`_. -.. _on the beets blog: http://beets.radbox.org/blog/flexattr.html +.. _on the beets blog: http://beets.io/blog/flexattr.html Choose a path style manually for some music diff --git a/docs/guides/main.rst b/docs/guides/main.rst index b43e0e9b1..6e003705e 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -4,7 +4,7 @@ Getting Started Welcome to `beets`_! This guide will help you begin using it to make your music collection better. -.. _beets: http://beets.radbox.org/ +.. _beets: http://beets.io/ Installing ---------- diff --git a/docs/index.rst b/docs/index.rst index 57a736a48..9f1eafd8c 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -17,7 +17,7 @@ Freenode, send email to `the mailing list`_, or `file a bug`_ in the issue tracker. Please let us know where you think this documentation can be improved. -.. _beets: http://beets.radbox.org/ +.. _beets: http://beets.io/ .. _the mailing list: http://groups.google.com/group/beets-users .. _file a bug: https://github.com/sampsyo/beets/issues diff --git a/extra/_beet b/extra/_beet index 055072943..9e4a3437b 100644 --- a/extra/_beet +++ b/extra/_beet @@ -1,6 +1,6 @@ #compdef beet -# Completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ +# Completion for beets music library manager and MusicBrainz tagger: http://beets.io/ # useful: argument to _regex_arguments for matching any word local matchany=/$'[^\0]##\0'/ diff --git a/setup.py b/setup.py index d6c1fb5f7..f602e3537 100755 --- a/setup.py +++ b/setup.py @@ -60,7 +60,7 @@ setup( description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', - url='http://beets.radbox.org/', + url='http://beets.io/', license='MIT', platforms='ALL', long_description=_read('README.rst'), From 70a0d4680cc935c382aee36ecc80d5ad86274c93 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 20:01:20 -0800 Subject: [PATCH 0399/2280] Remove Mercurial vestiges :cry: I still love you, Mercurial. --- .hgignore | 7 ------- .hgtags | 29 ----------------------------- 2 files changed, 36 deletions(-) delete mode 100644 .hgignore delete mode 100644 .hgtags diff --git a/.hgignore b/.hgignore deleted file mode 100644 index 33acb4da3..000000000 --- a/.hgignore +++ /dev/null @@ -1,7 +0,0 @@ -^dist/ -^beets\.egg-info/ -^build/ -^MANIFEST$ -^docs/_build/ -^\.tox/ -^\.idea/ diff --git a/.hgtags b/.hgtags deleted file mode 100644 index 91ecdd73d..000000000 --- a/.hgtags +++ /dev/null @@ -1,29 +0,0 @@ -86681cf6e45cf8f8de36ffe4e543b8bdd0e92c70 1.0b2 -c367859a82b9f4db0a4e693db6e0cd9724f8f86d 1.0b1 -a5e6430ece5a806aae7e692bf274f700ba01c665 1.0b3 -127b1ca77a2b4d1bdff0fa2eac168684d7dfe29d 1.0b4 -7b14e7caeaeb15ccd3f280b8b745c9c8f1487b14 1.0b5 -fad79b29263e86815799d3049aaa2da5d4cd3a04 1.0b6 -5986215a08c24eea3eb48e1b13a4748b34040aa5 1.0b7 -cea5dcc51b047fa6535d535624363b50a991fb5b 1.0b8 -a256ec5b0b2de500305fd6656db0a195df273acc 1.0b9 -88807657483a916200296165933529da9a682528 1.0b10 -4ca1475821742002962df439f71f51d67640b91e 1.0b11 -284b58a9f9ce3a79f7d2bcc48819f2bb77773818 1.0b12 -b6c10981014a5b3a963460fca3b31cc62bf7ed2c 1.0b13 -d3dbc6df2b96f8ba5704305a893e3e63b7f9cd77 1.0b14 -618201431990382474829cf96ea58e3669159f9a 1.0b15 -c84744f4519be7416dc1653142f1763f406d6896 1.0rc1 -f3cd4c138c6f40dc324a23bf01c4c7d97766477e 1.0rc2 -6f29c0f4dc7025e8d8216ea960000c353886c4f4 v1.1.0-beta.1 -f28ea9e2ef8d39913d79dbba73db280ff0740c50 v1.1.0-beta.2 -8f070ce28a7b33d8509b29a8dbe937109bbdbd21 v1.1.0-beta.3 -97f04ce252332dbda013cbc478d702d54a8fc1bd v1.1.0 -b3f7b5267a2f7b46b826d087421d7f4569211240 v1.2.0 -b3f7b5267a2f7b46b826d087421d7f4569211240 v1.2.0 -ecff182221ec32a9f6549ad3ce8d2ab4c3e5568a v1.2.0 -bd7259ac13b54caecb1403f625688eb3eeeba8d6 v1.2.1 -c6af5962e25b915ce538af1c0b53a89ceb340b04 v1.2.2 -87945a0e217591a842307fa11e161d4912598c32 v1.3.0 -78ce7bd4a1d1ddcbbd2b624cdfcd70946640ae46 v1.3.1 -d3bb90ef6bc7f663f96dcc1bb5e46498662f16e7 v1.3.2 From c7045daf909c4ecee1f75905b400ba7a643e3e25 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 20:36:16 -0800 Subject: [PATCH 0400/2280] sampsyo -> beetbox (#1730) :tada: --- README.rst | 8 ++++---- beetsplug/discogs.py | 2 +- docs/changelog.rst | 2 +- docs/conf.py | 2 +- docs/faq.rst | 12 ++++++------ docs/guides/main.rst | 2 +- docs/guides/tagger.rst | 4 ++-- docs/index.rst | 2 +- docs/plugins/chroma.rst | 4 ++-- docs/plugins/discogs.rst | 2 +- docs/plugins/lastgenre.rst | 2 +- docs/plugins/mpdstats.rst | 2 +- docs/reference/cli.rst | 2 +- test/test_lyrics.py | 2 +- 14 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.rst b/README.rst index 2b012db02..1d865ec79 100644 --- a/README.rst +++ b/README.rst @@ -1,8 +1,8 @@ -.. image:: https://travis-ci.org/sampsyo/beets.svg?branch=master - :target: https://travis-ci.org/sampsyo/beets +.. image:: https://travis-ci.org/beetbox/beets.svg?branch=master + :target: https://travis-ci.org/beetbox/beets -.. image:: http://img.shields.io/codecov/c/github/sampsyo/beets.svg - :target: https://codecov.io/github/sampsyo/beets +.. image:: http://img.shields.io/codecov/c/github/beetbox/beets.svg + :target: https://codecov.io/github/beetbox/beets .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index d3088d218..321fbd09e 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -196,7 +196,7 @@ class DiscogsPlugin(BeetsPlugin): # album title. Use `re.UNICODE` flag to avoid stripping non-english # word characters. # TEMPORARY: Encode as ASCII to work around a bug: - # https://github.com/sampsyo/beets/issues/1051 + # https://github.com/beetbox/beets/issues/1051 # When the library is fixed, we should encode as UTF-8. query = re.sub(r'(?u)\W+', ' ', query).encode('ascii', "replace") # Strip medium information from query, Things like "CD1" and "disk 1" diff --git a/docs/changelog.rst b/docs/changelog.rst index 479546068..3a7804dd0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -2220,7 +2220,7 @@ release. * Significant internal restructuring to avoid SQLite locking errors. As part of these changes, the not-very-useful "save" plugin event has been removed. -.. _pyacoustid: https://github.com/sampsyo/pyacoustid +.. _pyacoustid: https://github.com/beetbox/pyacoustid 1.0b13 (March 16, 2012) diff --git a/docs/conf.py b/docs/conf.py index a63622079..cd533a4d8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,7 +20,7 @@ pygments_style = 'sphinx' # External links to the bug tracker. extlinks = { - 'bug': ('https://github.com/sampsyo/beets/issues/%s', '#'), + 'bug': ('https://github.com/beetbox/beets/issues/%s', '#'), 'user': ('https://github.com/%s', ''), } diff --git a/docs/faq.rst b/docs/faq.rst index 050461587..1d0829cd1 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -138,13 +138,13 @@ it's helpful to run on the "bleeding edge". To run the latest source: 2. Install from source. There are a few easy ways to do this: - Use ``pip`` to install the latest snapshot tarball: just type - ``pip install https://github.com/sampsyo/beets/tarball/master``. + ``pip install https://github.com/beetbox/beets/tarball/master``. - Grab the source using Git: - ``git clone https://github.com/sampsyo/beets.git``. Then + ``git clone https://github.com/beetbox/beets.git``. Then ``cd beets`` and type ``python setup.py install``. - Use ``pip`` to install an "editable" version of beets based on an automatic source checkout. For example, run - ``pip install -e git+https://github.com/sampsyo/beets#egg=beets`` + ``pip install -e git+https://github.com/beetbox/beets#egg=beets`` to clone beets and install it, allowing you to modify the source in-place to try out changes. @@ -157,8 +157,8 @@ pages. …report a bug in beets? ----------------------- -We use the `issue tracker `__ -on GitHub. `Enter a new issue `__ +We use the `issue tracker `__ +on GitHub. `Enter a new issue `__ there to report a bug. Please follow these guidelines when reporting an issue: - Most importantly: if beets is crashing, please `include the @@ -325,7 +325,7 @@ integrity---for example, type ``metaflac --list music.flac`` to check FLAC files. If beets still complains about a file that seems to be valid, `file a -bug `__ and we'll look into +bug `__ and we'll look into it. There's always a possibility that there's a bug "upstream" in the `Mutagen `__ library used by beets, in which case we'll forward the bug to that project's tracker. diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 6e003705e..2d80eb2fd 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -101,7 +101,7 @@ trouble or you have more detail to contribute here, please direct it to `the mailing list`_. .. _install Python: http://python.org/download/ -.. _beets.reg: https://github.com/sampsyo/beets/blob/master/extra/beets.reg +.. _beets.reg: https://github.com/beetbox/beets/blob/master/extra/beets.reg .. _install pip: http://www.pip-installer.org/en/latest/installing.html#install-pip .. _get-pip.py: https://raw.github.com/pypa/pip/master/contrib/get-pip.py diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index c557bbcaf..4a4c56184 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -76,7 +76,7 @@ all of these limitations. Musepack, Windows Media, Opus, and AIFF files are supported. (Do you use some other format? Please `file a feature request`_!) -.. _file a feature request: https://github.com/sampsyo/beets/issues/new +.. _file a feature request: https://github.com/beetbox/beets/issues/new Now that that's out of the way, let's tag some music. @@ -281,7 +281,7 @@ MusicBrainz---so consider adding the data yourself. If you think beets is ignoring an album that's listed in MusicBrainz, please `file a bug report`_. -.. _file a bug report: https://github.com/sampsyo/beets/issues +.. _file a bug report: https://github.com/beetbox/beets/issues I Hope That Makes Sense ----------------------- diff --git a/docs/index.rst b/docs/index.rst index 9f1eafd8c..772869389 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -19,7 +19,7 @@ improved. .. _beets: http://beets.io/ .. _the mailing list: http://groups.google.com/group/beets-users -.. _file a bug: https://github.com/sampsyo/beets/issues +.. _file a bug: https://github.com/beetbox/beets/issues Contents -------- diff --git a/docs/plugins/chroma.rst b/docs/plugins/chroma.rst index 2f52aa858..b2a9f90c6 100644 --- a/docs/plugins/chroma.rst +++ b/docs/plugins/chroma.rst @@ -77,8 +77,8 @@ You will also need a mechanism for decoding audio files supported by the * On Windows, try the Gstreamer "WinBuilds" from the `OSSBuild`_ project. -.. _audioread: https://github.com/sampsyo/audioread -.. _pyacoustid: http://github.com/sampsyo/pyacoustid +.. _audioread: https://github.com/beetbox/audioread +.. _pyacoustid: http://github.com/beetbox/pyacoustid .. _FFmpeg: http://ffmpeg.org/ .. _MAD: http://spacepants.org/src/pymad/ .. _pymad: http://www.underbit.com/products/mad/ diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index 038718f9b..eb60cca58 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -30,7 +30,7 @@ Troubleshooting Several issues have been encountered with the Discogs API. If you have one, please start by searching for `a similar issue on the repo -`_. +`_. Here are two things you can try: diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 9d3242467..bd3aebc83 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -37,7 +37,7 @@ Wikipedia`_. .. _pip: http://www.pip-installer.org/ .. _pylast: http://code.google.com/p/pylast/ .. _script that scrapes Wikipedia: https://gist.github.com/1241307 -.. _internal whitelist: https://raw.githubusercontent.com/sampsyo/beets/master/beetsplug/lastgenre/genres.txt +.. _internal whitelist: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres.txt Canonicalization ^^^^^^^^^^^^^^^^ diff --git a/docs/plugins/mpdstats.rst b/docs/plugins/mpdstats.rst index 1f74a0976..4389fa27e 100644 --- a/docs/plugins/mpdstats.rst +++ b/docs/plugins/mpdstats.rst @@ -95,4 +95,4 @@ Warning This has only been tested with MPD versions >= 0.16. It may not work on older versions. If that is the case, please report an `issue`_. -.. _issue: https://github.com/sampsyo/beets/issues +.. _issue: https://github.com/beetbox/beets/issues diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 5eb440316..c072c0c0f 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -439,7 +439,7 @@ defines some bash-specific functions to make this work without errors:: _filedir() { :; } eval "$(beet completion)" -.. _completion script: https://github.com/sampsyo/beets/blob/master/extra/_beet +.. _completion script: https://github.com/beetbox/beets/blob/master/extra/_beet .. only:: man diff --git a/test/test_lyrics.py b/test/test_lyrics.py index d1f1f05a7..bd2e69e97 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -380,7 +380,7 @@ class LyricsGooglePluginTest(unittest.TestCase): """Ensure that `is_page_candidate` doesn't crash when the artist and such contain special regular expression characters. """ - # https://github.com/sampsyo/beets/issues/1673 + # https://github.com/beetbox/beets/issues/1673 s = self.source url = s['url'] + s['path'] url_title = u'foo' From 6a379e1debd7358dca9693daafbbe72063192bb5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 8 Jan 2016 20:48:15 -0800 Subject: [PATCH 0401/2280] Changelog note about new homes (#1730) --- docs/changelog.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3a7804dd0..56810ef6c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,10 @@ Changelog 1.3.17 (in development) ----------------------- +As of this release, the beets project has some new Internet homes! Our new +domain name is `beets.io`_, and we have a shiny new GitHub organization: +`Beetbox`_. + New: * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It @@ -42,6 +46,9 @@ Fixes: * :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate (like the :ref:`modify-cmd` command). :bug:`1804` +.. _beets.io: http://beets.io/ +.. _Beetbox: https://github.com/beetbox + 1.3.16 (December 28, 2015) From 11c8af724d9369c92199870af2cc69704017d3a0 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 10 Jan 2016 21:00:39 -0800 Subject: [PATCH 0402/2280] Add more tests for dbcore --- test/test_dbcore.py | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index a69ffedbe..204398eaa 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -116,6 +116,16 @@ class TestDatabaseTwoModels(dbcore.Database): pass +class TestModelWithGetters(dbcore.Model): + + @classmethod + def _getters(cls): + return {'aComputedField': (lambda s: 'thing')} + + def _template_funcs(self): + return {} + + class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. @@ -274,6 +284,40 @@ class ModelTest(unittest.TestCase): model2.load() self.assertNotIn('flex_field', model2) + def test_check_db_fails(self): + with self.assertRaisesRegexp(ValueError, 'no database'): + dbcore.Model()._check_db() + with self.assertRaisesRegexp(ValueError, 'no id'): + TestModel1(self.db)._check_db() + + dbcore.Model(self.db)._check_db(need_id=False) + + def test_missing_field(self): + with self.assertRaises(AttributeError): + TestModel1(self.db).nonExistingKey + + def test_computed_field(self): + model = TestModelWithGetters() + self.assertEqual(model.aComputedField, 'thing') + with self.assertRaisesRegexp(KeyError, 'computed field .+ deleted'): + del model.aComputedField + + def test_items(self): + model = TestModel1(self.db) + model.id = 5 + self.assertEqual({('id', 5), ('field_one', None)}, + set(model.items())) + + def test_delete_internal_field(self): + model = dbcore.Model() + del model._db + with self.assertRaises(AttributeError): + model._db + + def test_parse_nonstring(self): + with self.assertRaisesRegexp(TypeError, "must be a string"): + dbcore.Model._parse(None, 42) + class FormatTest(unittest.TestCase): def test_format_fixed_field(self): @@ -588,6 +632,15 @@ class ResultsIteratorTest(unittest.TestCase): objs = self.db._fetch(TestModel1) self.assertEqual(len(objs), 2) + def test_out_of_range(self): + objs = self.db._fetch(TestModel1) + with self.assertRaises(IndexError): + objs[100] + + def test_no_results(self): + self.assertIsNone(self.db._fetch( + TestModel1, dbcore.query.FalseQuery()).get()) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From f770125e3cf3873f9812ab99a76a9f9fdd753186 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 10 Jan 2016 21:01:28 -0800 Subject: [PATCH 0403/2280] Avoid repeating expensive db creation Saves about 3 seconds --- test/test_dbcore.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 204398eaa..3c1a3599b 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -19,6 +19,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import os +import shutil import sqlite3 from test._common import unittest @@ -130,11 +131,13 @@ class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. """ - def setUp(self): - handle, self.libfile = mkstemp('db') + + @classmethod + def setUpClass(cls): + handle, cls.orig_libfile = mkstemp('orig_db') os.close(handle) # Set up a database with the two-field schema. - old_lib = TestDatabase2(self.libfile) + old_lib = TestDatabase2(cls.orig_libfile) # Add an item to the old library. old_lib._connection().execute( @@ -143,6 +146,15 @@ class MigrationTest(unittest.TestCase): old_lib._connection().commit() del old_lib + @classmethod + def tearDownClass(cls): + os.remove(cls.orig_libfile) + + def setUp(self): + handle, self.libfile = mkstemp('db') + os.close(handle) + shutil.copyfile(self.orig_libfile, self.libfile) + def tearDown(self): os.remove(self.libfile) From dda1173e02d73e5cfe07434238bd99dbd9e1ae45 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 10 Jan 2016 22:01:13 -0800 Subject: [PATCH 0404/2280] Escape quotes to make old version of emacs font-lock happy --- test/test_art.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index e19c7d211..4954106b5 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -209,10 +209,10 @@ class AAOTest(UseThePlugin): def test_aao_scraper_finds_image(self): body = b"""
- - View larger image + + \"View """ self.mock_response(self.AAO_URL, body) album = _common.Bag(asin=self.ASIN) From 760298b8e464d0821d937cfdade895ed0a4c72d6 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 10 Jan 2016 23:18:47 -0800 Subject: [PATCH 0405/2280] Mark slow tests to be skipped if SKIP_SLOW_TESTS env var is defined Saves over 100 seconds. --- test/test_art.py | 2 ++ test/test_convert.py | 6 ++++++ test/test_dbcore.py | 2 ++ test/test_edit.py | 3 +++ test/test_importer.py | 2 ++ test/test_logging.py | 3 +++ test/test_ui.py | 6 ++++++ 7 files changed, 24 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index 4954106b5..d4ca814a5 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -261,6 +261,8 @@ class GoogleImageTest(UseThePlugin): self.assertEqual(list(result_url), []) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() diff --git a/test/test_convert.py b/test/test_convert.py index ab1fa2504..e6f75c0ad 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -64,6 +64,8 @@ class TestHelper(helper.TestHelper): .format(path, tag)) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class ImportConvertTest(unittest.TestCase, TestHelper): def setUp(self): @@ -99,6 +101,8 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.assertTrue(os.path.isfile(item.path)) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class ConvertCliTest(unittest.TestCase, TestHelper): def setUp(self): @@ -186,6 +190,8 @@ class ConvertCliTest(unittest.TestCase, TestHelper): self.assertFalse(os.path.exists(converted)) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): """Test the effect of the `never_convert_lossy_files` option. """ diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 3c1a3599b..00ef2f1fb 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -127,6 +127,8 @@ class TestModelWithGetters(dbcore.Model): return {} +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. diff --git a/test/test_edit.py b/test/test_edit.py index 522437eaa..34bad25a7 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -15,6 +15,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import codecs +import os from mock import patch from test._common import unittest @@ -62,6 +63,8 @@ class ModifyFileMocker(object): f.write(contents) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class EditCommandTest(unittest.TestCase, TestHelper): """ Black box tests for `beetsplug.edit`. Command line interaction is simulated using `test.helper.control_stdin()`, and yaml editing via an diff --git a/test/test_importer.py b/test/test_importer.py index b9f75f7ef..27dcd5a12 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -236,6 +236,8 @@ class ImportHelper(TestHelper): self.assertEqual(len(os.listdir(self.libdir)), 0) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def setUp(self): self.setup_beets(disk=True) diff --git a/test/test_logging.py b/test/test_logging.py index 81df95a78..8517f0a3f 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -5,6 +5,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import sys +import os import threading import logging as log from StringIO import StringIO @@ -163,6 +164,8 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.assertIn('dummy: debug import_stage', logs) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class ConcurrentEventsTest(TestCase, helper.TestHelper): """Similar to LoggingLevelTest but lower-level and focused on multiple events interaction. Since this is a bit heavy we don't do it in diff --git a/test/test_ui.py b/test/test_ui.py index b32a4c452..08097b3f2 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -594,6 +594,8 @@ class InputTest(_common.TestCase): self.assertEqual(album, u'\xc2me') +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class ConfigTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() @@ -1035,6 +1037,8 @@ class PathFormatTest(_common.TestCase): self.assertEqual(pf[1:], default_formats) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class PluginTest(_common.TestCase): def test_plugin_command_from_pluginpath(self): config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] @@ -1042,6 +1046,8 @@ class PluginTest(_common.TestCase): ui._raw_main(['test']) +@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, + 'Skipping because test is slow') class CompletionTest(_common.TestCase): def test_completion(self): # Load plugin commands From 1c95b7c46fb74bb367082948dcd4fa3d81b94539 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 11 Jan 2016 17:39:05 +0100 Subject: [PATCH 0406/2280] Add musicbrainz id option to importer * Add '-m', '--musicbrainzid' option to the import command, allowing the user to specify a single MusicBrainz ID to be used for the candidate lookup instead of trying to find suitable candidates. * Modify lookup_candidates() of ImportTask and SingletonImportTask to use the musicbrainz id if present. --- beets/importer.py | 15 +++++++++++++-- beets/ui/commands.py | 4 ++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index e0d69b968..413750ef3 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -581,8 +581,13 @@ class ImportTask(BaseImportTask): def lookup_candidates(self): """Retrieve and store candidates for this album. """ + # Use a MusicBrainz id directly if provided by the importer -m option. + mb_id = None + if config['import']['musicbrainz_id'].exists(): + mb_id = config['import']['musicbrainz_id'].get() + artist, album, candidates, recommendation = \ - autotag.tag_album(self.items) + autotag.tag_album(self.items, search_id=mb_id) self.cur_artist = artist self.cur_album = album self.candidates = candidates @@ -821,7 +826,13 @@ class SingletonImportTask(ImportTask): plugins.send('item_imported', lib=lib, item=item) def lookup_candidates(self): - candidates, recommendation = autotag.tag_item(self.item) + # Use a MusicBrainz id directly if provided by the importer -m option. + mb_id = None + if config['import']['musicbrainz_id'].exists(): + mb_id = config['import']['musicbrainz_id'].get() + + candidates, recommendation = autotag.tag_item(self.item, + search_id=mb_id) self.candidates = candidates self.rec = recommendation diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 773c10cae..6616cb1bc 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1022,6 +1022,10 @@ import_cmd.parser.add_option( '--pretend', dest='pretend', action='store_true', help='just print the files to import' ) +import_cmd.parser.add_option( + '-m', '--musicbrainzid', dest='musicbrainz_id', + help='restrict the matching to a single MusicBrainz id' +) import_cmd.func = import_func default_commands.append(import_cmd) From 231981de0cb9ed9732aaf0ad084c30fa05a52d73 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 11 Jan 2016 10:13:26 -0800 Subject: [PATCH 0407/2280] Fix #1806: handle OSError in `stats -e` --- beets/ui/commands.py | 5 ++++- docs/changelog.rst | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 773c10cae..0022fac74 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1232,7 +1232,10 @@ def show_stats(lib, query, exact): for item in items: if exact: - total_size += os.path.getsize(item.path) + try: + total_size += os.path.getsize(item.path) + except OSError as exc: + log.info('could not get size of {}: {}', item.path, exc) else: total_size += int(item.length * item.bitrate / 8) total_time += item.length diff --git a/docs/changelog.rst b/docs/changelog.rst index 56810ef6c..808010aae 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -45,6 +45,8 @@ Fixes: * :doc:`/plugins/lyrics`: The Genius backend has been re-enabled. * :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate (like the :ref:`modify-cmd` command). :bug:`1804` +* The :ref:`stats-cmd` command no longer crashes when files are missing or + inaccessible. :bug:`1806` .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox From 8cb545b779fe03217216ba5a71c898022cc8fed2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 11 Jan 2016 10:30:33 -0800 Subject: [PATCH 0408/2280] Possibly fix #1805: bytes headers for requests --- beetsplug/fetchart.py | 4 ++-- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index fe32ab9ad..57d8e4c46 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -72,9 +72,9 @@ def _logged_get(log, *args, **kwargs): else: message = 'getting URL' - req = requests.Request('GET', *args, **req_kwargs) + req = requests.Request(b'GET', *args, **req_kwargs) with requests.Session() as s: - s.headers = {'User-Agent': 'beets'} + s.headers = {b'User-Agent': b'beets'} prepped = s.prepare_request(req) log.debug('{}: {}', message, prepped.url) return s.send(prepped, **send_kwargs) diff --git a/docs/changelog.rst b/docs/changelog.rst index 808010aae..2a27987f1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -47,6 +47,8 @@ Fixes: (like the :ref:`modify-cmd` command). :bug:`1804` * The :ref:`stats-cmd` command no longer crashes when files are missing or inaccessible. :bug:`1806` +* :doc:`/plugins/fetchart`: Possibly fix a Unicode-related crash when using + some versions of pyOpenSSL. :bug:`1805` .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox From d93f723263ec13ac4990707b467efbaae218af40 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 12 Jan 2016 21:53:52 -0800 Subject: [PATCH 0409/2280] Convert SKIP_SLOW_TESTS to its own decorator --- test/_common.py | 8 ++++++++ test/test_art.py | 3 +-- test/test_convert.py | 9 +++------ test/test_dbcore.py | 4 ++-- test/test_edit.py | 5 ++--- test/test_importer.py | 3 +-- test/test_logging.py | 5 ++--- test/test_ui.py | 9 +++------ 8 files changed, 22 insertions(+), 24 deletions(-) diff --git a/test/_common.py b/test/_common.py index 21c73858e..8105ef342 100644 --- a/test/_common.py +++ b/test/_common.py @@ -346,3 +346,11 @@ def system_mock(name): yield finally: platform.system = old_system + + +def slowTest(unused=None): + def _id(obj): + return obj + if 'SKIP_SLOW_TESTS' in os.environ: + return unittest.skip('test is slow') + return _id diff --git a/test/test_art.py b/test/test_art.py index d4ca814a5..b7b52c245 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -261,8 +261,7 @@ class GoogleImageTest(UseThePlugin): self.assertEqual(list(result_url), []) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() diff --git a/test/test_convert.py b/test/test_convert.py index e6f75c0ad..8ba71bdc9 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -64,8 +64,7 @@ class TestHelper(helper.TestHelper): .format(path, tag)) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class ImportConvertTest(unittest.TestCase, TestHelper): def setUp(self): @@ -101,8 +100,7 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.assertTrue(os.path.isfile(item.path)) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class ConvertCliTest(unittest.TestCase, TestHelper): def setUp(self): @@ -190,8 +188,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper): self.assertFalse(os.path.exists(converted)) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): """Test the effect of the `never_convert_lossy_files` option. """ diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 00ef2f1fb..4b4cc18bb 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -22,6 +22,7 @@ import os import shutil import sqlite3 +from test import _common from test._common import unittest from beets import dbcore from tempfile import mkstemp @@ -127,8 +128,7 @@ class TestModelWithGetters(dbcore.Model): return {} -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. diff --git a/test/test_edit.py b/test/test_edit.py index 34bad25a7..106cf1f25 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -15,9 +15,9 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import codecs -import os from mock import patch +from test import _common from test._common import unittest from test.helper import TestHelper, control_stdin @@ -63,8 +63,7 @@ class ModifyFileMocker(object): f.write(contents) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class EditCommandTest(unittest.TestCase, TestHelper): """ Black box tests for `beetsplug.edit`. Command line interaction is simulated using `test.helper.control_stdin()`, and yaml editing via an diff --git a/test/test_importer.py b/test/test_importer.py index 27dcd5a12..fea4d78a0 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -236,8 +236,7 @@ class ImportHelper(TestHelper): self.assertEqual(len(os.listdir(self.libdir)), 0) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def setUp(self): self.setup_beets(disk=True) diff --git a/test/test_logging.py b/test/test_logging.py index 8517f0a3f..478b7a7c6 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -5,7 +5,6 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) import sys -import os import threading import logging as log from StringIO import StringIO @@ -13,6 +12,7 @@ from StringIO import StringIO import beets.logging as blog from beets import plugins, ui import beetsplug +from test import _common from test._common import unittest, TestCase from test import helper @@ -164,8 +164,7 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.assertIn('dummy: debug import_stage', logs) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class ConcurrentEventsTest(TestCase, helper.TestHelper): """Similar to LoggingLevelTest but lower-level and focused on multiple events interaction. Since this is a bit heavy we don't do it in diff --git a/test/test_ui.py b/test/test_ui.py index 08097b3f2..207d39261 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -594,8 +594,7 @@ class InputTest(_common.TestCase): self.assertEqual(album, u'\xc2me') -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class ConfigTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() @@ -1037,8 +1036,7 @@ class PathFormatTest(_common.TestCase): self.assertEqual(pf[1:], default_formats) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class PluginTest(_common.TestCase): def test_plugin_command_from_pluginpath(self): config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] @@ -1046,8 +1044,7 @@ class PluginTest(_common.TestCase): ui._raw_main(['test']) -@unittest.skipIf('SKIP_SLOW_TESTS' in os.environ, - 'Skipping because test is slow') +@_common.slowTest() class CompletionTest(_common.TestCase): def test_completion(self): # Load plugin commands From c292b77e9e46687ced85b8f75e75ebf530ff0547 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 12 Jan 2016 22:02:12 -0800 Subject: [PATCH 0410/2280] fix travis-ci flake8 warning --- beets/library.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 59a20cabf..154b2be3c 100644 --- a/beets/library.py +++ b/beets/library.py @@ -86,8 +86,7 @@ class PathQuery(dbcore.FieldQuery): colon = query_part.find(':') if colon != -1: query_part = query_part[:colon] - return (os.sep in query_part - and os.path.exists(syspath(normpath(query_part)))) + return (os.sep in query_part and os.path.exists(syspath(normpath(query_part)))) def match(self, item): path = item.path if self.case_sensitive else item.path.lower() From ab2b1fa900fc8d756fa166a116a2cc504a5c3c25 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 12 Jan 2016 22:07:02 -0800 Subject: [PATCH 0411/2280] fix different travis-ci flake8 warning --- beets/library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 154b2be3c..1c2fac944 100644 --- a/beets/library.py +++ b/beets/library.py @@ -86,7 +86,8 @@ class PathQuery(dbcore.FieldQuery): colon = query_part.find(':') if colon != -1: query_part = query_part[:colon] - return (os.sep in query_part and os.path.exists(syspath(normpath(query_part)))) + return (os.sep in query_part and + os.path.exists(syspath(normpath(query_part)))) def match(self, item): path = item.path if self.case_sensitive else item.path.lower() From 72ce9ea3ebb45452605049ec24eecaa32c145e96 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Tue, 12 Jan 2016 22:14:12 -0800 Subject: [PATCH 0412/2280] use underscore in name for pep-8s sake --- test/_common.py | 2 +- test/test_art.py | 2 +- test/test_convert.py | 6 +++--- test/test_dbcore.py | 2 +- test/test_edit.py | 2 +- test/test_importer.py | 2 +- test/test_logging.py | 2 +- test/test_ui.py | 6 +++--- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/_common.py b/test/_common.py index 8105ef342..9f8b9f146 100644 --- a/test/_common.py +++ b/test/_common.py @@ -348,7 +348,7 @@ def system_mock(name): platform.system = old_system -def slowTest(unused=None): +def slow_test(unused=None): def _id(obj): return obj if 'SKIP_SLOW_TESTS' in os.environ: diff --git a/test/test_art.py b/test/test_art.py index b7b52c245..7902bb213 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -261,7 +261,7 @@ class GoogleImageTest(UseThePlugin): self.assertEqual(list(result_url), []) -@_common.slowTest() +@_common.slow_test() class ArtImporterTest(UseThePlugin): def setUp(self): super(ArtImporterTest, self).setUp() diff --git a/test/test_convert.py b/test/test_convert.py index 8ba71bdc9..72d52feaa 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -64,7 +64,7 @@ class TestHelper(helper.TestHelper): .format(path, tag)) -@_common.slowTest() +@_common.slow_test() class ImportConvertTest(unittest.TestCase, TestHelper): def setUp(self): @@ -100,7 +100,7 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.assertTrue(os.path.isfile(item.path)) -@_common.slowTest() +@_common.slow_test() class ConvertCliTest(unittest.TestCase, TestHelper): def setUp(self): @@ -188,7 +188,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper): self.assertFalse(os.path.exists(converted)) -@_common.slowTest() +@_common.slow_test() class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): """Test the effect of the `never_convert_lossy_files` option. """ diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 4b4cc18bb..39b7eea1e 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -128,7 +128,7 @@ class TestModelWithGetters(dbcore.Model): return {} -@_common.slowTest() +@_common.slow_test() class MigrationTest(unittest.TestCase): """Tests the ability to change the database schema between versions. diff --git a/test/test_edit.py b/test/test_edit.py index 106cf1f25..25b24cea0 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -63,7 +63,7 @@ class ModifyFileMocker(object): f.write(contents) -@_common.slowTest() +@_common.slow_test() class EditCommandTest(unittest.TestCase, TestHelper): """ Black box tests for `beetsplug.edit`. Command line interaction is simulated using `test.helper.control_stdin()`, and yaml editing via an diff --git a/test/test_importer.py b/test/test_importer.py index fea4d78a0..6eacab32d 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -236,7 +236,7 @@ class ImportHelper(TestHelper): self.assertEqual(len(os.listdir(self.libdir)), 0) -@_common.slowTest() +@_common.slow_test() class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def setUp(self): self.setup_beets(disk=True) diff --git a/test/test_logging.py b/test/test_logging.py index 478b7a7c6..a3fe363b9 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -164,7 +164,7 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.assertIn('dummy: debug import_stage', logs) -@_common.slowTest() +@_common.slow_test() class ConcurrentEventsTest(TestCase, helper.TestHelper): """Similar to LoggingLevelTest but lower-level and focused on multiple events interaction. Since this is a bit heavy we don't do it in diff --git a/test/test_ui.py b/test/test_ui.py index 207d39261..ed1740643 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -594,7 +594,7 @@ class InputTest(_common.TestCase): self.assertEqual(album, u'\xc2me') -@_common.slowTest() +@_common.slow_test() class ConfigTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() @@ -1036,7 +1036,7 @@ class PathFormatTest(_common.TestCase): self.assertEqual(pf[1:], default_formats) -@_common.slowTest() +@_common.slow_test() class PluginTest(_common.TestCase): def test_plugin_command_from_pluginpath(self): config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] @@ -1044,7 +1044,7 @@ class PluginTest(_common.TestCase): ui._raw_main(['test']) -@_common.slowTest() +@_common.slow_test() class CompletionTest(_common.TestCase): def test_completion(self): # Load plugin commands From 20e4f5d2098f2b76aaa1ec41e61e8f4e52da99d1 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Thu, 14 Jan 2016 18:08:22 -0200 Subject: [PATCH 0413/2280] Info plugin: add option to print only keys --- beetsplug/info.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index 61f0c7971..e67527247 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -119,6 +119,24 @@ def print_data(data, item=None, fmt=None): ui.print_(lineformat.format(field, value)) +def print_data_keys(data, item=None): + + path = displayable_path(item.path) if item else None + formatted = [] + for key, value in data.iteritems(): + formatted.append(key) + + if len(formatted) == 0: + return + + line_format = u'{0}{{0}}'.format(u' ' * 4) + if path: + ui.print_(displayable_path(path)) + + for field in sorted(formatted): + ui.print_(line_format.format(field)) + + class InfoPlugin(BeetsPlugin): def commands(self): @@ -131,6 +149,8 @@ class InfoPlugin(BeetsPlugin): cmd.parser.add_option('-i', '--include-keys', default=[], action='append', dest='included_keys', help='comma separated list of keys to show') + cmd.parser.add_option('-k', '--keys-only', action='store_true', + help='show only the keys') cmd.parser.add_format_option(target='item') return [cmd] @@ -173,7 +193,10 @@ class InfoPlugin(BeetsPlugin): else: if not first: ui.print_() - print_data(data, item, opts.format) + if opts.keys_only: + print_data_keys(data, item) + else: + print_data(data, item, opts.format) first = False if opts.summarize: From f75b4b4e3b6b164234021381947b3b347a4152e1 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Fri, 15 Jan 2016 02:40:33 -0200 Subject: [PATCH 0414/2280] Update info docs --- docs/plugins/info.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/info.rst b/docs/plugins/info.rst index b36e69051..238a957ff 100644 --- a/docs/plugins/info.rst +++ b/docs/plugins/info.rst @@ -39,7 +39,7 @@ Additional command-line options include: * ``--format`` or ``-f``: Specify a specific format with which to print every item. This uses the same template syntax as beets’ :doc:`path formats `. - +* ``--keys-only`` or ``-k``: Show the name of the tags without the values. .. _id3v2: http://id3v2.sourceforge.net .. _mp3info: http://www.ibiblio.org/mp3info/ From 7251f2b9cdb5d54a7be3ced506965f4cddf21f42 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 15 Jan 2016 10:10:17 -0800 Subject: [PATCH 0415/2280] Changelog for #1812 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2a27987f1..51fab3100 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,8 @@ New: * A new :doc:`/plugins/mbsubmit` lets you print the tracks of an album in a format parseable by MusicBrainz track parser during an interactive import session. :bug:`1779` +* :doc:`/plugins/info`: A new option will print only fields' names and not + their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` .. _AcousticBrainz: http://acousticbrainz.org/ From 1866264732b85852db349a956dc871018ca00357 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 15 Jan 2016 10:10:56 -0800 Subject: [PATCH 0416/2280] Docsring for #1812 --- beetsplug/info.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index e67527247..a29a6ccfc 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -120,7 +120,8 @@ def print_data(data, item=None, fmt=None): def print_data_keys(data, item=None): - + """Print only the keys (field names) for an item. + """ path = displayable_path(item.path) if item else None formatted = [] for key, value in data.iteritems(): From da1c4545aa5cd1ca3352a804456d7c2352458d25 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 16 Jan 2016 00:10:13 -0800 Subject: [PATCH 0417/2280] Add more test coverage for mpdstats --- test/test_mpdstats.py | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index 9d7d16881..a2e2fb26a 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -17,7 +17,7 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) -from mock import Mock +from mock import Mock, patch, call, ANY from test._common import unittest from test.helper import TestHelper @@ -44,6 +44,44 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.assertFalse(mpdstats.update_rating(item, True)) self.assertFalse(mpdstats.update_rating(None, True)) + def test_get_item(self): + ITEM_PATH = '/foo/bar.flac' + item = Item(title='title', path=ITEM_PATH, id=1) + item.add(self.lib) + + log = Mock() + mpdstats = MPDStats(self.lib, log) + + self.assertEqual(str(mpdstats.get_item(ITEM_PATH)), str(item)) + self.assertIsNone(mpdstats.get_item('/some/non-existing/path')) + self.assertIn('item not found:', log.info.call_args[0][0]) + + FAKE_UNKNOWN_STATE = 'some-unknown-one' + STATUSES = [{'state': FAKE_UNKNOWN_STATE}, + {'state': 'pause'}, + {'state': 'play', 'songid': 1, 'time': '0:1'}, + {'state': 'stop'}] + ITEM_PATH = '/foo/bar.flac' + + @patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{ + "events.side_effect": [["player"]] * (len(STATUSES)-1) + [KeyboardInterrupt], + "status.side_effect": STATUSES, + "playlist.return_value": {1: ITEM_PATH}})) + def test_run_MPDStats(self, mpd_mock): + item = Item(title='title', path=self.ITEM_PATH, id=1) + item.add(self.lib) + + log = Mock() + try: + MPDStats(self.lib, log).run() + except KeyboardInterrupt: + pass + + log.debug.assert_has_calls( + [call(u'unhandled status "{0}"', ANY)]) + log.info.assert_has_calls( + [call(u'pause'), call(u'playing {0}', ANY), call(u'stop')]) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From e3d19b0a0f3120f122c28bfddfe02a2076715960 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sat, 16 Jan 2016 00:26:56 -0800 Subject: [PATCH 0418/2280] flake8 fixes --- test/test_mpdstats.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index a2e2fb26a..f28e29d68 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -61,11 +61,11 @@ class MPDStatsTest(unittest.TestCase, TestHelper): {'state': 'pause'}, {'state': 'play', 'songid': 1, 'time': '0:1'}, {'state': 'stop'}] + EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt] ITEM_PATH = '/foo/bar.flac' @patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{ - "events.side_effect": [["player"]] * (len(STATUSES)-1) + [KeyboardInterrupt], - "status.side_effect": STATUSES, + "events.side_effect": EVENTS, "status.side_effect": STATUSES, "playlist.return_value": {1: ITEM_PATH}})) def test_run_MPDStats(self, mpd_mock): item = Item(title='title', path=self.ITEM_PATH, id=1) From 248b0b070c487c0ab406572293bb367a7f46da07 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 18 Jan 2016 16:08:54 -0500 Subject: [PATCH 0419/2280] Remove stray space in docs --- docs/plugins/ihate.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/ihate.rst b/docs/plugins/ihate.rst index f2224bf5a..f9cde39eb 100644 --- a/docs/plugins/ihate.rst +++ b/docs/plugins/ihate.rst @@ -25,7 +25,7 @@ Here's an example:: ihate: warn: - artist:rnb - - genre: soul + - genre:soul # Only warn about tribute albums in rock genre. - genre:rock album:tribute skip: From 48c92fbf5a1ddff59594f458364a8333d1e90321 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 19 Jan 2016 21:43:32 +0100 Subject: [PATCH 0420/2280] Allow multiple MB ids to be passed to the importer * Modify the "--musicbrainzid" argument to the importer so multiple IDs can be specified by the user instead of a single one. * Revise autotag.match.tag_album and autotag.match.tag_item signature to expect a list of IDs (search_ids) instead of a single one (search_id), and add logic for handling and returning multiple matches for those IDs. * Update calls to those functions in other parts of the code. --- beets/autotag/match.py | 42 +++++++++++++++++++++++------------------- beets/importer.py | 16 ++++++++-------- beets/ui/commands.py | 6 +++--- beetsplug/bench.py | 2 +- 4 files changed, 35 insertions(+), 31 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index d4bad9e87..df5183fc8 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -370,7 +370,7 @@ def _add_candidate(items, results, info): def tag_album(items, search_artist=None, search_album=None, - search_id=None): + search_ids=[]): """Return a tuple of a artist name, an album name, a list of `AlbumMatch` candidates from the metadata backend, and a `Recommendation`. @@ -397,9 +397,11 @@ def tag_album(items, search_artist=None, search_album=None, candidates = {} # Search by explicit ID. - if search_id is not None: - log.debug(u'Searching for album ID: {0}', search_id) - search_cands = hooks.albums_for_id(search_id) + if search_ids: + search_cands = [] + for search_id in search_ids: + log.debug(u'Searching for album ID: {0}', search_id) + search_cands.extend(hooks.albums_for_id(search_id)) # Use existing metadata or text search. else: @@ -444,33 +446,35 @@ def tag_album(items, search_artist=None, search_album=None, def tag_item(item, search_artist=None, search_title=None, - search_id=None): + search_ids=[]): """Attempts to find metadata for a single track. Returns a `(candidates, recommendation)` pair where `candidates` is a list of TrackMatch objects. `search_artist` and `search_title` may be used to override the current metadata for the purposes of the MusicBrainz - title; likewise `search_id`. + title; likewise `search_ids`. """ # Holds candidates found so far: keys are MBIDs; values are # (distance, TrackInfo) pairs. candidates = {} # First, try matching by MusicBrainz ID. - trackid = search_id or item.mb_trackid - if trackid: - log.debug(u'Searching for track ID: {0}', trackid) - for track_info in hooks.tracks_for_id(trackid): - dist = track_distance(item, track_info, incl_artist=True) - candidates[track_info.track_id] = \ - hooks.TrackMatch(dist, track_info) - # If this is a good match, then don't keep searching. - rec = _recommendation(candidates.values()) - if rec == Recommendation.strong and not config['import']['timid']: - log.debug(u'Track ID match.') - return candidates.values(), rec + trackids = search_ids or filter(None, [item.mb_trackid]) + if trackids: + for trackid in trackids: + log.debug(u'Searching for track ID: {0}', trackid) + for track_info in hooks.tracks_for_id(trackid): + dist = track_distance(item, track_info, incl_artist=True) + candidates[track_info.track_id] = \ + hooks.TrackMatch(dist, track_info) + # If this is a good match, then don't keep searching. + rec = _recommendation(candidates.values()) + if rec == Recommendation.strong and \ + not config['import']['timid']: + log.debug(u'Track ID match.') + return candidates.values(), rec # If we're searching by ID, don't proceed. - if search_id is not None: + if search_ids != []: if candidates: return candidates.values(), rec else: diff --git a/beets/importer.py b/beets/importer.py index 413750ef3..28a32ec7e 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -582,12 +582,12 @@ class ImportTask(BaseImportTask): """Retrieve and store candidates for this album. """ # Use a MusicBrainz id directly if provided by the importer -m option. - mb_id = None - if config['import']['musicbrainz_id'].exists(): - mb_id = config['import']['musicbrainz_id'].get() + mb_ids = [] + if config['import']['musicbrainz_ids'].exists(): + mb_ids = config['import']['musicbrainz_ids'].get() artist, album, candidates, recommendation = \ - autotag.tag_album(self.items, search_id=mb_id) + autotag.tag_album(self.items, search_ids=mb_ids) self.cur_artist = artist self.cur_album = album self.candidates = candidates @@ -827,12 +827,12 @@ class SingletonImportTask(ImportTask): def lookup_candidates(self): # Use a MusicBrainz id directly if provided by the importer -m option. - mb_id = None - if config['import']['musicbrainz_id'].exists(): - mb_id = config['import']['musicbrainz_id'].get() + mb_ids = [] + if config['import']['musicbrainz_ids'].exists(): + mb_ids = config['import']['musicbrainz_ids'].get() candidates, recommendation = autotag.tag_item(self.item, - search_id=mb_id) + search_ids=mb_ids) self.candidates = candidates self.rec = recommendation diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 6616cb1bc..474b6650f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -734,7 +734,7 @@ class TerminalImportSession(importer.ImportSession): search_id = manual_id(False) if search_id: _, _, candidates, rec = autotag.tag_album( - task.items, search_id=search_id + task.items, search_ids=[search_id] ) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. @@ -787,7 +787,7 @@ class TerminalImportSession(importer.ImportSession): search_id = manual_id(True) if search_id: candidates, rec = autotag.tag_item(task.item, - search_id=search_id) + search_ids=[search_id]) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) @@ -1023,7 +1023,7 @@ import_cmd.parser.add_option( help='just print the files to import' ) import_cmd.parser.add_option( - '-m', '--musicbrainzid', dest='musicbrainz_id', + '-m', '--musicbrainzid', dest='musicbrainz_ids', action='append', help='restrict the matching to a single MusicBrainz id' ) import_cmd.func = import_func diff --git a/beetsplug/bench.py b/beetsplug/bench.py index 4d6c6a656..41f575cd2 100644 --- a/beetsplug/bench.py +++ b/beetsplug/bench.py @@ -75,7 +75,7 @@ def match_benchmark(lib, prof, query=None, album_id=None): # Run the match. def _run_match(): - match.tag_album(items, search_id=album_id) + match.tag_album(items, search_ids=[album_id]) if prof: cProfile.runctx('_run_match()', {}, {'_run_match': _run_match}, 'match.prof') From 865be11ba1aa8d03b9b32a20472389a521566269 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 19 Jan 2016 21:51:41 +0100 Subject: [PATCH 0421/2280] Add tests for importer musicbrainz id argument * Add tests for the "--musicbrainzid" argument (one/several ids for matching an album/singleton; direct test on task.lookup_candidates() for album/singleton). --- test/test_importer.py | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/test/test_importer.py b/test/test_importer.py index b9f75f7ef..c088492d1 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1688,6 +1688,84 @@ class ImportPretendTest(_common.TestCase, ImportHelper): .format(displayable_path(self.empty_path))]) +class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): + """Test the --musicbrainzid argument.""" + # The Beatles - Revolver (14 tracks) + ID_REVOLVER = ('https://musicbrainz.org/release/' + 'd74365b0-288d-3b85-b344-7f9f603378b6') + # The Beatles - Rubber Soul (14 tracks) + ID_RUBBER = ('https://musicbrainz.org/release/' + 'd5d19748-72fc-3f20-aae7-7ca22da283a0') + # The Beatles - Rubber Soul - Michelle + ID_MICHELLE = ('https://musicbrainz.org/recording/' + '45846566-fb79-4758-a006-15cf69e0d138') + # The Beatles - Rubber Soul - Girl + ID_GIRL = ('https://musicbrainz.org/recording/' + '91ec42bc-a04d-497e-b829-439831c8dbcb') + + def setUp(self): + self.setup_beets() + self._create_import_dir(1) + + def tearDown(self): + self.teardown_beets() + + def test_one_mbid_one_album(self): + self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER] + self._setup_import_session() + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'Revolver') + + def test_several_mbid_one_album(self): + self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER, + self.ID_RUBBER] + self._setup_import_session() + self.importer.add_choice(2) + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'Rubber Soul') + + def test_one_mbid_one_singleton(self): + self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE] + self._setup_import_session(singletons=True) + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'Michelle') + + def test_several_mbid_one_singleton(self): + self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE, + self.ID_GIRL] + self._setup_import_session(singletons=True) + self.importer.add_choice(2) + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'Girl') + + def test_candidates_album(self): + """Test directly task.lookup_candidates().""" + self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER, + self.ID_RUBBER, + 'invalid id'] # discarded + task = importer.ImportTask(paths=self.import_dir, + toppath='top path', + items=[_common.item()]) + task.lookup_candidates() + self.assertEqual(set(['Revolver', 'Rubber Soul']), + set([c.info.album for c in task.candidates])) + + def test_candidates_singleton(self): + """Test directly task.lookup_candidates().""" + self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE, + self.ID_GIRL, + 'invalid id'] # discarded + task = importer.SingletonImportTask(toppath='top path', + item=_common.item()) + task.lookup_candidates() + self.assertEqual(set(['Michelle', 'Girl']), + set([c.info.title for c in task.candidates])) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 4e5ddac9499dd7a610897c725c2aa8edc3cda7eb Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 20 Jan 2016 17:03:16 +0100 Subject: [PATCH 0422/2280] Avoid querying MB during ImportMusicBrainzIdTest * Replace the entities used on ImportMusicBrainzIdTest mocking the calls to musicbrainzngs.get_release_by_id and musicbrainzngs.get_recording_by_id instead of querying MusicBrainz. * Other cleanup and docstring fixes. --- test/test_importer.py | 155 +++++++++++++++++++++++++++++++++--------- 1 file changed, 121 insertions(+), 34 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 880590f4d..4797bb084 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1691,82 +1691,169 @@ class ImportPretendTest(_common.TestCase, ImportHelper): class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): """Test the --musicbrainzid argument.""" - # The Beatles - Revolver (14 tracks) - ID_REVOLVER = ('https://musicbrainz.org/release/' - 'd74365b0-288d-3b85-b344-7f9f603378b6') - # The Beatles - Rubber Soul (14 tracks) - ID_RUBBER = ('https://musicbrainz.org/release/' - 'd5d19748-72fc-3f20-aae7-7ca22da283a0') - # The Beatles - Rubber Soul - Michelle - ID_MICHELLE = ('https://musicbrainz.org/recording/' - '45846566-fb79-4758-a006-15cf69e0d138') - # The Beatles - Rubber Soul - Girl - ID_GIRL = ('https://musicbrainz.org/recording/' - '91ec42bc-a04d-497e-b829-439831c8dbcb') + + MB_RELEASE_PREFIX = 'https://musicbrainz.org/release/' + MB_RECORDING_PREFIX = 'https://musicbrainz.org/recording/' + ID_RELEASE_0 = '00000000-0000-0000-0000-000000000000' + ID_RELEASE_1 = '11111111-1111-1111-1111-111111111111' + ID_RECORDING_0 = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' + ID_RECORDING_1 = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' def setUp(self): self.setup_beets() self._create_import_dir(1) + # Patch calls to musicbrainzngs. + self.release_patcher = patch('musicbrainzngs.get_release_by_id', + side_effect=mocked_get_release_by_id) + self.recording_patcher = patch('musicbrainzngs.get_recording_by_id', + side_effect=mocked_get_recording_by_id) + self.release_patcher.start() + self.recording_patcher.start() + def tearDown(self): + self.recording_patcher.stop() + self.release_patcher.stop() self.teardown_beets() def test_one_mbid_one_album(self): - self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER] + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0] self._setup_import_session() + self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Revolver') + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_0') def test_several_mbid_one_album(self): - self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER, - self.ID_RUBBER] + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1] self._setup_import_session() - self.importer.add_choice(2) + + self.importer.add_choice(2) # Pick the 2nd best match (release 1). self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Rubber Soul') + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_1') def test_one_mbid_one_singleton(self): - self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE] + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0] self._setup_import_session(singletons=True) + self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Michelle') + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_0') def test_several_mbid_one_singleton(self): - self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE, - self.ID_GIRL] + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1] self._setup_import_session(singletons=True) - self.importer.add_choice(2) + + self.importer.add_choice(2) # Pick the 2nd best match (recording 1). self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Girl') + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_1') def test_candidates_album(self): - """Test directly task.lookup_candidates().""" - self.config['import']['musicbrainz_ids'] = [self.ID_REVOLVER, - self.ID_RUBBER, - 'invalid id'] # discarded + """Test directly ImportTask.lookup_candidates().""" + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, + 'an invalid and discarded id'] + task = importer.ImportTask(paths=self.import_dir, toppath='top path', items=[_common.item()]) task.lookup_candidates() - self.assertEqual(set(['Revolver', 'Rubber Soul']), + self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), set([c.info.album for c in task.candidates])) def test_candidates_singleton(self): - """Test directly task.lookup_candidates().""" - self.config['import']['musicbrainz_ids'] = [self.ID_MICHELLE, - self.ID_GIRL, - 'invalid id'] # discarded + """Test directly SingletonImportTask.lookup_candidates().""" + self.config['import']['musicbrainz_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, + 'an invalid and discarded id'] + task = importer.SingletonImportTask(toppath='top path', item=_common.item()) task.lookup_candidates() - self.assertEqual(set(['Michelle', 'Girl']), + self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), set([c.info.title for c in task.candidates])) +# Helpers for ImportMusicBrainzIdTest. + + +def mocked_get_release_by_id(id_, includes=[], release_status=[], + release_type=[]): + """Mimic musicbrainzngs.get_release_by_id, accepting only a restricted list + of MB ids (ID_RELEASE_0, ID_RELEASE_1). The returned dict differs only in + the release title and artist name, so that ID_RELEASE_0 is a closer match + to the items created by ImportHelper._create_import_dir().""" + # Map IDs to (release title, artist), so the distances are different. + releases = {ImportMusicBrainzIdTest.ID_RELEASE_0: ('VALID_RELEASE_0', + 'TAG ARTIST'), + ImportMusicBrainzIdTest.ID_RELEASE_1: ('VALID_RELEASE_1', + 'DISTANT_MATCH')} + + return { + 'release': { + 'title': releases[id_][0], + 'id': id_, + 'medium-list': [{ + 'track-list': [{ + 'recording': { + 'title': 'foo', + 'id': 'bar', + 'length': 59, + }, + 'position': 9, + }], + 'position': 5, + }], + 'artist-credit': [{ + 'artist': { + 'name': releases[id_][1], + 'id': 'some-id', + }, + }], + 'release-group': { + 'id': 'another-id', + } + } + } + + +def mocked_get_recording_by_id(id_, includes=[], release_status=[], + release_type=[]): + """Mimic musicbrainzngs.get_recording_by_id, accepting only a restricted + list of MB ids (ID_RECORDING_0, ID_RECORDING_1). The returned dict differs + only in the recording title and artist name, so that ID_RECORDING_0 is a + closer match to the items created by ImportHelper._create_import_dir().""" + # Map IDs to (recording title, artist), so the distances are different. + releases = {ImportMusicBrainzIdTest.ID_RECORDING_0: ('VALID_RECORDING_0', + 'TAG ARTIST'), + ImportMusicBrainzIdTest.ID_RECORDING_1: ('VALID_RECORDING_1', + 'DISTANT_MATCH')} + + return { + 'recording': { + 'title': releases[id_][0], + 'id': id_, + 'length': 59, + }, + 'artist-credit': [{ + 'artist': { + 'name': releases[id_][1], + 'id': 'some-id', + }, + }], + } + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 39cf4651b8d2bcb4879af6d527acd9815bb9aebb Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 20 Jan 2016 20:22:48 +0100 Subject: [PATCH 0423/2280] Fix singleton candidate ordering when using MB id * Fix an issue that caused the candidates for a singleton not to be returned ordered by distance from autotag.match.tag_item(), when searching multiple MusicBrainz ids (ie. several "--musicbrainzid" arguments). The candidates are now explicitely reordered before being returned and before the recommendation is computed. * Fix test_importer.mocked_get_recording_by_id so that the artist is nested properly (and as a result, taken into account into the distance calculations). --- beets/autotag/match.py | 6 +++--- test/test_importer.py | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index df5183fc8..d95dc7a08 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -467,16 +467,16 @@ def tag_item(item, search_artist=None, search_title=None, candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) # If this is a good match, then don't keep searching. - rec = _recommendation(candidates.values()) + rec = _recommendation(sorted(candidates.itervalues())) if rec == Recommendation.strong and \ not config['import']['timid']: log.debug(u'Track ID match.') - return candidates.values(), rec + return sorted(candidates.itervalues()), rec # If we're searching by ID, don't proceed. if search_ids != []: if candidates: - return candidates.values(), rec + return sorted(candidates.itervalues()), rec else: return [], Recommendation.none diff --git a/test/test_importer.py b/test/test_importer.py index 4797bb084..295f1a701 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1844,13 +1844,13 @@ def mocked_get_recording_by_id(id_, includes=[], release_status=[], 'title': releases[id_][0], 'id': id_, 'length': 59, - }, - 'artist-credit': [{ - 'artist': { - 'name': releases[id_][1], - 'id': 'some-id', - }, - }], + 'artist-credit': [{ + 'artist': { + 'name': releases[id_][1], + 'id': 'some-id', + }, + }], + } } From b5262274827da83d3d39a4d23a09d3ebc69b63c7 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 21 Jan 2016 17:08:53 +0100 Subject: [PATCH 0424/2280] Cleanup and documentation for MB_id importer arg * Style cleanup and fixes for the "--musicbrainzid" import argument. * Allow the input of several IDs (separated by spaces) on the "enter Id" importer prompt. * Add basic documentation. --- beets/autotag/match.py | 12 ++++++++---- beets/config_default.yaml | 1 + beets/importer.py | 8 ++------ beets/ui/commands.py | 6 +++--- docs/guides/tagger.rst | 9 +++++++-- docs/reference/cli.rst | 5 +++++ 6 files changed, 26 insertions(+), 15 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index d95dc7a08..8baaf0108 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -380,8 +380,11 @@ def tag_album(items, search_artist=None, search_album=None, The `AlbumMatch` objects are generated by searching the metadata backends. By default, the metadata of the items is used for the - search. This can be customized by setting the parameters. The - `mapping` field of the album has the matched `items` as keys. + search. This can be customized by setting the parameters. + `search_ids` is a list of MusicBrainz release IDs: if specified, + it will restrict the candidates to those IDs, ignoring + `search_artist` and `search album`. The `mapping` field of the + album has the matched `items` as keys. The recommendation is calculated from the match quality of the candidates. @@ -451,7 +454,8 @@ def tag_item(item, search_artist=None, search_title=None, `(candidates, recommendation)` pair where `candidates` is a list of TrackMatch objects. `search_artist` and `search_title` may be used to override the current metadata for the purposes of the MusicBrainz - title; likewise `search_ids`. + title. `search_ids` may be used for restricting the search to a list + of MusicBrainz IDs. """ # Holds candidates found so far: keys are MBIDs; values are # (distance, TrackInfo) pairs. @@ -474,7 +478,7 @@ def tag_item(item, search_artist=None, search_title=None, return sorted(candidates.itervalues()), rec # If we're searching by ID, don't proceed. - if search_ids != []: + if search_ids: if candidates: return sorted(candidates.itervalues()), rec else: diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 545fa9638..3fdfaf836 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -22,6 +22,7 @@ import: flat: no group_albums: no pretend: false + musicbrainz_ids: [] clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information"] diff --git a/beets/importer.py b/beets/importer.py index 28a32ec7e..519eecc7e 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -582,9 +582,7 @@ class ImportTask(BaseImportTask): """Retrieve and store candidates for this album. """ # Use a MusicBrainz id directly if provided by the importer -m option. - mb_ids = [] - if config['import']['musicbrainz_ids'].exists(): - mb_ids = config['import']['musicbrainz_ids'].get() + mb_ids = config['import']['musicbrainz_ids'].as_str_seq() artist, album, candidates, recommendation = \ autotag.tag_album(self.items, search_ids=mb_ids) @@ -827,9 +825,7 @@ class SingletonImportTask(ImportTask): def lookup_candidates(self): # Use a MusicBrainz id directly if provided by the importer -m option. - mb_ids = [] - if config['import']['musicbrainz_ids'].exists(): - mb_ids = config['import']['musicbrainz_ids'].get() + mb_ids = config['import']['musicbrainz_ids'].as_str_seq() candidates, recommendation = autotag.tag_item(self.item, search_ids=mb_ids) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 74a6da0ed..c68dcf10f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -734,7 +734,7 @@ class TerminalImportSession(importer.ImportSession): search_id = manual_id(False) if search_id: _, _, candidates, rec = autotag.tag_album( - task.items, search_ids=[search_id] + task.items, search_ids=search_id.split(' ') ) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. @@ -786,8 +786,8 @@ class TerminalImportSession(importer.ImportSession): # Ask for a track ID. search_id = manual_id(True) if search_id: - candidates, rec = autotag.tag_item(task.item, - search_ids=[search_id]) + candidates, rec = autotag.tag_item( + task.item, search_ids=search_id.split(' ')) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 4a4c56184..95975c038 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -160,10 +160,10 @@ When beets needs your input about a match, it says something like this:: Beirut - Lon Gisland (Similarity: 94.4%) * Scenic World (Second Version) -> Scenic World - [A]pply, More candidates, Skip, Use as-is, as Tracks, Enter search, or aBort? + [A]pply, More candidates, Skip, Use as-is, as Tracks, Enter search, enter Id, or aBort? When beets asks you this question, it wants you to enter one of the capital -letters: A, M, S, U, T, G, E, or B. That is, you can choose one of the +letters: A, M, S, U, T, G, E, I or B. That is, you can choose one of the following: * *A*: Apply the suggested changes shown and move on. @@ -190,6 +190,11 @@ following: option if beets hasn't found any good options because the album is mistagged or untagged. +* *I*: Enter a MusicBrainz id to use as search in the database. Use this option + to specify a MusicBrainz entity (release or recording) directly, by pasting + its ID or the full URL. You can also specify several IDs by separating them + by a space. + * *B*: Cancel this import task altogether. No further albums will be tagged; beets shuts down immediately. The next time you attempt to import the same directory, though, beets will ask you if you want to resume tagging where you diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index c072c0c0f..25b3fcbc1 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -132,6 +132,11 @@ Optional command flags: option. If set, beets will just print a list of files that it would otherwise import. +* If you already have a MusicBrainz ID that matches the items to be imported, + you can instruct beets to restrict the search to that ID instead of searching + for other candidates by using the ``--musicbrainzid MB_ID`` option. Multiple + IDs can be specified by simply repeating the option several times. + .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 .. only:: html From 4eedd2bd8dbf9073eddfb94ed593dba12981df07 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 21 Jan 2016 20:33:54 +0100 Subject: [PATCH 0425/2280] Store user-supplied MB ids on the Tasks * Store the user-supplied MusicBrainz IDs (via the "--musicbrainzid" importer argument) on ImporTask.task.musicbrainz_ids during the lookup_candidates() pipeline stage. * Update test cases to reflect the changes. --- beets/importer.py | 22 ++++++++++++---------- test/test_importer.py | 18 ++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 519eecc7e..fb7195bc6 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -434,6 +434,7 @@ class ImportTask(BaseImportTask): self.rec = None self.should_remove_duplicates = False self.is_album = True + self.musicbrainz_ids = [] # user-supplied candidate IDs. def set_choice(self, choice): """Given an AlbumMatch or TrackMatch object or an action constant, @@ -579,13 +580,12 @@ class ImportTask(BaseImportTask): return tasks def lookup_candidates(self): - """Retrieve and store candidates for this album. + """Retrieve and store candidates for this album. User-specified + candidate IDs are stored in self.musicbrainz_ids: if present, the + initial lookup is restricted to only those IDs. """ - # Use a MusicBrainz id directly if provided by the importer -m option. - mb_ids = config['import']['musicbrainz_ids'].as_str_seq() - artist, album, candidates, recommendation = \ - autotag.tag_album(self.items, search_ids=mb_ids) + autotag.tag_album(self.items, search_ids=self.musicbrainz_ids) self.cur_artist = artist self.cur_album = album self.candidates = candidates @@ -824,11 +824,8 @@ class SingletonImportTask(ImportTask): plugins.send('item_imported', lib=lib, item=item) def lookup_candidates(self): - # Use a MusicBrainz id directly if provided by the importer -m option. - mb_ids = config['import']['musicbrainz_ids'].as_str_seq() - - candidates, recommendation = autotag.tag_item(self.item, - search_ids=mb_ids) + candidates, recommendation = autotag.tag_item( + self.item, search_ids=self.musicbrainz_ids) self.candidates = candidates self.rec = recommendation @@ -1253,6 +1250,11 @@ def lookup_candidates(session, task): plugins.send('import_task_start', session=session, task=task) log.debug(u'Looking up: {0}', displayable_path(task.paths)) + + # Restrict the initial lookup to IDs specified by the user via the -m + # option. Currently all the IDs are passed onto the tasks directly. + task.musicbrainz_ids = session.config['musicbrainz_ids'].as_str_seq() + task.lookup_candidates() diff --git a/test/test_importer.py b/test/test_importer.py index 295f1a701..21c11bc6e 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1758,27 +1758,25 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): def test_candidates_album(self): """Test directly ImportTask.lookup_candidates().""" - self.config['import']['musicbrainz_ids'] = \ - [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, - self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, - 'an invalid and discarded id'] - task = importer.ImportTask(paths=self.import_dir, toppath='top path', items=[_common.item()]) + task.musicbrainz_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, + 'an invalid and discarded id'] + task.lookup_candidates() self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), set([c.info.album for c in task.candidates])) def test_candidates_singleton(self): """Test directly SingletonImportTask.lookup_candidates().""" - self.config['import']['musicbrainz_ids'] = \ - [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, - self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, - 'an invalid and discarded id'] - task = importer.SingletonImportTask(toppath='top path', item=_common.item()) + task.musicbrainz_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, + 'an invalid and discarded id'] + task.lookup_candidates() self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), set([c.info.title for c in task.candidates])) From ba5b39cd463ef408f8def2970804dceb8199285b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 21 Jan 2016 13:57:24 -0800 Subject: [PATCH 0426/2280] Avoid including .pyc in source distribution Fix #1825. Inspired by: https://github.com/mitsuhiko/flask/blob/master/MANIFEST.in --- MANIFEST.in | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MANIFEST.in b/MANIFEST.in index e040a9c34..3e64d2781 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,6 +1,8 @@ # Include tests (but avoid including *.pyc, etc.) prune test recursive-include test/rsrc * +recursive-exclude test/rsrc *.pyc +recursive-exclude test/rsrc *.pyo include test/*.py # Include relevant text files. From 79d84c0e4f2325c4102dd1febacf642b811b05a4 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 22 Jan 2016 16:31:00 +0100 Subject: [PATCH 0427/2280] Style and doc fixes for MB_id importer argument * Rename the importer argument and related variables to make it more generic, as the feature should be independent of the backend used and not restricted to MusicBrainz. * Update documentation and docstrings accordingly. * Add changelog entry. --- beets/autotag/match.py | 4 ++-- beets/config_default.yaml | 2 +- beets/importer.py | 10 +++++----- beets/ui/commands.py | 9 +++++---- docs/changelog.rst | 4 ++++ docs/guides/tagger.rst | 12 ++++++------ docs/reference/cli.rst | 8 ++++---- test/test_importer.py | 20 ++++++++++---------- 8 files changed, 37 insertions(+), 32 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 8baaf0108..3565dba3f 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -381,7 +381,7 @@ def tag_album(items, search_artist=None, search_album=None, The `AlbumMatch` objects are generated by searching the metadata backends. By default, the metadata of the items is used for the search. This can be customized by setting the parameters. - `search_ids` is a list of MusicBrainz release IDs: if specified, + `search_ids` is a list of metadata backend IDs: if specified, it will restrict the candidates to those IDs, ignoring `search_artist` and `search album`. The `mapping` field of the album has the matched `items` as keys. @@ -455,7 +455,7 @@ def tag_item(item, search_artist=None, search_title=None, TrackMatch objects. `search_artist` and `search_title` may be used to override the current metadata for the purposes of the MusicBrainz title. `search_ids` may be used for restricting the search to a list - of MusicBrainz IDs. + of metadata backend IDs. """ # Holds candidates found so far: keys are MBIDs; values are # (distance, TrackInfo) pairs. diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 3fdfaf836..5bc921167 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -22,7 +22,7 @@ import: flat: no group_albums: no pretend: false - musicbrainz_ids: [] + search_ids: [] clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information"] diff --git a/beets/importer.py b/beets/importer.py index fb7195bc6..868ac6922 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -434,7 +434,7 @@ class ImportTask(BaseImportTask): self.rec = None self.should_remove_duplicates = False self.is_album = True - self.musicbrainz_ids = [] # user-supplied candidate IDs. + self.search_ids = [] # user-supplied candidate IDs. def set_choice(self, choice): """Given an AlbumMatch or TrackMatch object or an action constant, @@ -581,11 +581,11 @@ class ImportTask(BaseImportTask): def lookup_candidates(self): """Retrieve and store candidates for this album. User-specified - candidate IDs are stored in self.musicbrainz_ids: if present, the + candidate IDs are stored in self.search_ids: if present, the initial lookup is restricted to only those IDs. """ artist, album, candidates, recommendation = \ - autotag.tag_album(self.items, search_ids=self.musicbrainz_ids) + autotag.tag_album(self.items, search_ids=self.search_ids) self.cur_artist = artist self.cur_album = album self.candidates = candidates @@ -825,7 +825,7 @@ class SingletonImportTask(ImportTask): def lookup_candidates(self): candidates, recommendation = autotag.tag_item( - self.item, search_ids=self.musicbrainz_ids) + self.item, search_ids=self.search_ids) self.candidates = candidates self.rec = recommendation @@ -1253,7 +1253,7 @@ def lookup_candidates(session, task): # Restrict the initial lookup to IDs specified by the user via the -m # option. Currently all the IDs are passed onto the tasks directly. - task.musicbrainz_ids = session.config['musicbrainz_ids'].as_str_seq() + task.search_ids = session.config['search_ids'].as_str_seq() task.lookup_candidates() diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c68dcf10f..3e3acb7c3 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -734,7 +734,7 @@ class TerminalImportSession(importer.ImportSession): search_id = manual_id(False) if search_id: _, _, candidates, rec = autotag.tag_album( - task.items, search_ids=search_id.split(' ') + task.items, search_ids=search_id.split() ) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. @@ -787,7 +787,7 @@ class TerminalImportSession(importer.ImportSession): search_id = manual_id(True) if search_id: candidates, rec = autotag.tag_item( - task.item, search_ids=search_id.split(' ')) + task.item, search_ids=search_id.split()) elif choice in extra_ops.keys(): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) @@ -1023,8 +1023,9 @@ import_cmd.parser.add_option( help='just print the files to import' ) import_cmd.parser.add_option( - '-m', '--musicbrainzid', dest='musicbrainz_ids', action='append', - help='restrict the matching to a single MusicBrainz id' + '-S', '--search-id', dest='search_ids', action='append', + metavar='BACKEND_ID', + help='restrict matching to a specific metadata backend ID' ) import_cmd.func = import_func default_commands.append(import_cmd) diff --git a/docs/changelog.rst b/docs/changelog.rst index 51fab3100..b6c8bfb25 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,10 @@ New: session. :bug:`1779` * :doc:`/plugins/info`: A new option will print only fields' names and not their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` +* A new ``--search-id`` importer option lets you specify one or several + matching MusicBrainz/Discogs IDs directly, bypassing the default initial + candidate search. Also, the ``enter Id`` prompt choice now accepts several + IDs, separated by spaces. :bug:`1808` .. _AcousticBrainz: http://acousticbrainz.org/ diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 95975c038..0b21644bf 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -60,8 +60,8 @@ all of these limitations. because beets by default infers tags based on existing metadata. But this is not a hard and fast rule---there are a few ways to tag metadata-poor music: - * You can use the *E* option described below to search in MusicBrainz for - a specific album or song. + * You can use the *E* or *I* options described below to search in + MusicBrainz for a specific album or song. * The :doc:`Acoustid plugin ` extends the autotagger to use acoustic fingerprinting to find information for arbitrary audio. Install that plugin if you're willing to spend a little more CPU power @@ -190,10 +190,10 @@ following: option if beets hasn't found any good options because the album is mistagged or untagged. -* *I*: Enter a MusicBrainz id to use as search in the database. Use this option - to specify a MusicBrainz entity (release or recording) directly, by pasting - its ID or the full URL. You can also specify several IDs by separating them - by a space. +* *I*: Enter a metadata backend ID to use as search in the database. Use this + option to specify a backend entity (for example, a MusicBrainz release or + recording) directly, by pasting its ID or the full URL. You can also specify + several IDs by separating them by a space. * *B*: Cancel this import task altogether. No further albums will be tagged; beets shuts down immediately. The next time you attempt to import the same diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 25b3fcbc1..2ded2c48d 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -132,10 +132,10 @@ Optional command flags: option. If set, beets will just print a list of files that it would otherwise import. -* If you already have a MusicBrainz ID that matches the items to be imported, - you can instruct beets to restrict the search to that ID instead of searching - for other candidates by using the ``--musicbrainzid MB_ID`` option. Multiple - IDs can be specified by simply repeating the option several times. +* If you already have a metadata backend ID that matches the items to be + imported, you can instruct beets to restrict the search to that ID instead of + searching for other candidates by using the ``--search_id SEARCH_ID`` option. + Multiple IDs can be specified by simply repeating the option several times. .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 diff --git a/test/test_importer.py b/test/test_importer.py index 21c11bc6e..56f4a17a5 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1717,7 +1717,7 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): self.teardown_beets() def test_one_mbid_one_album(self): - self.config['import']['musicbrainz_ids'] = \ + self.config['import']['search_ids'] = \ [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0] self._setup_import_session() @@ -1726,7 +1726,7 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_0') def test_several_mbid_one_album(self): - self.config['import']['musicbrainz_ids'] = \ + self.config['import']['search_ids'] = \ [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, self.MB_RELEASE_PREFIX + self.ID_RELEASE_1] self._setup_import_session() @@ -1737,7 +1737,7 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_1') def test_one_mbid_one_singleton(self): - self.config['import']['musicbrainz_ids'] = \ + self.config['import']['search_ids'] = \ [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0] self._setup_import_session(singletons=True) @@ -1746,7 +1746,7 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_0') def test_several_mbid_one_singleton(self): - self.config['import']['musicbrainz_ids'] = \ + self.config['import']['search_ids'] = \ [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, self.MB_RECORDING_PREFIX + self.ID_RECORDING_1] self._setup_import_session(singletons=True) @@ -1761,9 +1761,9 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): task = importer.ImportTask(paths=self.import_dir, toppath='top path', items=[_common.item()]) - task.musicbrainz_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, - self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, - 'an invalid and discarded id'] + task.search_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, + 'an invalid and discarded id'] task.lookup_candidates() self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), @@ -1773,9 +1773,9 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): """Test directly SingletonImportTask.lookup_candidates().""" task = importer.SingletonImportTask(toppath='top path', item=_common.item()) - task.musicbrainz_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, - self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, - 'an invalid and discarded id'] + task.search_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, + 'an invalid and discarded id'] task.lookup_candidates() self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), From 4f51302d09cfaab99ceaec020f6672ebd7a991a4 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 22 Jan 2016 19:48:22 +0100 Subject: [PATCH 0428/2280] Fix typo on importer search by id documentation --- docs/reference/cli.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 2ded2c48d..8c04b6c90 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -134,7 +134,7 @@ Optional command flags: * If you already have a metadata backend ID that matches the items to be imported, you can instruct beets to restrict the search to that ID instead of - searching for other candidates by using the ``--search_id SEARCH_ID`` option. + searching for other candidates by using the ``--search-id SEARCH_ID`` option. Multiple IDs can be specified by simply repeating the option several times. .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 From b49426046a9a02e02a29ff26b8bdb5ad0f5cf896 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 22 Jan 2016 21:33:33 +0100 Subject: [PATCH 0429/2280] Fix unrestored AutotagStub on two TestCases * Call AutotagStub.restore() during the tearDown of test_mbsubmit.MBSubmitPluginTest and test_plugins.PromptChoicesTest, which could potentially lead to other tests calling mocked versions of autotag.mb.match_album, .match_track, .album_for_id and .track_for_id instead of the real functions. --- test/test_mbsubmit.py | 1 + test/test_plugins.py | 1 + 2 files changed, 2 insertions(+) diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index 5047fd3d0..808af9d8c 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -34,6 +34,7 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, def tearDown(self): self.unload_plugins() self.teardown_beets() + self.matcher.restore() def test_print_tracks_output(self): """Test the output of the "print tracks" choice.""" diff --git a/test/test_plugins.py b/test/test_plugins.py index 6f8035511..eaf2e83ed 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -419,6 +419,7 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.input_options_patcher.stop() self.teardown_plugin_loader() self.teardown_beets() + self.matcher.restore() def test_plugin_choices_in_ui_input_options_album(self): """Test the presence of plugin choices on the prompt (album).""" From a18d0e4b3bfc38510cd9cc330bb9533afe4d03ed Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 22 Jan 2016 15:22:48 -0800 Subject: [PATCH 0430/2280] Make bash-completion test more robust I found some infelicities while investigating #1826. This test was hard-coding a specific path for bash-completion, which was the wrong one for my system, so it was being skipped every time. This searches the list of paths used by the actual command. --- test/test_ui.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index ed1740643..6c433e46d 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -39,6 +39,7 @@ from beets.mediafile import MediaFile from beets import config from beets import plugins from beets.util.confit import ConfigError +from beets import util class ListTest(unittest.TestCase): @@ -1051,12 +1052,6 @@ class CompletionTest(_common.TestCase): config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] config['plugins'] = ['test'] - test_script = os.path.join( - os.path.dirname(__file__), 'test_completion.sh' - ) - bash_completion = os.path.abspath(os.environ.get( - 'BASH_COMPLETION_SCRIPT', '/etc/bash_completion')) - # Tests run in bash cmd = os.environ.get('BEETS_TEST_SHELL', '/bin/bash --norc').split() if not has_program(cmd[0]): @@ -1064,21 +1059,30 @@ class CompletionTest(_common.TestCase): tester = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - # Load bash_completion - try: - with open(bash_completion, 'r') as bash_completion: - tester.stdin.writelines(bash_completion) - except IOError: + # Load bash_completion library. + for path in commands.BASH_COMPLETION_PATHS: + if os.path.exists(util.syspath(path)): + bash_completion = path + break + else: self.skipTest('bash-completion script not found') + try: + with open(util.syspath(bash_completion), 'r') as f: + tester.stdin.writelines(f) + except IOError: + self.skipTest('could not read bash-completion script') - # Load complection script + # Load completion script. self.io.install() ui._raw_main(['completion']) completion_script = self.io.getoutput() self.io.restore() tester.stdin.writelines(completion_script) - # Load testsuite + # Load test suite. + test_script = os.path.join( + os.path.dirname(__file__), 'test_completion.sh' + ) with open(test_script, 'r') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() From a07cb837aa3257e1e7b6b0265e468b5fa3587df4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 22 Jan 2016 15:25:43 -0800 Subject: [PATCH 0431/2280] Fix #1826: include test_completion.sh in sdist --- test/{ => rsrc}/test_completion.sh | 0 test/test_ui.py | 4 +--- 2 files changed, 1 insertion(+), 3 deletions(-) rename test/{ => rsrc}/test_completion.sh (100%) diff --git a/test/test_completion.sh b/test/rsrc/test_completion.sh similarity index 100% rename from test/test_completion.sh rename to test/rsrc/test_completion.sh diff --git a/test/test_ui.py b/test/test_ui.py index 6c433e46d..61f20f83b 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1080,9 +1080,7 @@ class CompletionTest(_common.TestCase): tester.stdin.writelines(completion_script) # Load test suite. - test_script = os.path.join( - os.path.dirname(__file__), 'test_completion.sh' - ) + test_script = os.path.join(_common.RSRC, 'test_completion.sh') with open(test_script, 'r') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() From 5f8e710e073b57733747bb6bbde05cfd9dac48c2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jan 2016 10:27:36 -0800 Subject: [PATCH 0432/2280] Fix configuration in ReplayGain tests (#1830) --- test/test_replaygain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 2cb0446fd..edbfb96db 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -44,6 +44,7 @@ class ReplayGainCliTestBase(TestHelper): def setUp(self): self.setup_beets() + self.config['replaygain']['backend'] = self.backend try: self.load_plugins('replaygain') @@ -61,7 +62,6 @@ class ReplayGainCliTestBase(TestHelper): pass raise exc_info[1], None, exc_info[2] - self.config['replaygain']['backend'] = self.backend album = self.add_album_fixture(2) for item in album.items(): self._reset_replaygain(item) From 4634c7a9b84e4d5299af66f7cacda8750e213ce7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jan 2016 13:19:26 -0800 Subject: [PATCH 0433/2280] Add new livereload server for docs --- docs/Makefile | 4 ---- docs/refresh_safari.js | 19 ------------------- docs/serve.py | 5 +++++ 3 files changed, 5 insertions(+), 23 deletions(-) delete mode 100644 docs/refresh_safari.js create mode 100644 docs/serve.py diff --git a/docs/Makefile b/docs/Makefile index fd1707f27..f940dd931 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -38,10 +38,6 @@ help: @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" -# My magical rebuilding, Safari-reloading auto target. -auto: - watchmedo shell-command --patterns='*.rst' --ignore-pattern='_build/*' --recursive --command='if [ "$${watch_event_type}" == "created" -o "$${watch_event_type}" == "modified" ]; then make html ; osascript -l JavaScript refresh_safari.js; fi' --wait - clean: -rm -rf $(BUILDDIR)/* diff --git a/docs/refresh_safari.js b/docs/refresh_safari.js deleted file mode 100644 index 7f5cc0ccc..000000000 --- a/docs/refresh_safari.js +++ /dev/null @@ -1,19 +0,0 @@ -var safari = Application('com.apple.Safari'); - -for (var i = 0; i < safari.windows.length; ++i) { - var win = safari.windows[i]; - var tabs = win.tabs; - if (Object.keys(tabs).length) { - for (var j = 0; j < win.tabs.length; ++j) { - var tab = win.tabs[j]; - var url = tab.url(); - if (url.indexOf("file:") == 0) { - // A local file URL. - safari.doJavaScript("location.reload();", { in: tab }); - console.log(url); - } - } - } -} - -'done'; diff --git a/docs/serve.py b/docs/serve.py new file mode 100644 index 000000000..48673ea8d --- /dev/null +++ b/docs/serve.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +from livereload import Server, shell +server = Server() +server.watch('*.rst', shell('make html')) +server.serve(root='_build/html') From 0c839ae235afeeafee2487b8c080fae80f9485f5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jan 2016 13:53:38 -0800 Subject: [PATCH 0434/2280] Clean up changelog (ready for release?) --- docs/changelog.rst | 52 +++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b6c8bfb25..5a9cd366f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,49 +6,45 @@ Changelog As of this release, the beets project has some new Internet homes! Our new domain name is `beets.io`_, and we have a shiny new GitHub organization: -`Beetbox`_. +`beetbox`_. New: +* A new :doc:`/plugins/acousticbrainz` fetches acoustic-analysis information + from the `AcousticBrainz`_ project. Thanks to :user:`opatel99`, and thanks + to `Google Code-In`_! :bug:`1784` +* A new :doc:`/plugins/mbsubmit` lets you print music's current metadata in a + format that the MusicBrainz data parser can understand. You can trigger it + during an interactive import session. :bug:`1779` +* A new ``--search-id`` importer option lets you manually specify + IDs (i.e., MBIDs or Discogs IDs) for imported music. Doing this skips the + initial candidate search, which can be important for huge albums where this + initial lookup is slow. + Also, the ``enter Id`` prompt choice now accepts several IDs, separated by + spaces. :bug:`1808` * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It now requires an API key from Google. Thanks to :user:`lcharlick`. :bug:`1778` -* A new :doc:`/plugins/acousticbrainz` fetches acoustic-analysis information - from the `AcousticBrainz`_ project. Thanks to :user:`opatel99`. :bug:`1784` -* A new :doc:`/plugins/mbsubmit` lets you print the tracks of an album in a - format parseable by MusicBrainz track parser during an interactive import - session. :bug:`1779` * :doc:`/plugins/info`: A new option will print only fields' names and not their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` -* A new ``--search-id`` importer option lets you specify one or several - matching MusicBrainz/Discogs IDs directly, bypassing the default initial - candidate search. Also, the ``enter Id`` prompt choice now accepts several - IDs, separated by spaces. :bug:`1808` +.. _Google Code-In: https://codein.withgoogle.com/ .. _AcousticBrainz: http://acousticbrainz.org/ Fixes: -* :doc:`/plugins/play`: Remove dead code. From this point on, beets isn't - supposed and won't try to delete the playlists generated by ``beet play`` - (Note that although it was supposed to, beet didn't actually remove the - generated ``.m3u`` files beforehand either.). If this is an issue for you, you - might want to take a look at the ``raw`` config option of the - :doc:`/plugins/play`. :bug:`1785`, :bug:`1600` -* The :ref:`move-cmd` command does not display files whose path does not change - anymore. :bug:`1583` +* The :ref:`move-cmd` command no longer not prints filenames for files that + don't actually need to be moved. :bug:`1583` * :doc:`/plugins/play`: Fix a regression in the last version where there was no default command. :bug:`1793` -* :doc:`/plugins/lastimport`: Switched API method from library.getTracks to - user.getTopTracks. This fixes :bug:`1574`, which was caused by the former API - method being removed. Also moved from custom HTTP requests to using pylast - library. -* Fix typos. For the :doc:`/plugins/play`, the recommended configuration option - to set the warning threshold is now ``warning_threshold`` (instead of - ``warning_treshold``) but backwards compatibility is preserved until the next - major version so ``warning_treshold`` will still work. Thanks to - :user:`JesseWeinstein`. :bug:`1802` :bug:`1803` -* :doc:`/plugins/lyrics`: The Genius backend has been re-enabled. +* :doc:`/plugins/lastimport`: The plugin now works again after being broken by + some unannounced changes to the Last.fm API. :bug:`1574` +* :doc:`/plugins/play`: Fixed a typo in a configuration option. The option is + now ``warning_threshold`` instead of ``warning_treshold``, but we kept the + old name around for compatibility. Thanks to :user:`JesseWeinstein`. + :bug:`1802` :bug:`1803` +* :doc:`/plugins/lyrics`: The Genius backend has been re-enabled (after being + temporarily disabled in the last version). * :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate (like the :ref:`modify-cmd` command). :bug:`1804` * The :ref:`stats-cmd` command no longer crashes when files are missing or From d2cec48c651be8de93c69c00251f0d9f6ab02432 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 26 Jan 2016 17:59:51 +0100 Subject: [PATCH 0435/2280] Skip GStreamer tests if plugins are missing * Add a check to ReplayGainGstCliTest that ensures that the required initial gstreamer plugins can be loaded, skipping the test if it is not the case instead of running it. * Add a check to ReplayGainGstCliTest.test_cli_saves_track_gain for checking if item.rg_track_peak and item.rg_track_gain is not None. If they are None, it is assumed that the decoder plugins could not be found, and the tests is skipped, as discussed on #1830. --- test/test_replaygain.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test/test_replaygain.py b/test/test_replaygain.py index edbfb96db..4eefb4eff 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -20,7 +20,9 @@ from __future__ import (division, absolute_import, print_function, from test._common import unittest from test.helper import TestHelper, has_program +from beets import config from beets.mediafile import MediaFile +from beetsplug.replaygain import FatalReplayGainError, GStreamerBackend try: import gi @@ -87,6 +89,13 @@ class ReplayGainCliTestBase(TestHelper): self.assertIsNone(mediafile.rg_track_gain) self.run_command('replaygain') + + # Skip the test if rg_track_peak and rg_track gain is None, assuming + # that it could only happen if the decoder plugins are missing. + if all(i.rg_track_peak is None and i.rg_track_gain is None + for i in self.lib.items()): + self.skipTest('decoder plugins could not be loaded.') + for item in self.lib.items(): self.assertIsNotNone(item.rg_track_peak) self.assertIsNotNone(item.rg_track_gain) @@ -132,6 +141,20 @@ class ReplayGainCliTestBase(TestHelper): class ReplayGainGstCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'gstreamer' + def setUp(self): + try: + # Check if required plugins can be loaded by instantiating a + # GStreamerBackend (via its .__init__). + config['replaygain']['targetlevel'] = 89 + GStreamerBackend(config['replaygain'], None) + except FatalReplayGainError as e: + # Skip the test if plugins could not be loaded. + if str(e) == "Failed to load required GStreamer plugins": + self.skipTest(str(e)) + else: + raise e + super(ReplayGainGstCliTest, self).setUp() + @unittest.skipIf(not GAIN_PROG_AVAILABLE, 'no *gain command found') class ReplayGainCmdCliTest(ReplayGainCliTestBase, unittest.TestCase): From 76d7c65c1be2846916b19b155796383d5f02d6a7 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 26 Jan 2016 22:20:42 +0100 Subject: [PATCH 0436/2280] replaygain: refine test by subclassing exception * Subclass FatalReplayGainError into FatalGstreamerPluginReplayGainError in order to handle gstreamer plugin errors more cleanly on test_replaygain. --- beetsplug/replaygain.py | 7 ++++++- test/test_replaygain.py | 11 +++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index db4d202a6..acf996bd2 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -43,6 +43,11 @@ class FatalReplayGainError(Exception): """ +class FatalGstreamerPluginReplayGainError(FatalReplayGainError): + """Raised when a fatal error occurs in the GStreamerBackend when + loading the required plugins.""" + + def call(args): """Execute the command and return its output or raise a ReplayGainError on failure. @@ -391,7 +396,7 @@ class GStreamerBackend(Backend): if self._src is None or self._decbin is None or self._conv is None \ or self._res is None or self._rg is None: - raise FatalReplayGainError( + raise FatalGstreamerPluginReplayGainError( "Failed to load required GStreamer plugins" ) diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 4eefb4eff..5b20f5f3b 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -22,7 +22,8 @@ from test.helper import TestHelper, has_program from beets import config from beets.mediafile import MediaFile -from beetsplug.replaygain import FatalReplayGainError, GStreamerBackend +from beetsplug.replaygain import (FatalGstreamerPluginReplayGainError, + GStreamerBackend) try: import gi @@ -147,12 +148,10 @@ class ReplayGainGstCliTest(ReplayGainCliTestBase, unittest.TestCase): # GStreamerBackend (via its .__init__). config['replaygain']['targetlevel'] = 89 GStreamerBackend(config['replaygain'], None) - except FatalReplayGainError as e: + except FatalGstreamerPluginReplayGainError as e: # Skip the test if plugins could not be loaded. - if str(e) == "Failed to load required GStreamer plugins": - self.skipTest(str(e)) - else: - raise e + self.skipTest(str(e)) + super(ReplayGainGstCliTest, self).setUp() From c7fff5232447b7606407b9e3b1df6cd6a85e1323 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 27 Jan 2016 19:12:49 +0100 Subject: [PATCH 0437/2280] Fixed bug when running subset of testcases Happens when invoking `tox -e py27 test.test_ui` directly. `os.environ.get('HOME')` seems to return None and raises an Exception in tearDown of class --- test/test_ui.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index 61f20f83b..609c21c00 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -632,7 +632,8 @@ class ConfigTest(unittest.TestCase, TestHelper): def tearDown(self): commands.default_commands.pop() os.chdir(self._orig_cwd) - os.environ['HOME'] = self._old_home + if self._old_home is not None: + os.environ['HOME'] = self._old_home self.teardown_beets() def _make_test_cmd(self): From b7a2a42d9c9c166dd2629c1c93e8d346d41f3763 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 28 Jan 2016 13:01:44 +0100 Subject: [PATCH 0438/2280] Fix docs on plugin prompt choices conflict solving * Fix docstring and `plugins.rst` regarding how the PromptChoices that use the same short letter are handled (they are discarded instead of raising an Exception). --- beets/ui/commands.py | 4 +++- docs/dev/plugins.rst | 9 +++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 3e3acb7c3..41f118bc6 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -853,7 +853,9 @@ class TerminalImportSession(importer.ImportSession): checking the right conditions and returning a list of `PromptChoice`s, which is flattened and checked for conflicts. - Raises `ValueError` if two of the choices have the same short letter. + If two or more choices have the same short letter, a warning is + emitted and all but one choices are discarded, giving preference + to the default importer choices. Returns a list of `PromptChoice`s. """ diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index b7c5d82f9..80409d5f5 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -585,10 +585,11 @@ album has no candidates, the relevant checks against ``task.candidates`` should be performed inside the plugin's ``before_choose_candidate_event`` accordingly. Please make sure that the short letter for each of the choices provided by the -plugin is not already in use: the importer will raise an exception if two or -more choices try to use the same short letter. As a reference, the following -characters are used by the choices on the core importer prompt, and hence -should not be used: ``a``, ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. +plugin is not already in use: the importer will emit a warning and discard +all but one of the choices using the same letter, giving priority to the +core importer prompt choices. As a reference, the following characters are used +by the choices on the core importer prompt, and hence should not be used: +``a``, ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. Additionally, the callback function can optionally specify the next action to be performed by returning one of the values from ``importer.action``, which From 8954f1a494e7fcdf551b83c4101949e6b302fc1c Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 27 Jan 2016 19:42:53 +0100 Subject: [PATCH 0439/2280] split of modify function in modify_test --- test/test_ui.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 609c21c00..58eecee46 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -158,10 +158,13 @@ class ModifyTest(unittest.TestCase, TestHelper): def tearDown(self): self.teardown_beets() - def modify(self, *args): - with control_stdin('y'): + def modify_inp(self, inp, *args): + with control_stdin(inp): ui._raw_main(['modify'] + list(args), self.lib) + def modify(self, *args): + self.modify_inp('y', *args) + # Item tests def test_modify_item(self): From e0ffae3be055ab71236d30f9893c2d0dc1f75cae Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 27 Jan 2016 19:43:31 +0100 Subject: [PATCH 0440/2280] added test case for Modify without any change --- test/test_ui.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index 58eecee46..07d292bbe 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -172,6 +172,13 @@ class ModifyTest(unittest.TestCase, TestHelper): item = self.lib.items().get() self.assertEqual(item.title, 'newTitle') + def test_modify_item_no_change(self): + title = "Tracktitle" + item = self.add_item_fixture(title=title) + self.modify_inp('y', "title", "title={0}".format(title)) + item = self.lib.items(title).get() + self.assertEqual(item.title, title) + def test_modify_write_tags(self): self.modify("title=newTitle") item = self.lib.items().get() From a707715b81a7db8be82264f5cb1ba4ce0e193895 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 27 Jan 2016 19:51:22 +0100 Subject: [PATCH 0441/2280] added testcase with no write and no move improves coverage --- test/test_ui.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index 07d292bbe..9b31c02b9 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -201,6 +201,13 @@ class ModifyTest(unittest.TestCase, TestHelper): item = self.lib.items().get() self.assertNotIn(b'newTitle', item.path) + def test_no_write_no_move(self): + self.modify("--nomove", "--nowrite", "title=newTitle") + item = self.lib.items().get() + item.read() + self.assertNotIn(b'newTitle', item.path) + self.assertNotEqual(item.title, 'newTitle') + def test_update_mtime(self): item = self.item old_mtime = item.mtime From 7b2de49274dfe2b287a29fa6149e727da83ba04c Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 27 Jan 2016 19:55:23 +0100 Subject: [PATCH 0442/2280] added test for abort of modify action --- test/test_ui.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index 9b31c02b9..4a10a7947 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -172,6 +172,13 @@ class ModifyTest(unittest.TestCase, TestHelper): item = self.lib.items().get() self.assertEqual(item.title, 'newTitle') + def test_modify_item_abort(self): + item = self.lib.items().get() + title = item.title + self.modify_inp('n', "title=newTitle") + item = self.lib.items().get() + self.assertEqual(item.title, title) + def test_modify_item_no_change(self): title = "Tracktitle" item = self.add_item_fixture(title=title) From 7bdc7d37d31985e916e1acdc8856ed3eca923e34 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 20:26:04 +0100 Subject: [PATCH 0443/2280] Introduced input_select_items alternative and more flexibile implementation to fulfil #1723 Added test case for new input method --- beets/ui/__init__.py | 25 ++++++++++++++++++++++ test/test_ui_init.py | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index eaf79a0ce..d17e0b32c 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -367,6 +367,31 @@ def input_yn(prompt, require=False): return sel == 'y' +def input_select_items(prompt, items, rep): + """Prompts the user to use all, none or some of the items + Will return the list of items the user selected + prompt: prompt to use for all and for selective choice + items: full list of items + rep: function which represents an item to the user + is called with the item as argument + function is responsive for newline at input + """ + out_items = [] + choice = input_options( + ('y', 'n', 's'), False, + '%s (Yes/No/Selective)?' % prompt) + print() + if choice == 'y': + out_items = items + elif choice == 's': + for item in items: + rep(item) + if input_yn('%s (y/n)?' % prompt, True): + out_items.append(item) + print() + return out_items + + # Human output formatting. def human_bytes(size): diff --git a/test/test_ui_init.py b/test/test_ui_init.py index d692868be..6ab94f9ea 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -21,6 +21,56 @@ from test._common import unittest from beets import ui +class InputMethodsTest(_common.TestCase): + def setUp(self): + super(InputMethodsTest, self).setUp() + self.io.install() + + def _print_helper(self, s): + print(s) + + def _print_helper2(self, s, prefix): + print(prefix, s) + + def test_input_select_items(self): + full_items = ['1', '2', '3', '4', '5'] + + # Test no + self.io.addinput('n') + items = ui.input_select_items( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, []) + + # Test yes + self.io.addinput('y') + items = ui.input_select_items( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, full_items) + + # Test selective 1 + self.io.addinput('s') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + items = ui.input_select_items( + "Prompt", full_items, self._print_helper) + self.assertEqual(items, ['2', '4']) + + # Test selective 2 + self.io.addinput('s') + self.io.addinput('y') + self.io.addinput('y') + self.io.addinput('n') + self.io.addinput('y') + self.io.addinput('n') + items = ui.input_select_items( + "Prompt", full_items, + lambda s: self._print_helper2(s, "Prefix")) + self.assertEqual(items, ['1', '2', '4']) + + class InitTest(_common.LibTestCase): def setUp(self): super(InitTest, self).setUp() From ff01015b613c8b58663c082aab71070eca2636c0 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Mon, 18 Jan 2016 22:41:08 -0200 Subject: [PATCH 0444/2280] Fields: Print flexible attributes --- beets/ui/commands.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0022fac74..28893cd1f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -79,6 +79,14 @@ def _do_query(lib, query, album, also_items=True): return items, albums +def _print_sqlite(query): + """Gets the result of the query, transforms the sqlite3.Row in dictionary + entries and print the values of it, with identation of 2 spaces. + """ + for row in query: + print_(' ' * 2 + dict(zip(row.keys(), row))['key']) + + # fields: Shows a list of available fields for queries and format strings. def fields_func(lib, opts, args): @@ -92,6 +100,15 @@ def fields_func(lib, opts, args): print_("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_sqlite(tx.query(unique_fields % library.Item._flex_table)) + + print_("Album flexible attributes:") + _print_sqlite(tx.query(unique_fields % library.Album._flex_table)) fields_cmd = ui.Subcommand( 'fields', From 4605016c65edfd72083790ad86efc4692c046c35 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Thu, 28 Jan 2016 18:18:08 -0200 Subject: [PATCH 0445/2280] Changelog for #1818 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 51fab3100..ecb70f8de 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,8 @@ New: session. :bug:`1779` * :doc:`/plugins/info`: A new option will print only fields' names and not their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` +* The :ref:`fields-cmd` command now displays flexible attributes. + Thanks to :user:`GuilhermeHideki`. :bug:`1818` .. _AcousticBrainz: http://acousticbrainz.org/ From 6b3975133706c06c1dd91023af7323dea508e898 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 21:49:33 +0100 Subject: [PATCH 0446/2280] introduced print_modify_item as seperate function preparation to implement interactive selection in modify command --- beets/ui/commands.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 3e3acb7c3..176cf9218 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1330,13 +1330,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): .format(len(objs), 'album' if album else 'item')) changed = set() for obj in objs: - obj.update(mods) - for field in dels: - try: - del obj[field] - except KeyError: - pass - if ui.show_model_changes(obj): + if print_modify_item(obj, mods, dels): changed.add(obj) # Still something to do? @@ -1364,6 +1358,21 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): obj.try_sync(write, move) +def print_modify_item(obj, mods, dels): + """Print the modifications to an item + and return False if no changes were made + mods: modifications + dels: fields to delete + """ + obj.update(mods) + for field in dels: + try: + del obj[field] + except KeyError: + pass + return ui.show_model_changes(obj) + + def modify_parse_args(args): """Split the arguments for the modify subcommand into query parts, assignments (field=value), and deletions (field!). Returns the result as From c28eaee7d0a5a8db89356d0e0c019d124c378be7 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 21:50:37 +0100 Subject: [PATCH 0447/2280] implemented interactive selection in modify --- beets/ui/commands.py | 5 +++-- test/test_ui.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 176cf9218..afd998042 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1349,8 +1349,9 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): else: extra = '' - if not ui.input_yn('Really modify%s (Y/n)?' % extra): - return + changed = ui.input_select_items( + 'Really modify%s (Y/n)?' % extra, changed, + lambda o: print_modify_item(o, mods, dels)) # Apply changes to database and files with lib.transaction(): diff --git a/test/test_ui.py b/test/test_ui.py index 4a10a7947..480e6ce03 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -231,6 +231,22 @@ class ModifyTest(unittest.TestCase, TestHelper): item.load() self.assertEqual(0, item.mtime) + def test_selective_modify(self): + title = "Tracktitle" + album = "album" + origArtist = "composer" + newArtist = "coverArtist" + for i in range(0, 10): + self.add_item_fixture(title="{0}{1}".format(title, i), + artist=origArtist, + album=album) + self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn', + title, "artist={0}".format(newArtist)) + origItems = self.lib.items("artist:{0}".format(origArtist)) + newItems = self.lib.items("artist:{0}".format(newArtist)) + self.assertEqual(len(list(origItems)), 3) + self.assertEqual(len(list(newItems)), 7) + # Album Tests def test_modify_album(self): From 9f2d58211009c31d78e905c160ebdd52217eb43e Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 21:55:46 +0100 Subject: [PATCH 0448/2280] Added changelog entry for c28eaee --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5a9cd366f..199c08789 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ New: :bug:`1778` * :doc:`/plugins/info`: A new option will print only fields' names and not their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` +* The :ref:`modify-cmd` command lets you interactive select tracks to apply + changes. :bug:`1843` .. _Google Code-In: https://codein.withgoogle.com/ .. _AcousticBrainz: http://acousticbrainz.org/ From 2937607d529d1227f3461b0e674b244bf9357512 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 22:09:56 +0100 Subject: [PATCH 0449/2280] Removed duplicate (Y/n) Question from output --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index afd998042..d5aeefe2f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1350,7 +1350,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): extra = '' changed = ui.input_select_items( - 'Really modify%s (Y/n)?' % extra, changed, + 'Really modify%s' % extra, changed, lambda o: print_modify_item(o, mods, dels)) # Apply changes to database and files From 4863a945a282479e5b3f92931063a940a1c71922 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 22:22:21 +0100 Subject: [PATCH 0450/2280] introduced -t option for move command --- beets/ui/commands.py | 19 ++++++++++++++++--- docs/changelog.rst | 2 ++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index d5aeefe2f..1e9daff98 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1432,7 +1432,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend): +def move_items(lib, dest, query, copy, album, pretend, confirm): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. @@ -1446,6 +1446,7 @@ def move_items(lib, dest, query, copy, album, pretend): 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' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, 's' if len(objs) != 1 else '') @@ -1460,6 +1461,12 @@ def move_items(lib, dest, query, copy, album, pretend): show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: + if confirm: + objs = ui.input_select_items( + 'Really %s' % act, objs, + lambda o: show_path_changes( + [(o.path, o.destination(basedir=dest))])) + for obj in objs: log.debug(u'moving: {0}', util.displayable_path(obj.path)) @@ -1474,7 +1481,8 @@ def move_func(lib, opts, args): if not os.path.isdir(dest): raise ui.UserError('no such directory: %s' % dest) - move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend) + move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, + opts.timid) move_cmd = ui.Subcommand( @@ -1490,7 +1498,12 @@ move_cmd.parser.add_option( ) move_cmd.parser.add_option( '-p', '--pretend', default=False, action='store_true', - help='show how files would be moved, but don\'t touch anything') + help='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' +) move_cmd.parser.add_album_option() move_cmd.func = move_func default_commands.append(move_cmd) diff --git a/docs/changelog.rst b/docs/changelog.rst index 199c08789..d8ea34540 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -29,6 +29,8 @@ New: their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` * The :ref:`modify-cmd` command lets you interactive select tracks to apply changes. :bug:`1843` +* The :ref:`move-cmd` command accepts `-t`, `--timid` switch now to confirm + or interactive select tracks process. :bug:`1843` .. _Google Code-In: https://codein.withgoogle.com/ .. _AcousticBrainz: http://acousticbrainz.org/ From fafc73077da55fb663c7a49aad19083d7493a4c7 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 28 Jan 2016 22:26:55 +0100 Subject: [PATCH 0451/2280] fixed broken tests --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 1e9daff98..244d871c7 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1432,7 +1432,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, confirm): +def move_items(lib, dest, query, copy, album, pretend, confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. From 5ff14742b82d5e83dad00704b2d830a261ed2e0a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 28 Jan 2016 13:48:20 -0800 Subject: [PATCH 0452/2280] Simpler row lookup (#1818) --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 3ca2c0c42..7dc31d8a2 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -84,7 +84,7 @@ def _print_sqlite(query): entries and print the values of it, with identation of 2 spaces. """ for row in query: - print_(' ' * 2 + dict(zip(row.keys(), row))['key']) + print_(' ' * 2 + row[b'key']) # fields: Shows a list of available fields for queries and format strings. From 7b88dc5760c0dadb42b3a8491b68e06e1f976693 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 28 Jan 2016 13:50:10 -0800 Subject: [PATCH 0453/2280] Couple printer function with fields_func (#1818) This isn't really a generic utility, since it is hard-coded to print the "key" field of the result. So let's pair it with the place it's used. --- beets/ui/commands.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 7dc31d8a2..c6846e92f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -79,16 +79,16 @@ def _do_query(lib, query, album, also_items=True): return items, albums -def _print_sqlite(query): - """Gets the result of the query, transforms the sqlite3.Row in dictionary - entries and print the values of it, with identation of 2 spaces. +# fields: Shows a list of available fields for queries and format strings. + +def _print_keys(query): + """Given a SQLite query result, print the `key` field of each + returned row, with identation of 2 spaces. """ for row in query: print_(' ' * 2 + row[b'key']) -# fields: Shows a list of available fields for queries and format strings. - def fields_func(lib, opts, args): def _print_rows(names): names.sort() @@ -105,10 +105,10 @@ def fields_func(lib, opts, args): unique_fields = 'SELECT DISTINCT key FROM (%s)' print_("Item flexible attributes:") - _print_sqlite(tx.query(unique_fields % library.Item._flex_table)) + _print_keys(tx.query(unique_fields % library.Item._flex_table)) print_("Album flexible attributes:") - _print_sqlite(tx.query(unique_fields % library.Album._flex_table)) + _print_keys(tx.query(unique_fields % library.Album._flex_table)) fields_cmd = ui.Subcommand( 'fields', From d093ef9a4703645dae8a6ec42022c0d738ec39cd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 28 Jan 2016 13:52:07 -0800 Subject: [PATCH 0454/2280] A little more documentation for `fields` (#1818) --- docs/reference/cli.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 8c04b6c90..cd7872bd4 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -344,7 +344,9 @@ fields beet fields Show the item and album metadata fields available for use in :doc:`query` and -:doc:`pathformat`. Includes any template fields provided by plugins. +:doc:`pathformat`. The listing includes any template fields provided by +plugins and any flexible attributes you've manually assigned to your items and +albums. .. _config-cmd: From 5747c6ae68e59af55fe01d7351836c2522d44e41 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 29 Jan 2016 16:19:31 +0100 Subject: [PATCH 0455/2280] changed "Selecive" to "Select items" in ui --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index d17e0b32c..1ff7da562 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -379,7 +379,7 @@ def input_select_items(prompt, items, rep): out_items = [] choice = input_options( ('y', 'n', 's'), False, - '%s (Yes/No/Selective)?' % prompt) + '%s (Yes/No/Select items)?' % prompt) print() if choice == 'y': out_items = items From 34e455b2ea454b397ab0509037a91e8b90a70706 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 29 Jan 2016 16:21:39 +0100 Subject: [PATCH 0456/2280] changed docstring for print_modify_item --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 244d871c7..69e4c2e0b 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1361,7 +1361,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): def print_modify_item(obj, mods, dels): """Print the modifications to an item - and return False if no changes were made + and return a bool indicating whether any changes were made mods: modifications dels: fields to delete """ From 98abe6952048cbb23448fedae1e8ed402020acc8 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 28 Jan 2016 14:07:10 +0100 Subject: [PATCH 0457/2280] edit: invoke editor during importer, on Items * Initial draft for invoking the edit plugin during an importer session. * Add prompt choices for editing the original file tags ("eDit") and apply a candidate and then edit ("edit Candidates"). * Modify plugin (_get_fields, apply_data, edit_objects) so "path" can be used as a reference field instead of "id", as the Items are not still on the database when the plugin is invoked via the importer. * Modify ImportTask.manipulate_files() with a temporary flag for writing the item tags even if ASIS was selected. --- beets/importer.py | 3 +- beetsplug/edit.py | 93 +++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 88 insertions(+), 8 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 868ac6922..b8bbed65f 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -672,7 +672,8 @@ class ImportTask(BaseImportTask): # old paths. item.move(copy, link) - if write and self.apply: + # TODO: the EDIT_FLAG field is a hack! + if write and (self.apply or getattr(self, 'EDIT_FLAG', False)): item.try_write() with session.lib.transaction(): diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 29676fa08..a3905e5dd 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -21,7 +21,9 @@ from beets import plugins from beets import util from beets import ui from beets.dbcore import types -from beets.ui.commands import _do_query +from beets.importer import action +from beets.ui.commands import _do_query, PromptChoice +from copy import deepcopy import subprocess import yaml from tempfile import NamedTemporaryFile @@ -151,6 +153,13 @@ class EditPlugin(plugins.BeetsPlugin): 'ignore_fields': 'id path', }) + self.register_listener('before_choose_candidate', + self.before_choose_candidate_event) + + # Field to be used as "unequivocal, non-editable key" for an Item. + # TODO: cleanup + self.mapping_field = 'id' + def commands(self): edit_command = ui.Subcommand( 'edit', @@ -202,8 +211,8 @@ class EditPlugin(plugins.BeetsPlugin): if extra: fields += extra - # Ensure we always have the `id` field for identification. - fields.append('id') + # Ensure we always have the mapping field for identification. + fields.append(self.mapping_field) return set(fields) @@ -262,10 +271,21 @@ class EditPlugin(plugins.BeetsPlugin): return False # Show the changes. + # If the objects are not on the DB yet, we need a copy of their + # original state for show_model_changes. + if all(not obj.id for obj in objs): + objs_old = deepcopy(objs) self.apply_data(objs, old_data, new_data) changed = False for obj in objs: - changed |= ui.show_model_changes(obj) + if not obj.id: + # TODO: remove uglyness + obj_old = next(x for x in objs_old if + getattr(x, self.mapping_field) == + getattr(obj, self.mapping_field)) + else: + obj_old = None + changed |= ui.show_model_changes(obj, obj_old) if not changed: ui.print_('No changes to apply.') return False @@ -295,11 +315,24 @@ class EditPlugin(plugins.BeetsPlugin): The objects are not written back to the database, so the changes are temporary. """ + # TODO: make this more pythonic + def ref_field_value(o): + if self.mapping_field == 'id': + return int(o.id) + elif self.mapping_field == 'path': + return util.displayable_path(o.path) + + def obj_from_ref(d): + if self.mapping_field == 'id': + return int(d['id']) + elif self.mapping_field == 'path': + return util.displayable_path(d['path']) + if len(old_data) != len(new_data): self._log.warn('number of objects changed from {} to {}', len(old_data), len(new_data)) - obj_by_id = {o.id: o for o in objs} + obj_by_f = {ref_field_value(o): o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() for old_dict, new_dict in zip(old_data, new_data): # Prohibit any changes to forbidden fields to avoid @@ -313,8 +346,9 @@ class EditPlugin(plugins.BeetsPlugin): if forbidden: continue - id = int(old_dict['id']) - apply(obj_by_id[id], new_dict) + # Reconcile back the user edits, using the mapping_field. + val = obj_from_ref(old_dict) + apply(obj_by_f[val], new_dict) def save_changes(self, objs): """Save a list of updated Model objects to the database. @@ -324,3 +358,48 @@ class EditPlugin(plugins.BeetsPlugin): if ob._dirty: self._log.debug('saving changes to {}', ob) ob.try_sync(ui.should_write(), ui.should_move()) + + # Methods for interactive importer execution. + + def before_choose_candidate_event(self, session, task): + """Append an "Edit" choice to the interactive importer prompt. + """ + return [PromptChoice('d', 'eDit', self.importer_edit), + PromptChoice('c', 'edit Candidates', + self.importer_edit_candidate)] + + def importer_edit(self, session, task): + """Callback for invoking the functionality during an interactive + import session on the *original* item tags. + """ + # Make 'path' the mapping field, as the Items do not have ids yet. + # TODO: move to ~import_begin + self.mapping_field = 'path' + + # Present the YAML to the user and let her change it. + fields = self._get_fields(album=None, extra=[]) + success = self.edit_objects(task.items, fields) + + # Save the new data. + if success: + # TODO: implement properly, this is a quick illustrative hack. + # If using Items, the operation is something like + # "use the *modified* Items AS-IS *and* write() them" + task.EDIT_FLAG = True + return action.ASIS + else: + # Edit cancelled / no edits made. Revert changes. + for obj in task.items: + obj.read() + + def importer_edit_candidate(self, session, task): + """Callback for invoking the functionality during an interactive + import session on a *candidate* applied to the original items. + """ + # Prompt the user for a candidate, and simulate matching. + sel = ui.input_options([], numrange=(1, len(task.candidates))) + # Force applying the candidate on the items. + task.match = task.candidates[sel-1] + task.apply_metadata() + + return self.importer_edit(session, task) From 30927a901ffeaa279512e2565683314925e62c90 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 29 Jan 2016 19:54:23 +0100 Subject: [PATCH 0458/2280] Fix flake8 error --- beetsplug/edit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index a3905e5dd..77984b77b 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -399,7 +399,7 @@ class EditPlugin(plugins.BeetsPlugin): # Prompt the user for a candidate, and simulate matching. sel = ui.input_options([], numrange=(1, len(task.candidates))) # Force applying the candidate on the items. - task.match = task.candidates[sel-1] + task.match = task.candidates[sel - 1] task.apply_metadata() return self.importer_edit(session, task) From 6eed42d2abbc458b7df4d06faf55a70e33404030 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 29 Jan 2016 20:11:26 +0100 Subject: [PATCH 0459/2280] Update documentation copyright year to 2016 --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index cd533a4d8..66223d6f7 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -11,7 +11,7 @@ source_suffix = '.rst' master_doc = 'index' project = u'beets' -copyright = u'2012, Adrian Sampson' +copyright = u'2016, Adrian Sampson' version = '1.3' release = '1.3.17' From 8412bd0f23d3f11d703a820d22e936aa035a3b35 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 30 Jan 2016 09:45:50 +0100 Subject: [PATCH 0460/2280] renamed print_modify_item to print_and_modify --- beets/ui/commands.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 69e4c2e0b..d1d641b15 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1330,7 +1330,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): .format(len(objs), 'album' if album else 'item')) changed = set() for obj in objs: - if print_modify_item(obj, mods, dels): + if print_and_modify(obj, mods, dels): changed.add(obj) # Still something to do? @@ -1351,7 +1351,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): changed = ui.input_select_items( 'Really modify%s' % extra, changed, - lambda o: print_modify_item(o, mods, dels)) + lambda o: print_and_modify(o, mods, dels)) # Apply changes to database and files with lib.transaction(): @@ -1359,7 +1359,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): obj.try_sync(write, move) -def print_modify_item(obj, mods, dels): +def print_and_modify(obj, mods, dels): """Print the modifications to an item and return a bool indicating whether any changes were made mods: modifications From 694738504a9552e7f85bc1233b3afb9eb20fff01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Guillou?= Date: Mon, 1 Feb 2016 10:19:51 +1000 Subject: [PATCH 0461/2280] typo: "how" -> "show" --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index eaf79a0ce..f718e4623 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1176,7 +1176,7 @@ def _raw_main(args, lib=None): parser.add_option('-c', '--config', dest='config', help='path to configuration file') parser.add_option('-h', '--help', dest='help', action='store_true', - help='how this help message and exit') + help='show this help message and exit') parser.add_option('--version', dest='version', action='store_true', help=optparse.SUPPRESS_HELP) From e23718dc0c826b81abef677d44a73c117914649e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 1 Feb 2016 18:51:24 +0100 Subject: [PATCH 0462/2280] Add importer RETAG action * Add importer "RETAG" action, to represent the case where the files metadata has been modified by some mean other than applying metadata (via a plugin), and as a result needs to be written to disk if the "write" config flag is set. --- beets/importer.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index b8bbed65f..fdee257e9 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -45,7 +45,7 @@ from beets import mediafile action = Enum('action', ['SKIP', 'ASIS', 'TRACKS', 'MANUAL', 'APPLY', 'MANUAL_ID', - 'ALBUMS']) + 'ALBUMS', 'RETAG']) QUEUE_SIZE = 128 SINGLE_ARTIST_THRESH = 0.25 @@ -443,7 +443,8 @@ class ImportTask(BaseImportTask): # Not part of the task structure: assert choice not in (action.MANUAL, action.MANUAL_ID) assert choice != action.APPLY # Only used internally. - if choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS): + if choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS, + action.RETAG): self.choice_flag = choice self.match = None else: @@ -482,7 +483,7 @@ class ImportTask(BaseImportTask): (in which case the data comes from the files' current metadata) or APPLY (data comes from the choice). """ - if self.choice_flag is action.ASIS: + if self.choice_flag in (action.ASIS, action.RETAG): return (self.cur_artist, self.cur_album) elif self.choice_flag is action.APPLY: return (self.match.info.artist, self.match.info.album) @@ -493,7 +494,7 @@ class ImportTask(BaseImportTask): If the tasks applies an album match the method only returns the matched items. """ - if self.choice_flag == action.ASIS: + if self.choice_flag in (action.ASIS, action.RETAG): return list(self.items) elif self.choice_flag == action.APPLY: return self.match.mapping.keys() @@ -637,7 +638,7 @@ class ImportTask(BaseImportTask): changes['albumartist'] = config['va_name'].get(unicode) changes['comp'] = True - elif self.choice_flag == action.APPLY: + elif self.choice_flag in (action.APPLY, action.RETAG): # Applying autotagged metadata. Just get AA from the first # item. if not self.items[0].albumartist: @@ -672,8 +673,7 @@ class ImportTask(BaseImportTask): # old paths. item.move(copy, link) - # TODO: the EDIT_FLAG field is a hack! - if write and (self.apply or getattr(self, 'EDIT_FLAG', False)): + if write and (self.apply or self.choice_flag == action.RETAG): item.try_write() with session.lib.transaction(): @@ -1316,7 +1316,7 @@ def resolve_duplicates(session, task): """Check if a task conflicts with items or albums already imported and ask the session to resolve this. """ - if task.choice_flag in (action.ASIS, action.APPLY): + if task.choice_flag in (action.ASIS, action.APPLY, action.RETAG): found_duplicates = task.find_duplicates(session.lib) if found_duplicates: log.debug('found duplicates: {}'.format( From b8ec22ca340b7c9205e812e2f098c15c15111dd8 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 1 Feb 2016 18:57:03 +0100 Subject: [PATCH 0463/2280] edit: use action.RETAG, cleanup * Make the edit plugin return action.RETAG when invoked during an interactive import session, making the importer handle the writing of the tags to the files (if needed) properly. * Move the logic relative to the "reference field" to _set_reference_field(), simplifying a bit the functions that depend on this field. * Hide the "edit Candidates" choice if no candidates are found. --- beetsplug/edit.py | 80 ++++++++++++++++++++++++----------------------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 77984b77b..9961b6399 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -154,11 +154,21 @@ class EditPlugin(plugins.BeetsPlugin): }) self.register_listener('before_choose_candidate', - self.before_choose_candidate_event) + self.before_choose_candidate_listener) + self.register_listener('import_begin', self.import_begin_listener) - # Field to be used as "unequivocal, non-editable key" for an Item. - # TODO: cleanup - self.mapping_field = 'id' + def _set_reference_field(self, field): + """Set the "unequivocal, non-editable field" that will be used for + reconciling back the user changes. + """ + if field == 'id': + self.reference_field = 'id' + self.ref_field_value = lambda o: int(o.id) + self.obj_from_ref = lambda d: int(d['id']) + elif field == 'path': + self.reference_field = 'path' + self.ref_field_value = lambda o: util.displayable_path(o.path) + self.obj_from_ref = lambda d: util.displayable_path(d['path']) def commands(self): edit_command = ui.Subcommand( @@ -183,6 +193,9 @@ class EditPlugin(plugins.BeetsPlugin): def _edit_command(self, lib, opts, args): """The CLI command function for the `beet edit` command. """ + # Set the reference field to "id", as all Models have valid ids. + self._set_reference_field('id') + # Get the objects to edit. query = ui.decargs(args) items, albums = _do_query(lib, query, opts.album, False) @@ -211,8 +224,8 @@ class EditPlugin(plugins.BeetsPlugin): if extra: fields += extra - # Ensure we always have the mapping field for identification. - fields.append(self.mapping_field) + # Ensure we always have the reference field for identification. + fields.append(self.reference_field) return set(fields) @@ -274,15 +287,14 @@ class EditPlugin(plugins.BeetsPlugin): # If the objects are not on the DB yet, we need a copy of their # original state for show_model_changes. if all(not obj.id for obj in objs): - objs_old = deepcopy(objs) + objs_old = {self.ref_field_value(obj): deepcopy(obj) + for obj in objs} self.apply_data(objs, old_data, new_data) changed = False for obj in objs: if not obj.id: # TODO: remove uglyness - obj_old = next(x for x in objs_old if - getattr(x, self.mapping_field) == - getattr(obj, self.mapping_field)) + obj_old = objs_old[self.ref_field_value(obj)] else: obj_old = None changed |= ui.show_model_changes(obj, obj_old) @@ -315,24 +327,11 @@ class EditPlugin(plugins.BeetsPlugin): The objects are not written back to the database, so the changes are temporary. """ - # TODO: make this more pythonic - def ref_field_value(o): - if self.mapping_field == 'id': - return int(o.id) - elif self.mapping_field == 'path': - return util.displayable_path(o.path) - - def obj_from_ref(d): - if self.mapping_field == 'id': - return int(d['id']) - elif self.mapping_field == 'path': - return util.displayable_path(d['path']) - if len(old_data) != len(new_data): self._log.warn('number of objects changed from {} to {}', len(old_data), len(new_data)) - obj_by_f = {ref_field_value(o): o for o in objs} + obj_by_f = {self.ref_field_value(o): o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() for old_dict, new_dict in zip(old_data, new_data): # Prohibit any changes to forbidden fields to avoid @@ -346,8 +345,8 @@ class EditPlugin(plugins.BeetsPlugin): if forbidden: continue - # Reconcile back the user edits, using the mapping_field. - val = obj_from_ref(old_dict) + # Reconcile back the user edits, using the reference_field. + val = self.obj_from_ref(old_dict) apply(obj_by_f[val], new_dict) def save_changes(self, objs): @@ -361,32 +360,35 @@ class EditPlugin(plugins.BeetsPlugin): # Methods for interactive importer execution. - def before_choose_candidate_event(self, session, task): + def before_choose_candidate_listener(self, session, task): """Append an "Edit" choice to the interactive importer prompt. """ - return [PromptChoice('d', 'eDit', self.importer_edit), - PromptChoice('c', 'edit Candidates', - self.importer_edit_candidate)] + choices = [PromptChoice('d', 'eDit', self.importer_edit)] + if task.candidates: + choices.append(PromptChoice('c', 'edit Candidates', + self.importer_edit_candidate)) + + return choices + + def import_begin_listener(self, session): + """Initialize the reference field to 'path', as during an interactive + import session Models do not have valid 'id's yet. + """ + self._set_reference_field('path') def importer_edit(self, session, task): """Callback for invoking the functionality during an interactive import session on the *original* item tags. """ - # Make 'path' the mapping field, as the Items do not have ids yet. - # TODO: move to ~import_begin - self.mapping_field = 'path' - # Present the YAML to the user and let her change it. fields = self._get_fields(album=None, extra=[]) success = self.edit_objects(task.items, fields) # Save the new data. if success: - # TODO: implement properly, this is a quick illustrative hack. - # If using Items, the operation is something like - # "use the *modified* Items AS-IS *and* write() them" - task.EDIT_FLAG = True - return action.ASIS + # Return action.RETAG, which makes the importer write the tags + # to the files if needed. + return action.RETAG else: # Edit cancelled / no edits made. Revert changes. for obj in task.items: From 0aea7e398b87b3c63ae9bb46d0600ee096e97d0a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 2 Feb 2016 08:08:58 -0800 Subject: [PATCH 0464/2280] replaygain: Handle missing GStreamer data (#1855) --- beetsplug/replaygain.py | 21 ++++++++++++++++----- docs/changelog.rst | 2 ++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index acf996bd2..babb469ad 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -501,14 +501,25 @@ class GStreamerBackend(Backend): if len(self._file_tags) != len(items): raise ReplayGainError("Some items in album did not receive tags") - ret = [] + # Collect track gains. + track_gains = [] for item in items: - ret.append(Gain(self._file_tags[item]["TRACK_GAIN"], - self._file_tags[item]["TRACK_PEAK"])) + try: + gain = self._file_tags[item]["TRACK_GAIN"] + peak = self._file_tags[item]["TRACK_PEAK"] + except KeyError: + raise ReplayGainError("results missing for track") + track_gains.append(Gain(gain, peak)) + # Get album gain information from the last track. last_tags = self._file_tags[items[-1]] - return AlbumGain(Gain(last_tags["ALBUM_GAIN"], - last_tags["ALBUM_PEAK"]), ret) + try: + gain = last_tags["ALBUM_GAIN"] + peak = last_tags["ALBUM_PEAK"] + except KeyError: + raise ReplayGainError("results missing for album") + + return AlbumGain(Gain(gain, peak), track_gains) def close(self): self._bus.remove_signal_watch() diff --git a/docs/changelog.rst b/docs/changelog.rst index 7dac1a1a9..45cd01ecb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -53,6 +53,8 @@ Fixes: inaccessible. :bug:`1806` * :doc:`/plugins/fetchart`: Possibly fix a Unicode-related crash when using some versions of pyOpenSSL. :bug:`1805` +* :doc:`/plugins/replaygain`: Fix an intermittent crash with the GStreamer + backend. :bug:`1855` .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox From 60888274c4dc1d4bd453fe7bf8092ab2b792f2ce Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 2 Feb 2016 08:14:22 -0800 Subject: [PATCH 0465/2280] lyrics: Re-disable Genius backend As #1854 pointed out, the Genius API service is down *again*. --- beetsplug/lyrics.py | 2 +- docs/changelog.rst | 3 +++ docs/plugins/lyrics.rst | 7 +++---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 5b30184a0..9e5e2fad6 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -537,7 +537,7 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch', 'genius'] + SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, diff --git a/docs/changelog.rst b/docs/changelog.rst index 45cd01ecb..b5a120418 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -55,6 +55,9 @@ Fixes: some versions of pyOpenSSL. :bug:`1805` * :doc:`/plugins/replaygain`: Fix an intermittent crash with the GStreamer backend. :bug:`1855` +* :doc:`/plugins/lyrics`: In a continuing saga, the Genius API we use is down + again, so it's been disabled by default *again*. We'll probably leave it + disabled this time. .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 4f1569c38..0d504733f 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -52,10 +52,9 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch genius``, i.e., all - sources. - The `google` source will be automatically deactivated if no - ``google_API_key`` is setup. + Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all the + sources except for `genius`. The `google` source will be automatically + deactivated if no ``google_API_key`` is setup. Here's an example of ``config.yaml``:: From 09a21eac56b07bf85d638ed9799c7e0475a56a90 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 2 Feb 2016 08:15:51 -0800 Subject: [PATCH 0466/2280] Stray trailing whitespace --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b5a120418..d862a6641 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,7 +27,7 @@ New: :bug:`1778` * :doc:`/plugins/info`: A new option will print only fields' names and not their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` -* The :ref:`fields-cmd` command now displays flexible attributes. +* The :ref:`fields-cmd` command now displays flexible attributes. Thanks to :user:`GuilhermeHideki`. :bug:`1818` .. _Google Code-In: https://codein.withgoogle.com/ From 0e649e549a6292c8c0262e78806543ff137d82ee Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 3 Feb 2016 17:13:33 +0100 Subject: [PATCH 0467/2280] edit: add RETAG support for singleton, fix logic * Add support for the RETAG action to SingletonImportTask. * Modify ImportTask.align_album_level_fields() so the source of the information is a bit more intelligent in the RETAG case instead of always assuming the items come from applied metadata. --- beets/importer.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index fdee257e9..97cabb92b 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -621,8 +621,12 @@ class ImportTask(BaseImportTask): """Make some album fields equal across `self.items`. """ changes = {} + # Determine where to gather the info from for the RETAG action. + retag_asis = (self.choice_flag == action.RETAG and + not self.items[0].artist and + not self.items[0].mb_artistid) - if self.choice_flag == action.ASIS: + if self.choice_flag == action.ASIS or retag_asis: # Taking metadata "as-is". Guess whether this album is VA. plur_albumartist, freq = util.plurality( [i.albumartist or i.artist for i in self.items] @@ -808,8 +812,8 @@ class SingletonImportTask(ImportTask): self.paths = [item.path] def chosen_ident(self): - assert self.choice_flag in (action.ASIS, action.APPLY) - if self.choice_flag is action.ASIS: + assert self.choice_flag in (action.ASIS, action.APPLY, action.RETAG) + if self.choice_flag in (action.ASIS, action.RETAG): return (self.item.artist, self.item.title) elif self.choice_flag is action.APPLY: return (self.match.info.artist, self.match.info.title) From 32f9bd507752d49bb7db89125a95ea2b8313dd1c Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 3 Feb 2016 17:17:48 +0100 Subject: [PATCH 0468/2280] edit: add tests for interactive importer execution * Add EditDuringImporterTest test case, covering the running of the plugin during an import session. Includes editing the "album" field and applying/discarding for both editing from items and editing from a candidate; and editing and applying for singletons for both editing from items and editing from a candidate. --- test/test_edit.py | 280 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 220 insertions(+), 60 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 25b24cea0..8a95c00b4 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -20,11 +20,15 @@ from mock import patch from test import _common from test._common import unittest from test.helper import TestHelper, control_stdin +from test.test_ui_importer import TerminalImportSessionSetup +from test.test_importer import ImportHelper, AutotagStub +from beets.library import Item class ModifyFileMocker(object): """Helper for modifying a file, replacing or editing its contents. Used for - mocking the calls to the external editor during testing.""" + mocking the calls to the external editor during testing. + """ def __init__(self, contents=None, replacements=None): """ `self.contents` and `self.replacements` are initalized here, in @@ -63,52 +67,8 @@ class ModifyFileMocker(object): f.write(contents) -@_common.slow_test() -class EditCommandTest(unittest.TestCase, TestHelper): - """ Black box tests for `beetsplug.edit`. Command line interaction is - simulated using `test.helper.control_stdin()`, and yaml editing via an - external editor is simulated using `ModifyFileMocker`. - """ - ALBUM_COUNT = 1 - TRACK_COUNT = 10 - - def setUp(self): - self.setup_beets() - self.load_plugins('edit') - # make sure that we avoid invoking the editor except for making changes - self.config['edit']['diff_method'] = '' - # add an album, storing the original fields for comparison - self.album = self.add_album_fixture(track_count=self.TRACK_COUNT) - self.album_orig = {f: self.album[f] for f in self.album._fields} - self.items_orig = [{f: item[f] for f in item._fields} for - item in self.album.items()] - - # keep track of write()s - self.write_patcher = patch('beets.library.Item.write') - self.mock_write = self.write_patcher.start() - - def tearDown(self): - self.write_patcher.stop() - self.teardown_beets() - self.unload_plugins() - - def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]): - """Run the edit command, with mocked stdin and yaml writing, and - passing `args` to `run_command`.""" - m = ModifyFileMocker(**modify_file_args) - with patch('beetsplug.edit.edit', side_effect=m.action): - with control_stdin('\n'.join(stdin)): - self.run_command('edit', *args) - - def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, - write_call_count=TRACK_COUNT, title_starts_with=''): - """Several common assertions on Album, Track and call counts.""" - self.assertEqual(len(self.lib.albums()), album_count) - self.assertEqual(len(self.lib.items()), track_count) - self.assertEqual(self.mock_write.call_count, write_call_count) - self.assertTrue(all(i.title.startswith(title_starts_with) - for i in self.lib.items())) - +class EditMixin(object): + """Helper containing some common functionality used for the Edit tests.""" def assertItemFieldsModified(self, library_items, items, fields=[], allowed=['path']): """Assert that items in the library (`lib_items`) have different values @@ -125,9 +85,63 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertEqual(set(diff_fields).difference(allowed), set(fields)) + def run_mocked_interpreter(self, modify_file_args={}, stdin=[]): + """Run the edit command during an import session, with mocked stdin and + yaml writing. + """ + m = ModifyFileMocker(**modify_file_args) + with patch('beetsplug.edit.edit', side_effect=m.action): + with control_stdin('\n'.join(stdin)): + self.importer.run() + + def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]): + """Run the edit command, with mocked stdin and yaml writing, and + passing `args` to `run_command`.""" + m = ModifyFileMocker(**modify_file_args) + with patch('beetsplug.edit.edit', side_effect=m.action): + with control_stdin('\n'.join(stdin)): + self.run_command('edit', *args) + + +@_common.slow_test() +class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): + """Black box tests for `beetsplug.edit`. Command line interaction is + simulated using `test.helper.control_stdin()`, and yaml editing via an + external editor is simulated using `ModifyFileMocker`. + """ + ALBUM_COUNT = 1 + TRACK_COUNT = 10 + + def setUp(self): + self.setup_beets() + self.load_plugins('edit') + # Add an album, storing the original fields for comparison. + self.album = self.add_album_fixture(track_count=self.TRACK_COUNT) + self.album_orig = {f: self.album[f] for f in self.album._fields} + self.items_orig = [{f: item[f] for f in item._fields} for + item in self.album.items()] + + # Keep track of write()s. + self.write_patcher = patch('beets.library.Item.write') + self.mock_write = self.write_patcher.start() + + def tearDown(self): + self.write_patcher.stop() + self.teardown_beets() + self.unload_plugins() + + def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, + write_call_count=TRACK_COUNT, title_starts_with=''): + """Several common assertions on Album, Track and call counts.""" + self.assertEqual(len(self.lib.albums()), album_count) + self.assertEqual(len(self.lib.items()), track_count) + self.assertEqual(self.mock_write.call_count, write_call_count) + self.assertTrue(all(i.title.startswith(title_starts_with) + for i in self.lib.items())) + def test_title_edit_discard(self): - """Edit title for all items in the library, then discard changes-""" - # edit titles + """Edit title for all items in the library, then discard changes.""" + # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, # Cancel. @@ -139,7 +153,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): def test_title_edit_apply(self): """Edit title for all items in the library, then apply changes.""" - # edit titles + # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': u'modified t\u00eftle'}}, # Apply changes. @@ -152,14 +166,14 @@ class EditCommandTest(unittest.TestCase, TestHelper): def test_single_title_edit_apply(self): """Edit title for one item in the library, then apply changes.""" - # edit title + # Edit one track title. self.run_mocked_command({'replacements': {u't\u00eftle 9': u'modified t\u00eftle 9'}}, # Apply changes. ['a']) self.assertCounts(write_call_count=1,) - # no changes except on last item + # No changes except on last item. self.assertItemFieldsModified(list(self.album.items())[:-1], self.items_orig[:-1], []) self.assertEqual(list(self.album.items())[-1].title, @@ -167,9 +181,9 @@ class EditCommandTest(unittest.TestCase, TestHelper): def test_noedit(self): """Do not edit anything.""" - # do not edit anything + # Do not edit anything. self.run_mocked_command({'contents': None}, - # no stdin + # No stdin. []) self.assertCounts(write_call_count=0, @@ -180,7 +194,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Edit the album field for all items in the library, apply changes. By design, the album should not be updated."" """ - # edit album + # Edit album. self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, # Apply changes. @@ -189,14 +203,14 @@ class EditCommandTest(unittest.TestCase, TestHelper): self.assertCounts(write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) - # ensure album is *not* modified + # Ensure album is *not* modified. self.album.load() self.assertEqual(self.album.album, u'\u00e4lbum') def test_single_edit_add_field(self): """Edit the yaml file appending an extra field to the first item, then apply changes.""" - # append "foo: bar" to item with id == 1 + # Append "foo: bar" to item with id == 1. self.run_mocked_command({'replacements': {u"id: 1": u"id: 1\nfoo: bar"}}, # Apply changes. @@ -237,7 +251,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): def test_malformed_yaml(self): """Edit the yaml file incorrectly (resulting in a malformed yaml document).""" - # edit the yaml file to an invalid file + # Edit the yaml file to an invalid file. self.run_mocked_command({'contents': '!MALFORMED'}, # Edit again to fix? No. ['n']) @@ -248,15 +262,161 @@ class EditCommandTest(unittest.TestCase, TestHelper): def test_invalid_yaml(self): """Edit the yaml file incorrectly (resulting in a well-formed but invalid yaml document).""" - # edit the yaml file to an invalid file + # Edit the yaml file to an invalid but parseable file. self.run_mocked_command({'contents': 'wellformed: yes, but invalid'}, - # no stdin + # No stdin. []) self.assertCounts(write_call_count=0, title_starts_with=u't\u00eftle') +@_common.slow_test() +class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, + ImportHelper, TestHelper, EditMixin): + """TODO + """ + IGNORED = ['added', 'album_id', 'id', 'mtime', 'path'] + + def setUp(self): + self.setup_beets() + self.load_plugins('edit') + # Create some mediafiles, and store them for comparison. + self._create_import_dir(3) + self.items_orig = [Item.from_path(f.path) for f in self.media_files] + self.matcher = AutotagStub().install() + self.matcher.matching = AutotagStub.GOOD + self.config['import']['timid'] = True + + def tearDown(self): + self.unload_plugins() + self.teardown_beets() + self.matcher.restore() + + def test_edit_apply_asis(self): + """Edit the album field for all items in the library, apply changes, + using the original item tags. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Apply changes. + ['d', 'a']) + + # Check that only the 'title' field is modified. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + ['title'], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Edited Title' in i.title + for i in self.lib.items())) + + # Ensure album is *not* fetched from a candidate. + self.assertEqual(self.lib.albums()[0].mb_albumid, u'') + + def test_edit_discard_asis(self): + """Edit the album field for all items in the library, discard changes, + using the original item tags. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Cancel, Use as-is. + ['d', 'c', 'u']) + + # Check that nothing is modified, the album is imported ASIS. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + [], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Tag Title' in i.title + for i in self.lib.items())) + + # Ensure album is *not* fetched from a candidate. + self.assertEqual(self.lib.albums()[0].mb_albumid, u'') + + def test_edit_apply_candidate(self): + """Edit the album field for all items in the library, apply changes, + using a candidate. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes. + ['c', '1', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + + def test_edit_discard_candidate(self): + """Edit the album field for all items in the library, discard changes, + using a candidate. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes. + ['c', '1', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + + def test_edit_apply_asis_singleton(self): + """Edit the album field for all items in the library, apply changes, + using the original item tags and singleton mode. + """ + self._setup_import_session(singletons=True) + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Tag Title': + u'Edited Title'}}, + # eDit, Apply changes, aBort. + ['d', 'a', 'b']) + + # Check that only the 'title' field is modified. + self.assertItemFieldsModified(self.lib.items(), self.items_orig, + ['title'], + self.IGNORED + ['albumartist', + 'mb_albumartistid']) + self.assertTrue(all('Edited Title' in i.title + for i in self.lib.items())) + + def test_edit_apply_candidate_singleton(self): + """Edit the album field for all items in the library, apply changes, + using a candidate and singleton mode. + """ + self._setup_import_session() + # Edit track titles. + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # edit Candidates, 1, Apply changes, aBort. + ['c', '1', 'a', 'b']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 0ba8f83929863daf03cc9aa1659c247e94f7482e Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 3 Feb 2016 17:22:03 +0100 Subject: [PATCH 0469/2280] edit: allow edit album+item fields in single yaml * Add support for editing both the item fields and the album fields in a single YAML file, by appending an Album-like object as the front of the objects to be edited. * The FakeAlbum class provides that object, mimicking the original Album behaviour and including an _apply_changes() method that propagates the changes read from the yaml onto the Items. * Modify edit_objects() so the flattening of the objects takes into account the type of object, using different fields for Albums and for Items. * Renamed apply() to apply_() to prevent an IDE warning about reusing a reserved built-in symbol. --- beetsplug/edit.py | 67 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 9 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 9961b6399..cc7c99632 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -21,7 +21,8 @@ from beets import plugins from beets import util from beets import ui from beets.dbcore import types -from beets.importer import action +from beets.importer import action, SingletonImportTask +from beets.library import Item, Album from beets.ui.commands import _do_query, PromptChoice from copy import deepcopy import subprocess @@ -121,7 +122,7 @@ def flatten(obj, fields): return d -def apply(obj, data): +def apply_(obj, data): """Set the fields of a `dbcore.Model` object according to a dictionary. @@ -238,20 +239,26 @@ class EditPlugin(plugins.BeetsPlugin): everything). """ # Present the YAML to the user and let her change it. - success = self.edit_objects(objs, fields) + if album: + success = self.edit_objects(objs, None, fields) + else: + success = self.edit_objects(objs, fields, None) # Save the new data. if success: self.save_changes(objs) - def edit_objects(self, objs, fields): + def edit_objects(self, objs, item_fields, album_fields): """Dump a set of Model objects to a file as text, ask the user to edit it, and apply any changes to the objects. Return a boolean indicating whether the edit succeeded. """ # Get the content to edit as raw data structures. - old_data = [flatten(o, fields) for o in objs] + old_data = [flatten(o, + item_fields if isinstance(o, Item) + else album_fields) + for o in objs] # Set up a temporary file with the initial data for editing. new = NamedTemporaryFile(suffix='.yaml', delete=False) @@ -331,7 +338,7 @@ class EditPlugin(plugins.BeetsPlugin): self._log.warn('number of objects changed from {} to {}', len(old_data), len(new_data)) - obj_by_f = {self.ref_field_value(o): o for o in objs} + obj_by_ref = {self.ref_field_value(o): o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() for old_dict, new_dict in zip(old_data, new_data): # Prohibit any changes to forbidden fields to avoid @@ -347,7 +354,7 @@ class EditPlugin(plugins.BeetsPlugin): # Reconcile back the user edits, using the reference_field. val = self.obj_from_ref(old_dict) - apply(obj_by_f[val], new_dict) + apply_(obj_by_ref[val], new_dict) def save_changes(self, objs): """Save a list of updated Model objects to the database. @@ -380,12 +387,25 @@ class EditPlugin(plugins.BeetsPlugin): """Callback for invoking the functionality during an interactive import session on the *original* item tags. """ + singleton = isinstance(object, SingletonImportTask) + item_fields = self._get_fields(False, []) + items = list(task.items) # Shallow copy, not modifying task.items. + if not singleton: + # Prepend a FakeAlbum for allowing the user to edit album fields. + album = FakeAlbum(task.items, task.toppath) + items.insert(0, album) + album_fields = self._get_fields(True, []) + else: + album_fields = None + # Present the YAML to the user and let her change it. - fields = self._get_fields(album=None, extra=[]) - success = self.edit_objects(task.items, fields) + success = self.edit_objects(items, item_fields, album_fields) # Save the new data. if success: + if not singleton: + # Propagate the album changes to the items. + album._apply_changes() # Return action.RETAG, which makes the importer write the tags # to the files if needed. return action.RETAG @@ -405,3 +425,32 @@ class EditPlugin(plugins.BeetsPlugin): task.apply_metadata() return self.importer_edit(session, task) + + +class FakeAlbum(Album): + """Helper for presenting the user with an Album to be edited when there + is no real Album present. The album fields are set from the first item, + and after editing propagated to the items on `_apply_changes`. + """ + def __init__(self, items, path): + self._src_items = items + + # Create the album structure using metadata from the first item. + values = dict((key, items[0][key]) for key in Album.item_keys) + # Manually set the path as a single value field. + values[u'path'] = util.displayable_path(path) + super(FakeAlbum, self).__init__(**values) + + def _getters(self): + """Remove 'path' from Album._getters(), treating it as a regular field + in order to be able to use it directly.""" + getters = Album._getters() + getters.pop('path') + return getters + + def _apply_changes(self): + """Propagate changes to the album fields onto the Items. + """ + values = dict((key, self[key]) for key in Album.item_keys) + for i in self._src_items: + i.update(values) From f550dfecf1283e1099795572db788adf5fd224b6 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 3 Feb 2016 18:43:26 +0100 Subject: [PATCH 0470/2280] changed prompt for input_select_items moved question mark and removed word "item" --- beets/ui/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 1ff7da562..5e3835825 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -379,14 +379,14 @@ def input_select_items(prompt, items, rep): out_items = [] choice = input_options( ('y', 'n', 's'), False, - '%s (Yes/No/Select items)?' % prompt) + '%s? (Yes/no/select)' % prompt) print() if choice == 'y': out_items = items elif choice == 's': for item in items: rep(item) - if input_yn('%s (y/n)?' % prompt, True): + if input_yn('%s? (yes/no)' % prompt, True): out_items.append(item) print() return out_items From 7b6c2c36d366af0792d6154e46c6e6369b760498 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Wed, 3 Feb 2016 18:58:29 +0100 Subject: [PATCH 0471/2280] edit: fix Plugin not unloaded during tests --- test/test_edit.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_edit.py b/test/test_edit.py index 8a95c00b4..c35c71c08 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -23,6 +23,7 @@ from test.helper import TestHelper, control_stdin from test.test_ui_importer import TerminalImportSessionSetup from test.test_importer import ImportHelper, AutotagStub from beets.library import Item +from beetsplug.edit import EditPlugin class ModifyFileMocker(object): @@ -126,6 +127,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.mock_write = self.write_patcher.start() def tearDown(self): + EditPlugin.listeners = None self.write_patcher.stop() self.teardown_beets() self.unload_plugins() @@ -289,6 +291,7 @@ class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, self.config['import']['timid'] = True def tearDown(self): + EditPlugin.listeners = None self.unload_plugins() self.teardown_beets() self.matcher.restore() From 89d38caea6368fcc802e18e719358134b131458a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 3 Feb 2016 19:14:12 +0100 Subject: [PATCH 0472/2280] added comment --- beets/ui/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 5e3835825..0d018d1e7 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -380,7 +380,7 @@ def input_select_items(prompt, items, rep): choice = input_options( ('y', 'n', 's'), False, '%s? (Yes/no/select)' % prompt) - print() + print() # go to a new line if choice == 'y': out_items = items elif choice == 's': @@ -388,7 +388,7 @@ def input_select_items(prompt, items, rep): rep(item) if input_yn('%s? (yes/no)' % prompt, True): out_items.append(item) - print() + print() # go to a new line return out_items From a942719ffcf2d85aca2f25cbefbb55869d2b1503 Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Wed, 3 Feb 2016 20:38:29 +0100 Subject: [PATCH 0473/2280] Fix grammar --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 84e4368d6..2a93d2204 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -715,7 +715,7 @@ defaults look like this:: singleton: Non-Album/$artist/$title comp: Compilations/$album%aunique{}/$track $title -Note the use of ``$albumartist`` instead of ``$artist``; this ensure that albums +Note the use of ``$albumartist`` instead of ``$artist``; this ensures that albums will be well-organized. For more about these format strings, see :doc:`pathformat`. The ``aunique{}`` function ensures that identically-named albums are placed in different directories; see :ref:`aunique` for details. From 38a86054a5485fd42734fb24555c27e2db21d4bd Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Wed, 3 Feb 2016 22:30:25 +0100 Subject: [PATCH 0474/2280] Fix typo --- docs/plugins/acousticbrainz.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 4e1bf7b27..9be9bede7 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -1,7 +1,7 @@ AcousticBrainz Plugin ===================== -The ``acoustricbrainz`` plugin gets acoustic-analysis information from the +The ``acousticbrainz`` plugin gets acoustic-analysis information from the `AcousticBrainz`_ project. The spirit is similar to the :doc:`/plugins/echonest`. From 45cc4300b798904abc7f617a8f3be2cca65b74ea Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Thu, 4 Feb 2016 03:39:51 +0100 Subject: [PATCH 0475/2280] Link to nested genre names The internal whitelist is already linked, this one should be, too! --- docs/plugins/lastgenre.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index bd3aebc83..69db32877 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -44,10 +44,11 @@ Canonicalization The plugin can also *canonicalize* genres, meaning that more obscure genres can be turned into coarser-grained ones that are present in the whitelist. This -works using a tree of nested genre names, represented using `YAML`_, where the +works using a `tree of nested genre names`_, represented using `YAML`_, where the leaves of the tree represent the most specific genres. .. _YAML: http://www.yaml.org/ +.. _tree of nested genre names: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres-tree.yaml Genre Source From fac814421a4df08cd8a5ad3575c46e2445ceffb2 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 4 Feb 2016 17:59:59 +0100 Subject: [PATCH 0476/2280] Added documentation for changes by #1843 --- docs/guides/advanced.rst | 5 ++++- docs/reference/cli.rst | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/guides/advanced.rst b/docs/guides/advanced.rst index 119139c50..d68696906 100644 --- a/docs/guides/advanced.rst +++ b/docs/guides/advanced.rst @@ -117,7 +117,10 @@ using the :ref:`modify-cmd` command:: beet modify context=party artist:'beastie boys' -And then :doc:`query ` your music just as you would with any +By default beets will show you the changes that are about to be applied and ask +if you really want to apply them to all, some or none of the items or albums. + +Then :doc:`query ` your music just as you would with any other field:: beet ls context:mope diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index cd7872bd4..000fda231 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -250,7 +250,7 @@ move ```` :: - beet move [-cap] [-d DIR] QUERY + beet move [-capt] [-d DIR] QUERY Move or copy items in your library. @@ -262,7 +262,8 @@ them. As with other commands, the ``-a`` option matches albums instead of items. To perform a "dry run", just use the ``-p`` (for "pretend") flag. This will show you a list of files that would be moved but won't actually change anything -on disk. +on disk. In advance the ``-t`` option sets the timid mode which will ask again +before really moving or copying the files. .. _update-cmd: From f6b81c1bdd59adb4c57e1bf7a5ad1afb7012157a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 4 Feb 2016 18:35:01 +0100 Subject: [PATCH 0477/2280] Made changes suggested by @sampsyo --- docs/guides/advanced.rst | 2 ++ docs/reference/cli.rst | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/guides/advanced.rst b/docs/guides/advanced.rst index d68696906..55bda7aac 100644 --- a/docs/guides/advanced.rst +++ b/docs/guides/advanced.rst @@ -119,6 +119,8 @@ using the :ref:`modify-cmd` command:: By default beets will show you the changes that are about to be applied and ask if you really want to apply them to all, some or none of the items or albums. +You can type y for "yes", n for "no", or s for "select". If you choose the latter, +the command will prompt you for each individual matching item or album. Then :doc:`query ` your music just as you would with any other field:: diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 000fda231..fcef6d23f 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -262,7 +262,7 @@ them. As with other commands, the ``-a`` option matches albums instead of items. To perform a "dry run", just use the ``-p`` (for "pretend") flag. This will show you a list of files that would be moved but won't actually change anything -on disk. In advance the ``-t`` option sets the timid mode which will ask again +on disk. The ``-t`` option sets the timid mode which will ask again before really moving or copying the files. .. _update-cmd: From 25045245d69b203d9cd611ce1de5ae0ca926d837 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 Feb 2016 11:29:11 -0800 Subject: [PATCH 0478/2280] Use two items when testing path queries --- test/test_query.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/test/test_query.py b/test/test_query.py index deb9f090f..20267bf16 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -371,12 +371,25 @@ class MatchTest(_common.TestCase): class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): def setUp(self): super(PathQueryTest, self).setUp() + + # This is the item we'll try to match. self.i.path = '/a/b/c.mp3' self.i.title = 'path item' self.i.album = 'path album' self.i.store() self.lib.add_album([self.i]) + # A second item for testing exclusion. + i2 = _common.item() + i2.path = '/x/y/z.mp3' + i2.title = 'another item' + i2.album = 'another album' + self.lib.add(i2) + self.lib.add_album([i2]) + + # Unadorned path queries with path separators in them are considered + # path queries only when the path in question actually exists. So we + # mock the existence check to return true. self.patcher_exists = patch('beets.library.os.path.exists') self.patcher_exists.start().return_value = True @@ -462,7 +475,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_items_matched(results, []) def test_path_item_regex(self): - q = 'path::\\.mp3$' + q = 'path::c\\.mp3$' results = self.lib.items(q) self.assert_items_matched(results, ['path item']) From 19a5d8c45fcec0a08859c8af45f40248a174de26 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 Feb 2016 11:35:23 -0800 Subject: [PATCH 0479/2280] Add failing test for #1865 --- test/test_query.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/test_query.py b/test/test_query.py index 20267bf16..bb9572a1b 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -461,6 +461,12 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): results = self.lib.albums(q) self.assert_albums_matched(results, ['path album']) + @unittest.skip('unfixed (#1865)') + def test_path_query_in_or_query(self): + q = '/a/b , /a/b' + results = self.lib.items(q) + self.assert_items_matched(results, ['path item']) + def test_non_slashed_does_not_match_path(self): q = 'c.mp3' results = self.lib.items(q) From 8d3f9a573cbcfd9041df7735ba37bb08df464862 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 5 Feb 2016 12:35:11 +0100 Subject: [PATCH 0480/2280] edit: revert album-field changes, use temporary id * Revert the changes related to allowing the album- and item-level fields to be edited at the same time, as the increase in complexity was deemed excesive during review. * Modify the interactive execution so temporary Item.id's are used, removing the extra functionality needed for dealing with both id and path as reference fields. * Docstrings and comments cleanup. --- beetsplug/edit.py | 123 ++++++++++------------------------------------ 1 file changed, 27 insertions(+), 96 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index cc7c99632..ee045664e 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -21,8 +21,7 @@ from beets import plugins from beets import util from beets import ui from beets.dbcore import types -from beets.importer import action, SingletonImportTask -from beets.library import Item, Album +from beets.importer import action from beets.ui.commands import _do_query, PromptChoice from copy import deepcopy import subprocess @@ -156,20 +155,6 @@ class EditPlugin(plugins.BeetsPlugin): self.register_listener('before_choose_candidate', self.before_choose_candidate_listener) - self.register_listener('import_begin', self.import_begin_listener) - - def _set_reference_field(self, field): - """Set the "unequivocal, non-editable field" that will be used for - reconciling back the user changes. - """ - if field == 'id': - self.reference_field = 'id' - self.ref_field_value = lambda o: int(o.id) - self.obj_from_ref = lambda d: int(d['id']) - elif field == 'path': - self.reference_field = 'path' - self.ref_field_value = lambda o: util.displayable_path(o.path) - self.obj_from_ref = lambda d: util.displayable_path(d['path']) def commands(self): edit_command = ui.Subcommand( @@ -194,9 +179,6 @@ class EditPlugin(plugins.BeetsPlugin): def _edit_command(self, lib, opts, args): """The CLI command function for the `beet edit` command. """ - # Set the reference field to "id", as all Models have valid ids. - self._set_reference_field('id') - # Get the objects to edit. query = ui.decargs(args) items, albums = _do_query(lib, query, opts.album, False) @@ -225,8 +207,8 @@ class EditPlugin(plugins.BeetsPlugin): if extra: fields += extra - # Ensure we always have the reference field for identification. - fields.append(self.reference_field) + # Ensure we always have the `id` field for identification. + fields.append('id') return set(fields) @@ -239,26 +221,20 @@ class EditPlugin(plugins.BeetsPlugin): everything). """ # Present the YAML to the user and let her change it. - if album: - success = self.edit_objects(objs, None, fields) - else: - success = self.edit_objects(objs, fields, None) + success = self.edit_objects(objs, fields) # Save the new data. if success: self.save_changes(objs) - def edit_objects(self, objs, item_fields, album_fields): + def edit_objects(self, objs, fields): """Dump a set of Model objects to a file as text, ask the user to edit it, and apply any changes to the objects. Return a boolean indicating whether the edit succeeded. """ # Get the content to edit as raw data structures. - old_data = [flatten(o, - item_fields if isinstance(o, Item) - else album_fields) - for o in objs] + old_data = [flatten(o, fields) for o in objs] # Set up a temporary file with the initial data for editing. new = NamedTemporaryFile(suffix='.yaml', delete=False) @@ -293,17 +269,11 @@ class EditPlugin(plugins.BeetsPlugin): # Show the changes. # If the objects are not on the DB yet, we need a copy of their # original state for show_model_changes. - if all(not obj.id for obj in objs): - objs_old = {self.ref_field_value(obj): deepcopy(obj) - for obj in objs} + objs_old = [deepcopy(obj) if not obj._db else None + for obj in objs] self.apply_data(objs, old_data, new_data) changed = False - for obj in objs: - if not obj.id: - # TODO: remove uglyness - obj_old = objs_old[self.ref_field_value(obj)] - else: - obj_old = None + for obj, obj_old in zip(objs, objs_old): changed |= ui.show_model_changes(obj, obj_old) if not changed: ui.print_('No changes to apply.') @@ -338,7 +308,7 @@ class EditPlugin(plugins.BeetsPlugin): self._log.warn('number of objects changed from {} to {}', len(old_data), len(new_data)) - obj_by_ref = {self.ref_field_value(o): o for o in objs} + obj_by_id = {o.id: o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() for old_dict, new_dict in zip(old_data, new_data): # Prohibit any changes to forbidden fields to avoid @@ -352,9 +322,8 @@ class EditPlugin(plugins.BeetsPlugin): if forbidden: continue - # Reconcile back the user edits, using the reference_field. - val = self.obj_from_ref(old_dict) - apply_(obj_by_ref[val], new_dict) + id_ = int(old_dict['id']) + apply_(obj_by_id[id_], new_dict) def save_changes(self, objs): """Save a list of updated Model objects to the database. @@ -368,7 +337,8 @@ class EditPlugin(plugins.BeetsPlugin): # Methods for interactive importer execution. def before_choose_candidate_listener(self, session, task): - """Append an "Edit" choice to the interactive importer prompt. + """Append an "Edit" choice and an "edit Candidates" choice (if + there are candidates) to the interactive importer prompt. """ choices = [PromptChoice('d', 'eDit', self.importer_edit)] if task.candidates: @@ -377,37 +347,26 @@ class EditPlugin(plugins.BeetsPlugin): return choices - def import_begin_listener(self, session): - """Initialize the reference field to 'path', as during an interactive - import session Models do not have valid 'id's yet. - """ - self._set_reference_field('path') - def importer_edit(self, session, task): """Callback for invoking the functionality during an interactive import session on the *original* item tags. """ - singleton = isinstance(object, SingletonImportTask) - item_fields = self._get_fields(False, []) - items = list(task.items) # Shallow copy, not modifying task.items. - if not singleton: - # Prepend a FakeAlbum for allowing the user to edit album fields. - album = FakeAlbum(task.items, task.toppath) - items.insert(0, album) - album_fields = self._get_fields(True, []) - else: - album_fields = None + # Assign temporary ids to the Items. + for i, obj in enumerate(task.items): + obj.id = i + 1 # Present the YAML to the user and let her change it. - success = self.edit_objects(items, item_fields, album_fields) + fields = self._get_fields(album=False, extra=[]) + success = self.edit_objects(task.items, fields) + + # Remove temporary ids. + for obj in task.items: + obj.id = None # Save the new data. if success: - if not singleton: - # Propagate the album changes to the items. - album._apply_changes() # Return action.RETAG, which makes the importer write the tags - # to the files if needed. + # to the files if needed without re-applying metadata. return action.RETAG else: # Edit cancelled / no edits made. Revert changes. @@ -416,41 +375,13 @@ class EditPlugin(plugins.BeetsPlugin): def importer_edit_candidate(self, session, task): """Callback for invoking the functionality during an interactive - import session on a *candidate* applied to the original items. + import session on a *candidate*. The candidate's metadata is + applied to the original items. """ - # Prompt the user for a candidate, and simulate matching. + # Prompt the user for a candidate. sel = ui.input_options([], numrange=(1, len(task.candidates))) # Force applying the candidate on the items. task.match = task.candidates[sel - 1] task.apply_metadata() return self.importer_edit(session, task) - - -class FakeAlbum(Album): - """Helper for presenting the user with an Album to be edited when there - is no real Album present. The album fields are set from the first item, - and after editing propagated to the items on `_apply_changes`. - """ - def __init__(self, items, path): - self._src_items = items - - # Create the album structure using metadata from the first item. - values = dict((key, items[0][key]) for key in Album.item_keys) - # Manually set the path as a single value field. - values[u'path'] = util.displayable_path(path) - super(FakeAlbum, self).__init__(**values) - - def _getters(self): - """Remove 'path' from Album._getters(), treating it as a regular field - in order to be able to use it directly.""" - getters = Album._getters() - getters.pop('path') - return getters - - def _apply_changes(self): - """Propagate changes to the album fields onto the Items. - """ - values = dict((key, self[key]) for key in Album.item_keys) - for i in self._src_items: - i.update(values) From 7f75a066bd8fb8a05d2602c6f427fbe53b416fd1 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 5 Feb 2016 12:38:50 +0100 Subject: [PATCH 0481/2280] edit: RETAG importer fixes and docstrings * Remove the RETAG-specific logic on align_album_level_fields, assuming that the user will always make sure to have proper data on the first item. * Revise some docstrings and comments in order to clarify the use of RETAG. --- beets/importer.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 97cabb92b..f4dd4853d 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -46,6 +46,9 @@ from beets import mediafile action = Enum('action', ['SKIP', 'ASIS', 'TRACKS', 'MANUAL', 'APPLY', 'MANUAL_ID', 'ALBUMS', 'RETAG']) +# The RETAG action represents "don't apply any match, but do record +# new metadata". It's not reachable via the standard command prompt but +# can be used by plugins. QUEUE_SIZE = 128 SINGLE_ARTIST_THRESH = 0.25 @@ -480,8 +483,8 @@ class ImportTask(BaseImportTask): """Returns identifying metadata about the current choice. For albums, this is an (artist, album) pair. For items, this is (artist, title). May only be called when the choice flag is ASIS - (in which case the data comes from the files' current metadata) - or APPLY (data comes from the choice). + or RETAG (in which case the data comes from the files' current + metadata) or APPLY (data comes from the choice). """ if self.choice_flag in (action.ASIS, action.RETAG): return (self.cur_artist, self.cur_album) @@ -618,15 +621,14 @@ class ImportTask(BaseImportTask): return duplicates def align_album_level_fields(self): - """Make some album fields equal across `self.items`. + """Make some album fields equal across `self.items`. For the + RETAG action, we assume that the responsible for returning it + (ie. a plugin) always ensures that the first item contains + valid data on the relevant fields. """ changes = {} - # Determine where to gather the info from for the RETAG action. - retag_asis = (self.choice_flag == action.RETAG and - not self.items[0].artist and - not self.items[0].mb_artistid) - if self.choice_flag == action.ASIS or retag_asis: + if self.choice_flag == action.ASIS: # Taking metadata "as-is". Guess whether this album is VA. plur_albumartist, freq = util.plurality( [i.albumartist or i.artist for i in self.items] From 763813fdf71e59befdb6b05f783595b7639dfb15 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 5 Feb 2016 13:12:46 +0100 Subject: [PATCH 0482/2280] edit: add documentation * Add documentation to plugins/edit.rst about the execution of the plugin during the importer. --- docs/plugins/edit.rst | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/plugins/edit.rst b/docs/plugins/edit.rst index 507d56950..44286f79c 100644 --- a/docs/plugins/edit.rst +++ b/docs/plugins/edit.rst @@ -23,6 +23,30 @@ The ``edit`` command has these command-line options: (in addition to the defaults set in the configuration). - ``--all``: Edit *all* available fields. +Interactive Usage +----------------- + +The ``edit`` plugin can also be invoked during an import session. If enabled, it +adds two new options to the user prompt:: + + [A]pply, More candidates, Skip, Use as-is, as Tracks, Group albums, Enter search, enter Id, aBort, eDit, edit Candidates? + +- ``eDit``: use this option for using the original items' metadata as the + starting point for your edits. +- ``edit Candidates``: use this option for using a candidate's metadata as the + starting point for your edits. + +Please note that currently the interactive usage of the plugin will only allow +you to change the item-level fields. In case you need to edit the album-level +fields, the recommended approach is to invoke the plugin via the command line +in album mode (``beet edit -a QUERY``) after the import. + +Also, please be aware that the ``edit Candidates`` choice can only be used with +the matches found during the initial search (and currently not supporting the +candidates found via the ``Enter search`` or ``enter Id`` choices). You might +find the ``--search-id SEARCH_ID`` :ref:`import-cmd` option useful for those +cases where you already have a specific candidate ID that you want to edit. + Configuration ------------- From 0f155ce3b913ca49e5f23063706501fe8d004769 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Fri, 5 Feb 2016 23:50:24 -0600 Subject: [PATCH 0483/2280] Use beets API key for lastimport plugin. --- beetsplug/lastimport.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 38b5bfc10..1151622ba 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -171,7 +171,7 @@ def fetch_tracks(user, page, limit): } ] """ - network = pylast.LastFMNetwork(api_key=config['lastfm']['api_key']) + network = pylast.LastFMNetwork(api_key=plugins.LASTFM_KEY) user_obj = CustomUser(user, network) results, total_pages =\ user_obj.get_top_tracks_by_page(limit=limit, page=page) From ea36c5a8256bc43a0627014ade8535630188ebba Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 6 Feb 2016 00:41:59 -0600 Subject: [PATCH 0484/2280] Allow default lastfm key to be overridden in config --- beetsplug/lastimport.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 1151622ba..29560b7f2 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -32,7 +32,7 @@ class LastImportPlugin(plugins.BeetsPlugin): super(LastImportPlugin, self).__init__() config['lastfm'].add({ 'user': '', - 'api_key': '', + 'api_key': plugins.LASTFM_KEY, }) config['lastfm']['api_key'].redact = True self.config.add({ @@ -171,7 +171,7 @@ def fetch_tracks(user, page, limit): } ] """ - network = pylast.LastFMNetwork(api_key=plugins.LASTFM_KEY) + network = pylast.LastFMNetwork(api_key=config['lastfm']['api_key']) user_obj = CustomUser(user, network) results, total_pages =\ user_obj.get_top_tracks_by_page(limit=limit, page=page) From 94b9d786b591128c7a972c3eab267c27f2ee8194 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 6 Feb 2016 00:42:23 -0600 Subject: [PATCH 0485/2280] add to changelog --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index c23597285..99ed6d99b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -62,6 +62,8 @@ Fixes: * :doc:`/plugins/lyrics`: In a continuing saga, the Genius API we use is down again, so it's been disabled by default *again*. We'll probably leave it disabled this time. +* :doc:`/plugins/lastimport`: The plugin now works with the beets api key by + default. This can be overridden in the plugin config. .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox From 10d44fe5262f57396cca2453caf5d088778cc382 Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Sat, 6 Feb 2016 07:46:31 +0100 Subject: [PATCH 0486/2280] Add some more docs to canonicalization with example It really didn't make sense to me before I did some further research. You shouldn't have to do further research to understand this apart form reading the docs. --- docs/plugins/lastgenre.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 69db32877..097a6cbaa 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -47,6 +47,16 @@ be turned into coarser-grained ones that are present in the whitelist. This works using a `tree of nested genre names`_, represented using `YAML`_, where the leaves of the tree represent the most specific genres. +The most common way to use this would be with a custom whitelist containing only +a desired subset of genres. For example, if the custom whitelist contains `rock` +and `heavy metal` (which is a child node of `rock` in the default genre tree) +then an item that has its genre specified as `viking metal` would actually be +tagged as `heavy metal` because neither `viking metal` nor its parent +`black metal` are in the whitelist. Considering that, it's not very useful to +use the default whitelist (which contains about any genre contained in the tree) +with canonicalization because nothing would ever be matched to a more generic +node since all the specific subgenres are in the whitelist to begin with. + .. _YAML: http://www.yaml.org/ .. _tree of nested genre names: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres-tree.yaml From 14db7ea6ec21acd02f7c9fdba0d6328bc376edf1 Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Sat, 6 Feb 2016 08:44:17 +0100 Subject: [PATCH 0487/2280] Add snippets for canonicalization --- docs/plugins/lastgenre.rst | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 097a6cbaa..5c3f0b77e 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -48,14 +48,29 @@ works using a `tree of nested genre names`_, represented using `YAML`_, where th leaves of the tree represent the most specific genres. The most common way to use this would be with a custom whitelist containing only -a desired subset of genres. For example, if the custom whitelist contains `rock` -and `heavy metal` (which is a child node of `rock` in the default genre tree) -then an item that has its genre specified as `viking metal` would actually be -tagged as `heavy metal` because neither `viking metal` nor its parent -`black metal` are in the whitelist. Considering that, it's not very useful to -use the default whitelist (which contains about any genre contained in the tree) -with canonicalization because nothing would ever be matched to a more generic -node since all the specific subgenres are in the whitelist to begin with. +a desired subset of genres. Consider for a example this minimal whitelist:: + + rock + heavy metal + pop + +together with the default genre tree. Then an item that has its genre specified +as `viking metal` would actually be tagged as `heavy metal` because neither +`viking metal` nor its parent `black metal` are in the whitelist. It always +tries to use the most specific genre that's available in the whitelist. + +The relevant subtree path in the default tree looks like this:: + + - rock: + - heavy metal: + - black metal: + - viking metal + +Considering that, it's not very useful to use the default whitelist (which +contains about any genre contained in the tree) with canonicalization because +nothing would ever be matched to a more generic node since all the specific +subgenres are in the whitelist to begin with. + .. _YAML: http://www.yaml.org/ .. _tree of nested genre names: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres-tree.yaml From 945ef18164b7579605abfc02ee47bec8350c5468 Mon Sep 17 00:00:00 2001 From: Sven-Hendrik Haase Date: Sat, 6 Feb 2016 08:45:32 +0100 Subject: [PATCH 0488/2280] Some typesetting --- docs/plugins/lastgenre.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 5c3f0b77e..8db198151 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -55,8 +55,8 @@ a desired subset of genres. Consider for a example this minimal whitelist:: pop together with the default genre tree. Then an item that has its genre specified -as `viking metal` would actually be tagged as `heavy metal` because neither -`viking metal` nor its parent `black metal` are in the whitelist. It always +as *viking metal* would actually be tagged as *heavy metal* because neither +*viking metal* nor its parent *black metal* are in the whitelist. It always tries to use the most specific genre that's available in the whitelist. The relevant subtree path in the default tree looks like this:: From 314521b6aee7da7abd65aec739793f602797fb69 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 14:28:33 -0800 Subject: [PATCH 0489/2280] replaygain: Fix obvious typo (fix #1873, I hope) --- beetsplug/replaygain.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index babb469ad..9e5bff4e0 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -743,7 +743,7 @@ class AudioToolsBackend(Backend): # Each call to title_gain on a ReplayGain object returns peak and gain # of the track. - rg_track_gain, rg_track_peak = rg._title_gain(rg, audiofile) + rg_track_gain, rg_track_peak = self._title_gain(rg, audiofile) self._log.debug(u'ReplayGain for track {0} - {1}: {2:.2f}, {3:.2f}', item.artist, item.title, rg_track_gain, rg_track_peak) diff --git a/docs/changelog.rst b/docs/changelog.rst index 99ed6d99b..0bde4470e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -64,6 +64,8 @@ Fixes: disabled this time. * :doc:`/plugins/lastimport`: The plugin now works with the beets api key by default. This can be overridden in the plugin config. +* :doc:`/plugins/replaygain`: Fix a crash using the Python Audio Tools + backend. :bug:`1873` .. _beets.io: http://beets.io/ .. _Beetbox: https://github.com/beetbox From 66fa962833c61afe54c86be8102ddc2bbcb9274a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 14:38:08 -0800 Subject: [PATCH 0490/2280] Changelog for #1846; fix #396 --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0bde4470e..d930d9f43 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,12 @@ New: initial lookup is slow. Also, the ``enter Id`` prompt choice now accepts several IDs, separated by spaces. :bug:`1808` +* :doc:`/plugins/edit`: You can now edit metadata *on the fly* during the + import process. The plugin provides two new interactive options: one to edit + *your music's* metadata, and one to edit the *matched metadata* retrieved + from MusicBrainz (or another data source). This feature is still in its + early stages, so please send feedback if you find anything missing. + :bug:`1846` :bug:`396` * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It now requires an API key from Google. Thanks to :user:`lcharlick`. :bug:`1778` From abc2ff066b55e422111493d03c754b5691a95a9f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 14:48:45 -0800 Subject: [PATCH 0491/2280] Refine naming and docs for #1843 Most urgently, this function doesn't just work on *items*; it works on arbitrary objects (and, in particular, albums). --- beets/ui/__init__.py | 37 ++++++++++++++++++++----------------- beets/ui/commands.py | 4 ++-- test/test_ui_init.py | 10 +++++----- 3 files changed, 27 insertions(+), 24 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index be47ba1cb..3805aa4e1 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -367,29 +367,32 @@ def input_yn(prompt, require=False): return sel == 'y' -def input_select_items(prompt, items, rep): - """Prompts the user to use all, none or some of the items - Will return the list of items the user selected - prompt: prompt to use for all and for selective choice - items: full list of items - rep: function which represents an item to the user - is called with the item as argument - function is responsive for newline at input +def input_select_objects(prompt, objs, rep): + """Prompt to user to choose all, none, or some of the given objects. + Return the list of selected objects. + + `prompt` is the prompt string to use for each question (it should be + phrased as an imperative verb). `rep` is a function to call on each + object to print it out when confirming objects individually. """ - out_items = [] choice = input_options( ('y', 'n', 's'), False, '%s? (Yes/no/select)' % prompt) - print() # go to a new line - if choice == 'y': - out_items = items - elif choice == 's': - for item in items: - rep(item) + print() # Blank line. + + if choice == 'y': # Yes. + return objs + + elif choice == 's': # Select. + out = [] + for obj in objs: + rep(obj) if input_yn('%s? (yes/no)' % prompt, True): - out_items.append(item) + out.append(obj) print() # go to a new line - return out_items + + else: # No. + return [] # Human output formatting. diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 1bd58fbd5..c27346be5 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1368,7 +1368,7 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): else: extra = '' - changed = ui.input_select_items( + changed = ui.input_select_objects( 'Really modify%s' % extra, changed, lambda o: print_and_modify(o, mods, dels)) @@ -1481,7 +1481,7 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False): for obj in objs]) else: if confirm: - objs = ui.input_select_items( + objs = ui.input_select_objects( 'Really %s' % act, objs, lambda o: show_path_changes( [(o.path, o.destination(basedir=dest))])) diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 6ab94f9ea..98a2aac99 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -32,18 +32,18 @@ class InputMethodsTest(_common.TestCase): def _print_helper2(self, s, prefix): print(prefix, s) - def test_input_select_items(self): + def test_input_select_objects(self): full_items = ['1', '2', '3', '4', '5'] # Test no self.io.addinput('n') - items = ui.input_select_items( + items = ui.input_select_objects( "Prompt", full_items, self._print_helper) self.assertEqual(items, []) # Test yes self.io.addinput('y') - items = ui.input_select_items( + items = ui.input_select_objects( "Prompt", full_items, self._print_helper) self.assertEqual(items, full_items) @@ -54,7 +54,7 @@ class InputMethodsTest(_common.TestCase): self.io.addinput('n') self.io.addinput('y') self.io.addinput('n') - items = ui.input_select_items( + items = ui.input_select_objects( "Prompt", full_items, self._print_helper) self.assertEqual(items, ['2', '4']) @@ -65,7 +65,7 @@ class InputMethodsTest(_common.TestCase): self.io.addinput('n') self.io.addinput('y') self.io.addinput('n') - items = ui.input_select_items( + items = ui.input_select_objects( "Prompt", full_items, lambda s: self._print_helper2(s, "Prefix")) self.assertEqual(items, ['1', '2', '4']) From 2aeed21f80ced6bb3a45edda7702a093c74683ae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 14:50:38 -0800 Subject: [PATCH 0492/2280] A little more documentation massaging for #1843 To make the docstirng fit in with the standard style. --- beets/ui/commands.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c27346be5..bc57a5431 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1370,7 +1370,8 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): changed = ui.input_select_objects( 'Really modify%s' % extra, changed, - lambda o: print_and_modify(o, mods, dels)) + lambda o: print_and_modify(o, mods, dels) + ) # Apply changes to database and files with lib.transaction(): @@ -1379,10 +1380,11 @@ def modify_items(lib, mods, dels, query, write, move, album, confirm): def print_and_modify(obj, mods, dels): - """Print the modifications to an item - and return a bool indicating whether any changes were made - mods: modifications - dels: fields to delete + """Print the modifications to an item and return a bool indicating + whether any changes were made. + + `mods` is a dictionary of fields and values to update on the object; + `dels` is a sequence of fields to delete. """ obj.update(mods) for field in dels: From 12633774101534f923bdd33f3892561599c97c37 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 14:52:38 -0800 Subject: [PATCH 0493/2280] Restore missing return statement Oops! :flushed: --- beets/ui/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 3805aa4e1..d395fe465 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -390,6 +390,7 @@ def input_select_objects(prompt, objs, rep): if input_yn('%s? (yes/no)' % prompt, True): out.append(obj) print() # go to a new line + return out else: # No. return [] From d87f921570a80d32335befa9ee1c06163f95803e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 15:02:31 -0800 Subject: [PATCH 0494/2280] Clean up changelog for release --- docs/changelog.rst | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index d930d9f43..059b1a3ff 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,11 +4,19 @@ Changelog 1.3.17 (in development) ----------------------- -As of this release, the beets project has some new Internet homes! Our new -domain name is `beets.io`_, and we have a shiny new GitHub organization: +This release introduces one new plugin to fetch audio information from the +`AcousticBrainz`_ project and another plugin to make it easier to submit your +handcrafted metadata back to MusicBrainz. +The importer also gained two oft-requested features: a way to skip the initial +search process by specifying an ID ahead of time, and a way to *manually* +provide metadata in the middle of the import process (via the +:doc:`/plugins/edit`). + +Also, as of this release, the beets project has some new Internet homes! Our +new domain name is `beets.io`_, and we have a shiny new GitHub organization: `beetbox`_. -New: +Here are the big new features: * A new :doc:`/plugins/acousticbrainz` fetches acoustic-analysis information from the `AcousticBrainz`_ project. Thanks to :user:`opatel99`, and thanks @@ -28,6 +36,9 @@ New: from MusicBrainz (or another data source). This feature is still in its early stages, so please send feedback if you find anything missing. :bug:`1846` :bug:`396` + +There are even more new features: + * :doc:`/plugins/fetchart`: The Google Images backend has been restored. It now requires an API key from Google. Thanks to :user:`lcharlick`. :bug:`1778` @@ -35,18 +46,18 @@ New: their values. Thanks to :user:`GuilhermeHideki`. :bug:`1812` * The :ref:`fields-cmd` command now displays flexible attributes. Thanks to :user:`GuilhermeHideki`. :bug:`1818` -* The :ref:`modify-cmd` command lets you interactive select tracks to apply - changes. :bug:`1843` -* The :ref:`move-cmd` command accepts `-t`, `--timid` switch now to confirm - or interactive select tracks process. :bug:`1843` +* The :ref:`modify-cmd` command lets you interactively select which albums or + items you want to change. :bug:`1843` +* The :ref:`move-cmd` command gained a new ``--timid`` flag to print and + confirm which files you want to move. :bug:`1843` +* The :ref:`move-cmd` command no longer prints filenames for files that + don't actually need to be moved. :bug:`1583` .. _Google Code-In: https://codein.withgoogle.com/ .. _AcousticBrainz: http://acousticbrainz.org/ Fixes: -* The :ref:`move-cmd` command no longer not prints filenames for files that - don't actually need to be moved. :bug:`1583` * :doc:`/plugins/play`: Fix a regression in the last version where there was no default command. :bug:`1793` * :doc:`/plugins/lastimport`: The plugin now works again after being broken by @@ -55,8 +66,6 @@ Fixes: now ``warning_threshold`` instead of ``warning_treshold``, but we kept the old name around for compatibility. Thanks to :user:`JesseWeinstein`. :bug:`1802` :bug:`1803` -* :doc:`/plugins/lyrics`: The Genius backend has been re-enabled (after being - temporarily disabled in the last version). * :doc:`/plugins/edit`: Editing metadata now moves files, when appropriate (like the :ref:`modify-cmd` command). :bug:`1804` * The :ref:`stats-cmd` command no longer crashes when files are missing or @@ -65,11 +74,8 @@ Fixes: some versions of pyOpenSSL. :bug:`1805` * :doc:`/plugins/replaygain`: Fix an intermittent crash with the GStreamer backend. :bug:`1855` -* :doc:`/plugins/lyrics`: In a continuing saga, the Genius API we use is down - again, so it's been disabled by default *again*. We'll probably leave it - disabled this time. -* :doc:`/plugins/lastimport`: The plugin now works with the beets api key by - default. This can be overridden in the plugin config. +* :doc:`/plugins/lastimport`: The plugin now works with the beets API key by + default. You can still provide a different key the configuration. * :doc:`/plugins/replaygain`: Fix a crash using the Python Audio Tools backend. :bug:`1873` From 53029a0ed6fcaacf8ad96a201f99e0872748afaf Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Mon, 8 Feb 2016 00:48:00 +0100 Subject: [PATCH 0495/2280] edit docs for replaygain audio tools backend --- docs/plugins/replaygain.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/replaygain.rst b/docs/plugins/replaygain.rst index 968e996e6..6f119e2b0 100644 --- a/docs/plugins/replaygain.rst +++ b/docs/plugins/replaygain.rst @@ -67,7 +67,7 @@ Python Audio Tools This backend uses the `Python Audio Tools`_ package to compute ReplayGain for a range of different file formats. The package is not available via PyPI; it -must be installed manually. +must be installed manually (only versions preceding 3.x are compatible). On OS X, most of the dependencies can be installed with `Homebrew`_:: From 65521cd05dc65a3b0e7b49bcd50b0fbda95961b6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 22:38:54 -0800 Subject: [PATCH 0496/2280] Add date for 1.3.17 release --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 059b1a3ff..4019e66af 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.17 (in development) ------------------------ +1.3.17 (February 7, 2016) +------------------------- This release introduces one new plugin to fetch audio information from the `AcousticBrainz`_ project and another plugin to make it easier to submit your From df07d83a6d069740336b5a3f3094655990462382 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 22:39:32 -0800 Subject: [PATCH 0497/2280] Version bump: 1.3.18 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index a1fa5c432..89ab74708 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -20,7 +20,7 @@ import os import beets.library from beets.util import confit -__version__ = '1.3.17' +__version__ = '1.3.18' __author__ = 'Adrian Sampson ' Library = beets.library.Library diff --git a/docs/changelog.rst b/docs/changelog.rst index 4019e66af..df54089f2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.3.18 (in development) +----------------------- + +Changelog goes here! + + 1.3.17 (February 7, 2016) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index 66223d6f7..ad100b467 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,7 +14,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.3' -release = '1.3.17' +release = '1.3.18' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index f602e3537..3acd45e7c 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.17', + version='1.3.18', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 1cbf992d4fb61dff76824b852a254989225c28a3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 7 Feb 2016 23:00:06 -0800 Subject: [PATCH 0498/2280] release.py: Automate GitHub release creation --- extra/release.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/extra/release.py b/extra/release.py index 302a5f3de..7bbc080c4 100755 --- a/extra/release.py +++ b/extra/release.py @@ -64,6 +64,9 @@ VERSION_LOCS = [ ), ] +GITHUB_USER = 'beetbox' +GITHUB_REPO = 'beets' + def bump_version(version): """Update the version number in setup.py, docs config, changelog, @@ -312,5 +315,40 @@ def publish(): subprocess.check_call(['twine', 'upload', path]) +@release.command() +def ghrelease(): + """Create a GitHub release using the `github-release` command-line + tool. + + Reads the changelog to upload from `changelog.md`. Uploads the + tarball from the `dist` directory. + """ + version = get_version(1) + tag = 'v' + version + + # Load the changelog. + with open(os.path.join(BASE, 'changelog.md')) as f: + cl_md = f.read() + + # Create the release. + subprocess.check_call([ + 'github-release', 'release', + '-u', GITHUB_USER, '-r', GITHUB_REPO, + '--tag', tag, + '--name', '{} {}'.format(GITHUB_REPO, version), + '--description', cl_md, + ]) + + # Attach the release tarball. + tarball = os.path.join(BASE, 'dist', 'beets-{}.tar.gz'.format(version)) + subprocess.check_call([ + 'github-release', 'upload', + '-u', GITHUB_USER, '-r', GITHUB_REPO, + '--tag', tag, + '--name', os.path.basename(tarball), + '--file', tarball, + ]) + + if __name__ == '__main__': release() From 82dc89ad83b8b389f2037ce586c3e1abee3adb83 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Wed, 10 Feb 2016 10:14:48 -0600 Subject: [PATCH 0499/2280] documention for overriding the default last.fm api key with a custom one in lastimport --- docs/plugins/lastimport.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index a38447083..697ce2717 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -53,3 +53,8 @@ options under the ``lastimport:`` section: * **retry_limit**: How many times should we re-send requests to Last.fm on failure? Default: 3. + +By default lastimport will use beets Last.fm API key. If you wish you can +override this with your own API key. + lastfm: + api_key: your_api_key From 0babeab862b62c1d61898990f5e7e60124fdae97 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Wed, 10 Feb 2016 10:33:52 -0600 Subject: [PATCH 0500/2280] fix documentation error --- docs/plugins/lastimport.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index 697ce2717..78a4a3953 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -55,6 +55,7 @@ options under the ``lastimport:`` section: Default: 3. By default lastimport will use beets Last.fm API key. If you wish you can -override this with your own API key. - lastfm: +override this with your own API key.:: + + lastfm: api_key: your_api_key From fb4ba2924fbf4ff6bd694000ad0a2c0e03ab0fc9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 10 Feb 2016 10:10:26 -0800 Subject: [PATCH 0501/2280] Grammar/formatting refinement for #1878 --- docs/plugins/lastimport.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index 78a4a3953..d047f8a3b 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -54,8 +54,8 @@ options under the ``lastimport:`` section: failure? Default: 3. -By default lastimport will use beets Last.fm API key. If you wish you can -override this with your own API key.:: +By default, the plugin will use beets's own Last.fm API key. You can also +override it with your own API key:: lastfm: - api_key: your_api_key + api_key: your_api_key From 30eed5915b10593ca44df034dbfaefea7a61dbda Mon Sep 17 00:00:00 2001 From: Manuel Koell Date: Mon, 15 Feb 2016 23:13:46 +0100 Subject: [PATCH 0502/2280] beet import: there is no such option: -M --- docs/faq.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/faq.rst b/docs/faq.rst index 1d0829cd1..974b0dce6 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -221,7 +221,7 @@ move all your files. If you've already moved your music *outside* of beets, you have a few options: - Move the music back (with an ordinary ``mv``) and then use the above steps. -- Delete your database and re-create it from the new paths using ``beet import -AWMC``. +- Delete your database and re-create it from the new paths using ``beet import -AWC``. - Resort to manually modifying the SQLite database (not recommended). From 49b85347149276a05027b7ae40a249798c1e75d8 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 17 Feb 2016 21:46:26 +0100 Subject: [PATCH 0503/2280] Started remove import of unicode_literals --- beets/__init__.py | 6 +++--- beets/autotag/__init__.py | 3 +-- beets/autotag/hooks.py | 19 +++++++++---------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index a1fa5c432..1f75209a1 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -13,15 +13,15 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import, unicode_literals +from __future__ import absolute_import import os import beets.library from beets.util import confit -__version__ = '1.3.17' -__author__ = 'Adrian Sampson ' +__version__ = u'1.3.17' +__author__ = u'Adrian Sampson ' Library = beets.library.Library diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 924eb85f2..17885a817 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -16,8 +16,7 @@ """Facilities for automatically determining files' correct metadata. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets import logging from beets import config diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 303ce3418..642c0cb4b 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """Glue between metadata sources and the matching logic.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from collections import namedtuple import re @@ -394,7 +393,7 @@ class Distance(object): """ if not isinstance(dist, Distance): raise ValueError( - '`dist` must be a Distance object, not {0}'.format(type(dist)) + u'`dist` must be a Distance object, not {0}'.format(type(dist)) ) for key, penalties in dist._penalties.iteritems(): self._penalties.setdefault(key, []).extend(penalties) @@ -418,7 +417,7 @@ class Distance(object): """ if not 0.0 <= dist <= 1.0: raise ValueError( - '`dist` must be between 0.0 and 1.0, not {0}'.format(dist) + u'`dist` must be between 0.0 and 1.0, not {0}'.format(dist) ) self._penalties.setdefault(key, []).append(dist) @@ -514,7 +513,7 @@ def album_for_mbid(release_id): try: album = mb.album_for_id(release_id) if album: - plugins.send('albuminfo_received', info=album) + plugins.send(u'albuminfo_received', info=album) return album except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -527,7 +526,7 @@ def track_for_mbid(recording_id): try: track = mb.track_for_id(recording_id) if track: - plugins.send('trackinfo_received', info=track) + plugins.send(u'trackinfo_received', info=track) return track except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -538,7 +537,7 @@ def albums_for_id(album_id): candidates = [album_for_mbid(album_id)] plugin_albums = plugins.album_for_id(album_id) for a in plugin_albums: - plugins.send('albuminfo_received', info=a) + plugins.send(u'albuminfo_received', info=a) candidates.extend(plugin_albums) return filter(None, candidates) @@ -548,7 +547,7 @@ def tracks_for_id(track_id): candidates = [track_for_mbid(track_id)] plugin_tracks = plugins.track_for_id(track_id) for t in plugin_tracks: - plugins.send('trackinfo_received', info=t) + plugins.send(u'trackinfo_received', info=t) candidates.extend(plugin_tracks) return filter(None, candidates) @@ -581,7 +580,7 @@ def album_candidates(items, artist, album, va_likely): # Notify subscribed plugins about fetched album info for a in out: - plugins.send('albuminfo_received', info=a) + plugins.send(u'albuminfo_received', info=a) return out @@ -605,6 +604,6 @@ def item_candidates(item, artist, title): # Notify subscribed plugins about fetched track info for i in out: - plugins.send('trackinfo_received', info=i) + plugins.send(u'trackinfo_received', info=i) return out From f300667c04243feed0ab1f48eca6978ab20202d5 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 17 Feb 2016 21:55:27 +0100 Subject: [PATCH 0504/2280] Enabled travis on all branches --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 4a17ab2ea..f78612b7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,6 @@ language: python sudo: false -branches: - only: - - master - matrix: include: - python: 2.7 From 05622ba059260c552949fb9998d117a88271d75d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 17 Feb 2016 15:01:24 -0800 Subject: [PATCH 0505/2280] Start an issue template --- .github/ISSUE_TEMPLATE.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..cda20d4df --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,14 @@ +(Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please also fill out the "Setup" section below. Otherwise, you can delete it.) + +### Setup + +* OS: +* Python version: +* beets version: +* I tried turning off plugins, and that made the problem go away (yes/no): + +My configuration (output of `beet config`) is: + +```yaml +(paste here) +``` From 6f2c495973bc23d9417a4fb4a48a3d22700d0f58 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 17 Feb 2016 15:51:04 -0800 Subject: [PATCH 0506/2280] Suggest ways to describe problems --- .github/ISSUE_TEMPLATE.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index cda20d4df..09981d1d7 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,4 +1,22 @@ -(Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please also fill out the "Setup" section below. Otherwise, you can delete it.) +Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please fill out the "Problem" and "Setup" sections below. Otherwise, you can delete it. + + +### Problem + +Running this command in verbose (`-vv`) mode: + +```sh +$ beet -vv (... paste here ...) +``` + +Led to this problem: + +``` +(paste here) +``` + +Here's a link to the music files that trigger the bug (if relevant): + ### Setup From 4f0352f4d404623f9f78149124ea2222f6b57947 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 21:47:29 +0100 Subject: [PATCH 0507/2280] Removed unicode_literals from module autotag --- beets/autotag/match.py | 5 ++--- beets/autotag/mb.py | 15 +++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 3565dba3f..230e26e52 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -17,8 +17,7 @@ releases and tracks. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import datetime import re @@ -337,7 +336,7 @@ def _add_candidate(items, results, info): # Discard albums with zero tracks. if not info.tracks: - log.debug('No tracks.') + log.debug(u'No tracks.') return # Don't duplicate. diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index cc1780365..9ffac4918 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -15,8 +15,7 @@ """Searches for albums in the MusicBrainz database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import musicbrainzngs import re @@ -43,7 +42,7 @@ class MusicBrainzAPIError(util.HumanReadableException): def __init__(self, reason, verb, query, tb=None): self.query = query if isinstance(reason, musicbrainzngs.WebServiceError): - reason = 'MusicBrainz not reachable' + reason = u'MusicBrainz not reachable' super(MusicBrainzAPIError, self).__init__(reason, verb, tb) def get_message(self): @@ -162,7 +161,7 @@ def track_info(recording, index=None, medium=None, medium_index=None, medium=medium, medium_index=medium_index, medium_total=medium_total, - data_source='MusicBrainz', + data_source=u'MusicBrainz', data_url=track_url(recording['id']), ) @@ -256,7 +255,7 @@ def album_info(release): mediums=len(release['medium-list']), artist_sort=artist_sort_name, artist_credit=artist_credit_name, - data_source='MusicBrainz', + data_source=u'MusicBrainz', data_url=album_url(release['id']), ) info.va = info.artist_id == VARIOUS_ARTISTS_ID @@ -377,7 +376,7 @@ def _parse_id(s): no ID can be found, return None. """ # Find the first thing that looks like a UUID/MBID. - match = re.search('[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) + match = re.search(r'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group() @@ -398,7 +397,7 @@ def album_for_id(releaseid): log.debug(u'Album ID match failed.') return None except musicbrainzngs.MusicBrainzError as exc: - raise MusicBrainzAPIError(exc, 'get release by ID', albumid, + raise MusicBrainzAPIError(exc, u'get release by ID', albumid, traceback.format_exc()) return album_info(res['release']) @@ -417,6 +416,6 @@ def track_for_id(releaseid): log.debug(u'Track ID match failed.') return None except musicbrainzngs.MusicBrainzError as exc: - raise MusicBrainzAPIError(exc, 'get recording by ID', trackid, + raise MusicBrainzAPIError(exc, u'get recording by ID', trackid, traceback.format_exc()) return track_info(res['recording']) From 32d26d86c00580c921108e8e8cf057780bc5cebe Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 22:05:11 +0100 Subject: [PATCH 0508/2280] Removed unicode_literals form module dbcore --- beets/dbcore/db.py | 25 ++++++++++++------------- beets/dbcore/query.py | 41 ++++++++++++++++++++--------------------- beets/dbcore/types.py | 3 +-- 3 files changed, 33 insertions(+), 36 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index d784ddcae..aef4f9e62 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -15,8 +15,7 @@ """The central Model and Database constructs for DBCore. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import time import os @@ -184,7 +183,7 @@ class Model(object): return obj def __repr__(self): - return '{0}({1})'.format( + return u'{0}({1})'.format( type(self).__name__, ', '.join('{0}={1!r}'.format(k, v) for k, v in dict(self).items()), ) @@ -201,9 +200,9 @@ class Model(object): exception is raised otherwise. """ if not self._db: - raise ValueError('{0} has no database'.format(type(self).__name__)) + raise ValueError(u'{0} has no database'.format(type(self).__name__)) if need_id and not self.id: - raise ValueError('{0} has no id'.format(type(self).__name__)) + raise ValueError(u'{0} has no id'.format(type(self).__name__)) # Essential field accessors. @@ -255,11 +254,11 @@ class Model(object): del self._values_flex[key] self._dirty.add(key) # Mark for dropping on store. elif key in self._getters(): # Computed. - raise KeyError('computed field {0} cannot be deleted'.format(key)) + raise KeyError(u'computed field {0} cannot be deleted'.format(key)) elif key in self._fields: # Fixed. - raise KeyError('fixed field {0} cannot be deleted'.format(key)) + raise KeyError(u'fixed field {0} cannot be deleted'.format(key)) else: - raise KeyError('no such field {0}'.format(key)) + raise KeyError(u'no such field {0}'.format(key)) def keys(self, computed=False): """Get a list of available field names for this object. The @@ -318,12 +317,12 @@ class Model(object): def __getattr__(self, key): if key.startswith('_'): - raise AttributeError('model has no attribute {0!r}'.format(key)) + raise AttributeError(u'model has no attribute {0!r}'.format(key)) else: try: return self[key] except KeyError: - raise AttributeError('no such field {0!r}'.format(key)) + raise AttributeError(u'no such field {0!r}'.format(key)) def __setattr__(self, key, value): if key.startswith('_'): @@ -390,7 +389,7 @@ class Model(object): """ self._check_db() stored_obj = self._db._get(type(self), self.id) - assert stored_obj is not None, "object {0} not in DB".format(self.id) + assert stored_obj is not None, u"object {0} not in DB".format(self.id) self._values_fixed = {} self._values_flex = {} self.update(dict(stored_obj)) @@ -463,7 +462,7 @@ class Model(object): """Parse a string as a value for the given key. """ if not isinstance(string, basestring): - raise TypeError("_parse() argument must be a string") + raise TypeError(u"_parse() argument must be a string") return cls._type(key).parse(string) @@ -611,7 +610,7 @@ class Results(object): it.next() return it.next() except StopIteration: - raise IndexError('result index {0} out of range'.format(n)) + raise IndexError(u'result index {0} out of range'.format(n)) def get(self): """Return the first matching object, or None if no objects diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f91992712..268c879c7 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -15,8 +15,7 @@ """The Query type hierarchy for DBCore. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re from operator import mul @@ -39,7 +38,7 @@ class InvalidQueryError(ParsingError): def __init__(self, query, explanation): if isinstance(query, list): query = " ".join(query) - message = "'{0}': {1}".format(query, explanation) + message = u"'{0}': {1}".format(query, explanation) super(InvalidQueryError, self).__init__(message) @@ -50,9 +49,9 @@ class InvalidQueryArgumentTypeError(ParsingError): query) InvalidQueryError can be raised. """ def __init__(self, what, expected, detail=None): - message = "'{0}' is not {1}".format(what, expected) + message = u"'{0}' is not {1}".format(what, expected) if detail: - message = "{0}: {1}".format(message, detail) + message = u"{0}: {1}".format(message, detail) super(InvalidQueryArgumentTypeError, self).__init__(message) @@ -75,7 +74,7 @@ class Query(object): raise NotImplementedError def __repr__(self): - return "{0.__class__.__name__}()".format(self) + return u"{0.__class__.__name__}()".format(self) def __eq__(self, other): return type(self) == type(other) @@ -117,8 +116,8 @@ class FieldQuery(Query): return self.value_match(self.pattern, item.get(self.field)) def __repr__(self): - return ("{0.__class__.__name__}({0.field!r}, {0.pattern!r}, " - "{0.fast})".format(self)) + return (u"{0.__class__.__name__}({0.field!r}, {0.pattern!r}, " + u"{0.fast})".format(self)) def __eq__(self, other): return super(FieldQuery, self).__eq__(other) and \ @@ -154,7 +153,7 @@ class NoneQuery(FieldQuery): return True def __repr__(self): - return "{0.__class__.__name__}({0.field!r}, {0.fast})".format(self) + return u"{0.__class__.__name__}({0.field!r}, {0.fast})".format(self) class StringFieldQuery(FieldQuery): @@ -208,7 +207,7 @@ class RegexpQuery(StringFieldQuery): except re.error as exc: # Invalid regular expression. raise InvalidQueryArgumentTypeError(pattern, - "a regular expression", + u"a regular expression", format(exc)) @staticmethod @@ -283,7 +282,7 @@ class NumericQuery(FieldQuery): try: return float(s) except ValueError: - raise InvalidQueryArgumentTypeError(s, "an int or a float") + raise InvalidQueryArgumentTypeError(s, u"an int or a float") def __init__(self, field, pattern, fast=True): super(NumericQuery, self).__init__(field, pattern, fast) @@ -328,7 +327,7 @@ class NumericQuery(FieldQuery): elif self.rangemax is not None: return u'{0} <= ?'.format(self.field), (self.rangemax,) else: - return '1', () + return u'1', () class CollectionQuery(Query): @@ -369,7 +368,7 @@ class CollectionQuery(Query): return clause, subvals def __repr__(self): - return "{0.__class__.__name__}({0.subqueries})".format(self) + return u"{0.__class__.__name__}({0.subqueries})".format(self) def __eq__(self, other): return super(CollectionQuery, self).__eq__(other) and \ @@ -407,8 +406,8 @@ class AnyFieldQuery(CollectionQuery): return False def __repr__(self): - return ("{0.__class__.__name__}({0.pattern!r}, {0.fields}, " - "{0.query_class.__name__})".format(self)) + return (u"{0.__class__.__name__}({0.pattern!r}, {0.fields}, " + u"{0.query_class.__name__})".format(self)) def __eq__(self, other): return super(AnyFieldQuery, self).__eq__(other) and \ @@ -467,7 +466,7 @@ class NotQuery(Query): return not self.subquery.match(item) def __repr__(self): - return "{0.__class__.__name__}({0.subquery})".format(self) + return u"{0.__class__.__name__}({0.subquery})".format(self) def __eq__(self, other): return super(NotQuery, self).__eq__(other) and \ @@ -535,7 +534,7 @@ class Period(object): precision (a string, one of "year", "month", or "day"). """ if precision not in Period.precisions: - raise ValueError('Invalid precision {0}'.format(precision)) + raise ValueError(u'Invalid precision {0}'.format(precision)) self.date = date self.precision = precision @@ -575,7 +574,7 @@ class Period(object): elif 'day' == precision: return date + timedelta(days=1) else: - raise ValueError('unhandled precision {0}'.format(precision)) + raise ValueError(u'unhandled precision {0}'.format(precision)) class DateInterval(object): @@ -587,7 +586,7 @@ class DateInterval(object): def __init__(self, start, end): if start is not None and end is not None and not start < end: - raise ValueError("start date {0} is not before end date {1}" + raise ValueError(u"start date {0} is not before end date {1}" .format(start, end)) self.start = start self.end = end @@ -608,7 +607,7 @@ class DateInterval(object): return True def __str__(self): - return'[{0}, {1})'.format(self.start, self.end) + return u'[{0}, {1})'.format(self.start, self.end) class DateQuery(FieldQuery): @@ -677,7 +676,7 @@ class DurationQuery(NumericQuery): except ValueError: raise InvalidQueryArgumentTypeError( s, - "a M:SS string or a float") + u"a M:SS string or a float") # Sorting. diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index e90fd9d9b..acda2c3a2 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -15,8 +15,7 @@ """Representation of type information for DBCore model fields. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from . import query from beets.util import str2bool From 26c3cca83510c3d364767282380803c966604402 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 22:13:33 +0100 Subject: [PATCH 0509/2280] Removed unicode_literales from importer --- beets/importer.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 868ac6922..da51ac2a5 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Provides the basic, interface-agnostic workflow for importing and autotagging music files. @@ -248,17 +247,17 @@ class ImportSession(object): if duplicate: # Duplicate: log all three choices (skip, keep both, and trump). if task.should_remove_duplicates: - self.tag_log('duplicate-replace', paths) + self.tag_log(u'duplicate-replace', paths) elif task.choice_flag in (action.ASIS, action.APPLY): - self.tag_log('duplicate-keep', paths) + self.tag_log(u'duplicate-keep', paths) elif task.choice_flag is (action.SKIP): - self.tag_log('duplicate-skip', paths) + self.tag_log(u'duplicate-skip', paths) else: # Non-duplicate: log "skip" and "asis" choices. if task.choice_flag is action.ASIS: - self.tag_log('asis', paths) + self.tag_log(u'asis', paths) elif task.choice_flag is action.SKIP: - self.tag_log('skip', paths) + self.tag_log(u'skip', paths) def should_resume(self, path): raise NotImplementedError @@ -1143,7 +1142,7 @@ class ImportTaskFactory(object): if not (self.session.config['move'] or self.session.config['copy']): log.warn(u"Archive importing requires either " - "'copy' or 'move' to be enabled.") + u"'copy' or 'move' to be enabled.") return log.debug(u'Extracting archive: {0}', @@ -1318,7 +1317,7 @@ def resolve_duplicates(session, task): if task.choice_flag in (action.ASIS, action.APPLY): found_duplicates = task.find_duplicates(session.lib) if found_duplicates: - log.debug('found duplicates: {}'.format( + log.debug(u'found duplicates: {}'.format( [o.id for o in found_duplicates] )) session.resolve_duplicate(task, found_duplicates) @@ -1335,7 +1334,7 @@ def import_asis(session, task): if task.skip: return - log.info('{}', displayable_path(task.paths)) + log.info(u'{}', displayable_path(task.paths)) task.set_choice(action.ASIS) apply_choice(session, task) From 4b7b96128a95835680960ffbce4bac9a15793b71 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 22:15:40 +0100 Subject: [PATCH 0510/2280] fixed broken test --- beets/dbcore/db.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index aef4f9e62..07b0e9a45 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -200,7 +200,8 @@ class Model(object): exception is raised otherwise. """ if not self._db: - raise ValueError(u'{0} has no database'.format(type(self).__name__)) + raise ValueError( + u'{0} has no database'.format(type(self).__name__)) if need_id and not self.id: raise ValueError(u'{0} has no id'.format(type(self).__name__)) From 43572f50b0eb3522239d94149d91223e67d9a009 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 22:29:31 +0100 Subject: [PATCH 0511/2280] Removed unicode_literals from library, logging and mediafile --- beets/library.py | 20 ++++++++++---------- beets/logging.py | 3 +-- beets/mediafile.py | 15 +++++++-------- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/beets/library.py b/beets/library.py index 1c2fac944..901c3c1b0 100644 --- a/beets/library.py +++ b/beets/library.py @@ -15,8 +15,7 @@ """The core data store and collection logic for beets. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import sys @@ -627,7 +626,7 @@ class Item(LibModel): self.write(path, tags) return True except FileOperationError as exc: - log.error("{0}", exc) + log.error(u"{0}", exc) return False def try_sync(self, write, move, with_album=True): @@ -647,7 +646,7 @@ class Item(LibModel): if move: # Check whether this file is inside the library directory. if self._db and self._db.directory in util.ancestry(self.path): - log.debug('moving {0} to synchronize path', + log.debug(u'moving {0} to synchronize path', util.displayable_path(self.path)) self.move(with_album=with_album) self.store() @@ -796,7 +795,7 @@ class Item(LibModel): if query == PF_KEY_DEFAULT: break else: - assert False, "no default path format" + assert False, u"no default path format" if isinstance(path_format, Template): subpath_tmpl = path_format else: @@ -826,9 +825,10 @@ class Item(LibModel): if fellback: # Print an error message if legalization fell back to # default replacements because of the maximum length. - log.warning('Fell back to default replacements when naming ' - 'file {}. Configure replacements to avoid lengthening ' - 'the filename.', subpath) + log.warning( + u'Fell back to default replacements when naming ' + u'file {}. Configure replacements to avoid lengthening ' + u'the filename.', subpath) if fragment: return subpath @@ -1016,7 +1016,7 @@ class Album(LibModel): """ item = self.items().get() if not item: - raise ValueError('empty album') + raise ValueError(u'empty album') return os.path.dirname(item.path) def _albumtotal(self): @@ -1170,7 +1170,7 @@ def parse_query_string(s, model_cls): The string is split into components using shell-like syntax. """ - assert isinstance(s, unicode), "Query is not unicode: {0!r}".format(s) + assert isinstance(s, unicode), u"Query is not unicode: {0!r}".format(s) try: parts = util.shlex_split(s) except ValueError as exc: diff --git a/beets/logging.py b/beets/logging.py index 40748bc68..fc49cace7 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -21,8 +21,7 @@ that when getLogger(name) instantiates a logger that logger uses {}-style formatting. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from copy import copy from logging import * # noqa diff --git a/beets/mediafile.py b/beets/mediafile.py index 5010f8797..79223e70f 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -33,8 +33,7 @@ Internally ``MediaFile`` uses ``MediaField`` descriptors to access the data from the tags. In turn ``MediaField`` uses a number of ``StorageStyle`` strategies to handle format specific logic. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import mutagen import mutagen.mp3 @@ -645,13 +644,13 @@ class MP4BoolStorageStyle(MP4StorageStyle): return None def get_list(self, mutagen_file): - raise NotImplementedError('MP4 bool storage does not support lists') + raise NotImplementedError(u'MP4 bool storage does not support lists') def set(self, mutagen_file, value): mutagen_file[self.key] = value def set_list(self, mutagen_file, values): - raise NotImplementedError('MP4 bool storage does not support lists') + raise NotImplementedError(u'MP4 bool storage does not support lists') class MP4ImageStorageStyle(MP4ListStorageStyle): @@ -669,7 +668,7 @@ class MP4ImageStorageStyle(MP4ListStorageStyle): elif image.mime_type == 'image/jpeg': kind = mutagen.mp4.MP4Cover.FORMAT_JPEG else: - raise ValueError('MP4 files only supports PNG and JPEG images') + raise ValueError(u'MP4 files only supports PNG and JPEG images') return mutagen.mp4.MP4Cover(image.data, kind) @@ -1359,11 +1358,11 @@ class MediaFile(object): # anywhere else. raise else: - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) raise MutagenError(path, exc) except Exception as exc: # Isolate bugs in Mutagen. - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) log.error(u'uncaught Mutagen exception in open: {0}', exc) raise MutagenError(path, exc) @@ -1436,7 +1435,7 @@ class MediaFile(object): # Propagate these through: they don't represent Mutagen bugs. raise except Exception as exc: - log.debug('{}', traceback.format_exc()) + log.debug(u'{}', traceback.format_exc()) log.error(u'uncaught Mutagen exception in save: {0}', exc) raise MutagenError(self.path, exc) From 9918cbb34bf260030599ae8971983f1ca2d47013 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 22:35:14 +0100 Subject: [PATCH 0512/2280] Removed unicode_literals from plugins and vfs --- beets/plugins.py | 9 ++++----- beets/vfs.py | 3 +-- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index 4233003ea..b78b8fe59 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -15,8 +15,7 @@ """Support for beets plugins.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import inspect import traceback @@ -267,7 +266,7 @@ def load_plugins(names=()): except: log.warn( - '** error loading plugin {}:\n{}', + u'** error loading plugin {}:\n{}', name, traceback.format_exc(), ) @@ -322,8 +321,8 @@ def types(model_cls): if field in types and plugin_types[field] != types[field]: raise PluginConflictException( u'Plugin {0} defines flexible field {1} ' - 'which has already been defined with ' - 'another type.'.format(plugin.name, field) + u'which has already been defined with ' + u'another type.'.format(plugin.name, field) ) types.update(plugin_types) return types diff --git a/beets/vfs.py b/beets/vfs.py index d99031c63..75529c999 100644 --- a/beets/vfs.py +++ b/beets/vfs.py @@ -16,8 +16,7 @@ """A simple utility for constructing filesystem-like trees from beets libraries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from collections import namedtuple from beets import util From 2048a4fbcbee186683ee084aaf4cb6296ddeafd4 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Fri, 19 Feb 2016 23:28:22 +0100 Subject: [PATCH 0513/2280] 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 From 95e940b9f27ffd5cc767dc136709228480b27872 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 11:16:55 +0100 Subject: [PATCH 0514/2280] Removed unicode_literals from module util --- beets/util/__init__.py | 29 +++++++------- beets/util/artresizer.py | 9 ++--- beets/util/bluelet.py | 7 ++-- beets/util/confit.py | 77 +++++++++++++++++++------------------- beets/util/enumeration.py | 3 +- beets/util/functemplate.py | 7 ++-- beets/util/pipeline.py | 23 ++++++------ 7 files changed, 74 insertions(+), 81 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 0da68efc7..2a078380c 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -15,8 +15,7 @@ """Miscellaneous utility functions.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import sys import re @@ -57,10 +56,10 @@ class HumanReadableException(Exception): def _gerund(self): """Generate a (likely) gerund form of the English verb. """ - if ' ' in self.verb: + if u' ' in self.verb: return self.verb - gerund = self.verb[:-1] if self.verb.endswith('e') else self.verb - gerund += 'ing' + gerund = self.verb[:-1] if self.verb.endswith(u'e') else self.verb + gerund += u'ing' return gerund def _reasonstr(self): @@ -415,7 +414,7 @@ def copy(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if not replace and os.path.exists(dest): - raise FilesystemError('file exists', 'copy', (path, dest)) + raise FilesystemError(u'file exists', 'copy', (path, dest)) try: shutil.copyfile(path, dest) except (OSError, IOError) as exc: @@ -436,7 +435,7 @@ def move(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if os.path.exists(dest) and not replace: - raise FilesystemError('file exists', 'rename', (path, dest), + raise FilesystemError(u'file exists', 'rename', (path, dest), traceback.format_exc()) # First, try renaming the file. @@ -462,13 +461,13 @@ def link(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if os.path.exists(dest) and not replace: - raise FilesystemError('file exists', 'rename', (path, dest), + raise FilesystemError(u'file exists', 'rename', (path, dest), traceback.format_exc()) try: os.symlink(path, dest) except OSError: - raise FilesystemError('Operating system does not support symbolic ' - 'links.', 'link', (path, dest), + raise FilesystemError(u'Operating system does not support symbolic ' + u'links.', 'link', (path, dest), traceback.format_exc()) @@ -619,7 +618,7 @@ def legalize_path(path, replacements, length, extension, fragment): def str2bool(value): """Returns a boolean reflecting a human-entered string.""" - return value.lower() in ('yes', '1', 'true', 't', 'y') + return value.lower() in (u'yes', u'1', u'true', u't', u'y') def as_string(value): @@ -643,7 +642,7 @@ def plurality(objs): """ c = Counter(objs) if not c: - raise ValueError('sequence must be non-empty') + raise ValueError(u'sequence must be non-empty') return c.most_common(1)[0] @@ -766,7 +765,7 @@ def shlex_split(s): return [c.decode('utf8') for c in shlex.split(bs)] else: - raise TypeError('shlex_split called with non-string') + raise TypeError(u'shlex_split called with non-string') def interactive_open(targets, command): @@ -854,8 +853,8 @@ def raw_seconds_short(string): Raises ValueError if the conversion cannot take place due to `string` not being in the right format. """ - match = re.match('^(\d+):([0-5]\d)$', string) + match = re.match(r'^(\d+):([0-5]\d)$', string) if not match: - raise ValueError('String not in M:SS format') + raise ValueError(u'String not in M:SS format') minutes, seconds = map(int, match.groups()) return float(minutes * 60 + seconds) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 1b6a5903e..0fd4253d7 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -16,8 +16,7 @@ """Abstraction layer to resize images using PIL, ImageMagick, or a public resizing proxy if neither is available. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import urllib import subprocess @@ -125,10 +124,10 @@ def im_getsize(path_in): try: out = util.command_output(cmd) except subprocess.CalledProcessError as exc: - log.warn('ImageMagick size query failed') + log.warn(u'ImageMagick size query failed') log.debug( - '`convert` exited with (status {}) when ' - 'getting size with command {}:\n{}', + u'`convert` exited with (status {}) when ' + u'getting size with command {}:\n{}', exc.returncode, cmd, exc.output.strip() ) return diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index e736bab27..96ae6f686 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -7,8 +7,7 @@ asyncore. Bluelet: easy concurrency without all the messy parallelism. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import socket import select @@ -555,7 +554,7 @@ def spawn(coro): and child coroutines run concurrently. """ if not isinstance(coro, types.GeneratorType): - raise ValueError('%s is not a coroutine' % coro) + raise ValueError(u'%s is not a coroutine' % coro) return SpawnEvent(coro) @@ -565,7 +564,7 @@ def call(coro): returns a value using end(), then this event returns that value. """ if not isinstance(coro, types.GeneratorType): - raise ValueError('%s is not a coroutine' % coro) + raise ValueError(u'%s is not a coroutine' % coro) return DelegationEvent(coro) diff --git a/beets/util/confit.py b/beets/util/confit.py index 29b906cb6..e017c7d54 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -15,8 +15,7 @@ """Worry-free YAML configuration files. """ -from __future__ import (unicode_literals, absolute_import, print_function, - division) +from __future__ import (absolute_import, print_function, division) import platform import os @@ -101,17 +100,17 @@ class ConfigReadError(ConfigError): self.filename = filename self.reason = reason - message = 'file {0} could not be read'.format(filename) + message = u'file {0} could not be read'.format(filename) if isinstance(reason, yaml.scanner.ScannerError) and \ reason.problem == YAML_TAB_PROBLEM: # Special-case error message for tab indentation in YAML markup. - message += ': found tab character at line {0}, column {1}'.format( + message += u': found tab character at line {0}, column {1}'.format( reason.problem_mark.line + 1, reason.problem_mark.column + 1, ) elif reason: # Generic error message uses exception's message. - message += ': {0}'.format(reason) + message += u': {0}'.format(reason) super(ConfigReadError, self).__init__(message) @@ -125,7 +124,7 @@ class ConfigSource(dict): def __init__(self, value, filename=None, default=False): super(ConfigSource, self).__init__(value) if filename is not None and not isinstance(filename, BASESTRING): - raise TypeError('filename must be a string or None') + raise TypeError(u'filename must be a string or None') self.filename = filename self.default = default @@ -147,7 +146,7 @@ class ConfigSource(dict): elif isinstance(value, dict): return ConfigSource(value) else: - raise TypeError('source value must be a dict') + raise TypeError(u'source value must be a dict') class ConfigView(object): @@ -182,7 +181,7 @@ class ConfigView(object): try: return iter_first(pairs) except ValueError: - raise NotFoundError("{0} not found".format(self.name)) + raise NotFoundError(u"{0} not found".format(self.name)) def exists(self): """Determine whether the view has a setting in any source. @@ -213,7 +212,7 @@ class ConfigView(object): raise NotImplementedError def __repr__(self): - return '<{}: {}>'.format(self.__class__.__name__, self.name) + return u'<{}: {}>'.format(self.__class__.__name__, self.name) def __iter__(self): """Iterate over the keys of a dictionary view or the *subviews* @@ -230,7 +229,7 @@ class ConfigView(object): collection = self.get() if not isinstance(collection, (list, tuple)): raise ConfigTypeError( - '{0} must be a dictionary or a list, not {1}'.format( + u'{0} must be a dictionary or a list, not {1}'.format( self.name, type(collection).__name__ ) ) @@ -308,7 +307,7 @@ class ConfigView(object): cur_keys = dic.keys() except AttributeError: raise ConfigTypeError( - '{0} must be a dict, not {1}'.format( + u'{0} must be a dict, not {1}'.format( self.name, type(dic).__name__ ) ) @@ -349,7 +348,7 @@ class ConfigView(object): it = iter(collection) except TypeError: raise ConfigTypeError( - '{0} must be an iterable, not {1}'.format( + u'{0} must be an iterable, not {1}'.format( self.name, type(collection).__name__ ) ) @@ -489,7 +488,7 @@ class Subview(ConfigView): if not isinstance(self.key, int): self.name += '.' if isinstance(self.key, int): - self.name += '#{0}'.format(self.key) + self.name += u'#{0}'.format(self.key) elif isinstance(self.key, BASESTRING): if isinstance(self.key, bytes): self.name += self.key.decode('utf8') @@ -511,7 +510,7 @@ class Subview(ConfigView): except TypeError: # Not subscriptable. raise ConfigTypeError( - "{0} must be a collection, not {1}".format( + u"{0} must be a collection, not {1}".format( self.parent.name, type(collection).__name__ ) ) @@ -621,7 +620,7 @@ class Loader(yaml.SafeLoader): else: raise yaml.constructor.ConstructorError( None, None, - 'expected a mapping node, but found %s' % node.id, + u'expected a mapping node, but found %s' % node.id, node.start_mark ) @@ -632,7 +631,7 @@ class Loader(yaml.SafeLoader): hash(key) except TypeError as exc: raise yaml.constructor.ConstructorError( - 'while constructing a mapping', + u'while constructing a mapping', node.start_mark, 'found unacceptable key (%s)' % exc, key_node.start_mark ) @@ -710,9 +709,9 @@ class Dumper(yaml.SafeDumper): """Represent bool as 'yes' or 'no' instead of 'true' or 'false'. """ if data: - value = 'yes' + value = u'yes' else: - value = 'no' + value = u'no' return self.represent_scalar('tag:yaml.org,2002:bool', value) def represent_none(self, data): @@ -837,7 +836,7 @@ class Configuration(RootView): appdir = os.environ[self._env_var] appdir = os.path.abspath(os.path.expanduser(appdir)) if os.path.isfile(appdir): - raise ConfigError('{0} must be a directory'.format( + raise ConfigError(u'{0} must be a directory'.format( self._env_var )) @@ -990,7 +989,7 @@ class Template(object): return self.convert(value, view) elif self.default is REQUIRED: # Missing required value. This is an error. - raise NotFoundError("{0} not found".format(view.name)) + raise NotFoundError(u"{0} not found".format(view.name)) else: # Missing value, but not required. return self.default @@ -1015,11 +1014,11 @@ class Template(object): """ exc_class = ConfigTypeError if type_error else ConfigValueError raise exc_class( - '{0}: {1}'.format(view.name, message) + u'{0}: {1}'.format(view.name, message) ) def __repr__(self): - return '{0}({1})'.format( + return u'{0}({1})'.format( type(self).__name__, '' if self.default is REQUIRED else repr(self.default), ) @@ -1036,7 +1035,7 @@ class Integer(Template): elif isinstance(value, float): return int(value) else: - self.fail('must be a number', view, True) + self.fail(u'must be a number', view, True) class Number(Template): @@ -1049,7 +1048,7 @@ class Number(Template): return value else: self.fail( - 'must be numeric, not {0}'.format(type(value).__name__), + u'must be numeric, not {0}'.format(type(value).__name__), view, True ) @@ -1111,12 +1110,12 @@ class String(Template): if isinstance(value, BASESTRING): if self.pattern and not self.regex.match(value): self.fail( - "must match the pattern {0}".format(self.pattern), + u"must match the pattern {0}".format(self.pattern), view ) return value else: - self.fail('must be a string', view, True) + self.fail(u'must be a string', view, True) class Choice(Template): @@ -1137,7 +1136,7 @@ class Choice(Template): """ if value not in self.choices: self.fail( - 'must be one of {0}, not {1}'.format( + u'must be one of {0}, not {1}'.format( repr(list(self.choices)), repr(value) ), view @@ -1206,7 +1205,7 @@ class OneOf(Template): raise ConfigTemplateError(exc) self.fail( - 'must be one of {0}, not {1}'.format( + u'must be one of {0}, not {1}'.format( repr(self.allowed), repr(value) ), view @@ -1242,7 +1241,7 @@ class StrSeq(Template): try: value = list(value) except TypeError: - self.fail('must be a whitespace-separated string or a list', + self.fail(u'must be a whitespace-separated string or a list', view, True) def convert(x): @@ -1251,7 +1250,7 @@ class StrSeq(Template): elif isinstance(x, bytes): return x.decode('utf8', 'ignore') else: - self.fail('must be a list of strings', view, True) + self.fail(u'must be a list of strings', view, True) return list(map(convert, value)) @@ -1301,19 +1300,19 @@ class Filename(Template): if not isinstance(template, (collections.Mapping, MappingTemplate)): # disallow config.get(Filename(relative_to='foo')) raise ConfigTemplateError( - 'relative_to may only be used when getting multiple values.' + u'relative_to may only be used when getting multiple values.' ) elif self.relative_to == view.key: raise ConfigTemplateError( - '{0} is relative to itself'.format(view.name) + u'{0} is relative to itself'.format(view.name) ) elif self.relative_to not in view.parent.keys(): # self.relative_to is not in the config self.fail( ( - 'needs sibling value "{0}" to expand relative path' + u'needs sibling value "{0}" to expand relative path' ).format(self.relative_to), view ) @@ -1335,12 +1334,12 @@ class Filename(Template): if next_relative in template.subtemplates: # we encountered this config key previously raise ConfigTemplateError(( - '{0} and {1} are recursively relative' + u'{0} and {1} are recursively relative' ).format(view.name, self.relative_to)) else: raise ConfigTemplateError(( - 'missing template for {0}, needed to expand {1}\'s' + - 'relative path' + u'missing template for {0}, needed to expand {1}\'s' + + u'relative path' ).format(self.relative_to, view.name)) next_template.subtemplates[next_relative] = rel_to_template @@ -1352,7 +1351,7 @@ class Filename(Template): path, source = view.first() if not isinstance(path, BASESTRING): self.fail( - 'must be a filename, not {0}'.format(type(path).__name__), + u'must be a filename, not {0}'.format(type(path).__name__), view, True ) @@ -1390,7 +1389,7 @@ class TypeTemplate(Template): def convert(self, value, view): if not isinstance(value, self.typ): self.fail( - 'must be a {0}, not {1}'.format( + u'must be a {0}, not {1}'.format( self.typ.__name__, type(value).__name__, ), @@ -1444,4 +1443,4 @@ def as_template(value): elif isinstance(value, type): return TypeTemplate(value) else: - raise ValueError('cannot convert to template: {0!r}'.format(value)) + raise ValueError(u'cannot convert to template: {0!r}'.format(value)) diff --git a/beets/util/enumeration.py b/beets/util/enumeration.py index 9dddf7f64..eb202b6d4 100644 --- a/beets/util/enumeration.py +++ b/beets/util/enumeration.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from enum import Enum diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 68cb4cd76..303338b4c 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -27,8 +27,7 @@ This is sort of like a tiny, horrible degeneration of a real templating engine like Jinja2 or Mustache. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re import ast @@ -79,7 +78,7 @@ def ex_literal(val): return ast.Name(bytes(val), ast.Load()) elif isinstance(val, basestring): return ast.Str(val) - raise TypeError('no literal for {0}'.format(type(val))) + raise TypeError(u'no literal for {0}'.format(type(val))) def ex_varassign(name, expr): @@ -571,4 +570,4 @@ if __name__ == b'__main__': 'from __main__ import _tmpl, _vars, _funcs', number=10000) print(comp_time) - print('Speedup:', interp_time / comp_time) + print(u'Speedup:', interp_time / comp_time) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index deb431fa1..666909af2 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -32,8 +32,7 @@ To do so, pass an iterable of coroutines to the Pipeline constructor in place of any single coroutine. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import Queue from threading import Thread, Lock @@ -362,7 +361,7 @@ class Pipeline(object): be at least two stages. """ if len(stages) < 2: - raise ValueError('pipeline must have at least two stages') + raise ValueError(u'pipeline must have at least two stages') self.stages = [] for stage in stages: if isinstance(stage, (list, tuple)): @@ -467,14 +466,14 @@ if __name__ == b'__main__': # in parallel. def produce(): for i in range(5): - print('generating %i' % i) + print(u'generating %i' % i) time.sleep(1) yield i def work(): num = yield while True: - print('processing %i' % num) + print(u'processing %i' % num) time.sleep(2) num = yield num * 2 @@ -482,7 +481,7 @@ if __name__ == b'__main__': while True: num = yield time.sleep(1) - print('received %i' % num) + print(u'received %i' % num) ts_start = time.time() Pipeline([produce(), work(), consume()]).run_sequential() @@ -491,22 +490,22 @@ if __name__ == b'__main__': ts_par = time.time() Pipeline([produce(), (work(), work()), consume()]).run_parallel() ts_end = time.time() - print('Sequential time:', ts_seq - ts_start) - print('Parallel time:', ts_par - ts_seq) - print('Multiply-parallel time:', ts_end - ts_par) + print(u'Sequential time:', ts_seq - ts_start) + print(u'Parallel time:', ts_par - ts_seq) + print(u'Multiply-parallel time:', ts_end - ts_par) print() # Test a pipeline that raises an exception. def exc_produce(): for i in range(10): - print('generating %i' % i) + print(u'generating %i' % i) time.sleep(1) yield i def exc_work(): num = yield while True: - print('processing %i' % num) + print(u'processing %i' % num) time.sleep(3) if num == 3: raise Exception() @@ -515,6 +514,6 @@ if __name__ == b'__main__': def exc_consume(): while True: num = yield - print('received %i' % num) + print(u'received %i' % num) Pipeline([exc_produce(), exc_work(), exc_consume()]).run_parallel(1) From 6852ab5472adf8822afef10afc074a5e166d346f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 11:49:10 +0100 Subject: [PATCH 0515/2280] Removed unicode_literals from plugins * acousticbrainz * badfiles * bpm --- beetsplug/acousticbrainz.py | 17 ++++++++--------- beetsplug/badfiles.py | 21 ++++++++++----------- beetsplug/bpm.py | 9 ++++----- 3 files changed, 22 insertions(+), 25 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 49f01ea21..d4b5aa9b4 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -15,8 +15,7 @@ """Fetch various AcousticBrainz metadata using MBID. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import requests import operator @@ -38,7 +37,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def commands(self): cmd = ui.Subcommand('acousticbrainz', - help="fetch metadata from AcousticBrainz") + help=u"fetch metadata from AcousticBrainz") def func(lib, opts, args): items = lib.items(ui.decargs(args)) @@ -63,24 +62,24 @@ def fetch_info(log, items, write): try: return reduce(operator.getitem, map_path, data) except KeyError: - log.debug('Invalid Path: {}', map_path) + log.debug(u'Invalid Path: {}', map_path) for item in items: if item.mb_trackid: - log.info('getting data for: {}', item) + log.info(u'getting data for: {}', item) # Fetch the data from the AB API. urls = [generate_url(item.mb_trackid, path) for path in LEVELS] - log.debug('fetching URLs: {}', ' '.join(urls)) + log.debug(u'fetching URLs: {}', ' '.join(urls)) try: res = [requests.get(url) for url in urls] except requests.RequestException as exc: - log.info('request error: {}', exc) + log.info(u'request error: {}', exc) continue # Check for missing tracks. if any(r.status_code == 404 for r in res): - log.info('recording ID {} not found', item.mb_trackid) + log.info(u'recording ID {} not found', item.mb_trackid) continue # Parse the JSON response. @@ -88,7 +87,7 @@ def fetch_info(log, items, write): data = res[0].json() data.update(res[1].json()) except ValueError: - log.debug('Invalid Response: {} & {}', [r.text for r in res]) + log.debug(u'Invalid Response: {} & {}', [r.text for r in res]) # Get each field and assign it on the item. item.danceable = get_value( diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index c6877205c..43df51cce 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -16,8 +16,7 @@ """Use command-line tools to check for audio file corruption. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.ui import Subcommand @@ -32,7 +31,7 @@ import sys class BadFiles(BeetsPlugin): def run_command(self, cmd): - self._log.debug("running command: {}", + self._log.debug(u"running command: {}", displayable_path(list2cmdline(cmd))) try: output = check_output(cmd, stderr=STDOUT) @@ -44,7 +43,7 @@ class BadFiles(BeetsPlugin): status = e.returncode except OSError as e: if e.errno == errno.ENOENT: - ui.print_("command not found: {}".format(cmd[0])) + ui.print_(u"command not found: {}".format(cmd[0])) sys.exit(1) else: raise @@ -87,9 +86,9 @@ class BadFiles(BeetsPlugin): # First, check whether the path exists. If not, the user # should probably run `beet update` to cleanup your library. dpath = displayable_path(item.path) - self._log.debug("checking path: {}", dpath) + self._log.debug(u"checking path: {}", dpath) if not os.path.exists(item.path): - ui.print_("{}: file does not exist".format( + ui.print_(u"{}: file does not exist".format( ui.colorize('text_error', dpath))) # Run the checker against the file if one is found @@ -102,20 +101,20 @@ class BadFiles(BeetsPlugin): path = item.path.decode(sys.getfilesystemencoding()) status, errors, output = checker(path) if status > 0: - ui.print_("{}: checker exited withs status {}" + ui.print_(u"{}: checker exited withs status {}" .format(ui.colorize('text_error', dpath), status)) for line in output: ui.print_(" {}".format(displayable_path(line))) elif errors > 0: - ui.print_("{}: checker found {} errors or warnings" + ui.print_(u"{}: checker found {} errors or warnings" .format(ui.colorize('text_warning', dpath), errors)) for line in output: - ui.print_(" {}".format(displayable_path(line))) + ui.print_(u" {}".format(displayable_path(line))) else: - ui.print_("{}: ok".format(ui.colorize('text_success', dpath))) + ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath))) def commands(self): bad_command = Subcommand('bad', - help='check for corrupt or missing files') + help=u'check for corrupt or missing files') bad_command.func = self.check_bad return [bad_command] diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index e0fc7f4f8..65ebc0712 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -15,8 +15,7 @@ """Determine BPM by pressing a key to the rhythm.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import time @@ -59,8 +58,8 @@ class BPMPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('bpm', - help='determine bpm of a song by pressing \ - a key to the rhythm') + help=u'determine bpm of a song by pressing ' + u'a key to the rhythm') cmd.func = self.command return [cmd] @@ -70,7 +69,7 @@ class BPMPlugin(BeetsPlugin): def get_bpm(self, items, write=False): overwrite = self.config['overwrite'].get(bool) if len(items) > 1: - raise ValueError('Can only get bpm of one song at time') + raise ValueError(u'Can only get bpm of one song at time') item = items[0] if item['bpm']: From 5db57bdc019e838609595ea3dd20a4b26ba50b4c Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 11:56:19 +0100 Subject: [PATCH 0516/2280] Removed unicode_literals from plugin bpd --- beetsplug/bpd/__init__.py | 23 +++++++++++------------ beetsplug/bpd/gstplayer.py | 5 ++--- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 7e8694bac..a475cf178 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -18,8 +18,7 @@ Beets library. Attempts to implement a compatible protocol to allow use of the wide range of MPD clients. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re from string import Template @@ -124,9 +123,9 @@ def make_bpd_error(s_code, s_message): pass return NewBPDError -ArgumentTypeError = make_bpd_error(ERROR_ARG, 'invalid type for argument') -ArgumentIndexError = make_bpd_error(ERROR_ARG, 'argument out of range') -ArgumentNotFoundError = make_bpd_error(ERROR_NO_EXIST, 'argument not found') +ArgumentTypeError = make_bpd_error(ERROR_ARG, u'invalid type for argument') +ArgumentIndexError = make_bpd_error(ERROR_ARG, u'argument out of range') +ArgumentNotFoundError = make_bpd_error(ERROR_NO_EXIST, u'argument not found') def cast_arg(t, val): @@ -269,7 +268,7 @@ class BaseServer(object): conn.authenticated = True else: conn.authenticated = False - raise BPDError(ERROR_PASSWORD, 'incorrect password') + raise BPDError(ERROR_PASSWORD, u'incorrect password') def cmd_commands(self, conn): """Lists the commands available to the user.""" @@ -807,9 +806,9 @@ class Server(BaseServer): """ # Path is ignored. Also, the real MPD does this asynchronously; # this is done inline. - print('Building directory tree...') + print(u'Building directory tree...') self.tree = vfs.libtree(self.lib) - print('... done.') + print(u'... done.') self.updated_time = time.time() # Path (directory tree) browsing. @@ -848,7 +847,7 @@ class Server(BaseServer): node = self._resolve_path(path) if isinstance(node, int): # Trying to list a track. - raise BPDError(ERROR_ARG, 'this is not a directory') + raise BPDError(ERROR_ARG, u'this is not a directory') else: for name, itemid in iter(sorted(node.files.items())): item = self.lib.get_item(itemid) @@ -1173,18 +1172,18 @@ class BPDPlugin(BeetsPlugin): def commands(self): cmd = beets.ui.Subcommand( - 'bpd', help='run an MPD-compatible music player server' + 'bpd', help=u'run an MPD-compatible music player server' ) cmd.parser.add_option( '-d', '--debug', action='store_true', - help='dump all MPD traffic to stdout' + help=u'dump all MPD traffic to stdout' ) def func(lib, opts, args): host = args.pop(0) if args else self.config['host'].get(unicode) port = args.pop(0) if args else self.config['port'].get(int) if args: - raise beets.ui.UserError('too many arguments') + raise beets.ui.UserError(u'too many arguments') password = self.config['password'].get(unicode) volume = self.config['volume'].get(int) debug = opts.debug or False diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index fa22b999d..e430f88ff 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -17,8 +17,7 @@ music player. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import sys import time @@ -91,7 +90,7 @@ class GstPlayer(object): # error self.player.set_state(gst.STATE_NULL) err, debug = message.parse_error() - print("Error: {0}".format(err)) + print(u"Error: {0}".format(err)) self.playing = False def _set_volume(self, volume): From 40900aa1cb61de5ab8aae9bf0d584da48b325cb6 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 12:10:01 +0100 Subject: [PATCH 0517/2280] Removed unicode_literals from plugins * bucket * chroma * convert * discogs --- beetsplug/bucket.py | 19 +++++++++---------- beetsplug/chroma.py | 9 ++++----- beetsplug/convert.py | 23 +++++++++++------------ beetsplug/discogs.py | 23 +++++++++++------------ 4 files changed, 35 insertions(+), 39 deletions(-) diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index 7ddc90920..b847cf03c 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -16,8 +16,7 @@ """Provides the %bucket{} function for path formatting. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from datetime import datetime import re @@ -46,7 +45,7 @@ def span_from_str(span_str): """Convert string to a 4 digits year """ if yearfrom < 100: - raise BucketError("%d must be expressed on 4 digits" % yearfrom) + raise BucketError(u"%d must be expressed on 4 digits" % yearfrom) # if two digits only, pick closest year that ends by these two # digits starting from yearfrom @@ -59,12 +58,12 @@ def span_from_str(span_str): years = [int(x) for x in re.findall('\d+', span_str)] if not years: - raise ui.UserError("invalid range defined for year bucket '%s': no " - "year found" % span_str) + raise ui.UserError(u"invalid range defined for year bucket '%s': no " + u"year found" % span_str) try: years = [normalize_year(x, years[0]) for x in years] except BucketError as exc: - raise ui.UserError("invalid range defined for year bucket '%s': %s" % + raise ui.UserError(u"invalid range defined for year bucket '%s': %s" % (span_str, exc)) res = {'from': years[0], 'str': span_str} @@ -119,8 +118,8 @@ def build_year_spans(year_spans_str): def str2fmt(s): """Deduces formatting syntax from a span string. """ - regex = re.compile("(?P\D*)(?P\d+)(?P\D*)" - "(?P\d*)(?P\D*)") + regex = re.compile(r"(?P\D*)(?P\d+)(?P\D*)" + r"(?P\d*)(?P\D*)") m = re.match(regex, s) res = {'fromnchars': len(m.group('fromyear')), @@ -166,8 +165,8 @@ def build_alpha_spans(alpha_spans_str, alpha_regexs): beginIdx = ASCII_DIGITS.index(bucket[0]) endIdx = ASCII_DIGITS.index(bucket[-1]) else: - raise ui.UserError("invalid range defined for alpha bucket " - "'%s': no alphanumeric character found" % + raise ui.UserError(u"invalid range defined for alpha bucket " + u"'%s': no alphanumeric character found" % elem) spans.append( re.compile( diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index cb0eaf24a..e40b2d29f 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -16,8 +16,7 @@ """Adds Chromaprint/Acoustid acoustic fingerprinting support to the autotagger. Requires the pyacoustid library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets import plugins from beets import ui @@ -178,19 +177,19 @@ class AcoustidPlugin(plugins.BeetsPlugin): def commands(self): submit_cmd = ui.Subcommand('submit', - help='submit Acoustid fingerprints') + help=u'submit Acoustid fingerprints') def submit_cmd_func(lib, opts, args): try: apikey = config['acoustid']['apikey'].get(unicode) except confit.NotFoundError: - raise ui.UserError('no Acoustid user API key provided') + raise ui.UserError(u'no Acoustid user API key provided') submit_items(self._log, apikey, lib.items(ui.decargs(args))) submit_cmd.func = submit_cmd_func fingerprint_cmd = ui.Subcommand( 'fingerprint', - help='generate fingerprints for items without them' + help=u'generate fingerprints for items without them' ) def fingerprint_cmd_func(lib, opts, args): diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 6145fdb74..0329f2a52 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -15,8 +15,7 @@ """Converts tracks or albums to external directory """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import threading @@ -138,21 +137,21 @@ class ConvertPlugin(BeetsPlugin): self.register_listener('import_task_files', self._cleanup) def commands(self): - cmd = ui.Subcommand('convert', help='convert to external location') + cmd = ui.Subcommand('convert', help=u'convert to external location') cmd.parser.add_option('-p', '--pretend', action='store_true', - help='show actions but do nothing') + help=u'show actions but do nothing') cmd.parser.add_option('-t', '--threads', action='store', type='int', - help='change the number of threads, \ + help=u'change the number of threads, \ defaults to maximum available processors') cmd.parser.add_option('-k', '--keep-new', action='store_true', - dest='keep_new', help='keep only the converted \ + dest='keep_new', help=u'keep only the converted \ and move the old files') cmd.parser.add_option('-d', '--dest', action='store', - help='set the destination directory') + help=u'set the destination directory') cmd.parser.add_option('-f', '--format', action='store', dest='format', - help='set the target format of the tracks') + help=u'set the target format of the tracks') cmd.parser.add_option('-y', '--yes', action='store_true', dest='yes', - help='do not ask for confirmation') + help=u'do not ask for confirmation') cmd.parser.add_album_option() cmd.func = self.convert_func return [cmd] @@ -292,7 +291,7 @@ class ConvertPlugin(BeetsPlugin): if self.config['embed']: album = item.get_album() if album and album.artpath: - self._log.debug('embedding album art from {}', + self._log.debug(u'embedding album art from {}', util.displayable_path(album.artpath)) art.embed_item(self._log, item, album.artpath, itempath=converted) @@ -349,7 +348,7 @@ class ConvertPlugin(BeetsPlugin): if not opts.dest: opts.dest = self.config['dest'].get() if not opts.dest: - raise ui.UserError('no convert destination set') + raise ui.UserError(u'no convert destination set') opts.dest = util.bytestring_path(opts.dest) if not opts.threads: @@ -369,7 +368,7 @@ class ConvertPlugin(BeetsPlugin): if not pretend: ui.commands.list_items(lib, ui.decargs(args), opts.album) - if not (opts.yes or ui.input_yn("Convert? (Y/n)")): + if not (opts.yes or ui.input_yn(u"Convert? (Y/n)")): return if opts.album: diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 321fbd09e..26c567a2c 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -16,8 +16,7 @@ """Adds Discogs album search support to the autotagger. Requires the discogs-client library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import beets.ui from beets import logging @@ -101,24 +100,24 @@ class DiscogsPlugin(BeetsPlugin): try: _, _, url = auth_client.get_authorize_url() except CONNECTION_ERRORS as e: - self._log.debug('connection error: {0}', e) - raise beets.ui.UserError('communication with Discogs failed') + self._log.debug(u'connection error: {0}', e) + raise beets.ui.UserError(u'communication with Discogs failed') - beets.ui.print_("To authenticate with Discogs, visit:") + beets.ui.print_(u"To authenticate with Discogs, visit:") beets.ui.print_(url) # Ask for the code and validate it. - code = beets.ui.input_("Enter the code:") + code = beets.ui.input_(u"Enter the code:") try: token, secret = auth_client.get_access_token(code) except DiscogsAPIError: - raise beets.ui.UserError('Discogs authorization failed') + raise beets.ui.UserError(u'Discogs authorization failed') except CONNECTION_ERRORS as e: self._log.debug(u'connection error: {0}', e) - raise beets.ui.UserError('Discogs token request failed') + raise beets.ui.UserError(u'Discogs token request failed') # Save the token for later use. - self._log.debug('Discogs token {0}, secret {1}', token, secret) + self._log.debug(u'Discogs token {0}, secret {1}', token, secret) with open(self._tokenfile(), 'w') as f: json.dump({'token': token, 'secret': secret}, f) @@ -153,7 +152,7 @@ class DiscogsPlugin(BeetsPlugin): else: return [] except CONNECTION_ERRORS: - self._log.debug('Connection error in album search', exc_info=True) + self._log.debug(u'Connection error in album search', exc_info=True) return [] def album_for_id(self, album_id): @@ -184,7 +183,7 @@ class DiscogsPlugin(BeetsPlugin): return self.album_for_id(album_id) return None except CONNECTION_ERRORS: - self._log.debug('Connection error in album lookup', exc_info=True) + self._log.debug(u'Connection error in album lookup', exc_info=True) return None return self.get_album_info(result) @@ -206,7 +205,7 @@ class DiscogsPlugin(BeetsPlugin): releases = self.discogs_client.search(query, type='release').page(1) except CONNECTION_ERRORS: - self._log.debug("Communication error while searching for {0!r}", + self._log.debug(u"Communication error while searching for {0!r}", query, exc_info=True) return [] return [self.get_album_info(release) for release in releases[:5]] From 5547a828487235e727922d1c5c669816bcb7dc75 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 13:26:27 +0100 Subject: [PATCH 0518/2280] Removed unicode_literals from plugin duplicates --- beetsplug/duplicates.py | 95 ++++++++++++++++++++++------------------- 1 file changed, 50 insertions(+), 45 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 3a04557ca..b3ee90742 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -15,8 +15,7 @@ """List duplicate tracks or albums. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import shlex @@ -54,51 +53,56 @@ class DuplicatesPlugin(BeetsPlugin): self._command = Subcommand('duplicates', help=__doc__, aliases=['dup']) - self._command.parser.add_option('-c', '--count', dest='count', - action='store_true', - help='show duplicate counts') + self._command.parser.add_option( + u'-c', u'--count', dest='count', + action='store_true', + help=u'show duplicate counts') - self._command.parser.add_option('-C', '--checksum', dest='checksum', - action='store', metavar='PROG', - help='report duplicates based on' - ' arbitrary command') + self._command.parser.add_option( + u'-C', u'--checksum', dest='checksum', + action='store', metavar='PROG', + help=u'report duplicates based on arbitrary command') - self._command.parser.add_option('-d', '--delete', dest='delete', - action='store_true', - help='delete items from library and ' - 'disk') + self._command.parser.add_option( + u'-d', u'--delete', dest='delete', + action='store_true', + help=u'delete items from library and disk') - self._command.parser.add_option('-F', '--full', dest='full', - action='store_true', - help='show all versions of duplicate' - ' tracks or albums') + self._command.parser.add_option( + u'-F', u'--full', dest='full', + action='store_true', + help=u'show all versions of duplicate tracks or albums') - self._command.parser.add_option('-s', '--strict', dest='strict', - action='store_true', - help='report duplicates only if all' - ' attributes are set') + self._command.parser.add_option( + u'-s', u'--strict', dest='strict', + action='store_true', + help=u'report duplicates only if all attributes are set') - self._command.parser.add_option('-k', '--keys', dest='keys', - action='callback', metavar='KEY1 KEY2', - callback=vararg_callback, - help='report duplicates based on keys') + self._command.parser.add_option( + u'-k', u'--keys', dest='keys', + action='callback', metavar='KEY1 KEY2', + callback=vararg_callback, + help=u'report duplicates based on keys') - self._command.parser.add_option('-M', '--merge', dest='merge', - action='store_true', - help='merge duplicate items') + self._command.parser.add_option( + u'-M', u'--merge', dest='merge', + action='store_true', + help=u'merge duplicate items') - self._command.parser.add_option('-m', '--move', dest='move', - action='store', metavar='DEST', - help='move items to dest') + self._command.parser.add_option( + u'-m', u'--move', dest='move', + action='store', metavar='DEST', + help=u'move items to dest') - self._command.parser.add_option('-o', '--copy', dest='copy', - action='store', metavar='DEST', - help='copy items to dest') + self._command.parser.add_option( + u'-o', u'--copy', dest='copy', + action='store', metavar='DEST', + help=u'copy items to dest') - self._command.parser.add_option('-t', '--tag', dest='tag', - action='store', - help='tag matched items with \'k=v\'' - ' attribute') + self._command.parser.add_option( + u'-t', u'--tag', dest='tag', + action='store', + help=u'tag matched items with \'k=v\' attribute') self._command.parser.add_all_common_options() @@ -181,7 +185,8 @@ class DuplicatesPlugin(BeetsPlugin): try: k, v = tag.split('=') except: - raise UserError('%s: can\'t parse k=v tag: %s' % (PLUGIN, tag)) + raise UserError( + u'%s: can\'t parse k=v tag: %s' % (PLUGIN, tag)) setattr(item, k, v) item.store() @@ -195,7 +200,7 @@ class DuplicatesPlugin(BeetsPlugin): checksum = getattr(item, key, False) if not checksum: self._log.debug(u'key {0} on item {1} not cached:' - 'computing checksum', + u'computing checksum', key, displayable_path(item.path)) try: checksum = command_output(args) @@ -208,7 +213,7 @@ class DuplicatesPlugin(BeetsPlugin): displayable_path(item.path), e) else: self._log.debug(u'key {0} on item {1} cached:' - 'not computing checksum', + u'not computing checksum', key, displayable_path(item.path)) return key, checksum @@ -225,11 +230,11 @@ class DuplicatesPlugin(BeetsPlugin): values = [v for v in values if v not in (None, '')] if strict and len(values) < len(keys): self._log.debug(u'some keys {0} on item {1} are null or empty:' - ' skipping', + u' skipping', keys, displayable_path(obj.path)) elif (not strict and not len(values)): self._log.debug(u'all keys {0} on item {1} are null or empty:' - ' skipping', + u' skipping', keys, displayable_path(obj.path)) else: key = tuple(values) @@ -279,7 +284,7 @@ class DuplicatesPlugin(BeetsPlugin): value = getattr(o, f, None) if value: self._log.debug(u'key {0} on item {1} is null ' - 'or empty: setting from item {2}', + u'or empty: setting from item {2}', f, displayable_path(objs[0].path), displayable_path(o.path)) setattr(objs[0], f, value) @@ -300,7 +305,7 @@ class DuplicatesPlugin(BeetsPlugin): missing.album_id = objs[0].id missing.add(i._db) self._log.debug(u'item {0} missing from album {1}:' - ' merging from {2} into {3}', + u' merging from {2} into {3}', missing, objs[0], displayable_path(o.path), From 53d2c8d9db87be4d4750ad879bf46176537be73f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 13:35:54 +0100 Subject: [PATCH 0519/2280] Removed unicode_literals from plugins * echonest * edit * embedart * embyupdate --- beetsplug/echonest.py | 16 ++++++++-------- beetsplug/edit.py | 41 ++++++++++++++++++++--------------------- beetsplug/embedart.py | 41 +++++++++++++++++++++-------------------- beetsplug/embyupdate.py | 5 ++--- 4 files changed, 51 insertions(+), 52 deletions(-) diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index 182c7f9a2..f758b5862 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -15,8 +15,7 @@ """Fetch a variety of acoustic metrics from The Echo Nest. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import time import socket @@ -465,10 +464,11 @@ class EchonestMetadataPlugin(plugins.BeetsPlugin): def commands(self): fetch_cmd = ui.Subcommand('echonest', - help='fetch metadata from The Echo Nest') + help=u'fetch metadata from The Echo Nest') fetch_cmd.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='(re-)download information from the EchoNest' + u'-f', u'--force', dest='force', + action='store_true', default=False, + help=u'(re-)download information from the EchoNest' ) def fetch_func(lib, opts, args): @@ -483,10 +483,10 @@ class EchonestMetadataPlugin(plugins.BeetsPlugin): fetch_cmd.func = fetch_func - sim_cmd = ui.Subcommand('echosim', help='show related files') + sim_cmd = ui.Subcommand('echosim', help=u'show related files') sim_cmd.parser.add_option( - '-t', '--threshold', dest='threshold', action='store', - type='float', default=0.15, help='Set difference threshold' + u'-t', u'--threshold', dest='threshold', action='store', + type='float', default=0.15, help=u'Set difference threshold' ) sim_cmd.parser.add_format_option() diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 29676fa08..d0e31d478 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -14,8 +14,7 @@ """Open metadata information in a text editor to let the user edit it. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets import plugins from beets import util @@ -68,7 +67,7 @@ def load(s): for d in yaml.load_all(s): if not isinstance(d, dict): raise ParseError( - 'each entry must be a dictionary; found {}'.format( + u'each entry must be a dictionary; found {}'.format( type(d).__name__ ) ) @@ -78,7 +77,7 @@ def load(s): out.append({unicode(k): v for k, v in d.items()}) except yaml.YAMLError as e: - raise ParseError('invalid YAML: {}'.format(e)) + raise ParseError(u'invalid YAML: {}'.format(e)) return out @@ -154,18 +153,18 @@ class EditPlugin(plugins.BeetsPlugin): def commands(self): edit_command = ui.Subcommand( 'edit', - help='interactively edit metadata' + help=u'interactively edit metadata' ) edit_command.parser.add_option( - '-f', '--field', + u'-f', u'--field', metavar='FIELD', action='append', - help='edit this field also', + help=u'edit this field also', ) edit_command.parser.add_option( - '--all', + u'--all', action='store_true', dest='all', - help='edit all fields', + help=u'edit all fields', ) edit_command.parser.add_album_option() edit_command.func = self._edit_command @@ -179,7 +178,7 @@ class EditPlugin(plugins.BeetsPlugin): items, albums = _do_query(lib, query, opts.album, False) objs = albums if opts.album else items if not objs: - ui.print_('Nothing to edit.') + ui.print_(u'Nothing to edit.') return # Get the fields to edit. @@ -248,15 +247,15 @@ class EditPlugin(plugins.BeetsPlugin): with open(new.name) as f: new_str = f.read() if new_str == old_str: - ui.print_("No changes; aborting.") + ui.print_(u"No changes; aborting.") return False # Parse the updated data. try: new_data = load(new_str) except ParseError as e: - ui.print_("Could not read data: {}".format(e)) - if ui.input_yn("Edit again to fix? (Y/n)", True): + ui.print_(u"Could not read data: {}".format(e)) + if ui.input_yn(u"Edit again to fix? (Y/n)", True): continue else: return False @@ -267,18 +266,18 @@ class EditPlugin(plugins.BeetsPlugin): for obj in objs: changed |= ui.show_model_changes(obj) if not changed: - ui.print_('No changes to apply.') + ui.print_(u'No changes to apply.') return False # Confirm the changes. choice = ui.input_options( - ('continue Editing', 'apply', 'cancel') + (u'continue Editing', u'apply', u'cancel') ) - if choice == 'a': # Apply. + if choice == u'a': # Apply. return True - elif choice == 'c': # Cancel. + elif choice == u'c': # Cancel. return False - elif choice == 'e': # Keep editing. + elif choice == u'e': # Keep editing. # Reset the temporary changes to the objects. for obj in objs: obj.read() @@ -296,7 +295,7 @@ class EditPlugin(plugins.BeetsPlugin): are temporary. """ if len(old_data) != len(new_data): - self._log.warn('number of objects changed from {} to {}', + self._log.warn(u'number of objects changed from {} to {}', len(old_data), len(new_data)) obj_by_id = {o.id: o for o in objs} @@ -307,7 +306,7 @@ class EditPlugin(plugins.BeetsPlugin): forbidden = False for key in ignore_fields: if old_dict.get(key) != new_dict.get(key): - self._log.warn('ignoring object whose {} changed', key) + self._log.warn(u'ignoring object whose {} changed', key) forbidden = True break if forbidden: @@ -322,5 +321,5 @@ class EditPlugin(plugins.BeetsPlugin): # Save to the database and possibly write tags. for ob in objs: if ob._dirty: - self._log.debug('saving changes to {}', ob) + self._log.debug(u'saving changes to {}', ob) ob.try_sync(ui.should_write(), ui.should_move()) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index b27964874..07321ce2b 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """Allows beets to embed album art into file metadata.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os.path @@ -56,10 +55,10 @@ class EmbedCoverArtPlugin(BeetsPlugin): def commands(self): # Embed command. embed_cmd = ui.Subcommand( - 'embedart', help='embed image files into file metadata' + 'embedart', help=u'embed image files into file metadata' ) embed_cmd.parser.add_option( - '-f', '--file', metavar='PATH', help='the image file to embed' + u'-f', u'--file', metavar='PATH', help=u'the image file to embed' ) maxwidth = self.config['maxwidth'].get(int) compare_threshold = self.config['compare_threshold'].get(int) @@ -84,17 +83,18 @@ class EmbedCoverArtPlugin(BeetsPlugin): embed_cmd.func = embed_func # Extract command. - extract_cmd = ui.Subcommand('extractart', - help='extract an image from file metadata') - extract_cmd.parser.add_option('-o', dest='outpath', - help='image output file') - extract_cmd.parser.add_option('-n', dest='filename', - help='image filename to create for all ' - 'matched albums') - extract_cmd.parser.add_option('-a', dest='associate', - action='store_true', - help='associate the extracted images ' - 'with the album') + extract_cmd = ui.Subcommand( + 'extractart', + help=u'extract an image from file metadata') + extract_cmd.parser.add_option( + u'-o', dest='outpath', + help=u'image output file') + extract_cmd.parser.add_option( + u'-n', dest='filename', + help=u'image filename to create for all matched albums') + extract_cmd.parser.add_option( + '-a', dest='associate', action='store_true', + help='associate the extracted images with the album') def extract_func(lib, opts, args): if opts.outpath: @@ -104,8 +104,8 @@ class EmbedCoverArtPlugin(BeetsPlugin): filename = bytestring_path(opts.filename or config['art_filename'].get()) if os.path.dirname(filename) != '': - self._log.error(u"Only specify a name rather than a path " - u"for -n") + self._log.error( + u"Only specify a name rather than a path for -n") return for album in lib.albums(decargs(args)): artpath = normpath(os.path.join(album.path, filename)) @@ -117,8 +117,9 @@ class EmbedCoverArtPlugin(BeetsPlugin): extract_cmd.func = extract_func # Clear command. - clear_cmd = ui.Subcommand('clearart', - help='remove images from file metadata') + clear_cmd = ui.Subcommand( + 'clearart', + help=u'remove images from file metadata') def clear_func(lib, opts, args): art.clear(self._log, lib, decargs(args)) @@ -142,7 +143,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): """ if self.config['remove_art_file'] and album.artpath: if os.path.isfile(album.artpath): - self._log.debug('Removing album art file for {0}', album) + self._log.debug(u'Removing album art file for {0}', album) os.remove(album.artpath) album.artpath = None album.store() diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 3953afe2c..a4db3a3c7 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -8,8 +8,7 @@ username: user password: password """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets import config from beets.plugins import BeetsPlugin @@ -120,7 +119,7 @@ class EmbyUpdate(BeetsPlugin): token = get_token(host, port, headers, auth_data) if not token: self._log.warning( - u'Couldnt not get token for user {0}'.format(username)) + u'Could not get token for user {0}'.format(username)) return # Recreate headers with a token. From 7d00ab3b50cc29719e4acd608aee27f0ce60f65d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 13:44:45 +0100 Subject: [PATCH 0520/2280] Removed unicode_literals from plugins * fetchart * freedesktop * fromfilename * ftintitle --- beetsplug/fetchart.py | 54 +++++++++++++++++++-------------------- beetsplug/freedesktop.py | 16 ++++++------ beetsplug/fromfilename.py | 3 +-- beetsplug/ftintitle.py | 9 +++---- 4 files changed, 39 insertions(+), 43 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 57d8e4c46..36496cc70 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -15,8 +15,7 @@ """Fetches album art. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from contextlib import closing import os @@ -206,14 +205,14 @@ class ITunesStore(ArtSource): try: results = itunes.search_album(search_string) except Exception as exc: - self._log.debug('iTunes search failed: {0}', exc) + self._log.debug(u'iTunes search failed: {0}', exc) return # Get the first match. if results: itunes_album = results[0] else: - self._log.debug('iTunes search for {:r} got no results', + self._log.debug(u'iTunes search for {:r} got no results', search_string) return @@ -276,9 +275,9 @@ class Wikipedia(ArtSource): cover_filename = 'File:' + results[0]['coverFilename']['value'] page_id = results[0]['pageId']['value'] else: - self._log.debug('wikipedia: album not found on dbpedia') + self._log.debug(u'wikipedia: album not found on dbpedia') except (ValueError, KeyError, IndexError): - self._log.debug('wikipedia: error scraping dbpedia response: {}', + self._log.debug(u'wikipedia: error scraping dbpedia response: {}', dbpedia_response.text) # Ensure we have a filename before attempting to query wikipedia @@ -293,8 +292,7 @@ class Wikipedia(ArtSource): if ' .' in cover_filename and \ '.' not in cover_filename.split(' .')[-1]: self._log.debug( - 'wikipedia: dbpedia provided incomplete cover_filename' - ) + u'wikipedia: dbpedia provided incomplete cover_filename') lpart, rpart = cover_filename.rsplit(' .', 1) # Query all the images in the page @@ -322,8 +320,7 @@ class Wikipedia(ArtSource): break except (ValueError, KeyError): self._log.debug( - 'wikipedia: failed to retrieve a cover_filename' - ) + u'wikipedia: failed to retrieve a cover_filename') return # Find the absolute url of the cover art on Wikipedia @@ -347,7 +344,7 @@ class Wikipedia(ArtSource): image_url = result['imageinfo'][0]['url'] yield image_url except (ValueError, KeyError, IndexError): - self._log.debug('wikipedia: error scraping imageinfo') + self._log.debug(u'wikipedia: error scraping imageinfo') return @@ -493,9 +490,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # Manual album art fetching. def commands(self): cmd = ui.Subcommand('fetchart', help='download album art') - cmd.parser.add_option('-f', '--force', dest='force', - action='store_true', default=False, - help='re-download art when already present') + cmd.parser.add_option( + u'-f', u'--force', dest='force', + action='store_true', default=False, + help=u're-download art when already present') def func(lib, opts, args): self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force) @@ -511,12 +509,12 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): """ try: with closing(self.request(url, stream=True, - message='downloading image')) as resp: + message=u'downloading image')) as resp: if 'Content-Type' not in resp.headers \ or resp.headers['Content-Type'] not in CONTENT_TYPES: self._log.debug( - 'not a supported image: {}', - resp.headers.get('Content-Type') or 'no content type', + u'not a supported image: {}', + resp.headers.get('Content-Type') or u'no content type', ) return None @@ -532,7 +530,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): except (IOError, requests.RequestException, TypeError) as exc: # Handling TypeError works around a urllib3 bug: # https://github.com/shazow/urllib3/issues/556 - self._log.debug('error fetching art: {}', exc) + self._log.debug(u'error fetching art: {}', exc) return None def _is_valid_image_candidate(self, candidate): @@ -551,7 +549,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # get_size returns None if no local imaging backend is available size = ArtResizer.shared.get_size(candidate) - self._log.debug('image size: {}', size) + self._log.debug(u'image size: {}', size) if not size: self._log.warning(u'Could not get size of image (please see ' @@ -562,19 +560,19 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # Check minimum size. if self.minwidth and size[0] < self.minwidth: - self._log.debug('image too small ({} < {})', + self._log.debug(u'image too small ({} < {})', size[0], self.minwidth) return CANDIDATE_BAD # Check aspect ratio. if self.enforce_ratio and size[0] != size[1]: - self._log.debug('image is not square ({} != {})', + self._log.debug(u'image is not square ({} != {})', size[0], size[1]) return CANDIDATE_BAD # Check maximum size. if self.maxwidth and size[0] > self.maxwidth: - self._log.debug('image needs resizing ({} > {})', + self._log.debug(u'image needs resizing ({} > {})', size[0], self.maxwidth) return CANDIDATE_DOWNSCALE @@ -600,7 +598,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): check = self._is_valid_image_candidate(candidate) if check: out = candidate - self._log.debug('found local image {}', out) + self._log.debug(u'found local image {}', out) break # Web art sources. @@ -613,7 +611,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): check = self._is_valid_image_candidate(candidate) if check: out = candidate - self._log.debug('using remote image {}', out) + self._log.debug(u'using remote image {}', out) break if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: @@ -627,7 +625,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): """ for album in albums: if album.artpath and not force and os.path.isfile(album.artpath): - message = ui.colorize('text_highlight_minor', 'has album art') + message = ui.colorize('text_highlight_minor', u'has album art') else: # In ordinary invocations, look for images on the # filesystem. When forcing, however, always go to the Web @@ -638,9 +636,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if path: album.set_art(path, False) album.store() - message = ui.colorize('text_success', 'found album art') + message = ui.colorize('text_success', u'found album art') else: - message = ui.colorize('text_error', 'no art found') + message = ui.colorize('text_error', u'no art found') self._log.info(u'{0}: {1}', album, message) @@ -654,7 +652,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): source_names = {v: k for k, v in ART_SOURCES.items()} for source in self.sources: self._log.debug( - 'trying source {0} for album {1.albumartist} - {1.album}', + u'trying source {0} for album {1.albumartist} - {1.album}', source_names[type(source)], album, ) diff --git a/beetsplug/freedesktop.py b/beetsplug/freedesktop.py index 33104fa13..c12fa3479 100644 --- a/beetsplug/freedesktop.py +++ b/beetsplug/freedesktop.py @@ -16,8 +16,7 @@ """Creates freedesktop.org-compliant .directory files on an album level. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import ui @@ -25,13 +24,14 @@ from beets import ui class FreedesktopPlugin(BeetsPlugin): def commands(self): - deprecated = ui.Subcommand("freedesktop", help="Print a message to " - "redirect to thumbnails --dolphin") + deprecated = ui.Subcommand( + "freedesktop", + help=u"Print a message to redirect to thumbnails --dolphin") deprecated.func = self.deprecation_message return [deprecated] def deprecation_message(self, lib, opts, args): - ui.print_("This plugin is deprecated. Its functionality is superseded " - "by the 'thumbnails' plugin") - ui.print_("'thumbnails --dolphin' replaces freedesktop. See doc & " - "changelog for more information") + ui.print_(u"This plugin is deprecated. Its functionality is " + u"superseded by the 'thumbnails' plugin") + ui.print_(u"'thumbnails --dolphin' replaces freedesktop. See doc & " + u"changelog for more information") diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index 895cab9e4..71e7ce3f2 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -16,8 +16,7 @@ """If the title is empty, try to extract track and title from the filename. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets import plugins from beets.util import displayable_path diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 30892f0dc..2bdf5a90b 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -15,8 +15,7 @@ """Moves "featured" artists to the title from the artist field. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re @@ -87,12 +86,12 @@ class FtInTitlePlugin(plugins.BeetsPlugin): self._command = ui.Subcommand( 'ftintitle', - help='move featured artists to the title field') + help=u'move featured artists to the title field') self._command.parser.add_option( - '-d', '--drop', dest='drop', + u'-d', u'--drop', dest='drop', action='store_true', default=False, - help='drop featuring from artists and ignore title update') + help=u'drop featuring from artists and ignore title update') if self.config['auto']: self.import_stages = [self.imported] From fc3d10d2483427e0ab1cb2affeb7edb532982ac3 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 13:53:10 +0100 Subject: [PATCH 0521/2280] Removed unicode_literals from plugins * fuzzy * ihate * importadded * importfeeds * info * inline --- beetsplug/fuzzy.py | 3 +-- beetsplug/ihate.py | 3 +-- beetsplug/importadded.py | 3 +-- beetsplug/importfeeds.py | 7 +++---- beetsplug/info.py | 27 +++++++++++++++------------ beetsplug/inline.py | 3 +-- 6 files changed, 22 insertions(+), 24 deletions(-) diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index 4e167217f..f2c9095b2 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -16,8 +16,7 @@ """Provides a fuzzy matching query. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.dbcore.query import StringFieldQuery diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index 7285c8482..c6e62fe29 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Warns you about things you hate (or even blocks import).""" diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 70be1089e..833f2f21c 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -5,8 +5,7 @@ modification time (mtime) of the item's source file before import. Reimported albums and items are skipped. """ -from __future__ import (unicode_literals, absolute_import, print_function, - division) +from __future__ import (absolute_import, print_function, division) import os diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index c3d677572..8bdabc632 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """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 @@ -135,9 +134,9 @@ class ImportFeedsPlugin(BeetsPlugin): os.symlink(syspath(path), syspath(dest)) if 'echo' in formats: - self._log.info("Location of imported music:") + self._log.info(u"Location of imported music:") for path in paths: - self._log.info(" {0}", path) + self._log.info(u" {0}", path) def library_opened(self, lib): if self.config['dir'].get() is None: diff --git a/beetsplug/info.py b/beetsplug/info.py index a29a6ccfc..05fd3fe58 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -16,8 +16,7 @@ """Shows file metadata. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import re @@ -141,17 +140,21 @@ def print_data_keys(data, item=None): class InfoPlugin(BeetsPlugin): def commands(self): - cmd = ui.Subcommand('info', help='show file metadata') + cmd = ui.Subcommand('info', help=u'show file metadata') cmd.func = self.run - cmd.parser.add_option('-l', '--library', action='store_true', - help='show library fields instead of tags') - cmd.parser.add_option('-s', '--summarize', action='store_true', - help='summarize the tags of all files') - cmd.parser.add_option('-i', '--include-keys', default=[], - action='append', dest='included_keys', - help='comma separated list of keys to show') - cmd.parser.add_option('-k', '--keys-only', action='store_true', - help='show only the keys') + cmd.parser.add_option( + u'-l', u'--library', action='store_true', + help=u'show library fields instead of tags') + cmd.parser.add_option( + u'-s', u'--summarize', action='store_true', + help=u'summarize the tags of all files') + cmd.parser.add_option( + u'-i', u'--include-keys', default=[], + action='append', dest='included_keys', + help=u'comma separated list of keys to show') + cmd.parser.add_option( + u'-k', u'--keys-only', action='store_true', + help=u'show only the keys') cmd.parser.add_format_option(target='item') return [cmd] diff --git a/beetsplug/inline.py b/beetsplug/inline.py index 5c0c81b80..8e22ad9c8 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -15,8 +15,7 @@ """Allows inline path template customization code in the config file. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import traceback import itertools From f2fc1a78bf636c11ed92322125f613eb84488bc7 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 13:59:58 +0100 Subject: [PATCH 0522/2280] Removed import of unicode_literals from plugins * keyfinder * lastimport * lyrics --- beetsplug/keyfinder.py | 9 ++++----- beetsplug/lastimport.py | 33 ++++++++++++++++----------------- beetsplug/lyrics.py | 31 ++++++++++++++++--------------- 3 files changed, 36 insertions(+), 37 deletions(-) diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index fc9c7b148..cc96cb886 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -16,8 +16,7 @@ """Uses the `KeyFinder` program to add the `initial_key` field. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import subprocess @@ -41,7 +40,7 @@ class KeyFinderPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('keyfinder', - help='detect and add initial key from audio') + help=u'detect and add initial key from audio') cmd.func = self.command return [cmd] @@ -63,12 +62,12 @@ class KeyFinderPlugin(BeetsPlugin): output = util.command_output([bin, b'-f', util.syspath(item.path)]) except (subprocess.CalledProcessError, OSError) as exc: - self._log.error('execution failed: {0}', exc) + self._log.error(u'execution failed: {0}', exc) continue except UnicodeEncodeError: # Workaround for Python 2 Windows bug. # http://bugs.python.org/issue1759845 - self._log.error('execution failed for Unicode path: {0!r}', + self._log.error(u'execution failed for Unicode path: {0!r}', item.path) continue diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 38b5bfc10..763a24a8c 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import pylast from pylast import TopItem, _extract, _number @@ -44,7 +43,7 @@ class LastImportPlugin(plugins.BeetsPlugin): } def commands(self): - cmd = ui.Subcommand('lastimport', help='import last.fm play-count') + cmd = ui.Subcommand('lastimport', help=u'import last.fm play-count') def func(lib, opts, args): import_lastfm(lib, self._log) @@ -115,9 +114,9 @@ def import_lastfm(lib, log): per_page = config['lastimport']['per_page'].get(int) if not user: - raise ui.UserError('You must specify a user name for lastimport') + raise ui.UserError(u'You must specify a user name for lastimport') - log.info('Fetching last.fm library for @{0}', user) + log.info(u'Fetching last.fm library for @{0}', user) page_total = 1 page_current = 0 @@ -126,7 +125,7 @@ def import_lastfm(lib, log): retry_limit = config['lastimport']['retry_limit'].get(int) # Iterate through a yet to be known page total count while page_current < page_total: - log.info('Querying page #{0}{1}...', + log.info(u'Querying page #{0}{1}...', page_current + 1, '/{}'.format(page_total) if page_total > 1 else '') @@ -134,7 +133,7 @@ def import_lastfm(lib, log): tracks, page_total = fetch_tracks(user, page_current + 1, per_page) if page_total < 1: # It means nothing to us! - raise ui.UserError('Last.fm reported no data.') + raise ui.UserError(u'Last.fm reported no data.') if tracks: found, unknown = process_tracks(lib, tracks, log) @@ -142,22 +141,22 @@ def import_lastfm(lib, log): unknown_total += unknown break else: - log.error('ERROR: unable to read page #{0}', + log.error(u'ERROR: unable to read page #{0}', page_current + 1) if retry < retry_limit: log.info( - 'Retrying page #{0}... ({1}/{2} retry)', + u'Retrying page #{0}... ({1}/{2} retry)', page_current + 1, retry + 1, retry_limit ) else: - log.error('FAIL: unable to fetch page #{0}, ', - 'tried {1} times', page_current, retry + 1) + log.error(u'FAIL: unable to fetch page #{0}, ', + u'tried {1} times', page_current, retry + 1) page_current += 1 - log.info('... done!') - log.info('finished processing {0} song pages', page_total) - log.info('{0} unknown play-counts', unknown_total) - log.info('{0} play-counts imported', found_total) + log.info(u'... done!') + log.info(u'finished processing {0} song pages', page_total) + log.info(u'{0} unknown play-counts', unknown_total) + log.info(u'{0} play-counts imported', found_total) def fetch_tracks(user, page, limit): @@ -191,7 +190,7 @@ def process_tracks(lib, tracks, log): total = len(tracks) total_found = 0 total_fails = 0 - log.info('Received {0} tracks in this page, processing...', total) + log.info(u'Received {0} tracks in this page, processing...', total) for num in xrange(0, total): song = None @@ -244,7 +243,7 @@ def process_tracks(lib, tracks, log): artist, title, album) if total_fails > 0: - log.info('Acquired {0}/{1} play-counts ({2} unknown)', + log.info(u'Acquired {0}/{1} play-counts ({2} unknown)', total_found, total, total_fails) return total_found, total_fails diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 9e5e2fad6..1b046c218 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -16,8 +16,7 @@ """Fetches, embeds, and displays lyrics. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re import requests @@ -107,7 +106,7 @@ def extract_text_in(html, starttag): parts.append(html[pos:match.start()]) break else: - print('no closing tag found!') + print(u'no closing tag found!') return return u''.join(parts) @@ -237,7 +236,7 @@ class Genius(Backend): url = u'https://api.genius.com/search?q=%s' \ % (urllib.quote(query.encode('utf8'))) - self._log.debug('genius: requesting search {}', url) + self._log.debug(u'genius: requesting search {}', url) try: req = requests.get( url, @@ -246,19 +245,19 @@ class Genius(Backend): ) req.raise_for_status() except requests.RequestException as exc: - self._log.debug('genius: request error: {}', exc) + self._log.debug(u'genius: request error: {}', exc) return None try: return req.json() except ValueError: - self._log.debug('genius: invalid response: {}', req.text) + self._log.debug(u'genius: invalid response: {}', req.text) return None def get_lyrics(self, link): url = u'http://genius-api.com/api/lyricsInfo' - self._log.debug('genius: requesting lyrics for link {}', link) + self._log.debug(u'genius: requesting lyrics for link {}', link) try: req = requests.post( url, @@ -268,13 +267,13 @@ class Genius(Backend): ) req.raise_for_status() except requests.RequestException as exc: - self._log.debug('genius: request error: {}', exc) + self._log.debug(u'genius: request error: {}', exc) return None try: return req.json() except ValueError: - self._log.debug('genius: invalid response: {}', req.text) + self._log.debug(u'genius: invalid response: {}', req.text) return None def build_lyric_string(self, lyrics): @@ -576,12 +575,14 @@ class LyricsPlugin(plugins.BeetsPlugin): def commands(self): cmd = ui.Subcommand('lyrics', help='fetch song lyrics') - cmd.parser.add_option('-p', '--print', dest='printlyr', - action='store_true', default=False, - help='print lyrics to console') - cmd.parser.add_option('-f', '--force', dest='force_refetch', - action='store_true', default=False, - help='always re-download lyrics') + cmd.parser.add_option( + u'-p', u'--print', dest='printlyr', + action='store_true', default=False, + help=u'print lyrics to console') + cmd.parser.add_option( + u'-f', u'--force', dest='force_refetch', + action='store_true', default=False, + help=u'always re-download lyrics') def func(lib, opts, args): # The "write to files" option corresponds to the From 48098c3741e40418da0ba16eab27744554f4b210 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:08:05 +0100 Subject: [PATCH 0523/2280] Removed import of unicode_literals from plugins * lastgenere * mbcollection * mbsubmit * mbsync * missing --- beetsplug/lastgenre/__init__.py | 33 +++++++++++++++++---------------- beetsplug/mbcollection.py | 21 +++++++++++---------- beetsplug/mbsubmit.py | 5 ++--- beetsplug/mbsync.py | 31 ++++++++++++++++--------------- beetsplug/missing.py | 15 +++++++-------- 5 files changed, 53 insertions(+), 52 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 554369ced..7faced0d4 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Gets genres for imported music based on Last.fm tags. @@ -239,25 +238,26 @@ class LastGenrePlugin(plugins.BeetsPlugin): def fetch_album_genre(self, obj): """Return the album genre for this Item or Album. """ - return self._last_lookup(u'album', LASTFM.get_album, obj.albumartist, - obj.album) + return self._last_lookup( + u'album', LASTFM.get_album, obj.albumartist, obj.album) def fetch_album_artist_genre(self, obj): """Return the album artist genre for this Item or Album. """ - return self._last_lookup(u'artist', LASTFM.get_artist, - obj.albumartist) + return self._last_lookup( + u'artist', LASTFM.get_artist, obj.albumartist) def fetch_artist_genre(self, item): """Returns the track artist genre for this Item. """ - return self._last_lookup(u'artist', LASTFM.get_artist, item.artist) + return self._last_lookup( + u'artist', LASTFM.get_artist, item.artist) def fetch_track_genre(self, obj): """Returns the track genre for this Item. """ - return self._last_lookup(u'track', LASTFM.get_track, obj.artist, - obj.title) + return self._last_lookup( + u'track', LASTFM.get_track, obj.artist, obj.title) def _get_genre(self, obj): """Get the genre string for an Album or Item object based on @@ -326,14 +326,15 @@ class LastGenrePlugin(plugins.BeetsPlugin): return None, None def commands(self): - lastgenre_cmd = ui.Subcommand('lastgenre', help='fetch genres') + lastgenre_cmd = ui.Subcommand('lastgenre', help=u'fetch genres') lastgenre_cmd.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='re-download genre when already present' + u'-f', u'--force', dest='force', + action='store_true', default=False, + help=u're-download genre when already present' ) lastgenre_cmd.parser.add_option( - '-s', '--source', dest='source', type='string', - help='genre source: artist, album, or track' + u'-s', u'--source', dest='source', type='string', + help=u'genre source: artist, album, or track' ) def lastgenre_func(lib, opts, args): @@ -406,8 +407,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): return [] except Exception as exc: # Isolate bugs in pylast. - self._log.debug('{}', traceback.format_exc()) - self._log.error('error in pylast library: {0}', exc) + self._log.debug(u'{}', traceback.format_exc()) + self._log.error(u'error in pylast library: {0}', exc) return [] # Filter by weight (optionally). diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 2e24ae59e..8c1c6a47a 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -13,8 +13,7 @@ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.ui import Subcommand @@ -34,11 +33,11 @@ def mb_call(func, *args, **kwargs): try: return func(*args, **kwargs) except musicbrainzngs.AuthenticationError: - raise ui.UserError('authentication with MusicBrainz failed') + raise ui.UserError(u'authentication with MusicBrainz failed') except (musicbrainzngs.ResponseError, musicbrainzngs.NetworkError) as exc: - raise ui.UserError('MusicBrainz API error: {0}'.format(exc)) + raise ui.UserError(u'MusicBrainz API error: {0}'.format(exc)) except musicbrainzngs.UsageError: - raise ui.UserError('MusicBrainz credentials missing') + raise ui.UserError(u'MusicBrainz credentials missing') def submit_albums(collection_id, release_ids): @@ -65,7 +64,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): self.import_stages = [self.imported] def commands(self): - mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection') + mbupdate = Subcommand('mbupdate', + help=u'Update MusicBrainz collection') mbupdate.func = self.update_collection return [mbupdate] @@ -84,7 +84,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): # Get the available collections. collections = mb_call(musicbrainzngs.get_collections) if not collections['collection-list']: - raise ui.UserError('no collections exist for user') + raise ui.UserError(u'no collections exist for user') # Get the first release collection. MusicBrainz also has event # collections, so we need to avoid adding to those. @@ -93,7 +93,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): collection_id = collection['id'] break else: - raise ui.UserError('No collection found.') + raise ui.UserError(u'No collection found.') # Get a list of all the album IDs. album_ids = [] @@ -106,6 +106,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): self._log.info(u'skipping invalid MBID: {0}', aid) # Submit to MusicBrainz. - self._log.info('Updating MusicBrainz collection {0}...', collection_id) + self._log.info( + u'Updating MusicBrainz collection {0}...', collection_id) submit_albums(collection_id, album_ids) - self._log.info('...MusicBrainz collection updated.') + self._log.info(u'...MusicBrainz collection updated.') diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 947e4cfc6..99ae7302c 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -22,8 +22,7 @@ implemented by MusicBrainz yet. [1] http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.autotag import Recommendation @@ -54,7 +53,7 @@ class MBSubmitPlugin(BeetsPlugin): def before_choose_candidate_event(self, session, task): if task.rec <= self.threshold: - return [PromptChoice('p', 'Print tracks', self.print_tracks)] + return [PromptChoice(u'p', u'Print tracks', self.print_tracks)] def print_tracks(self, session, task): for i in task.items: diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 00eb966fa..0d7669c0d 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -15,8 +15,7 @@ """Update library's tags using MusicBrainz. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import autotag, library, ui, util @@ -43,18 +42,20 @@ class MBSyncPlugin(BeetsPlugin): def commands(self): cmd = ui.Subcommand('mbsync', - help='update metadata from musicbrainz') - cmd.parser.add_option('-p', '--pretend', action='store_true', - help='show all changes but do nothing') - cmd.parser.add_option('-m', '--move', action='store_true', - dest='move', - help="move files in the library directory") - cmd.parser.add_option('-M', '--nomove', action='store_false', - dest='move', - help="don't move files in library") - cmd.parser.add_option('-W', '--nowrite', action='store_false', - default=None, dest='write', - help="don't write updated metadata to files") + help=u'update metadata from musicbrainz') + cmd.parser.add_option( + u'-p', u'--pretend', action='store_true', + help=u'show all changes but do nothing') + cmd.parser.add_option( + u'-m', u'--move', action='store_true', dest='move', + help=u"move files in the library directory") + cmd.parser.add_option( + u'-M', u'--nomove', action='store_false', dest='move', + help=u"don't move files in library") + cmd.parser.add_option( + u'-W', u'--nowrite', action='store_false', + default=None, dest='write', + help=u"don't write updated metadata to files") cmd.parser.add_format_option() cmd.func = self.func return [cmd] @@ -140,7 +141,7 @@ class MBSyncPlugin(BeetsPlugin): break # Apply. - self._log.debug('applying changes to {}', album_formatted) + self._log.debug(u'applying changes to {}', album_formatted) with lib.transaction(): autotag.apply_metadata(album_info, mapping) changed = False diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 05e66b7a8..d33843489 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -15,8 +15,7 @@ """List missing tracks. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.autotag import hooks from beets.library import Item @@ -95,12 +94,12 @@ class MissingPlugin(BeetsPlugin): self._command = Subcommand('missing', help=__doc__, aliases=['miss']) - self._command.parser.add_option('-c', '--count', dest='count', - action='store_true', - help='count missing tracks per album') - self._command.parser.add_option('-t', '--total', dest='total', - action='store_true', - help='count total of missing tracks') + self._command.parser.add_option( + u'-c', u'--count', dest='count', action='store_true', + help=u'count missing tracks per album') + self._command.parser.add_option( + u'-t', u'--total', dest='total', action='store_true', + help=u'count total of missing tracks') self._command.parser.add_format_option() def commands(self): From feab3df9108b3449d9758eb780ee0fa59cffe6a2 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:12:37 +0100 Subject: [PATCH 0524/2280] Removed import of unicode_literals from plugins * mpdstats * mpdupdate * permissions * zero --- beetsplug/mpdstats.py | 21 ++++++++++----------- beetsplug/mpdupdate.py | 5 ++--- beetsplug/permissions.py | 7 +++---- beetsplug/zero.py | 3 +-- 4 files changed, 16 insertions(+), 20 deletions(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 326afe4da..a2ade3186 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import mpd import socket @@ -80,7 +79,7 @@ class MPDClientWrapper(object): try: self.client.connect(host, port) except socket.error as e: - raise ui.UserError('could not connect to MPD: {0}'.format(e)) + raise ui.UserError(u'could not connect to MPD: {0}'.format(e)) password = mpd_config['password'].get(unicode) if password: @@ -88,7 +87,7 @@ class MPDClientWrapper(object): self.client.password(password) except mpd.CommandError as e: raise ui.UserError( - 'could not authenticate to MPD: {0}'.format(e) + u'could not authenticate to MPD: {0}'.format(e) ) def disconnect(self): @@ -338,16 +337,16 @@ class MPDStatsPlugin(plugins.BeetsPlugin): def commands(self): cmd = ui.Subcommand( 'mpdstats', - help='run a MPD client to gather play statistics') + help=u'run a MPD client to gather play statistics') cmd.parser.add_option( - '--host', dest='host', type='string', - help='set the hostname of the server to connect to') + u'--host', dest='host', type='string', + help=u'set the hostname of the server to connect to') cmd.parser.add_option( - '--port', dest='port', type='int', - help='set the port of the MPD server to connect to') + u'--port', dest='port', type='int', + help=u'set the port of the MPD server to connect to') cmd.parser.add_option( - '--password', dest='password', type='string', - help='set the password of the MPD server to connect to') + u'--password', dest='password', type='string', + help=u'set the password of the MPD server to connect to') def func(lib, opts, args): mpd_config.set_args(opts) diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 5e4e999aa..70fb4c749 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -21,8 +21,7 @@ Put something like the following in your config.yaml to configure: port: 6600 password: seekrit """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin import os @@ -126,4 +125,4 @@ class MPDUpdatePlugin(BeetsPlugin): s.send('close\n') s.close() - self._log.info('Database updated.') + self._log.info(u'Database updated.') diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 8a4ab960b..1099aad51 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Fixes file permissions after the file gets written on import. Put something like the following in your config.yaml to configure: @@ -82,7 +81,7 @@ def permissions(lib, item=None, album=None): # Checks if the destination path has the permissions configured. if not check_permissions(util.bytestring_path(path), file_perm): - message = 'There was a problem setting permission on {}'.format( + message = u'There was a problem setting permission on {}'.format( path) print(message) @@ -98,6 +97,6 @@ def permissions(lib, item=None, album=None): # Checks if the destination path has the permissions configured. if not check_permissions(util.bytestring_path(path), dir_perm): - message = 'There was a problem setting permission on {}'.format( + message = u'There was a problem setting permission on {}'.format( path) print(message) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index b427bbe8a..5623aa3df 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -15,8 +15,7 @@ """ Clears tag fields in media files.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re from beets.plugins import BeetsPlugin From 456565b6f2969cb00c563375f98bae5987c2bb92 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:22:45 +0100 Subject: [PATCH 0525/2280] Removed import of unicode_literals from plugins * play * plexpudate * random * replaygain --- beetsplug/play.py | 24 ++++++------ beetsplug/plexupdate.py | 9 ++--- beetsplug/random.py | 15 ++++---- beetsplug/replaygain.py | 84 +++++++++++++++++------------------------ 4 files changed, 58 insertions(+), 74 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index b52b7e635..0faac7e42 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -15,8 +15,7 @@ """Send the results of a query to the configured music player as a playlist. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.ui import Subcommand @@ -49,13 +48,13 @@ class PlayPlugin(BeetsPlugin): def commands(self): play_command = Subcommand( 'play', - help='send music to a player as a playlist' + help=u'send music to a player as a playlist' ) play_command.parser.add_album_option() play_command.parser.add_option( - '-A', '--args', + u'-A', u'--args', action='store', - help='add additional arguments to the command', + help=u'add additional arguments to the command', ) play_command.func = self.play_music return [play_command] @@ -90,7 +89,7 @@ class PlayPlugin(BeetsPlugin): if ARGS_MARKER in command_str: command_str = command_str.replace(ARGS_MARKER, opts.args) else: - command_str = "{} {}".format(command_str, opts.args) + command_str = u"{} {}".format(command_str, opts.args) # Perform search by album and add folders rather than tracks to # playlist. @@ -119,16 +118,15 @@ class PlayPlugin(BeetsPlugin): if not selection: ui.print_(ui.colorize('text_warning', - 'No {0} to play.'.format(item_type))) + u'No {0} to play.'.format(item_type))) return # Warn user before playing any huge playlists. if warning_threshold and len(selection) > warning_threshold: ui.print_(ui.colorize( 'text_warning', - 'You are about to queue {0} {1}.'.format(len(selection), - item_type) - )) + u'You are about to queue {0} {1}.'.format( + len(selection), item_type))) if ui.input_options(('Continue', 'Abort')) == 'a': return @@ -139,13 +137,13 @@ class PlayPlugin(BeetsPlugin): else: open_args = [self._create_tmp_playlist(paths)] - self._log.debug('executing command: {} {}', command_str, + self._log.debug(u'executing command: {} {}', command_str, b' '.join(open_args)) try: util.interactive_open(open_args, command_str) except OSError as exc: - raise ui.UserError("Could not play the query: " - "{0}".format(exc)) + raise ui.UserError( + "Could not play the query: {0}".format(exc)) def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 51ee4fd85..30afe1b08 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -9,8 +9,7 @@ Put something like the following in your config.yaml to configure: port: 32400 token: token """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import requests from urlparse import urljoin @@ -78,7 +77,7 @@ class PlexUpdate(BeetsPlugin): def update(self, lib): """When the client exists try to send refresh request to Plex server. """ - self._log.info('Updating Plex library...') + self._log.info(u'Updating Plex library...') # Try to send update request. try: @@ -87,7 +86,7 @@ class PlexUpdate(BeetsPlugin): config['plex']['port'].get(), config['plex']['token'].get(), config['plex']['library_name'].get()) - self._log.info('... started.') + self._log.info(u'... started.') except requests.exceptions.RequestException: - self._log.warning('Update failed.') + self._log.warning(u'Update failed.') diff --git a/beetsplug/random.py b/beetsplug/random.py index 22ae23252..e94d7841c 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -15,8 +15,7 @@ """Get a random song or album from the library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs, print_ @@ -66,11 +65,13 @@ def random_item(lib, opts, args): print_(format(item)) random_cmd = Subcommand('random', - help='chose a random track or album') -random_cmd.parser.add_option('-n', '--number', action='store', type="int", - help='number of objects to choose', default=1) -random_cmd.parser.add_option('-e', '--equal-chance', action='store_true', - help='each artist has the same chance') + help=u'chose a random track or album') +random_cmd.parser.add_option( + u'-n', u'--number', action='store', type="int", + help=u'number of objects to choose', default=1) +random_cmd.parser.add_option( + u'-e', u'--equal-chance', action='store_true', + help=u'each artist has the same chance') random_cmd.parser.add_all_common_options() random_cmd.func = random_item diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index babb469ad..f8b4eed93 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import subprocess import os @@ -56,13 +55,13 @@ def call(args): return command_output(args) except subprocess.CalledProcessError as e: raise ReplayGainError( - "{0} exited with status {1}".format(args[0], e.returncode) + u"{0} exited with status {1}".format(args[0], e.returncode) ) except UnicodeEncodeError: # Due to a bug in Python 2's subprocess on Windows, Unicode # filenames can fail to encode on that platform. See: # http://code.google.com/p/beets/issues/detail?id=499 - raise ReplayGainError("argument encoding failed") + raise ReplayGainError(u"argument encoding failed") # Backend base and plumbing classes. @@ -111,11 +110,11 @@ class Bs1770gainBackend(Backend): self.command = cmd except OSError: raise FatalReplayGainError( - 'Is bs1770gain installed? Is your method in config correct?' + u'Is bs1770gain installed? Is your method in config correct?' ) if not self.command: raise FatalReplayGainError( - 'no replaygain command found: install bs1770gain' + u'no replaygain command found: install bs1770gain' ) def compute_track_gain(self, items): @@ -137,7 +136,7 @@ class Bs1770gainBackend(Backend): output = self.compute_gain(supported_items, True) if not output: - raise ReplayGainError('no output from bs1770gain') + raise ReplayGainError(u'no output from bs1770gain') return AlbumGain(output[-1], output[:-1]) def isplitter(self, items, chunk_at): @@ -204,7 +203,8 @@ class Bs1770gainBackend(Backend): args = cmd + [syspath(i.path, prefix=False) for i in items] # Invoke the command. - self._log.debug("executing {0}", " ".join(map(displayable_path, args))) + self._log.debug( + u'executing {0}', u' '.join(map(displayable_path, args))) output = call(args) self._log.debug(u'analysis finished: {0}', output) @@ -228,8 +228,8 @@ class Bs1770gainBackend(Backend): for parts in results[0:num_lines]: part = parts.split(b'\n') if len(part) == 0: - self._log.debug('bad tool output: {0!r}', text) - raise ReplayGainError('bs1770gain failed') + self._log.debug(u'bad tool output: {0!r}', text) + raise ReplayGainError(u'bs1770gain failed') try: song = { @@ -238,7 +238,7 @@ class Bs1770gainBackend(Backend): 'peak': float(part[2].split('/')[1]), } except IndexError: - self._log.info('bs1770gain reports (faulty file?): {}', parts) + self._log.info(u'bs1770gain reports (faulty file?): {}', parts) continue out.append(Gain(song['gain'], song['peak'])) @@ -261,9 +261,8 @@ class CommandBackend(Backend): # Explicit executable path. if not os.path.isfile(self.command): raise FatalReplayGainError( - 'replaygain command does not exist: {0}'.format( - self.command - ) + u'replaygain command does not exist: {0}'.format( + self.command) ) else: # Check whether the program is in $PATH. @@ -275,8 +274,7 @@ class CommandBackend(Backend): pass if not self.command: raise FatalReplayGainError( - 'no replaygain command found: install mp3gain or aacgain' - ) + u'no replaygain command found: install mp3gain or aacgain') self.noclip = config['noclip'].get(bool) target_level = config['targetlevel'].as_number() @@ -322,7 +320,7 @@ class CommandBackend(Backend): the album gain """ if len(items) == 0: - self._log.debug('no supported tracks to analyze') + self._log.debug(u'no supported tracks to analyze') return [] """Compute ReplayGain values and return a list of results @@ -361,7 +359,7 @@ class CommandBackend(Backend): parts = line.split(b'\t') if len(parts) != 6 or parts[0] == b'File': self._log.debug(u'bad tool output: {0}', text) - raise ReplayGainError('mp3gain failed') + raise ReplayGainError(u'mp3gain failed') d = { 'file': parts[0], 'mp3gain': int(parts[1]), @@ -397,8 +395,7 @@ class GStreamerBackend(Backend): if self._src is None or self._decbin is None or self._conv is None \ or self._res is None or self._rg is None: raise FatalGstreamerPluginReplayGainError( - "Failed to load required GStreamer plugins" - ) + u"Failed to load required GStreamer plugins") # We check which files need gain ourselves, so all files given # to rganalsys should have their gain computed, even if it @@ -444,15 +441,13 @@ class GStreamerBackend(Backend): import gi except ImportError: raise FatalReplayGainError( - "Failed to load GStreamer: python-gi not found" - ) + u"Failed to load GStreamer: python-gi not found") try: gi.require_version('Gst', '1.0') except ValueError as e: raise FatalReplayGainError( - "Failed to load GStreamer 1.0: {0}".format(e) - ) + u"Failed to load GStreamer 1.0: {0}".format(e)) from gi.repository import GObject, Gst, GLib # Calling GObject.threads_init() is not needed for @@ -486,7 +481,7 @@ class GStreamerBackend(Backend): def compute_track_gain(self, items): self.compute(items, False) if len(self._file_tags) != len(items): - raise ReplayGainError("Some tracks did not receive tags") + raise ReplayGainError(u"Some tracks did not receive tags") ret = [] for item in items: @@ -499,7 +494,7 @@ class GStreamerBackend(Backend): items = list(album.items()) self.compute(items, True) if len(self._file_tags) != len(items): - raise ReplayGainError("Some items in album did not receive tags") + raise ReplayGainError(u"Some items in album did not receive tags") # Collect track gains. track_gains = [] @@ -508,7 +503,7 @@ class GStreamerBackend(Backend): gain = self._file_tags[item]["TRACK_GAIN"] peak = self._file_tags[item]["TRACK_PEAK"] except KeyError: - raise ReplayGainError("results missing for track") + raise ReplayGainError(u"results missing for track") track_gains.append(Gain(gain, peak)) # Get album gain information from the last track. @@ -517,7 +512,7 @@ class GStreamerBackend(Backend): gain = last_tags["ALBUM_GAIN"] peak = last_tags["ALBUM_PEAK"] except KeyError: - raise ReplayGainError("results missing for album") + raise ReplayGainError(u"results missing for album") return AlbumGain(Gain(gain, peak), track_gains) @@ -539,8 +534,7 @@ class GStreamerBackend(Backend): f = self._src.get_property("location") # A GStreamer error, either an unsupported format or a bug. self._error = ReplayGainError( - "Error {0!r} - {1!r} on file {2!r}".format(err, debug, f) - ) + u"Error {0!r} - {1!r} on file {2!r}".format(err, debug, f)) def _on_tag(self, bus, message): tags = message.parse_tag() @@ -663,8 +657,7 @@ class AudioToolsBackend(Backend): import audiotools.replaygain except ImportError: raise FatalReplayGainError( - "Failed to load audiotools: audiotools not found" - ) + u"Failed to load audiotools: audiotools not found") self._mod_audiotools = audiotools self._mod_replaygain = audiotools.replaygain @@ -681,12 +674,10 @@ class AudioToolsBackend(Backend): audiofile = self._mod_audiotools.open(item.path) except IOError: raise ReplayGainError( - "File {} was not found".format(item.path) - ) + u"File {} was not found".format(item.path)) except self._mod_audiotools.UnsupportedFile: raise ReplayGainError( - "Unsupported file type {}".format(item.format) - ) + u"Unsupported file type {}".format(item.format)) return audiofile @@ -704,8 +695,7 @@ class AudioToolsBackend(Backend): rg = self._mod_replaygain.ReplayGain(audiofile.sample_rate()) except ValueError: raise ReplayGainError( - "Unsupported sample rate {}".format(item.samplerate) - ) + u"Unsupported sample rate {}".format(item.samplerate)) return return rg @@ -730,8 +720,8 @@ class AudioToolsBackend(Backend): except ValueError as exc: # `audiotools.replaygain` can raise a `ValueError` if the sample # rate is incorrect. - self._log.debug('error in rg.title_gain() call: {}', exc) - raise ReplayGainError('audiotools audio data error') + self._log.debug(u'error in rg.title_gain() call: {}', exc) + raise ReplayGainError(u'audiotools audio data error') def _compute_track_gain(self, item): """Compute ReplayGain value for the requested item. @@ -830,8 +820,7 @@ class ReplayGainPlugin(BeetsPlugin): ) except (ReplayGainError, FatalReplayGainError) as e: raise ui.UserError( - 'replaygain initialization failed: {0}'.format(e) - ) + u'replaygain initialization failed: {0}'.format(e)) def track_requires_gain(self, item): return self.overwrite or \ @@ -894,8 +883,7 @@ class ReplayGainPlugin(BeetsPlugin): self._log.info(u"ReplayGain error: {0}", e) except FatalReplayGainError as e: raise ui.UserError( - u"Fatal replay gain error: {0}".format(e) - ) + u"Fatal replay gain error: {0}".format(e)) def handle_track(self, item, write): """Compute track replay gain and store it in the item. @@ -914,8 +902,7 @@ class ReplayGainPlugin(BeetsPlugin): track_gains = self.backend_instance.compute_track_gain([item]) if len(track_gains) != 1: raise ReplayGainError( - u"ReplayGain backend failed for track {0}".format(item) - ) + u"ReplayGain backend failed for track {0}".format(item)) self.store_track_gain(item, track_gains[0]) if write: @@ -924,8 +911,7 @@ class ReplayGainPlugin(BeetsPlugin): self._log.info(u"ReplayGain error: {0}", e) except FatalReplayGainError as e: raise ui.UserError( - u"Fatal replay gain error: {0}".format(e) - ) + u"Fatal replay gain error: {0}".format(e)) def imported(self, session, task): """Add replay gain info to items or albums of ``task``. @@ -951,7 +937,7 @@ class ReplayGainPlugin(BeetsPlugin): for item in lib.items(ui.decargs(args)): self.handle_track(item, write) - cmd = ui.Subcommand('replaygain', help='analyze for ReplayGain') + cmd = ui.Subcommand('replaygain', help=u'analyze for ReplayGain') cmd.parser.add_album_option() cmd.func = func return [cmd] From 30cf40707406175d244cae22c4ebbda0cff6f752 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:31:27 +0100 Subject: [PATCH 0526/2280] Removed import of unicode_literals from plugins * rewrite * scrub * smartplaylist * spotify * the --- beetsplug/rewrite.py | 7 +++---- beetsplug/scrub.py | 12 ++++++------ beetsplug/smartplaylist.py | 27 ++++++++++++++------------- beetsplug/spotify.py | 17 ++++++++--------- beetsplug/the.py | 3 +-- 5 files changed, 32 insertions(+), 34 deletions(-) diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index 2327bc780..cba297cc4 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -16,8 +16,7 @@ """Uses user-specified rewriting rules to canonicalize names for path formats. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re from collections import defaultdict @@ -56,9 +55,9 @@ class RewritePlugin(BeetsPlugin): try: fieldname, pattern = key.split(None, 1) except ValueError: - raise ui.UserError("invalid rewrite specification") + raise ui.UserError(u"invalid rewrite specification") if fieldname not in library.Item._fields: - raise ui.UserError("invalid field name (%s) in rewriter" % + raise ui.UserError(u"invalid field name (%s) in rewriter" % fieldname) self._log.debug(u'adding template field {0}', key) pattern = re.compile(pattern.lower()) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 34e6428ad..3556de8c8 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -17,8 +17,7 @@ automatically whenever tags are written. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import ui @@ -64,10 +63,11 @@ class ScrubPlugin(BeetsPlugin): util.displayable_path(item.path)) self._scrub_item(item, opts.write) - scrub_cmd = ui.Subcommand('scrub', help='clean audio tags') - scrub_cmd.parser.add_option('-W', '--nowrite', dest='write', - action='store_false', default=True, - help='leave tags empty') + scrub_cmd = ui.Subcommand('scrub', help=u'clean audio tags') + scrub_cmd.parser.add_option( + u'-W', u'--nowrite', dest='write', + action='store_false', default=True, + help=u'leave tags empty') scrub_cmd.func = scrub_func return [scrub_cmd] diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index cc988b22c..ff1edf0db 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -16,8 +16,7 @@ """Generates smart playlists based on beets queries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import ui @@ -46,9 +45,10 @@ class SmartPlaylistPlugin(BeetsPlugin): self.register_listener('database_change', self.db_change) def commands(self): - spl_update = ui.Subcommand('splupdate', - help='update the smart playlists. Playlist ' - 'names may be passed as arguments.') + spl_update = ui.Subcommand( + 'splupdate', + help=u'update the smart playlists. Playlist ' + u'names may be passed as arguments.') spl_update.func = self.update_cmd return [spl_update] @@ -64,9 +64,9 @@ class SmartPlaylistPlugin(BeetsPlugin): for name, q, a_q in self._unmatched_playlists if name in args) if not playlists: - raise ui.UserError('No playlist matching any of {0} ' - 'found'.format([name for name, _, _ in - self._unmatched_playlists])) + raise ui.UserError( + u'No playlist matching any of {0} found'.format( + [name for name, _, _ in self._unmatched_playlists])) self._matched_playlists = playlists self._unmatched_playlists -= playlists @@ -95,7 +95,7 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self.config['playlists'].get(list): if 'name' not in playlist: - self._log.warn("playlist configuration is missing name") + self._log.warn(u"playlist configuration is missing name") continue playlist_data = (playlist['name'],) @@ -131,7 +131,7 @@ class SmartPlaylistPlugin(BeetsPlugin): playlist_data += (query_and_sort,) except ParsingError as exc: - self._log.warn("invalid query in playlist {}: {}", + self._log.warn(u"invalid query in playlist {}: {}", playlist['name'], exc) continue @@ -151,14 +151,15 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self._unmatched_playlists: n, (q, _), (a_q, _) = playlist if self.matches(model, q, a_q): - self._log.debug("{0} will be updated because of {1}", n, model) + self._log.debug( + u"{0} will be updated because of {1}", n, model) self._matched_playlists.add(playlist) self.register_listener('cli_exit', self.update_playlists) self._unmatched_playlists -= self._matched_playlists def update_playlists(self, lib): - self._log.info("Updating {0} smart playlists...", + self._log.info(u"Updating {0} smart playlists...", len(self._matched_playlists)) playlist_dir = self.config['playlist_dir'].as_filename() @@ -196,4 +197,4 @@ class SmartPlaylistPlugin(BeetsPlugin): with open(syspath(m3u_path), 'w') as f: for path in m3us[m3u]: f.write(path + b'\n') - self._log.info("{0} playlists updated", len(self._matched_playlists)) + self._log.info(u"{0} playlists updated", len(self._matched_playlists)) diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index f77756dbc..9564582fa 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re import webbrowser @@ -41,17 +40,17 @@ class SpotifyPlugin(BeetsPlugin): self.output_results(results) spotify_cmd = ui.Subcommand( 'spotify', - help='build a Spotify playlist' + help=u'build a Spotify playlist' ) spotify_cmd.parser.add_option( - '-m', '--mode', action='store', - help='"open" to open Spotify with playlist, ' - '"list" to print (default)' + u'-m', u'--mode', action='store', + help=u'"open" to open Spotify with playlist, ' + u'"list" to print (default)' ) spotify_cmd.parser.add_option( - '-f', '--show-failures', action='store_true', - help='list tracks that did not match a Spotify ID', - dest='show_failures', + u'-f', u'--show-failures', + action='store_true', dest='show_failures', + help=u'list tracks that did not match a Spotify ID' ) spotify_cmd.func = queries return [spotify_cmd] diff --git a/beetsplug/the.py b/beetsplug/the.py index b6ffc945f..5d9c958f2 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -15,8 +15,7 @@ """Moves patterns in path formats (suitable for moving articles).""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re from beets.plugins import BeetsPlugin From 7155999d009cd91bdd5c737875e9fe1c0e73e21f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:34:49 +0100 Subject: [PATCH 0527/2280] Removed import of unicode_literals from plugins * thumbnails * types --- beetsplug/thumbnails.py | 48 ++++++++++++++++++++--------------------- beetsplug/types.py | 3 +-- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index ca2a942a9..c9b484d5a 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -19,8 +19,7 @@ This plugin is POSIX-only. Spec: standards.freedesktop.org/thumbnail-spec/latest/index.html """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from hashlib import md5 import os @@ -58,14 +57,15 @@ class ThumbnailsPlugin(BeetsPlugin): def commands(self): thumbnails_command = Subcommand("thumbnails", - help="Create album thumbnails") + help=u"Create album thumbnails") thumbnails_command.parser.add_option( - '-f', '--force', dest='force', action='store_true', default=False, - help='force regeneration of thumbnails deemed fine (existing & ' - 'recent enough)') + u'-f', u'--force', + dest='force', action='store_true', default=False, + help=u'force regeneration of thumbnails deemed fine (existing & ' + u'recent enough)') thumbnails_command.parser.add_option( - '--dolphin', dest='dolphin', action='store_true', default=False, - help="create Dolphin-compatible thumbnail information (for KDE)") + u'--dolphin', dest='dolphin', action='store_true', default=False, + help=u"create Dolphin-compatible thumbnail information (for KDE)") thumbnails_command.func = self.process_query return [thumbnails_command] @@ -84,8 +84,8 @@ class ThumbnailsPlugin(BeetsPlugin): - detect whether we'll use GIO or Python to get URIs """ if not ArtResizer.shared.local: - self._log.warning("No local image resizing capabilities, " - "cannot generate thumbnails") + self._log.warning(u"No local image resizing capabilities, " + u"cannot generate thumbnails") return False for dir in (NORMAL_DIR, LARGE_DIR): @@ -99,12 +99,12 @@ class ThumbnailsPlugin(BeetsPlugin): assert has_PIL() # since we're local self.write_metadata = write_metadata_pil tool = "PIL" - self._log.debug("using {0} to write metadata", tool) + self._log.debug(u"using {0} to write metadata", tool) uri_getter = GioURI() if not uri_getter.available: uri_getter = PathlibURI() - self._log.debug("using {0.name} to compute URIs", uri_getter) + self._log.debug(u"using {0.name} to compute URIs", uri_getter) self.get_uri = uri_getter.uri return True @@ -122,7 +122,7 @@ class ThumbnailsPlugin(BeetsPlugin): size = ArtResizer.shared.get_size(album.artpath) if not size: - self._log.warning('problem getting the picture size for {0}', + self._log.warning(u'problem getting the picture size for {0}', album.artpath) return @@ -132,9 +132,9 @@ class ThumbnailsPlugin(BeetsPlugin): wrote &= self.make_cover_thumbnail(album, 128, NORMAL_DIR) if wrote: - self._log.info('wrote thumbnail for {0}', album) + self._log.info(u'wrote thumbnail for {0}', album) else: - self._log.info('nothing to do for {0}', album) + self._log.info(u'nothing to do for {0}', album) def make_cover_thumbnail(self, album, size, target_dir): """Make a thumbnail of given size for `album` and put it in @@ -145,11 +145,11 @@ class ThumbnailsPlugin(BeetsPlugin): if os.path.exists(target) and \ os.stat(target).st_mtime > os.stat(album.artpath).st_mtime: if self.config['force']: - self._log.debug("found a suitable {1}x{1} thumbnail for {0}, " - "forcing regeneration", album, size) + self._log.debug(u"found a suitable {1}x{1} thumbnail for {0}, " + u"forcing regeneration", album, size) else: - self._log.debug("{1}x{1} thumbnail for {0} exists and is " - "recent enough", album, size) + self._log.debug(u"{1}x{1} thumbnail for {0} exists and is " + u"recent enough", album, size) return False resized = ArtResizer.shared.resize(size, album.artpath, util.syspath(target)) @@ -174,7 +174,7 @@ class ThumbnailsPlugin(BeetsPlugin): try: self.write_metadata(image_path, metadata) except Exception: - self._log.exception("could not write metadata to {0}", + self._log.exception(u"could not write metadata to {0}", util.displayable_path(image_path)) def make_dolphin_cover_thumbnail(self, album): @@ -185,7 +185,7 @@ class ThumbnailsPlugin(BeetsPlugin): with open(outfilename, 'w') as f: f.write(b"[Desktop Entry]\nIcon=./{0}".format(artfile)) f.close() - self._log.debug("Wrote file {0}", util.displayable_path(outfilename)) + self._log.debug(u"Wrote file {0}", util.displayable_path(outfilename)) def write_metadata_im(file, metadata): @@ -266,7 +266,7 @@ class GioURI(URIGetter): def uri(self, path): g_file_ptr = self.libgio.g_file_new_for_path(path) if not g_file_ptr: - raise RuntimeError("No gfile pointer received for {0}".format( + raise RuntimeError(u"No gfile pointer received for {0}".format( util.displayable_path(path))) try: @@ -277,8 +277,8 @@ class GioURI(URIGetter): self.libgio.g_object_unref(g_file_ptr) if not uri_ptr: self.libgio.g_free(uri_ptr) - raise RuntimeError("No URI received from the gfile pointer for " - "{0}".format(util.displayable_path(path))) + raise RuntimeError(u"No URI received from the gfile pointer for " + u"{0}".format(util.displayable_path(path))) try: uri = copy_c_string(uri_ptr) diff --git a/beetsplug/types.py b/beetsplug/types.py index 4c5d20a45..40e504f27 100644 --- a/beetsplug/types.py +++ b/beetsplug/types.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets.dbcore import types From c2e7d59db7a21de8d3712fc03dd5779604607a86 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:36:56 +0100 Subject: [PATCH 0528/2280] Removed import of unicode_literals from plugin web --- beetsplug/web/__init__.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 377915626..6136e3ad3 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """A Web interface to beets.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import ui @@ -264,9 +263,9 @@ class WebPlugin(BeetsPlugin): }) def commands(self): - cmd = ui.Subcommand('web', help='start a Web interface') - cmd.parser.add_option('-d', '--debug', action='store_true', - default=False, help='debug mode') + cmd = ui.Subcommand('web', help=u'start a Web interface') + cmd.parser.add_option(u'-d', u'--debug', action='store_true', + default=False, help=u'debug mode') def func(lib, opts, args): args = ui.decargs(args) @@ -278,7 +277,7 @@ class WebPlugin(BeetsPlugin): app.config['lib'] = lib # Enable CORS if required. if self.config['cors']: - self._log.info('Enabling CORS with origin: {0}', + self._log.info(u'Enabling CORS with origin: {0}', self.config['cors']) from flask.ext.cors import CORS app.config['CORS_ALLOW_HEADERS'] = "Content-Type" From a5ce7a28140a8861043ae7f8137baaf2dad913bc Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:46:37 +0100 Subject: [PATCH 0529/2280] Removed import of unicode_literals from testsuite --- test/_common.py | 23 +++++++++++------------ test/helper.py | 19 +++++++++---------- test/testall.py | 3 +-- 3 files changed, 21 insertions(+), 24 deletions(-) diff --git a/test/_common.py b/test/_common.py index 9f8b9f146..5b179ed7e 100644 --- a/test/_common.py +++ b/test/_common.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """Some common functionality for beets' test cases.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import time import sys @@ -102,11 +101,11 @@ def album(lib=None): _item_ident += 1 i = beets.library.Album( artpath=None, - albumartist='some album artist', - albumartist_sort='some sort album artist', - albumartist_credit='some album artist credit', - album='the album', - genre='the genre', + albumartist=u'some album artist', + albumartist_sort=u'some sort album artist', + albumartist_credit=u'some album artist credit', + album=u'the album', + genre=u'the genre', year=2014, month=2, day=5, @@ -170,11 +169,11 @@ class TestCase(unittest.TestCase): def assertExists(self, path): self.assertTrue(os.path.exists(path), - 'file does not exist: {!r}'.format(path)) + u'file does not exist: {!r}'.format(path)) def assertNotExists(self, path): self.assertFalse(os.path.exists(path), - 'file exists: {!r}'.format((path))) + u'file exists: {!r}'.format((path))) class LibTestCase(TestCase): @@ -226,9 +225,9 @@ class InputException(Exception): self.output = output def __str__(self): - msg = "Attempt to read with no input provided." + msg = u"Attempt to read with no input provided." if self.output is not None: - msg += " Output: %s" % self.output + msg += u" Output: %s" % self.output return msg @@ -352,5 +351,5 @@ def slow_test(unused=None): def _id(obj): return obj if 'SKIP_SLOW_TESTS' in os.environ: - return unittest.skip('test is slow') + return unittest.skip(u'test is slow') return _id diff --git a/test/helper.py b/test/helper.py index e2bc42351..9721e7b4c 100644 --- a/test/helper.py +++ b/test/helper.py @@ -31,8 +31,7 @@ information or mock the environment. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import sys import os @@ -244,7 +243,7 @@ class TestHelper(object): track_no = 0 album_item_count = item_count while album_item_count: - title = 'track {0}'.format(track_no) + title = u'track {0}'.format(track_no) src = os.path.join(_common.RSRC, 'full.mp3') dest = os.path.join(album_dir, '{0}.mp3'.format(title)) if os.path.exists(dest): @@ -527,14 +526,14 @@ def generate_album_info(album_id, track_ids): """ tracks = [generate_track_info(id) for id in track_ids] album = AlbumInfo( - album_id='album info', - album='album info', - artist='album info', - artist_id='album info', + album_id=u'album info', + album=u'album info', + artist=u'album info', + artist_id=u'album info', tracks=tracks, ) for field in ALBUM_INFO_FIELDS: - setattr(album, field, 'album info') + setattr(album, field, u'album info') return album @@ -553,11 +552,11 @@ def generate_track_info(track_id='track info', values={}): string fields are set to "track info". """ track = TrackInfo( - title='track info', + title=u'track info', track_id=track_id, ) for field in TRACK_INFO_FIELDS: - setattr(track, field, 'track info') + setattr(track, field, u'track info') for field, value in values.items(): setattr(track, field, value) return track diff --git a/test/testall.py b/test/testall.py index fa556e364..e8e1d909d 100755 --- a/test/testall.py +++ b/test/testall.py @@ -15,8 +15,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import re From 302ca94bfb6a6d2a2d154285cbe5fb9c8fd0c60a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:48:35 +0100 Subject: [PATCH 0530/2280] Removed import of unicode_literals * test/lyrics_download_samples.py * test/rsrc/beetsplug/test.py --- test/lyrics_download_samples.py | 5 ++--- test/rsrc/beetsplug/test.py | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index 3a32577f9..fcc5a4db5 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import sys @@ -45,7 +44,7 @@ def main(argv=None): """ if argv is None: argv = sys.argv - print('Fetching samples from:') + print(u'Fetching samples from:') for s in test_lyrics.GOOGLE_SOURCES + test_lyrics.DEFAULT_SOURCES: print(s['url']) url = s['url'] + s['path'] diff --git a/test/rsrc/beetsplug/test.py b/test/rsrc/beetsplug/test.py index 85c6eb0c2..669072987 100644 --- a/test/rsrc/beetsplug/test.py +++ b/test/rsrc/beetsplug/test.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from beets.plugins import BeetsPlugin from beets import ui @@ -17,7 +16,7 @@ class TestPlugin(BeetsPlugin): test.func = lambda *args: None # Used in CompletionTest - test.parser.add_option('-o', '--option', dest='my_opt') + test.parser.add_option(u'-o', u'--option', dest='my_opt') plugin = ui.Subcommand('plugin') plugin.func = lambda *args: None From 68dbbba6a03bc91dfc0bd474b1a60552e35b5aa5 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sat, 20 Feb 2016 14:57:56 +0100 Subject: [PATCH 0531/2280] Removed import of unicode_literals from tests * test_art * test_autotag --- test/test_art.py | 13 ++++++------- test/test_autotag.py | 15 +++++++-------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 7902bb213..e1c22ad19 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -15,8 +15,7 @@ """Tests for the album art fetchers.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import shutil @@ -298,10 +297,10 @@ class ArtImporterTest(UseThePlugin): self.task.is_album = True self.task.album = self.album info = AlbumInfo( - album='some album', - album_id='albumid', - artist='some artist', - artist_id='artistid', + album=u'some album', + album_id=u'albumid', + artist=u'some artist', + artist_id=u'artistid', tracks=[], ) self.task.set_choice(AlbumMatch(0, info, {}, set(), set())) @@ -439,7 +438,7 @@ class ArtForAlbumTest(UseThePlugin): PIL (so comparisons and measurements are unavailable). """ if ArtResizer.shared.method[0] == WEBPROXY: - self.skipTest("ArtResizer has no local imaging backend available") + self.skipTest(u"ArtResizer has no local imaging backend available") def test_respect_minwidth(self): self._require_backend() diff --git a/test/test_autotag.py b/test/test_autotag.py index 2aecfb559..f5f13d4a7 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -15,8 +15,7 @@ """Tests for autotagging functionality. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re import copy @@ -636,7 +635,7 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): trackinfo = [] trackinfo.append(TrackInfo( u'oneNew', - 'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', + u'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', medium=1, medium_index=1, medium_total=1, @@ -646,7 +645,7 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): )) trackinfo.append(TrackInfo( u'twoNew', - '40130ed1-a27c-42fd-a328-1ebefb6caef4', + u'40130ed1-a27c-42fd-a328-1ebefb6caef4', medium=2, medium_index=1, index=2, @@ -808,16 +807,16 @@ class ApplyCompilationTest(_common.TestCase, ApplyTestUtil): trackinfo = [] trackinfo.append(TrackInfo( u'oneNew', - 'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', + u'dfa939ec-118c-4d0f-84a0-60f3d1e6522c', u'artistOneNew', - 'a05686fc-9db2-4c23-b99e-77f5db3e5282', + u'a05686fc-9db2-4c23-b99e-77f5db3e5282', index=1, )) trackinfo.append(TrackInfo( u'twoNew', - '40130ed1-a27c-42fd-a328-1ebefb6caef4', + u'40130ed1-a27c-42fd-a328-1ebefb6caef4', u'artistTwoNew', - '80b3cf5e-18fe-4c59-98c7-e5bb87210710', + u'80b3cf5e-18fe-4c59-98c7-e5bb87210710', index=2, )) self.info = AlbumInfo( From 908f684d0a168f071b82f7e0120ded25dd19fd37 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:38:05 +0100 Subject: [PATCH 0532/2280] Removed import of unicode_literals from test_bucket --- test/test_bucket.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_bucket.py b/test/test_bucket.py index 81a5d4441..bb0be5bee 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -15,8 +15,7 @@ """Tests for the 'bucket' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from beetsplug import bucket From a94bfa9eb9125a09a0670542e0418d767c068e4d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:40:07 +0100 Subject: [PATCH 0533/2280] Removed import of unicode_literals from test_mb --- test/test_mb.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_mb.py b/test/test_mb.py index dae1003c9..f8697cefa 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -15,8 +15,7 @@ """Tests for MusicBrainz API wrapper. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test import _common from test._common import unittest From 9507bfb1e4f7785321b20239b90cdeaa0d0f890d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:42:31 +0100 Subject: [PATCH 0534/2280] Removed unicode_literals from test_lyrics --- test/test_lyrics.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index bd2e69e97..1af6f4652 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -15,8 +15,7 @@ """Tests for the 'lyrics' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os from test import _common From 1162082026fdb80e4893f4e1cc446ea1ae2c0b16 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:44:16 +0100 Subject: [PATCH 0535/2280] Removed unicode_literals from test_info --- test/test_info.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_info.py b/test/test_info.py index fdf0b3861..fe11cff51 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper From 3b83209620ad8644ec30a6779ae35a773e1060c5 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:45:39 +0100 Subject: [PATCH 0536/2280] Removed unicode_literals from test_config_command --- test/test_config_command.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_config_command.py b/test/test_config_command.py index 60cf9de25..8c5034757 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import yaml From 14fc530200a62154c97b392d9c65f2c12f80313d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 07:47:06 +0100 Subject: [PATCH 0537/2280] Removed unicode_literals from test_convert --- test/test_convert.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_convert.py b/test/test_convert.py index 72d52feaa..3c91e40b2 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import re import os.path From 59e54d1792a1c2cc06c669c7a90305d2fe5c6abd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 22 Feb 2016 00:02:58 -0800 Subject: [PATCH 0538/2280] Fix #1891: Missing `syspath` in `beet stats -e` --- beets/ui/commands.py | 2 +- docs/changelog.rst | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index bc57a5431..641b1186f 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1257,7 +1257,7 @@ def show_stats(lib, query, exact): for item in items: if exact: try: - total_size += os.path.getsize(item.path) + total_size += os.path.getsize(syspath(item.path)) except OSError as exc: log.info('could not get size of {}: {}', item.path, exc) else: diff --git a/docs/changelog.rst b/docs/changelog.rst index df54089f2..3803894b2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,10 @@ Changelog 1.3.18 (in development) ----------------------- -Changelog goes here! +Fixes: + +* Fix a problem with the :ref:`stats-cmd` in exact mode when filenames on + Windows use non-ASCII characters. :bug:`1891` 1.3.17 (February 7, 2016) From ad321079f976673daad31b0c7c58ec4f17382f9b Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:07:12 +0100 Subject: [PATCH 0539/2280] Fixed test in test_lyrics --- test/test_lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 1af6f4652..e6e068a4b 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -384,7 +384,7 @@ class LyricsGooglePluginTest(unittest.TestCase): url = s['url'] + s['path'] url_title = u'foo' - google.is_page_candidate(url, url_title, s['title'], 'Sunn O)))') + google.is_page_candidate(url, url_title, s['title'], u'Sunn O)))') def suite(): From 5fda42c8385e438d3fc2241fbbf0ffeab2b129e8 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:08:54 +0100 Subject: [PATCH 0540/2280] Removed unicode_literals from test_datequery --- test/test_datequery.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index 9ad741ee0..1c0214860 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -15,8 +15,7 @@ """Test for dbcore's date-based queries. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test import _common from test._common import unittest From bdaafdb14726dd8a54a8e98f2f740c0f0654610a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:11:21 +0100 Subject: [PATCH 0541/2280] Removed unicode_literals from test_dbcore --- test/test_dbcore.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 39b7eea1e..0a2537337 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -15,8 +15,7 @@ """Tests for the DBCore database abstraction. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import shutil @@ -313,7 +312,7 @@ class ModelTest(unittest.TestCase): def test_computed_field(self): model = TestModelWithGetters() self.assertEqual(model.aComputedField, 'thing') - with self.assertRaisesRegexp(KeyError, 'computed field .+ deleted'): + with self.assertRaisesRegexp(KeyError, u'computed field .+ deleted'): del model.aComputedField def test_items(self): @@ -329,7 +328,7 @@ class ModelTest(unittest.TestCase): model._db def test_parse_nonstring(self): - with self.assertRaisesRegexp(TypeError, "must be a string"): + with self.assertRaisesRegexp(TypeError, u"must be a string"): dbcore.Model._parse(None, 42) From 59f670a29ec7b819266442f763f1a11a634328cf Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:13:15 +0100 Subject: [PATCH 0542/2280] Removed unicode_literals form test_echonest --- test/test_echonest.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/test_echonest.py b/test/test_echonest.py index cf460e19c..a365af8ac 100644 --- a/test/test_echonest.py +++ b/test/test_echonest.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os.path from mock import Mock, patch @@ -31,7 +30,7 @@ class EchonestCliTest(unittest.TestCase, TestHelper): try: __import__('pyechonest') except ImportError: - self.skipTest('pyechonest not available') + self.skipTest(u'pyechonest not available') self.setup_beets() self.load_plugins('echonest') @@ -157,7 +156,7 @@ class EchonestCliTest(unittest.TestCase, TestHelper): def test_custom_field_range_query(self): item = Item(liveness=2.2) item.add(self.lib) - item = self.lib.items('liveness:2.2..3').get() + item = self.lib.items(u'liveness:2.2..3').get() self.assertEqual(item['liveness'], 2.2) def profile(self, item, **values): From b4d7ad1911427f5cce40e2c687036a267fcfdc4f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:20:41 +0100 Subject: [PATCH 0543/2280] Removed unicode_literals from test_edit --- test/test_edit.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 25b24cea0..1d007b285 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -12,8 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import codecs from mock import patch @@ -202,7 +201,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): # Apply changes. ['a']) - self.assertEqual(self.lib.items('id:1')[0].foo, 'bar') + self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar') self.assertCounts(write_call_count=1, title_starts_with=u't\u00eftle') @@ -249,7 +248,7 @@ class EditCommandTest(unittest.TestCase, TestHelper): """Edit the yaml file incorrectly (resulting in a well-formed but invalid yaml document).""" # edit the yaml file to an invalid file - self.run_mocked_command({'contents': 'wellformed: yes, but invalid'}, + self.run_mocked_command({'contents': u'wellformed: yes, but invalid'}, # no stdin []) From 4d1a02a5521a03ab5c90366008afeafb4456b8c2 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 09:20:54 +0100 Subject: [PATCH 0544/2280] Removed unicode_literals from test_embedart --- test/test_embedart.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 8a21f55bc..104779810 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os.path import shutil @@ -101,7 +100,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): if os.path.isfile(tmp_path): os.remove(tmp_path) - self.fail('Artwork file {0} was not deleted'.format(tmp_path)) + self.fail(u'Artwork file {0} was not deleted'.format(tmp_path)) def test_art_file_missing(self): self.add_album_fixture() @@ -114,7 +113,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): logging.getLogger('beets.embedart').setLevel(logging.DEBUG) handle, tmp_path = tempfile.mkstemp() - os.write(handle, 'I am not an image.') + os.write(handle, u'I am not an image.') os.close(handle) try: @@ -136,7 +135,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, - 'Image written is not {0}'.format( + u'Image written is not {0}'.format( self.abbey_artpath)) @require_artresizer_compare @@ -150,7 +149,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, - 'Image written is not {0}'.format( + u'Image written is not {0}'.format( self.abbey_similarpath)) def test_non_ascii_album_path(self): From fc521efb3463216175cae410ece1e6e29712e0df Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:28:43 +0100 Subject: [PATCH 0545/2280] Removed unicode_literals from test_embyupdate --- test/test_embyupdate.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index dad438491..54e67526b 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper From 690498e87d37207496c36d6ddf83fb1f2ee0d368 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:30:47 +0100 Subject: [PATCH 0546/2280] Removed unicode_literals from test_fetchart --- test/test_fetchart.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_fetchart.py b/test/test_fetchart.py index f0dda4fce..6a313b965 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os from test._common import unittest From 0fececde4c3944efe2528b0781496955a2fcdb8d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:32:36 +0100 Subject: [PATCH 0547/2280] Removed unicode_literals from test_files --- test/test_files.py | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/test/test_files.py b/test/test_files.py index 60bc8024a..a9ee239bc 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -15,8 +15,7 @@ """Test file manipulation functionality of Item. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import shutil import os @@ -73,7 +72,7 @@ class MoveTest(_common.TestCase): old_path = self.i.path self.assertExists(old_path) - self.i.artist = 'newArtist' + self.i.artist = u'newArtist' self.i.move() self.assertNotExists(old_path) self.assertNotExists(os.path.dirname(old_path)) @@ -196,7 +195,7 @@ class AlbumFileTest(_common.TestCase): self.otherdir = os.path.join(self.temp_dir, 'testotherdir') def test_albuminfo_move_changes_paths(self): - self.ai.album = 'newAlbumName' + self.ai.album = u'newAlbumName' self.ai.move() self.ai.store() self.i.load() @@ -205,7 +204,7 @@ class AlbumFileTest(_common.TestCase): def test_albuminfo_move_moves_file(self): oldpath = self.i.path - self.ai.album = 'newAlbumName' + self.ai.album = u'newAlbumName' self.ai.move() self.ai.store() self.i.load() @@ -215,7 +214,7 @@ class AlbumFileTest(_common.TestCase): def test_albuminfo_move_copies_file(self): oldpath = self.i.path - self.ai.album = 'newAlbumName' + self.ai.album = u'newAlbumName' self.ai.move(True) self.ai.store() self.i.load() @@ -261,7 +260,7 @@ class ArtFileTest(_common.TestCase): def test_art_moves_with_album(self): self.assertTrue(os.path.exists(self.art)) oldpath = self.i.path - self.ai.album = 'newAlbum' + self.ai.album = u'newAlbum' self.ai.move() self.i.load() @@ -289,7 +288,7 @@ class ArtFileTest(_common.TestCase): touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) i2.move(True) @@ -305,7 +304,7 @@ class ArtFileTest(_common.TestCase): touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) i2.move(True) ai.set_art(newart) @@ -319,7 +318,7 @@ class ArtFileTest(_common.TestCase): touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) i2.move(True) @@ -336,7 +335,7 @@ class ArtFileTest(_common.TestCase): touch(newart) i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) i2.move(True) @@ -360,7 +359,7 @@ class ArtFileTest(_common.TestCase): try: i2 = item() i2.path = self.i.path - i2.artist = 'someArtist' + i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) i2.move(True) ai.set_art(newart) @@ -378,12 +377,12 @@ class ArtFileTest(_common.TestCase): oldartpath = self.lib.albums()[0].artpath self.assertExists(oldartpath) - self.ai.album = 'different_album' + self.ai.album = u'different_album' self.ai.store() self.ai.items()[0].move() artpath = self.lib.albums()[0].artpath - self.assertTrue('different_album' in artpath) + self.assertTrue(u'different_album' in artpath) self.assertExists(artpath) self.assertNotExists(oldartpath) @@ -395,12 +394,12 @@ class ArtFileTest(_common.TestCase): oldartpath = self.lib.albums()[0].artpath self.assertExists(oldartpath) - self.i.album = 'different_album' + self.i.album = u'different_album' self.i.album_id = None # detach from album self.i.move() artpath = self.lib.albums()[0].artpath - self.assertFalse('different_album' in artpath) + self.assertFalse(u'different_album' in artpath) self.assertEqual(artpath, oldartpath) self.assertExists(oldartpath) @@ -481,7 +480,7 @@ class SoftRemoveTest(_common.TestCase): try: util.remove(self.path + 'XXX', True) except OSError: - self.fail('OSError when removing path') + self.fail(u'OSError when removing path') class SafeMoveCopyTest(_common.TestCase): From e1356be8378f68ec141704d8ac240fee8b6a10f3 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:34:21 +0100 Subject: [PATCH 0548/2280] Removed unicode_literals from test_ftintitle --- test/test_ftintitle.py | 53 +++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index 481917f85..caecdfd27 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -15,8 +15,7 @@ """Tests for the 'ftintitle' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper @@ -150,33 +149,33 @@ class FtInTitlePluginTest(unittest.TestCase): self.assertEqual(feat_part, test_case['feat_part']) def test_split_on_feat(self): - parts = ftintitle.split_on_feat('Alice ft. Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice feat Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice feat. Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice featuring Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice & Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice and Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice With Bob') - self.assertEqual(parts, ('Alice', 'Bob')) - parts = ftintitle.split_on_feat('Alice defeat Bob') - self.assertEqual(parts, ('Alice defeat Bob', None)) + parts = ftintitle.split_on_feat(u'Alice ft. Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice feat Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice feat. Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice featuring Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice & Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice and Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice With Bob') + self.assertEqual(parts, (u'Alice', u'Bob')) + parts = ftintitle.split_on_feat(u'Alice defeat Bob') + self.assertEqual(parts, (u'Alice defeat Bob', None)) def test_contains_feat(self): - self.assertTrue(ftintitle.contains_feat('Alice ft. Bob')) - self.assertTrue(ftintitle.contains_feat('Alice feat. Bob')) - self.assertTrue(ftintitle.contains_feat('Alice feat Bob')) - self.assertTrue(ftintitle.contains_feat('Alice featuring Bob')) - self.assertTrue(ftintitle.contains_feat('Alice & Bob')) - self.assertTrue(ftintitle.contains_feat('Alice and Bob')) - self.assertTrue(ftintitle.contains_feat('Alice With Bob')) - self.assertFalse(ftintitle.contains_feat('Alice defeat Bob')) - self.assertFalse(ftintitle.contains_feat('Aliceft.Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice ft. Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice feat. Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice feat Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice featuring Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice & Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice and Bob')) + self.assertTrue(ftintitle.contains_feat(u'Alice With Bob')) + self.assertFalse(ftintitle.contains_feat(u'Alice defeat Bob')) + self.assertFalse(ftintitle.contains_feat(u'Aliceft.Bob')) def suite(): From 99f6457a8f41bd288b699c4f304a688984db94b2 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:36:52 +0100 Subject: [PATCH 0549/2280] Removed unicode_literals from test_ihate --- test/test_ihate.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/test/test_ihate.py b/test/test_ihate.py index 1ce4800b9..663e93d2c 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -2,8 +2,7 @@ """Tests for the 'ihate' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from beets import importer @@ -17,7 +16,7 @@ class IHatePluginTest(unittest.TestCase): match_pattern = {} test_item = Item( - genre='TestGenre', + genre=u'TestGenre', album=u'TestAlbum', artist=u'TestArtist') task = importer.SingletonImportTask(None, test_item) @@ -26,25 +25,25 @@ class IHatePluginTest(unittest.TestCase): self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # 1 query match. - match_pattern = ["artist:bad_artist", "artist:TestArtist"] + match_pattern = [u"artist:bad_artist", u"artist:TestArtist"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) # 2 query matches, either should trigger. - match_pattern = ["album:test", "artist:testartist"] + match_pattern = [u"album:test", u"artist:testartist"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) # Query is blocked by AND clause. - match_pattern = ["album:notthis genre:testgenre"] + match_pattern = [u"album:notthis genre:testgenre"] self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # Both queries are blocked by AND clause with unmatched condition. - match_pattern = ["album:notthis genre:testgenre", - "artist:testartist album:notthis"] + match_pattern = [u"album:notthis genre:testgenre", + u"artist:testartist album:notthis"] self.assertFalse(IHatePlugin.do_i_hate_this(task, match_pattern)) # Only one query should fire. - match_pattern = ["album:testalbum genre:testgenre", - "artist:testartist album:notthis"] + match_pattern = [u"album:testalbum genre:testgenre", + u"artist:testartist album:notthis"] self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern)) From c39a8ce652f63b3eb0f87755b87a45a52c824b4f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:37:11 +0100 Subject: [PATCH 0550/2280] Removed unicode_literals from test_importadded --- test/test_importadded.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/test_importadded.py b/test/test_importadded.py index b8801da60..1dcddbc75 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Tests for the `importadded` plugin.""" @@ -73,7 +72,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): for m in self.media_files: if m.title.replace('Tag', 'Applied') == item.title: return m - raise AssertionError("No MediaFile found for Item " + + raise AssertionError(u"No MediaFile found for Item " + util.displayable_path(item.path)) def assertEqualTimes(self, first, second, msg=None): @@ -127,7 +126,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): for item in album.items()) for item_path, added_after in items_added_after.iteritems(): self.assertEqualTimes(items_added_before[item_path], added_after, - "reimport modified Item.added for " + + u"reimport modified Item.added for " + item_path) def test_import_singletons_with_added_dates(self): @@ -165,7 +164,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): for item in self.lib.items()) for item_path, added_after in items_added_after.iteritems(): self.assertEqualTimes(items_added_before[item_path], added_after, - "reimport modified Item.added for " + + u"reimport modified Item.added for " + item_path) From df0d51ea869953014b020f3a28308790a8018826 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:53:40 +0100 Subject: [PATCH 0551/2280] Removed unicode_literals from test_keyfinder --- test/test_keyfinder.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 898bc566e..a9c2e85d5 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from mock import patch from test._common import unittest From d3d02e18b9fcead81721fcd6b390cdd747106935 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Mon, 22 Feb 2016 16:56:02 +0100 Subject: [PATCH 0552/2280] Removed unicode_literals from test_lastgenere --- test/test_lastgenre.py | 49 +++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 9f61107e9..c9aec1fd5 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -15,8 +15,7 @@ """Tests for the 'lastgenre' plugin.""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from mock import Mock @@ -52,7 +51,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config() self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Delta Blues') + u'Delta Blues') def test_c14n_only(self): """Default c14n tree funnels up to most common genre except for *wrong* @@ -60,16 +59,16 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical=True, count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Blues') + u'Blues') self.assertEqual(self.plugin._resolve_genres(['iota blues']), - 'Iota Blues') + u'Iota Blues') def test_whitelist_only(self): """Default whitelist rejects *wrong* (non existing) genres. """ self._setup_config(whitelist=True) self.assertEqual(self.plugin._resolve_genres(['iota blues']), - '') + u'') def test_whitelist_c14n(self): """Default whitelist and c14n both activated result in all parents @@ -77,7 +76,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical=True, whitelist=True, count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Delta Blues, Blues') + u'Delta Blues, Blues') def test_whitelist_custom(self): """Keep only genres that are in the whitelist. @@ -85,11 +84,11 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self._setup_config(whitelist=set(['blues', 'rock', 'jazz']), count=2) self.assertEqual(self.plugin._resolve_genres(['pop', 'blues']), - 'Blues') + u'Blues') self._setup_config(canonical='', whitelist=set(['rock'])) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - '') + u'') def test_count(self): """Keep the n first genres, as we expect them to be sorted from more to @@ -99,7 +98,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): count=2) self.assertEqual(self.plugin._resolve_genres( ['jazz', 'pop', 'rock', 'blues']), - 'Jazz, Rock') + u'Jazz, Rock') def test_count_c14n(self): """Keep the n first genres, after having applied c14n when necessary @@ -111,14 +110,14 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): # second slot self.assertEqual(self.plugin._resolve_genres( ['jazz', 'pop', 'country blues', 'rock']), - 'Jazz, Blues') + u'Jazz, Blues') def test_c14n_whitelist(self): """Genres first pass through c14n and are then filtered """ self._setup_config(canonical=True, whitelist=set(['rock'])) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - '') + u'') def test_empty_string_enables_canonical(self): """For backwards compatibility, setting the `canonical` option @@ -126,7 +125,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(canonical='', count=99) self.assertEqual(self.plugin._resolve_genres(['delta blues']), - 'Blues') + u'Blues') def test_empty_string_enables_whitelist(self): """Again for backwards compatibility, setting the `whitelist` @@ -134,14 +133,14 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): """ self._setup_config(whitelist='') self.assertEqual(self.plugin._resolve_genres(['iota blues']), - '') + u'') def test_no_duplicate(self): """Remove duplicated genres. """ self._setup_config(count=99) self.assertEqual(self.plugin._resolve_genres(['blues', 'blues']), - 'Blues') + u'Blues') def test_tags_for(self): class MockPylastElem(object): @@ -189,29 +188,29 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): config['lastgenre'] = {'force': False} res = self.plugin._get_genre(item) - self.assertEqual(res, (item.genre, 'keep')) + self.assertEqual(res, (item.genre, u'keep')) - config['lastgenre'] = {'force': True, 'source': 'track'} + config['lastgenre'] = {'force': True, 'source': u'track'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['track'], 'track')) + self.assertEqual(res, (MOCK_GENRES['track'], u'track')) - config['lastgenre'] = {'source': 'album'} + config['lastgenre'] = {'source': u'album'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['album'], 'album')) + self.assertEqual(res, (MOCK_GENRES['album'], u'album')) - config['lastgenre'] = {'source': 'artist'} + config['lastgenre'] = {'source': u'artist'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['artist'], 'artist')) + self.assertEqual(res, (MOCK_GENRES['artist'], u'artist')) MOCK_GENRES['artist'] = None res = self.plugin._get_genre(item) - self.assertEqual(res, (item.genre, 'original')) + self.assertEqual(res, (item.genre, u'original')) - config['lastgenre'] = {'fallback': 'rap'} + config['lastgenre'] = {'fallback': u'rap'} item.genre = None res = self.plugin._get_genre(item) self.assertEqual(res, (config['lastgenre']['fallback'].get(), - 'fallback')) + u'fallback')) def suite(): From 5abe1fdd9bd42b262baa532591ed2c234fbe455f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 07:34:44 +0100 Subject: [PATCH 0553/2280] Removed unicode_literals from test_web --- test/test_web.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/test/test_web.py b/test/test_web.py index 0299e82d4..2bf1b4ab5 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -2,8 +2,7 @@ """Tests for the 'web' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test import _common @@ -22,10 +21,10 @@ class WebPluginTest(_common.LibTestCase): # Add fixtures for track in self.lib.items(): track.remove() - self.lib.add(Item(title='title', path='', id=1)) - self.lib.add(Item(title='another title', path='', id=2)) - self.lib.add(Album(album='album', id=3)) - self.lib.add(Album(album='another album', id=4)) + self.lib.add(Item(title=u'title', path='', id=1)) + self.lib.add(Item(title=u'another title', path='', id=2)) + self.lib.add(Album(album=u'album', id=3)) + self.lib.add(Album(album=u'another album', id=4)) web.app.config['TESTING'] = True web.app.config['lib'] = self.lib @@ -44,7 +43,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(response.json['id'], 1) - self.assertEqual(response.json['title'], 'title') + self.assertEqual(response.json['title'], u'title') def test_get_multiple_items_by_id(self): response = self.client.get('/item/1,2') @@ -53,7 +52,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['items']), 2) response_titles = [item['title'] for item in response.json['items']] - self.assertItemsEqual(response_titles, ['title', 'another title']) + self.assertItemsEqual(response_titles, [u'title', u'another title']) def test_get_single_item_not_found(self): response = self.client.get('/item/3') @@ -72,7 +71,8 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['results']), 1) - self.assertEqual(response.json['results'][0]['title'], 'another title') + self.assertEqual(response.json['results'][0]['title'], + u'another title') def test_get_all_albums(self): response = self.client.get('/album/') @@ -80,7 +80,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, ['album', 'another album']) + self.assertItemsEqual(response_albums, [u'album', u'another album']) def test_get_single_album_by_id(self): response = self.client.get('/album/2') @@ -88,7 +88,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(response.json['id'], 2) - self.assertEqual(response.json['album'], 'another album') + self.assertEqual(response.json['album'], u'another album') def test_get_multiple_albums_by_id(self): response = self.client.get('/album/1,2') @@ -96,7 +96,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, ['album', 'another album']) + self.assertItemsEqual(response_albums, [u'album', u'another album']) def test_get_album_empty_query(self): response = self.client.get('/album/query/') From a627fd45d5b07d6e4dd30adb979cff071f74d816 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 07:37:23 +0100 Subject: [PATCH 0554/2280] Removed unicode_literals from test_the --- test/test_the.py | 66 ++++++++++++++++++++++++------------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/test/test_the.py b/test/test_the.py index 9cfb34d63..d63faad57 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -2,8 +2,7 @@ """Tests for the 'the' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test import _common @@ -14,51 +13,52 @@ from beetsplug.the import ThePlugin, PATTERN_A, PATTERN_THE, FORMAT class ThePluginTest(_common.TestCase): def test_unthe_with_default_patterns(self): - self.assertEqual(ThePlugin().unthe('', PATTERN_THE), '') - self.assertEqual(ThePlugin().unthe('The Something', PATTERN_THE), - 'Something, The') - self.assertEqual(ThePlugin().unthe('The The', PATTERN_THE), - 'The, The') - self.assertEqual(ThePlugin().unthe('The The', PATTERN_THE), - 'The, The') - self.assertEqual(ThePlugin().unthe('The The X', PATTERN_THE), - 'The X, The') - self.assertEqual(ThePlugin().unthe('the The', PATTERN_THE), - 'The, the') - self.assertEqual(ThePlugin().unthe('Protected The', PATTERN_THE), - 'Protected The') - self.assertEqual(ThePlugin().unthe('A Boy', PATTERN_A), - 'Boy, A') - self.assertEqual(ThePlugin().unthe('a girl', PATTERN_A), - 'girl, a') - self.assertEqual(ThePlugin().unthe('An Apple', PATTERN_A), - 'Apple, An') - self.assertEqual(ThePlugin().unthe('An A Thing', PATTERN_A), - 'A Thing, An') - self.assertEqual(ThePlugin().unthe('the An Arse', PATTERN_A), - 'the An Arse') + self.assertEqual(ThePlugin().unthe(u'', PATTERN_THE), '') + self.assertEqual(ThePlugin().unthe(u'The Something', PATTERN_THE), + u'Something, The') + self.assertEqual(ThePlugin().unthe(u'The The', PATTERN_THE), + u'The, The') + self.assertEqual(ThePlugin().unthe(u'The The', PATTERN_THE), + u'The, The') + self.assertEqual(ThePlugin().unthe(u'The The X', PATTERN_THE), + u'The X, The') + self.assertEqual(ThePlugin().unthe(u'the The', PATTERN_THE), + u'The, the') + self.assertEqual(ThePlugin().unthe(u'Protected The', PATTERN_THE), + u'Protected The') + self.assertEqual(ThePlugin().unthe(u'A Boy', PATTERN_A), + u'Boy, A') + self.assertEqual(ThePlugin().unthe(u'a girl', PATTERN_A), + u'girl, a') + self.assertEqual(ThePlugin().unthe(u'An Apple', PATTERN_A), + u'Apple, An') + self.assertEqual(ThePlugin().unthe(u'An A Thing', PATTERN_A), + u'A Thing, An') + self.assertEqual(ThePlugin().unthe(u'the An Arse', PATTERN_A), + u'the An Arse') def test_unthe_with_strip(self): config['the']['strip'] = True - self.assertEqual(ThePlugin().unthe('The Something', PATTERN_THE), - 'Something') - self.assertEqual(ThePlugin().unthe('An A', PATTERN_A), 'A') + self.assertEqual(ThePlugin().unthe(u'The Something', PATTERN_THE), + u'Something') + self.assertEqual(ThePlugin().unthe(u'An A', PATTERN_A), u'A') def test_template_function_with_defaults(self): ThePlugin().patterns = [PATTERN_THE, PATTERN_A] - self.assertEqual(ThePlugin().the_template_func('The The'), 'The, The') - self.assertEqual(ThePlugin().the_template_func('An A'), 'A, An') + self.assertEqual(ThePlugin().the_template_func(u'The The'), + u'The, The') + self.assertEqual(ThePlugin().the_template_func(u'An A'), u'A, An') def test_custom_pattern(self): config['the']['patterns'] = [u'^test\s'] config['the']['format'] = FORMAT - self.assertEqual(ThePlugin().the_template_func('test passed'), - 'passed, test') + self.assertEqual(ThePlugin().the_template_func(u'test passed'), + u'passed, test') def test_custom_format(self): config['the']['patterns'] = [PATTERN_THE, PATTERN_A] config['the']['format'] = u'{1} ({0})' - self.assertEqual(ThePlugin().the_template_func('The A'), 'The (A)') + self.assertEqual(ThePlugin().the_template_func(u'The A'), u'The (A)') def suite(): From 7135fac17bc4fea1f92ae9320527005a26d02abc Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:10:08 +0100 Subject: [PATCH 0555/2280] Removed unicode_literals from test_importfeeds --- test/test_importfeeds.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index 276a26ff2..4ae460c68 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import os.path From 955eae46c65fcb526d6a8392d28f04fb1c57d0fb Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:27:30 +0100 Subject: [PATCH 0556/2280] Removed unicode_literals from test_logging --- test/test_logging.py | 87 ++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/test/test_logging.py b/test/test_logging.py index a3fe363b9..2c2f473c2 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -1,8 +1,7 @@ # -*- coding: utf-8 -*- """Stupid tests that ensure logging works as expected""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import sys import threading @@ -45,9 +44,9 @@ class LoggingTest(TestCase): l.addHandler(handler) l.propagate = False - l.warning("foo {0} {bar}", "oof", bar="baz") + l.warning(u"foo {0} {bar}", "oof", bar=u"baz") handler.flush() - self.assertTrue(stream.getvalue(), "foo oof baz") + self.assertTrue(stream.getvalue(), u"foo oof baz") class LoggingLevelTest(unittest.TestCase, helper.TestHelper): @@ -59,9 +58,9 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.register_listener('dummy_event', self.listener) def log_all(self, name): - self._log.debug('debug ' + name) - self._log.info('info ' + name) - self._log.warning('warning ' + name) + self._log.debug(u'debug ' + name) + self._log.info(u'info ' + name) + self._log.warning(u'warning ' + name) def commands(self): cmd = ui.Subcommand('dummy') @@ -92,76 +91,76 @@ class LoggingLevelTest(unittest.TestCase, helper.TestHelper): self.config['verbose'] = 0 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertNotIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertNotIn(u'dummy: debug cmd', logs) def test_command_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertIn(u'dummy: debug cmd', logs) def test_command_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: self.run_command('dummy') - self.assertIn('dummy: warning cmd', logs) - self.assertIn('dummy: info cmd', logs) - self.assertIn('dummy: debug cmd', logs) + self.assertIn(u'dummy: warning cmd', logs) + self.assertIn(u'dummy: info cmd', logs) + self.assertIn(u'dummy: debug cmd', logs) def test_listener_level0(self): self.config['verbose'] = 0 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertNotIn('dummy: info listener', logs) - self.assertNotIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertNotIn(u'dummy: info listener', logs) + self.assertNotIn(u'dummy: debug listener', logs) def test_listener_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertIn('dummy: info listener', logs) - self.assertNotIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertIn(u'dummy: info listener', logs) + self.assertNotIn(u'dummy: debug listener', logs) def test_listener_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: plugins.send('dummy_event') - self.assertIn('dummy: warning listener', logs) - self.assertIn('dummy: info listener', logs) - self.assertIn('dummy: debug listener', logs) + self.assertIn(u'dummy: warning listener', logs) + self.assertIn(u'dummy: info listener', logs) + self.assertIn(u'dummy: debug listener', logs) def test_import_stage_level0(self): self.config['verbose'] = 0 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertNotIn('dummy: info import_stage', logs) - self.assertNotIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertNotIn(u'dummy: info import_stage', logs) + self.assertNotIn(u'dummy: debug import_stage', logs) def test_import_stage_level1(self): self.config['verbose'] = 1 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertIn('dummy: info import_stage', logs) - self.assertNotIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertIn(u'dummy: info import_stage', logs) + self.assertNotIn(u'dummy: debug import_stage', logs) def test_import_stage_level2(self): self.config['verbose'] = 2 with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn('dummy: warning import_stage', logs) - self.assertIn('dummy: info import_stage', logs) - self.assertIn('dummy: debug import_stage', logs) + self.assertIn(u'dummy: warning import_stage', logs) + self.assertIn(u'dummy: info import_stage', logs) + self.assertIn(u'dummy: debug import_stage', logs) @_common.slow_test() @@ -182,9 +181,9 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): self.t1_step = self.t2_step = 0 def log_all(self, name): - self._log.debug('debug ' + name) - self._log.info('info ' + name) - self._log.warning('warning ' + name) + self._log.debug(u'debug ' + name) + self._log.info(u'info ' + name) + self._log.warning(u'warning ' + name) def listener1(self): try: @@ -257,14 +256,14 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): self.assertFalse(t2.is_alive()) except: - print("Alive threads:", threading.enumerate()) + print(u"Alive threads:", threading.enumerate()) if dp.lock1.locked(): - print("Releasing lock1 after exception in test") + print(u"Releasing lock1 after exception in test") dp.lock1.release() if dp.lock2.locked(): - print("Releasing lock2 after exception in test") + print(u"Releasing lock2 after exception in test") dp.lock2.release() - print("Alive threads:", threading.enumerate()) + print(u"Alive threads:", threading.enumerate()) raise def test_root_logger_levels(self): @@ -283,14 +282,14 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): importer = self.create_importer() importer.run() for l in logs: - self.assertIn("import", l) - self.assertIn("album", l) + self.assertIn(u"import", l) + self.assertIn(u"album", l) blog.getLogger('beets').set_global_level(blog.DEBUG) with helper.capture_log() as logs: importer = self.create_importer() importer.run() - self.assertIn("Sending event: database_change", logs) + self.assertIn(u"Sending event: database_change", logs) def suite(): From cc50f41c3651fd28011348d47748f8f679388655 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:28:38 +0100 Subject: [PATCH 0557/2280] Removed unicode_literals from test_mbsubmit --- test/test_mbsubmit.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index 808af9d8c..d11bdf020 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import capture_stdout, control_stdin, TestHelper @@ -46,9 +45,9 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, self.importer.run() # Manually build the string for comparing the output. - tracklist = ('Print tracks? ' - '01. Tag Title 1 - Tag Artist (0:01)\n' - '02. Tag Title 2 - Tag Artist (0:01)') + tracklist = (u'Print tracks? ' + u'01. Tag Title 1 - Tag Artist (0:01)\n' + u'02. Tag Title 2 - Tag Artist (0:01)') self.assertIn(tracklist, output.getvalue()) def test_print_tracks_output_as_tracks(self): @@ -61,8 +60,8 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, self.importer.run() # Manually build the string for comparing the output. - tracklist = ('Print tracks? ' - '02. Tag Title 2 - Tag Artist (0:01)') + tracklist = (u'Print tracks? ' + u'02. Tag Title 2 - Tag Artist (0:01)') self.assertIn(tracklist, output.getvalue()) From 2ac27e72a6377825717d7461b7ab7d29e376b8f5 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:30:23 +0100 Subject: [PATCH 0558/2280] Removed unicode_literals from test_mbsync --- test/test_mbsync.py | 49 ++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/test/test_mbsync.py b/test/test_mbsync.py index 1cfdf96a1..bb231d6d2 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from mock import patch @@ -44,20 +43,20 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): album_for_mbid.return_value = \ generate_album_info('album id', ['track id']) track_for_mbid.return_value = \ - generate_track_info('singleton track id', - {'title': 'singleton info'}) + generate_track_info(u'singleton track id', + {'title': u'singleton info'}) album_item = Item( - album='old title', - mb_albumid='album id', - mb_trackid='track id', + album=u'old title', + mb_albumid=u'album id', + mb_trackid=u'track id', path='' ) album = self.lib.add_album([album_item]) item = Item( - title='old title', - mb_trackid='singleton track id', + title=u'old title', + mb_trackid=u'singleton track id', path='', ) self.lib.add(item) @@ -65,24 +64,24 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): self.run_command('mbsync') item.load() - self.assertEqual(item.title, 'singleton info') + self.assertEqual(item.title, u'singleton info') album_item.load() - self.assertEqual(album_item.title, 'track info') + self.assertEqual(album_item.title, u'track info') album.load() - self.assertEqual(album.album, 'album info') + self.assertEqual(album.album, u'album info') def test_message_when_skipping(self): - config['format_item'] = '$artist - $album - $title' - config['format_album'] = '$albumartist - $album' + config['format_item'] = u'$artist - $album - $title' + config['format_album'] = u'$albumartist - $album' # Test album with no mb_albumid. # The default format for an album include $albumartist so # set that here, too. album_invalid = Item( - albumartist='album info', - album='album info', + albumartist=u'album info', + album=u'album info', path='' ) self.lib.add_album([album_invalid]) @@ -90,14 +89,14 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): # default format with capture_log('beets.mbsync') as logs: self.run_command('mbsync') - e = 'mbsync: Skipping album with no mb_albumid: ' + \ - 'album info - album info' + e = u'mbsync: Skipping album with no mb_albumid: ' + \ + u'album info - album info' self.assertEqual(e, logs[0]) # custom format with capture_log('beets.mbsync') as logs: self.run_command('mbsync', '-f', "'$album'") - e = "mbsync: Skipping album with no mb_albumid: 'album info'" + e = u"mbsync: Skipping album with no mb_albumid: 'album info'" self.assertEqual(e, logs[0]) # restore the config @@ -108,9 +107,9 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): # The default singleton format includes $artist and $album # so we need to stub them here item_invalid = Item( - artist='album info', - album='album info', - title='old title', + artist=u'album info', + album=u'album info', + title=u'old title', path='', ) self.lib.add(item_invalid) @@ -118,14 +117,14 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): # default format with capture_log('beets.mbsync') as logs: self.run_command('mbsync') - e = 'mbsync: Skipping singleton with no mb_trackid: ' + \ - 'album info - album info - old title' + e = u'mbsync: Skipping singleton with no mb_trackid: ' + \ + u'album info - album info - old title' self.assertEqual(e, logs[0]) # custom format with capture_log('beets.mbsync') as logs: self.run_command('mbsync', '-f', "'$title'") - e = "mbsync: Skipping singleton with no mb_trackid: 'old title'" + e = u"mbsync: Skipping singleton with no mb_trackid: 'old title'" self.assertEqual(e, logs[0]) From 00a8ffe49b2f34248a948020076249ee02a5ee5c Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:35:14 +0100 Subject: [PATCH 0559/2280] Removed unicode_literals from test_mediafile --- test/test_mediafile.py | 83 +++++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 42 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index ed5680982..94085210d 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -16,8 +16,7 @@ """Automatically-generated blanket testing for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import shutil @@ -109,18 +108,18 @@ class ImageStructureTestMixin(ArtTestMixin): image = next(i for i in mediafile.images if i.mime_type == 'image/png') self.assertEqual(image.data, self.png_data) - self.assertExtendedImageAttributes(image, desc='album cover', + self.assertExtendedImageAttributes(image, desc=u'album cover', type=ImageType.front) image = next(i for i in mediafile.images if i.mime_type == 'image/jpeg') self.assertEqual(image.data, self.jpg_data) - self.assertExtendedImageAttributes(image, desc='the artist', + self.assertExtendedImageAttributes(image, desc=u'the artist', type=ImageType.artist) def test_set_image_structure(self): mediafile = self._mediafile_fixture('empty') - image = Image(data=self.png_data, desc='album cover', + image = Image(data=self.png_data, desc=u'album cover', type=ImageType.front) mediafile.images = [image] mediafile.save() @@ -131,14 +130,14 @@ class ImageStructureTestMixin(ArtTestMixin): image = mediafile.images[0] self.assertEqual(image.data, self.png_data) self.assertEqual(image.mime_type, 'image/png') - self.assertExtendedImageAttributes(image, desc='album cover', + self.assertExtendedImageAttributes(image, desc=u'album cover', type=ImageType.front) def test_add_image_structure(self): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) - image = Image(data=self.png_data, desc='the composer', + image = Image(data=self.png_data, desc=u'the composer', type=ImageType.composer) mediafile.images += [image] mediafile.save() @@ -146,10 +145,10 @@ class ImageStructureTestMixin(ArtTestMixin): mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) - images = (i for i in mediafile.images if i.desc == 'the composer') + images = (i for i in mediafile.images if i.desc == u'the composer') image = next(images, None) self.assertExtendedImageAttributes( - image, desc='the composer', type=ImageType.composer + image, desc=u'the composer', type=ImageType.composer ) def test_delete_image_structures(self): @@ -166,7 +165,7 @@ class ImageStructureTestMixin(ArtTestMixin): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) cover = CoverArtField.guess_cover_image(mediafile.images) - self.assertEqual(cover.desc, 'album cover') + self.assertEqual(cover.desc, u'album cover') self.assertEqual(mediafile.art, cover.data) def assertExtendedImageAttributes(self, image, **kwargs): @@ -186,7 +185,7 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): mediafile = self._mediafile_fixture('image') self.assertEqual(len(mediafile.images), 2) - image = Image(data=self.tiff_data, desc='the composer', + image = Image(data=self.tiff_data, desc=u'the composer', type=ImageType.composer) mediafile.images += [image] mediafile.save() @@ -198,14 +197,14 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): image = filter(lambda i: i.mime_type == 'image/tiff', mediafile.images)[0] self.assertExtendedImageAttributes( - image, desc='the composer', type=ImageType.composer) + image, desc=u'the composer', type=ImageType.composer) class LazySaveTestMixin(object): """Mediafile should only write changes when tags have changed """ - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_unmodified(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) @@ -214,7 +213,7 @@ class LazySaveTestMixin(object): mediafile.save() self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_same_tag_value(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) @@ -233,14 +232,14 @@ class LazySaveTestMixin(object): mediafile.save() self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_tag_value_change(self): mediafile = self._mediafile_fixture('full') mtime = self._set_past_mtime(mediafile.path) self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) mediafile.title = mediafile.title - mediafile.album = 'another' + mediafile.album = u'another' mediafile.save() self.assertNotEqual(os.stat(mediafile.path).st_mtime, mtime) @@ -249,7 +248,7 @@ class LazySaveTestMixin(object): mtime = self._set_past_mtime(mediafile.path) self.assertEqual(os.stat(mediafile.path).st_mtime, mtime) - mediafile.update({'title': mediafile.title, 'album': 'another'}) + mediafile.update({'title': mediafile.title, 'album': u'another'}) mediafile.save() self.assertNotEqual(os.stat(mediafile.path).st_mtime, mtime) @@ -273,7 +272,7 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertItemsEqual(mediafile.genres, ['one', 'two']) + self.assertItemsEqual(mediafile.genres, [u'one', u'two']) def test_write_genre_list_get_first(self): mediafile = self._mediafile_fixture('empty') @@ -281,11 +280,11 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.genre, 'one') + self.assertEqual(mediafile.genre, u'one') def test_append_genre_list(self): mediafile = self._mediafile_fixture('full') - self.assertEqual(mediafile.genre, 'the genre') + self.assertEqual(mediafile.genre, u'the genre') mediafile.genres += [u'another'] mediafile.save() @@ -308,11 +307,11 @@ class ExtendedFieldTestMixin(object): plugin.add_media_field('customtag', field_extension) mediafile = self._mediafile_fixture('empty') - mediafile.customtag = 'F#' + mediafile.customtag = u'F#' mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, 'F#') + self.assertEqual(mediafile.customtag, u'F#') delattr(MediaFile, 'customtag') Item._media_fields.remove('customtag') @@ -323,10 +322,10 @@ class ExtendedFieldTestMixin(object): mediafile = self._mediafile_fixture('empty') self.assertIsNone(mediafile.customtag) - item = Item(path=mediafile.path, customtag='Gb') + item = Item(path=mediafile.path, customtag=u'Gb') item.write() mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, 'Gb') + self.assertEqual(mediafile.customtag, u'Gb') delattr(MediaFile, 'customtag') Item._media_fields.remove('customtag') @@ -336,11 +335,11 @@ class ExtendedFieldTestMixin(object): plugin.add_media_field('customtag', field_extension) mediafile = self._mediafile_fixture('empty') - mediafile.update({'customtag': 'F#'}) + mediafile.update({'customtag': u'F#'}) mediafile.save() item = Item.from_path(mediafile.path) - self.assertEqual(item['customtag'], 'F#') + self.assertEqual(item['customtag'], u'F#') delattr(MediaFile, 'customtag') Item._media_fields.remove('customtag') @@ -348,13 +347,13 @@ class ExtendedFieldTestMixin(object): def test_invalid_descriptor(self): with self.assertRaises(ValueError) as cm: MediaFile.add_field('somekey', True) - self.assertIn('must be an instance of MediaField', + self.assertIn(u'must be an instance of MediaField', unicode(cm.exception)) def test_overwrite_property(self): with self.assertRaises(ValueError) as cm: MediaFile.add_field('artist', MediaField()) - self.assertIn('property "artist" already exists', + self.assertIn(u'property "artist" already exists', unicode(cm.exception)) @@ -667,12 +666,12 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, try: value2 = getattr(mediafile, key) except AttributeError: - errors.append('Tag %s does not exist' % key) + errors.append(u'Tag %s does not exist' % key) else: if value2 != value: - errors.append('Tag %s: %r != %r' % (key, value2, value)) + errors.append(u'Tag %s: %r != %r' % (key, value2, value)) if any(errors): - errors = ['Tags did not match'] + errors + errors = [u'Tags did not match'] + errors self.fail('\n '.join(errors)) def _mediafile_fixture(self, name): @@ -788,7 +787,7 @@ class MusepackTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 23458, - 'format': 'Musepack', + 'format': u'Musepack', 'samplerate': 44100, 'bitdepth': 0, 'channels': 2, @@ -801,7 +800,7 @@ class WMATest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 128000, - 'format': 'Windows Media', + 'format': u'Windows Media', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -818,9 +817,9 @@ class WMATest(ReadWriteTestBase, ExtendedImageStructureTestMixin, def test_read_pure_tags(self): mediafile = self._mediafile_fixture('pure') - self.assertEqual(mediafile.comments, 'the comments') - self.assertEqual(mediafile.title, 'the title') - self.assertEqual(mediafile.artist, 'the artist') + self.assertEqual(mediafile.comments, u'the comments') + self.assertEqual(mediafile.title, u'the title') + self.assertEqual(mediafile.artist, u'the artist') class OggTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, @@ -829,7 +828,7 @@ class OggTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 48000, - 'format': 'OGG', + 'format': u'OGG', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -873,7 +872,7 @@ class FlacTest(ReadWriteTestBase, PartialTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 175120, - 'format': 'FLAC', + 'format': u'FLAC', 'samplerate': 44100, 'bitdepth': 16, 'channels': 1, @@ -886,7 +885,7 @@ class ApeTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, audio_properties = { 'length': 1.0, 'bitrate': 112040, - 'format': 'APE', + 'format': u'APE', 'samplerate': 44100, 'bitdepth': 16, 'channels': 1, @@ -898,7 +897,7 @@ class WavpackTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 108744, - 'format': 'WavPack', + 'format': u'WavPack', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, @@ -910,7 +909,7 @@ class OpusTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 57984, - 'format': 'Opus', + 'format': u'Opus', 'samplerate': 48000, 'bitdepth': 0, 'channels': 1, @@ -922,7 +921,7 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): audio_properties = { 'length': 1.0, 'bitrate': 705600, - 'format': 'AIFF', + 'format': u'AIFF', 'samplerate': 44100, 'bitdepth': 0, 'channels': 1, From 6b6600d1dd5594db529f70eaf130245e8ffce880 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Tue, 23 Feb 2016 18:37:50 +0100 Subject: [PATCH 0560/2280] Removed unicode_literals from test_zero --- test/test_zero.py | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/test/test_zero.py b/test/test_zero.py index 623a7801b..78290b6ba 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -2,8 +2,7 @@ """Tests for the 'zero' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper @@ -24,7 +23,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): def test_no_patterns(self): tags = { - 'comments': 'test comment', + 'comments': u'test comment', 'day': 13, 'month': 3, 'year': 2012, @@ -32,9 +31,9 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): z = ZeroPlugin() z.debug = False z.fields = ['comments', 'month', 'day'] - z.patterns = {'comments': ['.'], - 'month': ['.'], - 'day': ['.']} + z.patterns = {'comments': [u'.'], + 'month': [u'.'], + 'day': [u'.']} z.write_event(None, None, tags) self.assertEqual(tags['comments'], None) self.assertEqual(tags['day'], None) @@ -45,11 +44,11 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): z = ZeroPlugin() z.debug = False z.fields = ['comments', 'year'] - z.patterns = {'comments': 'eac lame'.split(), - 'year': '2098 2099'.split()} + z.patterns = {'comments': u'eac lame'.split(), + 'year': u'2098 2099'.split()} tags = { - 'comments': 'from lame collection, ripped by eac', + 'comments': u'from lame collection, ripped by eac', 'year': 2012, } z.write_event(None, None, tags) @@ -97,7 +96,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(2000, mediafile.year) config['zero'] = { - 'fields': ['year'], + 'fields': [u'year'], 'update_database': True, } self.load_plugins('zero') @@ -114,7 +113,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): mediafile = MediaFile(item.path) self.assertNotEqual(0, len(mediafile.images)) - config['zero'] = {'fields': ['images']} + config['zero'] = {'fields': [u'images']} self.load_plugins('zero') item.write() From fe1e8b568750021f5d4b778c2924440c0cc82b2c Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:32:10 +0100 Subject: [PATCH 0561/2280] Removed unicode_literals from test_mediafile_edge --- test/test_mediafile_edge.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 298cb6dc1..80b923a91 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -15,8 +15,7 @@ """Specific, edge-case tests for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import shutil @@ -101,28 +100,28 @@ class EdgeTest(unittest.TestCase): class InvalidValueToleranceTest(unittest.TestCase): def test_safe_cast_string_to_int(self): - self.assertEqual(_sc(int, 'something'), 0) + self.assertEqual(_sc(int, u'something'), 0) def test_safe_cast_int_string_to_int(self): - self.assertEqual(_sc(int, '20'), 20) + self.assertEqual(_sc(int, u'20'), 20) def test_safe_cast_string_to_bool(self): - self.assertEqual(_sc(bool, 'whatever'), False) + self.assertEqual(_sc(bool, u'whatever'), False) def test_safe_cast_intstring_to_bool(self): - self.assertEqual(_sc(bool, '5'), True) + self.assertEqual(_sc(bool, u'5'), True) def test_safe_cast_string_to_float(self): - self.assertAlmostEqual(_sc(float, '1.234'), 1.234) + self.assertAlmostEqual(_sc(float, u'1.234'), 1.234) def test_safe_cast_int_to_float(self): self.assertAlmostEqual(_sc(float, 2), 2.0) def test_safe_cast_string_with_cruft_to_float(self): - self.assertAlmostEqual(_sc(float, '1.234stuff'), 1.234) + self.assertAlmostEqual(_sc(float, u'1.234stuff'), 1.234) def test_safe_cast_negative_string_to_float(self): - self.assertAlmostEqual(_sc(float, '-1.234'), -1.234) + self.assertAlmostEqual(_sc(float, u'-1.234'), -1.234) def test_safe_cast_special_chars_to_unicode(self): us = _sc(unicode, 'caf\xc3\xa9') @@ -130,7 +129,7 @@ class InvalidValueToleranceTest(unittest.TestCase): self.assertTrue(us.startswith(u'caf')) def test_safe_cast_float_with_no_numbers(self): - v = _sc(float, '+') + v = _sc(float, u'+') self.assertEqual(v, 0.0) @@ -177,7 +176,7 @@ class SafetyTest(unittest.TestCase, TestHelper): self._exccheck('nothing.xml', beets.mediafile.UnreadableFileError, "ftyp") - @unittest.skipIf(not hasattr(os, 'symlink'), 'platform lacks symlink') + @unittest.skipIf(not hasattr(os, 'symlink'), u'platform lacks symlink') def test_broken_symlink(self): fn = os.path.join(_common.RSRC, 'brokenlink') os.symlink('does_not_exist', fn) @@ -262,7 +261,7 @@ class TypeTest(unittest.TestCase): self.mf = beets.mediafile.MediaFile(path) def test_year_integer_in_string(self): - self.mf.year = '2009' + self.mf.year = u'2009' self.assertEqual(self.mf.year, 2009) def test_set_replaygain_gain_to_none(self): From 495de652a79517e8927e15d82c908fafcf32f401 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:33:34 +0100 Subject: [PATCH 0562/2280] Removed unicode_literals from test_mpdstats --- test/test_mpdstats.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index f28e29d68..4317e9824 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -13,9 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) - +from __future__ import (division, absolute_import, print_function) from mock import Mock, patch, call, ANY from test._common import unittest @@ -35,7 +33,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.unload_plugins() def test_update_rating(self): - item = Item(title='title', path='', id=1) + item = Item(title=u'title', path='', id=1) item.add(self.lib) log = Mock() @@ -46,7 +44,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): def test_get_item(self): ITEM_PATH = '/foo/bar.flac' - item = Item(title='title', path=ITEM_PATH, id=1) + item = Item(title=u'title', path=ITEM_PATH, id=1) item.add(self.lib) log = Mock() @@ -54,13 +52,13 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.assertEqual(str(mpdstats.get_item(ITEM_PATH)), str(item)) self.assertIsNone(mpdstats.get_item('/some/non-existing/path')) - self.assertIn('item not found:', log.info.call_args[0][0]) + self.assertIn(u'item not found:', log.info.call_args[0][0]) FAKE_UNKNOWN_STATE = 'some-unknown-one' STATUSES = [{'state': FAKE_UNKNOWN_STATE}, - {'state': 'pause'}, - {'state': 'play', 'songid': 1, 'time': '0:1'}, - {'state': 'stop'}] + {'state': u'pause'}, + {'state': u'play', 'songid': 1, 'time': u'0:1'}, + {'state': u'stop'}] EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt] ITEM_PATH = '/foo/bar.flac' @@ -68,7 +66,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): "events.side_effect": EVENTS, "status.side_effect": STATUSES, "playlist.return_value": {1: ITEM_PATH}})) def test_run_MPDStats(self, mpd_mock): - item = Item(title='title', path=self.ITEM_PATH, id=1) + item = Item(title=u'title', path=self.ITEM_PATH, id=1) item.add(self.lib) log = Mock() From 9fffd26267f0402a9cbe04a3351039a92c6e2add Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:35:11 +0100 Subject: [PATCH 0563/2280] Removed unicode_literals from test_permissions --- test/test_permissions.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index c1777ed59..de4b8577b 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -2,8 +2,7 @@ """Tests for the 'permissions' plugin. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os from mock import patch, Mock @@ -63,7 +62,7 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): for x in [(True, self.exp_perms[expectSuccess][typ], '!='), (False, self.exp_perms[not expectSuccess][typ], '==')]: self.assertEqual(x[0], check_permissions(path, x[1]), - msg='{} : {} {} {}'.format( + msg=u'{} : {} {} {}'.format( path, oct(os.stat(path).st_mode), x[2], oct(x[1]))) def test_convert_perm_from_string(self): From 945c4e201d5e8ed2bc2f52752ecc4e6fd1e37a1f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:36:23 +0100 Subject: [PATCH 0564/2280] Removed unicode_literals form test_pipeline --- test/test_pipeline.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 705a7eb73..7da8737a4 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -15,8 +15,7 @@ """Test the "pipeline.py" restricted parallel programming library. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from beets.util import pipeline From a77d3207cf229ad67971b25f26e29cc1d09be635 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:39:52 +0100 Subject: [PATCH 0565/2280] Removed unicode_literals from test_player --- test/test_player.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_player.py b/test/test_player.py index 4f2f6653a..a25d8b8ae 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -15,8 +15,7 @@ """Tests for BPD and music playing. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from beetsplug import bpd From 04e6377c1f84f98a92110fcc64d2ec95a2fcf59e Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:40:08 +0100 Subject: [PATCH 0566/2280] Removed unicode_literals from test_plexupdate --- test/test_plexupdate.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index 27a24ea30..36410d1e4 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper From be8feedfe62842c87929a7af32a65ee8e6960b9b Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 07:49:18 +0100 Subject: [PATCH 0567/2280] Removed unicode_literals from test_plugins --- test/test_plugins.py | 100 ++++++++++++++++++++++--------------------- 1 file changed, 52 insertions(+), 48 deletions(-) diff --git a/test/test_plugins.py b/test/test_plugins.py index eaf2e83ed..bd05d5e85 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os from mock import patch, Mock, ANY @@ -72,22 +71,22 @@ class ItemTypesTest(unittest.TestCase, TestHelper): self.register_plugin(RatingPlugin) self.config['plugins'] = 'rating' - item = Item(path='apath', artist='aaa') + item = Item(path=u'apath', artist=u'aaa') item.add(self.lib) # Do not match unset values - out = self.run_with_output('ls', 'rating:1..3') - self.assertNotIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:1..3') + self.assertNotIn(u'aaa', out) - self.run_command('modify', 'rating=2', '--yes') + self.run_command(u'modify', u'rating=2', u'--yes') # Match in range - out = self.run_with_output('ls', 'rating:1..3') - self.assertIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:1..3') + self.assertIn(u'aaa', out) # Don't match out of range - out = self.run_with_output('ls', 'rating:3..5') - self.assertNotIn('aaa', out) + out = self.run_with_output(u'ls', u'rating:3..5') + self.assertNotIn(u'aaa', out) class ItemWriteTest(unittest.TestCase, TestHelper): @@ -108,16 +107,16 @@ class ItemWriteTest(unittest.TestCase, TestHelper): def test_change_tags(self): def on_write(item=None, path=None, tags=None): - if tags['artist'] == 'XXX': - tags['artist'] = 'YYY' + if tags['artist'] == u'XXX': + tags['artist'] = u'YYY' self.register_listener('write', on_write) - item = self.add_item_fixture(artist='XXX') + item = self.add_item_fixture(artist=u'XXX') item.write() mediafile = MediaFile(item.path) - self.assertEqual(mediafile.artist, 'YYY') + self.assertEqual(mediafile.artist, u'YYY') def register_listener(self, event, func): self.event_listener_plugin.register_listener(event, func) @@ -193,8 +192,8 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): os.makedirs(self.album_path) metadata = { - 'artist': 'Tag Artist', - 'album': 'Tag Album', + 'artist': u'Tag Artist', + 'album': u'Tag Album', 'albumartist': None, 'mb_trackid': None, 'mb_albumid': None, @@ -203,7 +202,7 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): self.file_paths = [] for i in range(count): metadata['track'] = i + 1 - metadata['title'] = 'Tag Title Album %d' % (i + 1) + metadata['title'] = u'Tag Title Album %d' % (i + 1) dest_path = os.path.join(self.album_path, '%02d - track.mp3' % (i + 1)) self.__copy_file(dest_path, metadata) @@ -220,13 +219,14 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): # Exactly one event should have been imported (for the album). # Sentinels do not get emitted. - self.assertEqual(logs.count('Sending event: import_task_created'), 1) + self.assertEqual(logs.count(u'Sending event: import_task_created'), 1) - logs = [line for line in logs if not line.startswith('Sending event:')] + logs = [line for line in logs if not line.startswith( + u'Sending event:')] self.assertEqual(logs, [ - 'Album: {0}'.format(os.path.join(self.import_dir, 'album')), - ' {0}'.format(self.file_paths[0]), - ' {0}'.format(self.file_paths[1]), + u'Album: {0}'.format(os.path.join(self.import_dir, 'album')), + u' {0}'.format(self.file_paths[0]), + u' {0}'.format(self.file_paths[1]), ]) def test_import_task_created_with_plugin(self): @@ -262,23 +262,27 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): # Exactly one event should have been imported (for the album). # Sentinels do not get emitted. - self.assertEqual(logs.count('Sending event: import_task_created'), 1) + self.assertEqual(logs.count(u'Sending event: import_task_created'), 1) - logs = [line for line in logs if not line.startswith('Sending event:')] + logs = [line for line in logs if not line.startswith( + u'Sending event:')] self.assertEqual(logs, [ - 'Singleton: {0}'.format(self.file_paths[0]), - 'Singleton: {0}'.format(self.file_paths[1]), + u'Singleton: {0}'.format(self.file_paths[0]), + u'Singleton: {0}'.format(self.file_paths[1]), ]) class HelpersTest(unittest.TestCase): def test_sanitize_choices(self): - self.assertEqual(plugins.sanitize_choices(['A', 'Z'], ('A', 'B')), - ['A']) - self.assertEqual(plugins.sanitize_choices(['A', 'A'], ('A')), ['A']) - self.assertEqual(plugins.sanitize_choices(['D', '*', 'A'], - ('A', 'B', 'C', 'D')), ['D', 'B', 'C', 'A']) + self.assertEqual( + plugins.sanitize_choices([u'A', u'Z'], (u'A', u'B')), [u'A']) + self.assertEqual( + plugins.sanitize_choices([u'A', u'A'], (u'A')), [u'A']) + self.assertEqual( + plugins.sanitize_choices([u'D', u'*', u'A'], + (u'A', u'B', u'C', u'D')), + [u'D', u'B', u'C', u'A']) class ListenersTest(unittest.TestCase, TestHelper): @@ -331,8 +335,8 @@ class ListenersTest(unittest.TestCase, TestHelper): d.foo.assert_has_calls([]) d.bar.assert_has_calls([]) - plugins.send('event_foo', var="tagada") - d.foo.assert_called_once_with(var="tagada") + plugins.send('event_foo', var=u"tagada") + d.foo.assert_called_once_with(var=u"tagada") d.bar.assert_has_calls([]) @patch('beets.plugins.find_plugins') @@ -430,14 +434,14 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.return_choices) def return_choices(self, session, task): - return [ui.commands.PromptChoice('f', 'Foo', None), - ui.commands.PromptChoice('r', 'baR', None)] + return [ui.commands.PromptChoice('f', u'Foo', None), + ui.commands.PromptChoice('r', u'baR', None)] self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + ('Foo', 'baR') + u'enter Id', u'aBort') + (u'Foo', u'baR') self.importer.add_choice(action.SKIP) self.importer.run() @@ -453,14 +457,14 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.return_choices) def return_choices(self, session, task): - return [ui.commands.PromptChoice('f', 'Foo', None), - ui.commands.PromptChoice('r', 'baR', None)] + return [ui.commands.PromptChoice('f', u'Foo', None), + ui.commands.PromptChoice('r', u'baR', None)] self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', u'Enter search', - u'enter Id', u'aBort') + ('Foo', 'baR') + u'enter Id', u'aBort') + (u'Foo', u'baR') config['import']['singletons'] = True self.importer.add_choice(action.SKIP) @@ -477,16 +481,16 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.return_choices) def return_choices(self, session, task): - return [ui.commands.PromptChoice('a', 'A foo', None), # dupe - ui.commands.PromptChoice('z', 'baZ', None), # ok - ui.commands.PromptChoice('z', 'Zupe', None), # dupe - ui.commands.PromptChoice('z', 'Zoo', None)] # dupe + return [ui.commands.PromptChoice('a', u'A foo', None), # dupe + ui.commands.PromptChoice('z', u'baZ', None), # ok + ui.commands.PromptChoice('z', u'Zupe', None), # dupe + ui.commands.PromptChoice('z', u'Zoo', None)] # dupe self.register_plugin(DummyPlugin) # Default options + not dupe extra choices by the plugin ('baZ') 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') + ('baZ',) + u'enter Id', u'aBort') + (u'baZ',) self.importer.add_choice(action.SKIP) self.importer.run() self.mock_input_options.assert_called_once_with(opts, default='a', @@ -501,7 +505,7 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.return_choices) def return_choices(self, session, task): - return [ui.commands.PromptChoice('f', 'Foo', self.foo)] + return [ui.commands.PromptChoice('f', u'Foo', self.foo)] def foo(self, session, task): pass @@ -510,7 +514,7 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + ('Foo',) + u'enter Id', u'aBort') + (u'Foo',) # DummyPlugin.foo() should be called once with patch.object(DummyPlugin, 'foo', autospec=True) as mock_foo: @@ -532,7 +536,7 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.return_choices) def return_choices(self, session, task): - return [ui.commands.PromptChoice('f', 'Foo', self.foo)] + return [ui.commands.PromptChoice('f', u'Foo', self.foo)] def foo(self, session, task): return action.SKIP @@ -541,7 +545,7 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + ('Foo',) + u'enter Id', u'aBort') + (u'Foo',) # DummyPlugin.foo() should be called once with helper.control_stdin('f\n'): From a3138177e611dfe7934a1d709484b4ade2065326 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 18:08:23 +0100 Subject: [PATCH 0568/2280] Removed unicode_literals from test_spotify --- test/test_spotify.py | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/test/test_spotify.py b/test/test_spotify.py index 895106845..9fa64733c 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -2,8 +2,7 @@ """Tests for the 'spotify' plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test import _common import responses @@ -46,7 +45,7 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): self.assertEqual(True, self.spotify.parse_opts(opts)) def test_empty_query(self): - self.assertEqual(None, self.spotify.query_spotify(self.lib, "1=2")) + self.assertEqual(None, self.spotify.query_spotify(self.lib, u"1=2")) @responses.activate def test_missing_request(self): @@ -68,21 +67,21 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): body=response_body, status=200, content_type='application/json') item = Item( - mb_trackid='01234', - album='lkajsdflakjsd', - albumartist='ujydfsuihse', - title='duifhjslkef', + mb_trackid=u'01234', + album=u'lkajsdflakjsd', + albumartist=u'ujydfsuihse', + title=u'duifhjslkef', length=10 ) item.add(self.lib) - self.assertEqual([], self.spotify.query_spotify(self.lib, "")) + self.assertEqual([], self.spotify.query_spotify(self.lib, u"")) params = _params(responses.calls[0].request.url) self.assertEqual( params['q'], - ['duifhjslkef album:lkajsdflakjsd artist:ujydfsuihse'], + [u'duifhjslkef album:lkajsdflakjsd artist:ujydfsuihse'], ) - self.assertEqual(params['type'], ['track']) + self.assertEqual(params['type'], [u'track']) @responses.activate def test_track_request(self): @@ -186,24 +185,24 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): body=response_body, status=200, content_type='application/json') item = Item( - mb_trackid='01234', - album='Despicable Me 2', - albumartist='Pharrell Williams', - title='Happy', + mb_trackid=u'01234', + album=u'Despicable Me 2', + albumartist=u'Pharrell Williams', + title=u'Happy', length=10 ) item.add(self.lib) - results = self.spotify.query_spotify(self.lib, "Happy") + results = self.spotify.query_spotify(self.lib, u"Happy") self.assertEqual(1, len(results)) - self.assertEqual("6NPVjNh8Jhru9xOmyQigds", results[0]['id']) + self.assertEqual(u"6NPVjNh8Jhru9xOmyQigds", results[0]['id']) self.spotify.output_results(results) params = _params(responses.calls[0].request.url) self.assertEqual( params['q'], - ['Happy album:Despicable Me 2 artist:Pharrell Williams'], + [u'Happy album:Despicable Me 2 artist:Pharrell Williams'], ) - self.assertEqual(params['type'], ['track']) + self.assertEqual(params['type'], [u'track']) def suite(): From f33d9228983c18327ab6df96459ca534a71727b0 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Wed, 24 Feb 2016 18:24:29 +0100 Subject: [PATCH 0569/2280] Removed unicode_literals from test_query --- test/test_query.py | 417 +++++++++++++++++++++++---------------------- 1 file changed, 209 insertions(+), 208 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index deb9f090f..361d52fbc 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -15,8 +15,7 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from functools import partial from mock import patch @@ -54,19 +53,19 @@ class AnyFieldQueryTest(_common.LibTestCase): self.assertEqual(self.lib.items(q).get().title, 'the title') def test_restriction_completeness(self): - q = dbcore.query.AnyFieldQuery('title', ['title'], + q = dbcore.query.AnyFieldQuery('title', [u'title'], dbcore.query.SubstringQuery) - self.assertEqual(self.lib.items(q).get().title, 'the title') + self.assertEqual(self.lib.items(q).get().title, u'the title') def test_restriction_soundness(self): - q = dbcore.query.AnyFieldQuery('title', ['artist'], + q = dbcore.query.AnyFieldQuery('title', [u'artist'], dbcore.query.SubstringQuery) self.assertEqual(self.lib.items(q).get(), None) def test_eq(self): - q1 = dbcore.query.AnyFieldQuery('foo', ['bar'], + q1 = dbcore.query.AnyFieldQuery('foo', [u'bar'], dbcore.query.SubstringQuery) - q2 = dbcore.query.AnyFieldQuery('foo', ['bar'], + q2 = dbcore.query.AnyFieldQuery('foo', [u'bar'], dbcore.query.SubstringQuery) self.assertEqual(q1, q2) @@ -89,19 +88,19 @@ class DummyDataTestCase(_common.TestCase, AssertsMixin): super(DummyDataTestCase, self).setUp() self.lib = beets.library.Library(':memory:') items = [_common.item() for _ in range(3)] - items[0].title = 'foo bar' - items[0].artist = 'one' - items[0].album = 'baz' + items[0].title = u'foo bar' + items[0].artist = u'one' + items[0].album = u'baz' items[0].year = 2001 items[0].comp = True - items[1].title = 'baz qux' - items[1].artist = 'two' - items[1].album = 'baz' + items[1].title = u'baz qux' + items[1].artist = u'two' + items[1].album = u'baz' items[1].year = 2002 items[1].comp = True - items[2].title = 'beets 4 eva' - items[2].artist = 'three' - items[2].album = 'foo' + items[2].title = u'beets 4 eva' + items[2].artist = u'three' + items[2].album = u'foo' items[2].year = 2003 items[2].comp = False for item in items: @@ -110,15 +109,15 @@ class DummyDataTestCase(_common.TestCase, AssertsMixin): def assert_items_matched_all(self, results): self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', - 'beets 4 eva', + u'foo bar', + u'baz qux', + u'beets 4 eva', ]) class GetTest(DummyDataTestCase): def test_get_empty(self): - q = '' + q = u'' results = self.lib.items(q) self.assert_items_matched_all(results) @@ -128,152 +127,152 @@ class GetTest(DummyDataTestCase): self.assert_items_matched_all(results) def test_get_one_keyed_term(self): - q = 'title:qux' + q = u'title:qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_get_one_keyed_regexp(self): - q = r'artist::t.+r' + q = u'artist::t.+r' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_get_one_unkeyed_term(self): - q = 'three' + q = u'three' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_get_one_unkeyed_regexp(self): - q = r':x$' + q = u':x$' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_get_no_matches(self): - q = 'popebear' + q = u'popebear' results = self.lib.items(q) self.assert_items_matched(results, []) def test_invalid_key(self): - q = 'pope:bear' + q = u'pope:bear' results = self.lib.items(q) # Matches nothing since the flexattr is not present on the # objects. self.assert_items_matched(results, []) def test_term_case_insensitive(self): - q = 'oNE' + q = u'oNE' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_regexp_case_sensitive(self): - q = r':oNE' + q = u':oNE' results = self.lib.items(q) self.assert_items_matched(results, []) - q = r':one' + q = u':one' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_term_case_insensitive_with_key(self): - q = 'artist:thrEE' + q = u'artist:thrEE' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_key_case_insensitive(self): - q = 'ArTiST:three' + q = u'ArTiST:three' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_unkeyed_term_matches_multiple_columns(self): - q = 'baz' + q = u'baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_unkeyed_regexp_matches_multiple_columns(self): - q = r':z$' + q = u':z$' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_keyed_term_matches_only_one_column(self): - q = 'title:baz' + q = u'title:baz' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_keyed_regexp_matches_only_one_column(self): - q = r'title::baz' + q = u'title::baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'baz qux', + u'baz qux', ]) def test_multiple_terms_narrow_search(self): - q = 'qux baz' + q = u'qux baz' results = self.lib.items(q) self.assert_items_matched(results, [ - 'baz qux', + u'baz qux', ]) def test_multiple_regexps_narrow_search(self): - q = r':baz :qux' + q = u':baz :qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_mixed_terms_regexps_narrow_search(self): - q = r':baz qux' + q = u':baz qux' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_single_year(self): - q = 'year:2001' + q = u'year:2001' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar']) + self.assert_items_matched(results, [u'foo bar']) def test_year_range(self): - q = 'year:2000..2002' + q = u'year:2000..2002' results = self.lib.items(q) self.assert_items_matched(results, [ - 'foo bar', - 'baz qux', + u'foo bar', + u'baz qux', ]) def test_singleton_true(self): - q = 'singleton:true' + q = u'singleton:true' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_singleton_false(self): - q = 'singleton:false' + q = u'singleton:false' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'baz qux']) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) def test_compilation_true(self): - q = 'comp:true' + q = u'comp:true' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'baz qux']) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) def test_compilation_false(self): - q = 'comp:false' + q = u'comp:false' results = self.lib.items(q) - self.assert_items_matched(results, ['beets 4 eva']) + self.assert_items_matched(results, [u'beets 4 eva']) def test_unknown_field_name_no_results(self): - q = 'xyzzy:nonsense' + q = u'xyzzy:nonsense' results = self.lib.items(q) titles = [i.title for i in results] self.assertEqual(titles, []) def test_unknown_field_name_no_results_in_album_query(self): - q = 'xyzzy:nonsense' + q = u'xyzzy:nonsense' results = self.lib.albums(q) names = [a.album for a in results] self.assertEqual(names, []) def test_item_field_name_matches_nothing_in_album_query(self): - q = 'format:nonsense' + q = u'format:nonsense' results = self.lib.albums(q) names = [a.album for a in results] self.assertEqual(names, []) @@ -288,24 +287,24 @@ class GetTest(DummyDataTestCase): self.assert_items_matched(results, [u'caf\xe9']) def test_numeric_search_positive(self): - q = dbcore.query.NumericQuery('year', '2001') + q = dbcore.query.NumericQuery('year', u'2001') results = self.lib.items(q) self.assertTrue(results) def test_numeric_search_negative(self): - q = dbcore.query.NumericQuery('year', '1999') + q = dbcore.query.NumericQuery('year', u'1999') results = self.lib.items(q) self.assertFalse(results) def test_invalid_query(self): with self.assertRaises(InvalidQueryArgumentTypeError) as raised: - dbcore.query.NumericQuery('year', '199a') - self.assertIn('not an int', unicode(raised.exception)) + dbcore.query.NumericQuery('year', u'199a') + self.assertIn(u'not an int', unicode(raised.exception)) with self.assertRaises(InvalidQueryArgumentTypeError) as raised: - dbcore.query.RegexpQuery('year', '199(') - self.assertIn('not a regular expression', unicode(raised.exception)) - self.assertIn('unbalanced parenthesis', unicode(raised.exception)) + dbcore.query.RegexpQuery('year', u'199(') + self.assertIn(u'not a regular expression', unicode(raised.exception)) + self.assertIn(u'unbalanced parenthesis', unicode(raised.exception)) self.assertIsInstance(raised.exception, ParsingError) @@ -315,53 +314,53 @@ class MatchTest(_common.TestCase): self.item = _common.item() def test_regex_match_positive(self): - q = dbcore.query.RegexpQuery('album', '^the album$') + q = dbcore.query.RegexpQuery('album', u'^the album$') self.assertTrue(q.match(self.item)) def test_regex_match_negative(self): - q = dbcore.query.RegexpQuery('album', '^album$') + q = dbcore.query.RegexpQuery('album', u'^album$') self.assertFalse(q.match(self.item)) def test_regex_match_non_string_value(self): - q = dbcore.query.RegexpQuery('disc', '^6$') + q = dbcore.query.RegexpQuery('disc', u'^6$') self.assertTrue(q.match(self.item)) def test_substring_match_positive(self): - q = dbcore.query.SubstringQuery('album', 'album') + q = dbcore.query.SubstringQuery('album', u'album') self.assertTrue(q.match(self.item)) def test_substring_match_negative(self): - q = dbcore.query.SubstringQuery('album', 'ablum') + q = dbcore.query.SubstringQuery('album', u'ablum') self.assertFalse(q.match(self.item)) def test_substring_match_non_string_value(self): - q = dbcore.query.SubstringQuery('disc', '6') + q = dbcore.query.SubstringQuery('disc', u'6') self.assertTrue(q.match(self.item)) def test_year_match_positive(self): - q = dbcore.query.NumericQuery('year', '1') + q = dbcore.query.NumericQuery('year', u'1') self.assertTrue(q.match(self.item)) def test_year_match_negative(self): - q = dbcore.query.NumericQuery('year', '10') + q = dbcore.query.NumericQuery('year', u'10') self.assertFalse(q.match(self.item)) def test_bitrate_range_positive(self): - q = dbcore.query.NumericQuery('bitrate', '100000..200000') + q = dbcore.query.NumericQuery('bitrate', u'100000..200000') self.assertTrue(q.match(self.item)) def test_bitrate_range_negative(self): - q = dbcore.query.NumericQuery('bitrate', '200000..300000') + q = dbcore.query.NumericQuery('bitrate', u'200000..300000') self.assertFalse(q.match(self.item)) def test_open_range(self): - dbcore.query.NumericQuery('bitrate', '100000..') + dbcore.query.NumericQuery('bitrate', u'100000..') def test_eq(self): - q1 = dbcore.query.MatchQuery('foo', 'bar') - q2 = dbcore.query.MatchQuery('foo', 'bar') - q3 = dbcore.query.MatchQuery('foo', 'baz') - q4 = dbcore.query.StringFieldQuery('foo', 'bar') + q1 = dbcore.query.MatchQuery('foo', u'bar') + q2 = dbcore.query.MatchQuery('foo', u'bar') + q3 = dbcore.query.MatchQuery('foo', u'baz') + q4 = dbcore.query.StringFieldQuery('foo', u'bar') self.assertEqual(q1, q2) self.assertNotEqual(q1, q3) self.assertNotEqual(q1, q4) @@ -372,8 +371,8 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): def setUp(self): super(PathQueryTest, self).setUp() self.i.path = '/a/b/c.mp3' - self.i.title = 'path item' - self.i.album = 'path album' + self.i.title = u'path item' + self.i.album = u'path album' self.i.store() self.lib.add_album([self.i]) @@ -393,31 +392,31 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.patcher_exists.stop() def test_path_exact_match(self): - q = 'path:/a/b/c.mp3' + q = u'path:/a/b/c.mp3' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) self.assert_albums_matched(results, []) def test_parent_directory_no_slash(self): - q = 'path:/a' + q = u'path:/a' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_parent_directory_with_slash(self): - q = 'path:/a/' + q = u'path:/a/' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_no_match(self): - q = 'path:/xyzzy/' + q = u'path:/xyzzy/' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -425,7 +424,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_fragment_no_match(self): - q = 'path:/b/' + q = u'path:/b/' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -433,23 +432,23 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_nonnorm_path(self): - q = 'path:/x/../a/b' + q = u'path:/x/../a/b' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_slashed_query_matches_path(self): - q = '/a/b' + q = u'/a/b' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_non_slashed_does_not_match_path(self): - q = 'c.mp3' + q = u'c.mp3' results = self.lib.items(q) self.assert_items_matched(results, []) @@ -457,60 +456,60 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, []) def test_slashes_in_explicit_field_does_not_match_path(self): - q = 'title:/a/b' + q = u'title:/a/b' results = self.lib.items(q) self.assert_items_matched(results, []) def test_path_item_regex(self): - q = 'path::\\.mp3$' + q = u'path::\\.mp3$' results = self.lib.items(q) - self.assert_items_matched(results, ['path item']) + self.assert_items_matched(results, [u'path item']) def test_path_album_regex(self): - q = 'path::b' + q = u'path::b' results = self.lib.albums(q) - self.assert_albums_matched(results, ['path album']) + self.assert_albums_matched(results, [u'path album']) def test_escape_underscore(self): - self.add_album(path='/a/_/title.mp3', title='with underscore', - album='album with underscore') - q = 'path:/a/_' + self.add_album(path='/a/_/title.mp3', title=u'with underscore', + album=u'album with underscore') + q = u'path:/a/_' results = self.lib.items(q) - self.assert_items_matched(results, ['with underscore']) + self.assert_items_matched(results, [u'with underscore']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with underscore']) + self.assert_albums_matched(results, [u'album with underscore']) def test_escape_percent(self): - self.add_album(path='/a/%/title.mp3', title='with percent', - album='album with percent') - q = 'path:/a/%' + self.add_album(path='/a/%/title.mp3', title=u'with percent', + album=u'album with percent') + q = u'path:/a/%' results = self.lib.items(q) - self.assert_items_matched(results, ['with percent']) + self.assert_items_matched(results, [u'with percent']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with percent']) + self.assert_albums_matched(results, [u'album with percent']) def test_escape_backslash(self): - self.add_album(path=r'/a/\x/title.mp3', title='with backslash', - album='album with backslash') - q = r'path:/a/\\x' + self.add_album(path=r'/a/\x/title.mp3', title=u'with backslash', + album=u'album with backslash') + q = u'path:/a/\\\\x' results = self.lib.items(q) - self.assert_items_matched(results, ['with backslash']) + self.assert_items_matched(results, [u'with backslash']) results = self.lib.albums(q) - self.assert_albums_matched(results, ['album with backslash']) + self.assert_albums_matched(results, [u'album with backslash']) def test_case_sensitivity(self): - self.add_album(path='/A/B/C2.mp3', title='caps path') + self.add_album(path='/A/B/C2.mp3', title=u'caps path') - makeq = partial(beets.library.PathQuery, 'path', '/A/B') + makeq = partial(beets.library.PathQuery, u'path', '/A/B') results = self.lib.items(makeq(case_sensitive=True)) - self.assert_items_matched(results, ['caps path']) + self.assert_items_matched(results, [u'caps path']) results = self.lib.items(makeq(case_sensitive=False)) - self.assert_items_matched(results, ['path item', 'caps path']) + self.assert_items_matched(results, [u'path item', u'caps path']) # Check for correct case sensitivity selection (this check # only works on non-Windows OSes). @@ -594,32 +593,32 @@ class IntQueryTest(unittest.TestCase, TestHelper): def test_exact_value_match(self): item = self.add_item(bpm=120) - matched = self.lib.items('bpm:120').get() + matched = self.lib.items(u'bpm:120').get() self.assertEqual(item.id, matched.id) def test_range_match(self): item = self.add_item(bpm=120) self.add_item(bpm=130) - matched = self.lib.items('bpm:110..125') + matched = self.lib.items(u'bpm:110..125') self.assertEqual(1, len(matched)) self.assertEqual(item.id, matched.get().id) def test_flex_range_match(self): Item._types = {'myint': types.Integer()} item = self.add_item(myint=2) - matched = self.lib.items('myint:2').get() + matched = self.lib.items(u'myint:2').get() self.assertEqual(item.id, matched.id) def test_flex_dont_match_missing(self): Item._types = {'myint': types.Integer()} self.add_item() - matched = self.lib.items('myint:2').get() + matched = self.lib.items(u'myint:2').get() self.assertIsNone(matched) def test_no_substring_match(self): self.add_item(bpm=120) - matched = self.lib.items('bpm:12').get() + matched = self.lib.items(u'bpm:12').get() self.assertIsNone(matched) @@ -635,35 +634,35 @@ class BoolQueryTest(unittest.TestCase, TestHelper): def test_parse_true(self): item_true = self.add_item(comp=True) item_false = self.add_item(comp=False) - matched = self.lib.items('comp:true') + matched = self.lib.items(u'comp:true') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_true(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:true') + matched = self.lib.items(u'flexbool:true') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_false(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:false') + matched = self.lib.items(u'flexbool:false') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) def test_flex_parse_1(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:1') + matched = self.lib.items(u'flexbool:1') self.assertInResult(item_true, matched) self.assertNotInResult(item_false, matched) def test_flex_parse_0(self): item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:0') + matched = self.lib.items(u'flexbool:0') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) @@ -671,26 +670,26 @@ class BoolQueryTest(unittest.TestCase, TestHelper): # TODO this should be the other way around item_true = self.add_item(flexbool=True) item_false = self.add_item(flexbool=False) - matched = self.lib.items('flexbool:something') + matched = self.lib.items(u'flexbool:something') self.assertInResult(item_false, matched) self.assertNotInResult(item_true, matched) class DefaultSearchFieldsTest(DummyDataTestCase): def test_albums_matches_album(self): - albums = list(self.lib.albums('baz')) + albums = list(self.lib.albums(u'baz')) self.assertEqual(len(albums), 1) def test_albums_matches_albumartist(self): - albums = list(self.lib.albums(['album artist'])) + albums = list(self.lib.albums([u'album artist'])) self.assertEqual(len(albums), 1) def test_items_matches_title(self): - items = self.lib.items('beets') - self.assert_items_matched(items, ['beets 4 eva']) + items = self.lib.items(u'beets') + self.assert_items_matched(items, [u'beets 4 eva']) def test_items_does_not_match_year(self): - items = self.lib.items('2001') + items = self.lib.items(u'2001') self.assert_items_matched(items, []) @@ -703,18 +702,18 @@ class NoneQueryTest(unittest.TestCase, TestHelper): singleton = self.add_item() album_item = self.add_album().items().get() - matched = self.lib.items(NoneQuery('album_id')) + matched = self.lib.items(NoneQuery(u'album_id')) self.assertInResult(singleton, matched) self.assertNotInResult(album_item, matched) def test_match_after_set_none(self): item = self.add_item(rg_track_gain=0) - matched = self.lib.items(NoneQuery('rg_track_gain')) + matched = self.lib.items(NoneQuery(u'rg_track_gain')) self.assertNotInResult(item, matched) item['rg_track_gain'] = None item.store() - matched = self.lib.items(NoneQuery('rg_track_gain')) + matched = self.lib.items(NoneQuery(u'rg_track_gain')) self.assertInResult(item, matched) @@ -728,57 +727,57 @@ class NotQueryMatchTest(_common.TestCase): self.item = _common.item() def test_regex_match_positive(self): - q = dbcore.query.RegexpQuery('album', '^the album$') + q = dbcore.query.RegexpQuery(u'album', u'^the album$') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_regex_match_negative(self): - q = dbcore.query.RegexpQuery('album', '^album$') + q = dbcore.query.RegexpQuery(u'album', u'^album$') self.assertFalse(q.match(self.item)) self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_regex_match_non_string_value(self): - q = dbcore.query.RegexpQuery('disc', '^6$') + q = dbcore.query.RegexpQuery(u'disc', u'^6$') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_positive(self): - q = dbcore.query.SubstringQuery('album', 'album') + q = dbcore.query.SubstringQuery(u'album', u'album') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_negative(self): - q = dbcore.query.SubstringQuery('album', 'ablum') + q = dbcore.query.SubstringQuery(u'album', u'ablum') self.assertFalse(q.match(self.item)) self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_substring_match_non_string_value(self): - q = dbcore.query.SubstringQuery('disc', '6') + q = dbcore.query.SubstringQuery(u'disc', u'6') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_year_match_positive(self): - q = dbcore.query.NumericQuery('year', '1') + q = dbcore.query.NumericQuery(u'year', u'1') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_year_match_negative(self): - q = dbcore.query.NumericQuery('year', '10') + q = dbcore.query.NumericQuery(u'year', u'10') self.assertFalse(q.match(self.item)) self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_bitrate_range_positive(self): - q = dbcore.query.NumericQuery('bitrate', '100000..200000') + q = dbcore.query.NumericQuery(u'bitrate', u'100000..200000') self.assertTrue(q.match(self.item)) self.assertFalse(dbcore.query.NotQuery(q).match(self.item)) def test_bitrate_range_negative(self): - q = dbcore.query.NumericQuery('bitrate', '200000..300000') + q = dbcore.query.NumericQuery(u'bitrate', u'200000..300000') self.assertFalse(q.match(self.item)) self.assertTrue(dbcore.query.NotQuery(q).match(self.item)) def test_open_range(self): - q = dbcore.query.NumericQuery('bitrate', '100000..') + q = dbcore.query.NumericQuery(u'bitrate', u'100000..') dbcore.query.NotQuery(q) @@ -814,27 +813,29 @@ class NotQueryTest(DummyDataTestCase): def test_type_and(self): # not(a and b) <-> not(a) or not(b) - q = dbcore.query.AndQuery([dbcore.query.BooleanQuery('comp', True), - dbcore.query.NumericQuery('year', '2002')]) + q = dbcore.query.AndQuery([ + dbcore.query.BooleanQuery(u'comp', True), + dbcore.query.NumericQuery(u'year', u'2002')], + ) not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(not_results, [u'foo bar', u'beets 4 eva']) self.assertNegationProperties(q) def test_type_anyfield(self): - q = dbcore.query.AnyFieldQuery('foo', ['title', 'artist', 'album'], + q = dbcore.query.AnyFieldQuery(u'foo', [u'title', u'artist', u'album'], dbcore.query.SubstringQuery) not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['baz qux']) + self.assert_items_matched(not_results, [u'baz qux']) self.assertNegationProperties(q) def test_type_boolean(self): - q = dbcore.query.BooleanQuery('comp', True) + q = dbcore.query.BooleanQuery(u'comp', True) not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['beets 4 eva']) + self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) def test_type_date(self): - q = dbcore.query.DateQuery('mtime', '0.0') + q = dbcore.query.DateQuery(u'mtime', u'0.0') not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, []) self.assertNegationProperties(q) @@ -846,41 +847,41 @@ class NotQueryTest(DummyDataTestCase): self.assertNegationProperties(q) def test_type_match(self): - q = dbcore.query.MatchQuery('year', '2003') + q = dbcore.query.MatchQuery(u'year', u'2003') not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['foo bar', 'baz qux']) + self.assert_items_matched(not_results, [u'foo bar', u'baz qux']) self.assertNegationProperties(q) def test_type_none(self): - q = dbcore.query.NoneQuery('rg_track_gain') + q = dbcore.query.NoneQuery(u'rg_track_gain') not_results = self.lib.items(dbcore.query.NotQuery(q)) self.assert_items_matched(not_results, []) self.assertNegationProperties(q) def test_type_numeric(self): - q = dbcore.query.NumericQuery('year', '2001..2002') + q = dbcore.query.NumericQuery(u'year', u'2001..2002') not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['beets 4 eva']) + self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) def test_type_or(self): # not(a or b) <-> not(a) and not(b) - q = dbcore.query.OrQuery([dbcore.query.BooleanQuery('comp', True), - dbcore.query.NumericQuery('year', '2002')]) + q = dbcore.query.OrQuery([dbcore.query.BooleanQuery(u'comp', True), + dbcore.query.NumericQuery(u'year', u'2002')]) not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['beets 4 eva']) + self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) def test_type_regexp(self): - q = dbcore.query.RegexpQuery('artist', '^t') + q = dbcore.query.RegexpQuery(u'artist', u'^t') not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['foo bar']) + self.assert_items_matched(not_results, [u'foo bar']) self.assertNegationProperties(q) def test_type_substring(self): - q = dbcore.query.SubstringQuery('album', 'ba') + q = dbcore.query.SubstringQuery(u'album', u'ba') not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, ['beets 4 eva']) + self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) def test_type_true(self): @@ -891,41 +892,41 @@ class NotQueryTest(DummyDataTestCase): def test_get_prefixes_keyed(self): """Test both negation prefixes on a keyed query.""" - q0 = '-title:qux' - q1 = '^title:qux' + q0 = u'-title:qux' + q1 = u'^title:qux' results0 = self.lib.items(q0) results1 = self.lib.items(q1) - self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) - self.assert_items_matched(results1, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva']) + self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva']) def test_get_prefixes_unkeyed(self): """Test both negation prefixes on an unkeyed query.""" - q0 = '-qux' - q1 = '^qux' + q0 = u'-qux' + q1 = u'^qux' results0 = self.lib.items(q0) results1 = self.lib.items(q1) - self.assert_items_matched(results0, ['foo bar', 'beets 4 eva']) - self.assert_items_matched(results1, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva']) + self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva']) def test_get_one_keyed_regexp(self): - q = r'-artist::t.+r' + q = u'-artist::t.+r' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'baz qux']) + self.assert_items_matched(results, [u'foo bar', u'baz qux']) def test_get_one_unkeyed_regexp(self): - q = r'-:x$' + q = u'-:x$' results = self.lib.items(q) - self.assert_items_matched(results, ['foo bar', 'beets 4 eva']) + self.assert_items_matched(results, [u'foo bar', u'beets 4 eva']) def test_get_multiple_terms(self): - q = 'baz -bar' + q = u'baz -bar' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_get_mixed_terms(self): - q = 'baz -title:bar' + q = u'baz -title:bar' results = self.lib.items(q) - self.assert_items_matched(results, ['baz qux']) + self.assert_items_matched(results, [u'baz qux']) def test_fast_vs_slow(self): """Test that the results are the same regardless of the `fast` flag @@ -935,13 +936,13 @@ class NotQueryTest(DummyDataTestCase): AttributeError: type object 'NoneQuery' has no attribute 'field' at NoneQuery.match() (due to being @classmethod, and no self?) """ - classes = [(dbcore.query.DateQuery, ['mtime', '0.0']), - (dbcore.query.MatchQuery, ['artist', 'one']), + classes = [(dbcore.query.DateQuery, [u'mtime', u'0.0']), + (dbcore.query.MatchQuery, [u'artist', u'one']), # (dbcore.query.NoneQuery, ['rg_track_gain']), - (dbcore.query.NumericQuery, ['year', '2002']), - (dbcore.query.StringFieldQuery, ['year', '2001']), - (dbcore.query.RegexpQuery, ['album', '^.a']), - (dbcore.query.SubstringQuery, ['title', 'x'])] + (dbcore.query.NumericQuery, [u'year', u'2002']), + (dbcore.query.StringFieldQuery, [u'year', u'2001']), + (dbcore.query.RegexpQuery, [u'album', u'^.a']), + (dbcore.query.SubstringQuery, [u'title', u'x'])] for klass, args in classes: q_fast = dbcore.query.NotQuery(klass(*(args + [True]))) From e58e04f0ab18a7d9b3ea8a4a5589fa0f55d93c85 Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 12:44:09 +1030 Subject: [PATCH 0570/2280] move and split fetchart valid_image --- beets/util/artresizer.py | 40 +++++++++++++++++ beetsplug/fetchart.py | 93 ++++++++++++++-------------------------- 2 files changed, 72 insertions(+), 61 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 1b6a5903e..919a10883 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -173,6 +173,46 @@ class ArtResizer(object): log.debug(u"artresizer: method is {0}", self.method) self.can_compare = self._can_compare() + def valid_size(self, size, enforce_ratio = False, minwidth = None): + """If size constraints exist, check whether the provided image size + matches them. + """ + # Check minimum size. + if minwidth and size[0] < minwidth: + log.debug('image too small ({} < {})', + size[0], minwidth) + return False + + # Check aspect ratio. + if enforce_ratio and size[0] != size[1]: + log.debug('image is not square ({} != {})', + size[0], size[1]) + return False + + return True + + def must_resize(self, size, maxwidth = None): + """Determine whether the provided image size means that the image + will need to be scaled to fit the maximum width. + """ + if not maxwidth: + return False + + if not size: + log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies).') + return False + + if size[0] <= maxwidth: + log.debug('dump values ({} > {})', + size[0], maxwidth) + log.debug(u'Image does not need to be resized.') + return False + + log.debug('Image needs resizing ({} > {})', + size[0], maxwidth) + return True + def resize(self, maxwidth, path_in, path_out=None): """Manipulate an image file according to the method, returning a new path. For PIL or IMAGEMAGIC methods, resizes the image to a diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 57d8e4c46..efa2f5bde 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -42,10 +42,6 @@ IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' -CANDIDATE_BAD = 0 -CANDIDATE_EXACT = 1 -CANDIDATE_DOWNSCALE = 2 - def _logged_get(log, *args, **kwargs): """Like `requests.get`, but logs the effective URL to the specified @@ -535,51 +531,6 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self._log.debug('error fetching art: {}', exc) return None - def _is_valid_image_candidate(self, candidate): - """Determine whether the given candidate artwork is valid based on - its dimensions (width and ratio). - - Return `CANDIDATE_BAD` if the file is unusable. - Return `CANDIDATE_EXACT` if the file is usable as-is. - Return `CANDIDATE_DOWNSCALE` if the file must be resized. - """ - if not candidate: - return CANDIDATE_BAD - - if not (self.enforce_ratio or self.minwidth or self.maxwidth): - return CANDIDATE_EXACT - - # get_size returns None if no local imaging backend is available - size = ArtResizer.shared.get_size(candidate) - self._log.debug('image size: {}', size) - - if not size: - self._log.warning(u'Could not get size of image (please see ' - u'documentation for dependencies). ' - u'The configuration options `minwidth` and ' - u'`enforce_ratio` may be violated.') - return CANDIDATE_EXACT - - # Check minimum size. - if self.minwidth and size[0] < self.minwidth: - self._log.debug('image too small ({} < {})', - size[0], self.minwidth) - return CANDIDATE_BAD - - # Check aspect ratio. - if self.enforce_ratio and size[0] != size[1]: - self._log.debug('image is not square ({} != {})', - size[0], size[1]) - return CANDIDATE_BAD - - # Check maximum size. - if self.maxwidth and size[0] > self.maxwidth: - self._log.debug('image needs resizing ({} > {})', - size[0], self.maxwidth) - return CANDIDATE_DOWNSCALE - - return CANDIDATE_EXACT - def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the album (or None if no art is found). If `maxwidth`, then images are @@ -588,7 +539,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): are made. """ out = None - check = None + size = None # Local art. cover_names = self.config['cover_names'].as_str_seq() @@ -597,11 +548,21 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if paths: for path in paths: candidate = self.fs_source.get(path, cover_names, cautious) - check = self._is_valid_image_candidate(candidate) - if check: - out = candidate - self._log.debug('found local image {}', out) - break + if not candidate: + continue + + # get_size returns None if no local imaging backend is available + size = ArtResizer.shared.get_size(candidate) + self._log.debug('image size: {}', size) + if size: + valid = ArtResizer.shared.valid_size(size, + self.enforce_ratio, self.minwidth) + if not valid: + continue + + out = candidate + self._log.debug('found local image {}', out) + break # Web art sources. remote_priority = self.config['remote_priority'].get(bool) @@ -610,13 +571,23 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if self.maxwidth: url = ArtResizer.shared.proxy_url(self.maxwidth, url) candidate = self._fetch_image(url) - check = self._is_valid_image_candidate(candidate) - if check: - out = candidate - self._log.debug('using remote image {}', out) - break + if not candidate: + continue - if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: + # get_size returns None if no local imaging backend is available + size = ArtResizer.shared.get_size(candidate) + self._log.debug('image size: {}', size) + if size: + valid = ArtResizer.shared.valid_size(size, + self.enforce_ratio, self.minwidth) + if not valid: + continue + + out = candidate + self._log.debug('using remote image {}', out) + break + + if self.maxwidth and out and ArtResizer.shared.must_resize(size, self.maxwidth): out = ArtResizer.shared.resize(self.maxwidth, out) return out From 04c12a50ac0124c77cdc02e0dd6251004e76c6db Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 12:44:56 +1030 Subject: [PATCH 0571/2280] add copy_album_art_maxwidth config option to convert plugin --- beetsplug/convert.py | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 6145fdb74..0e0ad5817 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -29,6 +29,7 @@ from beets import ui, util, plugins, config from beets.plugins import BeetsPlugin from beets.util.confit import ConfigTypeError from beets import art +from beets.util.artresizer import ArtResizer _fs_lock = threading.Lock() _temp_files = [] # Keep track of temporary transcoded files for deletion. @@ -132,6 +133,7 @@ class ConvertPlugin(BeetsPlugin): u'paths': {}, u'never_convert_lossy_files': False, u'copy_album_art': False, + u'copy_album_art_maxwidth': 0, }) self.import_stages = [self.auto_convert] @@ -305,8 +307,8 @@ class ConvertPlugin(BeetsPlugin): dest=converted, keepnew=False) def copy_album_art(self, album, dest_dir, path_formats, pretend=False): - """Copies the associated cover art of the album. Album must have at - least one track. + """Copies or converts the associated cover art of the album. Album must + have at least one track. """ if not album or not album.artpath: return @@ -336,14 +338,33 @@ class ConvertPlugin(BeetsPlugin): util.displayable_path(album.artpath)) return - if pretend: - self._log.info(u'cp {0} {1}', - util.displayable_path(album.artpath), - util.displayable_path(dest)) + resize = False + maxwidth = None + + if self.config['copy_album_art_maxwidth']: + maxwidth = self.config['copy_album_art_maxwidth'].get(int) + size = ArtResizer.shared.get_size(album.artpath) + if size: + resize = ArtResizer.shared.must_resize(size, maxwidth) + + if resize: + if pretend: + self._log.info(u'resize_artwork {0} {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + else: + self._log.info(u'Converting cover art to {0}', + util.displayable_path(dest)) + ArtResizer.shared.resize(maxwidth, album.artpath, dest) else: - self._log.info(u'Copying cover art to {0}', - util.displayable_path(dest)) - util.copy(album.artpath, dest) + if pretend: + self._log.info(u'cp {0} {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + else: + self._log.info(u'Copying cover art to {0}', + util.displayable_path(dest)) + util.copy(album.artpath, dest) def convert_func(self, lib, opts, args): if not opts.dest: From e1890f836ead8298064bd92849c58220ff04b655 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:27:08 +0100 Subject: [PATCH 0572/2280] Removed unicode_literals from test_types_plugin --- test/test_types_plugin.py | 79 +++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index ba3fa54e1..92cab3397 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import time from datetime import datetime @@ -37,69 +36,69 @@ class TypesPluginTest(unittest.TestCase, TestHelper): def test_integer_modify_and_query(self): self.config['types'] = {'myint': 'int'} - item = self.add_item(artist='aaa') + item = self.add_item(artist=u'aaa') # Do not match unset values - out = self.list('myint:1..3') - self.assertEqual('', out) + out = self.list(u'myint:1..3') + self.assertEqual(u'', out) - self.modify('myint=2') + self.modify(u'myint=2') item.load() self.assertEqual(item['myint'], 2) # Match in range - out = self.list('myint:1..3') + out = self.list(u'myint:1..3') self.assertIn(b'aaa', out) def test_album_integer_modify_and_query(self): - self.config['types'] = {'myint': 'int'} - album = self.add_album(albumartist='aaa') + self.config['types'] = {'myint': u'int'} + album = self.add_album(albumartist=u'aaa') # Do not match unset values - out = self.list_album('myint:1..3') - self.assertEqual('', out) + out = self.list_album(u'myint:1..3') + self.assertEqual(u'', out) - self.modify('-a', 'myint=2') + self.modify(u'-a', u'myint=2') album.load() self.assertEqual(album['myint'], 2) # Match in range - out = self.list_album('myint:1..3') + out = self.list_album(u'myint:1..3') self.assertIn(b'aaa', out) def test_float_modify_and_query(self): - self.config['types'] = {'myfloat': 'float'} - item = self.add_item(artist='aaa') + self.config['types'] = {'myfloat': u'float'} + item = self.add_item(artist=u'aaa') - self.modify('myfloat=-9.1') + self.modify(u'myfloat=-9.1') item.load() self.assertEqual(item['myfloat'], -9.1) # Match in range - out = self.list('myfloat:-10..0') + out = self.list(u'myfloat:-10..0') self.assertIn(b'aaa', out) def test_bool_modify_and_query(self): - self.config['types'] = {'mybool': 'bool'} - true = self.add_item(artist='true') - false = self.add_item(artist='false') - self.add_item(artist='unset') + self.config['types'] = {'mybool': u'bool'} + true = self.add_item(artist=u'true') + false = self.add_item(artist=u'false') + self.add_item(artist=u'unset') # Set true - self.modify('mybool=1', 'artist:true') + self.modify(u'mybool=1', u'artist:true') true.load() self.assertEqual(true['mybool'], True) # Set false - self.modify('mybool=false', 'artist:false') + self.modify(u'mybool=false', u'artist:false') false.load() self.assertEqual(false['mybool'], False) # Query bools - out = self.list('mybool:true', '$artist $mybool') - self.assertEqual('true True', out) + out = self.list(u'mybool:true', u'$artist $mybool') + self.assertEqual(u'true True', out) - out = self.list('mybool:false', '$artist $mybool') + out = self.list(u'mybool:false', u'$artist $mybool') # Dealing with unset fields? # self.assertEqual('false False', out) @@ -107,23 +106,23 @@ class TypesPluginTest(unittest.TestCase, TestHelper): # self.assertIn('unset $mybool', out) def test_date_modify_and_query(self): - self.config['types'] = {'mydate': 'date'} + self.config['types'] = {'mydate': u'date'} # FIXME parsing should also work with default time format self.config['time_format'] = '%Y-%m-%d' - old = self.add_item(artist='prince') - new = self.add_item(artist='britney') + old = self.add_item(artist=u'prince') + new = self.add_item(artist=u'britney') - self.modify('mydate=1999-01-01', 'artist:prince') + self.modify(u'mydate=1999-01-01', u'artist:prince') old.load() self.assertEqual(old['mydate'], mktime(1999, 01, 01)) - self.modify('mydate=1999-12-30', 'artist:britney') + self.modify(u'mydate=1999-12-30', u'artist:britney') new.load() self.assertEqual(new['mydate'], mktime(1999, 12, 30)) # Match in range - out = self.list('mydate:..1999-07', '$artist $mydate') - self.assertEqual('prince 1999-01-01', out) + out = self.list(u'mydate:..1999-07', u'$artist $mydate') + self.assertEqual(u'prince 1999-01-01', out) # FIXME some sort of timezone issue here # out = self.list('mydate:1999-12-30', '$artist $mydate') @@ -132,17 +131,17 @@ class TypesPluginTest(unittest.TestCase, TestHelper): def test_unknown_type_error(self): self.config['types'] = {'flex': 'unkown type'} with self.assertRaises(ConfigValueError): - self.run_command('ls') + self.run_command(u'ls') def modify(self, *args): - return self.run_with_output('modify', '--yes', '--nowrite', - '--nomove', *args) + return self.run_with_output(u'modify', u'--yes', u'--nowrite', + u'--nomove', *args) - def list(self, query, fmt='$artist - $album - $title'): - return self.run_with_output('ls', '-f', fmt, query).strip() + def list(self, query, fmt=u'$artist - $album - $title'): + return self.run_with_output(u'ls', u'-f', fmt, query).strip() - def list_album(self, query, fmt='$albumartist - $album - $title'): - return self.run_with_output('ls', '-a', '-f', fmt, query).strip() + def list_album(self, query, fmt=u'$albumartist - $album - $title'): + return self.run_with_output(u'ls', u'-a', u'-f', fmt, query).strip() def mktime(*args): From 867dafea91228ca1bb253ddc563bb6efec49d45a Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:36:21 +0100 Subject: [PATCH 0573/2280] Removed unicode_literals form test_sort --- test/test_sort.py | 290 +++++++++++++++++++++++----------------------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/test/test_sort.py b/test/test_sort.py index dc4e6d2b2..7dadbcf79 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -15,8 +15,7 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test import _common from test._common import unittest @@ -33,71 +32,71 @@ class DummyDataTestCase(_common.TestCase): self.lib = beets.library.Library(':memory:') albums = [_common.album() for _ in range(3)] - albums[0].album = "Album A" - albums[0].genre = "Rock" + albums[0].album = u"Album A" + albums[0].genre = u"Rock" albums[0].year = 2001 - albums[0].flex1 = "Flex1-1" - albums[0].flex2 = "Flex2-A" - albums[0].albumartist = "Foo" + albums[0].flex1 = u"Flex1-1" + albums[0].flex2 = u"Flex2-A" + albums[0].albumartist = u"Foo" albums[0].albumartist_sort = None - albums[1].album = "Album B" - albums[1].genre = "Rock" + albums[1].album = u"Album B" + albums[1].genre = u"Rock" albums[1].year = 2001 - albums[1].flex1 = "Flex1-2" - albums[1].flex2 = "Flex2-A" - albums[1].albumartist = "Bar" + albums[1].flex1 = u"Flex1-2" + albums[1].flex2 = u"Flex2-A" + albums[1].albumartist = u"Bar" albums[1].albumartist_sort = None - albums[2].album = "Album C" - albums[2].genre = "Jazz" + albums[2].album = u"Album C" + albums[2].genre = u"Jazz" albums[2].year = 2005 - albums[2].flex1 = "Flex1-1" - albums[2].flex2 = "Flex2-B" - albums[2].albumartist = "Baz" + albums[2].flex1 = u"Flex1-1" + albums[2].flex2 = u"Flex2-B" + albums[2].albumartist = u"Baz" albums[2].albumartist_sort = None for album in albums: self.lib.add(album) items = [_common.item() for _ in range(4)] - items[0].title = 'Foo bar' - items[0].artist = 'One' - items[0].album = 'Baz' + items[0].title = u'Foo bar' + items[0].artist = u'One' + items[0].album = u'Baz' items[0].year = 2001 items[0].comp = True - items[0].flex1 = "Flex1-0" - items[0].flex2 = "Flex2-A" + items[0].flex1 = u"Flex1-0" + items[0].flex2 = u"Flex2-A" items[0].album_id = albums[0].id items[0].artist_sort = None items[0].path = "/path0.mp3" items[0].track = 1 - items[1].title = 'Baz qux' - items[1].artist = 'Two' - items[1].album = 'Baz' + items[1].title = u'Baz qux' + items[1].artist = u'Two' + items[1].album = u'Baz' items[1].year = 2002 items[1].comp = True - items[1].flex1 = "Flex1-1" - items[1].flex2 = "Flex2-A" + items[1].flex1 = u"Flex1-1" + items[1].flex2 = u"Flex2-A" items[1].album_id = albums[0].id items[1].artist_sort = None items[1].path = "/patH1.mp3" items[1].track = 2 - items[2].title = 'Beets 4 eva' - items[2].artist = 'Three' - items[2].album = 'Foo' + items[2].title = u'Beets 4 eva' + items[2].artist = u'Three' + items[2].album = u'Foo' items[2].year = 2003 items[2].comp = False - items[2].flex1 = "Flex1-2" - items[2].flex2 = "Flex1-B" + items[2].flex1 = u"Flex1-2" + items[2].flex2 = u"Flex1-B" items[2].album_id = albums[1].id items[2].artist_sort = None items[2].path = "/paTH2.mp3" items[2].track = 3 - items[3].title = 'Beets 4 eva' - items[3].artist = 'Three' - items[3].album = 'Foo2' + items[3].title = u'Beets 4 eva' + items[3].artist = u'Three' + items[3].album = u'Foo2' items[3].year = 2004 items[3].comp = False - items[3].flex1 = "Flex1-2" - items[3].flex2 = "Flex1-C" + items[3].flex1 = u"Flex1-2" + items[3].flex2 = u"Flex1-C" items[3].album_id = albums[2].id items[3].artist_sort = None items[3].path = "/PATH3.mp3" @@ -108,50 +107,50 @@ class DummyDataTestCase(_common.TestCase): class SortFixedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", True) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", True) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2001) # same thing with query string - q = 'year+' + q = u'year+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", False) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", False) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2004) # same thing with query string - q = 'year-' + q = u'year-' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.FixedFieldSort("album", True) - s2 = dbcore.query.FixedFieldSort("year", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"album", True) + s2 = dbcore.query.FixedFieldSort(u"year", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['album'], results[1]['album']) self.assertLessEqual(results[1]['album'], results[2]['album']) - self.assertEqual(results[0]['album'], 'Baz') - self.assertEqual(results[1]['album'], 'Baz') + self.assertEqual(results[0]['album'], u'Baz') + self.assertEqual(results[1]['album'], u'Baz') self.assertLessEqual(results[0]['year'], results[1]['year']) # same thing with query string - q = 'album+ year+' + q = u'album+ year+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_path_field(self): - q = '' + q = u'' sort = dbcore.query.FixedFieldSort('path', True) results = self.lib.items(q, sort) self.assertEqual(results[0]['path'], '/path0.mp3') @@ -162,46 +161,46 @@ class SortFixedFieldTest(DummyDataTestCase): class SortFlexFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", True) results = self.lib.items(q, sort) self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) - self.assertEqual(results[0]['flex1'], 'Flex1-0') + self.assertEqual(results[0]['flex1'], u'Flex1-0') # same thing with query string - q = 'flex1+' + q = u'flex1+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", False) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['flex1'], results[1]['flex1']) self.assertGreaterEqual(results[1]['flex1'], results[2]['flex1']) self.assertGreaterEqual(results[2]['flex1'], results[3]['flex1']) - self.assertEqual(results[0]['flex1'], 'Flex1-2') + self.assertEqual(results[0]['flex1'], u'Flex1-2') # same thing with query string - q = 'flex1-' + q = u'flex1-' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field(self): - q = '' - s1 = dbcore.query.SlowFieldSort("flex2", False) - s2 = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"flex2", False) + s2 = dbcore.query.SlowFieldSort(u"flex1", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.items(q, sort) self.assertGreaterEqual(results[0]['flex2'], results[1]['flex2']) self.assertGreaterEqual(results[1]['flex2'], results[2]['flex2']) - self.assertEqual(results[0]['flex2'], 'Flex2-A') - self.assertEqual(results[1]['flex2'], 'Flex2-A') + self.assertEqual(results[0]['flex2'], u'Flex2-A') + self.assertEqual(results[1]['flex2'], u'Flex2-A') self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) # same thing with query string - q = 'flex2- flex1+' + q = u'flex2- flex1+' results2 = self.lib.items(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -209,44 +208,44 @@ class SortFlexFieldTest(DummyDataTestCase): class SortAlbumFixedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", True) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2001) # same thing with query string - q = 'year+' + q = u'year+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.FixedFieldSort("year", False) + q = u'' + sort = dbcore.query.FixedFieldSort(u"year", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['year'], results[1]['year']) self.assertEqual(results[0]['year'], 2005) # same thing with query string - q = 'year-' + q = u'year-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.FixedFieldSort("genre", True) - s2 = dbcore.query.FixedFieldSort("album", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"genre", True) + s2 = dbcore.query.FixedFieldSort(u"album", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['genre'], results[1]['genre']) self.assertLessEqual(results[1]['genre'], results[2]['genre']) - self.assertEqual(results[1]['genre'], 'Rock') - self.assertEqual(results[2]['genre'], 'Rock') + self.assertEqual(results[1]['genre'], u'Rock') + self.assertEqual(results[2]['genre'], u'Rock') self.assertLessEqual(results[1]['album'], results[2]['album']) # same thing with query string - q = 'genre+ album+' + q = u'genre+ album+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -254,44 +253,44 @@ class SortAlbumFixedFieldTest(DummyDataTestCase): class SortAlbumFlexFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) self.assertLessEqual(results[1]['flex1'], results[2]['flex1']) # same thing with query string - q = 'flex1+' + q = u'flex1+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("flex1", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"flex1", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['flex1'], results[1]['flex1']) self.assertGreaterEqual(results[1]['flex1'], results[2]['flex1']) # same thing with query string - q = 'flex1-' + q = u'flex1-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_two_field_asc(self): - q = '' - s1 = dbcore.query.SlowFieldSort("flex2", True) - s2 = dbcore.query.SlowFieldSort("flex1", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"flex2", True) + s2 = dbcore.query.SlowFieldSort(u"flex1", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['flex2'], results[1]['flex2']) self.assertLessEqual(results[1]['flex2'], results[2]['flex2']) - self.assertEqual(results[0]['flex2'], 'Flex2-A') - self.assertEqual(results[1]['flex2'], 'Flex2-A') + self.assertEqual(results[0]['flex2'], u'Flex2-A') + self.assertEqual(results[1]['flex2'], u'Flex2-A') self.assertLessEqual(results[0]['flex1'], results[1]['flex1']) # same thing with query string - q = 'flex2+ flex1+' + q = u'flex2+ flex1+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -299,25 +298,25 @@ class SortAlbumFlexFieldTest(DummyDataTestCase): class SortAlbumComputedFieldTest(DummyDataTestCase): def test_sort_asc(self): - q = '' - sort = dbcore.query.SlowFieldSort("path", True) + q = u'' + sort = dbcore.query.SlowFieldSort(u"path", True) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['path'], results[1]['path']) self.assertLessEqual(results[1]['path'], results[2]['path']) # same thing with query string - q = 'path+' + q = u'path+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_sort_desc(self): - q = '' - sort = dbcore.query.SlowFieldSort("path", False) + q = u'' + sort = dbcore.query.SlowFieldSort(u"path", False) results = self.lib.albums(q, sort) self.assertGreaterEqual(results[0]['path'], results[1]['path']) self.assertGreaterEqual(results[1]['path'], results[2]['path']) # same thing with query string - q = 'path-' + q = u'path-' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -325,24 +324,24 @@ class SortAlbumComputedFieldTest(DummyDataTestCase): class SortCombinedFieldTest(DummyDataTestCase): def test_computed_first(self): - q = '' - s1 = dbcore.query.SlowFieldSort("path", True) - s2 = dbcore.query.FixedFieldSort("year", True) + q = u'' + s1 = dbcore.query.SlowFieldSort(u"path", True) + s2 = dbcore.query.FixedFieldSort(u"year", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) results = self.lib.albums(q, sort) self.assertLessEqual(results[0]['path'], results[1]['path']) self.assertLessEqual(results[1]['path'], results[2]['path']) - q = 'path+ year+' + q = u'path+ year+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) def test_computed_second(self): - q = '' - s1 = dbcore.query.FixedFieldSort("year", True) - s2 = dbcore.query.SlowFieldSort("path", True) + q = u'' + s1 = dbcore.query.FixedFieldSort(u"year", True) + s2 = dbcore.query.SlowFieldSort(u"path", True) sort = dbcore.query.MultipleSort() sort.add_sort(s1) sort.add_sort(s2) @@ -350,7 +349,7 @@ class SortCombinedFieldTest(DummyDataTestCase): self.assertLessEqual(results[0]['year'], results[1]['year']) self.assertLessEqual(results[1]['year'], results[2]['year']) self.assertLessEqual(results[0]['path'], results[1]['path']) - q = 'year+ path+' + q = u'year+ path+' results2 = self.lib.albums(q) for r1, r2 in zip(results, results2): self.assertEqual(r1.id, r2.id) @@ -385,23 +384,23 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): super(CaseSensitivityTest, self).setUp() album = _common.album() - album.album = "album" - album.genre = "alternative" - album.year = "2001" - album.flex1 = "flex1" - album.flex2 = "flex2-A" - album.albumartist = "bar" + album.album = u"album" + album.genre = u"alternative" + album.year = u"2001" + album.flex1 = u"flex1" + album.flex2 = u"flex2-A" + album.albumartist = u"bar" album.albumartist_sort = None self.lib.add(album) item = _common.item() - item.title = 'another' - item.artist = 'lowercase' - item.album = 'album' + item.title = u'another' + item.artist = u'lowercase' + item.album = u'album' item.year = 2001 item.comp = True - item.flex1 = "flex1" - item.flex2 = "flex2-A" + item.flex1 = u"flex1" + item.flex2 = u"flex2-A" item.album_id = album.id item.artist_sort = None item.track = 10 @@ -417,49 +416,49 @@ class CaseSensitivityTest(DummyDataTestCase, _common.TestCase): def test_smart_artist_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'artist+' + q = u'artist+' results = list(self.lib.items(q)) - self.assertEqual(results[0].artist, 'lowercase') - self.assertEqual(results[1].artist, 'One') + self.assertEqual(results[0].artist, u'lowercase') + self.assertEqual(results[1].artist, u'One') def test_smart_artist_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'artist+' + q = u'artist+' results = list(self.lib.items(q)) - self.assertEqual(results[0].artist, 'One') - self.assertEqual(results[-1].artist, 'lowercase') + self.assertEqual(results[0].artist, u'One') + self.assertEqual(results[-1].artist, u'lowercase') def test_fixed_field_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'album+' + q = u'album+' results = list(self.lib.albums(q)) - self.assertEqual(results[0].album, 'album') - self.assertEqual(results[1].album, 'Album A') + self.assertEqual(results[0].album, u'album') + self.assertEqual(results[1].album, u'Album A') def test_fixed_field_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'album+' + q = u'album+' results = list(self.lib.albums(q)) - self.assertEqual(results[0].album, 'Album A') - self.assertEqual(results[-1].album, 'album') + self.assertEqual(results[0].album, u'Album A') + self.assertEqual(results[-1].album, u'album') def test_flex_field_case_insensitive(self): config['sort_case_insensitive'] = True - q = 'flex1+' + q = u'flex1+' results = list(self.lib.items(q)) - self.assertEqual(results[0].flex1, 'flex1') - self.assertEqual(results[1].flex1, 'Flex1-0') + self.assertEqual(results[0].flex1, u'flex1') + self.assertEqual(results[1].flex1, u'Flex1-0') def test_flex_field_case_sensitive(self): config['sort_case_insensitive'] = False - q = 'flex1+' + q = u'flex1+' results = list(self.lib.items(q)) - self.assertEqual(results[0].flex1, 'Flex1-0') - self.assertEqual(results[-1].flex1, 'flex1') + self.assertEqual(results[0].flex1, u'Flex1-0') + self.assertEqual(results[-1].flex1, u'flex1') def test_case_sensitive_only_affects_text(self): config['sort_case_insensitive'] = True - q = 'track+' + q = u'track+' results = list(self.lib.items(q)) # If the numerical values were sorted as strings, # then ['1', '10', '2'] would be valid. @@ -473,9 +472,10 @@ class NonExistingFieldTest(DummyDataTestCase): """Test sorting by non-existing fields""" def test_non_existing_fields_not_fail(self): - qs = ['foo+', 'foo-', '--', '-+', '+-', '++', '-foo-', '-foo+', '---'] + qs = [u'foo+', u'foo-', u'--', u'-+', u'+-', + u'++', u'-foo-', u'-foo+', u'---'] - q0 = 'foo+' + q0 = u'foo+' results0 = list(self.lib.items(q0)) for q1 in qs: results1 = list(self.lib.items(q1)) @@ -483,16 +483,16 @@ class NonExistingFieldTest(DummyDataTestCase): self.assertEqual(r1.id, r2.id) def test_combined_non_existing_field_asc(self): - all_results = list(self.lib.items('id+')) - q = 'foo+ id+' + all_results = list(self.lib.items(u'id+')) + q = u'foo+ id+' results = list(self.lib.items(q)) self.assertEqual(len(all_results), len(results)) for r1, r2 in zip(all_results, results): self.assertEqual(r1.id, r2.id) def test_combined_non_existing_field_desc(self): - all_results = list(self.lib.items('id+')) - q = 'foo- id+' + all_results = list(self.lib.items(u'id+')) + q = u'foo- id+' results = list(self.lib.items(q)) self.assertEqual(len(all_results), len(results)) for r1, r2 in zip(all_results, results): @@ -501,18 +501,18 @@ class NonExistingFieldTest(DummyDataTestCase): def test_field_present_in_some_items(self): """Test ordering by a field not present on all items.""" # append 'foo' to two to items (1,2) - items = self.lib.items('id+') + items = self.lib.items(u'id+') ids = [i.id for i in items] - items[1].foo = 'bar1' - items[2].foo = 'bar2' + items[1].foo = u'bar1' + items[2].foo = u'bar2' items[1].store() items[2].store() - results_asc = list(self.lib.items('foo+ id+')) + results_asc = list(self.lib.items(u'foo+ id+')) self.assertEqual([i.id for i in results_asc], # items without field first [ids[0], ids[3], ids[1], ids[2]]) - results_desc = list(self.lib.items('foo- id+')) + results_desc = list(self.lib.items(u'foo- id+')) self.assertEqual([i.id for i in results_desc], # items without field last [ids[2], ids[1], ids[0], ids[3]]) @@ -523,13 +523,13 @@ class NonExistingFieldTest(DummyDataTestCase): If a string ends with a sorting suffix, it takes precedence over the NotQuery parsing. """ - query, sort = beets.library.parse_query_string('-bar+', + query, sort = beets.library.parse_query_string(u'-bar+', beets.library.Item) self.assertEqual(len(query.subqueries), 1) self.assertTrue(isinstance(query.subqueries[0], dbcore.query.TrueQuery)) self.assertTrue(isinstance(sort, dbcore.query.SlowFieldSort)) - self.assertEqual(sort.field, '-bar') + self.assertEqual(sort.field, u'-bar') def suite(): From 27c6c3d6da2df4772f4f977bdf6ed3d18955fc99 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:38:38 +0100 Subject: [PATCH 0574/2280] Removed unicode_literals from test_replaygain --- test/test_replaygain.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 5b20f5f3b..11cedeecb 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest from test.helper import TestHelper, has_program @@ -95,7 +94,7 @@ class ReplayGainCliTestBase(TestHelper): # that it could only happen if the decoder plugins are missing. if all(i.rg_track_peak is None and i.rg_track_gain is None for i in self.lib.items()): - self.skipTest('decoder plugins could not be loaded.') + self.skipTest(u'decoder plugins could not be loaded.') for item in self.lib.items(): self.assertIsNotNone(item.rg_track_peak) @@ -107,11 +106,11 @@ class ReplayGainCliTestBase(TestHelper): mediafile.rg_track_gain, item.rg_track_gain, places=2) def test_cli_skips_calculated_tracks(self): - self.run_command('replaygain') + self.run_command(u'replaygain') item = self.lib.items()[0] peak = item.rg_track_peak item.rg_track_gain = 0.0 - self.run_command('replaygain') + self.run_command(u'replaygain') self.assertEqual(item.rg_track_gain, 0.0) self.assertEqual(item.rg_track_peak, peak) @@ -121,7 +120,7 @@ class ReplayGainCliTestBase(TestHelper): self.assertIsNone(mediafile.rg_album_peak) self.assertIsNone(mediafile.rg_album_gain) - self.run_command('replaygain', '-a') + self.run_command(u'replaygain', u'-a') peaks = [] gains = [] @@ -138,7 +137,7 @@ class ReplayGainCliTestBase(TestHelper): self.assertNotEqual(max(peaks), 0.0) -@unittest.skipIf(not GST_AVAILABLE, 'gstreamer cannot be found') +@unittest.skipIf(not GST_AVAILABLE, u'gstreamer cannot be found') class ReplayGainGstCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'gstreamer' @@ -155,12 +154,12 @@ class ReplayGainGstCliTest(ReplayGainCliTestBase, unittest.TestCase): super(ReplayGainGstCliTest, self).setUp() -@unittest.skipIf(not GAIN_PROG_AVAILABLE, 'no *gain command found') +@unittest.skipIf(not GAIN_PROG_AVAILABLE, u'no *gain command found') class ReplayGainCmdCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'command' -@unittest.skipIf(not LOUDNESS_PROG_AVAILABLE, 'bs1770gain cannot be found') +@unittest.skipIf(not LOUDNESS_PROG_AVAILABLE, u'bs1770gain cannot be found') class ReplayGainLdnsCliTest(ReplayGainCliTestBase, unittest.TestCase): backend = u'bs1770gain' From 47e5d15a78b5b785212bf9edef0602b0210c7356 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:43:12 +0100 Subject: [PATCH 0575/2280] Removed unicode_literals from test_smartplaylist --- test/test_smartplaylist.py | 87 ++++++++++++++++++++------------------ 1 file changed, 46 insertions(+), 41 deletions(-) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index c5ac4fb5b..40992c0fd 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from os import path, remove from tempfile import mkdtemp @@ -46,36 +45,42 @@ class SmartPlaylistTest(unittest.TestCase): self.assertEqual(spl._unmatched_playlists, set()) config['smartplaylist']['playlists'].set([ - {'name': 'foo', - 'query': 'FOO foo'}, - {'name': 'bar', - 'album_query': ['BAR bar1', 'BAR bar2']}, - {'name': 'baz', - 'query': 'BAZ baz', - 'album_query': 'BAZ baz'} + {'name': u'foo', + 'query': u'FOO foo'}, + {'name': u'bar', + 'album_query': [u'BAR bar1', u'BAR bar2']}, + {'name': u'baz', + 'query': u'BAZ baz', + 'album_query': u'BAZ baz'} ]) spl.build_queries() self.assertEqual(spl._matched_playlists, set()) - foo_foo = parse_query_string('FOO foo', Item) - baz_baz = parse_query_string('BAZ baz', Item) - baz_baz2 = parse_query_string('BAZ baz', Album) - bar_bar = OrQuery((parse_query_string('BAR bar1', Album)[0], - parse_query_string('BAR bar2', Album)[0])) + foo_foo = parse_query_string(u'FOO foo', Item) + baz_baz = parse_query_string(u'BAZ baz', Item) + baz_baz2 = parse_query_string(u'BAZ baz', Album) + bar_bar = OrQuery((parse_query_string(u'BAR bar1', Album)[0], + parse_query_string(u'BAR bar2', Album)[0])) self.assertEqual(spl._unmatched_playlists, set([ - ('foo', foo_foo, (None, None)), - ('baz', baz_baz, baz_baz2), - ('bar', (None, None), (bar_bar, None)), + (u'foo', foo_foo, (None, None)), + (u'baz', baz_baz, baz_baz2), + (u'bar', (None, None), (bar_bar, None)), ])) def test_build_queries_with_sorts(self): spl = SmartPlaylistPlugin() config['smartplaylist']['playlists'].set([ - {'name': 'no_sort', 'query': 'foo'}, - {'name': 'one_sort', 'query': 'foo year+'}, - {'name': 'only_empty_sorts', 'query': ['foo', 'bar']}, - {'name': 'one_non_empty_sort', 'query': ['foo year+', 'bar']}, - {'name': 'multiple_sorts', 'query': ['foo year+', 'bar genre-']}, - {'name': 'mixed', 'query': ['foo year+', 'bar', 'baz genre+ id-']} + {'name': u'no_sort', + 'query': u'foo'}, + {'name': u'one_sort', + 'query': u'foo year+'}, + {'name': u'only_empty_sorts', + 'query': [u'foo', u'bar']}, + {'name': u'one_non_empty_sort', + 'query': [u'foo year+', u'bar']}, + {'name': u'multiple_sorts', + 'query': [u'foo year+', u'bar genre-']}, + {'name': u'mixed', + 'query': [u'foo year+', u'bar', u'baz genre+ id-']} ]) spl.build_queries() @@ -85,13 +90,13 @@ class SmartPlaylistTest(unittest.TestCase): asseq = self.assertEqual # less cluttered code S = FixedFieldSort # short cut since we're only dealing with this asseq(sorts["no_sort"], NullSort()) - asseq(sorts["one_sort"], S('year')) + asseq(sorts["one_sort"], S(u'year')) asseq(sorts["only_empty_sorts"], None) - asseq(sorts["one_non_empty_sort"], S('year')) + asseq(sorts["one_non_empty_sort"], S(u'year')) asseq(sorts["multiple_sorts"], - MultipleSort([S('year'), S('genre', False)])) + MultipleSort([S('year'), S(u'genre', False)])) asseq(sorts["mixed"], - MultipleSort([S('year'), S('genre'), S('id', False)])) + MultipleSort([S('year'), S(u'genre'), S(u'id', False)])) def test_matches(self): spl = SmartPlaylistPlugin() @@ -119,25 +124,25 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() nones = None, None - pl1 = '1', ('q1', None), nones - pl2 = '2', ('q2', None), nones - pl3 = '3', ('q3', None), nones + pl1 = '1', (u'q1', None), nones + pl2 = '2', (u'q2', None), nones + pl3 = '3', (u'q3', None), nones spl._unmatched_playlists = set([pl1, pl2, pl3]) spl._matched_playlists = set() spl.matches = Mock(return_value=False) - spl.db_change(None, "nothing") + spl.db_change(None, u"nothing") self.assertEqual(spl._unmatched_playlists, set([pl1, pl2, pl3])) self.assertEqual(spl._matched_playlists, set()) - spl.matches.side_effect = lambda _, q, __: q == 'q3' - spl.db_change(None, "matches 3") + spl.matches.side_effect = lambda _, q, __: q == u'q3' + spl.db_change(None, u"matches 3") self.assertEqual(spl._unmatched_playlists, set([pl1, pl2])) self.assertEqual(spl._matched_playlists, set([pl3])) - spl.matches.side_effect = lambda _, q, __: q == 'q1' - spl.db_change(None, "matches 3") + spl.matches.side_effect = lambda _, q, __: q == u'q1' + spl.db_change(None, u"matches 3") self.assertEqual(spl._matched_playlists, set([pl1, pl3])) self.assertEqual(spl._unmatched_playlists, set([pl2])) @@ -184,7 +189,7 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): {'name': 'my_playlist.m3u', 'query': self.item.title}, {'name': 'all.m3u', - 'query': ''} + 'query': u''} ]) config['smartplaylist']['playlist_dir'].set(self.temp_dir) self.load_plugins('smartplaylist') @@ -195,22 +200,22 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): def test_splupdate(self): with self.assertRaises(UserError): - self.run_with_output('splupdate', 'tagada') + self.run_with_output(u'splupdate', u'tagada') - self.run_with_output('splupdate', 'my_playlist') + self.run_with_output(u'splupdate', u'my_playlist') m3u_path = path.join(self.temp_dir, 'my_playlist.m3u') self.assertTrue(path.exists(m3u_path)) with open(m3u_path, 'r') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) - self.run_with_output('splupdate', 'my_playlist.m3u') + self.run_with_output(u'splupdate', u'my_playlist.m3u') with open(m3u_path, 'r') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) - self.run_with_output('splupdate') - for name in ('my_playlist.m3u', 'all.m3u'): + self.run_with_output(u'splupdate') + for name in (u'my_playlist.m3u', u'all.m3u'): with open(path.join(self.temp_dir, name), 'r') as f: self.assertEqual(f.read(), self.item.path + b"\n") From b4e7f7c80c669bc54d4d2204fb7173d2a30502c2 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:44:29 +0100 Subject: [PATCH 0576/2280] Removed unicode_literals from test_template --- test/test_template.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_template.py b/test/test_template.py index 96100bdfe..0f2273dd2 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -15,8 +15,7 @@ """Tests for template engine. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import warnings From 6ec70d65193e144195da55fbf3e62484de8be47f Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:52:52 +0100 Subject: [PATCH 0577/2280] Removed unicode_literals from test_ui_importer --- test/test_ui_importer.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 4f0de1c92..3248b25a3 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -19,8 +19,7 @@ test_importer module. But here the test importer inherits from ``TerminalImportSession``. So we test this class, too. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test._common import unittest, DummyIO from test import test_importer @@ -59,21 +58,21 @@ class TestTerminalImportSession(TerminalImportSession): choice = self.default_choice if choice == importer.action.APPLY: - self.io.addinput('A') + self.io.addinput(u'A') elif choice == importer.action.ASIS: - self.io.addinput('U') + self.io.addinput(u'U') elif choice == importer.action.ALBUMS: - self.io.addinput('G') + self.io.addinput(u'G') elif choice == importer.action.TRACKS: - self.io.addinput('T') + self.io.addinput(u'T') elif choice == importer.action.SKIP: - self.io.addinput('S') + self.io.addinput(u'S') elif isinstance(choice, int): - self.io.addinput('M') + self.io.addinput(u'M') self.io.addinput(unicode(choice)) self._add_choice_input() else: - raise Exception('Unknown choice %s' % choice) + raise Exception(u'Unknown choice %s' % choice) class TerminalImportSessionSetup(object): From ccc61a638ef1bd2bd04ef101971cd3bbb5594790 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 25 Feb 2016 07:53:20 +0100 Subject: [PATCH 0578/2280] Removed unicode_literals from test_util --- test/test_util.py | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/test/test_util.py b/test/test_util.py index 6d4707273..c7b15650b 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """Tests for base utils from the beets.util package. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import sys import re @@ -43,39 +42,39 @@ class UtilTest(unittest.TestCase): @patch('os.execlp') @patch('beets.util.open_anything') def test_interactive_open(self, mock_open, mock_execlp): - mock_open.return_value = 'tagada' + mock_open.return_value = u'tagada' util.interactive_open(['foo'], util.open_anything()) - mock_execlp.assert_called_once_with('tagada', 'tagada', 'foo') + mock_execlp.assert_called_once_with(u'tagada', u'tagada', u'foo') mock_execlp.reset_mock() - util.interactive_open(['foo'], 'bar') - mock_execlp.assert_called_once_with('bar', 'bar', 'foo') + util.interactive_open(['foo'], u'bar') + mock_execlp.assert_called_once_with(u'bar', u'bar', u'foo') def test_sanitize_unix_replaces_leading_dot(self): with _common.platform_posix(): p = util.sanitize_path(u'one/.two/three') - self.assertFalse('.' in p) + self.assertFalse(u'.' in p) def test_sanitize_windows_replaces_trailing_dot(self): with _common.platform_windows(): p = util.sanitize_path(u'one/two./three') - self.assertFalse('.' in p) + self.assertFalse(u'.' in p) def test_sanitize_windows_replaces_illegal_chars(self): with _common.platform_windows(): p = util.sanitize_path(u':*?"<>|') - self.assertFalse(':' in p) - self.assertFalse('*' in p) - self.assertFalse('?' in p) - self.assertFalse('"' in p) - self.assertFalse('<' in p) - self.assertFalse('>' in p) - self.assertFalse('|' in p) + self.assertFalse(u':' in p) + self.assertFalse(u'*' in p) + self.assertFalse(u'?' in p) + self.assertFalse(u'"' in p) + self.assertFalse(u'<' in p) + self.assertFalse(u'>' in p) + self.assertFalse(u'|' in p) def test_sanitize_windows_replaces_trailing_space(self): with _common.platform_windows(): p = util.sanitize_path(u'one/two /three') - self.assertFalse(' ' in p) + self.assertFalse(u' ' in p) def test_sanitize_path_works_on_empty_string(self): with _common.platform_posix(): @@ -96,7 +95,7 @@ class UtilTest(unittest.TestCase): ]) self.assertEqual(p, u'bar/bar') - @unittest.skip('unimplemented: #359') + @unittest.skip(u'unimplemented: #359') def test_sanitize_empty_component(self): with _common.platform_posix(): p = util.sanitize_path(u'foo//bar', [ @@ -108,7 +107,7 @@ class UtilTest(unittest.TestCase): def test_command_output(self, mock_popen): def popen_fail(*args, **kwargs): m = Mock(returncode=1) - m.communicate.return_value = 'foo', 'bar' + m.communicate.return_value = u'foo', u'bar' return m mock_popen.side_effect = popen_fail @@ -121,7 +120,7 @@ class UtilTest(unittest.TestCase): class PathConversionTest(_common.TestCase): def test_syspath_windows_format(self): with _common.platform_windows(): - path = os.path.join('a', 'b', 'c') + path = os.path.join(u'a', u'b', u'c') outpath = util.syspath(path) self.assertTrue(isinstance(outpath, unicode)) self.assertTrue(outpath.startswith(u'\\\\?\\')) @@ -137,7 +136,7 @@ class PathConversionTest(_common.TestCase): def test_syspath_posix_unchanged(self): with _common.platform_posix(): - path = os.path.join('a', 'b', 'c') + path = os.path.join(u'a', u'b', u'c') outpath = util.syspath(path) self.assertEqual(path, outpath) From 1fc6efe3b4b0bad39379144ab2e3b8318545c151 Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 18:45:53 +1030 Subject: [PATCH 0579/2280] fix indentation --- beetsplug/convert.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 0e0ad5817..a99d1983d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -342,10 +342,10 @@ class ConvertPlugin(BeetsPlugin): maxwidth = None if self.config['copy_album_art_maxwidth']: - maxwidth = self.config['copy_album_art_maxwidth'].get(int) - size = ArtResizer.shared.get_size(album.artpath) - if size: - resize = ArtResizer.shared.must_resize(size, maxwidth) + maxwidth = self.config['copy_album_art_maxwidth'].get(int) + size = ArtResizer.shared.get_size(album.artpath) + if size: + resize = ArtResizer.shared.must_resize(size, maxwidth) if resize: if pretend: From bc21afab4276fc27d2d874fd8563c4baf77b6b6a Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 18:50:41 +1030 Subject: [PATCH 0580/2280] better text for artwork resize/copy logs --- beetsplug/convert.py | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index a99d1983d..f02fd6442 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -348,22 +348,16 @@ class ConvertPlugin(BeetsPlugin): resize = ArtResizer.shared.must_resize(size, maxwidth) if resize: - if pretend: - self._log.info(u'resize_artwork {0} {1}', - util.displayable_path(album.artpath), - util.displayable_path(dest)) - else: - self._log.info(u'Converting cover art to {0}', - util.displayable_path(dest)) + self._log.info(u'Resizing cover art from {0} to {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + if not pretend: ArtResizer.shared.resize(maxwidth, album.artpath, dest) else: - if pretend: - self._log.info(u'cp {0} {1}', - util.displayable_path(album.artpath), - util.displayable_path(dest)) - else: - self._log.info(u'Copying cover art to {0}', - util.displayable_path(dest)) + self._log.info(u'Copying cover art from {0} to {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + if not pretend: util.copy(album.artpath, dest) def convert_func(self, lib, opts, args): From a1f80275c4d86954b4b4b451b3efde2fe382c30d Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 19:41:00 +1030 Subject: [PATCH 0581/2280] revert a chunk of the work to be the way it was --- beets/util/artresizer.py | 40 ----------------- beetsplug/convert.py | 6 ++- beetsplug/fetchart.py | 93 ++++++++++++++++++++++++++-------------- 3 files changed, 66 insertions(+), 73 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 919a10883..1b6a5903e 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -173,46 +173,6 @@ class ArtResizer(object): log.debug(u"artresizer: method is {0}", self.method) self.can_compare = self._can_compare() - def valid_size(self, size, enforce_ratio = False, minwidth = None): - """If size constraints exist, check whether the provided image size - matches them. - """ - # Check minimum size. - if minwidth and size[0] < minwidth: - log.debug('image too small ({} < {})', - size[0], minwidth) - return False - - # Check aspect ratio. - if enforce_ratio and size[0] != size[1]: - log.debug('image is not square ({} != {})', - size[0], size[1]) - return False - - return True - - def must_resize(self, size, maxwidth = None): - """Determine whether the provided image size means that the image - will need to be scaled to fit the maximum width. - """ - if not maxwidth: - return False - - if not size: - log.warning(u'Could not get size of image (please see ' - u'documentation for dependencies).') - return False - - if size[0] <= maxwidth: - log.debug('dump values ({} > {})', - size[0], maxwidth) - log.debug(u'Image does not need to be resized.') - return False - - log.debug('Image needs resizing ({} > {})', - size[0], maxwidth) - return True - def resize(self, maxwidth, path_in, path_out=None): """Manipulate an image file according to the method, returning a new path. For PIL or IMAGEMAGIC methods, resizes the image to a diff --git a/beetsplug/convert.py b/beetsplug/convert.py index f02fd6442..0f2eb8d4d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -344,8 +344,12 @@ class ConvertPlugin(BeetsPlugin): if self.config['copy_album_art_maxwidth']: maxwidth = self.config['copy_album_art_maxwidth'].get(int) size = ArtResizer.shared.get_size(album.artpath) + self._log.debug('image size: {}', size) if size: - resize = ArtResizer.shared.must_resize(size, maxwidth) + resize = size[0] > maxwidth + else: + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies).') if resize: self._log.info(u'Resizing cover art from {0} to {1}', diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index efa2f5bde..57d8e4c46 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -42,6 +42,10 @@ IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' +CANDIDATE_BAD = 0 +CANDIDATE_EXACT = 1 +CANDIDATE_DOWNSCALE = 2 + def _logged_get(log, *args, **kwargs): """Like `requests.get`, but logs the effective URL to the specified @@ -531,6 +535,51 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self._log.debug('error fetching art: {}', exc) return None + def _is_valid_image_candidate(self, candidate): + """Determine whether the given candidate artwork is valid based on + its dimensions (width and ratio). + + Return `CANDIDATE_BAD` if the file is unusable. + Return `CANDIDATE_EXACT` if the file is usable as-is. + Return `CANDIDATE_DOWNSCALE` if the file must be resized. + """ + if not candidate: + return CANDIDATE_BAD + + if not (self.enforce_ratio or self.minwidth or self.maxwidth): + return CANDIDATE_EXACT + + # get_size returns None if no local imaging backend is available + size = ArtResizer.shared.get_size(candidate) + self._log.debug('image size: {}', size) + + if not size: + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies). ' + u'The configuration options `minwidth` and ' + u'`enforce_ratio` may be violated.') + return CANDIDATE_EXACT + + # Check minimum size. + if self.minwidth and size[0] < self.minwidth: + self._log.debug('image too small ({} < {})', + size[0], self.minwidth) + return CANDIDATE_BAD + + # Check aspect ratio. + if self.enforce_ratio and size[0] != size[1]: + self._log.debug('image is not square ({} != {})', + size[0], size[1]) + return CANDIDATE_BAD + + # Check maximum size. + if self.maxwidth and size[0] > self.maxwidth: + self._log.debug('image needs resizing ({} > {})', + size[0], self.maxwidth) + return CANDIDATE_DOWNSCALE + + return CANDIDATE_EXACT + def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the album (or None if no art is found). If `maxwidth`, then images are @@ -539,7 +588,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): are made. """ out = None - size = None + check = None # Local art. cover_names = self.config['cover_names'].as_str_seq() @@ -548,21 +597,11 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if paths: for path in paths: candidate = self.fs_source.get(path, cover_names, cautious) - if not candidate: - continue - - # get_size returns None if no local imaging backend is available - size = ArtResizer.shared.get_size(candidate) - self._log.debug('image size: {}', size) - if size: - valid = ArtResizer.shared.valid_size(size, - self.enforce_ratio, self.minwidth) - if not valid: - continue - - out = candidate - self._log.debug('found local image {}', out) - break + check = self._is_valid_image_candidate(candidate) + if check: + out = candidate + self._log.debug('found local image {}', out) + break # Web art sources. remote_priority = self.config['remote_priority'].get(bool) @@ -571,23 +610,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if self.maxwidth: url = ArtResizer.shared.proxy_url(self.maxwidth, url) candidate = self._fetch_image(url) - if not candidate: - continue + check = self._is_valid_image_candidate(candidate) + if check: + out = candidate + self._log.debug('using remote image {}', out) + break - # get_size returns None if no local imaging backend is available - size = ArtResizer.shared.get_size(candidate) - self._log.debug('image size: {}', size) - if size: - valid = ArtResizer.shared.valid_size(size, - self.enforce_ratio, self.minwidth) - if not valid: - continue - - out = candidate - self._log.debug('using remote image {}', out) - break - - if self.maxwidth and out and ArtResizer.shared.must_resize(size, self.maxwidth): + if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: out = ArtResizer.shared.resize(self.maxwidth, out) return out From b59792c7a8c7f197f791310c630029d4d38a55a6 Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Thu, 25 Feb 2016 19:41:28 +1030 Subject: [PATCH 0582/2280] doc note for new copy_album_art_maxwidth option --- docs/plugins/convert.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 7480bacbb..b992663a4 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -62,6 +62,9 @@ file. The available options are: Default: none (system default), - **copy_album_art**: Copy album art when copying or transcoding albums matched using the ``-a`` option. Default: ``no``. +- **copy_album_art_maxwidth**: Downscale album art if it's too big. The + resize operation reduces image width to at most ``maxwidth`` pixels. The + height is recomputed so that the aspect ratio is preserved. - **dest**: The directory where the files will be converted (or copied) to. Default: none. - **embed**: Embed album art in converted items. Default: ``yes``. From 786bfb9168f7dc8ec32bae07f51cbdecea8de7b0 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 25 Feb 2016 23:16:39 +0100 Subject: [PATCH 0583/2280] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 09981d1d7..f6c75ba61 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -23,7 +23,7 @@ Here's a link to the music files that trigger the bug (if relevant): * OS: * Python version: * beets version: -* I tried turning off plugins, and that made the problem go away (yes/no): +* Turning off plugins made problem go away (yes/no): My configuration (output of `beet config`) is: From 7202b3d4131f7436cebd3725605bfa89379c9271 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 26 Feb 2016 12:15:24 -0800 Subject: [PATCH 0584/2280] Slightly more logical instruction placement --- .github/ISSUE_TEMPLATE.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index f6c75ba61..0f5481f0c 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,8 +1,7 @@ -Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please fill out the "Problem" and "Setup" sections below. Otherwise, you can delete it. - - ### Problem +(Describe your problem, feature request, or discussion topic here. If you're reporting a bug, please fill out this and the "Setup" section below. Otherwise, you can delete them.) + Running this command in verbose (`-vv`) mode: ```sh From a751d6d442935cfddd039ec742ea0239bb907c77 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 26 Feb 2016 12:23:32 -0800 Subject: [PATCH 0585/2280] Fix #1895: don't assume SC data is bytes --- beets/mediafile.py | 7 ++++++- docs/changelog.rst | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 5010f8797..02befcbb0 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -211,9 +211,14 @@ def _pack_asf_image(mime, data, type=3, description=""): # iTunes Sound Check encoding. def _sc_decode(soundcheck): - """Convert a Sound Check string value to a (gain, peak) tuple as + """Convert a Sound Check bytestring value to a (gain, peak) tuple as used by ReplayGain. """ + # We decode binary data. If one of the formats gives us a text + # string, guess that it's UTF-8. + if isinstance(soundcheck, unicode): + soundcheck = soundcheck.decode('utf8') + # SoundCheck tags consist of 10 numbers, each represented by 8 # characters of ASCII hex preceded by a space. try: diff --git a/docs/changelog.rst b/docs/changelog.rst index 3803894b2..349d484b9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,7 @@ Fixes: * Fix a problem with the :ref:`stats-cmd` in exact mode when filenames on Windows use non-ASCII characters. :bug:`1891` +* Fix a crash when iTunes Sound Check tags contained invalid data. :bug:`1895` 1.3.17 (February 7, 2016) From a98bc481cd3e9718e58cf551a11905c6ea3e832b Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Sat, 27 Feb 2016 19:02:10 +1030 Subject: [PATCH 0586/2280] tweaks for style, option name --- beetsplug/convert.py | 8 ++++---- docs/plugins/convert.rst | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 0f2eb8d4d..81c6f4eb8 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -133,7 +133,7 @@ class ConvertPlugin(BeetsPlugin): u'paths': {}, u'never_convert_lossy_files': False, u'copy_album_art': False, - u'copy_album_art_maxwidth': 0, + u'album_art_maxwidth': 0, }) self.import_stages = [self.auto_convert] @@ -341,8 +341,8 @@ class ConvertPlugin(BeetsPlugin): resize = False maxwidth = None - if self.config['copy_album_art_maxwidth']: - maxwidth = self.config['copy_album_art_maxwidth'].get(int) + if self.config['album_art_maxwidth']: + maxwidth = self.config['album_art_maxwidth'].get(int) size = ArtResizer.shared.get_size(album.artpath) self._log.debug('image size: {}', size) if size: @@ -358,7 +358,7 @@ class ConvertPlugin(BeetsPlugin): if not pretend: ArtResizer.shared.resize(maxwidth, album.artpath, dest) else: - self._log.info(u'Copying cover art from {0} to {1}', + self._log.info(u'cp {0} {1}', util.displayable_path(album.artpath), util.displayable_path(dest)) if not pretend: diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index b992663a4..b93227b62 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -62,9 +62,9 @@ file. The available options are: Default: none (system default), - **copy_album_art**: Copy album art when copying or transcoding albums matched using the ``-a`` option. Default: ``no``. -- **copy_album_art_maxwidth**: Downscale album art if it's too big. The - resize operation reduces image width to at most ``maxwidth`` pixels. The - height is recomputed so that the aspect ratio is preserved. +- **album_art_maxwidth**: Downscale album art if it's too big. The resize + operation reduces image width to at most ``maxwidth`` pixels. The height is + recomputed so that the aspect ratio is preserved. - **dest**: The directory where the files will be converted (or copied) to. Default: none. - **embed**: Embed album art in converted items. Default: ``yes``. From 9f59e136f983f34a9aaf0eb57c5e0d0696cc20f1 Mon Sep 17 00:00:00 2001 From: Ali Graham Date: Sat, 27 Feb 2016 19:16:13 +1030 Subject: [PATCH 0587/2280] changelog entry for new convert.album_art_maxwidth option --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3803894b2..77be3019a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,12 @@ Changelog 1.3.18 (in development) ----------------------- +New features: + +* :doc:`/plugins/convert`: A new `album_art_maxwidth` option which will + downsize destination images if the `copy_album_art` switch is true and the + image is too wide. + Fixes: * Fix a problem with the :ref:`stats-cmd` in exact mode when filenames on From 031d50abbf8070adbb98232848318e9d5a4d041e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 27 Feb 2016 09:58:05 -0800 Subject: [PATCH 0588/2280] Human-readable message in non-pretend mode (#1894) --- beetsplug/convert.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 81c6f4eb8..ce475a19d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -338,9 +338,9 @@ class ConvertPlugin(BeetsPlugin): util.displayable_path(album.artpath)) return + # Decide whether we need to resize the cover-art image. resize = False maxwidth = None - if self.config['album_art_maxwidth']: maxwidth = self.config['album_art_maxwidth'].get(int) size = ArtResizer.shared.get_size(album.artpath) @@ -351,6 +351,7 @@ class ConvertPlugin(BeetsPlugin): self._log.warning(u'Could not get size of image (please see ' u'documentation for dependencies).') + # Either copy or resize (while copying) the image. if resize: self._log.info(u'Resizing cover art from {0} to {1}', util.displayable_path(album.artpath), @@ -358,10 +359,14 @@ class ConvertPlugin(BeetsPlugin): if not pretend: ArtResizer.shared.resize(maxwidth, album.artpath, dest) else: - self._log.info(u'cp {0} {1}', - util.displayable_path(album.artpath), - util.displayable_path(dest)) - if not pretend: + if pretend: + self._log.info(u'cp {0} {1}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) + else: + self._log.info(u'Copying cover art to {0}', + util.displayable_path(album.artpath), + util.displayable_path(dest)) util.copy(album.artpath, dest) def convert_func(self, lib, opts, args): From 5b5a8c5a6d692e75b7ae37b820133a833bacf699 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 27 Feb 2016 09:59:34 -0800 Subject: [PATCH 0589/2280] Minor docs refinements for #1894 --- docs/changelog.rst | 5 ++--- docs/plugins/convert.rst | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4e3b12893..a2c19dcab 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,9 +6,8 @@ Changelog New features: -* :doc:`/plugins/convert`: A new `album_art_maxwidth` option which will - downsize destination images if the `copy_album_art` switch is true and the - image is too wide. +* :doc:`/plugins/convert`: A new `album_art_maxwidth` lets you resize album + art while copying it. Fixes: diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index b93227b62..f5b258065 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -63,8 +63,8 @@ file. The available options are: - **copy_album_art**: Copy album art when copying or transcoding albums matched using the ``-a`` option. Default: ``no``. - **album_art_maxwidth**: Downscale album art if it's too big. The resize - operation reduces image width to at most ``maxwidth`` pixels. The height is - recomputed so that the aspect ratio is preserved. + operation reduces image width to at most ``maxwidth`` pixels while + preserving the aspect ratio. - **dest**: The directory where the files will be converted (or copied) to. Default: none. - **embed**: Embed album art in converted items. Default: ``yes``. From ad073652c20cf5b64df2a7fc1cb6d1a579cbdc09 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 12:50:36 +0100 Subject: [PATCH 0590/2280] Removed unicode_literals from test_thumbnails --- test/test_thumbnails.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 60297c68e..d0fbe02ae 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os.path from mock import Mock, patch, call @@ -38,13 +37,13 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.util') def test_write_metadata_im(self, mock_util): - metadata = {"a": "A", "b": "B"} + metadata = {"a": u"A", "b": u"B"} write_metadata_im("foo", metadata) try: - command = "convert foo -set a A -set b B foo".split(' ') + command = u"convert foo -set a A -set b B foo".split(' ') mock_util.command_output.assert_called_once_with(command) except AssertionError: - command = "convert foo -set b B -set a A foo".split(' ') + command = u"convert foo -set b B -set a A foo".split(' ') mock_util.command_output.assert_called_once_with(command) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @@ -60,7 +59,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): plugin.add_tags(album, b"/path/to/thumbnail") metadata = {"Thumb::URI": b"COVER_URI", - "Thumb::MTime": "12345"} + "Thumb::MTime": u"12345"} plugin.write_metadata.assert_called_once_with(b"/path/to/thumbnail", metadata) mock_stat.assert_called_once_with(album.artpath) @@ -85,7 +84,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): return False if path == LARGE_DIR: return True - raise ValueError("unexpected path {0!r}".format(path)) + raise ValueError(u"unexpected path {0!r}".format(path)) mock_os.path.exists = exists plugin = ThumbnailsPlugin() mock_os.makedirs.assert_called_once_with(NORMAL_DIR) @@ -143,7 +142,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): elif target == path_to_art: return Mock(st_mtime=2) else: - raise ValueError("invalid target {0}".format(target)) + raise ValueError(u"invalid target {0}".format(target)) mock_os.stat.side_effect = os_stat plugin.make_cover_thumbnail(album, 12345, thumbnail_dir) @@ -169,7 +168,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): elif target == path_to_art: return Mock(st_mtime=2) else: - raise ValueError("invalid target {0}".format(target)) + raise ValueError(u"invalid target {0}".format(target)) mock_os.stat.side_effect = os_stat plugin.make_cover_thumbnail(album, 12345, thumbnail_dir) @@ -266,7 +265,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.BaseDirectory') def test_thumbnail_file_name(self, mock_basedir): plug = ThumbnailsPlugin() - plug.get_uri = Mock(return_value="file:///my/uri") + plug.get_uri = Mock(return_value=u"file:///my/uri") self.assertEqual(plug.thumbnail_file_name("idontcare"), b"9488f5797fbe12ffb316d607dfd93d04.png") @@ -274,9 +273,9 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): gio = GioURI() plib = PathlibURI() if not gio.available: - self.skipTest("GIO library not found") + self.skipTest(u"GIO library not found") - self.assertEqual(gio.uri("/foo"), b"file:///") # silent fail + self.assertEqual(gio.uri(u"/foo"), b"file:///") # silent fail self.assertEqual(gio.uri(b"/foo"), b"file:///foo") self.assertEqual(gio.uri(b"/foo!"), b"file:///foo!") self.assertEqual(plib.uri(b"/foo!"), b"file:///foo%21") From 92a9c6ff50cbb944f1dc60b721d52c4d82a0db38 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 13:04:47 +0100 Subject: [PATCH 0591/2280] Removed unicode_literals from test_library --- test/test_library.py | 281 +++++++++++++++++++++---------------------- 1 file changed, 140 insertions(+), 141 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 5fdb1f2ec..fa11e5d53 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -15,8 +15,7 @@ """Tests for non-query database functions of Item. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import os.path @@ -47,12 +46,12 @@ np = util.normpath class LoadTest(_common.LibTestCase): def test_load_restores_data_from_db(self): original_title = self.i.title - self.i.title = 'something' + self.i.title = u'something' self.i.load() self.assertEqual(original_title, self.i.title) def test_load_clears_dirty_flags(self): - self.i.artist = 'something' + self.i.artist = u'something' self.assertTrue('artist' in self.i._dirty) self.i.load() self.assertTrue('artist' not in self.i._dirty) @@ -69,7 +68,7 @@ class StoreTest(_common.LibTestCase): def test_store_only_writes_dirty_fields(self): original_genre = self.i.genre - self.i._values_fixed['genre'] = 'beatboxing' # change w/o dirtying + self.i._values_fixed['genre'] = u'beatboxing' # change w/o dirtying self.i.store() new_genre = self.lib._connection().execute( 'select genre from items where ' @@ -77,7 +76,7 @@ class StoreTest(_common.LibTestCase): self.assertEqual(new_genre, original_genre) def test_store_clears_dirty_flags(self): - self.i.composer = 'tvp' + self.i.composer = u'tvp' self.i.store() self.assertTrue('composer' not in self.i._dirty) @@ -131,7 +130,7 @@ class GetSetTest(_common.TestCase): self.assertTrue('title' not in self.i._dirty) def test_invalid_field_raises_attributeerror(self): - self.assertRaises(AttributeError, getattr, self.i, 'xyzzy') + self.assertRaises(AttributeError, getattr, self.i, u'xyzzy') class DestinationTest(_common.TestCase): @@ -150,17 +149,17 @@ class DestinationTest(_common.TestCase): def test_directory_works_with_trailing_slash(self): self.lib.directory = 'one/' - self.lib.path_formats = [('default', 'two')] + self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_directory_works_without_trailing_slash(self): self.lib.directory = 'one' - self.lib.path_formats = [('default', 'two')] + self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_destination_substitues_metadata_values(self): self.lib.directory = 'base' - self.lib.path_formats = [('default', '$album/$artist $title')] + self.lib.path_formats = [(u'default', u'$album/$artist $title')] self.i.title = 'three' self.i.artist = 'two' self.i.album = 'one' @@ -169,22 +168,22 @@ class DestinationTest(_common.TestCase): def test_destination_preserves_extension(self): self.lib.directory = 'base' - self.lib.path_formats = [('default', '$title')] + self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.audioformat' self.assertEqual(self.i.destination(), np('base/the title.audioformat')) def test_lower_case_extension(self): self.lib.directory = 'base' - self.lib.path_formats = [('default', '$title')] + self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.MP3' self.assertEqual(self.i.destination(), np('base/the title.mp3')) def test_destination_pads_some_indices(self): self.lib.directory = 'base' - self.lib.path_formats = [('default', - '$track $tracktotal $disc $disctotal $bpm')] + self.lib.path_formats = [(u'default', + u'$track $tracktotal $disc $disctotal $bpm')] self.i.track = 1 self.i.tracktotal = 2 self.i.disc = 3 @@ -195,7 +194,7 @@ class DestinationTest(_common.TestCase): def test_destination_pads_date_values(self): self.lib.directory = 'base' - self.lib.path_formats = [('default', '$year-$month-$day')] + self.lib.path_formats = [(u'default', u'$year-$month-$day')] self.i.year = 1 self.i.month = 2 self.i.day = 3 @@ -222,13 +221,13 @@ class DestinationTest(_common.TestCase): self.assertTrue(os.path.join('one', 'two') in dest) def test_destination_long_names_truncated(self): - self.i.title = 'X' * 300 - self.i.artist = 'Y' * 300 + self.i.title = u'X' * 300 + self.i.artist = u'Y' * 300 for c in self.i.destination().split(os.path.sep): self.assertTrue(len(c) <= 255) def test_destination_long_names_keep_extension(self): - self.i.title = 'X' * 300 + self.i.title = u'X' * 300 self.i.path = 'something.extn' dest = self.i.destination() self.assertEqual(dest[-5:], '.extn') @@ -243,7 +242,7 @@ class DestinationTest(_common.TestCase): self.assertFalse('two / three' in p) def test_path_with_format(self): - self.lib.path_formats = [('default', '$artist/$album ($format)')] + self.lib.path_formats = [(u'default', u'$artist/$album ($format)')] p = self.i.destination() self.assert_('(FLAC)' in p) @@ -251,7 +250,7 @@ class DestinationTest(_common.TestCase): i1, i2 = item(), item() self.lib.add_album([i1, i2]) i1.year, i2.year = 2009, 2010 - self.lib.path_formats = [('default', '$album ($year)/$track $title')] + self.lib.path_formats = [(u'default', u'$album ($year)/$track $title')] dest1, dest2 = i1.destination(), i2.destination() self.assertEqual(os.path.dirname(dest1), os.path.dirname(dest2)) @@ -259,17 +258,17 @@ class DestinationTest(_common.TestCase): self.i.comp = False self.lib.add_album([self.i]) self.lib.directory = 'one' - self.lib.path_formats = [('default', 'two'), - ('comp:true', 'three')] + self.lib.path_formats = [(u'default', u'two'), + (u'comp:true', u'three')] self.assertEqual(self.i.destination(), np('one/two')) def test_singleton_path(self): i = item(self.lib) self.lib.directory = 'one' self.lib.path_formats = [ - ('default', 'two'), - ('singleton:true', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'singleton:true', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(i.destination(), np('one/four')) @@ -278,9 +277,9 @@ class DestinationTest(_common.TestCase): i.comp = True self.lib.directory = 'one' self.lib.path_formats = [ - ('default', 'two'), - ('comp:true', 'three'), - ('singleton:true', 'four'), + (u'default', u'two'), + (u'comp:true', u'three'), + (u'singleton:true', u'four'), ] self.assertEqual(i.destination(), np('one/three')) @@ -289,32 +288,32 @@ class DestinationTest(_common.TestCase): self.lib.add_album([self.i]) self.lib.directory = 'one' self.lib.path_formats = [ - ('default', 'two'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/three')) def test_albumtype_query_path(self): self.i.comp = True self.lib.add_album([self.i]) - self.i.albumtype = 'sometype' + self.i.albumtype = u'sometype' self.lib.directory = 'one' self.lib.path_formats = [ - ('default', 'two'), - ('albumtype:sometype', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'albumtype:sometype', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/four')) def test_albumtype_path_fallback_to_comp(self): self.i.comp = True self.lib.add_album([self.i]) - self.i.albumtype = 'sometype' + self.i.albumtype = u'sometype' self.lib.directory = 'one' self.lib.path_formats = [ - ('default', 'two'), - ('albumtype:anothertype', 'four'), - ('comp:true', 'three'), + (u'default', u'two'), + (u'albumtype:anothertype', u'four'), + (u'comp:true', u'three'), ] self.assertEqual(self.i.destination(), np('one/three')) @@ -356,42 +355,42 @@ class DestinationTest(_common.TestCase): self.assertEqual(val, u'') def test_artist_falls_back_to_albumartist(self): - self.i.artist = '' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$artist')] + self.i.artist = u'' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$artist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'something') + self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') def test_albumartist_falls_back_to_artist(self): - self.i.artist = 'trackartist' - self.i.albumartist = '' - self.lib.path_formats = [('default', '$albumartist')] + self.i.artist = u'trackartist' + self.i.albumartist = u'' + self.lib.path_formats = [(u'default', u'$albumartist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'trackartist') + self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'trackartist') def test_artist_overrides_albumartist(self): - self.i.artist = 'theartist' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$artist')] + self.i.artist = u'theartist' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$artist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'theartist') + self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'theartist') def test_albumartist_overrides_artist(self): - self.i.artist = 'theartist' - self.i.albumartist = 'something' - self.lib.path_formats = [('default', '$albumartist')] + self.i.artist = u'theartist' + self.i.albumartist = u'something' + self.lib.path_formats = [(u'default', u'$albumartist')] p = self.i.destination() - self.assertEqual(p.rsplit(os.path.sep, 1)[1], 'something') + self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') def test_unicode_normalized_nfd_on_mac(self): instr = unicodedata.normalize('NFC', u'caf\xe9') - self.lib.path_formats = [('default', instr)] + self.lib.path_formats = [(u'default', instr)] dest = self.i.destination(platform='darwin', fragment=True) self.assertEqual(dest, unicodedata.normalize('NFD', instr)) def test_unicode_normalized_nfc_on_linux(self): instr = unicodedata.normalize('NFD', u'caf\xe9') - self.lib.path_formats = [('default', instr)] + self.lib.path_formats = [(u'default', instr)] dest = self.i.destination(platform='linux2', fragment=True) self.assertEqual(dest, unicodedata.normalize('NFC', instr)) @@ -400,7 +399,7 @@ class DestinationTest(_common.TestCase): sys.getfilesystemencoding = lambda: 'mbcs' try: self.i.title = u'h\u0259d' - self.lib.path_formats = [('default', '$title')] + self.lib.path_formats = [(u'default', u'$title')] p = self.i.destination() self.assertFalse(b'?' in p) # We use UTF-8 to encode Windows paths now. @@ -409,7 +408,7 @@ class DestinationTest(_common.TestCase): sys.getfilesystemencoding = oldfunc def test_unicode_extension_in_fragment(self): - self.lib.path_formats = [('default', u'foo')] + self.lib.path_formats = [(u'default', u'foo')] self.i.path = util.bytestring_path(u'bar.caf\xe9') dest = self.i.destination(platform='linux2', fragment=True) self.assertEqual(dest, u'foo.caf\xe9') @@ -418,16 +417,16 @@ class DestinationTest(_common.TestCase): config['asciify_paths'] = True self.lib.replacements = [(re.compile(u'"'), u'q')] self.lib.directory = 'lib' - self.lib.path_formats = [('default', '$title')] + self.lib.path_formats = [(u'default', u'$title')] self.i.title = u'\u201c\u00f6\u2014\u00cf\u201d' self.assertEqual(self.i.destination(), np('lib/qo--Iq')) def test_destination_with_replacements(self): self.lib.directory = 'base' self.lib.replacements = [(re.compile(r'a'), u'e')] - self.lib.path_formats = [('default', '$album/$title')] - self.i.title = 'foo' - self.i.album = 'bar' + self.lib.path_formats = [(u'default', u'$album/$title')] + self.i.title = u'foo' + self.i.album = u'bar' self.assertEqual(self.i.destination(), np('base/ber/foo')) @@ -435,11 +434,11 @@ class DestinationTest(_common.TestCase): def test_destination_with_empty_component(self): self.lib.directory = 'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] - self.lib.path_formats = [('default', '$album/$artist/$title')] - self.i.title = 'three' - self.i.artist = '' - self.i.albumartist = '' - self.i.album = 'one' + self.lib.path_formats = [(u'default', u'$album/$artist/$title')] + self.i.title = u'three' + self.i.artist = u'' + self.i.albumartist = u'' + self.i.album = u'one' self.assertEqual(self.i.destination(), np('base/one/_/three')) @@ -447,9 +446,9 @@ class DestinationTest(_common.TestCase): def test_destination_with_empty_final_component(self): self.lib.directory = 'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] - self.lib.path_formats = [('default', '$album/$title')] - self.i.title = '' - self.i.album = 'one' + self.lib.path_formats = [(u'default', u'$album/$title')] + self.i.title = u'' + self.i.album = u'one' self.i.path = 'foo.mp3' self.assertEqual(self.i.destination(), np('base/one/_.mp3')) @@ -463,11 +462,11 @@ class DestinationTest(_common.TestCase): # Construct an item whose untruncated path ends with a Y but whose # truncated version ends with an X. - self.i.title = 'X' * 300 + 'Y' + self.i.title = u'X' * 300 + u'Y' # The final path should reflect the replacement. dest = self.i.destination() - self.assertEqual(dest[-2:], 'XZ') + self.assertEqual(dest[-2:], u'XZ') def test_legalize_path_one_for_many_replacement(self): # Use a replacement that should always replace the last X in any @@ -478,18 +477,18 @@ class DestinationTest(_common.TestCase): # Construct an item whose untruncated path ends with a Y but whose # truncated version ends with an X. - self.i.title = 'X' * 300 + 'Y' + self.i.title = u'X' * 300 + u'Y' # The final path should ignore the user replacement and create a path # of the correct length, containing Xs. dest = self.i.destination() - self.assertEqual(dest[-2:], 'XX') + self.assertEqual(dest[-2:], u'XX') class ItemFormattedMappingTest(_common.LibTestCase): def test_formatted_item_value(self): formatted = self.i.formatted() - self.assertEqual(formatted['artist'], 'the artist') + self.assertEqual(formatted['artist'], u'the artist') def test_get_unset_field(self): formatted = self.i.formatted() @@ -502,53 +501,53 @@ class ItemFormattedMappingTest(_common.LibTestCase): def test_get_method_with_specified_default(self): formatted = self.i.formatted() - self.assertEqual(formatted.get('other_field', 'default'), 'default') + self.assertEqual(formatted.get('other_field', u'default'), u'default') def test_item_precedence(self): album = self.lib.add_album([self.i]) - album['artist'] = 'foo' + album['artist'] = u'foo' album.store() - self.assertNotEqual('foo', self.i.formatted().get('artist')) + self.assertNotEqual(u'foo', self.i.formatted().get('artist')) def test_album_flex_field(self): album = self.lib.add_album([self.i]) - album['flex'] = 'foo' + album['flex'] = u'foo' album.store() - self.assertEqual('foo', self.i.formatted().get('flex')) + self.assertEqual(u'foo', self.i.formatted().get('flex')) def test_album_field_overrides_item_field_for_path(self): # Make the album inconsistent with the item. album = self.lib.add_album([self.i]) - album.album = 'foo' + album.album = u'foo' album.store() - self.i.album = 'bar' + self.i.album = u'bar' self.i.store() # Ensure the album takes precedence. formatted = self.i.formatted(for_path=True) - self.assertEqual(formatted['album'], 'foo') + self.assertEqual(formatted['album'], u'foo') def test_artist_falls_back_to_albumartist(self): - self.i.artist = '' + self.i.artist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['artist'], 'the album artist') + self.assertEqual(formatted['artist'], u'the album artist') def test_albumartist_falls_back_to_artist(self): - self.i.albumartist = '' + self.i.albumartist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['albumartist'], 'the artist') + self.assertEqual(formatted['albumartist'], u'the artist') def test_both_artist_and_albumartist_empty(self): - self.i.artist = '' - self.i.albumartist = '' + self.i.artist = u'' + self.i.albumartist = u'' formatted = self.i.formatted() - self.assertEqual(formatted['albumartist'], '') + self.assertEqual(formatted['albumartist'], u'') class PathFormattingMixin(object): """Utilities for testing path formatting.""" def _setf(self, fmt): - self.lib.path_formats.insert(0, ('default', fmt)) + self.lib.path_formats.insert(0, (u'default', fmt)) def _assert_dest(self, dest, i=None): if i is None: @@ -563,7 +562,7 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): super(DestinationFunctionTest, self).setUp() self.lib = beets.library.Library(':memory:') self.lib.directory = '/base' - self.lib.path_formats = [('default', u'path')] + self.lib.path_formats = [(u'default', u'path')] self.i = item(self.lib) def tearDown(self): @@ -624,7 +623,7 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): super(DisambiguationTest, self).setUp() self.lib = beets.library.Library(':memory:') self.lib.directory = '/base' - self.lib.path_formats = [('default', u'path')] + self.lib.path_formats = [(u'default', u'path')] self.i1 = item() self.i1.year = 2001 @@ -645,14 +644,14 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): def test_unique_with_default_arguments_uses_albumtype(self): album2 = self.lib.get_album(self.i1) - album2.albumtype = 'bar' + album2.albumtype = u'bar' album2.store() self._setf(u'foo%aunique{}/$title') self._assert_dest('/base/foo [bar]/the title', self.i1) def test_unique_expands_to_nothing_for_distinct_albums(self): album2 = self.lib.get_album(self.i2) - album2.album = 'different album' + album2.album = u'different album' album2.store() self._assert_dest('/base/foo/the title', self.i1) @@ -673,7 +672,7 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): album2 = self.lib.get_album(self.i2) album2.year = 2001 album1 = self.lib.get_album(self.i1) - album1.albumtype = 'foo/bar' + album1.albumtype = u'foo/bar' album2.store() album1.store() self._setf(u'foo%aunique{albumartist album,albumtype}/$title') @@ -698,7 +697,7 @@ class PluginDestinationTest(_common.TestCase): self.lib = beets.library.Library(':memory:') self.lib.directory = '/base' - self.lib.path_formats = [('default', u'$artist $foo')] + self.lib.path_formats = [(u'default', u'$artist $foo')] self.i = item(self.lib) def tearDown(self): @@ -711,25 +710,25 @@ class PluginDestinationTest(_common.TestCase): self.assertEqual(the_dest, '/base/' + dest) def test_undefined_value_not_substituted(self): - self._assert_dest('the artist $foo') + self._assert_dest(u'the artist $foo') def test_plugin_value_not_substituted(self): self._tv_map = { 'foo': 'bar', } - self._assert_dest('the artist bar') + self._assert_dest(u'the artist bar') def test_plugin_value_overrides_attribute(self): self._tv_map = { 'artist': 'bar', } - self._assert_dest('bar $foo') + self._assert_dest(u'bar $foo') def test_plugin_value_sanitized(self): self._tv_map = { 'foo': 'bar/baz', } - self._assert_dest('the artist bar_baz') + self._assert_dest(u'the artist bar_baz') class AlbumInfoTest(_common.TestCase): @@ -766,7 +765,7 @@ class AlbumInfoTest(_common.TestCase): def test_individual_tracks_have_no_albuminfo(self): i2 = item() - i2.album = 'aTotallyDifferentAlbum' + i2.album = u'aTotallyDifferentAlbum' self.lib.add(i2) ai = self.lib.get_album(i2) self.assertEqual(ai, None) @@ -782,29 +781,29 @@ class AlbumInfoTest(_common.TestCase): if i.id == self.i.id: break else: - self.fail("item not found") + self.fail(u"item not found") def test_albuminfo_changes_affect_items(self): ai = self.lib.get_album(self.i) - ai.album = 'myNewAlbum' + ai.album = u'myNewAlbum' ai.store() i = self.lib.items()[0] - self.assertEqual(i.album, 'myNewAlbum') + self.assertEqual(i.album, u'myNewAlbum') def test_albuminfo_change_albumartist_changes_items(self): ai = self.lib.get_album(self.i) - ai.albumartist = 'myNewArtist' + ai.albumartist = u'myNewArtist' ai.store() i = self.lib.items()[0] - self.assertEqual(i.albumartist, 'myNewArtist') - self.assertNotEqual(i.artist, 'myNewArtist') + self.assertEqual(i.albumartist, u'myNewArtist') + self.assertNotEqual(i.artist, u'myNewArtist') def test_albuminfo_change_artist_does_not_change_items(self): ai = self.lib.get_album(self.i) - ai.artist = 'myNewArtist' + ai.artist = u'myNewArtist' ai.store() i = self.lib.items()[0] - self.assertNotEqual(i.artist, 'myNewArtist') + self.assertNotEqual(i.artist, u'myNewArtist') def test_albuminfo_remove_removes_items(self): item_id = self.i.id @@ -821,7 +820,7 @@ class AlbumInfoTest(_common.TestCase): def test_noop_albuminfo_changes_affect_items(self): i = self.lib.items()[0] - i.album = 'foobar' + i.album = u'foobar' i.store() ai = self.lib.get_album(self.i) ai.album = ai.album @@ -882,7 +881,7 @@ class PathStringTest(_common.TestCase): self.assert_(isinstance(i.path, bytes)) def test_special_chars_preserved_in_database(self): - path = 'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf8') self.i.path = path self.i.store() i = list(self.lib.items())[0] @@ -890,7 +889,7 @@ class PathStringTest(_common.TestCase): def test_special_char_path_added_to_database(self): self.i.remove() - path = 'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf8') i = item() i.path = path self.lib.add(i) @@ -962,16 +961,16 @@ class MtimeTest(_common.TestCase): self.assertGreaterEqual(self.i.mtime, self._mtime()) def test_mtime_reset_on_db_modify(self): - self.i.title = 'something else' + self.i.title = u'something else' self.assertLess(self.i.mtime, self._mtime()) def test_mtime_up_to_date_after_write(self): - self.i.title = 'something else' + self.i.title = u'something else' self.i.write() self.assertGreaterEqual(self.i.mtime, self._mtime()) def test_mtime_up_to_date_after_read(self): - self.i.title = 'something else' + self.i.title = u'something else' self.i.read() self.assertGreaterEqual(self.i.mtime, self._mtime()) @@ -996,19 +995,19 @@ class TemplateTest(_common.LibTestCase): def test_year_formatted_in_template(self): self.i.year = 123 self.i.store() - self.assertEqual(self.i.evaluate_template('$year'), '0123') + self.assertEqual(self.i.evaluate_template('$year'), u'0123') def test_album_flexattr_appears_in_item_template(self): self.album = self.lib.add_album([self.i]) - self.album.foo = 'baz' + self.album.foo = u'baz' self.album.store() - self.assertEqual(self.i.evaluate_template('$foo'), 'baz') + self.assertEqual(self.i.evaluate_template('$foo'), u'baz') def test_album_and_item_format(self): config['format_album'] = u'foö $foo' album = beets.library.Album() - album.foo = 'bar' - album.tagada = 'togodo' + album.foo = u'bar' + album.tagada = u'togodo' self.assertEqual(u"{0}".format(album), u"foö bar") self.assertEqual(u"{0:$tagada}".format(album), u"togodo") self.assertEqual(unicode(album), u"foö bar") @@ -1016,10 +1015,10 @@ class TemplateTest(_common.LibTestCase): config['format_item'] = 'bar $foo' item = beets.library.Item() - item.foo = 'bar' - item.tagada = 'togodo' - self.assertEqual("{0}".format(item), "bar bar") - self.assertEqual("{0:$tagada}".format(item), "togodo") + item.foo = u'bar' + item.tagada = u'togodo' + self.assertEqual("{0}".format(item), u"bar bar") + self.assertEqual("{0:$tagada}".format(item), u"togodo") class UnicodePathTest(_common.LibTestCase): @@ -1079,7 +1078,7 @@ class WriteTest(unittest.TestCase, TestHelper): # Since `date` is not a MediaField, this should do nothing. item = self.add_item_fixture() clean_year = item.year - item.date = 'foo' + item.date = u'foo' item.write() self.assertEqual(MediaFile(item.path).year, clean_year) @@ -1119,7 +1118,7 @@ class FilesizeTest(unittest.TestCase, TestHelper): class ParseQueryTest(unittest.TestCase): def test_parse_invalid_query_string(self): with self.assertRaises(beets.dbcore.InvalidQueryError) as raised: - beets.library.parse_query_string('foo"', None) + beets.library.parse_query_string(u'foo"', None) self.assertIsInstance(raised.exception, beets.dbcore.query.ParsingError) @@ -1139,9 +1138,9 @@ class LibraryFieldTypesTest(unittest.TestCase): self.assertEqual(time_local, t.format(123456789)) # parse self.assertEqual(123456789.0, t.parse(time_local)) - self.assertEqual(123456789.0, t.parse('123456789.0')) - self.assertEqual(t.null, t.parse('not123456789.0')) - self.assertEqual(t.null, t.parse('1973-11-29')) + self.assertEqual(123456789.0, t.parse(u'123456789.0')) + self.assertEqual(t.null, t.parse(u'not123456789.0')) + self.assertEqual(t.null, t.parse(u'1973-11-29')) def test_pathtype(self): t = beets.library.PathType() @@ -1157,23 +1156,23 @@ class LibraryFieldTypesTest(unittest.TestCase): t = beets.library.MusicalKey() # parse - self.assertEqual('C#m', t.parse('c#m')) - self.assertEqual('Gm', t.parse('g minor')) - self.assertEqual('Not c#m', t.parse('not C#m')) + self.assertEqual(u'C#m', t.parse(u'c#m')) + self.assertEqual(u'Gm', t.parse(u'g minor')) + self.assertEqual(u'Not c#m', t.parse(u'not C#m')) def test_durationtype(self): t = beets.library.DurationType() # format - self.assertEqual('1:01', t.format(61.23)) - self.assertEqual('60:01', t.format(3601.23)) - self.assertEqual('0:00', t.format(None)) + self.assertEqual(u'1:01', t.format(61.23)) + self.assertEqual(u'60:01', t.format(3601.23)) + self.assertEqual(u'0:00', t.format(None)) # parse - self.assertEqual(61.0, t.parse('1:01')) - self.assertEqual(61.23, t.parse('61.23')) - self.assertEqual(3601.0, t.parse('60:01')) - self.assertEqual(t.null, t.parse('1:00:01')) - self.assertEqual(t.null, t.parse('not61.23')) + self.assertEqual(61.0, t.parse(u'1:01')) + self.assertEqual(61.23, t.parse(u'61.23')) + self.assertEqual(3601.0, t.parse(u'60:01')) + self.assertEqual(t.null, t.parse(u'1:00:01')) + self.assertEqual(t.null, t.parse(u'not61.23')) # config format_raw_length beets.config['format_raw_length'] = True self.assertEqual(61.23, t.format(61.23)) From 3b4bf17d1ab101b269fff3d83dc7ed94be8b828b Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 13:06:18 +0100 Subject: [PATCH 0592/2280] Removed unicode_literals from test_vfs --- test/test_vfs.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/test/test_vfs.py b/test/test_vfs.py index e11e04780..d9536b9d5 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -14,8 +14,7 @@ # included in all copies or substantial portions of the Software. """Tests for the virtual filesystem builder..""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) from test import _common from test._common import unittest @@ -27,8 +26,8 @@ class VFSTest(_common.TestCase): def setUp(self): super(VFSTest, self).setUp() self.lib = library.Library(':memory:', path_formats=[ - ('default', 'albums/$album/$title'), - ('singleton:true', 'tracks/$artist/$title'), + (u'default', u'albums/$album/$title'), + (u'singleton:true', u'tracks/$artist/$title'), ]) self.lib.add(_common.item()) self.lib.add_album([_common.item()]) From 07a225992da3e2054fbe69ed540c526d2be08862 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 13:24:13 +0100 Subject: [PATCH 0593/2280] Removed unicode_literals from test_play --- test/test_play.py | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index d0371cf15..1405204e2 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -15,8 +15,7 @@ """Tests for the play plugin""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os @@ -33,7 +32,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('play') - self.item = self.add_item(album='a nice älbum', title='aNiceTitle') + self.item = self.add_item(album=u'a nice älbum', title=u'aNiceTitle') self.lib.add_album([self.item]) self.open_patcher = patch('beetsplug.play.util.interactive_open') self.open_mock = self.open_patcher.start() @@ -45,7 +44,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.unload_plugins() def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', - expected_playlist='{}\n'): + expected_playlist=u'{}\n'): self.run_command('play', *args) self.open_mock.assert_called_once_with(ANY, expected_cmd) @@ -57,21 +56,21 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.do_test() def test_album_option(self): - self.do_test(['-a', 'nice']) + self.do_test([u'-a', u'nice']) def test_args_option(self): - self.do_test(['-A', 'foo', 'title:aNiceTitle'], 'echo foo') + self.do_test([u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') def test_args_option_in_middle(self): self.config['play']['command'] = 'echo $args other' - self.do_test(['-A', 'foo', 'title:aNiceTitle'], 'echo foo other') + self.do_test([u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') def test_relative_to(self): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' - self.do_test(expected_cmd='echo', expected_playlist='..{}\n') + self.do_test(expected_cmd='echo', expected_playlist=u'..{}\n') def test_use_folders(self): self.config['play']['command'] = None @@ -80,19 +79,19 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.open_mock.assert_called_once_with(ANY, open_anything()) playlist = open(self.open_mock.call_args[0][0][0], 'r') - self.assertEqual('{}\n'.format( + self.assertEqual(u'{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), playlist.read().decode('utf-8')) def test_raw(self): self.config['play']['raw'] = True - self.run_command('play', 'nice') + self.run_command(u'play', u'nice') self.open_mock.assert_called_once_with([self.item.path], 'echo') def test_not_found(self): - self.run_command('play', 'not found') + self.run_command(u'play', u'not found') self.open_mock.assert_not_called() @@ -101,24 +100,24 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.add_item(title='another NiceTitle') with control_stdin("a"): - self.run_command('play', 'nice') + self.run_command(u'play', u'nice') self.open_mock.assert_not_called() def test_warning_threshold_backwards_compat(self): self.config['play']['warning_treshold'] = 1 - self.add_item(title='another NiceTitle') + self.add_item(title=u'another NiceTitle') with control_stdin("a"): - self.run_command('play', 'nice') + self.run_command(u'play', u'nice') self.open_mock.assert_not_called() def test_command_failed(self): - self.open_mock.side_effect = OSError("some reason") + self.open_mock.side_effect = OSError(u"some reason") with self.assertRaises(UserError): - self.run_command('play', 'title:aNiceTitle') + self.run_command(u'play', u'title:aNiceTitle') def suite(): From df7241ecce6bdd6ccb6f862c94f7109195e13b33 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 13:37:13 +0100 Subject: [PATCH 0594/2280] Removed unicode_literals from test_importer --- test/test_importer.py | 161 +++++++++++++++++++++--------------------- 1 file changed, 80 insertions(+), 81 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 56f4a17a5..7e85b041b 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -13,8 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) """Tests for the general importer functionality. """ @@ -121,7 +120,7 @@ class AutotagStub(object): else: id = '' if artist is None: - artist = "Various Artists" + artist = u"Various Artists" else: artist = artist.replace('Tag', 'Applied') + id album = album.replace('Tag', 'Applied') + id @@ -150,9 +149,9 @@ class ImportHelper(TestHelper): def setup_beets(self, disk=False): super(ImportHelper, self).setup_beets(disk) self.lib.path_formats = [ - ('default', os.path.join('$artist', '$album', '$title')), - ('singleton:true', os.path.join('singletons', '$title')), - ('comp:true', os.path.join('compilations', '$album', '$title')), + (u'default', os.path.join('$artist', '$album', '$title')), + (u'singleton:true', os.path.join('singletons', '$title')), + (u'comp:true', os.path.join('compilations', '$album', '$title')), ] def _create_import_dir(self, count=3): @@ -179,8 +178,8 @@ class ImportHelper(TestHelper): resource_path = os.path.join(_common.RSRC, 'full.mp3') metadata = { - 'artist': 'Tag Artist', - 'album': 'Tag Album', + 'artist': u'Tag Artist', + 'album': u'Tag Album', 'albumartist': None, 'mb_trackid': None, 'mb_albumid': None, @@ -195,7 +194,7 @@ class ImportHelper(TestHelper): # Set metadata metadata['track'] = i + 1 - metadata['title'] = 'Tag Title %d' % (i + 1) + metadata['title'] = u'Tag Title %d' % (i + 1) for attr in metadata: setattr(medium, attr, metadata[attr]) medium.save() @@ -250,7 +249,7 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() albums = self.lib.albums() self.assertEqual(len(albums), 1) - self.assertEqual(albums[0].albumartist, 'Tag Artist') + self.assertEqual(albums[0].albumartist, u'Tag Artist') def test_import_copy_arrives(self): self.importer.run() @@ -411,7 +410,7 @@ class ImportTarTest(ImportZipTest): return path -@unittest.skipIf(not has_program('unrar'), 'unrar program not found') +@unittest.skipIf(not has_program('unrar'), u'unrar program not found') class ImportRarTest(ImportZipTest): def create_archive(self): @@ -446,7 +445,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Tag Title 1') + self.assertEqual(self.lib.items().get().title, u'Tag Title 1') def test_apply_asis_does_not_add_album(self): self.assertEqual(self.lib.albums().get(), None) @@ -467,7 +466,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') def test_apply_candidate_does_not_add_album(self): self.importer.add_choice(importer.action.APPLY) @@ -479,7 +478,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assert_file_in_lib('singletons', 'Applied Title 1.mp3') + self.assert_file_in_lib('singletons', u'Applied Title 1.mp3') def test_skip_does_not_add_first_track(self): self.importer.add_choice(importer.action.SKIP) @@ -532,13 +531,13 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Tag Album') + self.assertEqual(self.lib.albums().get().album, u'Tag Album') def test_apply_asis_adds_tracks(self): self.assertEqual(self.lib.items().get(), None) self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Tag Title 1') + self.assertEqual(self.lib.items().get().title, u'Tag Title 1') def test_apply_asis_adds_album_path(self): self.assert_lib_dir_empty() @@ -552,14 +551,14 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album') + self.assertEqual(self.lib.albums().get().album, u'Applied Album') def test_apply_candidate_adds_tracks(self): self.assertEqual(self.lib.items().get(), None) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') def test_apply_candidate_adds_album_path(self): self.assert_lib_dir_empty() @@ -617,7 +616,7 @@ class ImportTest(_common.TestCase, ImportHelper): with capture_log() as logs: self.importer.run() - self.assertIn('No files imported from {0}'.format(import_dir), logs) + self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_empty_directory_singleton_warning(self): import_dir = os.path.join(self.temp_dir, 'empty') @@ -626,7 +625,7 @@ class ImportTest(_common.TestCase, ImportHelper): with capture_log() as logs: self.importer.run() - self.assertIn('No files imported from {0}'.format(import_dir), logs) + self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_asis_no_data_source(self): self.assertEqual(self.lib.items().get(), None) @@ -659,7 +658,7 @@ class ImportTracksTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'Applied Title 1') + self.assertEqual(self.lib.items().get().title, u'Applied Title 1') self.assertEqual(self.lib.albums().get(), None) def test_apply_tracks_adds_singleton_path(self): @@ -688,27 +687,27 @@ class ImportCompilationTest(_common.TestCase, ImportHelper): def test_asis_homogenous_sets_albumartist(self): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Tag Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Tag Artist') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Tag Artist') + self.assertEqual(item.albumartist, u'Tag Artist') def test_asis_heterogenous_sets_various_albumartist(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Another Artist' + self.import_media[1].artist = u'Another Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) self.importer.run() self.assertEqual(self.lib.albums().get().albumartist, - 'Various Artists') + u'Various Artists') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Various Artists') + self.assertEqual(item.albumartist, u'Various Artists') def test_asis_heterogenous_sets_sompilation(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Another Artist' + self.import_media[1].artist = u'Another Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) @@ -717,33 +716,33 @@ class ImportCompilationTest(_common.TestCase, ImportHelper): self.assertTrue(item.comp) def test_asis_sets_majority_albumartist(self): - self.import_media[0].artist = 'Other Artist' + self.import_media[0].artist = u'Other Artist' self.import_media[0].save() - self.import_media[1].artist = 'Other Artist' + self.import_media[1].artist = u'Other Artist' self.import_media[1].save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Other Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Other Artist') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Other Artist') + self.assertEqual(item.albumartist, u'Other Artist') def test_asis_albumartist_tag_sets_albumartist(self): - self.import_media[0].artist = 'Other Artist' - self.import_media[1].artist = 'Another Artist' + self.import_media[0].artist = u'Other Artist' + self.import_media[1].artist = u'Another Artist' for mediafile in self.import_media: - mediafile.albumartist = 'Album Artist' - mediafile.mb_albumartistid = 'Album Artist ID' + mediafile.albumartist = u'Album Artist' + mediafile.mb_albumartistid = u'Album Artist ID' mediafile.save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.albums().get().albumartist, 'Album Artist') + self.assertEqual(self.lib.albums().get().albumartist, u'Album Artist') self.assertEqual(self.lib.albums().get().mb_albumartistid, - 'Album Artist ID') + u'Album Artist ID') for item in self.lib.items(): - self.assertEqual(item.albumartist, 'Album Artist') - self.assertEqual(item.mb_albumartistid, 'Album Artist ID') + self.assertEqual(item.albumartist, u'Album Artist') + self.assertEqual(item.mb_albumartistid, u'Album Artist ID') class ImportExistingTest(_common.TestCase, ImportHelper): @@ -794,17 +793,17 @@ class ImportExistingTest(_common.TestCase, ImportHelper): def test_asis_updates_metadata(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assertEqual(self.lib.items().get().title, 'New Title') + self.assertEqual(self.lib.items().get().title, u'New Title') def test_asis_updated_moves_file(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() old_path = os.path.join('Applied Artist', 'Applied Album', @@ -820,7 +819,7 @@ class ImportExistingTest(_common.TestCase, ImportHelper): def test_asis_updated_without_copy_does_not_move_file(self): self.setup_importer.run() medium = MediaFile(self.lib.items().get().path) - medium.title = 'New Title' + medium.title = u'New Title' medium.save() old_path = os.path.join('Applied Artist', 'Applied Album', @@ -881,8 +880,8 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.matcher.restore() def test_add_album_for_different_artist_and_different_album(self): - self.import_media[0].artist = "Artist B" - self.import_media[0].album = "Album B" + self.import_media[0].artist = u"Artist B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -890,11 +889,11 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(albums, set(['Album B', 'Tag Album'])) def test_add_album_for_different_artist_and_same_albumartist(self): - self.import_media[0].artist = "Artist B" - self.import_media[0].albumartist = "Album Artist" + self.import_media[0].artist = u"Artist B" + self.import_media[0].albumartist = u"Album Artist" self.import_media[0].save() - self.import_media[1].artist = "Artist C" - self.import_media[1].albumartist = "Album Artist" + self.import_media[1].artist = u"Artist C" + self.import_media[1].albumartist = u"Album Artist" self.import_media[1].save() self.importer.run() @@ -902,7 +901,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(artists, set(['Album Artist', 'Tag Artist'])) def test_add_album_for_same_artist_and_different_album(self): - self.import_media[0].album = "Album B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -910,7 +909,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): self.assertEqual(albums, set(['Album B', 'Tag Album'])) def test_add_album_for_same_album_and_different_artist(self): - self.import_media[0].artist = "Artist B" + self.import_media[0].artist = u"Artist B" self.import_media[0].save() self.importer.run() @@ -919,7 +918,7 @@ class GroupAlbumsImportTest(_common.TestCase, ImportHelper): def test_incremental(self): config['import']['incremental'] = True - self.import_media[0].album = "Album B" + self.import_media[0].album = u"Album B" self.import_media[0].save() self.importer.run() @@ -951,12 +950,12 @@ class ChooseCandidateTest(_common.TestCase, ImportHelper): def test_choose_first_candidate(self): self.importer.add_choice(1) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album M') + self.assertEqual(self.lib.albums().get().album, u'Applied Album M') def test_choose_second_candidate(self): self.importer.add_choice(2) self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'Applied Album MM') + self.assertEqual(self.lib.albums().get().album, u'Applied Album MM') class InferAlbumDataTest(_common.TestCase): @@ -966,9 +965,9 @@ class InferAlbumDataTest(_common.TestCase): i1 = _common.item() i2 = _common.item() i3 = _common.item() - i1.title = 'first item' - i2.title = 'second item' - i3.title = 'third item' + i1.title = u'first item' + i2.title = u'second item' + i3.title = u'third item' i1.comp = i2.comp = i3.comp = False i1.albumartist = i2.albumartist = i3.albumartist = '' i1.mb_albumartistid = i2.mb_albumartistid = i3.mb_albumartistid = '' @@ -984,28 +983,28 @@ class InferAlbumDataTest(_common.TestCase): self.assertEqual(self.items[0].albumartist, self.items[2].artist) def test_asis_heterogenous_va(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() self.assertTrue(self.items[0].comp) - self.assertEqual(self.items[0].albumartist, 'Various Artists') + self.assertEqual(self.items[0].albumartist, u'Various Artists') def test_asis_comp_applied_to_all_items(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() for item in self.items: self.assertTrue(item.comp) - self.assertEqual(item.albumartist, 'Various Artists') + self.assertEqual(item.albumartist, u'Various Artists') def test_asis_majority_artist_single_artist(self): - self.items[0].artist = 'another artist' + self.items[0].artist = u'another artist' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() @@ -1014,19 +1013,19 @@ class InferAlbumDataTest(_common.TestCase): self.assertEqual(self.items[0].albumartist, self.items[2].artist) def test_asis_track_albumartist_override(self): - self.items[0].artist = 'another artist' - self.items[1].artist = 'some other artist' + self.items[0].artist = u'another artist' + self.items[1].artist = u'some other artist' for item in self.items: - item.albumartist = 'some album artist' - item.mb_albumartistid = 'some album artist id' + item.albumartist = u'some album artist' + item.mb_albumartistid = u'some album artist id' self.task.set_choice(importer.action.ASIS) self.task.align_album_level_fields() self.assertEqual(self.items[0].albumartist, - 'some album artist') + u'some album artist') self.assertEqual(self.items[0].mb_albumartistid, - 'some album artist id') + u'some album artist id') def test_apply_gets_artist_and_id(self): self.task.set_choice(AlbumMatch(0, None, {}, set(), set())) # APPLY @@ -1039,16 +1038,16 @@ class InferAlbumDataTest(_common.TestCase): def test_apply_lets_album_values_override(self): for item in self.items: - item.albumartist = 'some album artist' - item.mb_albumartistid = 'some album artist id' + item.albumartist = u'some album artist' + item.mb_albumartistid = u'some album artist id' self.task.set_choice(AlbumMatch(0, None, {}, set(), set())) # APPLY self.task.align_album_level_fields() self.assertEqual(self.items[0].albumartist, - 'some album artist') + u'some album artist') self.assertEqual(self.items[0].mb_albumartistid, - 'some album artist id') + u'some album artist id') def test_small_single_artist_album(self): self.items = [self.items[0]] @@ -1272,11 +1271,11 @@ class ResumeImportTest(unittest.TestCase, TestHelper): self.importer.run() self.assertEqual(len(self.lib.albums()), 1) - self.assertIsNotNone(self.lib.albums('album:album 0').get()) + self.assertIsNotNone(self.lib.albums(u'album:album 0').get()) self.importer.run() self.assertEqual(len(self.lib.albums()), 2) - self.assertIsNotNone(self.lib.albums('album:album 1').get()) + self.assertIsNotNone(self.lib.albums(u'album:album 1').get()) @patch('beets.plugins.send') def test_resume_singleton(self, plugins_send): @@ -1293,11 +1292,11 @@ class ResumeImportTest(unittest.TestCase, TestHelper): self.importer.run() self.assertEqual(len(self.lib.items()), 1) - self.assertIsNotNone(self.lib.items('title:track 0').get()) + self.assertIsNotNone(self.lib.items(u'title:track 0').get()) self.importer.run() self.assertEqual(len(self.lib.items()), 2) - self.assertIsNotNone(self.lib.items('title:track 1').get()) + self.assertIsNotNone(self.lib.items(u'title:track 1').get()) class IncrementalImportTest(unittest.TestCase, TestHelper): @@ -1685,7 +1684,7 @@ class ImportPretendTest(_common.TestCase, ImportHelper): def test_import_pretend_empty(self): logs = self.__run([self.empty_path]) - self.assertEqual(logs, ['No files imported from {0}' + self.assertEqual(logs, [u'No files imported from {0}' .format(displayable_path(self.empty_path))]) From b6e069604184c70305f89084dfcce97cbb02e915 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Sun, 28 Feb 2016 13:39:24 +0100 Subject: [PATCH 0595/2280] Removed unicode_literals from test_ui MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * nosetests ´test.test_ui´ fails for two tests --- test/test_ui.py | 311 ++++++++++++++++++++++++------------------------ 1 file changed, 156 insertions(+), 155 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 480e6ce03..52adaa556 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -15,8 +15,7 @@ """Tests for the command-line interface. """ -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import (division, absolute_import, print_function) import os import shutil @@ -50,7 +49,7 @@ class ListTest(unittest.TestCase): self.lib.add(self.item) self.lib.add_album([self.item]) - def _run_list(self, query='', album=False, path=False, fmt=''): + def _run_list(self, query=u'', album=False, path=False, fmt=''): commands.list_items(self.lib, query, album, fmt) def test_list_outputs_item(self): @@ -135,14 +134,14 @@ class RemoveTest(_common.TestCase): def test_remove_items_no_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, '', False, False) + commands.remove_items(self.lib, u'', False, False) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertTrue(os.path.exists(self.i.path)) def test_remove_items_with_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, '', False, True) + commands.remove_items(self.lib, u'', False, True) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertFalse(os.path.exists(self.i.path)) @@ -168,58 +167,58 @@ class ModifyTest(unittest.TestCase, TestHelper): # Item tests def test_modify_item(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() - self.assertEqual(item.title, 'newTitle') + self.assertEqual(item.title, u'newTitle') def test_modify_item_abort(self): item = self.lib.items().get() title = item.title - self.modify_inp('n', "title=newTitle") + self.modify_inp('n', u"title=newTitle") item = self.lib.items().get() self.assertEqual(item.title, title) def test_modify_item_no_change(self): - title = "Tracktitle" + title = u"Tracktitle" item = self.add_item_fixture(title=title) - self.modify_inp('y', "title", "title={0}".format(title)) + self.modify_inp('y', u"title", u"title={0}".format(title)) item = self.lib.items(title).get() self.assertEqual(item.title, title) def test_modify_write_tags(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() item.read() - self.assertEqual(item.title, 'newTitle') + self.assertEqual(item.title, u'newTitle') def test_modify_dont_write_tags(self): - self.modify("--nowrite", "title=newTitle") + self.modify(u"--nowrite", u"title=newTitle") item = self.lib.items().get() item.read() self.assertNotEqual(item.title, 'newTitle') def test_move(self): - self.modify("title=newTitle") + self.modify(u"title=newTitle") item = self.lib.items().get() self.assertIn(b'newTitle', item.path) def test_not_move(self): - self.modify("--nomove", "title=newTitle") + self.modify(u"--nomove", u"title=newTitle") item = self.lib.items().get() self.assertNotIn(b'newTitle', item.path) def test_no_write_no_move(self): - self.modify("--nomove", "--nowrite", "title=newTitle") + self.modify(u"--nomove", u"--nowrite", u"title=newTitle") item = self.lib.items().get() item.read() self.assertNotIn(b'newTitle', item.path) - self.assertNotEqual(item.title, 'newTitle') + self.assertNotEqual(item.title, u'newTitle') def test_update_mtime(self): item = self.item old_mtime = item.mtime - self.modify("title=newTitle") + self.modify(u"title=newTitle") item.load() self.assertNotEqual(old_mtime, item.mtime) self.assertEqual(item.current_mtime(), item.mtime) @@ -227,53 +226,53 @@ class ModifyTest(unittest.TestCase, TestHelper): def test_reset_mtime_with_no_write(self): item = self.item - self.modify("--nowrite", "title=newTitle") + self.modify(u"--nowrite", u"title=newTitle") item.load() self.assertEqual(0, item.mtime) def test_selective_modify(self): - title = "Tracktitle" - album = "album" - origArtist = "composer" - newArtist = "coverArtist" + title = u"Tracktitle" + album = u"album" + origArtist = u"composer" + newArtist = u"coverArtist" for i in range(0, 10): - self.add_item_fixture(title="{0}{1}".format(title, i), + self.add_item_fixture(title=u"{0}{1}".format(title, i), artist=origArtist, album=album) self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn', - title, "artist={0}".format(newArtist)) - origItems = self.lib.items("artist:{0}".format(origArtist)) - newItems = self.lib.items("artist:{0}".format(newArtist)) + title, u"artist={0}".format(newArtist)) + origItems = self.lib.items(u"artist:{0}".format(origArtist)) + newItems = self.lib.items(u"artist:{0}".format(newArtist)) self.assertEqual(len(list(origItems)), 3) self.assertEqual(len(list(newItems)), 7) # Album Tests def test_modify_album(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") album = self.lib.albums().get() - self.assertEqual(album.album, 'newAlbum') + self.assertEqual(album.album, u'newAlbum') def test_modify_album_write_tags(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() - self.assertEqual(item.album, 'newAlbum') + self.assertEqual(item.album, u'newAlbum') def test_modify_album_dont_write_tags(self): - self.modify("--album", "--nowrite", "album=newAlbum") + self.modify(u"--album", u"--nowrite", u"album=newAlbum") item = self.lib.items().get() item.read() - self.assertEqual(item.album, 'the album') + self.assertEqual(item.album, u'the album') def test_album_move(self): - self.modify("--album", "album=newAlbum") + self.modify(u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() self.assertIn(b'newAlbum', item.path) def test_album_not_move(self): - self.modify("--nomove", "--album", "album=newAlbum") + self.modify(u"--nomove", u"--album", u"album=newAlbum") item = self.lib.items().get() item.read() self.assertNotIn(b'newAlbum', item.path) @@ -281,62 +280,62 @@ class ModifyTest(unittest.TestCase, TestHelper): # Misc def test_write_initial_key_tag(self): - self.modify("initial_key=C#m") + self.modify(u"initial_key=C#m") item = self.lib.items().get() mediafile = MediaFile(item.path) - self.assertEqual(mediafile.initial_key, 'C#m') + self.assertEqual(mediafile.initial_key, u'C#m') def test_set_flexattr(self): - self.modify("flexattr=testAttr") + self.modify(u"flexattr=testAttr") item = self.lib.items().get() - self.assertEqual(item.flexattr, 'testAttr') + self.assertEqual(item.flexattr, u'testAttr') def test_remove_flexattr(self): item = self.lib.items().get() - item.flexattr = 'testAttr' + item.flexattr = u'testAttr' item.store() - self.modify("flexattr!") + self.modify(u"flexattr!") item = self.lib.items().get() - self.assertNotIn("flexattr", item) + self.assertNotIn(u"flexattr", item) - @unittest.skip('not yet implemented') + @unittest.skip(u'not yet implemented') def test_delete_initial_key_tag(self): item = self.lib.items().get() - item.initial_key = 'C#m' + item.initial_key = u'C#m' item.write() item.store() mediafile = MediaFile(item.path) - self.assertEqual(mediafile.initial_key, 'C#m') + self.assertEqual(mediafile.initial_key, u'C#m') - self.modify("initial_key!") + self.modify(u"initial_key!") mediafile = MediaFile(item.path) self.assertIsNone(mediafile.initial_key) def test_arg_parsing_colon_query(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle", - "title=newTitle"]) - self.assertEqual(query, ["title:oldTitle"]) - self.assertEqual(mods, {"title": "newTitle"}) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle", + u"title=newTitle"]) + self.assertEqual(query, [u"title:oldTitle"]) + self.assertEqual(mods, {"title": u"newTitle"}) def test_arg_parsing_delete(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle", - "title!"]) - self.assertEqual(query, ["title:oldTitle"]) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle", + u"title!"]) + self.assertEqual(query, [u"title:oldTitle"]) self.assertEqual(dels, ["title"]) def test_arg_parsing_query_with_exclaimation(self): - (query, mods, dels) = commands.modify_parse_args(["title:oldTitle!", - "title=newTitle!"]) - self.assertEqual(query, ["title:oldTitle!"]) - self.assertEqual(mods, {"title": "newTitle!"}) + (query, mods, dels) = commands.modify_parse_args([u"title:oldTitle!", + u"title=newTitle!"]) + self.assertEqual(query, [u"title:oldTitle!"]) + self.assertEqual(mods, {"title": u"newTitle!"}) def test_arg_parsing_equals_in_value(self): - (query, mods, dels) = commands.modify_parse_args(["title:foo=bar", - "title=newTitle"]) - self.assertEqual(query, ["title:foo=bar"]) - self.assertEqual(mods, {"title": "newTitle"}) + (query, mods, dels) = commands.modify_parse_args([u"title:foo=bar", + u"title=newTitle"]) + self.assertEqual(query, [u"title:foo=bar"]) + self.assertEqual(mods, {"title": u"newTitle"}) class WriteTest(unittest.TestCase, TestHelper): @@ -352,7 +351,7 @@ class WriteTest(unittest.TestCase, TestHelper): def test_update_mtime(self): item = self.add_item_fixture() - item['title'] = 'a new title' + item['title'] = u'a new title' item.store() item = self.lib.items().get() @@ -384,13 +383,13 @@ class WriteTest(unittest.TestCase, TestHelper): item.read() old_title = item.title - item.title = 'new title' + item.title = u'new title' item.store() with capture_stdout() as stdout: self.write_cmd() - self.assertTrue('{0} -> new title'.format(old_title) + self.assertTrue(u'{0} -> new title'.format(old_title) in stdout.getvalue()) @@ -522,40 +521,40 @@ class UpdateTest(_common.TestCase): def test_modified_metadata_detected(self): mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf.title = u'differentTitle' mf.save() self._update() item = self.lib.items().get() - self.assertEqual(item.title, 'differentTitle') + self.assertEqual(item.title, u'differentTitle') def test_modified_metadata_moved(self): mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf.title = u'differentTitle' mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue('differentTitle' in item.path) + self.assertTrue(u'differentTitle' in item.path) def test_modified_metadata_not_moved(self): mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf.title = u'differentTitle' mf.save() self._update(move=False) item = self.lib.items().get() - self.assertTrue('differentTitle' not in item.path) + self.assertTrue(u'differentTitle' not in item.path) def test_modified_album_metadata_moved(self): mf = MediaFile(self.i.path) - mf.album = 'differentAlbum' + mf.album = u'differentAlbum' mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue('differentAlbum' in item.path) + self.assertTrue(u'differentAlbum' in item.path) def test_modified_album_metadata_art_moved(self): artpath = self.album.artpath mf = MediaFile(self.i.path) - mf.album = 'differentAlbum' + mf.album = u'differentAlbum' mf.save() self._update(move=True) album = self.lib.albums()[0] @@ -563,7 +562,7 @@ class UpdateTest(_common.TestCase): def test_mtime_match_skips_update(self): mf = MediaFile(self.i.path) - mf.title = 'differentTitle' + mf.title = u'differentTitle' mf.save() # Make in-memory mtime match on-disk mtime. @@ -572,7 +571,7 @@ class UpdateTest(_common.TestCase): self._update(reset_mtime=False) item = self.lib.items().get() - self.assertEqual(item.title, 'full') + self.assertEqual(item.title, u'full') class PrintTest(_common.TestCase): @@ -588,7 +587,7 @@ class PrintTest(_common.TestCase): try: ui.print_(u'something') except TypeError: - self.fail('TypeError during print') + self.fail(u'TypeError during print') finally: if lang: os.environ['LANG'] = lang @@ -602,7 +601,7 @@ class PrintTest(_common.TestCase): try: ui.print_(u'something') except ValueError: - self.fail('ValueError during print') + self.fail(u'ValueError during print') finally: if old_lang: os.environ['LANG'] = old_lang @@ -677,7 +676,7 @@ class ConfigTest(unittest.TestCase, TestHelper): self.teardown_beets() def _make_test_cmd(self): - test_cmd = ui.Subcommand('test', help='test') + test_cmd = ui.Subcommand('test', help=u'test') def run(lib, options, args): test_cmd.lib = lib @@ -747,7 +746,7 @@ class ConfigTest(unittest.TestCase, TestHelper): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ - (re.compile(r'[xy]'), 'z'), + (re.compile(r'[xy]'), u'z'), (re.compile(r'foo'), 'bar'), ]) @@ -929,34 +928,34 @@ class ShowModelChangeTest(_common.TestCase): self.b.title = 'x' change, out = self._show() self.assertTrue(change) - self.assertTrue('title' in out) + self.assertTrue(u'title' in out) def test_int_fixed_field_change(self): self.b.track = 9 change, out = self._show() self.assertTrue(change) - self.assertTrue('track' in out) + self.assertTrue(u'track' in out) def test_floats_close_to_identical(self): self.a.length = 1.00001 self.b.length = 1.00005 change, out = self._show() self.assertFalse(change) - self.assertEqual(out, '') + self.assertEqual(out, u'') def test_floats_different(self): self.a.length = 1.00001 self.b.length = 2.00001 change, out = self._show() self.assertTrue(change) - self.assertTrue('length' in out) + self.assertTrue(u'length' in out) def test_both_values_shown(self): - self.a.title = 'foo' - self.b.title = 'bar' + self.a.title = u'foo' + self.b.title = u'bar' change, out = self._show() - self.assertTrue('foo' in out) - self.assertTrue('bar' in out) + self.assertTrue(u'foo' in out) + self.assertTrue(u'bar' in out) class ShowChangeTest(_common.TestCase): @@ -1014,12 +1013,12 @@ class ShowChangeTest(_common.TestCase): def test_album_data_change_with_unicode(self): msg = self._show_change(cur_artist=u'caf\xe9', cur_album=u'another album') - self.assertTrue('correcting tags from:' in msg) + self.assertTrue(u'correcting tags from:' in msg) def test_item_data_change_title_missing(self): self.items[0].title = u'' msg = re.sub(r' +', ' ', self._show_change()) - self.assertTrue('file.mp3 -> the title' in msg) + self.assertTrue(u'file.mp3 -> the title' in msg) def test_item_data_change_title_missing_with_unicode_filename(self): self.items[0].title = u'' @@ -1042,28 +1041,28 @@ class SummarizeItemsTest(_common.TestCase): def test_summarize_item(self): summary = commands.summarize_items([], True) - self.assertEqual(summary, "") + self.assertEqual(summary, u"") summary = commands.summarize_items([self.item], True) - self.assertEqual(summary, "F, 4kbps, 10:54, 987.0 B") + self.assertEqual(summary, u"F, 4kbps, 10:54, 987.0 B") def test_summarize_items(self): summary = commands.summarize_items([], False) - self.assertEqual(summary, "0 items") + self.assertEqual(summary, u"0 items") summary = commands.summarize_items([self.item], False) - self.assertEqual(summary, "1 items, F, 4kbps, 10:54, 987.0 B") + self.assertEqual(summary, u"1 items, F, 4kbps, 10:54, 987.0 B") i2 = deepcopy(self.item) summary = commands.summarize_items([self.item, i2], False) - self.assertEqual(summary, "2 items, F, 4kbps, 21:48, 1.9 KiB") + self.assertEqual(summary, u"2 items, F, 4kbps, 21:48, 1.9 KiB") i2.format = "G" summary = commands.summarize_items([self.item, i2], False) - self.assertEqual(summary, "2 items, F 1, G 1, 4kbps, 21:48, 1.9 KiB") + self.assertEqual(summary, u"2 items, F 1, G 1, 4kbps, 21:48, 1.9 KiB") summary = commands.summarize_items([self.item, i2, i2], False) - self.assertEqual(summary, "3 items, G 2, F 1, 4kbps, 32:42, 2.9 KiB") + self.assertEqual(summary, u"3 items, G 2, F 1, 4kbps, 32:42, 2.9 KiB") class PathFormatTest(_common.TestCase): @@ -1073,8 +1072,8 @@ class PathFormatTest(_common.TestCase): config['paths'] = {u'foo': u'bar'} pf = ui.get_path_formats() key, tmpl = pf[0] - self.assertEqual(key, 'foo') - self.assertEqual(tmpl.original, 'bar') + self.assertEqual(key, u'foo') + self.assertEqual(tmpl.original, u'bar') self.assertEqual(pf[1:], default_formats) @@ -1096,7 +1095,7 @@ class CompletionTest(_common.TestCase): # Tests run in bash cmd = os.environ.get('BEETS_TEST_SHELL', '/bin/bash --norc').split() if not has_program(cmd[0]): - self.skipTest('bash not available') + self.skipTest(u'bash not available') tester = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) @@ -1106,12 +1105,12 @@ class CompletionTest(_common.TestCase): bash_completion = path break else: - self.skipTest('bash-completion script not found') + self.skipTest(u'bash-completion script not found') try: with open(util.syspath(bash_completion), 'r') as f: tester.stdin.writelines(f) except IOError: - self.skipTest('could not read bash-completion script') + self.skipTest(u'could not read bash-completion script') # Load completion script. self.io.install() @@ -1125,9 +1124,9 @@ class CompletionTest(_common.TestCase): with open(test_script, 'r') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() - if tester.returncode != 0 or out != "completion tests passed\n": + if tester.returncode != 0 or out != u"completion tests passed\n": print(out) - self.fail('test/test_completion.sh did not execute properly') + self.fail(u'test/test_completion.sh did not execute properly') class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): @@ -1146,56 +1145,57 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): self.teardown_beets() def test_base(self): - l = self.run_with_output('ls') - self.assertEqual(l, 'the artist - the album - the title\n') + l = self.run_with_output(u'ls') + self.assertEqual(l, u'the artist - the album - the title\n') - l = self.run_with_output('ls', '-a') - self.assertEqual(l, 'the album artist - the album\n') + l = self.run_with_output(u'ls', u'-a') + self.assertEqual(l, u'the album artist - the album\n') def test_path_option(self): - l = self.run_with_output('ls', '-p') - self.assertEqual(l, 'xxx/yyy\n') + l = self.run_with_output(u'ls', u'-p') + self.assertEqual(l, u'xxx/yyy\n') - l = self.run_with_output('ls', '-a', '-p') - self.assertEqual(l, 'xxx\n') + l = self.run_with_output(u'ls', u'-a', u'-p') + self.assertEqual(l, u'xxx\n') def test_format_option(self): - l = self.run_with_output('ls', '-f', '$artist') - self.assertEqual(l, 'the artist\n') + l = self.run_with_output(u'ls', u'-f', '$artist') + self.assertEqual(l, u'the artist\n') - l = self.run_with_output('ls', '-a', '-f', '$albumartist') - self.assertEqual(l, 'the album artist\n') + l = self.run_with_output(u'ls', u'-a', u'-f', '$albumartist') + self.assertEqual(l, u'the album artist\n') def test_root_format_option(self): - l = self.run_with_output('--format-item', '$artist', - '--format-album', 'foo', 'ls') - self.assertEqual(l, 'the artist\n') + l = self.run_with_output(u'--format-item', u'$artist', + u'--format-album', u'foo', u'ls') + self.assertEqual(l, u'the artist\n') - l = self.run_with_output('--format-item', 'foo', - '--format-album', '$albumartist', 'ls', '-a') - self.assertEqual(l, 'the album artist\n') + l = self.run_with_output(u'--format-item', u'foo', + u'--format-album', u'$albumartist', + u'ls', u'-a') + self.assertEqual(l, u'the album artist\n') def test_help(self): - l = self.run_with_output('help') - self.assertIn('Usage:', l) + l = self.run_with_output(u'help') + self.assertIn(u'Usage:', l) - l = self.run_with_output('help', 'list') - self.assertIn('Usage:', l) + l = self.run_with_output(u'help', u'list') + self.assertIn(u'Usage:', l) with self.assertRaises(ui.UserError): - self.run_command('help', 'this.is.not.a.real.command') + self.run_command(u'help', u'this.is.not.a.real.command') def test_stats(self): - l = self.run_with_output('stats') - self.assertIn('Approximate total size:', l) + l = self.run_with_output(u'stats') + self.assertIn(u'Approximate total size:', l) # # Need to have more realistic library setup for this to work # l = self.run_with_output('stats', '-e') # self.assertIn('Total size:', l) def test_version(self): - l = self.run_with_output('version') - self.assertIn('no plugins loaded', l) + l = self.run_with_output(u'version') + self.assertIn(u'no plugins loaded', l) # # Need to have plugin loaded # l = self.run_with_output('version') @@ -1216,8 +1216,9 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): self.assertTrue(bool(parser._album_flags)) self.assertEqual(parser.parse_args([]), ({'album': None}, [])) - self.assertEqual(parser.parse_args(['-a']), ({'album': True}, [])) - self.assertEqual(parser.parse_args(['--album']), ({'album': True}, [])) + self.assertEqual(parser.parse_args([u'-a']), ({'album': True}, [])) + self.assertEqual(parser.parse_args([u'--album']), + ({'album': True}, [])) def test_path_option(self): parser = ui.CommonOptionsParser() @@ -1228,13 +1229,13 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): self.assertEqual(parser.parse_args([]), ({'path': None}, [])) self.assertEqual(config['format_item'].get(unicode), u'$foo') - self.assertEqual(parser.parse_args(['-p']), - ({'path': True, 'format': '$path'}, [])) + self.assertEqual(parser.parse_args([u'-p']), + ({'path': True, 'format': u'$path'}, [])) self.assertEqual(parser.parse_args(['--path']), - ({'path': True, 'format': '$path'}, [])) + ({'path': True, 'format': u'$path'}, [])) - self.assertEqual(config['format_item'].get(unicode), '$path') - self.assertEqual(config['format_album'].get(unicode), '$path') + self.assertEqual(config['format_item'].get(unicode), u'$path') + self.assertEqual(config['format_album'].get(unicode), u'$path') def test_format_option(self): parser = ui.CommonOptionsParser() @@ -1245,13 +1246,13 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): self.assertEqual(parser.parse_args([]), ({'format': None}, [])) self.assertEqual(config['format_item'].get(unicode), u'$foo') - self.assertEqual(parser.parse_args(['-f', '$bar']), - ({'format': '$bar'}, [])) - self.assertEqual(parser.parse_args(['--format', '$baz']), - ({'format': '$baz'}, [])) + 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(unicode), '$baz') - self.assertEqual(config['format_album'].get(unicode), '$baz') + self.assertEqual(config['format_item'].get(unicode), u'$baz') + self.assertEqual(config['format_album'].get(unicode), u'$baz') def test_format_option_with_target(self): with self.assertRaises(KeyError): @@ -1263,11 +1264,11 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$item') config['format_album'].set('$album') - self.assertEqual(parser.parse_args(['-f', '$bar']), - ({'format': '$bar'}, [])) + self.assertEqual(parser.parse_args([u'-f', u'$bar']), + ({'format': u'$bar'}, [])) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$album') + self.assertEqual(config['format_item'].get(unicode), u'$bar') + self.assertEqual(config['format_album'].get(unicode), u'$album') def test_format_option_with_album(self): parser = ui.CommonOptionsParser() @@ -1277,16 +1278,16 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$item') config['format_album'].set('$album') - parser.parse_args(['-f', '$bar']) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$album') + parser.parse_args([u'-f', u'$bar']) + self.assertEqual(config['format_item'].get(unicode), u'$bar') + self.assertEqual(config['format_album'].get(unicode), u'$album') - parser.parse_args(['-a', '-f', '$foo']) - self.assertEqual(config['format_item'].get(unicode), '$bar') - self.assertEqual(config['format_album'].get(unicode), '$foo') + parser.parse_args([u'-a', u'-f', u'$foo']) + self.assertEqual(config['format_item'].get(unicode), u'$bar') + self.assertEqual(config['format_album'].get(unicode), u'$foo') - parser.parse_args(['-f', '$foo2', '-a']) - self.assertEqual(config['format_album'].get(unicode), '$foo2') + parser.parse_args([u'-f', u'$foo2', u'-a']) + self.assertEqual(config['format_album'].get(unicode), u'$foo2') def test_add_all_common_options(self): parser = ui.CommonOptionsParser() From a07b98ad246e324c26efb4dc1f202a0cb45e5cd8 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Sun, 28 Feb 2016 19:21:59 +0100 Subject: [PATCH 0596/2280] Fix leftover literals --- test/test_ui.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 52adaa556..a4763644d 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -737,7 +737,7 @@ class ConfigTest(unittest.TestCase, TestHelper): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements - self.assertEqual(replacements, [(re.compile(r'[xy]'), b'z')]) + self.assertEqual(replacements, [(re.compile(u'[xy]'), b'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: @@ -746,8 +746,8 @@ class ConfigTest(unittest.TestCase, TestHelper): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ - (re.compile(r'[xy]'), u'z'), - (re.compile(r'foo'), 'bar'), + (re.compile(u'[xy]'), u'z'), + (re.compile(u'foo'), u'bar'), ]) def test_cli_config_option(self): From 48659c5df418fbe9bf34d0d563ed93f65b9af3d3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 13:37:01 -0800 Subject: [PATCH 0597/2280] Fix #1896 (bungled fix to #1895) --- beets/mediafile.py | 4 ++-- test/test_mediafile_edge.py | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 02befcbb0..c6d265b40 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -215,9 +215,9 @@ def _sc_decode(soundcheck): used by ReplayGain. """ # We decode binary data. If one of the formats gives us a text - # string, guess that it's UTF-8. + # string, interpret it as UTF-8. if isinstance(soundcheck, unicode): - soundcheck = soundcheck.decode('utf8') + soundcheck = soundcheck.encode('utf8') # SoundCheck tags consist of 10 numbers, each represented by 8 # characters of ASCII hex preceded by a space. diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 298cb6dc1..da522cd3d 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -313,6 +313,13 @@ class SoundCheckTest(unittest.TestCase): self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) + def test_decode_handles_unicode(self): + # Most of the time, we expect to decode the raw bytes. But some formats + # might give us text strings, which we need to handle. + gain, peak = beets.mediafile._sc_decode(u'caf\xe9') + self.assertEqual(gain, 0.0) + self.assertEqual(peak, 0.0) + class ID3v23Test(unittest.TestCase, TestHelper): def _make_test(self, ext='mp3', id3v23=False): From c16201a7950de36e2227e8b8ec99ea3137f74c5c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 14:10:11 -0800 Subject: [PATCH 0598/2280] Keep raw literals for regular expressions --- test/test_ui.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index a4763644d..d9a7da86f 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -737,7 +737,7 @@ class ConfigTest(unittest.TestCase, TestHelper): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements - self.assertEqual(replacements, [(re.compile(u'[xy]'), b'z')]) + self.assertEqual(replacements, [(re.compile(ur'[xy]'), b'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: @@ -746,8 +746,8 @@ class ConfigTest(unittest.TestCase, TestHelper): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ - (re.compile(u'[xy]'), u'z'), - (re.compile(u'foo'), u'bar'), + (re.compile(ur'[xy]'), u'z'), + (re.compile(ur'foo'), u'bar'), ]) def test_cli_config_option(self): From 7c30f56271395db0863d362a0ffa56d428c21151 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 14:17:01 -0800 Subject: [PATCH 0599/2280] Another regex literal --- beets/autotag/mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 9ffac4918..33bf9b8a7 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -376,7 +376,7 @@ def _parse_id(s): no ID can be found, return None. """ # Find the first thing that looks like a UUID/MBID. - match = re.search(r'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) + match = re.search(ur'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group() From ad1bab63edd38c05cbb562ac976c29c331e2d4e4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 14:18:50 -0800 Subject: [PATCH 0600/2280] Fiddle with whitespace --- beets/dbcore/db.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 07b0e9a45..19dd720d9 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -201,7 +201,8 @@ class Model(object): """ if not self._db: raise ValueError( - u'{0} has no database'.format(type(self).__name__)) + u'{0} has no database'.format(type(self).__name__) + ) if need_id and not self.id: raise ValueError(u'{0} has no id'.format(type(self).__name__)) From 1478ba734f202367b56c687f3e370f87a79c1b6f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 14:19:01 -0800 Subject: [PATCH 0601/2280] __repr__ and __str__ return "native" strings --- beets/dbcore/db.py | 2 +- beets/dbcore/query.py | 22 +++++++++++----------- beets/util/confit.py | 12 ++++++------ test/_common.py | 4 ++-- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 19dd720d9..2a2709240 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -183,7 +183,7 @@ class Model(object): return obj def __repr__(self): - return u'{0}({1})'.format( + return '{0}({1})'.format( type(self).__name__, ', '.join('{0}={1!r}'.format(k, v) for k, v in dict(self).items()), ) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 268c879c7..7c6fc077d 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -74,7 +74,7 @@ class Query(object): raise NotImplementedError def __repr__(self): - return u"{0.__class__.__name__}()".format(self) + return "{0.__class__.__name__}()".format(self) def __eq__(self, other): return type(self) == type(other) @@ -116,8 +116,8 @@ class FieldQuery(Query): return self.value_match(self.pattern, item.get(self.field)) def __repr__(self): - return (u"{0.__class__.__name__}({0.field!r}, {0.pattern!r}, " - u"{0.fast})".format(self)) + return ("{0.__class__.__name__}({0.field!r}, {0.pattern!r}, " + "{0.fast})".format(self)) def __eq__(self, other): return super(FieldQuery, self).__eq__(other) and \ @@ -153,7 +153,7 @@ class NoneQuery(FieldQuery): return True def __repr__(self): - return u"{0.__class__.__name__}({0.field!r}, {0.fast})".format(self) + return "{0.__class__.__name__}({0.field!r}, {0.fast})".format(self) class StringFieldQuery(FieldQuery): @@ -368,7 +368,7 @@ class CollectionQuery(Query): return clause, subvals def __repr__(self): - return u"{0.__class__.__name__}({0.subqueries})".format(self) + return "{0.__class__.__name__}({0.subqueries!r})".format(self) def __eq__(self, other): return super(CollectionQuery, self).__eq__(other) and \ @@ -406,8 +406,8 @@ class AnyFieldQuery(CollectionQuery): return False def __repr__(self): - return (u"{0.__class__.__name__}({0.pattern!r}, {0.fields}, " - u"{0.query_class.__name__})".format(self)) + return ("{0.__class__.__name__}({0.pattern!r}, {0.fields!r}, " + "{0.query_class.__name__})".format(self)) def __eq__(self, other): return super(AnyFieldQuery, self).__eq__(other) and \ @@ -466,7 +466,7 @@ class NotQuery(Query): return not self.subquery.match(item) def __repr__(self): - return u"{0.__class__.__name__}({0.subquery})".format(self) + return "{0.__class__.__name__}({0.subquery!r})".format(self) def __eq__(self, other): return super(NotQuery, self).__eq__(other) and \ @@ -607,7 +607,7 @@ class DateInterval(object): return True def __str__(self): - return u'[{0}, {1})'.format(self.start, self.end) + return '[{0}, {1})'.format(self.start, self.end) class DateQuery(FieldQuery): @@ -768,7 +768,7 @@ class MultipleSort(Sort): return items def __repr__(self): - return u'MultipleSort({0})'.format(repr(self.sorts)) + return 'MultipleSort({!r})'.format(self.sorts) def __hash__(self): return hash(tuple(self.sorts)) @@ -801,7 +801,7 @@ class FieldSort(Sort): return sorted(objs, key=key, reverse=not self.ascending) def __repr__(self): - return u'<{0}: {1}{2}>'.format( + return '<{0}: {1}{2}>'.format( type(self).__name__, self.field, '+' if self.ascending else '-', diff --git a/beets/util/confit.py b/beets/util/confit.py index e017c7d54..301699864 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -129,10 +129,10 @@ class ConfigSource(dict): self.default = default def __repr__(self): - return 'ConfigSource({0}, {1}, {2})'.format( - super(ConfigSource, self).__repr__(), - repr(self.filename), - repr(self.default) + return 'ConfigSource({0!r}, {1!r}, {2!r})'.format( + super(ConfigSource, self), + self.filename, + self.default, ) @classmethod @@ -212,7 +212,7 @@ class ConfigView(object): raise NotImplementedError def __repr__(self): - return u'<{}: {}>'.format(self.__class__.__name__, self.name) + return '<{}: {}>'.format(self.__class__.__name__, self.name) def __iter__(self): """Iterate over the keys of a dictionary view or the *subviews* @@ -1018,7 +1018,7 @@ class Template(object): ) def __repr__(self): - return u'{0}({1})'.format( + return '{0}({1})'.format( type(self).__name__, '' if self.default is REQUIRED else repr(self.default), ) diff --git a/test/_common.py b/test/_common.py index 5b179ed7e..e3b006e14 100644 --- a/test/_common.py +++ b/test/_common.py @@ -225,9 +225,9 @@ class InputException(Exception): self.output = output def __str__(self): - msg = u"Attempt to read with no input provided." + msg = "Attempt to read with no input provided." if self.output is not None: - msg += u" Output: %s" % self.output + msg += " Output: {!r}".format(self.output) return msg From d53019f9db883d2877c70422623cd64a95ba4840 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 14:48:10 -0800 Subject: [PATCH 0602/2280] Further whitespace fiddling Most commonly, this sticks with: log.debug( 'some long message here' ) instead of placing the closing ) at the end of the string literal. --- beets/library.py | 4 ++- beets/ui/__init__.py | 5 +++- beetsplug/duplicates.py | 43 +++++++++++++++++---------------- beetsplug/embedart.py | 15 ++++++++---- beetsplug/embyupdate.py | 3 ++- beetsplug/fetchart.py | 9 ++++--- beetsplug/info.py | 12 ++++++--- beetsplug/lastgenre/__init__.py | 12 ++++++--- beetsplug/lyrics.py | 6 +++-- beetsplug/mbcollection.py | 3 ++- beetsplug/replaygain.py | 30 +++++++++++++++-------- beetsplug/smartplaylist.py | 8 +++--- 12 files changed, 94 insertions(+), 56 deletions(-) diff --git a/beets/library.py b/beets/library.py index 901c3c1b0..a90ec7607 100644 --- a/beets/library.py +++ b/beets/library.py @@ -828,7 +828,9 @@ class Item(LibModel): log.warning( u'Fell back to default replacements when naming ' u'file {}. Configure replacements to avoid lengthening ' - u'the filename.', subpath) + u'the filename.', + subpath + ) if fragment: return subpath diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 12f12738a..24163e459 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1144,7 +1144,10 @@ def _configure(options): 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)) + u'See changelog & documentation.', + old_key, + new_key, + ) config[new_key].set(config[old_key]) config_path = config.user_config_path() diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index b3ee90742..c63d7ffba 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -56,54 +56,54 @@ class DuplicatesPlugin(BeetsPlugin): self._command.parser.add_option( u'-c', u'--count', dest='count', action='store_true', - help=u'show duplicate counts') - + help=u'show duplicate counts', + ) self._command.parser.add_option( u'-C', u'--checksum', dest='checksum', action='store', metavar='PROG', - help=u'report duplicates based on arbitrary command') - + help=u'report duplicates based on arbitrary command', + ) self._command.parser.add_option( u'-d', u'--delete', dest='delete', action='store_true', - help=u'delete items from library and disk') - + help=u'delete items from library and disk', + ) self._command.parser.add_option( u'-F', u'--full', dest='full', action='store_true', - help=u'show all versions of duplicate tracks or albums') - + help=u'show all versions of duplicate tracks or albums', + ) self._command.parser.add_option( u'-s', u'--strict', dest='strict', action='store_true', - help=u'report duplicates only if all attributes are set') - + help=u'report duplicates only if all attributes are set', + ) self._command.parser.add_option( u'-k', u'--keys', dest='keys', action='callback', metavar='KEY1 KEY2', callback=vararg_callback, - help=u'report duplicates based on keys') - + help=u'report duplicates based on keys', + ) self._command.parser.add_option( u'-M', u'--merge', dest='merge', action='store_true', - help=u'merge duplicate items') - + help=u'merge duplicate items', + ) self._command.parser.add_option( u'-m', u'--move', dest='move', action='store', metavar='DEST', - help=u'move items to dest') - + help=u'move items to dest', + ) self._command.parser.add_option( u'-o', u'--copy', dest='copy', action='store', metavar='DEST', - help=u'copy items to dest') - + help=u'copy items to dest', + ) self._command.parser.add_option( u'-t', u'--tag', dest='tag', action='store', - help=u'tag matched items with \'k=v\' attribute') - + help=u'tag matched items with \'k=v\' attribute', + ) self._command.parser.add_all_common_options() def commands(self): @@ -186,7 +186,8 @@ class DuplicatesPlugin(BeetsPlugin): k, v = tag.split('=') except: raise UserError( - u'%s: can\'t parse k=v tag: %s' % (PLUGIN, tag)) + u"{}: can't parse k=v tag: {}".format(PLUGIN, tag) + ) setattr(item, k, v) item.store() diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 07321ce2b..97ca1ba2c 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -85,16 +85,20 @@ class EmbedCoverArtPlugin(BeetsPlugin): # Extract command. extract_cmd = ui.Subcommand( 'extractart', - help=u'extract an image from file metadata') + help=u'extract an image from file metadata', + ) extract_cmd.parser.add_option( u'-o', dest='outpath', - help=u'image output file') + help=u'image output file', + ) extract_cmd.parser.add_option( u'-n', dest='filename', - help=u'image filename to create for all matched albums') + help=u'image filename to create for all matched albums', + ) extract_cmd.parser.add_option( '-a', dest='associate', action='store_true', - help='associate the extracted images with the album') + help='associate the extracted images with the album', + ) def extract_func(lib, opts, args): if opts.outpath: @@ -119,7 +123,8 @@ class EmbedCoverArtPlugin(BeetsPlugin): # Clear command. clear_cmd = ui.Subcommand( 'clearart', - help=u'remove images from file metadata') + help=u'remove images from file metadata', + ) def clear_func(lib, opts, args): art.clear(self._log, lib, decargs(args)) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index a4db3a3c7..29e00f8d2 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -119,7 +119,8 @@ class EmbyUpdate(BeetsPlugin): token = get_token(host, port, headers, auth_data) if not token: self._log.warning( - u'Could not get token for user {0}'.format(username)) + u'Could not get token for user {0}', username + ) return # Recreate headers with a token. diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 36496cc70..267ba8712 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -292,7 +292,8 @@ class Wikipedia(ArtSource): if ' .' in cover_filename and \ '.' not in cover_filename.split(' .')[-1]: self._log.debug( - u'wikipedia: dbpedia provided incomplete cover_filename') + u'wikipedia: dbpedia provided incomplete cover_filename' + ) lpart, rpart = cover_filename.rsplit(' .', 1) # Query all the images in the page @@ -320,7 +321,8 @@ class Wikipedia(ArtSource): break except (ValueError, KeyError): self._log.debug( - u'wikipedia: failed to retrieve a cover_filename') + u'wikipedia: failed to retrieve a cover_filename' + ) return # Find the absolute url of the cover art on Wikipedia @@ -493,7 +495,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): cmd.parser.add_option( u'-f', u'--force', dest='force', action='store_true', default=False, - help=u're-download art when already present') + help=u're-download art when already present' + ) def func(lib, opts, args): self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force) diff --git a/beetsplug/info.py b/beetsplug/info.py index 05fd3fe58..3e17152cc 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -144,17 +144,21 @@ class InfoPlugin(BeetsPlugin): cmd.func = self.run cmd.parser.add_option( u'-l', u'--library', action='store_true', - help=u'show library fields instead of tags') + help=u'show library fields instead of tags', + ) cmd.parser.add_option( u'-s', u'--summarize', action='store_true', - help=u'summarize the tags of all files') + help=u'summarize the tags of all files', + ) cmd.parser.add_option( u'-i', u'--include-keys', default=[], action='append', dest='included_keys', - help=u'comma separated list of keys to show') + help=u'comma separated list of keys to show', + ) cmd.parser.add_option( u'-k', u'--keys-only', action='store_true', - help=u'show only the keys') + help=u'show only the keys', + ) cmd.parser.add_format_option(target='item') return [cmd] diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 7faced0d4..202bc06ad 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -239,25 +239,29 @@ class LastGenrePlugin(plugins.BeetsPlugin): """Return the album genre for this Item or Album. """ return self._last_lookup( - u'album', LASTFM.get_album, obj.albumartist, obj.album) + u'album', LASTFM.get_album, obj.albumartist, obj.album + ) def fetch_album_artist_genre(self, obj): """Return the album artist genre for this Item or Album. """ return self._last_lookup( - u'artist', LASTFM.get_artist, obj.albumartist) + u'artist', LASTFM.get_artist, obj.albumartist + ) def fetch_artist_genre(self, item): """Returns the track artist genre for this Item. """ return self._last_lookup( - u'artist', LASTFM.get_artist, item.artist) + u'artist', LASTFM.get_artist, item.artist + ) def fetch_track_genre(self, obj): """Returns the track genre for this Item. """ return self._last_lookup( - u'track', LASTFM.get_track, obj.artist, obj.title) + u'track', LASTFM.get_track, obj.artist, obj.title + ) def _get_genre(self, obj): """Get the genre string for an Album or Item object based on diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 1b046c218..2c98044a1 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -578,11 +578,13 @@ class LyricsPlugin(plugins.BeetsPlugin): cmd.parser.add_option( u'-p', u'--print', dest='printlyr', action='store_true', default=False, - help=u'print lyrics to console') + help=u'print lyrics to console', + ) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, - help=u'always re-download lyrics') + help=u'always re-download lyrics', + ) def func(lib, opts, args): # The "write to files" option corresponds to the diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 8c1c6a47a..fb5af7dde 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -107,6 +107,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): # Submit to MusicBrainz. self._log.info( - u'Updating MusicBrainz collection {0}...', collection_id) + u'Updating MusicBrainz collection {0}...', collection_id + ) submit_albums(collection_id, album_ids) self._log.info(u'...MusicBrainz collection updated.') diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index f8b4eed93..cdb574d78 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -204,7 +204,8 @@ class Bs1770gainBackend(Backend): # Invoke the command. self._log.debug( - u'executing {0}', u' '.join(map(displayable_path, args))) + u'executing {0}', u' '.join(map(displayable_path, args)) + ) output = call(args) self._log.debug(u'analysis finished: {0}', output) @@ -274,7 +275,8 @@ class CommandBackend(Backend): pass if not self.command: raise FatalReplayGainError( - u'no replaygain command found: install mp3gain or aacgain') + u'no replaygain command found: install mp3gain or aacgain' + ) self.noclip = config['noclip'].get(bool) target_level = config['targetlevel'].as_number() @@ -395,7 +397,8 @@ class GStreamerBackend(Backend): if self._src is None or self._decbin is None or self._conv is None \ or self._res is None or self._rg is None: raise FatalGstreamerPluginReplayGainError( - u"Failed to load required GStreamer plugins") + u"Failed to load required GStreamer plugins" + ) # We check which files need gain ourselves, so all files given # to rganalsys should have their gain computed, even if it @@ -441,13 +444,15 @@ class GStreamerBackend(Backend): import gi except ImportError: raise FatalReplayGainError( - u"Failed to load GStreamer: python-gi not found") + u"Failed to load GStreamer: python-gi not found" + ) try: gi.require_version('Gst', '1.0') except ValueError as e: raise FatalReplayGainError( - u"Failed to load GStreamer 1.0: {0}".format(e)) + u"Failed to load GStreamer 1.0: {0}".format(e) + ) from gi.repository import GObject, Gst, GLib # Calling GObject.threads_init() is not needed for @@ -534,7 +539,8 @@ class GStreamerBackend(Backend): f = self._src.get_property("location") # A GStreamer error, either an unsupported format or a bug. self._error = ReplayGainError( - u"Error {0!r} - {1!r} on file {2!r}".format(err, debug, f)) + u"Error {0!r} - {1!r} on file {2!r}".format(err, debug, f) + ) def _on_tag(self, bus, message): tags = message.parse_tag() @@ -657,7 +663,8 @@ class AudioToolsBackend(Backend): import audiotools.replaygain except ImportError: raise FatalReplayGainError( - u"Failed to load audiotools: audiotools not found") + u"Failed to load audiotools: audiotools not found" + ) self._mod_audiotools = audiotools self._mod_replaygain = audiotools.replaygain @@ -674,10 +681,12 @@ class AudioToolsBackend(Backend): audiofile = self._mod_audiotools.open(item.path) except IOError: raise ReplayGainError( - u"File {} was not found".format(item.path)) + u"File {} was not found".format(item.path) + ) except self._mod_audiotools.UnsupportedFile: raise ReplayGainError( - u"Unsupported file type {}".format(item.format)) + u"Unsupported file type {}".format(item.format) + ) return audiofile @@ -902,7 +911,8 @@ class ReplayGainPlugin(BeetsPlugin): track_gains = self.backend_instance.compute_track_gain([item]) if len(track_gains) != 1: raise ReplayGainError( - u"ReplayGain backend failed for track {0}".format(item)) + u"ReplayGain backend failed for track {0}".format(item) + ) self.store_track_gain(item, track_gains[0]) if write: diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index ff1edf0db..fd69835bc 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -47,8 +47,9 @@ class SmartPlaylistPlugin(BeetsPlugin): def commands(self): spl_update = ui.Subcommand( 'splupdate', - help=u'update the smart playlists. Playlist ' - u'names may be passed as arguments.') + help=u'update the smart playlists. Playlist names may be ' + u'passed as arguments.' + ) spl_update.func = self.update_cmd return [spl_update] @@ -66,7 +67,8 @@ class SmartPlaylistPlugin(BeetsPlugin): if not playlists: raise ui.UserError( u'No playlist matching any of {0} found'.format( - [name for name, _, _ in self._unmatched_playlists])) + [name for name, _, _ in self._unmatched_playlists]) + ) self._matched_playlists = playlists self._unmatched_playlists -= playlists From e54c7eec3da8ecc240bbe13339e684cba058876a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 15:03:51 -0800 Subject: [PATCH 0603/2280] Standardize __future__ imports without parentheses Since the list is short enough now, we don't need parentheses for the line wrap. This is a little less ugly. --- beets/__init__.py | 2 +- beets/autotag/__init__.py | 2 +- beets/autotag/hooks.py | 2 +- beets/autotag/match.py | 2 +- beets/autotag/mb.py | 2 +- beets/dbcore/__init__.py | 2 +- beets/dbcore/db.py | 2 +- beets/dbcore/query.py | 2 +- beets/dbcore/types.py | 2 +- beets/importer.py | 2 +- beets/library.py | 2 +- beets/logging.py | 2 +- beets/mediafile.py | 2 +- beets/plugins.py | 2 +- beets/ui/__init__.py | 2 +- beets/ui/commands.py | 2 +- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 2 +- beets/util/bluelet.py | 2 +- beets/util/confit.py | 2 +- beets/util/enumeration.py | 2 +- beets/util/functemplate.py | 2 +- beets/util/pipeline.py | 2 +- beets/vfs.py | 2 +- beetsplug/__init__.py | 4 ++-- beetsplug/acousticbrainz.py | 2 +- beetsplug/badfiles.py | 2 +- beetsplug/bpd/__init__.py | 2 +- beetsplug/bpd/gstplayer.py | 2 +- beetsplug/bpm.py | 2 +- beetsplug/bucket.py | 2 +- beetsplug/chroma.py | 2 +- beetsplug/convert.py | 2 +- beetsplug/discogs.py | 2 +- beetsplug/duplicates.py | 2 +- beetsplug/echonest.py | 2 +- beetsplug/edit.py | 2 +- beetsplug/embedart.py | 2 +- beetsplug/embyupdate.py | 2 +- beetsplug/fetchart.py | 2 +- beetsplug/freedesktop.py | 2 +- beetsplug/fromfilename.py | 2 +- beetsplug/ftintitle.py | 2 +- beetsplug/fuzzy.py | 2 +- beetsplug/ihate.py | 2 +- beetsplug/importadded.py | 2 +- beetsplug/importfeeds.py | 2 +- beetsplug/info.py | 2 +- beetsplug/inline.py | 2 +- beetsplug/keyfinder.py | 2 +- beetsplug/lastgenre/__init__.py | 2 +- beetsplug/lastimport.py | 2 +- beetsplug/lyrics.py | 2 +- beetsplug/mbcollection.py | 2 +- beetsplug/mbsubmit.py | 2 +- beetsplug/mbsync.py | 2 +- beetsplug/missing.py | 2 +- beetsplug/mpdstats.py | 2 +- beetsplug/mpdupdate.py | 2 +- beetsplug/permissions.py | 2 +- beetsplug/play.py | 2 +- beetsplug/plexupdate.py | 2 +- beetsplug/random.py | 2 +- beetsplug/replaygain.py | 2 +- beetsplug/rewrite.py | 2 +- beetsplug/scrub.py | 2 +- beetsplug/smartplaylist.py | 2 +- beetsplug/spotify.py | 2 +- beetsplug/the.py | 2 +- beetsplug/thumbnails.py | 2 +- beetsplug/types.py | 2 +- beetsplug/web/__init__.py | 2 +- beetsplug/zero.py | 2 +- test/_common.py | 2 +- test/helper.py | 2 +- test/lyrics_download_samples.py | 2 +- test/rsrc/beetsplug/test.py | 2 +- test/test_art.py | 2 +- test/test_autotag.py | 2 +- test/test_bucket.py | 2 +- test/test_config_command.py | 2 +- test/test_convert.py | 2 +- test/test_datequery.py | 2 +- test/test_dbcore.py | 2 +- test/test_echonest.py | 2 +- test/test_edit.py | 2 +- test/test_embedart.py | 2 +- test/test_embyupdate.py | 2 +- test/test_fetchart.py | 2 +- test/test_files.py | 2 +- test/test_ftintitle.py | 2 +- test/test_ihate.py | 2 +- test/test_importadded.py | 2 +- test/test_importer.py | 2 +- test/test_importfeeds.py | 2 +- test/test_info.py | 2 +- test/test_keyfinder.py | 2 +- test/test_lastgenre.py | 2 +- test/test_library.py | 2 +- test/test_logging.py | 2 +- test/test_lyrics.py | 2 +- test/test_mb.py | 2 +- test/test_mbsubmit.py | 2 +- test/test_mbsync.py | 2 +- test/test_mediafile.py | 2 +- test/test_mediafile_edge.py | 2 +- test/test_mpdstats.py | 2 +- test/test_permissions.py | 2 +- test/test_pipeline.py | 2 +- test/test_play.py | 2 +- test/test_player.py | 2 +- test/test_plexupdate.py | 2 +- test/test_plugins.py | 2 +- test/test_query.py | 2 +- test/test_replaygain.py | 2 +- test/test_smartplaylist.py | 2 +- test/test_sort.py | 2 +- test/test_spotify.py | 2 +- test/test_template.py | 2 +- test/test_the.py | 2 +- test/test_thumbnails.py | 2 +- test/test_types_plugin.py | 2 +- test/test_ui.py | 2 +- test/test_ui_importer.py | 2 +- test/test_util.py | 2 +- test/test_vfs.py | 2 +- test/test_web.py | 2 +- test/test_zero.py | 2 +- test/testall.py | 2 +- 129 files changed, 130 insertions(+), 130 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 1f75209a1..7463d16e0 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import +from __future__ import division, absolute_import, print_function import os diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 17885a817..f8233be61 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -16,7 +16,7 @@ """Facilities for automatically determining files' correct metadata. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets import logging from beets import config diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 642c0cb4b..26b7f5819 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """Glue between metadata sources and the matching logic.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from collections import namedtuple import re diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 230e26e52..e16b0dfaa 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -17,7 +17,7 @@ releases and tracks. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import datetime import re diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 33bf9b8a7..e64da8d5c 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -15,7 +15,7 @@ """Searches for albums in the MusicBrainz database. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import musicbrainzngs import re diff --git a/beets/dbcore/__init__.py b/beets/dbcore/__init__.py index 78b53c192..689e7202c 100644 --- a/beets/dbcore/__init__.py +++ b/beets/dbcore/__init__.py @@ -16,7 +16,7 @@ """DBCore is an abstract database package that forms the basis for beets' Library. """ -from __future__ import absolute_import +from __future__ import division, absolute_import, print_function from .db import Model, Database from .query import Query, FieldQuery, MatchQuery, AndQuery, OrQuery diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 2a2709240..09a96d8c2 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -15,7 +15,7 @@ """The central Model and Database constructs for DBCore. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import time import os diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 7c6fc077d..8e3b7ca16 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -15,7 +15,7 @@ """The Query type hierarchy for DBCore. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re from operator import mul diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index acda2c3a2..2726969dd 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -15,7 +15,7 @@ """Representation of type information for DBCore model fields. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from . import query from beets.util import str2bool diff --git a/beets/importer.py b/beets/importer.py index da51ac2a5..724ed67b9 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Provides the basic, interface-agnostic workflow for importing and autotagging music files. diff --git a/beets/library.py b/beets/library.py index a90ec7607..f2c3875b0 100644 --- a/beets/library.py +++ b/beets/library.py @@ -15,7 +15,7 @@ """The core data store and collection logic for beets. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import sys diff --git a/beets/logging.py b/beets/logging.py index fc49cace7..e4e628d69 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -21,7 +21,7 @@ that when getLogger(name) instantiates a logger that logger uses {}-style formatting. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from copy import copy from logging import * # noqa diff --git a/beets/mediafile.py b/beets/mediafile.py index 79223e70f..5305ef057 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -33,7 +33,7 @@ Internally ``MediaFile`` uses ``MediaField`` descriptors to access the data from the tags. In turn ``MediaField`` uses a number of ``StorageStyle`` strategies to handle format specific logic. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import mutagen import mutagen.mp3 diff --git a/beets/plugins.py b/beets/plugins.py index b78b8fe59..ebc37796c 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -15,7 +15,7 @@ """Support for beets plugins.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import inspect import traceback diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 24163e459..e5f4f78b7 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -18,7 +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) +from __future__ import division, absolute_import, print_function import locale import optparse diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 869702e4a..59b5b46c7 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -17,7 +17,7 @@ interface. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import re diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 2a078380c..4d46aecd2 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -15,7 +15,7 @@ """Miscellaneous utility functions.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import sys import re diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 0fd4253d7..9d2ee5952 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -16,7 +16,7 @@ """Abstraction layer to resize images using PIL, ImageMagick, or a public resizing proxy if neither is available. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import urllib import subprocess diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index 96ae6f686..d81c2919a 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -7,7 +7,7 @@ asyncore. Bluelet: easy concurrency without all the messy parallelism. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import socket import select diff --git a/beets/util/confit.py b/beets/util/confit.py index 301699864..0b29928c8 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -15,7 +15,7 @@ """Worry-free YAML configuration files. """ -from __future__ import (absolute_import, print_function, division) +from __future__ import division, absolute_import, print_function import platform import os diff --git a/beets/util/enumeration.py b/beets/util/enumeration.py index eb202b6d4..3e9467185 100644 --- a/beets/util/enumeration.py +++ b/beets/util/enumeration.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from enum import Enum diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 303338b4c..5764807c3 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -27,7 +27,7 @@ This is sort of like a tiny, horrible degeneration of a real templating engine like Jinja2 or Mustache. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re import ast diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 666909af2..9b134d1e7 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -32,7 +32,7 @@ To do so, pass an iterable of coroutines to the Pipeline constructor in place of any single coroutine. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import Queue from threading import Thread, Lock diff --git a/beets/vfs.py b/beets/vfs.py index 75529c999..7f9a049ee 100644 --- a/beets/vfs.py +++ b/beets/vfs.py @@ -16,7 +16,7 @@ """A simple utility for constructing filesystem-like trees from beets libraries. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from collections import namedtuple from beets import util diff --git a/beetsplug/__init__.py b/beetsplug/__init__.py index ea5e7fe40..febeb66f4 100644 --- a/beetsplug/__init__.py +++ b/beetsplug/__init__.py @@ -15,8 +15,8 @@ """A namespace package for beets plugins.""" -# Make this a namespace package. -from __future__ import absolute_import +from __future__ import division, absolute_import, print_function +# Make this a namespace package. from pkgutil import extend_path __path__ = extend_path(__path__, __name__) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index d4b5aa9b4..6acea8140 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -15,7 +15,7 @@ """Fetch various AcousticBrainz metadata using MBID. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import requests import operator diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 43df51cce..f9704d484 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -16,7 +16,7 @@ """Use command-line tools to check for audio file corruption. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index a475cf178..33deda02c 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -18,7 +18,7 @@ Beets library. Attempts to implement a compatible protocol to allow use of the wide range of MPD clients. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re from string import Template diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index e430f88ff..70d0613d5 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -17,7 +17,7 @@ music player. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import sys import time diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index 65ebc0712..ba284c042 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -15,7 +15,7 @@ """Determine BPM by pressing a key to the rhythm.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import time diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index b847cf03c..cfd4106d4 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -16,7 +16,7 @@ """Provides the %bucket{} function for path formatting. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from datetime import datetime import re diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index e40b2d29f..148e9c20c 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -16,7 +16,7 @@ """Adds Chromaprint/Acoustid acoustic fingerprinting support to the autotagger. Requires the pyacoustid library. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets import plugins from beets import ui diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 0329f2a52..c852b13ef 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -15,7 +15,7 @@ """Converts tracks or albums to external directory """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import threading diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 26c567a2c..62a78a5ff 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -16,7 +16,7 @@ """Adds Discogs album search support to the autotagger. Requires the discogs-client library. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import beets.ui from beets import logging diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index c63d7ffba..4f0397171 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -15,7 +15,7 @@ """List duplicate tracks or albums. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import shlex diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py index f758b5862..a979972d8 100644 --- a/beetsplug/echonest.py +++ b/beetsplug/echonest.py @@ -15,7 +15,7 @@ """Fetch a variety of acoustic metrics from The Echo Nest. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import time import socket diff --git a/beetsplug/edit.py b/beetsplug/edit.py index d0e31d478..d4b17ff66 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -14,7 +14,7 @@ """Open metadata information in a text editor to let the user edit it. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets import plugins from beets import util diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 97ca1ba2c..71b05f370 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """Allows beets to embed album art into file metadata.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os.path diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 29e00f8d2..38f8929e5 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -8,7 +8,7 @@ username: user password: password """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets import config from beets.plugins import BeetsPlugin diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 267ba8712..ad51bb995 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -15,7 +15,7 @@ """Fetches album art. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from contextlib import closing import os diff --git a/beetsplug/freedesktop.py b/beetsplug/freedesktop.py index c12fa3479..a768be2d8 100644 --- a/beetsplug/freedesktop.py +++ b/beetsplug/freedesktop.py @@ -16,7 +16,7 @@ """Creates freedesktop.org-compliant .directory files on an album level. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index 71e7ce3f2..e9c49bee3 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -16,7 +16,7 @@ """If the title is empty, try to extract track and title from the filename. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets import plugins from beets.util import displayable_path diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 2bdf5a90b..eefdfcf15 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -15,7 +15,7 @@ """Moves "featured" artists to the title from the artist field. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index f2c9095b2..4a631a887 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -16,7 +16,7 @@ """Provides a fuzzy matching query. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.dbcore.query import StringFieldQuery diff --git a/beetsplug/ihate.py b/beetsplug/ihate.py index c6e62fe29..6ed250fe4 100644 --- a/beetsplug/ihate.py +++ b/beetsplug/ihate.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Warns you about things you hate (or even blocks import).""" diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 833f2f21c..1202e95de 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -5,7 +5,7 @@ modification time (mtime) of the item's source file before import. Reimported albums and items are skipped. """ -from __future__ import (absolute_import, print_function, division) +from __future__ import division, absolute_import, print_function import os diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 8bdabc632..d046ddc47 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """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 diff --git a/beetsplug/info.py b/beetsplug/info.py index 3e17152cc..29bff7a29 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -16,7 +16,7 @@ """Shows file metadata. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import re diff --git a/beetsplug/inline.py b/beetsplug/inline.py index 8e22ad9c8..6e3771f2a 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -15,7 +15,7 @@ """Allows inline path template customization code in the config file. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import traceback import itertools diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index cc96cb886..b6131a4b0 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -16,7 +16,7 @@ """Uses the `KeyFinder` program to add the `initial_key` field. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import subprocess diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 202bc06ad..ad051c45c 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Gets genres for imported music based on Last.fm tags. diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 763a24a8c..39274f6c4 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import pylast from pylast import TopItem, _extract, _number diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 2c98044a1..66b859f59 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -16,7 +16,7 @@ """Fetches, embeds, and displays lyrics. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re import requests diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index fb5af7dde..21944154e 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -13,7 +13,7 @@ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 99ae7302c..91de6128e 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -22,7 +22,7 @@ implemented by MusicBrainz yet. [1] http://wiki.musicbrainz.org/History:How_To_Parse_Track_Listings """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.autotag import Recommendation diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 0d7669c0d..56513353a 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -15,7 +15,7 @@ """Update library's tags using MusicBrainz. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import autotag, library, ui, util diff --git a/beetsplug/missing.py b/beetsplug/missing.py index d33843489..8fff659fe 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -15,7 +15,7 @@ """List missing tracks. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.autotag import hooks from beets.library import Item diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index a2ade3186..2b6422942 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import mpd import socket diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 70fb4c749..f828ba5d7 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -21,7 +21,7 @@ Put something like the following in your config.yaml to configure: port: 6600 password: seekrit """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin import os diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 1099aad51..0de8978c0 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Fixes file permissions after the file gets written on import. Put something like the following in your config.yaml to configure: diff --git a/beetsplug/play.py b/beetsplug/play.py index 0faac7e42..fa70f2bc0 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -15,7 +15,7 @@ """Send the results of a query to the configured music player as a playlist. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 30afe1b08..ef50fde73 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -9,7 +9,7 @@ Put something like the following in your config.yaml to configure: port: 32400 token: token """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import requests from urlparse import urljoin diff --git a/beetsplug/random.py b/beetsplug/random.py index e94d7841c..e1c6fea4a 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -15,7 +15,7 @@ """Get a random song or album from the library. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs, print_ diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index cdb574d78..23b1d2c1c 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import subprocess import os diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index cba297cc4..b0104a118 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -16,7 +16,7 @@ """Uses user-specified rewriting rules to canonicalize names for path formats. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re from collections import defaultdict diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 3556de8c8..1c842f234 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -17,7 +17,7 @@ automatically whenever tags are written. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index fd69835bc..f6d7f7157 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -16,7 +16,7 @@ """Generates smart playlists based on beets queries. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 9564582fa..081a027f2 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re import webbrowser diff --git a/beetsplug/the.py b/beetsplug/the.py index 5d9c958f2..6bed4c6ed 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -15,7 +15,7 @@ """Moves patterns in path formats (suitable for moving articles).""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re from beets.plugins import BeetsPlugin diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index c9b484d5a..da4a4027b 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -19,7 +19,7 @@ This plugin is POSIX-only. Spec: standards.freedesktop.org/thumbnail-spec/latest/index.html """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from hashlib import md5 import os diff --git a/beetsplug/types.py b/beetsplug/types.py index 40e504f27..0c078881c 100644 --- a/beetsplug/types.py +++ b/beetsplug/types.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.dbcore import types diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 6136e3ad3..ede4658a2 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """A Web interface to beets.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 5623aa3df..d20f76166 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -15,7 +15,7 @@ """ Clears tag fields in media files.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re from beets.plugins import BeetsPlugin diff --git a/test/_common.py b/test/_common.py index e3b006e14..c64ff0b71 100644 --- a/test/_common.py +++ b/test/_common.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """Some common functionality for beets' test cases.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import time import sys diff --git a/test/helper.py b/test/helper.py index 9721e7b4c..0f708b640 100644 --- a/test/helper.py +++ b/test/helper.py @@ -31,7 +31,7 @@ information or mock the environment. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import sys import os diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index fcc5a4db5..280f076a2 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import sys diff --git a/test/rsrc/beetsplug/test.py b/test/rsrc/beetsplug/test.py index 669072987..6dedd0e33 100644 --- a/test/rsrc/beetsplug/test.py +++ b/test/rsrc/beetsplug/test.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui diff --git a/test/test_art.py b/test/test_art.py index e1c22ad19..ebfcd53f4 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -15,7 +15,7 @@ """Tests for the album art fetchers.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_autotag.py b/test/test_autotag.py index f5f13d4a7..30d60f8c4 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -15,7 +15,7 @@ """Tests for autotagging functionality. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re import copy diff --git a/test/test_bucket.py b/test/test_bucket.py index bb0be5bee..395d2a546 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -15,7 +15,7 @@ """Tests for the 'bucket' plugin.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from beetsplug import bucket diff --git a/test/test_config_command.py b/test/test_config_command.py index 8c5034757..f00594b80 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import yaml diff --git a/test/test_convert.py b/test/test_convert.py index 3c91e40b2..20ed6c743 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import re import os.path diff --git a/test/test_datequery.py b/test/test_datequery.py index 1c0214860..6c9818b77 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -15,7 +15,7 @@ """Test for dbcore's date-based queries. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test import _common from test._common import unittest diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 0a2537337..0098dc375 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -15,7 +15,7 @@ """Tests for the DBCore database abstraction. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_echonest.py b/test/test_echonest.py index a365af8ac..f19b901d6 100644 --- a/test/test_echonest.py +++ b/test/test_echonest.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os.path from mock import Mock, patch diff --git a/test/test_edit.py b/test/test_edit.py index 1d007b285..d21b04936 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -12,7 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import codecs from mock import patch diff --git a/test/test_embedart.py b/test/test_embedart.py index 104779810..145593829 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os.path import shutil diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index 54e67526b..3928ae390 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper diff --git a/test/test_fetchart.py b/test/test_fetchart.py index 6a313b965..065905a87 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os from test._common import unittest diff --git a/test/test_files.py b/test/test_files.py index a9ee239bc..e3e4857c9 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -15,7 +15,7 @@ """Test file manipulation functionality of Item. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import shutil import os diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index caecdfd27..b8fa90681 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -15,7 +15,7 @@ """Tests for the 'ftintitle' plugin.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper diff --git a/test/test_ihate.py b/test/test_ihate.py index 663e93d2c..6567d13be 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -2,7 +2,7 @@ """Tests for the 'ihate' plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from beets import importer diff --git a/test/test_importadded.py b/test/test_importadded.py index 1dcddbc75..9fa30f523 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Tests for the `importadded` plugin.""" diff --git a/test/test_importer.py b/test/test_importer.py index 7e85b041b..d1ef6ef18 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function """Tests for the general importer functionality. """ diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index 4ae460c68..df293ce63 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import os.path diff --git a/test/test_info.py b/test/test_info.py index fe11cff51..77f88e7c4 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index a9c2e85d5..90d65bd26 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from mock import patch from test._common import unittest diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index c9aec1fd5..82396f7c7 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -15,7 +15,7 @@ """Tests for the 'lastgenre' plugin.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from mock import Mock diff --git a/test/test_library.py b/test/test_library.py index fa11e5d53..d57566f5f 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -15,7 +15,7 @@ """Tests for non-query database functions of Item. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import os.path diff --git a/test/test_logging.py b/test/test_logging.py index 2c2f473c2..4cf6d1ccc 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """Stupid tests that ensure logging works as expected""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import sys import threading diff --git a/test/test_lyrics.py b/test/test_lyrics.py index e6e068a4b..2658232ae 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -15,7 +15,7 @@ """Tests for the 'lyrics' plugin.""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os from test import _common diff --git a/test/test_mb.py b/test/test_mb.py index f8697cefa..5333b2b8c 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -15,7 +15,7 @@ """Tests for MusicBrainz API wrapper. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test import _common from test._common import unittest diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index d11bdf020..e89ba2748 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import capture_stdout, control_stdin, TestHelper diff --git a/test/test_mbsync.py b/test/test_mbsync.py index bb231d6d2..14d349a8f 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from mock import patch diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 94085210d..71fd796bd 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -16,7 +16,7 @@ """Automatically-generated blanket testing for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 80b923a91..84606e623 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -15,7 +15,7 @@ """Specific, edge-case tests for the MediaFile metadata layer. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index 4317e9824..0fa800dfd 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from mock import Mock, patch, call, ANY from test._common import unittest diff --git a/test/test_permissions.py b/test/test_permissions.py index de4b8577b..6dcf4d01c 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -2,7 +2,7 @@ """Tests for the 'permissions' plugin. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os from mock import patch, Mock diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 7da8737a4..2f5395fb5 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -15,7 +15,7 @@ """Test the "pipeline.py" restricted parallel programming library. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from beets.util import pipeline diff --git a/test/test_play.py b/test/test_play.py index 1405204e2..a0f3a6e48 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -15,7 +15,7 @@ """Tests for the play plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os diff --git a/test/test_player.py b/test/test_player.py index a25d8b8ae..7898fab68 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -15,7 +15,7 @@ """Tests for BPD and music playing. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from beetsplug import bpd diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index 36410d1e4..a6c8741b3 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper diff --git a/test/test_plugins.py b/test/test_plugins.py index bd05d5e85..ea1756852 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os from mock import patch, Mock, ANY diff --git a/test/test_query.py b/test/test_query.py index 361d52fbc..080f7d384 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -15,7 +15,7 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from functools import partial from mock import patch diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 11cedeecb..d0ceaf709 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper, has_program diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 40992c0fd..c30ba24d0 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from os import path, remove from tempfile import mkdtemp diff --git a/test/test_sort.py b/test/test_sort.py index 7dadbcf79..daaca262a 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -15,7 +15,7 @@ """Various tests for querying the library database. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test import _common from test._common import unittest diff --git a/test/test_spotify.py b/test/test_spotify.py index 9fa64733c..6f218c339 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -2,7 +2,7 @@ """Tests for the 'spotify' plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test import _common import responses diff --git a/test/test_template.py b/test/test_template.py index 0f2273dd2..efc900034 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -15,7 +15,7 @@ """Tests for template engine. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import warnings diff --git a/test/test_the.py b/test/test_the.py index d63faad57..3d5c722be 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -2,7 +2,7 @@ """Tests for the 'the' plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test import _common diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index d0fbe02ae..5dd9551b7 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os.path from mock import Mock, patch, call diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 92cab3397..7af1a8d72 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import time from datetime import datetime diff --git a/test/test_ui.py b/test/test_ui.py index d9a7da86f..fdc16aff9 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -15,7 +15,7 @@ """Tests for the command-line interface. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 3248b25a3..7dbf1f533 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -19,7 +19,7 @@ test_importer module. But here the test importer inherits from ``TerminalImportSession``. So we test this class, too. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest, DummyIO from test import test_importer diff --git a/test/test_util.py b/test/test_util.py index c7b15650b..f6c42a2da 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """Tests for base utils from the beets.util package. """ -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import sys import re diff --git a/test/test_vfs.py b/test/test_vfs.py index d9536b9d5..6ffaa859d 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -14,7 +14,7 @@ # included in all copies or substantial portions of the Software. """Tests for the virtual filesystem builder..""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test import _common from test._common import unittest diff --git a/test/test_web.py b/test/test_web.py index 2bf1b4ab5..51f32567d 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -2,7 +2,7 @@ """Tests for the 'web' plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test import _common diff --git a/test/test_zero.py b/test/test_zero.py index 78290b6ba..e223dd787 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -2,7 +2,7 @@ """Tests for the 'zero' plugin""" -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function from test._common import unittest from test.helper import TestHelper diff --git a/test/testall.py b/test/testall.py index e8e1d909d..68475e379 100755 --- a/test/testall.py +++ b/test/testall.py @@ -15,7 +15,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function) +from __future__ import division, absolute_import, print_function import os import re From 4d40b058d36c14b6fc54a7ad0cd7a1a3a8834bda Mon Sep 17 00:00:00 2001 From: Ivan Shapovalov Date: Sun, 6 Mar 2016 02:12:43 +0300 Subject: [PATCH 0604/2280] treewide: add `u` to instances of 'singleton:true' Fixes #1901. --- beets/ui/__init__.py | 4 ++-- beetsplug/mbsync.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 8daefa12a..ac919d7d2 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -59,8 +59,8 @@ log.propagate = False # Don't propagate to root handler. PF_KEY_QUERIES = { - 'comp': 'comp:true', - 'singleton': 'singleton:true', + 'comp': u'comp:true', + 'singleton': u'singleton:true', } diff --git a/beetsplug/mbsync.py b/beetsplug/mbsync.py index 56513353a..cf58c82d5 100644 --- a/beetsplug/mbsync.py +++ b/beetsplug/mbsync.py @@ -75,7 +75,7 @@ class MBSyncPlugin(BeetsPlugin): """Retrieve and apply info from the autotagger for items matched by query. """ - for item in lib.items(query + ['singleton:true']): + for item in lib.items(query + [u'singleton:true']): item_formatted = format(item) if not item.mb_trackid: self._log.info(u'Skipping singleton with no mb_trackid: {0}', From c18b5dbadd40735e564cbb83b1671caf167030b6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 11 Mar 2016 16:50:32 -0500 Subject: [PATCH 0605/2280] Fix #1907: redact MusicBrainz password --- beetsplug/mbcollection.py | 1 + docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 21944154e..b95ba6fed 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -55,6 +55,7 @@ def submit_albums(collection_id, release_ids): class MusicBrainzCollectionPlugin(BeetsPlugin): def __init__(self): super(MusicBrainzCollectionPlugin, self).__init__() + config['musicbrainz']['pass'].redact = True musicbrainzngs.auth( config['musicbrainz']['user'].get(unicode), config['musicbrainz']['pass'].get(unicode), diff --git a/docs/changelog.rst b/docs/changelog.rst index a2c19dcab..4063b0fa4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,8 @@ Fixes: * Fix a problem with the :ref:`stats-cmd` in exact mode when filenames on Windows use non-ASCII characters. :bug:`1891` * Fix a crash when iTunes Sound Check tags contained invalid data. :bug:`1895` +* :doc:`/plugins/mbcollection`: The plugin now redacts your MusicBrainz + password in the ``beet config`` output. :bug:`1907` 1.3.17 (February 7, 2016) From 8a0b18c9608755e7640856eeab75c5b687921c36 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 15 Mar 2016 23:06:10 -0400 Subject: [PATCH 0606/2280] Fix #1903: scrub sometimes ignored id3v23 --- beetsplug/scrub.py | 3 ++- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 1c842f234..66815ee31 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -133,7 +133,8 @@ class ScrubPlugin(BeetsPlugin): item.try_write() if art: self._log.debug(u'restoring art') - mf = mediafile.MediaFile(util.syspath(item.path)) + mf = mediafile.MediaFile(util.syspath(item.path), + config['id3v23'].get(bool)) mf.art = art mf.save() diff --git a/docs/changelog.rst b/docs/changelog.rst index 4063b0fa4..22d2c7226 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,6 +16,8 @@ Fixes: * Fix a crash when iTunes Sound Check tags contained invalid data. :bug:`1895` * :doc:`/plugins/mbcollection`: The plugin now redacts your MusicBrainz password in the ``beet config`` output. :bug:`1907` +* :doc:`/plugins/scrub`: Fix an occasional problem where scrubbing on import + could undo the ``id3v23`` setting. :bug:`1903` 1.3.17 (February 7, 2016) From 44c799320fcf1e3d10fd4368db776fa786f0cb1d Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 16 Mar 2016 20:46:25 +0000 Subject: [PATCH 0607/2280] Improve URL generation in lyrics plugin Allow custom replacements to be defined in subclasses of SymbolsReplaced. Replace spaces with a hyphens when the source is MusiXmatch, instead of (incorrectly) using underscores. This fixes #1880. --- beetsplug/lyrics.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 66b859f59..c7ce64584 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -200,18 +200,27 @@ class Backend(object): class SymbolsReplaced(Backend): + REPLACEMENTS = { + r'\s+': '_', + '<': 'Less_Than', + '>': 'Greater_Than', + '#': 'Number_', + r'[\[\{]': '(', + r'[\[\{]': ')' + } + @classmethod def _encode(cls, s): - s = re.sub(r'\s+', '_', s) - s = s.replace("<", "Less_Than") - s = s.replace(">", "Greater_Than") - s = s.replace("#", "Number_") - s = re.sub(r'[\[\{]', '(', s) - s = re.sub(r'[\]\}]', ')', s) + for old, new in cls.REPLACEMENTS.iteritems(): + s = re.sub(old, new, s) + return super(SymbolsReplaced, cls)._encode(s) - class MusiXmatch(SymbolsReplaced): + REPLACEMENTS = dict(SymbolsReplaced.REPLACEMENTS, **{ + r'\s+': '-' + }) + URL_PATTERN = 'https://www.musixmatch.com/lyrics/%s/%s' def fetch(self, artist, title): From 1ec06e14c52ea883f2aa770c4d99a16de66d1aeb Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 16 Mar 2016 20:48:57 +0000 Subject: [PATCH 0608/2280] Fix lyrics extraction from MusiXmatch Remove "lyrics_" prefix from extract_text_between arguments to reflect changes made to the MusiXmatch website. --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c7ce64584..c921081e7 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -229,7 +229,7 @@ class MusiXmatch(SymbolsReplaced): if not html: return lyrics = extract_text_between(html, - '"lyrics_body":', '"lyrics_language":') + '"body":', '"language":') return lyrics.strip(',"').replace('\\n', '\n') From c41700318464fc7621f5fc72edded7978fac016e Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 16 Mar 2016 21:07:28 +0000 Subject: [PATCH 0609/2280] Add missing newline --- beetsplug/lyrics.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c921081e7..37cbb9739 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -216,6 +216,7 @@ class SymbolsReplaced(Backend): return super(SymbolsReplaced, cls)._encode(s) + class MusiXmatch(SymbolsReplaced): REPLACEMENTS = dict(SymbolsReplaced.REPLACEMENTS, **{ r'\s+': '-' From 0689279e6733942fee4780a04f81976858d21782 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 17 Mar 2016 14:49:01 +0000 Subject: [PATCH 0610/2280] Update changelog to reflect changes to lyrics plugin --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 22d2c7226..79425ad24 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,8 @@ Fixes: password in the ``beet config`` output. :bug:`1907` * :doc:`/plugins/scrub`: Fix an occasional problem where scrubbing on import could undo the ``id3v23`` setting. :bug:`1903` +* :doc:`/plugins/lyrics`: Fix lyric retrieval for MusixMatch and improve URL + generation. :bug:`1880` 1.3.17 (February 7, 2016) From 60148918d9bc63405e90504f05aa4aeee9d31d8b Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 17 Mar 2016 17:47:50 +0000 Subject: [PATCH 0611/2280] Fix LyricsWiki scraping code LyricsWiki now escapes song lyrics using HTML entities (presumably to prevent scraping), so we now unescape these before parsing. LyricsWiki has also added a script tag inside the div we are scraping, so we have to remove this using `scrape_lyrics_from_html`. --- beetsplug/lyrics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 66b859f59..b979e1b64 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -321,7 +321,8 @@ class LyricsWiki(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_in(html, u"
") + lyrics = extract_text_in(unescape(html), u"
") + lyrics = scrape_lyrics_from_html(lyrics) if lyrics and 'Unfortunately, we are not licensed' not in lyrics: return lyrics From 9fac645b11bfc54427919fbee2d627fbd130ec54 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 18 Mar 2016 11:49:24 -0400 Subject: [PATCH 0612/2280] Changelog for #1912 (part of #1909) --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 22d2c7226..cc4b57b78 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,8 @@ Fixes: password in the ``beet config`` output. :bug:`1907` * :doc:`/plugins/scrub`: Fix an occasional problem where scrubbing on import could undo the ``id3v23`` setting. :bug:`1903` +* :doc:`/plugins/lyrics`: Add compatibility with some changes to the + LyricsWiki page markup. :bug:`1912` :bug:`1909` 1.3.17 (February 7, 2016) From f684f29a2536dc567eedacac27d843828022cafd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 21 Mar 2016 10:24:13 -0700 Subject: [PATCH 0613/2280] lyrics: Tolerate pages without text (fix #1914) --- beetsplug/lyrics.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b5212b56f..7ed64d88d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -430,8 +430,13 @@ def scrape_lyrics_from_html(html): parse_only=SoupStrainer(text=is_text_notcode)) except HTMLParseError: return None - soup = sorted(soup.stripped_strings, key=len)[-1] - return soup + + # Get the longest text element (if any). + strings = sorted(soup.stripped_strings, key=len, reverse=True) + if strings: + return strings[0] + else: + return None class Google(Backend): From d1753b341eefe33e925e0e5a3618ede53efef455 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 21 Mar 2016 10:28:30 -0700 Subject: [PATCH 0614/2280] lyrics: Some comments and better naming --- beetsplug/lyrics.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7ed64d88d..207b9d084 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -331,8 +331,12 @@ class LyricsWiki(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_in(unescape(html), u"
") - lyrics = scrape_lyrics_from_html(lyrics) + + # Get the HTML fragment inside the appropriate HTML element and then + # extract the text from it. + html_frag = extract_text_in(unescape(html), u"
") + lyrics = scrape_lyrics_from_html(html_frag) + if lyrics and 'Unfortunately, we are not licensed' not in lyrics: return lyrics From 8ef36198fb65b1739c9afdcdc599f5d09cba777b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Tissi=C3=A8res?= Date: Mon, 21 Mar 2016 20:47:05 +0100 Subject: [PATCH 0615/2280] importadded: preserve mtime after any write --- beetsplug/importadded.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 1202e95de..71ead7193 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -19,6 +19,7 @@ class ImportAddedPlugin(BeetsPlugin): super(ImportAddedPlugin, self).__init__() self.config.add({ 'preserve_mtimes': False, + 'preserve_write_mtimes': False, }) # item.id for new items that were reimported @@ -37,6 +38,7 @@ class ImportAddedPlugin(BeetsPlugin): register('item_linked', self.record_import_mtime) register('album_imported', self.update_album_times) register('item_imported', self.update_item_times) + register('after_write', self.update_after_write_time) def check_config(self, task, session): self.config['preserve_mtimes'].get(bool) @@ -120,3 +122,13 @@ class ImportAddedPlugin(BeetsPlugin): self._log.debug(u"Import of item '{0}', selected item.added={1}", util.displayable_path(item.path), item.added) item.store() + + def update_after_write_time(self, item): + """Update the mtime of the item's file with the item.added value + after each write of the item if `preserve_write_mtimes` is enabled. + """ + if item.added: + if self.config['preserve_write_mtimes'].get(bool): + self.write_item_mtime(item, item.added) + self._log.debug(u"Write of item '{0}', selected item.added={1}", + util.displayable_path(item.path), item.added) From e5be804802d6a11e9e5e0b8c25ba17999fd2f95c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Tissi=C3=A8res?= Date: Tue, 22 Mar 2016 06:24:09 +0100 Subject: [PATCH 0616/2280] importadded: adapt doc for new option preserve_write_mtimes --- beetsplug/importadded.py | 4 ++-- docs/changelog.rst | 2 ++ docs/plugins/importadded.rst | 15 +++++++++++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 71ead7193..77c7e7ab8 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -124,8 +124,8 @@ class ImportAddedPlugin(BeetsPlugin): item.store() def update_after_write_time(self, item): - """Update the mtime of the item's file with the item.added value - after each write of the item if `preserve_write_mtimes` is enabled. + """Update the mtime of the item's file with the item.added value + after each write of the item if `preserve_write_mtimes` is enabled. """ if item.added: if self.config['preserve_write_mtimes'].get(bool): diff --git a/docs/changelog.rst b/docs/changelog.rst index 9cc53ac97..f3460cfde 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,8 @@ New features: * :doc:`/plugins/convert`: A new `album_art_maxwidth` lets you resize album art while copying it. +* :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option + lets you preserve mtime of files after each write. Fixes: diff --git a/docs/plugins/importadded.rst b/docs/plugins/importadded.rst index 677879da8..2a2e8ea29 100644 --- a/docs/plugins/importadded.rst +++ b/docs/plugins/importadded.rst @@ -22,8 +22,11 @@ The ``item.added`` field is populated as follows: set to the oldest mtime of the files in the album before they were imported. The mtime of album directories is ignored. -This plugin can optionally be configured to also preserve mtimes using the -``preserve_mtimes`` option. +This plugin can optionally be configured to also preserve mtimes at +import using the ``preserve_mtimes`` option. + +When ``preserve_write_mtimes`` option is set, this plugin preserves +mtimes after each write to files using the ``item.added`` attribute. File modification times are preserved as follows: @@ -40,9 +43,13 @@ Configuration ------------- To configure the plugin, make an ``importadded:`` section in your -configuration file. There is one option available: +configuration file. There are two options available: -- **preserve_mtimes**: After writing files, re-set their mtimes to their +- **preserve_mtimes**: After importing files, re-set their mtimes to their + original value. + Default: ``no``. + +- **preserve_write_mtimes**: After writing files, re-set their mtimes to their original value. Default: ``no``. From c0a041b87e629a23826da87bb6b14151065529dc Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Mar 2016 19:42:16 +0100 Subject: [PATCH 0617/2280] fetchart: Unify handling of local and remote sources. --- beetsplug/fetchart.py | 230 +++++++++++++++++++++++------------------- 1 file changed, 125 insertions(+), 105 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index ad51bb995..6b205ae0c 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -99,11 +99,58 @@ class ArtSource(RequestMixin): self._log = log self._config = config - def get(self, album): + def get(self, album, extra): raise NotImplementedError() + def fetch_image(self, candidate, extra): + raise NotImplementedError() -class CoverArtArchive(ArtSource): +class LocalArtSource(ArtSource): + IS_LOCAL = True + LOC_STR = u'local' + + def fetch_image(self, candidate, extra): + return candidate + +class RemoteArtSource(ArtSource): + IS_LOCAL = False + LOC_STR = u'remote' + + def fetch_image(self, candidate, extra): + """Downloads an image from a URL and checks whether it seems to + actually be an image. If so, returns a path to the downloaded image. + Otherwise, returns None. + """ + if extra['maxwidth']: + url = ArtResizer.shared.proxy_url(extra['maxwidth'], candidate) + try: + with closing(self.request(url, stream=True, + message=u'downloading image')) as resp: + if 'Content-Type' not in resp.headers \ + or resp.headers['Content-Type'] not in CONTENT_TYPES: + self._log.debug( + u'not a supported image: {}', + resp.headers.get('Content-Type') or u'no content type', + ) + return None + + # Generate a temporary file with the correct extension. + with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, + delete=False) as fh: + for chunk in resp.iter_content(chunk_size=1024): + fh.write(chunk) + self._log.debug(u'downloaded art to: {0}', + util.displayable_path(fh.name)) + return fh.name + + except (IOError, requests.RequestException, TypeError) as exc: + # Handling TypeError works around a urllib3 bug: + # https://github.com/shazow/urllib3/issues/556 + self._log.debug(u'error fetching art: {}', exc) + return None + + +class CoverArtArchive(RemoteArtSource): """Cover Art Archive""" URL = 'http://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' @@ -118,7 +165,7 @@ class CoverArtArchive(ArtSource): yield self.GROUP_URL.format(mbid=album.mb_releasegroupid) -class Amazon(ArtSource): +class Amazon(RemoteArtSource): URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) @@ -130,7 +177,7 @@ class Amazon(ArtSource): yield self.URL % (album.asin, index) -class AlbumArtOrg(ArtSource): +class AlbumArtOrg(RemoteArtSource): """AlbumArt.org scraper""" URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' @@ -157,7 +204,7 @@ class AlbumArtOrg(ArtSource): self._log.debug(u'no image found on page') -class GoogleImages(ArtSource): +class GoogleImages(RemoteArtSource): URL = u'https://www.googleapis.com/customsearch/v1' def get(self, album): @@ -192,7 +239,7 @@ class GoogleImages(ArtSource): yield item['link'] -class ITunesStore(ArtSource): +class ITunesStore(RemoteArtSource): # Art from the iTunes Store. def get(self, album): """Return art URL from iTunes Store given an album title. @@ -226,7 +273,7 @@ class ITunesStore(ArtSource): self._log.debug(u'album not found in iTunes Store') -class Wikipedia(ArtSource): +class Wikipedia(RemoteArtSource): # Art from Wikipedia (queried through DBpedia) DBPEDIA_URL = 'http://dbpedia.org/sparql' WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' @@ -350,7 +397,7 @@ class Wikipedia(ArtSource): return -class FileSystem(ArtSource): +class FileSystem(LocalArtSource): """Art from the filesystem""" @staticmethod def filename_priority(filename, cover_names): @@ -362,43 +409,51 @@ class FileSystem(ArtSource): """ return [idx for (idx, x) in enumerate(cover_names) if x in filename] - def get(self, path, cover_names, cautious): - """Look for album art files in a specified directory. + def get(self, extra): + """Look for album art files in the specified directories. """ - if not os.path.isdir(path): - return - - # Find all files that look like images in the directory. - images = [] - for fn in os.listdir(path): - for ext in IMAGE_EXTENSIONS: - if fn.lower().endswith(b'.' + ext.encode('utf8')) and \ - os.path.isfile(os.path.join(path, fn)): - images.append(fn) - - # Look for "preferred" filenames. - images = sorted(images, - key=lambda x: self.filename_priority(x, cover_names)) + paths = extra['paths'] + cover_names = extra['cover_names'] + def sortkey(): + return self.filename_priority(x, cover_names) cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) - for fn in images: - if re.search(cover_pat, os.path.splitext(fn)[0], re.I): - self._log.debug(u'using well-named art file {0}', - util.displayable_path(fn)) - return os.path.join(path, fn) + cautious = extra['cautious'] + + for path in paths + if not os.path.isdir(path): + continue - # Fall back to any image in the folder. - if images and not cautious: - self._log.debug(u'using fallback art file {0}', - util.displayable_path(images[0])) - return os.path.join(path, images[0]) + # Find all files that look like images in the directory. + images = [] + for fn in os.listdir(path): + for ext in IMAGE_EXTENSIONS: + if fn.lower().endswith(b'.' + ext.encode('utf8')) and \ + os.path.isfile(os.path.join(path, fn)): + images.append(fn) + + # Look for "preferred" filenames. + images = sorted(images, sortkey) + for fn in images: + if re.search(cover_pat, os.path.splitext(fn)[0], re.I): + self._log.debug(u'using well-named art file {0}', + util.displayable_path(fn)) + yield os.path.join(path, fn) + + # Fall back to any image in the folder. + if images and not cautious: + self._log.debug(u'using fallback art file {0}', + util.displayable_path(images[0])) + yield os.path.join(path, images[0]) # Try each source in turn. -SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', +SOURCES_ALL = [u'filesysytem', + u'coverart', u'itunes', u'amazon', u'albumart', u'wikipedia', u'google'] ART_SOURCES = { + u'filesystem': FileSystem, u'coverart': CoverArtArchive, u'itunes': ITunesStore, u'albumart': AlbumArtOrg, @@ -422,7 +477,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'remote_priority': False, 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], - 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], + 'sources': ['filesystem', + 'coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', }) @@ -449,9 +505,18 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'google') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) + if 'remote_priority' in self.config: + self._log.warning( + u'The `fetch_art.remote_priority` configuration option has ' + u'been deprecated, see the documentation.') + if self.config['remote_priority'].get(bool): + try: + self.sources_name.remove[u'filesystem'] + sources_name.append[u'filesystem'] + except ValueError: + pass self.sources = [ART_SOURCES[s](self._log, self.config) for s in sources_name] - self.fs_source = FileSystem(self._log, self.config) # Asynchronous; after music is added to the library. def fetch_art(self, session, task): @@ -505,37 +570,6 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # Utilities converted from functions to methods on logging overhaul - def _fetch_image(self, url): - """Downloads an image from a URL and checks whether it seems to - actually be an image. If so, returns a path to the downloaded image. - Otherwise, returns None. - """ - try: - with closing(self.request(url, stream=True, - message=u'downloading image')) as resp: - if 'Content-Type' not in resp.headers \ - or resp.headers['Content-Type'] not in CONTENT_TYPES: - self._log.debug( - u'not a supported image: {}', - resp.headers.get('Content-Type') or u'no content type', - ) - return None - - # Generate a temporary file with the correct extension. - with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, - delete=False) as fh: - for chunk in resp.iter_content(chunk_size=1024): - fh.write(chunk) - self._log.debug(u'downloaded art to: {0}', - util.displayable_path(fh.name)) - return fh.name - - except (IOError, requests.RequestException, TypeError) as exc: - # Handling TypeError works around a urllib3 bug: - # https://github.com/shazow/urllib3/issues/556 - self._log.debug(u'error fetching art: {}', exc) - return None - def _is_valid_image_candidate(self, candidate): """Determine whether the given candidate artwork is valid based on its dimensions (width and ratio). @@ -591,30 +625,33 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): out = None check = None - # Local art. cover_names = self.config['cover_names'].as_str_seq() cover_names = map(util.bytestring_path, cover_names) cautious = self.config['cautious'].get(bool) - if paths: - for path in paths: - candidate = self.fs_source.get(path, cover_names, cautious) - check = self._is_valid_image_candidate(candidate) - if check: - out = candidate - self._log.debug(u'found local image {}', out) - break + extra = {'paths': paths, + 'cover_names': cover_names, + 'cautious': cautious, + 'maxwidth': self.maxwidth} + source_names = {v: k for k, v in ART_SOURCES.items()} - # Web art sources. - remote_priority = self.config['remote_priority'].get(bool) - if not local_only and (remote_priority or not out): - for url in self._source_urls(album): - if self.maxwidth: - url = ArtResizer.shared.proxy_url(self.maxwidth, url) - candidate = self._fetch_image(url) - check = self._is_valid_image_candidate(candidate) - if check: - out = candidate - self._log.debug(u'using remote image {}', out) + for source in self.sources: + if source.is_local or not local_only: + self._log.debug( + u'trying source {0} for album {1.albumartist} - {1.album}', + source_names[type(source)], + album, + ) + # URLs might be invalid at this point, or the image may not + # fulfill the requirements + for candidate in source.get(album, extra): + candidate = source.fetch_image(candidate) + check = self._is_valid_image_candidate(candidate) + if check: + out = candidate + self._log.debug(u'using {0.LOC_STR()} image {1}' + .format(source, out)) + break + if out: break if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: @@ -645,20 +682,3 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self._log.info(u'{0}: {1}', album, message) - def _source_urls(self, album): - """Generate possible source URLs for an album's art. The URLs are - not guaranteed to work so they each need to be attempted in turn. - This allows the main `art_for_album` function to abort iteration - through this sequence early to avoid the cost of scraping when not - necessary. - """ - source_names = {v: k for k, v in ART_SOURCES.items()} - for source in self.sources: - self._log.debug( - u'trying source {0} for album {1.albumartist} - {1.album}', - source_names[type(source)], - album, - ) - urls = source.get(album) - for url in urls: - yield url From b37cc02f1a5820c4d9c21629efa777d5191d5740 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Mar 2016 20:52:25 +0100 Subject: [PATCH 0618/2280] fetchart: Introduce the Candidate class, some fixes to the previous commit. --- beetsplug/fetchart.py | 201 ++++++++++++++++++++++++++---------------- 1 file changed, 124 insertions(+), 77 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 6b205ae0c..63d56ce44 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -45,6 +45,75 @@ CANDIDATE_BAD = 0 CANDIDATE_EXACT = 1 CANDIDATE_DOWNSCALE = 2 +MATCH_EXACT = 0 +MATCH_FALLBACK = 1 + +class Candidate(): + """ + + """ + def __init__(self, path=None, url=None, source=u'', match=None): + self.path = path + self.source = source + self.check = None + self.match = match + self.size = None + + def _validate(self, extra): + """Determine whether the candidate artwork is valid based on + its dimensions (width and ratio). + + Return `CANDIDATE_BAD` if the file is unusable. + Return `CANDIDATE_EXACT` if the file is usable as-is. + Return `CANDIDATE_DOWNSCALE` if the file must be resized. + """ + if not self.path: + return CANDIDATE_BAD + + if not (extra.['enforce_ratio'] or + extra.['minwidth'] or + extra.['maxwidth']): + return CANDIDATE_EXACT + + # get_size returns None if no local imaging backend is available + self.size = ArtResizer.shared.get_size(self.path) + self._log.debug(u'image size: {}', self.size) + + if not self.size: + self._log.warning(u'Could not get size of image (please see ' + u'documentation for dependencies). ' + u'The configuration options `minwidth` and ' + u'`enforce_ratio` may be violated.') + return CANDIDATE_EXACT + + # Check minimum size. + if extra.['minwidth'] and self.size[0] < extra.['minwidth']: + self._log.debug(u'image too small ({} < {})', + self.size[0], extra.['minwidth']) + return CANDIDATE_BAD + + # Check aspect ratio. + if extra.['enforce_ratio'] and self.size[0] != self.size[1]: + self._log.debug(u'image is not square ({} != {})', + self.size[0], self.size[1]) + return CANDIDATE_BAD + + # Check maximum size. + if extra.['maxwidth'] and self.size[0] > extra.['maxwidth']: + self._log.debug(u'image needs resizing ({} > {})', + self.size[0], extra.['maxwidth']) + return CANDIDATE_DOWNSCALE + + return CANDIDATE_EXACT + + def validate(self, extra): + self.check = self._validate(extra) + return self.check + + def resize(self, extra): + if extra.['maxwidth'] and self.check == CANDIDATE_DOWNSCALE: + self.path = ArtResizer.shared.resize(extra.['maxwidth'], self.path) + def _logged_get(log, *args, **kwargs): """Like `requests.get`, but logs the effective URL to the specified @@ -122,9 +191,10 @@ class RemoteArtSource(ArtSource): Otherwise, returns None. """ if extra['maxwidth']: - url = ArtResizer.shared.proxy_url(extra['maxwidth'], candidate) + candidate.url = ArtResizer.shared.proxy_url(extra['maxwidth'], + candidate.url) try: - with closing(self.request(url, stream=True, + with closing(self.request(candidate.url, stream=True, message=u'downloading image')) as resp: if 'Content-Type' not in resp.headers \ or resp.headers['Content-Type'] not in CONTENT_TYPES: @@ -132,7 +202,8 @@ class RemoteArtSource(ArtSource): u'not a supported image: {}', resp.headers.get('Content-Type') or u'no content type', ) - return None + candidate.path = None + return # Generate a temporary file with the correct extension. with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, @@ -141,13 +212,15 @@ class RemoteArtSource(ArtSource): fh.write(chunk) self._log.debug(u'downloaded art to: {0}', util.displayable_path(fh.name)) - return fh.name + candidate.path = fh.name + return except (IOError, requests.RequestException, TypeError) as exc: # Handling TypeError works around a urllib3 bug: # https://github.com/shazow/urllib3/issues/556 self._log.debug(u'error fetching art: {}', exc) - return None + candidate.path = None + return class CoverArtArchive(RemoteArtSource): @@ -155,26 +228,32 @@ class CoverArtArchive(RemoteArtSource): URL = 'http://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' - def get(self, album): + def get(self, album, extra): """Return the Cover Art Archive and Cover Art Archive release group URLs using album MusicBrainz release ID and release group ID. """ if album.mb_albumid: - yield self.URL.format(mbid=album.mb_albumid) + yield Candidate(url=self.URL.format(mbid=album.mb_albumid), + source=u'coverartarchive.org', + match=MATCH_EXACT) if album.mb_releasegroupid: - yield self.GROUP_URL.format(mbid=album.mb_releasegroupid) + yield Candidate(url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), + source=u'coverartarchive.org', + match=MATCH_FALLBACK) class Amazon(RemoteArtSource): URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) - def get(self, album): + def get(self, album, extra): """Generate URLs using Amazon ID (ASIN) string. """ if album.asin: for index in self.INDICES: - yield self.URL % (album.asin, index) + yield Candidate(url=self.URL % (album.asin, index), + source=u'Amazon', + match=MATCH_EXACT) class AlbumArtOrg(RemoteArtSource): @@ -182,7 +261,7 @@ class AlbumArtOrg(RemoteArtSource): URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' - def get(self, album): + def get(self, album, extra): """Return art URL from AlbumArt.org using album ASIN. """ if not album.asin: @@ -199,7 +278,9 @@ class AlbumArtOrg(RemoteArtSource): m = re.search(self.PAT, resp.text) if m: image_url = m.group(1) - yield image_url + yield Candidate(url=image_url, + source=u'AlbumArt.org', + match=MATCH_EXACT) else: self._log.debug(u'no image found on page') @@ -207,7 +288,7 @@ class AlbumArtOrg(RemoteArtSource): class GoogleImages(RemoteArtSource): URL = u'https://www.googleapis.com/customsearch/v1' - def get(self, album): + def get(self, album, extra): """Return art URL from google custom search engine given an album title and interpreter. """ @@ -236,12 +317,14 @@ class GoogleImages(RemoteArtSource): if 'items' in data.keys(): for item in data['items']: - yield item['link'] + yield Candidate(url=item['link'], + source=u'Google images', + match=MATCH_EXACT) class ITunesStore(RemoteArtSource): # Art from the iTunes Store. - def get(self, album): + def get(self, album, extra): """Return art URL from iTunes Store given an album title. """ if not (album.albumartist and album.album): @@ -266,7 +349,9 @@ class ITunesStore(RemoteArtSource): if itunes_album.get_artwork()['100']: small_url = itunes_album.get_artwork()['100'] big_url = small_url.replace('100x100', '1200x1200') - yield big_url + yield Candidate(url=big_url, + source=u'iTunes Store', + match=MATCH_EXACT) else: self._log.debug(u'album has no artwork in iTunes Store') except IndexError: @@ -299,7 +384,7 @@ class Wikipedia(RemoteArtSource): }} Limit 1''' - def get(self, album): + def get(self, album, extra): if not (album.albumartist and album.album): return @@ -391,7 +476,9 @@ class Wikipedia(RemoteArtSource): results = data['query']['pages'] for _, result in results.iteritems(): image_url = result['imageinfo'][0]['url'] - yield image_url + yield Candidate(url=image_url, + source=u'Wikipedia', + match=MATCH_EXACT) except (ValueError, KeyError, IndexError): self._log.debug(u'wikipedia: error scraping imageinfo') return @@ -409,13 +496,11 @@ class FileSystem(LocalArtSource): """ return [idx for (idx, x) in enumerate(cover_names) if x in filename] - def get(self, extra): + def get(self, album, extra): """Look for album art files in the specified directories. """ paths = extra['paths'] cover_names = extra['cover_names'] - def sortkey(): - return self.filename_priority(x, cover_names) cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) cautious = extra['cautious'] @@ -432,18 +517,23 @@ class FileSystem(LocalArtSource): images.append(fn) # Look for "preferred" filenames. - images = sorted(images, sortkey) + images = sorted(images, + lambda x: self.filename_priority(x, cover_names)) for fn in images: if re.search(cover_pat, os.path.splitext(fn)[0], re.I): self._log.debug(u'using well-named art file {0}', util.displayable_path(fn)) - yield os.path.join(path, fn) + yield Candidate(path=os.path.join(path, fn), + source=u'Filesystem', + match=MATCH_EXACT) # Fall back to any image in the folder. if images and not cautious: self._log.debug(u'using fallback art file {0}', util.displayable_path(images[0])) - yield os.path.join(path, images[0]) + yield Candidate(path=os.path.join(path, images[0]), + source=u'Filesystem', + match=MATCH_FALLBACK) # Try each source in turn. @@ -461,6 +551,7 @@ ART_SOURCES = { u'wikipedia': Wikipedia, u'google': GoogleImages, } +SOURCE_NAMES = {v: k for k, v in ART_SOURCES.items()} # PLUGIN LOGIC ############################################################### @@ -570,51 +661,6 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # Utilities converted from functions to methods on logging overhaul - def _is_valid_image_candidate(self, candidate): - """Determine whether the given candidate artwork is valid based on - its dimensions (width and ratio). - - Return `CANDIDATE_BAD` if the file is unusable. - Return `CANDIDATE_EXACT` if the file is usable as-is. - Return `CANDIDATE_DOWNSCALE` if the file must be resized. - """ - if not candidate: - return CANDIDATE_BAD - - if not (self.enforce_ratio or self.minwidth or self.maxwidth): - return CANDIDATE_EXACT - - # get_size returns None if no local imaging backend is available - size = ArtResizer.shared.get_size(candidate) - self._log.debug(u'image size: {}', size) - - if not size: - self._log.warning(u'Could not get size of image (please see ' - u'documentation for dependencies). ' - u'The configuration options `minwidth` and ' - u'`enforce_ratio` may be violated.') - return CANDIDATE_EXACT - - # Check minimum size. - if self.minwidth and size[0] < self.minwidth: - self._log.debug(u'image too small ({} < {})', - size[0], self.minwidth) - return CANDIDATE_BAD - - # Check aspect ratio. - if self.enforce_ratio and size[0] != size[1]: - self._log.debug(u'image is not square ({} != {})', - size[0], size[1]) - return CANDIDATE_BAD - - # Check maximum size. - if self.maxwidth and size[0] > self.maxwidth: - self._log.debug(u'image needs resizing ({} > {})', - size[0], self.maxwidth) - return CANDIDATE_DOWNSCALE - - return CANDIDATE_EXACT - def art_for_album(self, album, paths, local_only=False): """Given an Album object, returns a path to downloaded art for the album (or None if no art is found). If `maxwidth`, then images are @@ -625,37 +671,38 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): out = None check = None + # all the information any of the sources might need cover_names = self.config['cover_names'].as_str_seq() cover_names = map(util.bytestring_path, cover_names) cautious = self.config['cautious'].get(bool) extra = {'paths': paths, 'cover_names': cover_names, 'cautious': cautious, + 'enforce_ratio': self.enforce_ratio, + 'minwidth': self.minwidth, 'maxwidth': self.maxwidth} - source_names = {v: k for k, v in ART_SOURCES.items()} for source in self.sources: if source.is_local or not local_only: self._log.debug( u'trying source {0} for album {1.albumartist} - {1.album}', - source_names[type(source)], + SOURCE_NAMES[type(source)], album, ) # URLs might be invalid at this point, or the image may not # fulfill the requirements for candidate in source.get(album, extra): - candidate = source.fetch_image(candidate) - check = self._is_valid_image_candidate(candidate) - if check: + source.fetch_image(candidate) + if candidate.validate(extra): out = candidate self._log.debug(u'using {0.LOC_STR()} image {1}' - .format(source, out)) + .format(source, out.path)) break if out: break - if self.maxwidth and out and check == CANDIDATE_DOWNSCALE: - out = ArtResizer.shared.resize(self.maxwidth, out) + if out: + out.resize(extra) return out From 1cfd039da43ebeca210e429171b1c40a3e6bde0c Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Mar 2016 21:09:05 +0100 Subject: [PATCH 0619/2280] Update fetchart documentation. --- docs/plugins/fetchart.rst | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index e53dbc219..132efd5b5 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -43,15 +43,14 @@ file. The available options are: pixels. The height is recomputed so that the aspect ratio is preserved. - **enforce_ratio**: Only images with a width:height ratio of 1:1 are considered as valid album art candidates. Default: ``no``. -- **remote_priority**: Query remote sources every time and use local image only - as fallback. - Default: ``no``; remote (Web) art sources are only queried if no local art is - found in the filesystem. - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. - Default: ``coverart itunes amazon albumart``, i.e., everything but + Default: ``filesystem coverart itunes amazon albumart``, i.e., everything but ``wikipedia`` and ``google``. Enable those two sources for more matches at - the cost of some speed. + the cost of some speed. They are searched in the given order, thus in the + default config, no remote (Web) art source are queried if local art is + found in the filesystem. To use a local image as fallback, move it to the end + of the list. - **google_key**: Your Google API key (to enable the Google Custom Search backend). Default: None. From 8356e7d33d5a6d53152445a52789793a9202305b Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 23 Mar 2016 00:47:11 +0100 Subject: [PATCH 0620/2280] fix syntax --- beetsplug/fetchart.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 63d56ce44..3e954feff 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -70,9 +70,9 @@ class Candidate(): if not self.path: return CANDIDATE_BAD - if not (extra.['enforce_ratio'] or - extra.['minwidth'] or - extra.['maxwidth']): + if not (extra['enforce_ratio'] or + extra['minwidth'] or + extra['maxwidth']): return CANDIDATE_EXACT # get_size returns None if no local imaging backend is available @@ -87,21 +87,21 @@ class Candidate(): return CANDIDATE_EXACT # Check minimum size. - if extra.['minwidth'] and self.size[0] < extra.['minwidth']: + if extra['minwidth'] and self.size[0] < extra['minwidth']: self._log.debug(u'image too small ({} < {})', - self.size[0], extra.['minwidth']) + self.size[0], extra['minwidth']) return CANDIDATE_BAD # Check aspect ratio. - if extra.['enforce_ratio'] and self.size[0] != self.size[1]: + if extra['enforce_ratio'] and self.size[0] != self.size[1]: self._log.debug(u'image is not square ({} != {})', self.size[0], self.size[1]) return CANDIDATE_BAD # Check maximum size. - if extra.['maxwidth'] and self.size[0] > extra.['maxwidth']: + if extra['maxwidth'] and self.size[0] > extra['maxwidth']: self._log.debug(u'image needs resizing ({} > {})', - self.size[0], extra.['maxwidth']) + self.size[0], extra['maxwidth']) return CANDIDATE_DOWNSCALE return CANDIDATE_EXACT @@ -111,8 +111,8 @@ class Candidate(): return self.check def resize(self, extra): - if extra.['maxwidth'] and self.check == CANDIDATE_DOWNSCALE: - self.path = ArtResizer.shared.resize(extra.['maxwidth'], self.path) + if extra['maxwidth'] and self.check == CANDIDATE_DOWNSCALE: + self.path = ArtResizer.shared.resize(extra['maxwidth'], self.path) def _logged_get(log, *args, **kwargs): @@ -504,7 +504,7 @@ class FileSystem(LocalArtSource): cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) cautious = extra['cautious'] - for path in paths + for path in paths: if not os.path.isdir(path): continue From 50bf28edd4e4707af930ae7e1dcb95ce0d70032e Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 23 Mar 2016 16:46:39 +0100 Subject: [PATCH 0621/2280] move constants into Candidate --- beetsplug/fetchart.py | 50 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 3e954feff..08e8988ff 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -41,17 +41,17 @@ IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' -CANDIDATE_BAD = 0 -CANDIDATE_EXACT = 1 -CANDIDATE_DOWNSCALE = 2 - -MATCH_EXACT = 0 -MATCH_FALLBACK = 1 - class Candidate(): """ """ + CANDIDATE_BAD = 0 + CANDIDATE_EXACT = 1 + CANDIDATE_DOWNSCALE = 2 + + MATCH_EXACT = 0 + MATCH_FALLBACK = 1 + def __init__(self, path=None, url=None, source=u'', match=None): self.path = path self.source = source @@ -68,12 +68,12 @@ class Candidate(): Return `CANDIDATE_DOWNSCALE` if the file must be resized. """ if not self.path: - return CANDIDATE_BAD + return self.CANDIDATE_BAD if not (extra['enforce_ratio'] or extra['minwidth'] or extra['maxwidth']): - return CANDIDATE_EXACT + return self.CANDIDATE_EXACT # get_size returns None if no local imaging backend is available self.size = ArtResizer.shared.get_size(self.path) @@ -84,34 +84,34 @@ class Candidate(): u'documentation for dependencies). ' u'The configuration options `minwidth` and ' u'`enforce_ratio` may be violated.') - return CANDIDATE_EXACT + return self.CANDIDATE_EXACT # Check minimum size. if extra['minwidth'] and self.size[0] < extra['minwidth']: self._log.debug(u'image too small ({} < {})', self.size[0], extra['minwidth']) - return CANDIDATE_BAD + return self.CANDIDATE_BAD # Check aspect ratio. if extra['enforce_ratio'] and self.size[0] != self.size[1]: self._log.debug(u'image is not square ({} != {})', self.size[0], self.size[1]) - return CANDIDATE_BAD + return self.CANDIDATE_BAD # Check maximum size. if extra['maxwidth'] and self.size[0] > extra['maxwidth']: self._log.debug(u'image needs resizing ({} > {})', self.size[0], extra['maxwidth']) - return CANDIDATE_DOWNSCALE + return self.CANDIDATE_DOWNSCALE - return CANDIDATE_EXACT + return self.CANDIDATE_EXACT def validate(self, extra): self.check = self._validate(extra) return self.check def resize(self, extra): - if extra['maxwidth'] and self.check == CANDIDATE_DOWNSCALE: + if extra['maxwidth'] and self.check == self.CANDIDATE_DOWNSCALE: self.path = ArtResizer.shared.resize(extra['maxwidth'], self.path) @@ -235,11 +235,11 @@ class CoverArtArchive(RemoteArtSource): if album.mb_albumid: yield Candidate(url=self.URL.format(mbid=album.mb_albumid), source=u'coverartarchive.org', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) if album.mb_releasegroupid: yield Candidate(url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), source=u'coverartarchive.org', - match=MATCH_FALLBACK) + match=Candidate.MATCH_FALLBACK) class Amazon(RemoteArtSource): @@ -253,7 +253,7 @@ class Amazon(RemoteArtSource): for index in self.INDICES: yield Candidate(url=self.URL % (album.asin, index), source=u'Amazon', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) class AlbumArtOrg(RemoteArtSource): @@ -280,7 +280,7 @@ class AlbumArtOrg(RemoteArtSource): image_url = m.group(1) yield Candidate(url=image_url, source=u'AlbumArt.org', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) else: self._log.debug(u'no image found on page') @@ -319,7 +319,7 @@ class GoogleImages(RemoteArtSource): for item in data['items']: yield Candidate(url=item['link'], source=u'Google images', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) class ITunesStore(RemoteArtSource): @@ -351,7 +351,7 @@ class ITunesStore(RemoteArtSource): big_url = small_url.replace('100x100', '1200x1200') yield Candidate(url=big_url, source=u'iTunes Store', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) else: self._log.debug(u'album has no artwork in iTunes Store') except IndexError: @@ -478,7 +478,7 @@ class Wikipedia(RemoteArtSource): image_url = result['imageinfo'][0]['url'] yield Candidate(url=image_url, source=u'Wikipedia', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) except (ValueError, KeyError, IndexError): self._log.debug(u'wikipedia: error scraping imageinfo') return @@ -525,7 +525,7 @@ class FileSystem(LocalArtSource): util.displayable_path(fn)) yield Candidate(path=os.path.join(path, fn), source=u'Filesystem', - match=MATCH_EXACT) + match=Candidate.MATCH_EXACT) # Fall back to any image in the folder. if images and not cautious: @@ -533,7 +533,7 @@ class FileSystem(LocalArtSource): util.displayable_path(images[0])) yield Candidate(path=os.path.join(path, images[0]), source=u'Filesystem', - match=MATCH_FALLBACK) + match=Candidate.MATCH_FALLBACK) # Try each source in turn. @@ -683,7 +683,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'maxwidth': self.maxwidth} for source in self.sources: - if source.is_local or not local_only: + if source.IS_LOCAL or not local_only: self._log.debug( u'trying source {0} for album {1.albumartist} - {1.album}', SOURCE_NAMES[type(source)], From 31aff68150313e6c3a1a2afa315c562b70cf0168 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 25 Mar 2016 16:25:00 +0100 Subject: [PATCH 0622/2280] fetchart: Adapt FetchImageTest, FSArtTest --- test/test_art.py | 46 ++++++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index ebfcd53f4..aa2c74f1c 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -53,15 +53,23 @@ class FetchImageTest(UseThePlugin): responses.add(responses.GET, 'http://example.com', content_type=content_type) + def setUp(self): + super(FetchImageTest, self).setUp() + self.dpath = os.path.join(self.temp_dir, 'arttest') + self.candidate = self.plugin.Candidate(url='http://example.com') + self.source = self.plugin.RemoteArtSource(logger, self.plugin.config) + def test_invalid_type_returns_none(self): self.mock_response('image/watercolour') - artpath = self.plugin._fetch_image('http://example.com') - self.assertEqual(artpath, None) + self.candidate.path = None + self.source.fetch_image(candidate) + self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): self.mock_response('image/jpeg') - artpath = self.plugin._fetch_image('http://example.com') - self.assertNotEqual(artpath, None) + self.candidate.path = None + self.source.fetch_image(candidate) + self.assertNotEqual(self.candidate.path, None) class FSArtTest(UseThePlugin): @@ -71,38 +79,44 @@ class FSArtTest(UseThePlugin): os.mkdir(self.dpath) self.source = fetchart.FileSystem(logger, self.plugin.config) + self.extra = {'cautious': False, + 'cover_names': ('art',), + 'paths': self.dpath} def test_finds_jpg_in_directory(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, os.path.join(self.dpath, 'a.jpg')) + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, os.path.join(self.dpath, 'a.jpg')) def test_appropriately_named_file_takes_precedence(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) _common.touch(os.path.join(self.dpath, 'art.jpg')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, os.path.join(self.dpath, 'art.jpg')) + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) def test_non_image_file_not_identified(self): _common.touch(os.path.join(self.dpath, 'a.txt')) - fn = self.source.get(self.dpath, ('art',), False) - self.assertEqual(fn, None) + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, None) def test_cautious_skips_fallback(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) - fn = self.source.get(self.dpath, ('art',), True) - self.assertEqual(fn, None) + self.extra['cautious'] = True + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, None) def test_empty_dir(self): - fn = self.source.get(self.dpath, ('art',), True) - self.assertEqual(fn, None) + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, None) def test_precedence_amongst_correct_files(self): _common.touch(os.path.join(self.dpath, 'back.jpg')) _common.touch(os.path.join(self.dpath, 'front.jpg')) _common.touch(os.path.join(self.dpath, 'front-cover.jpg')) - fn = self.source.get(self.dpath, ('cover', 'front', 'back'), False) - self.assertEqual(fn, os.path.join(self.dpath, 'front-cover.jpg')) + self.extra['cover_names'] = ('cover', 'front', 'back') + candidate = next(self.source.get(None, self.extra)) + self.assertEqual(candidate.path, + os.path.join(self.dpath, 'front-cover.jpg')) class CombinedTest(UseThePlugin): From 3f4f0772729a2890ecb8d45d5539830bea5f1eb0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Apr 2016 17:38:40 -0400 Subject: [PATCH 0623/2280] edit: Log the invoked command --- beetsplug/edit.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 58d0828a5..191091295 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -40,11 +40,12 @@ class ParseError(Exception): """ -def edit(filename): +def edit(filename, log): """Open `filename` in a text editor. """ cmd = util.shlex_split(util.editor_command()) cmd.append(filename) + log.debug(u'invoking editor command: {!r}', cmd) subprocess.call(cmd) @@ -245,7 +246,7 @@ class EditPlugin(plugins.BeetsPlugin): try: while True: # Ask the user to edit the data. - edit(new.name) + edit(new.name, self._log) # Read the data back after editing and check whether anything # changed. From fa2aa82a0d2142a933ab64adea71de7bc12d1c8f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Apr 2016 17:42:25 -0400 Subject: [PATCH 0624/2280] Fix #1927: useful error message for failed edit --- beetsplug/edit.py | 7 ++++++- docs/changelog.rst | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 191091295..5c7796ee8 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -46,7 +46,12 @@ def edit(filename, log): cmd = util.shlex_split(util.editor_command()) cmd.append(filename) log.debug(u'invoking editor command: {!r}', cmd) - subprocess.call(cmd) + try: + subprocess.call(cmd) + except OSError as exc: + raise ui.UserError(u'could not run editor command {!r}: {}'.format( + cmd[0], exc + )) def dump(arg): diff --git a/docs/changelog.rst b/docs/changelog.rst index f3460cfde..43c2893d7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,8 @@ Fixes: LyricsWiki page markup. :bug:`1912` :bug:`1909` * :doc:`/plugins/lyrics`: Also fix retrieval from Musixmatch and the way we guess the URL for lyrics. :bug:`1880` +* :doc:`/plugins/error`: Fail gracefully when the configured text editor + command can't be invoked. :bug:`1927` 1.3.17 (February 7, 2016) From cb498e07726212143e392ba1e4898b227efa5d1c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Apr 2016 17:50:18 -0400 Subject: [PATCH 0625/2280] Fix tests for #1927 fix --- test/test_edit.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 3bb817734..e756f99a2 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -47,7 +47,9 @@ class ModifyFileMocker(object): if replacements: self.action = self.replace_contents - def overwrite_contents(self, filename): + # The two methods below mock the `edit` utility function in the plugin. + + def overwrite_contents(self, filename, log): """Modify `filename`, replacing its contents with `self.contents`. If `self.contents` is empty, the file remains unchanged. """ @@ -55,7 +57,7 @@ class ModifyFileMocker(object): with codecs.open(filename, 'w', encoding='utf8') as f: f.write(self.contents) - def replace_contents(self, filename): + def replace_contents(self, filename, log): """Modify `filename`, reading its contents and replacing the strings specified in `self.replacements`. """ From 1d3637e507965a733fa3bdc78777394b7fd35cf4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 3 Apr 2016 18:00:44 -0400 Subject: [PATCH 0626/2280] Fix typo in changelog --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 43c2893d7..67960d56f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,7 +24,7 @@ Fixes: LyricsWiki page markup. :bug:`1912` :bug:`1909` * :doc:`/plugins/lyrics`: Also fix retrieval from Musixmatch and the way we guess the URL for lyrics. :bug:`1880` -* :doc:`/plugins/error`: Fail gracefully when the configured text editor +* :doc:`/plugins/edit`: Fail gracefully when the configured text editor command can't be invoked. :bug:`1927` From 02892a41aaabea81f1231f7ccc0e942c9e0d3526 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 5 Apr 2016 21:34:58 +0200 Subject: [PATCH 0627/2280] fetchart: Adapt CombinedTest --- test/test_art.py | 59 ++++++++++++++++++++++++------------------------ 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index aa2c74f1c..27ee3d6e7 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -96,27 +96,28 @@ class FSArtTest(UseThePlugin): def test_non_image_file_not_identified(self): _common.touch(os.path.join(self.dpath, 'a.txt')) - candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, None) + with self.assertRaises(StopIteration): + candidate = next(self.source.get(None, self.extra)) def test_cautious_skips_fallback(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) self.extra['cautious'] = True - candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, None) + with self.assertRaises(StopIteration): + candidate = next(self.source.get(None, self.extra)) def test_empty_dir(self): - candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, None) + with self.assertRaises(StopIteration): + candidate = next(self.source.get(None, self.extra)) def test_precedence_amongst_correct_files(self): - _common.touch(os.path.join(self.dpath, 'back.jpg')) - _common.touch(os.path.join(self.dpath, 'front.jpg')) - _common.touch(os.path.join(self.dpath, 'front-cover.jpg')) + images = ('front-cover.jpg', 'front.jpg', 'back.jpg') + paths = (os.path.join(self.dpath, i) for i in images) + for p in paths: + _common.touch(p) self.extra['cover_names'] = ('cover', 'front', 'back') - candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, - os.path.join(self.dpath, 'front-cover.jpg')) + candidates = (candidate.path + for candidate in self.source.get(None, self.extra)) + self.assertEqual(candidates, paths) class CombinedTest(UseThePlugin): @@ -144,27 +145,27 @@ class CombinedTest(UseThePlugin): def test_main_interface_returns_amazon_art(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, None) - self.assertNotEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertNotEqual(candidate.path, None) def test_main_interface_returns_none_for_missing_asin_and_path(self): album = _common.Bag() - artpath = self.plugin.art_for_album(album, None) - self.assertEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertEqual(candidate.path, None) def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, 'art.jpg')) self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath]) - self.assertEqual(artpath, os.path.join(self.dpath, 'art.jpg')) + candidate = self.plugin.art_for_album(album, [self.dpath]) + self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) def test_main_interface_falls_back_to_amazon(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath]) - self.assertNotEqual(artpath, None) - self.assertFalse(artpath.startswith(self.dpath)) + candidate = self.plugin.art_for_album(album, [self.dpath]) + self.assertNotEqual(candidate.path, None) + self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): self.mock_response(self.AMAZON_URL) @@ -182,24 +183,24 @@ class CombinedTest(UseThePlugin): def test_main_interface_uses_caa_when_mbid_available(self): self.mock_response(self.CAA_URL) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, None) - self.assertNotEqual(artpath, None) + candidate = self.plugin.art_for_album(album, None) + self.assertNotEqual(candidate.path, None) self.assertEqual(len(responses.calls), 1) self.assertEqual(responses.calls[0].request.url, self.CAA_URL) def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath], - local_only=True) - self.assertEqual(artpath, None) + candidate = self.plugin.art_for_album(album, [self.dpath], + local_only=True) + self.assertEqual(candidate.path, None) self.assertEqual(len(responses.calls), 0) def test_local_only_gets_fs_image(self): _common.touch(os.path.join(self.dpath, 'art.jpg')) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - artpath = self.plugin.art_for_album(album, [self.dpath], - local_only=True) - self.assertEqual(artpath, os.path.join(self.dpath, 'art.jpg')) + candidate = self.plugin.art_for_album(album, [self.dpath], + local_only=True) + self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) self.assertEqual(len(responses.calls), 0) From 4b4a0e8bd322d2fa777f1d6c2167f469735e4239 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 5 Apr 2016 21:52:30 +0200 Subject: [PATCH 0628/2280] fetchart: Adapt AAOTest, GoogleImageTest --- test/test_art.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 27ee3d6e7..09e940b82 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -211,6 +211,7 @@ class AAOTest(UseThePlugin): def setUp(self): super(AAOTest, self).setUp() self.source = fetchart.AlbumArtOrg(logger, self.plugin.config) + self.extra = dict() @responses.activate def run(self, *args, **kwargs): @@ -230,20 +231,21 @@ class AAOTest(UseThePlugin): """ self.mock_response(self.AAO_URL, body) album = _common.Bag(asin=self.ASIN) - res = self.source.get(album) - self.assertEqual(list(res)[0], 'TARGET_URL') + candidate = next(self.source.get(album, self.extra)) + self.assertEqual(candidate.url, 'TARGET_URL') def test_aao_scraper_returns_no_result_when_no_image_present(self): self.mock_response(self.AAO_URL, b'blah blah') album = _common.Bag(asin=self.ASIN) - res = self.source.get(album) - self.assertEqual(list(res), []) + with assertRaises(StopIteration): + candidate = next(self.source.get(album, self.extra)) class GoogleImageTest(UseThePlugin): def setUp(self): super(GoogleImageTest, self).setUp() self.source = fetchart.GoogleImages(logger, self.plugin.config) + self.extra = dict() @responses.activate def run(self, *args, **kwargs): @@ -257,22 +259,22 @@ class GoogleImageTest(UseThePlugin): album = _common.Bag(albumartist="some artist", album="some album") json = b'{"items": [{"link": "url_to_the_image"}]}' self.mock_response(fetchart.GoogleImages.URL, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url)[0], 'url_to_the_image') + candidate = next(self.source.get(album, self.extra)) + self.assertEqual(candidate.url, 'url_to_the_image') def test_google_art_returns_no_result_when_error_received(self): album = _common.Bag(albumartist="some artist", album="some album") json = b'{"error": {"errors": [{"reason": "some reason"}]}}' self.mock_response(fetchart.GoogleImages.URL, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url), []) + with assertRaises(StopIteration): + candidate = next(self.source.get(album, self.extra)) def test_google_art_returns_no_result_with_malformed_response(self): album = _common.Bag(albumartist="some artist", album="some album") json = b"""bla blup""" self.mock_response(fetchart.GoogleImages.URL, json) - result_url = self.source.get(album) - self.assertEqual(list(result_url), []) + with assertRaises(StopIteration): + candidate = next(self.source.get(album, self.extra)) @_common.slow_test() From 206a88caff310a2c7bc7f81c769e94488847b7ef Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 5 Apr 2016 22:43:17 +0200 Subject: [PATCH 0629/2280] fetchart: Adapt ArtImporterTest --- test/test_art.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 09e940b82..02b8d6287 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -286,7 +286,7 @@ class ArtImporterTest(UseThePlugin): self.art_file = os.path.join(self.temp_dir, 'tmpcover.jpg') _common.touch(self.art_file) self.old_afa = self.plugin.art_for_album - self.afa_response = self.art_file + self.afa_response = fetchart.Candidate(path=self.art_file) def art_for_album(i, p, local_only=False): return self.afa_response @@ -377,7 +377,7 @@ class ArtImporterTest(UseThePlugin): def test_do_not_delete_original_if_already_in_place(self): artdest = os.path.join(os.path.dirname(self.i.path), 'cover.jpg') shutil.copyfile(self.art_file, artdest) - self.afa_response = artdest + self.afa_response = fetchart.Candidate(path=artdest) self._fetch_art(True) def test_fetch_art_if_imported_file_deleted(self): From a2141c6f3abd0a77dba9e2b25e7b58248cde1070 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 5 Apr 2016 22:44:13 +0200 Subject: [PATCH 0630/2280] fetchart: fix refactoring --- beetsplug/fetchart.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 08e8988ff..6f84b37c0 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -626,10 +626,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # For any other choices (e.g., TRACKS), do nothing. return - path = self.art_for_album(task.album, task.paths, local) + candidate = self.art_for_album(task.album, task.paths, local) - if path: - self.art_paths[task] = path + if candidate: + self.art_paths[task] = candidate.path # Synchronous; after music files are put in place. def assign_art(self, session, task): @@ -719,9 +719,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # sources. local_paths = None if force else [album.path] - path = self.art_for_album(album, local_paths) - if path: - album.set_art(path, False) + candidate = self.art_for_album(album, local_paths) + if candidate: + album.set_art(candidate.path, False) album.store() message = ui.colorize('text_success', u'found album art') else: From bbc06e9de9eec6de462e349256c893c6800ac406 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 5 Apr 2016 23:24:30 +0200 Subject: [PATCH 0631/2280] fetchart: Adapt ArtForAlbumTest --- beetsplug/fetchart.py | 2 +- test/test_art.py | 36 +++++++++++------------------------- 2 files changed, 12 insertions(+), 26 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 6f84b37c0..b82b64460 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -179,7 +179,7 @@ class LocalArtSource(ArtSource): LOC_STR = u'local' def fetch_image(self, candidate, extra): - return candidate + pass class RemoteArtSource(ArtSource): IS_LOCAL = False diff --git a/test/test_art.py b/test/test_art.py index 02b8d6287..c71a9a820 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -405,44 +405,30 @@ class ArtForAlbumTest(UseThePlugin): def setUp(self): super(ArtForAlbumTest, self).setUp() - self.old_fs_source_get = self.plugin.fs_source.get - self.old_fetch_img = self.plugin._fetch_image - self.old_source_urls = self.plugin._source_urls + self.old_fs_source_get = fetchart.FileSystem.get - def fs_source_get(*_): - return self.image_file + def fs_source_get(album, paths, *_): + if paths: + yield fetchart.Candidate(path=self.image_file) - def source_urls(_): - return [''] - - def fetch_img(_): - return self.image_file - - self.plugin.fs_source.get = fs_source_get - self.plugin._source_urls = source_urls - self.plugin._fetch_image = fetch_img + fetchart.FileSystem.get = fs_source_get def tearDown(self): - self.plugin.fs_source.get = self.old_fs_source_get - self.plugin._source_urls = self.old_source_urls - self.plugin._fetch_image = self.old_fetch_img + fetchart.FileSystem.get = self.old_fs_source_get super(ArtForAlbumTest, self).tearDown() def _assertImageIsValidArt(self, image_file, should_exist): self.assertExists(image_file) self.image_file = image_file - local_artpath = self.plugin.art_for_album(None, [''], True) - remote_artpath = self.plugin.art_for_album(None, [], False) - - self.assertEqual(local_artpath, remote_artpath) + artpath = self.plugin.art_for_album(None, [''], True).path if should_exist: - self.assertEqual(local_artpath, self.image_file) - self.assertExists(local_artpath) - return local_artpath + self.assertEqual(artpath, self.image_file) + self.assertExists(artpath) + return artpath else: - self.assertIsNone(local_artpath) + self.assertIsNone(artpath) def _assertImageResized(self, image_file, should_resize): self.image_file = image_file From bc877a6d7f286de5b4aeea5026ae1ac53e1013bc Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 6 Apr 2016 01:19:44 +0200 Subject: [PATCH 0632/2280] fetchart: fix tests (mostly pep8, syntax) --- beetsplug/fetchart.py | 44 +++++++++++++++++++----------------- test/test_art.py | 52 ++++++++++++++++++++++--------------------- 2 files changed, 50 insertions(+), 46 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b82b64460..93a703a73 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -41,9 +41,10 @@ IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' -class Candidate(): - """ +class Candidate(): + """Holds information about a matching artwork, deals with validation of + dimension restrictions and resizing. """ CANDIDATE_BAD = 0 CANDIDATE_EXACT = 1 @@ -54,6 +55,7 @@ class Candidate(): def __init__(self, path=None, url=None, source=u'', match=None): self.path = path + self.url = url self.source = source self.check = None self.match = match @@ -70,8 +72,8 @@ class Candidate(): if not self.path: return self.CANDIDATE_BAD - if not (extra['enforce_ratio'] or - extra['minwidth'] or + if not (extra['enforce_ratio'] or + extra['minwidth'] or extra['maxwidth']): return self.CANDIDATE_EXACT @@ -174,12 +176,14 @@ class ArtSource(RequestMixin): def fetch_image(self, candidate, extra): raise NotImplementedError() + class LocalArtSource(ArtSource): IS_LOCAL = True LOC_STR = u'local' def fetch_image(self, candidate, extra): - pass + pass + class RemoteArtSource(ArtSource): IS_LOCAL = False @@ -191,7 +195,7 @@ class RemoteArtSource(ArtSource): Otherwise, returns None. """ if extra['maxwidth']: - candidate.url = ArtResizer.shared.proxy_url(extra['maxwidth'], + candidate.url = ArtResizer.shared.proxy_url(extra['maxwidth'], candidate.url) try: with closing(self.request(candidate.url, stream=True, @@ -203,7 +207,7 @@ class RemoteArtSource(ArtSource): resp.headers.get('Content-Type') or u'no content type', ) candidate.path = None - return + return # Generate a temporary file with the correct extension. with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, @@ -220,7 +224,7 @@ class RemoteArtSource(ArtSource): # https://github.com/shazow/urllib3/issues/556 self._log.debug(u'error fetching art: {}', exc) candidate.path = None - return + return class CoverArtArchive(RemoteArtSource): @@ -237,9 +241,10 @@ class CoverArtArchive(RemoteArtSource): source=u'coverartarchive.org', match=Candidate.MATCH_EXACT) if album.mb_releasegroupid: - yield Candidate(url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), - source=u'coverartarchive.org', - match=Candidate.MATCH_FALLBACK) + yield Candidate( + url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), + source=u'coverartarchive.org', + match=Candidate.MATCH_FALLBACK) class Amazon(RemoteArtSource): @@ -503,7 +508,7 @@ class FileSystem(LocalArtSource): cover_names = extra['cover_names'] cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) cautious = extra['cautious'] - + for path in paths: if not os.path.isdir(path): continue @@ -517,7 +522,7 @@ class FileSystem(LocalArtSource): images.append(fn) # Look for "preferred" filenames. - images = sorted(images, + images = sorted(images, lambda x: self.filename_priority(x, cover_names)) for fn in images: if re.search(cover_pat, os.path.splitext(fn)[0], re.I): @@ -538,7 +543,7 @@ class FileSystem(LocalArtSource): # Try each source in turn. -SOURCES_ALL = [u'filesysytem', +SOURCES_ALL = [u'filesysytem', u'coverart', u'itunes', u'amazon', u'albumart', u'wikipedia', u'google'] @@ -565,10 +570,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'minwidth': 0, 'maxwidth': 0, 'enforce_ratio': False, - 'remote_priority': False, 'cautious': False, 'cover_names': ['cover', 'front', 'art', 'album', 'folder'], - 'sources': ['filesystem', + 'sources': ['filesystem', 'coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', @@ -669,14 +673,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): are made. """ out = None - check = None # all the information any of the sources might need cover_names = self.config['cover_names'].as_str_seq() cover_names = map(util.bytestring_path, cover_names) cautious = self.config['cautious'].get(bool) - extra = {'paths': paths, - 'cover_names': cover_names, + extra = {'paths': paths, + 'cover_names': cover_names, 'cautious': cautious, 'enforce_ratio': self.enforce_ratio, 'minwidth': self.minwidth, @@ -692,7 +695,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # URLs might be invalid at this point, or the image may not # fulfill the requirements for candidate in source.get(album, extra): - source.fetch_image(candidate) + source.fetch_image(candidate, extra) if candidate.validate(extra): out = candidate self._log.debug(u'using {0.LOC_STR()} image {1}' @@ -728,4 +731,3 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): message = ui.colorize('text_error', u'no art found') self._log.info(u'{0}: {1}', album, message) - diff --git a/test/test_art.py b/test/test_art.py index c71a9a820..671dfaeaa 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -45,31 +45,32 @@ class UseThePlugin(_common.TestCase): class FetchImageTest(UseThePlugin): + URL = 'http://example.com' + @responses.activate def run(self, *args, **kwargs): super(FetchImageTest, self).run(*args, **kwargs) def mock_response(self, content_type): - responses.add(responses.GET, 'http://example.com', + responses.add(responses.GET, self.URL, content_type=content_type) def setUp(self): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, 'arttest') - self.candidate = self.plugin.Candidate(url='http://example.com') self.source = self.plugin.RemoteArtSource(logger, self.plugin.config) def test_invalid_type_returns_none(self): self.mock_response('image/watercolour') - self.candidate.path = None + candidate = fetchart.Candidate(url=self.URL) self.source.fetch_image(candidate) - self.assertEqual(self.candidate.path, None) + self.assertEqual(candidate.path, None) def test_jpeg_type_returns_path(self): self.mock_response('image/jpeg') - self.candidate.path = None + candidate = fetchart.Candidate(url=self.URL) self.source.fetch_image(candidate) - self.assertNotEqual(self.candidate.path, None) + self.assertNotEqual(candidate.path, None) class FSArtTest(UseThePlugin): @@ -97,26 +98,26 @@ class FSArtTest(UseThePlugin): def test_non_image_file_not_identified(self): _common.touch(os.path.join(self.dpath, 'a.txt')) with self.assertRaises(StopIteration): - candidate = next(self.source.get(None, self.extra)) + next(self.source.get(None, self.extra)) def test_cautious_skips_fallback(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) self.extra['cautious'] = True with self.assertRaises(StopIteration): - candidate = next(self.source.get(None, self.extra)) + next(self.source.get(None, self.extra)) def test_empty_dir(self): with self.assertRaises(StopIteration): - candidate = next(self.source.get(None, self.extra)) + next(self.source.get(None, self.extra)) def test_precedence_amongst_correct_files(self): - images = ('front-cover.jpg', 'front.jpg', 'back.jpg') - paths = (os.path.join(self.dpath, i) for i in images) + images = ['front-cover.jpg', 'front.jpg', 'back.jpg'] + paths = [os.path.join(self.dpath, i) for i in images] for p in paths: _common.touch(p) - self.extra['cover_names'] = ('cover', 'front', 'back') - candidates = (candidate.path - for candidate in self.source.get(None, self.extra)) + self.extra['cover_names'] = ['cover', 'front', 'back'] + candidates = [candidate.path for candidate in + self.source.get(None, self.extra)] self.assertEqual(candidates, paths) @@ -237,8 +238,8 @@ class AAOTest(UseThePlugin): def test_aao_scraper_returns_no_result_when_no_image_present(self): self.mock_response(self.AAO_URL, b'blah blah') album = _common.Bag(asin=self.ASIN) - with assertRaises(StopIteration): - candidate = next(self.source.get(album, self.extra)) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.extra)) class GoogleImageTest(UseThePlugin): @@ -266,15 +267,15 @@ class GoogleImageTest(UseThePlugin): album = _common.Bag(albumartist="some artist", album="some album") json = b'{"error": {"errors": [{"reason": "some reason"}]}}' self.mock_response(fetchart.GoogleImages.URL, json) - with assertRaises(StopIteration): - candidate = next(self.source.get(album, self.extra)) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.extra)) def test_google_art_returns_no_result_with_malformed_response(self): album = _common.Bag(albumartist="some artist", album="some album") json = b"""bla blup""" self.mock_response(fetchart.GoogleImages.URL, json) - with assertRaises(StopIteration): - candidate = next(self.source.get(album, self.extra)) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.extra)) @_common.slow_test() @@ -421,14 +422,15 @@ class ArtForAlbumTest(UseThePlugin): self.assertExists(image_file) self.image_file = image_file - artpath = self.plugin.art_for_album(None, [''], True).path + candidate = self.plugin.art_for_album(None, [''], True) if should_exist: - self.assertEqual(artpath, self.image_file) - self.assertExists(artpath) - return artpath + self.assertNotEqual(candidate, None) + self.assertEqual(candidate.path, self.image_file) + self.assertExists(candidate.path) + return candidate.path else: - self.assertIsNone(artpath) + self.assertIsNone(candidate) def _assertImageResized(self, image_file, should_resize): self.image_file = image_file From a4994d2bf806aa1efb3ed3141e0d89449061f755 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 6 Apr 2016 01:36:32 +0200 Subject: [PATCH 0633/2280] fetchart: fix more tests --- beetsplug/fetchart.py | 2 +- test/test_art.py | 17 +++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 93a703a73..c70db8f6b 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -698,7 +698,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): source.fetch_image(candidate, extra) if candidate.validate(extra): out = candidate - self._log.debug(u'using {0.LOC_STR()} image {1}' + self._log.debug(u'using {0.LOC_STR} image {1}' .format(source, out.path)) break if out: diff --git a/test/test_art.py b/test/test_art.py index 671dfaeaa..5971fe880 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -58,7 +58,7 @@ class FetchImageTest(UseThePlugin): def setUp(self): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, 'arttest') - self.source = self.plugin.RemoteArtSource(logger, self.plugin.config) + self.source = fetchart.RemoteArtSource(logger, self.plugin.config) def test_invalid_type_returns_none(self): self.mock_response('image/watercolour') @@ -147,25 +147,26 @@ class CombinedTest(UseThePlugin): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) - self.assertNotEqual(candidate.path, None) + self.assertIsNotNone(candidate) def test_main_interface_returns_none_for_missing_asin_and_path(self): album = _common.Bag() candidate = self.plugin.art_for_album(album, None) - self.assertEqual(candidate.path, None) + self.assertIsNotNone(candidate) def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, 'art.jpg')) self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) + self.assertIsNotNone(candidate) self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) def test_main_interface_falls_back_to_amazon(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) - self.assertNotEqual(candidate.path, None) + self.assertIsNotNone(candidate) self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): @@ -185,15 +186,14 @@ class CombinedTest(UseThePlugin): self.mock_response(self.CAA_URL) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) - self.assertNotEqual(candidate.path, None) + self.assertIsNotNone(candidate) self.assertEqual(len(responses.calls), 1) self.assertEqual(responses.calls[0].request.url, self.CAA_URL) def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - candidate = self.plugin.art_for_album(album, [self.dpath], - local_only=True) - self.assertEqual(candidate.path, None) + with self.assertRaises(StopIteration): + self.plugin.art_for_album(album, local_only=True) self.assertEqual(len(responses.calls), 0) def test_local_only_gets_fs_image(self): @@ -201,6 +201,7 @@ class CombinedTest(UseThePlugin): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath], local_only=True) + self.assertIsNotNone(candidate) self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) self.assertEqual(len(responses.calls), 0) From 1cc4d11baf94accbd2391a27130e50852dcec763 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 13 Apr 2016 22:56:18 +0200 Subject: [PATCH 0634/2280] Fetchart: fix tests and fetachart logic --- beetsplug/fetchart.py | 81 +++++++++++++++++++++++-------------------- test/test_art.py | 27 +++++++-------- 2 files changed, 56 insertions(+), 52 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index c70db8f6b..1eb139602 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -53,7 +53,8 @@ class Candidate(): MATCH_EXACT = 0 MATCH_FALLBACK = 1 - def __init__(self, path=None, url=None, source=u'', match=None): + def __init__(self, log, path=None, url=None, source=u'', match=None): + self._log = log self.path = path self.url = url self.source = source @@ -173,6 +174,9 @@ class ArtSource(RequestMixin): def get(self, album, extra): raise NotImplementedError() + def _candidate(self, **kwargs): + return Candidate(source=self.NAME, log=self._log, **kwargs) + def fetch_image(self, candidate, extra): raise NotImplementedError() @@ -228,7 +232,8 @@ class RemoteArtSource(ArtSource): class CoverArtArchive(RemoteArtSource): - """Cover Art Archive""" + NAME = u"Cover Art Archive" + URL = 'http://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' @@ -237,17 +242,16 @@ class CoverArtArchive(RemoteArtSource): using album MusicBrainz release ID and release group ID. """ if album.mb_albumid: - yield Candidate(url=self.URL.format(mbid=album.mb_albumid), - source=u'coverartarchive.org', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=self.URL.format(mbid=album.mb_albumid), + match=Candidate.MATCH_EXACT) if album.mb_releasegroupid: - yield Candidate( + yield self._candidate( url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), - source=u'coverartarchive.org', match=Candidate.MATCH_FALLBACK) class Amazon(RemoteArtSource): + NAME = u"Amazon" URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) @@ -256,13 +260,12 @@ class Amazon(RemoteArtSource): """ if album.asin: for index in self.INDICES: - yield Candidate(url=self.URL % (album.asin, index), - source=u'Amazon', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=self.URL % (album.asin, index), + match=Candidate.MATCH_EXACT) class AlbumArtOrg(RemoteArtSource): - """AlbumArt.org scraper""" + NAME = u"AlbumArt.org scraper" URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' @@ -283,14 +286,13 @@ class AlbumArtOrg(RemoteArtSource): m = re.search(self.PAT, resp.text) if m: image_url = m.group(1) - yield Candidate(url=image_url, - source=u'AlbumArt.org', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=image_url, match=Candidate.MATCH_EXACT) else: self._log.debug(u'no image found on page') class GoogleImages(RemoteArtSource): + NAME = u"Google Images" URL = u'https://www.googleapis.com/customsearch/v1' def get(self, album, extra): @@ -322,13 +324,13 @@ class GoogleImages(RemoteArtSource): if 'items' in data.keys(): for item in data['items']: - yield Candidate(url=item['link'], - source=u'Google images', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=item['link'], + match=Candidate.MATCH_EXACT) class ITunesStore(RemoteArtSource): - # Art from the iTunes Store. + NAME = u"iTunes Store" + def get(self, album, extra): """Return art URL from iTunes Store given an album title. """ @@ -354,9 +356,7 @@ class ITunesStore(RemoteArtSource): if itunes_album.get_artwork()['100']: small_url = itunes_album.get_artwork()['100'] big_url = small_url.replace('100x100', '1200x1200') - yield Candidate(url=big_url, - source=u'iTunes Store', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=big_url, match=Candidate.MATCH_EXACT) else: self._log.debug(u'album has no artwork in iTunes Store') except IndexError: @@ -364,7 +364,7 @@ class ITunesStore(RemoteArtSource): class Wikipedia(RemoteArtSource): - # Art from Wikipedia (queried through DBpedia) + NAME = u"Wikipedia (queried through DBpedia)" DBPEDIA_URL = 'http://dbpedia.org/sparql' WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' SPARQL_QUERY = '''PREFIX rdf: @@ -481,16 +481,16 @@ class Wikipedia(RemoteArtSource): results = data['query']['pages'] for _, result in results.iteritems(): image_url = result['imageinfo'][0]['url'] - yield Candidate(url=image_url, - source=u'Wikipedia', - match=Candidate.MATCH_EXACT) + yield self._candidate(url=image_url, + match=Candidate.MATCH_EXACT) except (ValueError, KeyError, IndexError): self._log.debug(u'wikipedia: error scraping imageinfo') return class FileSystem(LocalArtSource): - """Art from the filesystem""" + NAME = u"Filesystem" + @staticmethod def filename_priority(filename, cover_names): """Sort order for image names. @@ -505,6 +505,8 @@ class FileSystem(LocalArtSource): """Look for album art files in the specified directories. """ paths = extra['paths'] + if not paths: + return cover_names = extra['cover_names'] cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) cautious = extra['cautious'] @@ -523,27 +525,29 @@ class FileSystem(LocalArtSource): # Look for "preferred" filenames. images = sorted(images, - lambda x: self.filename_priority(x, cover_names)) + key=lambda x: + self.filename_priority(x, cover_names)) + remaining = [] for fn in images: if re.search(cover_pat, os.path.splitext(fn)[0], re.I): self._log.debug(u'using well-named art file {0}', util.displayable_path(fn)) - yield Candidate(path=os.path.join(path, fn), - source=u'Filesystem', - match=Candidate.MATCH_EXACT) + yield self._candidate(path=os.path.join(path, fn), + match=Candidate.MATCH_EXACT) + else: + remaining.append(fn) # Fall back to any image in the folder. - if images and not cautious: + if remaining and not cautious: self._log.debug(u'using fallback art file {0}', - util.displayable_path(images[0])) - yield Candidate(path=os.path.join(path, images[0]), - source=u'Filesystem', - match=Candidate.MATCH_FALLBACK) + util.displayable_path(remaining[0])) + yield self._candidate(path=os.path.join(path, remaining[0]), + match=Candidate.MATCH_FALLBACK) # Try each source in turn. -SOURCES_ALL = [u'filesysytem', +SOURCES_ALL = [u'filesystem', u'coverart', u'itunes', u'amazon', u'albumart', u'wikipedia', u'google'] @@ -698,8 +702,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): source.fetch_image(candidate, extra) if candidate.validate(extra): out = candidate - self._log.debug(u'using {0.LOC_STR} image {1}' - .format(source, out.path)) + self._log.debug( + u'using {0.LOC_STR} image {1}'.format( + source, util.displayable_path(out.path))) break if out: break diff --git a/test/test_art.py b/test/test_art.py index 5971fe880..2edea0c69 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -59,17 +59,18 @@ class FetchImageTest(UseThePlugin): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, 'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) + self.extra = {'maxwidth': 0} def test_invalid_type_returns_none(self): self.mock_response('image/watercolour') - candidate = fetchart.Candidate(url=self.URL) - self.source.fetch_image(candidate) + candidate = fetchart.Candidate(logger, url=self.URL) + self.source.fetch_image(candidate, self.extra) self.assertEqual(candidate.path, None) def test_jpeg_type_returns_path(self): self.mock_response('image/jpeg') - candidate = fetchart.Candidate(url=self.URL) - self.source.fetch_image(candidate) + candidate = fetchart.Candidate(logger, url=self.URL) + self.source.fetch_image(candidate, self.extra) self.assertNotEqual(candidate.path, None) @@ -82,7 +83,7 @@ class FSArtTest(UseThePlugin): self.source = fetchart.FileSystem(logger, self.plugin.config) self.extra = {'cautious': False, 'cover_names': ('art',), - 'paths': self.dpath} + 'paths': [self.dpath]} def test_finds_jpg_in_directory(self): _common.touch(os.path.join(self.dpath, 'a.jpg')) @@ -152,7 +153,7 @@ class CombinedTest(UseThePlugin): def test_main_interface_returns_none_for_missing_asin_and_path(self): album = _common.Bag() candidate = self.plugin.art_for_album(album, None) - self.assertIsNotNone(candidate) + self.assertIsNone(candidate) def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, 'art.jpg')) @@ -192,8 +193,7 @@ class CombinedTest(UseThePlugin): def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) - with self.assertRaises(StopIteration): - self.plugin.art_for_album(album, local_only=True) + self.plugin.art_for_album(album, None, local_only=True) self.assertEqual(len(responses.calls), 0) def test_local_only_gets_fs_image(self): @@ -288,7 +288,7 @@ class ArtImporterTest(UseThePlugin): self.art_file = os.path.join(self.temp_dir, 'tmpcover.jpg') _common.touch(self.art_file) self.old_afa = self.plugin.art_for_album - self.afa_response = fetchart.Candidate(path=self.art_file) + self.afa_response = fetchart.Candidate(logger, path=self.art_file) def art_for_album(i, p, local_only=False): return self.afa_response @@ -379,7 +379,7 @@ class ArtImporterTest(UseThePlugin): def test_do_not_delete_original_if_already_in_place(self): artdest = os.path.join(os.path.dirname(self.i.path), 'cover.jpg') shutil.copyfile(self.art_file, artdest) - self.afa_response = fetchart.Candidate(path=artdest) + self.afa_response = fetchart.Candidate(logger, path=artdest) self._fetch_art(True) def test_fetch_art_if_imported_file_deleted(self): @@ -409,9 +409,9 @@ class ArtForAlbumTest(UseThePlugin): self.old_fs_source_get = fetchart.FileSystem.get - def fs_source_get(album, paths, *_): - if paths: - yield fetchart.Candidate(path=self.image_file) + def fs_source_get(_self, album, extra): + if extra['paths']: + yield fetchart.Candidate(logger, path=self.image_file) fetchart.FileSystem.get = fs_source_get @@ -429,7 +429,6 @@ class ArtForAlbumTest(UseThePlugin): self.assertNotEqual(candidate, None) self.assertEqual(candidate.path, self.image_file) self.assertExists(candidate.path) - return candidate.path else: self.assertIsNone(candidate) From d67950cdccfd2362c5bdbe9f1dd7e42ab3d7ef67 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 00:45:55 +0200 Subject: [PATCH 0635/2280] pep8 --- beetsplug/lyrics.py | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 207b9d084..c766db2a7 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -13,18 +13,15 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""Fetches, embeds, and displays lyrics. -""" +from __future__ import absolute_import, division, print_function -from __future__ import division, absolute_import, print_function - -import re -import requests -import json -import unicodedata -import urllib import difflib import itertools +import json +import re +import requests +import unicodedata +import urllib import warnings from HTMLParser import HTMLParseError @@ -56,7 +53,7 @@ URL_CHARACTERS = { def unescape(text): - """Resolves &#xxx; HTML entities (and some others).""" + """Resolve &#xxx; HTML entities (and some others).""" if isinstance(text, bytes): text = text.decode('utf8', 'ignore') out = text.replace(u' ', u' ') @@ -455,29 +452,29 @@ class Google(Backend): """ if not text: return False - badTriggersOcc = [] - nbLines = text.count('\n') - if nbLines <= 1: + bad_triggers_occ = [] + nb_lines = text.count('\n') + if nb_lines <= 1: self._log.debug(u"Ignoring too short lyrics '{0}'", text) return False - elif nbLines < 5: - badTriggersOcc.append('too_short') + elif nb_lines < 5: + bad_triggers_occ.append('too_short') else: # Lyrics look legit, remove credits to avoid being penalized # further down text = remove_credits(text) - badTriggers = ['lyrics', 'copyright', 'property', 'links'] + bad_triggers = ['lyrics', 'copyright', 'property', 'links'] if artist: - badTriggersOcc += [artist] + bad_triggers_occ += [artist] - for item in badTriggers: - badTriggersOcc += [item] * len(re.findall(r'\W%s\W' % item, - text, re.I)) + for item in bad_triggers: + bad_triggers_occ += [item] * len(re.findall(r'\W%s\W' % item, + text, re.I)) - if badTriggersOcc: - self._log.debug(u'Bad triggers detected: {0}', badTriggersOcc) - return len(badTriggersOcc) < 2 + if bad_triggers_occ: + self._log.debug(u'Bad triggers detected: {0}', bad_triggers_occ) + return len(bad_triggers_occ) < 2 def slugify(self, text): """Normalize a string and remove non-alphanumeric characters. From 3c2479ab4904c566ca978c35bb073a577c73b3a6 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 00:53:58 +0200 Subject: [PATCH 0636/2280] translate lyrics using Bing API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit By subscribing to Microsoft Translator API, one can now activate the translation of lyrics from one set of source langages to a target langage. Translations are appended to each original sentence using ‘/‘ as separator. --- beetsplug/lyrics.py | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c766db2a7..7b3f93671 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -24,6 +24,7 @@ import unicodedata import urllib import warnings from HTMLParser import HTMLParseError +from langdetect import detect from beets import plugins from beets import ui @@ -567,6 +568,9 @@ class LyricsPlugin(plugins.BeetsPlugin): self.import_stages = [self.imported] self.config.add({ 'auto': True, + 'bing_client_secret': None, + 'bing_lang_from': [], + 'bing_lang_to': None, 'google_API_key': None, 'google_engine_ID': u'009217259823014548361:lndtuqkycfu', 'genius_api_key': @@ -576,6 +580,7 @@ class LyricsPlugin(plugins.BeetsPlugin): 'force': False, 'sources': self.SOURCES, }) + self.config['bing_client_secret'].redact = True self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True self.config['genius_api_key'].redact = True @@ -589,6 +594,27 @@ class LyricsPlugin(plugins.BeetsPlugin): self.backends = [self.SOURCE_BACKENDS[key](self.config, self._log) for key in self.config['sources'].as_str_seq()] + self.config['bing_lang_from'] = [ + x.lower() for x in self.config['bing_lang_from'].as_str_seq()] + self.bing_auth_token = None + + def get_bing_access_token(self): + params = { + 'client_id': 'beets', + 'client_secret': self.config['bing_client_secret'], + 'scope': 'http://api.microsofttranslator.com', + 'grant_type': 'client_credentials', + } + + oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13' + oauth_token = json.loads(requests.post( + oauth_url, + data=urllib.urlencode(params)).content) + if 'access_token' in oauth_token: + return "Bearer " + oauth_token['access_token'] + else: + self._log.warning(u'Could not get Bing Translate API access token. ' + u'Check your "bing_client_secret" password') def commands(self): cmd = ui.Subcommand('lyrics', help='fetch song lyrics') @@ -644,6 +670,15 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) + lang_lyrics = detect(lyrics) + + if self.config['bing_client_secret'].get() and \ + self.config['bing_lang_to']: + if not self.config['bing_lang_from'] or ( + lang_lyrics in self.config[ + 'bing_lang_from'].as_str_seq()): + lyrics = self.append_translation( + lyrics, self.config['bing_lang_to']) else: self._log.info(u'lyrics not found: {0}', item) fallback = self.config['fallback'].get() @@ -668,3 +703,24 @@ class LyricsPlugin(plugins.BeetsPlugin): self._log.debug(u'got lyrics from backend: {0}', backend.__class__.__name__) return _scrape_strip_cruft(lyrics, True) + + def append_translation(self, text, to_language): + import xml.etree.ElementTree as ET + + if not self.bing_auth_token: + self.bing_auth_token = self.get_bing_access_token() + if self.bing_auth_token: + headers = {"Authorization ": self.bing_auth_token} + url = ('http://api.microsofttranslator.com/v2/Http.svc/' + 'Translate?text=%s&to=%s' % (text.replace('\n', '|'), + to_language)) + r = requests.get(url, headers=headers) + if r.status_code != 200: + self._log.debug(r.text) + return text + translation = ET.fromstring(r.text.encode('utf8')).text + result = '' + for (orig, translated) in zip(text.split('\n'), + translation.split('|')): + result += '%s / %s\n' % (orig, translated) + return result From 6d90dfea2486b30800efd9418c5392406424e366 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 00:54:26 +0200 Subject: [PATCH 0637/2280] add doc for bing translate api related options --- docs/plugins/lyrics.rst | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 0d504733f..c13b02241 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -38,6 +38,14 @@ configuration file. The available options are: - **auto**: Fetch lyrics automatically during import. Default: ``yes``. +- **bing_client_secret**: Your Bing Translation application password (to enable + on-the-fly translating) +- **bing_lang_from**: By default all lyrics with a language other than + ``bing_lang_to`` are translated. Use a list of lang codes to restrict the set + of source languages to translate. + Default: ``[]`` +- **bing_lang_to**: Language to translate lyrics into. + Default: None. - **fallback**: By default, the file will be left unchanged when no lyrics are found. Use the empty string ``''`` to reset the lyrics in such a case. Default: None. @@ -113,3 +121,19 @@ After that, the lyrics plugin will fall back on other declared data sources. .. _pip: http://www.pip-installer.org/ .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ + +Activate on-the-fly translation +------------------------------- + +Using the Bing Translation API requires `langdetect`_, which you can install +using `pip`_ by typing:: + + pip install langdetect + +You also need to register for a Microsoft Azure Marketplace free account and +to the `Microsoft Translator API`_. +Set the ``bing_client_secret`` configuration option to your registered +application password, alongside ``bing_lang_to`` target `language code`_. + +.. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx +.. _language code: https://msdn.microsoft.com/en-us/library/hh456380.aspx From 66a627fed8a2c148cd10433e60ff71a27029c0d4 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 00:58:42 +0200 Subject: [PATCH 0638/2280] restore module docstring --- beetsplug/lyrics.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7b3f93671..b039bb986 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -13,6 +13,9 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""Fetches, embeds, and displays lyrics. +""" + from __future__ import absolute_import, division, print_function import difflib From e03c3af91f0ee09af42b4b73e3de8057c9c8032a Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 01:11:14 +0200 Subject: [PATCH 0639/2280] don't translate lyrics already in the target language --- beetsplug/lyrics.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b039bb986..b18e715d8 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -673,12 +673,11 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) - lang_lyrics = detect(lyrics) - + lang_from = detect(lyrics) if self.config['bing_client_secret'].get() and \ - self.config['bing_lang_to']: + self.config['bing_lang_to'].get() != lang_from: if not self.config['bing_lang_from'] or ( - lang_lyrics in self.config[ + lang_from in self.config[ 'bing_lang_from'].as_str_seq()): lyrics = self.append_translation( lyrics, self.config['bing_lang_to']) @@ -689,9 +688,7 @@ class LyricsPlugin(plugins.BeetsPlugin): lyrics = fallback else: return - item.lyrics = lyrics - if write: item.try_write() item.store() From 58df77e2cb6dc9bbaabea017d0b9b93809efbbd5 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 08:31:14 +0200 Subject: [PATCH 0640/2280] langdetect conditional import --- beetsplug/lyrics.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b18e715d8..40154cefd 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -27,7 +27,6 @@ import unicodedata import urllib import warnings from HTMLParser import HTMLParseError -from langdetect import detect from beets import plugins from beets import ui @@ -673,12 +672,14 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) - lang_from = detect(lyrics) - if self.config['bing_client_secret'].get() and \ - self.config['bing_lang_to'].get() != lang_from: - if not self.config['bing_lang_from'] or ( + if self.config['bing_client_secret'].get(): + from langdetect import detect + + lang_from = detect(lyrics) + if self.config['bing_lang_to'].get() != lang_from and ( + not self.config['bing_lang_from'] or ( lang_from in self.config[ - 'bing_lang_from'].as_str_seq()): + 'bing_lang_from'].as_str_seq())): lyrics = self.append_translation( lyrics, self.config['bing_lang_to']) else: From 6cfc106b8a4b83e76634eec7fd6cb848fd75b2cc Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 08:31:55 +0200 Subject: [PATCH 0641/2280] better docs and debug msg --- beetsplug/lyrics.py | 4 +++- docs/plugins/lyrics.rst | 15 +++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 40154cefd..7de1c3d76 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -692,6 +692,7 @@ class LyricsPlugin(plugins.BeetsPlugin): item.lyrics = lyrics if write: item.try_write() + print(lyrics) item.store() def get_lyrics(self, artist, title): @@ -717,7 +718,8 @@ class LyricsPlugin(plugins.BeetsPlugin): to_language)) r = requests.get(url, headers=headers) if r.status_code != 200: - self._log.debug(r.text) + self._log.debug('translation API error {}: {}', r.status_code, + r.text) return text translation = ET.fromstring(r.text.encode('utf8')).text result = '' diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index c13b02241..e3fa0cc53 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -38,8 +38,8 @@ configuration file. The available options are: - **auto**: Fetch lyrics automatically during import. Default: ``yes``. -- **bing_client_secret**: Your Bing Translation application password (to enable - on-the-fly translating) +- **bing_client_secret**: Your `Bing Translation application password`_ + (to :ref:`lyrics-translation`) - **bing_lang_from**: By default all lyrics with a language other than ``bing_lang_to`` are translated. Use a list of lang codes to restrict the set of source languages to translate. @@ -122,7 +122,9 @@ After that, the lyrics plugin will fall back on other declared data sources. .. _pip: http://www.pip-installer.org/ .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ -Activate on-the-fly translation +.. _lyrics-translation: + +Activate On-the-Fly Translation ------------------------------- Using the Bing Translation API requires `langdetect`_, which you can install @@ -131,9 +133,10 @@ using `pip`_ by typing:: pip install langdetect You also need to register for a Microsoft Azure Marketplace free account and -to the `Microsoft Translator API`_. -Set the ``bing_client_secret`` configuration option to your registered -application password, alongside ``bing_lang_to`` target `language code`_. +to the `Microsoft Translator API`_. Follow the four steps process, specifically +at step 3 enter `beets`` as *Client ID* and copy the generated *Client secret*. +Paste it into your ``bing_client_secret`` configuration, alongside +``bing_lang_to`` target `language code`_. .. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx .. _language code: https://msdn.microsoft.com/en-us/library/hh456380.aspx From df46ae6d4d2b909519a7232964498c3cc1cfe394 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 08:38:53 +0200 Subject: [PATCH 0642/2280] fix docs missing target link --- docs/plugins/lyrics.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index e3fa0cc53..da10bf8f9 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -38,7 +38,7 @@ configuration file. The available options are: - **auto**: Fetch lyrics automatically during import. Default: ``yes``. -- **bing_client_secret**: Your `Bing Translation application password`_ +- **bing_client_secret**: Your Bing Translation application password (to :ref:`lyrics-translation`) - **bing_lang_from**: By default all lyrics with a language other than ``bing_lang_to`` are translated. Use a list of lang codes to restrict the set From d40a168b5bc699d436e7adb19064aa1265aa64f3 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 08:51:24 +0200 Subject: [PATCH 0643/2280] docs: add langdetect pypi links --- docs/plugins/lyrics.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index da10bf8f9..5cdc3f1c7 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -138,5 +138,6 @@ at step 3 enter `beets`` as *Client ID* and copy the generated *Client secret*. Paste it into your ``bing_client_secret`` configuration, alongside ``bing_lang_to`` target `language code`_. +.. _langdetect: https://pypi.python.org/pypi/langdetect .. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx .. _language code: https://msdn.microsoft.com/en-us/library/hh456380.aspx From de3e91db87a1bf5a1bfef0c39c392ad8c89b333b Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 15:25:10 +0200 Subject: [PATCH 0644/2280] fetchart: fix tests providing album=None --- test/test_art.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 2edea0c69..b81c5ea6d 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -415,6 +415,8 @@ class ArtForAlbumTest(UseThePlugin): fetchart.FileSystem.get = fs_source_get + self.album = _common.Bag() + def tearDown(self): fetchart.FileSystem.get = self.old_fs_source_get super(ArtForAlbumTest, self).tearDown() @@ -423,7 +425,7 @@ class ArtForAlbumTest(UseThePlugin): self.assertExists(image_file) self.image_file = image_file - candidate = self.plugin.art_for_album(None, [''], True) + candidate = self.plugin.art_for_album(self.album, [''], True) if should_exist: self.assertNotEqual(candidate, None) @@ -435,7 +437,7 @@ class ArtForAlbumTest(UseThePlugin): def _assertImageResized(self, image_file, should_resize): self.image_file = image_file with patch.object(ArtResizer.shared, 'resize') as mock_resize: - self.plugin.art_for_album(None, [''], True) + self.plugin.art_for_album(self.album, [''], True) self.assertEqual(mock_resize.called, should_resize) def _require_backend(self): From 6bc3fb8f679234c85b28e47f0471328208f38784 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 15:27:47 +0200 Subject: [PATCH 0645/2280] fetchart: make Candidate a new-style class --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 1eb139602..0b020c8f1 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -42,7 +42,7 @@ CONTENT_TYPES = ('image/jpeg', 'image/png') DOWNLOAD_EXTENSION = '.jpg' -class Candidate(): +class Candidate(object): """Holds information about a matching artwork, deals with validation of dimension restrictions and resizing. """ From aaf614c869342cbf5db5c76bedc8b4b48e26b67b Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 16:00:24 +0200 Subject: [PATCH 0646/2280] fetchart: move config reads to __init__ --- beetsplug/fetchart.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 0b020c8f1..89ce8fe39 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -295,6 +295,11 @@ class GoogleImages(RemoteArtSource): NAME = u"Google Images" URL = u'https://www.googleapis.com/customsearch/v1' + def __init__(self, *args, **kwargs): + super(RemoteArtSource, self).__init__(*args, **kwargs) + self.key: self._config['google_key'].get(), + self.cx: self._config['google_engine'].get(), + def get(self, album, extra): """Return art URL from google custom search engine given an album title and interpreter. @@ -303,8 +308,8 @@ class GoogleImages(RemoteArtSource): return search_string = (album.albumartist + ',' + album.album).encode('utf-8') response = self.request(self.URL, params={ - 'key': self._config['google_key'].get(), - 'cx': self._config['google_engine'].get(), + 'key': self.key, + 'cx': self.cx, 'q': search_string, 'searchType': 'image' }) @@ -591,6 +596,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self.maxwidth = self.config['maxwidth'].get(int) self.enforce_ratio = self.config['enforce_ratio'].get(bool) + cover_names = self.config['cover_names'].as_str_seq() + self.cover_names = map(util.bytestring_path, cover_names) + self.cautious = self.config['cautious'].get(bool) + + self.src_removed = (config['import']['delete'].get(bool) or + config['import']['move'].get(bool)) + if self.config['auto']: # Enable two import hooks when fetching is enabled. self.import_stages = [self.fetch_art] @@ -646,11 +658,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): path = self.art_paths.pop(task) album = task.album - src_removed = (config['import']['delete'].get(bool) or - config['import']['move'].get(bool)) - album.set_art(path, not src_removed) + album.set_art(path, not self.src_removed) album.store() - if src_removed: + if self.src_removed: task.prune(path) # Manual album art fetching. @@ -679,12 +689,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): out = None # all the information any of the sources might need - cover_names = self.config['cover_names'].as_str_seq() - cover_names = map(util.bytestring_path, cover_names) - cautious = self.config['cautious'].get(bool) extra = {'paths': paths, - 'cover_names': cover_names, - 'cautious': cautious, + 'cover_names': self.cover_names, + 'cautious': self.cautious, 'enforce_ratio': self.enforce_ratio, 'minwidth': self.minwidth, 'maxwidth': self.maxwidth} From 7322e212a404d5b90a620f7c49a5ed9e7625d14f Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 16:49:06 +0200 Subject: [PATCH 0647/2280] fetchart: adapt test to earlier config read --- beetsplug/fetchart.py | 4 ++-- test/test_art.py | 7 +------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 89ce8fe39..60d883b73 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -297,8 +297,8 @@ class GoogleImages(RemoteArtSource): def __init__(self, *args, **kwargs): super(RemoteArtSource, self).__init__(*args, **kwargs) - self.key: self._config['google_key'].get(), - self.cx: self._config['google_engine'].get(), + self.key = self._config['google_key'].get(), + self.cx = self._config['google_engine'].get(), def get(self, album, extra): """Return art URL from google custom search engine diff --git a/test/test_art.py b/test/test_art.py index b81c5ea6d..9cf8bd18e 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -367,12 +367,7 @@ class ArtImporterTest(UseThePlugin): self.assertExists(self.art_file) def test_delete_original_file(self): - config['import']['delete'] = True - self._fetch_art(True) - self.assertNotExists(self.art_file) - - def test_move_original_file(self): - config['import']['move'] = True + self.plugin.src_removed = True self._fetch_art(True) self.assertNotExists(self.art_file) From 98d5aa4a1341b88bb139ca78e7b53e6cdf4a3173 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 16:56:45 +0200 Subject: [PATCH 0648/2280] fetchart: remove unused import --- test/test_art.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/test_art.py b/test/test_art.py index 9cf8bd18e..a25c82486 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -29,7 +29,6 @@ from beetsplug import fetchart from beets.autotag import AlbumInfo, AlbumMatch from beets import library from beets import importer -from beets import config from beets import logging from beets import util from beets.util.artresizer import ArtResizer, WEBPROXY From 0346be701ea4f7ec48ca858bd3bf62d2b4b90008 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 14 Apr 2016 17:14:49 +0200 Subject: [PATCH 0649/2280] list skipped tests when running nosetests --- tox.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index af245bf8f..d220f1895 100644 --- a/tox.ini +++ b/tox.ini @@ -12,6 +12,7 @@ deps = flask mock nose + nose-show-skipped pyechonest pylast rarfile @@ -29,7 +30,7 @@ deps = {[testenv]deps} coverage commands = - nosetests --with-coverage {posargs} + nosetests --show-skipped --with-coverage {posargs} [testenv:py27setup] basepython = python2.7 From 56d7e5dfa0f1ba232bbcc64556597e6c3f769878 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 22:57:17 +0200 Subject: [PATCH 0650/2280] send as little text as possible to bing api MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bing API has a limit of 2M chars/month. It’s common to have repeating sentences in lyrics so to reduce number of chars sent per song, store sentences in a set and send it, instead of sending the whole lyrics. --- beetsplug/lyrics.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7de1c3d76..13184f4fe 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -615,8 +615,8 @@ class LyricsPlugin(plugins.BeetsPlugin): if 'access_token' in oauth_token: return "Bearer " + oauth_token['access_token'] else: - self._log.warning(u'Could not get Bing Translate API access token. ' - u'Check your "bing_client_secret" password') + self._log.warning(u'Could not get Bing Translate API access token.' + u' Check your "bing_client_secret" password') def commands(self): cmd = ui.Subcommand('lyrics', help='fetch song lyrics') @@ -706,24 +706,26 @@ class LyricsPlugin(plugins.BeetsPlugin): backend.__class__.__name__) return _scrape_strip_cruft(lyrics, True) - def append_translation(self, text, to_language): + def append_translation(self, text, to_lang): import xml.etree.ElementTree as ET if not self.bing_auth_token: self.bing_auth_token = self.get_bing_access_token() if self.bing_auth_token: - headers = {"Authorization ": self.bing_auth_token} + # Extract unique lines to limit API request size per song + text_lines = set(text.split('\n')) url = ('http://api.microsofttranslator.com/v2/Http.svc/' - 'Translate?text=%s&to=%s' % (text.replace('\n', '|'), - to_language)) - r = requests.get(url, headers=headers) + 'Translate?text=%s&to=%s' % ('|'.join(text_lines), to_lang)) + r = requests.get(url, + headers={"Authorization ": self.bing_auth_token}) if r.status_code != 200: self._log.debug('translation API error {}: {}', r.status_code, r.text) return text - translation = ET.fromstring(r.text.encode('utf8')).text + lines_translated = ET.fromstring(r.text.encode('utf8')).text + # Use a translation mapping dict to build resulting lyrics + translations = dict(zip(text_lines, lines_translated.split('|'))) result = '' - for (orig, translated) in zip(text.split('\n'), - translation.split('|')): - result += '%s / %s\n' % (orig, translated) + for line in text.split('\n'): + result += '%s / %s\n' % (line, translations[line]) return result From 05970e8a9391a2f8262738fc60a6ff8df9f6f53f Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 22:57:41 +0200 Subject: [PATCH 0651/2280] re-query token when it has expired --- beetsplug/lyrics.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 13184f4fe..6a6bc7729 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -721,6 +721,9 @@ class LyricsPlugin(plugins.BeetsPlugin): if r.status_code != 200: self._log.debug('translation API error {}: {}', r.status_code, r.text) + if 'token has expired' in r.text: + self.bing_auth_token = None + return self.append_translation(text, to_lang) return text lines_translated = ET.fromstring(r.text.encode('utf8')).text # Use a translation mapping dict to build resulting lyrics From 95b77bf5d07ae84ac6b5e36f9b1afd5e1f1c59ea Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Thu, 14 Apr 2016 23:24:16 +0200 Subject: [PATCH 0652/2280] lyrics: update docs + changelog --- docs/changelog.rst | 3 +++ docs/plugins/lyrics.rst | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 67960d56f..81078950e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,9 @@ New features: art while copying it. * :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option lets you preserve mtime of files after each write. +* :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to a + configured `bing_lang_to` langage. Enabling translation require to register + for a Microsoft Azure Marketplace free account. Thanks to :user:`Kraymer`. Fixes: diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 5cdc3f1c7..b922b747f 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -134,8 +134,8 @@ using `pip`_ by typing:: You also need to register for a Microsoft Azure Marketplace free account and to the `Microsoft Translator API`_. Follow the four steps process, specifically -at step 3 enter `beets`` as *Client ID* and copy the generated *Client secret*. -Paste it into your ``bing_client_secret`` configuration, alongside +at step 3 enter `beets`` as *Client ID* and copy/paste the generated +*Client secret*. into your ``bing_client_secret`` configuration, alongside ``bing_lang_to`` target `language code`_. .. _langdetect: https://pypi.python.org/pypi/langdetect From ecc6e1c3d6698f800527a9040aecc2d7da1fb712 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Mar 2016 14:47:09 +0100 Subject: [PATCH 0653/2280] fanart.tv albumart fetching, missing a project API key --- beetsplug/fetchart.py | 77 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index ad51bb995..61bff901f 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -192,6 +192,68 @@ class GoogleImages(ArtSource): yield item['link'] +class FanartTV(ArtSource): + """Art from fanart.tv requested using their API""" + API_URL = 'http://webservice.fanart.tv/v3/' + API_ALBUMS = API_URL + 'music/albums/' + + def get(self, album): + if not album.mb_releasegroupid: + return + + response = self.request( + self.API_ALBUMS + album.mb_releasegroupid, + headers={ + 'api-key': self._config['fanarttv_api_key'].get(), + 'client-key': self._config['fanarttv_personal_key'].get() + }) + + try: + data = response.json() + except ValueError: + self._log.debug(u'fanart.tv: error loading response: {}', + response.text) + return + + def escapeforlog(s): + # the logger will eventually try to .format() the message, and + # interpret the dict as format spec... + r = [] + for c in s: + if c in ['{', '}']: + r.append(c) + r.append(c) + return ''.join(r) + self._log.debug(escapeforlog(str(data))) + + if u'status' in data and data[u'status'] == u'error': + if u'not found' in data[u'error message'].lower(): + self._log.debug(u'fanart.tv: no image found') + elif u'api key' in data[u'error message'].lower(): + self._log.warning(u'fanart.tv: Invalid API key given, please ' + u'enter a valid one in your config file.') + else: + self._log.debug(u'fanart.tv: error on request: {}', + data[u'error message']) + return + + matches = [] + # can there be more than one releasegroupid per responce? + for mb_releasegroupid in data.get(u'albums', dict()): + if album.mb_releasegroupid == mb_releasegroupid: + # note: there might be more art referenced, e.g. cdart + matches.extend( + data[u'albums'][mb_releasegroupid][u'albumcover']) + # can this actually occur? + else: + self._log.debug(u'fanart.tv: unexpected mb_releasegroupid in ' + u'response!') + + matches.sort(key=lambda x: x[u'likes'], reverse=True) + for item in matches: + yield item[u'url'] + + class ITunesStore(ArtSource): # Art from the iTunes Store. def get(self, album): @@ -351,7 +413,7 @@ class Wikipedia(ArtSource): class FileSystem(ArtSource): - """Art from the filesystem""" + """Art from the fileszystem""" @staticmethod def filename_priority(filename, cover_names): """Sort order for image names. @@ -396,7 +458,7 @@ class FileSystem(ArtSource): # Try each source in turn. SOURCES_ALL = [u'coverart', u'itunes', u'amazon', u'albumart', - u'wikipedia', u'google'] + u'wikipedia', u'google', u'fanarttv'] ART_SOURCES = { u'coverart': CoverArtArchive, @@ -405,6 +467,7 @@ ART_SOURCES = { u'amazon': Amazon, u'wikipedia': Wikipedia, u'google': GoogleImages, + u'fanarttv': FanartTV, } # PLUGIN LOGIC ############################################################### @@ -425,8 +488,11 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', + 'fanarttv_api_key': None, + 'fanarttv_personal_key': None }) self.config['google_key'].redact = True + self.config['fanarttv_personal_key'].redact = True # Holds paths to downloaded images between fetching them and # placing them in the filesystem. @@ -447,6 +513,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') + if not self.config['fanarttv_personal_key'].get() and \ + u'fanarttv' in available_sources: + self._log.warn( + u'fanart.tv source enabled, but no personal API given. This ' + u'works as of now, however, fanart.tv prefers users to ' + u'register a personal key. Additionaly this makes new art ' + u'available shorter after its upload. See the documentation.') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) self.sources = [ART_SOURCES[s](self._log, self.config) From 8a8b8f832a52fc13bd0a9bc05e2f80e462b7ed5d Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 02:23:22 +0200 Subject: [PATCH 0654/2280] Update Documentation for fanart.tv --- docs/plugins/fetchart.rst | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index e53dbc219..24a67ded6 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -50,13 +50,15 @@ file. The available options are: - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. Default: ``coverart itunes amazon albumart``, i.e., everything but - ``wikipedia`` and ``google``. Enable those two sources for more matches at - the cost of some speed. + ``wikipedia``, ``google`` and ``fanarttv``. Enable those sources for more + matches at the cost of some speed. - **google_key**: Your Google API key (to enable the Google Custom Search backend). Default: None. - **google_engine**: The custom search engine to use. Default: The `beets custom search engine`_, which searches the entire web. + **fanarttv_personal_key**: The personal API key for requesting art from + fanart.tv. See below. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ or `Pillow`_. @@ -162,6 +164,21 @@ default engine searches the entire web for cover art. Note that the Google custom search API is limited to 100 queries per day. After that, the fetchart plugin will fall back on other declared data sources. +Fanart.tv +......... + +Although not strictly necesarry right now, you might think about +`registering a personal fanart.tv API key`_. Set the ``fanarttv_personal_key`` +configurati option to your key, then add ``fanarttv`` to the list of sources in +your configuration. + +.. _registering a personal fanart.tv API key: https://fanart.tv/get-an-api-key/ + +More detailed information can be found `on their blog`_. Specifically, the +personal key will give you earlier access to new art. + +.. _on their blog: https://fanart.tv/2015/01/personal-api-keys/ + Embedding Album Art ------------------- From d46b45861b8f69e76061049fd30e603b00ca6bcb Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 02:40:52 +0200 Subject: [PATCH 0655/2280] typo, rename project key config option --- beetsplug/fetchart.py | 4 ++-- docs/plugins/fetchart.rst | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 61bff901f..860379107 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -204,7 +204,7 @@ class FanartTV(ArtSource): response = self.request( self.API_ALBUMS + album.mb_releasegroupid, headers={ - 'api-key': self._config['fanarttv_api_key'].get(), + 'api-key': self._config['fanarttv_project_key'].get(), 'client-key': self._config['fanarttv_personal_key'].get() }) @@ -488,7 +488,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', - 'fanarttv_api_key': None, + 'fanarttv_project_key': None, 'fanarttv_personal_key': None }) self.config['google_key'].redact = True diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 24a67ded6..f9280204b 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -169,8 +169,8 @@ Fanart.tv Although not strictly necesarry right now, you might think about `registering a personal fanart.tv API key`_. Set the ``fanarttv_personal_key`` -configurati option to your key, then add ``fanarttv`` to the list of sources in -your configuration. +configuration option to your key, then add ``fanarttv`` to the list of sources +in your configuration. .. _registering a personal fanart.tv API key: https://fanart.tv/get-an-api-key/ From 2dfdc8b90ad260d4ac4ec367ff9bf4bc0b70fc26 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 02:47:56 +0200 Subject: [PATCH 0656/2280] fix doc formatting --- docs/plugins/fetchart.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index f9280204b..005bea320 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -165,7 +165,7 @@ Note that the Google custom search API is limited to 100 queries per day. After that, the fetchart plugin will fall back on other declared data sources. Fanart.tv -......... +''''''''' Although not strictly necesarry right now, you might think about `registering a personal fanart.tv API key`_. Set the ``fanarttv_personal_key`` From 87aa5dab13e3605b69a67ab13bd4592b54400119 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 13:28:48 +0200 Subject: [PATCH 0657/2280] fixes according to feedback by @Kraymer --- beetsplug/fetchart.py | 25 ++++++++++--------------- docs/plugins/fetchart.rst | 6 +++--- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 860379107..fd84416d5 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -196,6 +196,7 @@ class FanartTV(ArtSource): """Art from fanart.tv requested using their API""" API_URL = 'http://webservice.fanart.tv/v3/' API_ALBUMS = API_URL + 'music/albums/' + PROJECT_KEY = '' def get(self, album): if not album.mb_releasegroupid: @@ -204,8 +205,8 @@ class FanartTV(ArtSource): response = self.request( self.API_ALBUMS + album.mb_releasegroupid, headers={ - 'api-key': self._config['fanarttv_project_key'].get(), - 'client-key': self._config['fanarttv_personal_key'].get() + 'api-key': self.PROJECT_KEY, + 'client-key': self._config['fanarttv_key'].get() }) try: @@ -215,16 +216,11 @@ class FanartTV(ArtSource): response.text) return - def escapeforlog(s): + def escape_for_log(s): # the logger will eventually try to .format() the message, and # interpret the dict as format spec... - r = [] - for c in s: - if c in ['{', '}']: - r.append(c) - r.append(c) - return ''.join(r) - self._log.debug(escapeforlog(str(data))) + return ''.join((2 * c if c in '{}' else c for c in s)) + self._log.debug(escape_for_log(str(data))) if u'status' in data and data[u'status'] == u'error': if u'not found' in data[u'error message'].lower(): @@ -413,7 +409,7 @@ class Wikipedia(ArtSource): class FileSystem(ArtSource): - """Art from the fileszystem""" + """Art from the filesystem""" @staticmethod def filename_priority(filename, cover_names): """Sort order for image names. @@ -488,11 +484,10 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'sources': ['coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', - 'fanarttv_project_key': None, - 'fanarttv_personal_key': None + 'fanarttv_key': None }) self.config['google_key'].redact = True - self.config['fanarttv_personal_key'].redact = True + self.config['fanarttv_key'].redact = True # Holds paths to downloaded images between fetching them and # placing them in the filesystem. @@ -513,7 +508,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') - if not self.config['fanarttv_personal_key'].get() and \ + if not self.config['fanarttv_key'].get() and \ u'fanarttv' in available_sources: self._log.warn( u'fanart.tv source enabled, but no personal API given. This ' diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 005bea320..f5e3ae601 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -57,7 +57,7 @@ file. The available options are: Default: None. - **google_engine**: The custom search engine to use. Default: The `beets custom search engine`_, which searches the entire web. - **fanarttv_personal_key**: The personal API key for requesting art from + **fanarttv_key**: The personal API key for requesting art from fanart.tv. See below. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ @@ -167,8 +167,8 @@ After that, the fetchart plugin will fall back on other declared data sources. Fanart.tv ''''''''' -Although not strictly necesarry right now, you might think about -`registering a personal fanart.tv API key`_. Set the ``fanarttv_personal_key`` +Although not strictly necessary right now, you might think about +`registering a personal fanart.tv API key`_. Set the ``fanarttv_key`` configuration option to your key, then add ``fanarttv`` to the list of sources in your configuration. From 7bec3b9de5d9cb7ab5b857a4bc1bd022a39887ca Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 14:56:14 +0200 Subject: [PATCH 0658/2280] fanart.tv tests, mostly copied and pasted from the google tests --- test/test_art.py | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index ebfcd53f4..79326b6c4 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -260,6 +260,81 @@ class GoogleImageTest(UseThePlugin): self.assertEqual(list(result_url), []) +class FanartTVTest(UseThePlugin): + RESPONSE_MULTIPLE = u"""{ + "name": "artistname", + "mbid_id": "artistid", + "albums": { + "thereleasegroupid": { + "albumcover": [ + { + "id": "24", + "url": "http://example.com/1.jpg", + "likes": "0" + }, + { + "id": "42", + "url": "http://example.com/2.jpg", + "likes": "0" + }, + { + "id": "23", + "url": "http://example.com/3.jpg", + "likes": "0" + } + ], + "cdart": [ + { + "id": "123", + "url": "http://example.com/4.jpg", + "likes": "0", + "disc": "1", + "size": "1000" + } + ] + } + } + }""" + RESPONSE_ERROR = u"""{ + "status": "error", + "error message": "the error message" + }""" + RESPONSE_MALFORMED = u"bla blup" + + def setUp(self): + super(FanartTVTest, self).setUp() + self.source = fetchart.FanartTV(logger, self.plugin.config) + + @responses.activate + def run(self, *args, **kwargs): + super(FanartTVTest, self).run(*args, **kwargs) + + def mock_response(self, url, json): + responses.add(responses.GET, url, body=json, + content_type='application/json') + + def test_fanarttv_finds_image(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_MULTIPLE) + result_url = self.source.get(album) + self.assertEqual(list(result_url)[0], 'http://example.com/1.jpg') + + def test_fanarttv_returns_no_result_when_error_received(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_ERROR) + result_url = self.source.get(album) + self.assertEqual(list(result_url), []) + + def test_fanarttv_returns_no_result_with_malformed_response(self): + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_MALFORMED) + result_url = self.source.get(album) + self.assertEqual(list(result_url), []) + + @_common.slow_test() class ArtImporterTest(UseThePlugin): def setUp(self): From 3a2eb03e0e377c80b9e1191b60c3978e1dd9fdea Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 19:32:17 +0200 Subject: [PATCH 0659/2280] Add fanart.tv API key --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index fd84416d5..a31e25cca 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -196,7 +196,7 @@ class FanartTV(ArtSource): """Art from fanart.tv requested using their API""" API_URL = 'http://webservice.fanart.tv/v3/' API_ALBUMS = API_URL + 'music/albums/' - PROJECT_KEY = '' + PROJECT_KEY = '61a7d0ab4e67162b7a0c7c35915cd48e' def get(self, album): if not album.mb_releasegroupid: From 4763fec35b9efe088785dc87928ef8630755d31f Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 19:42:06 +0200 Subject: [PATCH 0660/2280] fanart.tv: remove overly verbose logging left over from debugging --- beetsplug/fetchart.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a31e25cca..6f38f6bd2 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -216,12 +216,6 @@ class FanartTV(ArtSource): response.text) return - def escape_for_log(s): - # the logger will eventually try to .format() the message, and - # interpret the dict as format spec... - return ''.join((2 * c if c in '{}' else c for c in s)) - self._log.debug(escape_for_log(str(data))) - if u'status' in data and data[u'status'] == u'error': if u'not found' in data[u'error message'].lower(): self._log.debug(u'fanart.tv: no image found') From 9106f2d1c27be45c1644079ff153645aa579c838 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 15 Apr 2016 20:14:45 +0200 Subject: [PATCH 0661/2280] update changelog --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 67960d56f..9f18dda0d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,10 @@ New features: art while copying it. * :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option lets you preserve mtime of files after each write. +* :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. + Albums are matched using the ``mb_releasegroupid`` tag. + +.. _fanart.tv: https://fanart.tv/ Fixes: From 53b5faf7a856ab95e92ea54684de40e211230d50 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 28 Feb 2016 15:24:48 -0800 Subject: [PATCH 0662/2280] Add __future__ import style checker This adds the [flake8-future-import][f] plugin for flake8, which enforces the standard set of `__future__` imports at the top of all Python files. This revealed a fair number of files that need to be fixed. To be revisited after #1887 is merged. [f]: https://github.com/xZise/flake8-future-import --- setup.cfg | 12 ++++++++---- tox.ini | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/setup.cfg b/setup.cfg index 40eda74ec..16ab16367 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,11 @@ logging-clear-handlers=1 eval-attr="!=slow" [flake8] -# E241 missing whitespace after ',' (used to align visually) -# E221 multiple spaces before operator (used to align visually) -# E731 do not assign a lambda expression, use a def -ignore=E241,E221,E731 +# Default pyflakes errors we ignore: +# - E241: missing whitespace after ',' (used to align visually) +# - E221: multiple spaces before operator (used to align visually) +# - E731: do not assign a lambda expression, use a def +# +# And for `flake8-future-import`, we define the set of imports we require: +# division, absolute_import, and print_function. +ignore=E241,E221,E731,FI50,FI51,FI12,FI53,FI14,FI15 diff --git a/tox.ini b/tox.ini index d220f1895..cd29693a1 100644 --- a/tox.ini +++ b/tox.ini @@ -47,4 +47,5 @@ commands = [testenv:flake8] deps = flake8 + flake8-future-import commands = flake8 beets beetsplug beet test setup.py docs From 205f868a202526a8238166e20df5f7f8e89201f1 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 16 Mar 2016 21:03:11 +0000 Subject: [PATCH 0663/2280] Add description for all errors we ignore --- setup.cfg | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/setup.cfg b/setup.cfg index 16ab16367..b093a20b5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -8,7 +8,11 @@ eval-attr="!=slow" # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) # - E731: do not assign a lambda expression, use a def -# -# And for `flake8-future-import`, we define the set of imports we require: -# division, absolute_import, and print_function. +# `flake8-future-import` errors we ignore: +# - FI50: `__future__` import "division" present +# - FI51: `__future__` import "absolute_import" present +# - FI12: `__future__` import "with_statement" missing +# - FI53: `__future__` import "print_function" present +# - FI14: `__future__` import "unicode_literals" missing +# - FI15: `__future__` import "generator_stop" missing ignore=E241,E221,E731,FI50,FI51,FI12,FI53,FI14,FI15 From 6b43e1204f5eb5879221cad380201d94f29903f3 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 01:53:39 +0200 Subject: [PATCH 0664/2280] add missing print_function future imports --- beet | 2 ++ beets/art.py | 2 ++ beetsplug/cue.py | 2 ++ beetsplug/filefilter.py | 2 ++ beetsplug/ipfs.py | 3 +++ beetsplug/metasync/__init__.py | 3 +++ beetsplug/metasync/amarok.py | 2 ++ beetsplug/metasync/itunes.py | 3 +++ docs/conf.py | 2 ++ docs/serve.py | 4 ++++ test/__init__.py | 2 ++ test/test_filefilter.py | 3 +++ test/test_ipfs.py | 2 ++ test/test_metasync.py | 3 +++ test/test_ui_commands.py | 3 +++ test/test_ui_init.py | 3 +++ 16 files changed, 41 insertions(+) diff --git a/beet b/beet index 99dbd8cf5..9b6b0cabc 100755 --- a/beet +++ b/beet @@ -15,6 +15,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +from __future__ import print_function + import beets.ui if __name__ == '__main__': diff --git a/beets/art.py b/beets/art.py index 60f9dce88..f225c1c09 100644 --- a/beets/art.py +++ b/beets/art.py @@ -17,6 +17,8 @@ music and items' embedded album art. """ +from __future__ import print_function + import subprocess import platform from tempfile import NamedTemporaryFile diff --git a/beetsplug/cue.py b/beetsplug/cue.py index 3e545c9a8..b207a4223 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -2,6 +2,8 @@ # Copyright 2016 Bruno Cauet # Split an album-file in tracks thanks a cue file +from __future__ import print_function + import subprocess from os import path from glob import glob diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index 2481390f6..f706723fd 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -16,6 +16,8 @@ """Filter imported files using a regular expression. """ +from __future__ import print_function + import re from beets import config from beets.plugins import BeetsPlugin diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index 6e5a5c7d4..cf58d112c 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -14,6 +14,9 @@ """Adds support for ipfs. Requires go-ipfs and a running ipfs daemon """ + +from __future__ import print_function + from beets import ui, util, library, config from beets.plugins import BeetsPlugin diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 219d73474..50c1f3ebb 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -15,6 +15,9 @@ """Synchronize information from music player libraries """ + +from __future__ import print_function + from abc import abstractmethod, ABCMeta from importlib import import_module diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index 78241dc1b..97cfb8532 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -16,6 +16,8 @@ """Synchronize information from amarok's library via dbus """ +from __future__ import print_function + from os.path import basename from datetime import datetime from time import mktime diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index ead77cd39..3c132e9d8 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -15,6 +15,9 @@ """Synchronize information from iTunes's library """ + +from __future__ import print_function + from contextlib import contextmanager import os import shutil diff --git a/docs/conf.py b/docs/conf.py index ad100b467..986e42dcf 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- +from __future__ import print_function + AUTHOR = u'Adrian Sampson' # General configuration diff --git a/docs/serve.py b/docs/serve.py index 48673ea8d..facaf8fe6 100644 --- a/docs/serve.py +++ b/docs/serve.py @@ -1,5 +1,9 @@ #!/usr/bin/env python + +from __future__ import print_function + from livereload import Server, shell + server = Server() server.watch('*.rst', shell('make html')) server.serve(root='_build/html') diff --git a/test/__init__.py b/test/__init__.py index 72fb5d544..1582876d6 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -1,3 +1,5 @@ # -*- coding: utf-8 -*- # Make python -m testall.py work. + +from __future__ import print_function diff --git a/test/test_filefilter.py b/test/test_filefilter.py index aec96977e..0375e4499 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -15,6 +15,9 @@ """Tests for the `filefilter` plugin. """ + +from __future__ import print_function + import os import shutil diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 2b2acdc2d..67a6e9c29 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -12,6 +12,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +from __future__ import print_function + from mock import patch from beets import library diff --git a/test/test_metasync.py b/test/test_metasync.py index 6404ea1d8..19e50ee13 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -12,6 +12,9 @@ # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. + +from __future__ import print_function + import os import platform import time diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index ed7620725..a89e29d01 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -15,6 +15,9 @@ """Test module for file ui/commands.py """ + +from __future__ import print_function + import os import shutil diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 98a2aac99..14e53977f 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -15,6 +15,9 @@ """Test module for file ui/__init__.py """ + +from __future__ import print_function + from test import _common from test._common import unittest From 0cfddfaa8ab19d7a4e6a7552a87f7e40552f77e3 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 02:28:54 +0200 Subject: [PATCH 0665/2280] add missing absolute_import future imports --- beet | 2 +- beets/art.py | 2 +- beetsplug/cue.py | 2 +- beetsplug/filefilter.py | 2 +- beetsplug/ipfs.py | 2 +- beetsplug/metasync/__init__.py | 2 +- beetsplug/metasync/amarok.py | 2 +- beetsplug/metasync/itunes.py | 2 +- docs/conf.py | 2 +- docs/serve.py | 2 +- test/__init__.py | 2 +- test/test_filefilter.py | 10 +++++----- test/test_ipfs.py | 2 +- test/test_metasync.py | 2 +- test/test_ui_commands.py | 2 +- test/test_ui_init.py | 2 +- 16 files changed, 20 insertions(+), 20 deletions(-) diff --git a/beet b/beet index 9b6b0cabc..742dd2a36 100755 --- a/beet +++ b/beet @@ -15,7 +15,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import print_function +from __future__ import absolute_import, print_function import beets.ui diff --git a/beets/art.py b/beets/art.py index f225c1c09..9012db00e 100644 --- a/beets/art.py +++ b/beets/art.py @@ -17,7 +17,7 @@ music and items' embedded album art. """ -from __future__ import print_function +from __future__ import absolute_import, print_function import subprocess import platform diff --git a/beetsplug/cue.py b/beetsplug/cue.py index b207a4223..d6865b4f2 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -2,7 +2,7 @@ # Copyright 2016 Bruno Cauet # Split an album-file in tracks thanks a cue file -from __future__ import print_function +from __future__ import absolute_import, print_function import subprocess from os import path diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index f706723fd..437b66d9a 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -16,7 +16,7 @@ """Filter imported files using a regular expression. """ -from __future__ import print_function +from __future__ import absolute_import, print_function import re from beets import config diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index cf58d112c..119d857c8 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -15,7 +15,7 @@ """Adds support for ipfs. Requires go-ipfs and a running ipfs daemon """ -from __future__ import print_function +from __future__ import absolute_import, print_function from beets import ui, util, library, config from beets.plugins import BeetsPlugin diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 50c1f3ebb..a7ed292ce 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -16,7 +16,7 @@ """Synchronize information from music player libraries """ -from __future__ import print_function +from __future__ import absolute_import, print_function from abc import abstractmethod, ABCMeta from importlib import import_module diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index 97cfb8532..8d657b564 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -16,7 +16,7 @@ """Synchronize information from amarok's library via dbus """ -from __future__ import print_function +from __future__ import absolute_import, print_function from os.path import basename from datetime import datetime diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index 3c132e9d8..4e67193bc 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -16,7 +16,7 @@ """Synchronize information from iTunes's library """ -from __future__ import print_function +from __future__ import absolute_import, print_function from contextlib import contextmanager import os diff --git a/docs/conf.py b/docs/conf.py index 986e42dcf..6d58a8135 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import print_function +from __future__ import absolute_import, print_function AUTHOR = u'Adrian Sampson' diff --git a/docs/serve.py b/docs/serve.py index facaf8fe6..0920f9374 100644 --- a/docs/serve.py +++ b/docs/serve.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from __future__ import print_function +from __future__ import absolute_import, print_function from livereload import Server, shell diff --git a/test/__init__.py b/test/__init__.py index 1582876d6..4de37e268 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -2,4 +2,4 @@ # Make python -m testall.py work. -from __future__ import print_function +from __future__ import absolute_import, print_function diff --git a/test/test_filefilter.py b/test/test_filefilter.py index 0375e4499..a3a3e212f 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -16,19 +16,19 @@ """Tests for the `filefilter` plugin. """ -from __future__ import print_function +from __future__ import absolute_import, print_function import os import shutil -from _common import unittest +from test import _common +from test._common import unittest +from test.helper import capture_log +from test.test_importer import ImportHelper from beets import config from beets.mediafile import MediaFile from beets.util import displayable_path from beetsplug.filefilter import FileFilterPlugin -from test import _common -from test.helper import capture_log -from test.test_importer import ImportHelper class FileFilterPluginTest(unittest.TestCase, ImportHelper): diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 67a6e9c29..a261590b1 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -12,7 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import print_function +from __future__ import absolute_import, print_function from mock import patch diff --git a/test/test_metasync.py b/test/test_metasync.py index 19e50ee13..dce66b218 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import print_function +from __future__ import absolute_import, print_function import os import platform diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index a89e29d01..6347bc312 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -16,7 +16,7 @@ """Test module for file ui/commands.py """ -from __future__ import print_function +from __future__ import absolute_import, print_function import os import shutil diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 14e53977f..457655907 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -16,7 +16,7 @@ """Test module for file ui/__init__.py """ -from __future__ import print_function +from __future__ import absolute_import, print_function from test import _common from test._common import unittest From 36e91fc78b33c05acb7b40d44d486880b6ad9fdb Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 14:17:46 +0200 Subject: [PATCH 0666/2280] fix fanart.tv merge --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 830dab924..88c72cdbd 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -335,7 +335,7 @@ class GoogleImages(RemoteArtSource): match=Candidate.MATCH_EXACT) -class FanartTV(ArtSource): +class FanartTV(RemoteArtSource): """Art from fanart.tv requested using their API""" NAME = u"fanart.tv" From 0f89f17227a4c821cc42536da011fc5937b74fe2 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 18:33:54 +0200 Subject: [PATCH 0667/2280] add missing division future imports --- beet | 2 +- beets/art.py | 2 +- beetsplug/cue.py | 2 +- beetsplug/filefilter.py | 2 +- beetsplug/ipfs.py | 2 +- beetsplug/metasync/__init__.py | 2 +- beetsplug/metasync/amarok.py | 2 +- beetsplug/metasync/itunes.py | 2 +- docs/conf.py | 2 +- docs/serve.py | 2 +- test/__init__.py | 2 +- test/test_filefilter.py | 2 +- test/test_ipfs.py | 2 +- test/test_metasync.py | 2 +- test/test_ui_commands.py | 2 +- test/test_ui_init.py | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/beet b/beet index 742dd2a36..21fa085b9 100755 --- a/beet +++ b/beet @@ -15,7 +15,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import beets.ui diff --git a/beets/art.py b/beets/art.py index 9012db00e..7a65a2b80 100644 --- a/beets/art.py +++ b/beets/art.py @@ -17,7 +17,7 @@ music and items' embedded album art. """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import subprocess import platform diff --git a/beetsplug/cue.py b/beetsplug/cue.py index d6865b4f2..63051bfc1 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -2,7 +2,7 @@ # Copyright 2016 Bruno Cauet # Split an album-file in tracks thanks a cue file -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import subprocess from os import path diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index 437b66d9a..72b5ea9ea 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -16,7 +16,7 @@ """Filter imported files using a regular expression. """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import re from beets import config diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index 119d857c8..87a100b14 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -15,7 +15,7 @@ """Adds support for ipfs. Requires go-ipfs and a running ipfs daemon """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from beets import ui, util, library, config from beets.plugins import BeetsPlugin diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index a7ed292ce..3fc0be4cc 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -16,7 +16,7 @@ """Synchronize information from music player libraries """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from abc import abstractmethod, ABCMeta from importlib import import_module diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index 8d657b564..aaa1ee91e 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -16,7 +16,7 @@ """Synchronize information from amarok's library via dbus """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from os.path import basename from datetime import datetime diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index 4e67193bc..a62746848 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -16,7 +16,7 @@ """Synchronize information from iTunes's library """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from contextlib import contextmanager import os diff --git a/docs/conf.py b/docs/conf.py index 6d58a8135..e6eae663a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function AUTHOR = u'Adrian Sampson' diff --git a/docs/serve.py b/docs/serve.py index 0920f9374..d54c8b64d 100644 --- a/docs/serve.py +++ b/docs/serve.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from livereload import Server, shell diff --git a/test/__init__.py b/test/__init__.py index 4de37e268..8214c3b8e 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -2,4 +2,4 @@ # Make python -m testall.py work. -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function diff --git a/test/test_filefilter.py b/test/test_filefilter.py index a3a3e212f..9e6a71099 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -16,7 +16,7 @@ """Tests for the `filefilter` plugin. """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_ipfs.py b/test/test_ipfs.py index a261590b1..87ca3f2ec 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -12,7 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from mock import patch diff --git a/test/test_metasync.py b/test/test_metasync.py index dce66b218..f4a5f4d49 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import os import platform diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index 6347bc312..e71db3ca9 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -16,7 +16,7 @@ """Test module for file ui/commands.py """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import os import shutil diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 457655907..35fd99cc5 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -16,7 +16,7 @@ """Test module for file ui/__init__.py """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function from test import _common from test._common import unittest From 8169983074949e5418a259f92d98286cc536abff Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 17 Apr 2016 21:18:31 +0200 Subject: [PATCH 0668/2280] fix translation of the old remote_priority option for fetchart, add a test --- beetsplug/fetchart.py | 4 ++-- test/test_art.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 88c72cdbd..1f6605608 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -694,8 +694,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): u'been deprecated, see the documentation.') if self.config['remote_priority'].get(bool): try: - self.sources_name.remove[u'filesystem'] - sources_name.append[u'filesystem'] + sources_name.remove(u'filesystem') + sources_name.append(u'filesystem') except ValueError: pass self.sources = [ART_SOURCES[s](self._log, self.config) diff --git a/test/test_art.py b/test/test_art.py index 033174db4..e52eb6772 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -27,6 +27,7 @@ from test import _common from test._common import unittest from beetsplug import fetchart from beets.autotag import AlbumInfo, AlbumMatch +from beets import config from beets import library from beets import importer from beets import logging @@ -540,6 +541,24 @@ class ArtForAlbumTest(UseThePlugin): self._assertImageResized(self.IMG_348x348, True) +class DeprecatedConfigTest(_common.TestCase): + """While refactoring the plugin, the remote_priority option was deprecated, + and a new codepath should translate its effect. Check that it actually does + so. + """ + + # If we subclassed UseThePlugin, the configuration change would either be + # overwritten by _common.TestCase or be set after constructing the + # plugin object + def setUp(self): + super(DeprecatedConfigTest, self).setUp() + config['fetchart']['remote_priority'] = True + self.plugin = fetchart.FetchArtPlugin() + + def test_moves_filesystem_to_end(self): + self.assertEqual(type(self.plugin.sources[-1]), fetchart.FileSystem) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From f58d4e838a22f46a300098887edf95a34c81b5a3 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sat, 16 Apr 2016 21:25:49 -0300 Subject: [PATCH 0669/2280] Query data from items and export the json Based on the ``info`` plugin --- beetsplug/export.py | 145 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 beetsplug/export.py diff --git a/beetsplug/export.py b/beetsplug/export.py new file mode 100644 index 000000000..a92e57265 --- /dev/null +++ b/beetsplug/export.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Exports data from beets +""" + +from __future__ import division, absolute_import, print_function + +import json +import codecs + +from datetime import datetime, date +from beets.plugins import BeetsPlugin +from beets import ui +from beets import mediafile +from beetsplug.info import make_key_filter, library_data, tag_data + +json.JSONEncoder.default = lambda self, obj: \ + (obj.isoformat() if isinstance(obj, datetime) or isinstance(obj, date) + else None) + + +class ExportPlugin(BeetsPlugin): + + def __init__(self): + super(ExportPlugin, self).__init__() + + self.config.add({ + 'default_format': 'json', + 'json': { + # json module formatting options + 'formatting': { + 'ensure_ascii': False, + 'indent': 4, + 'separators': (',', ': '), + } + }, + # TODO: Use something like the edit plugin + # 'item_fields': [] + }) + + def commands(self): + # TODO: Add option to use albums + + cmd = ui.Subcommand('export', help=u'export data from beets') + cmd.func = self.run + cmd.parser.add_option( + u'-l', u'--library', action='store_true', + help=u'show library fields instead of tags', + ) + cmd.parser.add_option( + u'--append', action='store_true', default=False, + help=u'if should append data to the file', + ) + cmd.parser.add_option( + u'-i', u'--include-keys', default=[], + action='append', dest='included_keys', + help=u'comma separated list of keys to show', + ) + cmd.parser.add_option( + u'-p', u'--path', + help=u'path for the output file. If not given, will print the data' + ) + return [cmd] + + def run(self, lib, opts, args): + + file_path = opts.path + file_format = self.config['default_format'].get(str) + file_mode = 'a' if opts.append else 'w' + format_options = self.config[file_format]['formatting'].get(dict) + + export_format = ExportFormat.factory( + file_format, **{ + 'file_path': file_path, + 'file_mode': file_mode + } + ) + + items = [] + data_collector = library_data if opts.library else tag_data + + included_keys = [] + for keys in opts.included_keys: + included_keys.extend(keys.split(',')) + key_filter = make_key_filter(included_keys) + + for data_emitter in data_collector(lib, ui.decargs(args)): + try: + data, item = data_emitter() + except (mediafile.UnreadableFileError, IOError) as ex: + self._log.error(u'cannot read file: {0}', ex) + continue + + data = key_filter(data) + items += [data] + + export_format.export(items, **format_options) + + +class ExportFormat(object): + """The output format type""" + + @classmethod + def factory(self, type, **kwargs): + if type == "json": + if kwargs['file_path']: + return JsonFileFormat(**kwargs) + else: + return JsonPrintFormat() + raise NotImplemented("") + + def export(self, data, **kwargs): + raise NotImplemented("") + + +class JsonPrintFormat(ExportFormat): + """Outputs to the console""" + + def export(self, data, **kwargs): + ui.print_(json.dumps(data, **kwargs)) + + +class JsonFileFormat(ExportFormat): + """Saves in a json file""" + + def __init__(self, file_path, file_mode=u'w', encoding=u'utf-8'): + self.path = file_path + self.mode = file_mode + self.encoding = encoding + + def export(self, data, **kwargs): + with codecs.open(self.path, self.mode, self.encoding) as f: + json.dump(data, f, **kwargs) From 6cbbba7daeb6546991b681bceb15d5a6d17d901a Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 01:47:39 +0200 Subject: [PATCH 0670/2280] initial work on allowing slightly non-square images in fetchart --- beetsplug/fetchart.py | 56 ++++++++++++++++++++++++++++++++++++------- test/test_art.py | 44 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 9 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 1f6605608..e8d3e3438 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -30,6 +30,7 @@ from beets import ui from beets import util from beets import config from beets.util.artresizer import ArtResizer +from beets.util import confit try: import itunes @@ -91,6 +92,9 @@ class Candidate(object): u'`enforce_ratio` may be violated.') return self.CANDIDATE_EXACT + short_edge = min(self.size) + long_edge = max(self.size) + # Check minimum size. if extra['minwidth'] and self.size[0] < extra['minwidth']: self._log.debug(u'image too small ({} < {})', @@ -98,10 +102,23 @@ class Candidate(object): return self.CANDIDATE_BAD # Check aspect ratio. - if extra['enforce_ratio'] and self.size[0] != self.size[1]: - self._log.debug(u'image is not square ({} != {})', - self.size[0], self.size[1]) - return self.CANDIDATE_BAD + edge_diff = long_edge - short_edge + if extra['enforce_ratio']: + if extra['margin_px'] and edge_diff > extra['margin_px']: + self._log.debug(u'image is notblablapxsquare ({} != {})', + self.size[0], self.size[1]) + return self.CANDIDATE_BAD + elif extra['margin_percent'] and \ + edge_diff > extra['margin_percent'] * long_edge: + self._log.debug(u'image is notblablapercentsquare ({} != {})', + self.size[0], self.size[1]) + return self.CANDIDATE_BAD + elif not extra['margin_px'] and not extra['margin_percent'] and \ + edge_diff: + # also reached for margin_px == 0 and margin_percent == 0.0 + self._log.debug(u'image is not square ({} != {})', + self.size[0], self.size[1]) + return self.CANDIDATE_BAD # Check maximum size. if extra['maxwidth'] and self.size[0] > extra['maxwidth']: @@ -634,9 +651,16 @@ SOURCE_NAMES = {v: k for k, v in ART_SOURCES.items()} class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): + PAT_PX = r"(0|[1-9][0-9]*)px" + PAT_PERCENT = r"(100(\.00?)?|[1-9]?[0-9](\.[0-9]{1,2})?)%" + def __init__(self): super(FetchArtPlugin, self).__init__() + # Holds paths to downloaded images between fetching them and + # placing them in the filesystem. + self.art_paths = {} + self.config.add({ 'auto': True, 'minwidth': 0, @@ -653,13 +677,25 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self.config['google_key'].redact = True self.config['fanarttv_key'].redact = True - # Holds paths to downloaded images between fetching them and - # placing them in the filesystem. - self.art_paths = {} - self.minwidth = self.config['minwidth'].get(int) self.maxwidth = self.config['maxwidth'].get(int) - self.enforce_ratio = self.config['enforce_ratio'].get(bool) + + # allow both pixel and percentage-based margin specifications + self.enforce_ratio = self.config['enforce_ratio'].get( + confit.OneOf([bool, + confit.String(pattern=self.PAT_PX), + confit.String(pattern=self.PAT_PERCENT)])) + self.margin_px = None + self.margin_percent = None + if type(self.enforce_ratio) is unicode: + if self.enforce_ratio[-1] == u'%': + self.margin_percent = float(self.enforce_ratio[:-1]) / 100 + elif self.enforce_ratio[-2:] == u'px': + self.margin_px = int(self.enforce_ratio[:-2]) + else: + # shouldn't happen + raise confit.ConfigValueError() + self.enforce_ratio = True cover_names = self.config['cover_names'].as_str_seq() self.cover_names = map(util.bytestring_path, cover_names) @@ -765,6 +801,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'cover_names': self.cover_names, 'cautious': self.cautious, 'enforce_ratio': self.enforce_ratio, + 'margin_px': self.margin_px, + 'margin_percent': self.margin_percent, 'minwidth': self.minwidth, 'maxwidth': self.maxwidth} diff --git a/test/test_art.py b/test/test_art.py index e52eb6772..2e7db8439 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -33,6 +33,7 @@ from beets import importer from beets import logging from beets import util from beets.util.artresizer import ArtResizer, WEBPROXY +from beets.util import confit logger = logging.getLogger('beets.test_art') @@ -534,6 +535,26 @@ class ArtForAlbumTest(UseThePlugin): self.plugin.enforce_ratio = False self._assertImageIsValidArt(self.IMG_500x490, True) + def test_respect_enforce_ratio_px_above(self): + self.plugin.enforce_ratio = True + self.plugin.margin_px = 5 + self._assertImageIsValidArt(self.IMG_500x490, False) + + def test_respect_enforce_ratio_px_below(self): + self.plugin.enforce_ratio = True + self.plugin.margin_px = 15 + self._assertImageIsValidArt(self.IMG_500x490, True) + + def test_respect_enforce_ratio_percent_above(self): + self.plugin.enforce_ratio = True + self.plugin.margin_percent = (500 - 490) / 500 * 0.5 + self._assertImageIsValidArt(self.IMG_500x490, False) + + def test_respect_enforce_ratio_percent_below(self): + self.plugin.enforce_ratio = True + self.plugin.margin_percent = (500 - 490) / 500 * 1.5 + self._assertImageIsValidArt(self.IMG_500x490, True) + def test_resize_if_necessary(self): self._require_backend() self.plugin.maxwidth = 300 @@ -559,6 +580,29 @@ class DeprecatedConfigTest(_common.TestCase): self.assertEqual(type(self.plugin.sources[-1]), fetchart.FileSystem) +class EnforceRatioConfigTest(_common.TestCase): + """Throw some data at the regexes.""" + + def _load_with_config(self, values, should_raise): + if should_raise: + for v in values: + config['fetchart']['enforce_ratio'] = v + with self.assertRaises(confit.ConfigValueError): + fetchart.FetchArtPlugin() + else: + for v in values: + config['fetchart']['enforce_ratio'] = v + fetchart.FetchArtPlugin() + + def test_px(self): + self._load_with_config(u'0px 4px 12px 123px'.split(), False) + self._load_with_config(u'00px stuff5px'.split(), True) + + def test_percent(self): + self._load_with_config(u'0% 0.00% 5.1% 5% 100%'.split(), False) + self._load_with_config(u'00% 1.234% foo5% 100.1%'.split(), True) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From c211aabd72b63cfd049808a90b8791630255d7ac Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sun, 17 Apr 2016 21:39:53 -0300 Subject: [PATCH 0671/2280] simplify json printing --- beetsplug/export.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/export.py b/beetsplug/export.py index a92e57265..ec90332b4 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -17,6 +17,7 @@ from __future__ import division, absolute_import, print_function +import sys import json import codecs @@ -129,7 +130,7 @@ class JsonPrintFormat(ExportFormat): """Outputs to the console""" def export(self, data, **kwargs): - ui.print_(json.dumps(data, **kwargs)) + json.dump(data, sys.stdout, **kwargs) class JsonFileFormat(ExportFormat): From 1e3704a27e11d1e5caae4ea6cf89edc25f28cb91 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sun, 17 Apr 2016 21:52:09 -0300 Subject: [PATCH 0672/2280] fix NotImplementedError() --- beetsplug/export.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/export.py b/beetsplug/export.py index ec90332b4..46776354f 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -120,10 +120,10 @@ class ExportFormat(object): return JsonFileFormat(**kwargs) else: return JsonPrintFormat() - raise NotImplemented("") + raise NotImplementedError() def export(self, data, **kwargs): - raise NotImplemented("") + raise NotImplementedError() class JsonPrintFormat(ExportFormat): From 10acea4efd7b3a4b36ebab407eb799fcb6374ac9 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sun, 17 Apr 2016 22:17:56 -0300 Subject: [PATCH 0673/2280] Remove json monkey-patching and use encoder subclassing --- beetsplug/export.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/beetsplug/export.py b/beetsplug/export.py index 46776354f..379bb708e 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -27,9 +27,13 @@ from beets import ui from beets import mediafile from beetsplug.info import make_key_filter, library_data, tag_data -json.JSONEncoder.default = lambda self, obj: \ - (obj.isoformat() if isinstance(obj, datetime) or isinstance(obj, date) - else None) + +class ExportEncoder(json.JSONEncoder): + """Deals with dates because JSON doesn't have a standard""" + def default(self, o): + if isinstance(o, datetime) or isinstance(o, date): + return o.isoformat() + return json.JSONEncoder.default(self, o) class ExportPlugin(BeetsPlugin): @@ -130,7 +134,7 @@ class JsonPrintFormat(ExportFormat): """Outputs to the console""" def export(self, data, **kwargs): - json.dump(data, sys.stdout, **kwargs) + json.dump(data, sys.stdout, cls=ExportEncoder, **kwargs) class JsonFileFormat(ExportFormat): @@ -143,4 +147,4 @@ class JsonFileFormat(ExportFormat): def export(self, data, **kwargs): with codecs.open(self.path, self.mode, self.encoding) as f: - json.dump(data, f, **kwargs) + json.dump(data, f, cls=ExportEncoder, **kwargs) From 5e3c65d32e36c91f70ec2534f7035098c3072eb1 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sun, 17 Apr 2016 23:37:51 -0300 Subject: [PATCH 0674/2280] change option letter --- beetsplug/export.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/export.py b/beetsplug/export.py index 379bb708e..b66b549c7 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -74,14 +74,14 @@ class ExportPlugin(BeetsPlugin): help=u'comma separated list of keys to show', ) cmd.parser.add_option( - u'-p', u'--path', + u'-o', u'--output', help=u'path for the output file. If not given, will print the data' ) return [cmd] def run(self, lib, opts, args): - file_path = opts.path + file_path = opts.output file_format = self.config['default_format'].get(str) file_mode = 'a' if opts.append else 'w' format_options = self.config[file_format]['formatting'].get(dict) From 228ffc91beb1ae78f2d27c757a34d017bb373e81 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sun, 17 Apr 2016 23:47:12 -0300 Subject: [PATCH 0675/2280] use `sort_keys` to make the data more "predictable" --- beetsplug/export.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/export.py b/beetsplug/export.py index b66b549c7..93362550f 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -49,6 +49,7 @@ class ExportPlugin(BeetsPlugin): 'ensure_ascii': False, 'indent': 4, 'separators': (',', ': '), + 'sort_keys': True } }, # TODO: Use something like the edit plugin From 30bca5c8af108656325583a79eeba808661b5d07 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 11:39:09 +0200 Subject: [PATCH 0676/2280] fix unconditionally printing the personal key warning for in fanart.tv in fetchart --- beetsplug/fetchart.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 1f6605608..43da905fd 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -679,15 +679,15 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') + sources_name = plugins.sanitize_choices( + self.config['sources'].as_str_seq(), available_sources) if not self.config['fanarttv_key'].get() and \ - u'fanarttv' in available_sources: + u'fanarttv' in sources_name: self._log.warn( u'fanart.tv source enabled, but no personal API given. This ' u'works as of now, however, fanart.tv prefers users to ' u'register a personal key. Additionaly this makes new art ' u'available shorter after its upload. See the documentation.') - sources_name = plugins.sanitize_choices( - self.config['sources'].as_str_seq(), available_sources) if 'remote_priority' in self.config: self._log.warning( u'The `fetch_art.remote_priority` configuration option has ' From 20235264a412abdc07a1f0a7289b2170d6ace81e Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 15:23:38 +0200 Subject: [PATCH 0677/2280] rewire logic a bit; reasonable debug messages --- beetsplug/fetchart.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index e8d3e3438..7bfc5bc23 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -104,17 +104,20 @@ class Candidate(object): # Check aspect ratio. edge_diff = long_edge - short_edge if extra['enforce_ratio']: - if extra['margin_px'] and edge_diff > extra['margin_px']: - self._log.debug(u'image is notblablapxsquare ({} != {})', - self.size[0], self.size[1]) - return self.CANDIDATE_BAD - elif extra['margin_percent'] and \ - edge_diff > extra['margin_percent'] * long_edge: - self._log.debug(u'image is notblablapercentsquare ({} != {})', - self.size[0], self.size[1]) - return self.CANDIDATE_BAD - elif not extra['margin_px'] and not extra['margin_percent'] and \ - edge_diff: + if extra['margin_px']: + if edge_diff > extra['margin_px']: + self._log.debug(u'image is not close enough to being ' + u'square, ({} - {} > {})', + long_edge, short_edge, extra['margin_px']) + return self.CANDIDATE_BAD + elif extra['margin_percent']: + margin_px = extra['margin_percent'] * long_edge + if edge_diff > margin_px: + self._log.debug(u'image is not close enough to being ' + u'square, ({} - {} > {})', + long_edge, short_edge, margin_px) + return self.CANDIDATE_BAD + elif edge_diff: # also reached for margin_px == 0 and margin_percent == 0.0 self._log.debug(u'image is not square ({} != {})', self.size[0], self.size[1]) From 93267639e4019bd8b4e0cd31ca8c188303bc4841 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 15:32:09 +0200 Subject: [PATCH 0678/2280] update docs for enforce_ratio --- docs/plugins/fetchart.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 863a4996c..591dbc4b4 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -42,7 +42,11 @@ file. The available options are: too big. The resize operation reduces image width to at most ``maxwidth`` pixels. The height is recomputed so that the aspect ratio is preserved. - **enforce_ratio**: Only images with a width:height ratio of 1:1 are - considered as valid album art candidates. Default: ``no``. + considered as valid album art candidates if set to ``yes``. + It is also possible to specify a certain deviation to the exact ratio to + still be considered valid. This can be done either in pixels + (``enforce_ratio: 10px``) or as a percentage of the longer edge + (``enforce_ratio: 0.5%``). Default: ``no``. - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. Default: ``filesystem coverart itunes amazon albumart``, i.e., everything but From 8b4f349e27279ffa0f09e63a7649a85e3c2a0232 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 15:04:57 +0100 Subject: [PATCH 0679/2280] Improve hook plugin design and configuration - Remove `shell` option and split all commands using `shlex.split` before passing them to `subprocess.Popen`. - General refactor of hook plugin code - move hook creation function inside `HookPlugin`. - Add improved error handling for invalid (i.e. empty) commands or commands that do not exist. --- beetsplug/hook.py | 65 ++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 40 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 7925b16c8..0428831dc 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -16,27 +16,13 @@ from __future__ import (division, absolute_import, print_function, unicode_literals) +import shlex import subprocess +import sys -from beets.ui import _arg_encoding from beets.plugins import BeetsPlugin - - -def create_hook_function(log, event, command, shell, substitute_args): - def hook_function(**kwargs): - hook_command = command - - for key in substitute_args: - if key in kwargs: - hook_command = hook_command.replace(substitute_args[key], - unicode(kwargs[key], - _arg_encoding())) - - log.debug('Running command {0} for event {1}', hook_command, event) - - subprocess.Popen(hook_command, shell=shell).wait() - - return hook_function +from beets.ui import _arg_encoding +from beets.util.confit import ConfigValueError class HookPlugin(BeetsPlugin): @@ -45,14 +31,10 @@ class HookPlugin(BeetsPlugin): super(HookPlugin, self).__init__() self.config.add({ - 'hooks': [], - 'substitute_event': '%EVENT%', - 'shell': True + 'hooks': [] }) hooks = self.config['hooks'].get(list) - global_substitute_event = self.config['substitute_event'].get() - global_shell = self.config['shell'].get(bool) for hook_index in range(len(hooks)): hook = self.config['hooks'][hook_index] @@ -60,24 +42,27 @@ class HookPlugin(BeetsPlugin): hook_event = hook['event'].get() hook_command = hook['command'].get() - if 'substitute_event' in hook: - original = hook['substitute_event'].get() - else: - original = global_substitute_event + self.create_and_register_hook(hook_event, hook_command) - if 'shell' in hook: - shell = hook['shell'].get(bool) - else: - shell = global_shell + def create_and_register_hook(self, event, command): + def hook_function(**kwargs): + formatted_command = command.format(event=event, **kwargs) + encoded_command = formatted_command.decode(_arg_encoding()) + command_pieces = shlex.split(encoded_command) - if 'substitute_args' in hook: - substitute_args = hook['substitute_args'].get(dict) - else: - substitute_args = {} + if len(command_pieces) == 0: + raise ConfigValueError('invalid command \"{0}\"'.format( + command)) - hook_command = hook_command.replace(original, hook_event) - hook_function = create_hook_function(self._log, hook_event, - hook_command, shell, - substitute_args) + self._log.debug('Running command \"{0}\" for event \"{1}\"', + encoded_command, event) - self.register_listener(hook_event, hook_function) + try: + subprocess.Popen(command_pieces).wait() + except OSError as e: + _, _, trace = sys.exc_info() + message = "{0}: {1}".format(e, command_pieces[0]) + + raise OSError, message, trace + + self.register_listener(event, hook_function) From 686e069bc49b179c28104f63e8e897cff3ae8adf Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 15:35:15 +0100 Subject: [PATCH 0680/2280] Replace double quotes with single quotes --- beetsplug/hook.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 0428831dc..a86395640 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -61,7 +61,7 @@ class HookPlugin(BeetsPlugin): subprocess.Popen(command_pieces).wait() except OSError as e: _, _, trace = sys.exc_info() - message = "{0}: {1}".format(e, command_pieces[0]) + message = '{0}: {1}'.format(e, command_pieces[0]) raise OSError, message, trace From 3e35660ff31ededb00036877690a75e07979f681 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 15:36:05 +0100 Subject: [PATCH 0681/2280] Remove unnecessary escaping on double quotes --- beetsplug/hook.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index a86395640..dad6779ce 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -51,10 +51,10 @@ class HookPlugin(BeetsPlugin): command_pieces = shlex.split(encoded_command) if len(command_pieces) == 0: - raise ConfigValueError('invalid command \"{0}\"'.format( + raise ConfigValueError('invalid command "{0}"'.format( command)) - self._log.debug('Running command \"{0}\" for event \"{1}\"', + self._log.debug('Running command "{0}" for event "{1}"', encoded_command, event) try: From af5ce6e7e2cbad8250fa0a87618c79d80f2bc65c Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 15:36:25 +0100 Subject: [PATCH 0682/2280] Fix event name collision in tests and update tests - Fix `test_event_X` name collision between tests causing tests to fail unexpectedly. - Update tests to match new hook plugin design (i.e. remove shell and subtitution option testing). --- test/test_hook.py | 34 +++++++++------------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/test/test_hook.py b/test/test_hook.py index f6b8b4941..6b046e8ef 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -33,7 +33,6 @@ def get_temporary_path(): return os.path.join(temporary_directory, temporary_name) -# TODO: Find a good way to test shell option class HookTest(_common.TestCase, TestHelper): TEST_HOOK_COUNT = 5 @@ -44,23 +43,12 @@ class HookTest(_common.TestCase, TestHelper): self.unload_plugins() self.teardown_beets() - def _add_hook(self, event, command, substitute_event=None, shell=None, - substitute_args=None): - + def _add_hook(self, event, command): hook = { 'event': event, 'command': command } - if substitute_event is not None: - hook['substitute_event'] = substitute_event - - if shell is not None: - hook['shell'] = shell - - if substitute_args is not None: - hook['substitute_args'] = substitute_args - hooks = config['hook']['hooks'].get(list) if 'hook' in config else [] hooks.append(hook) @@ -72,29 +60,26 @@ class HookTest(_common.TestCase, TestHelper): ] for index, path in enumerate(temporary_paths): - self._add_hook('test_event_{0}'.format(index), - 'echo > "{0}"'.format(path)) + self._add_hook('test_no_argument_event_{0}'.format(index), + 'touch "{0}"'.format(path)) self.load_plugins('hook') for index in range(len(temporary_paths)): - plugins.send('test_event_{0}'.format(index)) + plugins.send('test_no_argument_event_{0}'.format(index)) for path in temporary_paths: self.assertTrue(os.path.isfile(path)) os.remove(path) def test_hook_event_substitution(self): - temporary_directory = tempfile._get_default_tempdir() - event_names = ['test_event_{0}'.format(i) for i in + event_names = ['test_event_event_{0}'.format(i) for i in range(self.TEST_HOOK_COUNT)] for event in event_names: self._add_hook(event, - 'echo > "{0}"'.format( - os.path.join(temporary_directory, '%EVENT%') - )) + 'touch "{0}/{{event}}"'.format(temporary_directory)) self.load_plugins('hook') @@ -113,14 +98,13 @@ class HookTest(_common.TestCase, TestHelper): ] for index, path in enumerate(temporary_paths): - self._add_hook('test_event_{0}'.format(index), - 'echo > "%PATH%"'.format(path), - substitute_args={'path': '%PATH%'}) + self._add_hook('test_argument_event_{0}'.format(index), + 'touch "{path}"') self.load_plugins('hook') for index, path in enumerate(temporary_paths): - plugins.send('test_event_{0}'.format(index), path=path) + plugins.send('test_argument_event_{0}'.format(index), path=path) for path in temporary_paths: self.assertTrue(os.path.isfile(path)) From 1644f7117a5f7cd29154a091b6bea017eeb0a06b Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Mon, 18 Apr 2016 11:54:22 -0300 Subject: [PATCH 0683/2280] documentation for export plugin --- docs/plugins/export.rst | 70 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs/plugins/export.rst diff --git a/docs/plugins/export.rst b/docs/plugins/export.rst new file mode 100644 index 000000000..abf56c29c --- /dev/null +++ b/docs/plugins/export.rst @@ -0,0 +1,70 @@ +Export Plugin +============= + +The ``export`` plugin lets you get data from the items and export the content to +a ``json`` file. + +Configuration +------------- +To configure the plugin, make a ``export:`` section in your configuration +file. The default options are:: + + export: + default_format: json + json: + formatting: + ensure_ascii: False + indent: 4 + separators: [',' , ': '] + sort_keys: true + +- **default_format**: Choose the format of the exported content. + Supports json only for now. + +Each format have their own options. + +The ``json`` formatting uses the `json`_ standard library options. +Using custom options overwrites all options at the same level. +The default options used here are: + +- **ensure_ascii**: All non-ASCII characters are escaped with `\uXXXX`, if true. + +- **indent**: The number of spaces for indentation. + +- **separators**: A ``(item_separator, dict_separator)`` tuple + +- **sort_keys**: Sorts the keys of the json + +.. _json: https://docs.python.org/2/library/json.html#basic-usage + +Using +----- + +Enable the ``export`` plugin (see :ref:`using-plugins` for help) and then add a +``export`` section to your :doc:`configuration file ` + +To use, you can enter a :doc:`query ` to get the data from +your library:: + + $ beet export beatles + +If you just want to see specific properties you can use the +``--include-keys`` option to filter them. The argument is a +comma-separated list of simple glob patterns where ``*`` matches any +string. For example:: + + $ beet export -i 'title,mb*' beatles + +Will only show the ``title`` property and all properties starting with +``mb``. You can add the ``-i`` option multiple times to the command +line. + +Additional command-line options include: + +* ``--library`` or ``-l``: Show data from the library database instead of the + files' tags. + +* ``--output`` or ``-o``: Path for an output file. If not informed, will print + the data in the console. + +* ``--append``: Appends the data to the file instead of writing. From 806f4908613f3227e6e3f15ff50b0f87c96d8bee Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Mon, 18 Apr 2016 11:59:48 -0300 Subject: [PATCH 0684/2280] add export plugin to index.rst --- docs/plugins/index.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 7d6313d7f..260eb7d49 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -44,6 +44,7 @@ Each plugin has its own set of options that can be defined in a section bearing edit embedart embyupdate + export fetchart fromfilename ftintitle @@ -161,6 +162,7 @@ Miscellaneous * :doc:`convert`: Transcode music and embed album art while exporting to a different directory. * :doc:`duplicates`: List duplicate tracks or albums. +* :doc:`export`: Export data from queries to a format. * :doc:`fuzzy`: Search albums and tracks with fuzzy string matching. * :doc:`ihate`: Automatically skip albums and tracks during the import process. * :doc:`info`: Print music files' tags to the console. From 070469e259226b485a062040bf042863d7f65489 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 16:00:13 +0100 Subject: [PATCH 0685/2280] Remove unicode_literals from __future__ imports --- beetsplug/hook.py | 3 +-- test/test_hook.py | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index dad6779ce..a32247bf8 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -13,8 +13,7 @@ # included in all copies or substantial portions of the Software. """Allows custom commands to be run when an event is emitted by beets""" -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import shlex import subprocess diff --git a/test/test_hook.py b/test/test_hook.py index 6b046e8ef..fc4e7a7ee 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -12,8 +12,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -from __future__ import (division, absolute_import, print_function, - unicode_literals) +from __future__ import division, absolute_import, print_function import os.path import tempfile From 5817c6578ab17e25eb539d41ba7517c2713a8ee7 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Mon, 18 Apr 2016 12:05:16 -0300 Subject: [PATCH 0686/2280] Add changelog --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 600bc4cb7..5e9fa21e6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,8 @@ New features: for a Microsoft Azure Marketplace free account. Thanks to :user:`Kraymer`. * :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. Albums are matched using the ``mb_releasegroupid`` tag. +* :doc:`/plugins/export`: A new plugin to export the data from queries to a + json format. Thanks to :user:`GuilhermeHideki`. .. _fanart.tv: https://fanart.tv/ From 028c78adc80968c5e6d8145669fc4dbfb3a82e3d Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 16:05:39 +0100 Subject: [PATCH 0687/2280] Update documentation to match new hook plugin design --- docs/plugins/hook.rst | 61 +++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst index 9ede5e998..2de736c7c 100644 --- a/docs/plugins/hook.rst +++ b/docs/plugins/hook.rst @@ -8,27 +8,18 @@ allows you to run commands when an event is emitted by beets, such as syncing your library with another drive when the library is updated. Hooks are currently run in the order defined in the configuration, however this -is dependent on beets itself (may change in the future) and cannot be controlled -by this plugin. +is dependent on beets itself and it's consistency should not be depended upon. .. _hook-configuration: Configuration ------------- -To configure the plugin, make a ``hook:`` section in your configuration +To configure the plugin, make a ``hook`` section in your configuration file. The available options are: -- **hooks**: A list of events and the commands to run (see :ref:`individual-hook-configuration`) - Default: Empty. -- **substitute_event**: The string to replace in each command with the name of - the event executing it. This can be used to allow one script to act - differently depending on the event it was called by. Can be individually - overridden (see :ref:`individual-hook-configuration`). - Default: ``%EVENT%`` -- **shell**: Run each command in a shell. Can be individually overridden (see - :ref:`individual-hook-configuration`). - Default: ``yes`` +- **hooks**: A list of events and the commands to run + (see :ref:`individual-hook-configuration`). Default: Empty. .. _individual-hook-configuration: @@ -38,20 +29,24 @@ Individual Hook Configuration Each element of the ``hooks`` configuration option can be configured separately. The available options are: -- **event** (required): The name of the event that should cause this hook to execute. See - :ref:`Plugin Events ` for a list of possible values. -- **command** (required): The command to run when this hook executes. -- **substitute_event**: Hook-level override for ``substitute_event`` option in - :ref:`hook-configuration`. - Default: Value of top level ``substitute_event`` option (see :ref:`hook-configuration`) -- **shell**: Hook-level override for ``shell`` option in :ref:`hook-configuration`. - Default: Value of top level ``shell`` option (see :ref:`hook-configuration`). -- **substitute_args**: A key/value set where the key is the name of the an - argument passed to the event (see :ref:`Plugin Events ` for - a list of arguments for each event) and the value is the string to replace - in the command with the value of the argument. Note that any arguments that - are not strings will be converted to strings (e.g. Python objects). - Default: Empty. +- **event**: The name of the event that should cause this hook to + execute. See the :ref:`plugin events ` documentation for a list + of possible values. +- **command**: The command to run when this hook executes. + +.. _command-substitution: + +Command Substitution +-------------------- + +Certain key words can be replaced in commands, allowing access to event +information such as the path of an album or the name of a song. This information +is accessed using the syntax ``{property_name}``, where ``property_name`` is the +name of an argument passed to the event. ``property_name`` can also be a key on +an argument passed to the event, such as ``{album.path}``. + +You can find a list of all available events and their arguments in the +:ref:`plugin events ` documentation. Example Configuration --------------------- @@ -68,10 +63,14 @@ Example Configuration - event: cli_exit command: echo "have a nice day!" - # Output on write + # Output on item import: + # importing "" + # Where is the item being imported + - event: item_imported + command: echo "importing \"{item.path}\"" + + # Output on write: # writing to "" # Where is the file being written to - event: write - command: echo "writing to \"%FILE_NAME%\"" - substitute_args: - path: %FILE_NAME% + command: echo "writing to {path}" From 019d7cd2e67c945fd33b5b1f7bdbc0f928ef9d46 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Mon, 18 Apr 2016 12:36:42 -0300 Subject: [PATCH 0688/2280] fix some typos --- beetsplug/convert.py | 2 +- docs/plugins/index.rst | 2 +- test/test_edit.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 303a9e149..dd57918d6 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -51,7 +51,7 @@ def replace_ext(path, ext): def get_format(fmt=None): - """Return the command tempate and the extension from the config. + """Return the command template and the extension from the config. """ if not fmt: fmt = config['convert']['format'].get(unicode).lower() diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 260eb7d49..24f261963 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -101,7 +101,7 @@ Metadata * :doc:`bpm`: Measure tempo using keystrokes. * :doc:`echonest`: Automatically fetch `acoustic attributes`_ from `the Echo Nest`_ (tempo, energy, danceability, ...). -* :doc:`edit`: Edit metadata from a texteditor. +* :doc:`edit`: Edit metadata from a text editor. * :doc:`embedart`: Embed album art images into files' metadata. * :doc:`fetchart`: Fetch album cover art from various sources. * :doc:`ftintitle`: Move "featured" artists from the artist field to the title diff --git a/test/test_edit.py b/test/test_edit.py index e756f99a2..ab0ae046a 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -31,7 +31,7 @@ class ModifyFileMocker(object): """ def __init__(self, contents=None, replacements=None): - """ `self.contents` and `self.replacements` are initalized here, in + """ `self.contents` and `self.replacements` are initialized here, in order to keep the rest of the functions of this class with the same signature as `EditPlugin.get_editor()`, making mocking easier. - `contents`: string with the contents of the file to be used for From 12c6cbaeee89de56389d972d5930dcbbf7c2f9c4 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 18:44:20 +0200 Subject: [PATCH 0689/2280] update changelog --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 600bc4cb7..ed1f17833 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,9 @@ New features: for a Microsoft Azure Marketplace free account. Thanks to :user:`Kraymer`. * :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. Albums are matched using the ``mb_releasegroupid`` tag. +* :doc:`/plugins/fetchart`: The ``enforce_ratio`` option was enhanced and now + allows specifying a certain deviation that a valid image may have from being + exactly square. .. _fanart.tv: https://fanart.tv/ From c3be244109b4b5eea67cec5b17ffcffdd6dbc379 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 18 Apr 2016 18:52:18 +0200 Subject: [PATCH 0690/2280] remove the personal key warning altogether; it's also in the docs and rather obtrusive --- beetsplug/fetchart.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 43da905fd..62a43474e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -681,13 +681,6 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): available_sources.remove(u'google') sources_name = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - if not self.config['fanarttv_key'].get() and \ - u'fanarttv' in sources_name: - self._log.warn( - u'fanart.tv source enabled, but no personal API given. This ' - u'works as of now, however, fanart.tv prefers users to ' - u'register a personal key. Additionaly this makes new art ' - u'available shorter after its upload. See the documentation.') if 'remote_priority' in self.config: self._log.warning( u'The `fetch_art.remote_priority` configuration option has ' From dea091ee5370dfd3af956b93132d60efdea07157 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 19:16:31 +0100 Subject: [PATCH 0691/2280] Improve error handling for invalid commands --- beetsplug/hook.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index a32247bf8..4f38a7b9c 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -45,23 +45,20 @@ class HookPlugin(BeetsPlugin): def create_and_register_hook(self, event, command): def hook_function(**kwargs): + if command is None or len(command) == 0: + self._log.error('invalid command "{0}"', command) + return + formatted_command = command.format(event=event, **kwargs) encoded_command = formatted_command.decode(_arg_encoding()) command_pieces = shlex.split(encoded_command) - if len(command_pieces) == 0: - raise ConfigValueError('invalid command "{0}"'.format( - command)) - - self._log.debug('Running command "{0}" for event "{1}"', + self._log.debug('Running command "{0}" for event {1}', encoded_command, event) try: subprocess.Popen(command_pieces).wait() - except OSError as e: - _, _, trace = sys.exc_info() - message = '{0}: {1}'.format(e, command_pieces[0]) - - raise OSError, message, trace + except OSError as exc: + self._log.error('hook for {0} failed: {1}', event, exc) self.register_listener(event, hook_function) From 85fd60852fdf5f927cd1060fca7c5b8316db4269 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 18 Apr 2016 19:21:31 +0100 Subject: [PATCH 0692/2280] Remove unused dependencies --- beetsplug/hook.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 4f38a7b9c..81fb9a7f9 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -17,11 +17,9 @@ from __future__ import division, absolute_import, print_function import shlex import subprocess -import sys from beets.plugins import BeetsPlugin from beets.ui import _arg_encoding -from beets.util.confit import ConfigValueError class HookPlugin(BeetsPlugin): From c27907b043bf4480de18994a6f19ff90ac5ed251 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 14:10:54 +0200 Subject: [PATCH 0693/2280] enable fetchart to store the artworks origin in a flexible field; as of now untested --- beetsplug/fetchart.py | 36 +++++++++++++++++++++++------------- docs/plugins/fetchart.rst | 13 +++++++++++++ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index c00124623..5c005656a 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -660,9 +660,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): def __init__(self): super(FetchArtPlugin, self).__init__() - # Holds paths to downloaded images between fetching them and - # placing them in the filesystem. - self.art_paths = {} + # Holds candidates corresponding to downloaded images between + # fetching them and placing them in the filesystem. + self.art_candidates = {} self.config.add({ 'auto': True, @@ -675,7 +675,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'coverart', 'itunes', 'amazon', 'albumart'], 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', - 'fanarttv_key': None + 'fanarttv_key': None, + 'store_origin': False }) self.config['google_key'].redact = True self.config['fanarttv_key'].redact = True @@ -703,6 +704,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): cover_names = self.config['cover_names'].as_str_seq() self.cover_names = map(util.bytestring_path, cover_names) self.cautious = self.config['cautious'].get(bool) + self.store_origin = self.config['store_origin'].get(bool) self.src_removed = (config['import']['delete'].get(bool) or config['import']['move'].get(bool)) @@ -753,19 +755,28 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): candidate = self.art_for_album(task.album, task.paths, local) if candidate: - self.art_paths[task] = candidate.path + self.art_candidates[task] = candidate + + def _set_art(self, album, candidate, delete=False): + album.set_art(candidate.path, delete) + if self.store_origin: + # store the origin of the chosen artwork in a flexible field + self._log.debug( + u"Storing artorigin for {0.albumartist} - {0.album}", + album) + album.artorigin = candidate.source + album.store() # Synchronous; after music files are put in place. def assign_art(self, session, task): """Place the discovered art in the filesystem.""" - if task in self.art_paths: - path = self.art_paths.pop(task) + if task in self.art_candidates: + candidate = self.art_candidates.pop(task) + + self._set_art(task.album, candidate, not self.src_removed) - album = task.album - album.set_art(path, not self.src_removed) - album.store() if self.src_removed: - task.prune(path) + task.prune(candidate.path) # Manual album art fetching. def commands(self): @@ -842,8 +853,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): candidate = self.art_for_album(album, local_paths) if candidate: - album.set_art(candidate.path, False) - album.store() + self._set_art(album, candidate) message = ui.colorize('text_success', u'found album art') else: message = ui.colorize('text_error', u'no art found') diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 591dbc4b4..72745e73a 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -62,6 +62,9 @@ file. The available options are: Default: The `beets custom search engine`_, which searches the entire web. **fanarttv_key**: The personal API key for requesting art from fanart.tv. See below. + **store_origin**: If enabled, fetchart store the artwork's source in a + flexible tag. See below for the rationale behind this. + Default: ``no``. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ or `Pillow`_. @@ -182,6 +185,16 @@ personal key will give you earlier access to new art. .. _on their blog: https://fanart.tv/2015/01/personal-api-keys/ +Storing the artwork's origin +---------------------------- + +Storing the current artwork's source gives the opportunity to selectively +search for new art. For example, if some albums have artwork placed manually in +their directories that should not be replaced by a forced album art fetch, you +could do + +``beet fetchart -f ^artorigin:filesystem`` + Embedding Album Art ------------------- From 740efc0a0e14fab57abf9d86e8b1b9cb0d488c8d Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 21:32:04 +0200 Subject: [PATCH 0694/2280] small fixes; consistently use 'source' instead of 'origin' --- beetsplug/fetchart.py | 12 ++++++------ docs/plugins/fetchart.rst | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 5c005656a..291181db7 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -676,7 +676,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): 'google_key': None, 'google_engine': u'001442825323518660753:hrh5ch1gjzm', 'fanarttv_key': None, - 'store_origin': False + 'store_source': False, }) self.config['google_key'].redact = True self.config['fanarttv_key'].redact = True @@ -704,7 +704,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): cover_names = self.config['cover_names'].as_str_seq() self.cover_names = map(util.bytestring_path, cover_names) self.cautious = self.config['cautious'].get(bool) - self.store_origin = self.config['store_origin'].get(bool) + self.store_source = self.config['store_source'].get(bool) self.src_removed = (config['import']['delete'].get(bool) or config['import']['move'].get(bool)) @@ -759,12 +759,12 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): def _set_art(self, album, candidate, delete=False): album.set_art(candidate.path, delete) - if self.store_origin: - # store the origin of the chosen artwork in a flexible field + if self.store_source: + # store the source of the chosen artwork in a flexible field self._log.debug( - u"Storing artorigin for {0.albumartist} - {0.album}", + u"Storing art_source for {0.albumartist} - {0.album}", album) - album.artorigin = candidate.source + album.art_source = candidate.source album.store() # Synchronous; after music files are put in place. diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 72745e73a..04ee5d699 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -62,8 +62,8 @@ file. The available options are: Default: The `beets custom search engine`_, which searches the entire web. **fanarttv_key**: The personal API key for requesting art from fanart.tv. See below. - **store_origin**: If enabled, fetchart store the artwork's source in a - flexible tag. See below for the rationale behind this. +- **store_source**: If enabled, fetchart store the artwork's source in a + flexible tag named ``art_source``. See below for the rationale behind this. Default: ``no``. Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ @@ -185,7 +185,7 @@ personal key will give you earlier access to new art. .. _on their blog: https://fanart.tv/2015/01/personal-api-keys/ -Storing the artwork's origin +Storing the Artwork's Source ---------------------------- Storing the current artwork's source gives the opportunity to selectively @@ -193,7 +193,7 @@ search for new art. For example, if some albums have artwork placed manually in their directories that should not be replaced by a forced album art fetch, you could do -``beet fetchart -f ^artorigin:filesystem`` +``beet fetchart -f ^art_source:filesystem`` Embedding Album Art ------------------- From ec4595677064de4e264d3ff35757e94d1d891d8e Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 16 Apr 2016 21:36:46 +0200 Subject: [PATCH 0695/2280] update changelog --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index c9e8ed67b..721c9ab8a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,8 @@ New features: * :doc:`/plugins/fetchart`: The ``enforce_ratio`` option was enhanced and now allows specifying a certain deviation that a valid image may have from being exactly square. +* :doc:`/plugins/fetchart`: The plugin can now optionally save the artwork's + source in a flexible field; for a usecase see the documentation. * :doc:`/plugins/export`: A new plugin to export the data from queries to a json format. Thanks to :user:`GuilhermeHideki`. From 7a9c3e592b37fffa24b6f5a9fa952f4b2beae197 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 17 Apr 2016 14:18:01 +0200 Subject: [PATCH 0696/2280] document values written to art_source --- docs/plugins/fetchart.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 04ee5d699..f59761bbb 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -195,6 +195,12 @@ could do ``beet fetchart -f ^art_source:filesystem`` +The values written to ``art_source`` are: + +``'Cover Art Archive'``, ``'Amazon'``, ``'AlbumArt.org scraper'``, ``'Google Images'``, +``'fanart.tv'``, ``'iTunes Store'``, ``'Wikipedia (queried through DBpedia)'``, +``'Filesystem'`` + Embedding Album Art ------------------- From 5fbca32ea44cb0c4490b95ab516c52aa097682d9 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 17 Apr 2016 20:15:12 +0200 Subject: [PATCH 0697/2280] reuse the 'sources' names from the configuration for art_source --- beetsplug/fetchart.py | 4 ++-- docs/plugins/fetchart.rst | 17 +++++++---------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 291181db7..db4d0034e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -197,7 +197,7 @@ class ArtSource(RequestMixin): raise NotImplementedError() def _candidate(self, **kwargs): - return Candidate(source=self.NAME, log=self._log, **kwargs) + return Candidate(source=self, log=self._log, **kwargs) def fetch_image(self, candidate, extra): raise NotImplementedError() @@ -764,7 +764,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self._log.debug( u"Storing art_source for {0.albumartist} - {0.album}", album) - album.art_source = candidate.source + album.art_source = SOURCE_NAMES[type(candidate.source)] album.store() # Synchronous; after music files are put in place. diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index f59761bbb..2812c7745 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -62,7 +62,7 @@ file. The available options are: Default: The `beets custom search engine`_, which searches the entire web. **fanarttv_key**: The personal API key for requesting art from fanart.tv. See below. -- **store_source**: If enabled, fetchart store the artwork's source in a +- **store_source**: If enabled, fetchart stores the artwork's source in a flexible tag named ``art_source``. See below for the rationale behind this. Default: ``no``. @@ -188,18 +188,15 @@ personal key will give you earlier access to new art. Storing the Artwork's Source ---------------------------- -Storing the current artwork's source gives the opportunity to selectively -search for new art. For example, if some albums have artwork placed manually in -their directories that should not be replaced by a forced album art fetch, you -could do +Storing the current artwork's source might be used to narrow down +``fetchart`` commands. For example, if some albums have artwork placed +manually in their directories that should not be replaced by a forced +album art fetch, you could do ``beet fetchart -f ^art_source:filesystem`` -The values written to ``art_source`` are: - -``'Cover Art Archive'``, ``'Amazon'``, ``'AlbumArt.org scraper'``, ``'Google Images'``, -``'fanart.tv'``, ``'iTunes Store'``, ``'Wikipedia (queried through DBpedia)'``, -``'Filesystem'`` +The values written to ``art_source`` are the same names used in the ``sources`` +configuration value. Embedding Album Art ------------------- From ac2f7fe7127150d2ce0f84890380a2aedd79bc16 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 20 Apr 2016 12:59:18 +0200 Subject: [PATCH 0698/2280] Fix the fanarttv source failing when there were images found, but no cover art --- beetsplug/fetchart.py | 12 ++++++------ test/test_art.py | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index db4d0034e..797d774c4 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -395,12 +395,12 @@ class FanartTV(RemoteArtSource): return matches = [] - # can there be more than one releasegroupid per responce? - for mb_releasegroupid in data.get(u'albums', dict()): - if album.mb_releasegroupid == mb_releasegroupid: - # note: there might be more art referenced, e.g. cdart - matches.extend( - data[u'albums'][mb_releasegroupid][u'albumcover']) + # can there be more than one releasegroupid per response? + for mbid, art in data.get(u'albums', dict()).items(): + # there might be more art referenced, e.g. cdart, and an albumcover + # might not be present, even if the request was succesful + if album.mb_releasegroupid == mbid and u'albumcover' in art: + matches.extend(art[u'albumcover']) # can this actually occur? else: self._log.debug(u'fanart.tv: unexpected mb_releasegroupid in ' diff --git a/test/test_art.py b/test/test_art.py index 2e7db8439..3014707a8 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -315,6 +315,23 @@ class FanartTVTest(UseThePlugin): } } }""" + RESPONSE_NO_ART = u"""{ + "name": "artistname", + "mbid_id": "artistid", + "albums": { + "thereleasegroupid": { + "cdart": [ + { + "id": "123", + "url": "http://example.com/4.jpg", + "likes": "0", + "disc": "1", + "size": "1000" + } + ] + } + } + }""" RESPONSE_ERROR = u"""{ "status": "error", "error message": "the error message" @@ -355,6 +372,14 @@ class FanartTVTest(UseThePlugin): with self.assertRaises(StopIteration): next(self.source.get(album, self.extra)) + def test_fanarttv_only_other_images(self): + # The source used to fail when there were images present, but no cover + album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') + self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', + self.RESPONSE_NO_ART) + with self.assertRaises(StopIteration): + next(self.source.get(album, self.extra)) + @_common.slow_test() class ArtImporterTest(UseThePlugin): From bf1b06f0c7f28b18a147ab6f15d6b65e7156a5b7 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Fri, 22 Apr 2016 17:30:06 -0300 Subject: [PATCH 0699/2280] don't print entire lyrics during import --- beetsplug/lyrics.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 6a6bc7729..afda54851 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -692,7 +692,6 @@ class LyricsPlugin(plugins.BeetsPlugin): item.lyrics = lyrics if write: item.try_write() - print(lyrics) item.store() def get_lyrics(self, artist, title): From 172498fd33fca44b5089688491044a0b257c5256 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Fri, 22 Apr 2016 19:02:58 -0300 Subject: [PATCH 0700/2280] use _out_encoding() to let the user override the encoding (e.g. cp65001/utf-8 throws Exception) --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ac919d7d2..89e09c05e 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -193,7 +193,7 @@ def input_(prompt=None): except EOFError: raise UserError(u'stdin stream ended while input required') - return resp.decode(sys.stdin.encoding or 'utf8', 'ignore') + return resp.decode(_out_encoding(), 'ignore') def input_options(options, require=False, prompt=None, fallback_prompt=None, From f18fe05e150ef0d44dc01657b37bc0146dd65bcb Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Fri, 22 Apr 2016 20:18:02 -0300 Subject: [PATCH 0701/2280] fix: use a _in_encoding(): instead _out_encoding(): --- beets/ui/__init__.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 89e09c05e..9096a87da 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -71,6 +71,15 @@ class UserError(Exception): # Encoding utilities. +def _in_encoding(): + """Get the encoding to use for *inputting* strings to the console. + """ + try: + return sys.stdin.encoding or 'utf-8' + except LookupError: + # TODO: create user config + return 'utf-8' + def _out_encoding(): """Get the encoding to use for *outputting* strings to the console. @@ -193,7 +202,7 @@ def input_(prompt=None): except EOFError: raise UserError(u'stdin stream ended while input required') - return resp.decode(_out_encoding(), 'ignore') + return resp.decode(_in_encoding(), 'ignore') def input_options(options, require=False, prompt=None, fallback_prompt=None, From 271f7c8d1756050e95e916f6de9fbdc779f141b1 Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Sat, 23 Apr 2016 13:59:25 -0300 Subject: [PATCH 0702/2280] new template path functions: %first{} and %ifdef{} (#1951) * New template functions: %first{} and %ifdef{} * Add documentation * Add to changelog --- beets/library.py | 29 +++++++++++++++++++++++++ docs/changelog.rst | 1 + docs/reference/pathformat.rst | 10 +++++++++ test/test_library.py | 40 +++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+) diff --git a/beets/library.py b/beets/library.py index f2c3875b0..ed1938671 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1466,6 +1466,35 @@ class DefaultTemplateFunctions(object): self.lib._memotable[memokey] = res return res + @staticmethod + def tmpl_first(s, count=1, skip=0, sep=u'; ', join_str=u'; '): + """ Gets the item(s) from x to y in a string separated by something + and join then with something + + :param s: the string + :param count: The number of items included + :param skip: The number of items skipped + :param sep: the separator. Usually is '; ' (default) or '/ ' + :param join_str: the string which will join the items, default '; '. + """ + skip = int(skip) + count = skip + int(count) + return join_str.join(s.split(sep)[skip:count]) + + def tmpl_ifdef(self, field, trueval=u'', falseval=u''): + """ If field exists return trueval or the field (default) + otherwise, emit return falseval (if provided). + + :param field: The name of the field + :param trueval: The string if the condition is true + :param falseval: The string if the condition is false + :return: The string, based on condition + """ + if self.item.formatted().get(field): + return trueval if trueval else self.item.formatted().get(field) + else: + return falseval + # Get the name of tmpl_* functions in the above class. DefaultTemplateFunctions._func_names = \ diff --git a/docs/changelog.rst b/docs/changelog.rst index 721c9ab8a..4908219a7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,7 @@ New features: source in a flexible field; for a usecase see the documentation. * :doc:`/plugins/export`: A new plugin to export the data from queries to a json format. Thanks to :user:`GuilhermeHideki`. +* :doc:`/reference/pathformat`: new functions: %first{} and %ifdef{} .. _fanart.tv: https://fanart.tv/ diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 8efe54cd2..b5d754bd4 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -76,6 +76,16 @@ These functions are built in to beets: * ``%time{date_time,format}``: Return the date and time in any format accepted by `strftime`_. For example, to get the year some music was added to your library, use ``%time{$added,%Y}``. +* ``%first{text}``: Returns the first item, separated by ``; ``. + You can use ``%first{text,count,skip}``, where ``count`` is the number of + items (default 1) and ``skip`` is number to skip (default 0). You can also use + ``%first{text,count,skip,sep,join}`` where ``sep`` is the separator, like + ``;`` or ``/`` and join is the text to concatenate the items. + For example, +* ``%ifdef{field}``, ``%ifdef{field,truetext}`` or + ``%ifdef{field,truetext,falsetext}``: If ``field`` exists, then return + ``truetext`` or ``field`` (default). Otherwise, returns ``falsetext``. + The ``field`` should be entered without ``$``. .. _unidecode module: http://pypi.python.org/pypi/Unidecode .. _strftime: http://docs.python.org/2/library/time.html#time.strftime diff --git a/test/test_library.py b/test/test_library.py index d57566f5f..4d6a51b93 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -617,6 +617,46 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): self._setf(u'%foo{bar}') self._assert_dest('/base/%foo{bar}') + def test_if_def_field_return_self(self): + self.i.bar = 3 + self._setf(u'%ifdef{bar}') + self._assert_dest('/base/3') + + def test_if_def_field_not_defined(self): + self._setf(u' %ifdef{bar}/$artist') + self._assert_dest('/base/the artist') + + def test_if_def_field_not_defined_2(self): + self._setf(u'$artist/%ifdef{bar}') + self._assert_dest('/base/the artist') + + def test_if_def_true(self): + self._setf(u'%ifdef{artist,cool}') + self._assert_dest('/base/cool') + + def test_if_def_true_complete(self): + self.i.series = "Now" + self._setf(u'%ifdef{series,$series Series,Albums}/$album') + self._assert_dest('/base/Now Series/the album') + + def test_if_def_false_complete(self): + self._setf(u'%ifdef{plays,$plays,not_played}') + self._assert_dest('/base/not_played') + + def test_first(self): + self.i.genres = "Pop; Rock; Classical Crossover" + self._setf(u'%first{$genres}') + self._assert_dest('/base/Pop') + + def test_first_skip(self): + self.i.genres = "Pop; Rock; Classical Crossover" + self._setf(u'%first{$genres,1,2}') + self._assert_dest('/base/Classical Crossover') + + def test_first_different_sep(self): + self._setf(u'%first{Alice / Bob / Eve,2,0, / , & }') + self._assert_dest('/base/Alice & Bob') + class DisambiguationTest(_common.TestCase, PathFormattingMixin): def setUp(self): From 4a5b886944a08542dbcbfbb59f37ad1715c24e2b Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 24 Apr 2016 00:35:15 +0200 Subject: [PATCH 0703/2280] Fix two non-guarded import statements in the lyrics plugin These could make the import process crash with a traceback. --- beetsplug/lyrics.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index afda54851..177bf7c1d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -415,7 +415,12 @@ def scrape_lyrics_from_html(html): """Scrape lyrics from a URL. If no lyrics can be found, return None instead. """ - from bs4 import SoupStrainer, BeautifulSoup + try: + from bs4 import SoupStrainer, BeautifulSoup + except ImportError: + # TODO: refactor the plugin to get access to a logger here and log + # a warning + pass if not html: return None @@ -673,7 +678,12 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) if self.config['bing_client_secret'].get(): - from langdetect import detect + try: + from langdetect import detect + except ImportError: + self._log.warn(u'To use bing translations, you need to ' + u'install the langdetect module. See the ' + u'documentation for further details.') lang_from = detect(lyrics) if self.config['bing_lang_to'].get() != lang_from and ( From 607f41be430507dc5f7522c19b5ee95605e0995c Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 24 Apr 2016 00:42:31 +0200 Subject: [PATCH 0704/2280] Fix the previous fix... --- beetsplug/lyrics.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 177bf7c1d..de9e1b313 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -420,7 +420,7 @@ def scrape_lyrics_from_html(html): except ImportError: # TODO: refactor the plugin to get access to a logger here and log # a warning - pass + return None if not html: return None @@ -675,16 +675,19 @@ class LyricsPlugin(plugins.BeetsPlugin): lyrics = u"\n\n---\n\n".join([l for l in lyrics if l]) + has_langdetect = False + if self.config['bing_client_secret'].get(): + try: + from langdetect import detect + has_langdetect = True + except ImportError: + self._log.warn(u'To use bing translations, you need to ' + u'install the langdetect module. See the ' + u'documentation for further details.') + if lyrics: self._log.info(u'fetched lyrics: {0}', item) - if self.config['bing_client_secret'].get(): - try: - from langdetect import detect - except ImportError: - self._log.warn(u'To use bing translations, you need to ' - u'install the langdetect module. See the ' - u'documentation for further details.') - + if has_langdetect: lang_from = detect(lyrics) if self.config['bing_lang_to'].get() != lang_from and ( not self.config['bing_lang_from'] or ( From 9c835715a3a60bad7eccc88079635caec7b86d84 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 24 Apr 2016 22:28:52 +0200 Subject: [PATCH 0705/2280] Update lyrics.rst --- docs/plugins/lyrics.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index b922b747f..b55811d0b 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -133,10 +133,11 @@ using `pip`_ by typing:: pip install langdetect You also need to register for a Microsoft Azure Marketplace free account and -to the `Microsoft Translator API`_. Follow the four steps process, specifically -at step 3 enter `beets`` as *Client ID* and copy/paste the generated -*Client secret*. into your ``bing_client_secret`` configuration, alongside -``bing_lang_to`` target `language code`_. +to the `Microsoft Translator API`_. +Follow the four steps process, specifically at step 3 enter `beets` as +*Client ID* and copy/paste the generated *Client secret* into your +``bing_client_secret`` configuration, alongside ``bing_lang_to`` target +`language code`_. .. _langdetect: https://pypi.python.org/pypi/langdetect .. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx From d3af2d53755acb07ba05a2e1fe58174c9d9a146f Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 24 Apr 2016 22:29:10 +0200 Subject: [PATCH 0706/2280] Update lyrics.rst --- docs/plugins/lyrics.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index b55811d0b..c1d1d67cd 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -134,6 +134,7 @@ using `pip`_ by typing:: You also need to register for a Microsoft Azure Marketplace free account and to the `Microsoft Translator API`_. + Follow the four steps process, specifically at step 3 enter `beets` as *Client ID* and copy/paste the generated *Client secret* into your ``bing_client_secret`` configuration, alongside ``bing_lang_to`` target From 3c10be117605b48fa381389448fc9d1e548dece2 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 24 Apr 2016 22:30:55 +0200 Subject: [PATCH 0707/2280] Update lyrics.rst --- docs/plugins/lyrics.rst | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index c1d1d67cd..8b88c7ef8 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -133,12 +133,10 @@ using `pip`_ by typing:: pip install langdetect You also need to register for a Microsoft Azure Marketplace free account and -to the `Microsoft Translator API`_. - -Follow the four steps process, specifically at step 3 enter `beets` as -*Client ID* and copy/paste the generated *Client secret* into your -``bing_client_secret`` configuration, alongside ``bing_lang_to`` target -`language code`_. +to the `Microsoft Translator API`_. Follow the four steps process, specifically +at step 3 enter ``beets`` as *Client ID* and copy/paste the generated +*Client secret* into your ``bing_client_secret`` configuration, alongside +``bing_lang_to`` target `language code`_. .. _langdetect: https://pypi.python.org/pypi/langdetect .. _Microsoft Translator API: https://www.microsoft.com/en-us/translator/getstarted.aspx From 2f1dd9451b9b189a6518ec775363fe9283245200 Mon Sep 17 00:00:00 2001 From: Dave Hayes Date: Mon, 25 Apr 2016 13:04:05 -0500 Subject: [PATCH 0708/2280] Add notes for installing the ZSH completion script --- docs/reference/cli.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index fcef6d23f..faae67ee6 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -435,7 +435,10 @@ later on you will want to re-generate the script. zsh ``` -If you use zsh, take a look at the included `completion script`_. +If you use zsh, take a look at the included `completion script`_. The script +should be placed in a directory that is part of your ``fpath``, and `not` +sourced in your ``.zshrc``. Running ``echo $fpath`` will give you a list of +valid directories. Another approach is to use zsh's bash completion compatibility. This snippet defines some bash-specific functions to make this work without errors:: From 1be9c3003ef297374abd9dfc6bee00811286570f Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 25 Apr 2016 19:14:30 +0100 Subject: [PATCH 0709/2280] Use different method to remove junk from LyricsWiki Use `_scrape_strip_cruft` instead of `scrape_lyrics_from_html` so that LyricsWiki does not depend on Beautiful Soup. --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index de9e1b313..70ce9c38b 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -335,7 +335,7 @@ class LyricsWiki(SymbolsReplaced): # Get the HTML fragment inside the appropriate HTML element and then # extract the text from it. html_frag = extract_text_in(unescape(html), u"
") - lyrics = scrape_lyrics_from_html(html_frag) + lyrics = _scrape_strip_cruft(html_frag, True) if lyrics and 'Unfortunately, we are not licensed' not in lyrics: return lyrics From c5e2334fb523052693669b71f49fb9443e74acbb Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Mon, 25 Apr 2016 19:24:26 +0100 Subject: [PATCH 0710/2280] Remove useless unescape Remove useless unescape as _scrape_script_cruft does it for us. --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 70ce9c38b..afd536394 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -334,7 +334,7 @@ class LyricsWiki(SymbolsReplaced): # Get the HTML fragment inside the appropriate HTML element and then # extract the text from it. - html_frag = extract_text_in(unescape(html), u"
") + html_frag = extract_text_in(html, u"
") lyrics = _scrape_strip_cruft(html_frag, True) if lyrics and 'Unfortunately, we are not licensed' not in lyrics: From 0395e7fd8095a1c03d2b9d1c3c0576ea4b95ce6e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Apr 2016 19:49:46 -0700 Subject: [PATCH 0711/2280] Configure CodeCov Apparently, CodeCov switched to a new configuration scheme without telling us. :cry: This turned on annoying pull-request comments. I *hope* this turns them off again. --- codecov.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 codecov.yaml diff --git a/codecov.yaml b/codecov.yaml new file mode 100644 index 000000000..d01e442e5 --- /dev/null +++ b/codecov.yaml @@ -0,0 +1,12 @@ +# Don't post a comment on pull requests. +comment: off + +# I think this disables commit statuses? +coverage: + status: + project: + enabled: no + patch: + enabled: no + changes: + enabled: no From 144c732ab0f9c9294da13bd5e49b2bd55611bd62 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Tue, 26 Apr 2016 23:33:52 +0100 Subject: [PATCH 0712/2280] Add flake8 check for pep8 naming Add flake8 check for pep8 naming using pep8-naming. --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index cd29693a1..6eba8395d 100644 --- a/tox.ini +++ b/tox.ini @@ -48,4 +48,5 @@ commands = deps = flake8 flake8-future-import + pep8-naming commands = flake8 beets beetsplug beet test setup.py docs From 09bc2504133150ab19eda133565b9e513ac81544 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 26 Apr 2016 16:59:23 -0700 Subject: [PATCH 0713/2280] Fix #1960: Unicode in fetchart Wikipedia source The SparQL query needed to use a Unicode literal. --- beetsplug/fetchart.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 797d774c4..a18e362e5 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -454,7 +454,7 @@ class Wikipedia(RemoteArtSource): NAME = u"Wikipedia (queried through DBpedia)" DBPEDIA_URL = 'http://dbpedia.org/sparql' WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' - SPARQL_QUERY = '''PREFIX rdf: + SPARQL_QUERY = u'''PREFIX rdf: PREFIX dbpprop: PREFIX owl: PREFIX rdfs: diff --git a/docs/changelog.rst b/docs/changelog.rst index 4908219a7..1844c4d87 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -41,6 +41,8 @@ Fixes: guess the URL for lyrics. :bug:`1880` * :doc:`/plugins/edit`: Fail gracefully when the configured text editor command can't be invoked. :bug:`1927` +* :doc:`/plugins/fetchart`: Fix a crash in the Wikipedia backend on non-ASCII + artist and album names. :bug:`1960` 1.3.17 (February 7, 2016) From 91c8a30e55b38b507a763c3750a7dea94c5c1147 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 26 Apr 2016 17:16:52 -0700 Subject: [PATCH 0714/2280] codecov.yaml -> codecov.yml :angry: :cry: --- codecov.yaml => codecov.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename codecov.yaml => codecov.yml (100%) diff --git a/codecov.yaml b/codecov.yml similarity index 100% rename from codecov.yaml rename to codecov.yml From b1c58e99ecbaa5fca5d2eb7dc98d2a213d44e7e3 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 27 Apr 2016 20:15:10 +0100 Subject: [PATCH 0715/2280] Update code to match pep8 naming standards --- beets/autotag/hooks.py | 2 +- beets/dbcore/db.py | 8 ++++---- beets/dbcore/query.py | 8 ++++---- beets/logging.py | 2 +- beets/util/artresizer.py | 22 +++++++++++----------- beetsplug/bucket.py | 13 ++++++++----- beetsplug/export.py | 2 +- beetsplug/fuzzy.py | 6 +++--- test/_common.py | 4 ++-- test/test_art.py | 4 ++-- test/test_autotag.py | 14 +++++++------- test/test_convert.py | 4 ++-- test/test_datequery.py | 4 ++-- test/test_edit.py | 4 ++-- test/test_importadded.py | 12 ++++++------ test/test_importer.py | 6 +++--- test/test_lastgenre.py | 18 +++++++++--------- test/test_lyrics.py | 8 ++++---- test/test_mediafile.py | 6 +++--- test/test_mpdstats.py | 14 +++++++------- test/test_permissions.py | 12 ++++++------ test/test_query.py | 6 +++--- test/test_smartplaylist.py | 10 +++++----- test/test_ui.py | 16 ++++++++-------- 24 files changed, 104 insertions(+), 101 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 26b7f5819..4a89e6dc8 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -297,7 +297,7 @@ class Distance(object): self._penalties = {} @LazyClassProperty - def _weights(cls): + def _weights(self): """A dictionary from keys to floating-point weights. """ weights_view = config['match']['distance_weights'] diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 09a96d8c2..ba67dd6d1 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -209,13 +209,13 @@ class Model(object): # Essential field accessors. @classmethod - def _type(self, key): + def _type(cls, key): """Get the type of a field, a `Type` instance. If the field has no explicit type, it is given the base `Type`, which does no conversion. """ - return self._fields.get(key) or self._types.get(key) or types.DEFAULT + return cls._fields.get(key) or cls._types.get(key) or types.DEFAULT def __getitem__(self, key): """Get the value for a field. Raise a KeyError if the field is @@ -274,11 +274,11 @@ class Model(object): return base_keys @classmethod - def all_keys(self): + def all_keys(cls): """Get a list of available keys for objects of this type. Includes fixed and computed fields. """ - return list(self._fields) + self._getters().keys() + return list(cls._fields) + cls._getters().keys() # Act like a dictionary. diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 8e3b7ca16..ed20d320d 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -146,9 +146,9 @@ class NoneQuery(FieldQuery): return self.field + " IS NULL", () @classmethod - def match(self, item): + def match(cls, item): try: - return item[self.field] is None + return item[cls.field] is None except KeyError: return True @@ -841,8 +841,8 @@ class SlowFieldSort(FieldSort): class NullSort(Sort): """No sorting. Leave results unsorted.""" - def sort(items): - return items + def sort(self): + return self def __nonzero__(self): return self.__bool__() diff --git a/beets/logging.py b/beets/logging.py index e4e628d69..a94da1c62 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -126,7 +126,7 @@ my_manager = copy(Logger.manager) my_manager.loggerClass = BeetsLogger -def getLogger(name=None): +def getLogger(name=None): # noqa if name: return my_manager.getLogger(name) else: diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 9d2ee5952..e94f8c380 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -149,15 +149,15 @@ class Shareable(type): lazily-created shared instance of ``MyClass`` while calling ``MyClass()`` to construct a new object works as usual. """ - def __init__(cls, name, bases, dict): - super(Shareable, cls).__init__(name, bases, dict) - cls._instance = None + def __init__(self, name, bases, dict): + super(Shareable, self).__init__(name, bases, dict) + self._instance = None @property - def shared(cls): - if cls._instance is None: - cls._instance = cls() - return cls._instance + def shared(self): + if self._instance is None: + self._instance = self() + return self._instance class ArtResizer(object): @@ -218,18 +218,18 @@ class ArtResizer(object): @staticmethod def _check_method(): """Return a tuple indicating an available method and its version.""" - version = has_IM() + version = get_image_magick_version() if version: return IMAGEMAGICK, version - version = has_PIL() + version = get_pil_version() if version: return PIL, version return WEBPROXY, (0) -def has_IM(): +def get_image_magick_version(): """Return Image Magick version or None if it is unavailable Try invoking ImageMagick's "convert".""" try: @@ -248,7 +248,7 @@ def has_IM(): return None -def has_PIL(): +def get_pil_version(): """Return Image Magick version or None if it is unavailable Try importing PIL.""" try: diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index cfd4106d4..21acb1f1e 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -26,6 +26,9 @@ from itertools import tee, izip from beets import plugins, ui +ASCII_DIGITS = string.digits + string.ascii_lowercase + + class BucketError(Exception): pass @@ -155,23 +158,23 @@ def build_alpha_spans(alpha_spans_str, alpha_regexs): [from...to] """ spans = [] - ASCII_DIGITS = string.digits + string.ascii_lowercase + for elem in alpha_spans_str: if elem in alpha_regexs: spans.append(re.compile(alpha_regexs[elem])) else: bucket = sorted([x for x in elem.lower() if x.isalnum()]) if bucket: - beginIdx = ASCII_DIGITS.index(bucket[0]) - endIdx = ASCII_DIGITS.index(bucket[-1]) + begin_index = ASCII_DIGITS.index(bucket[0]) + end_index = ASCII_DIGITS.index(bucket[-1]) else: raise ui.UserError(u"invalid range defined for alpha bucket " u"'%s': no alphanumeric character found" % elem) spans.append( re.compile( - "^[" + ASCII_DIGITS[beginIdx:endIdx + 1] + - ASCII_DIGITS[beginIdx:endIdx + 1].upper() + "]" + "^[" + ASCII_DIGITS[begin_index:end_index + 1] + + ASCII_DIGITS[begin_index:end_index + 1].upper() + "]" ) ) return spans diff --git a/beetsplug/export.py b/beetsplug/export.py index 93362550f..641b9fefc 100644 --- a/beetsplug/export.py +++ b/beetsplug/export.py @@ -119,7 +119,7 @@ class ExportFormat(object): """The output format type""" @classmethod - def factory(self, type, **kwargs): + def factory(cls, type, **kwargs): if type == "json": if kwargs['file_path']: return JsonFileFormat(**kwargs) diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index 4a631a887..3decdc602 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -26,13 +26,13 @@ import difflib class FuzzyQuery(StringFieldQuery): @classmethod - def string_match(self, pattern, val): + def string_match(cls, pattern, val): # smartcase if pattern.islower(): val = val.lower() - queryMatcher = difflib.SequenceMatcher(None, pattern, val) + query_matcher = difflib.SequenceMatcher(None, pattern, val) threshold = config['fuzzy']['threshold'].as_number() - return queryMatcher.quick_ratio() >= threshold + return query_matcher.quick_ratio() >= threshold class FuzzyPlugin(BeetsPlugin): diff --git a/test/_common.py b/test/_common.py index c64ff0b71..33928fb66 100644 --- a/test/_common.py +++ b/test/_common.py @@ -167,11 +167,11 @@ class TestCase(unittest.TestCase): beets.config.clear() beets.config._materialized = False - def assertExists(self, path): + def assertExists(self, path): # noqa self.assertTrue(os.path.exists(path), u'file does not exist: {!r}'.format(path)) - def assertNotExists(self, path): + def assertNotExists(self, path): # noqa self.assertFalse(os.path.exists(path), u'file exists: {!r}'.format((path))) diff --git a/test/test_art.py b/test/test_art.py index 3014707a8..44b3b9bd4 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -518,7 +518,7 @@ class ArtForAlbumTest(UseThePlugin): fetchart.FileSystem.get = self.old_fs_source_get super(ArtForAlbumTest, self).tearDown() - def _assertImageIsValidArt(self, image_file, should_exist): + def _assertImageIsValidArt(self, image_file, should_exist): # noqa self.assertExists(image_file) self.image_file = image_file @@ -531,7 +531,7 @@ class ArtForAlbumTest(UseThePlugin): else: self.assertIsNone(candidate) - def _assertImageResized(self, image_file, should_resize): + def _assertImageResized(self, image_file, should_resize): # noqa self.image_file = image_file with patch.object(ArtResizer.shared, 'resize') as mock_resize: self.plugin.art_for_album(self.album, [''], True) diff --git a/test/test_autotag.py b/test/test_autotag.py index 30d60f8c4..bdc3ee2d4 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -940,13 +940,13 @@ class EnumTest(_common.TestCase): Test Enum Subclasses defined in beets.util.enumeration """ def test_ordered_enum(self): - OrderedEnumTest = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) - self.assertLess(OrderedEnumTest.a, OrderedEnumTest.b) - self.assertLess(OrderedEnumTest.a, OrderedEnumTest.c) - self.assertLess(OrderedEnumTest.b, OrderedEnumTest.c) - self.assertGreater(OrderedEnumTest.b, OrderedEnumTest.a) - self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.a) - self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.b) + ordered_enum = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) + self.assertLess(ordered_enum.a, ordered_enum.b) + self.assertLess(ordered_enum.a, ordered_enum.c) + self.assertLess(ordered_enum.b, ordered_enum.c) + self.assertGreater(ordered_enum.b, ordered_enum.a) + self.assertGreater(ordered_enum.c, ordered_enum.a) + self.assertGreater(ordered_enum.c, ordered_enum.b) def suite(): diff --git a/test/test_convert.py b/test/test_convert.py index 20ed6c743..679b70a4f 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -40,7 +40,7 @@ class TestHelper(helper.TestHelper): return u'sh -c "cp \'$source\' \'$dest\'; ' \ u'printf {0} >> \'$dest\'"'.format(tag) - def assertFileTag(self, path, tag): + def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. """ self.assertTrue(os.path.isfile(path), @@ -50,7 +50,7 @@ class TestHelper(helper.TestHelper): self.assertEqual(f.read(), tag, u'{0} is not tagged with {1}'.format(path, tag)) - def assertNoFileTag(self, path, tag): + def assertNoFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content does not end with `tag`. """ diff --git a/test/test_datequery.py b/test/test_datequery.py index 6c9818b77..b978d7304 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -62,14 +62,14 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..', date=datetime.min) self.assertContains('..', '1000-01-01T00:00:00') - def assertContains(self, interval_pattern, date_pattern=None, date=None): + def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa if date is None: date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) interval = DateInterval.from_periods(start, end) self.assertTrue(interval.contains(date)) - def assertExcludes(self, interval_pattern, date_pattern): + def assertExcludes(self, interval_pattern, date_pattern): # noqa date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) interval = DateInterval.from_periods(start, end) diff --git a/test/test_edit.py b/test/test_edit.py index ab0ae046a..94bb2d937 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -71,7 +71,7 @@ class ModifyFileMocker(object): class EditMixin(object): """Helper containing some common functionality used for the Edit tests.""" - def assertItemFieldsModified(self, library_items, items, fields=[], + def assertItemFieldsModified(self, library_items, items, fields=[], # noqa allowed=['path']): """Assert that items in the library (`lib_items`) have different values on the specified `fields` (and *only* on those fields), compared to @@ -133,7 +133,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.teardown_beets() self.unload_plugins() - def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, + def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa write_call_count=TRACK_COUNT, title_starts_with=''): """Several common assertions on Album, Track and call counts.""" self.assertEqual(len(self.lib.albums()), album_count) diff --git a/test/test_importadded.py b/test/test_importadded.py index 9fa30f523..6e003ed0f 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -67,7 +67,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.teardown_beets() self.matcher.restore() - def findMediaFile(self, item): + def find_media_file(self, item): """Find the pre-import MediaFile for an Item""" for m in self.media_files: if m.title.replace('Tag', 'Applied') == item.title: @@ -75,11 +75,11 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): raise AssertionError(u"No MediaFile found for Item " + util.displayable_path(item.path)) - def assertEqualTimes(self, first, second, msg=None): + def assertEqualTimes(self, first, second, msg=None): # noqa """For comparing file modification times at a sufficient precision""" self.assertAlmostEqual(first, second, places=4, msg=msg) - def assertAlbumImport(self): + def assertAlbumImport(self): # noqa self.importer.run() album = self.lib.albums().get() self.assertEqual(album.added, self.min_mtime) @@ -102,7 +102,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.assertEqual(album.added, self.min_mtime) for item in album.items(): self.assertEqualTimes(item.added, self.min_mtime) - mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path) + mediafile_mtime = os.path.getmtime(self.find_media_file(item).path) self.assertEqualTimes(item.mtime, mediafile_mtime) self.assertEqualTimes(os.path.getmtime(item.path), mediafile_mtime) @@ -133,7 +133,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.config['import']['singletons'] = True self.importer.run() for item in self.lib.items(): - mfile = self.findMediaFile(item) + mfile = self.find_media_file(item) self.assertEqualTimes(item.added, os.path.getmtime(mfile.path)) def test_import_singletons_with_preserved_mtimes(self): @@ -141,7 +141,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.config['importadded']['preserve_mtimes'] = True self.importer.run() for item in self.lib.items(): - mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path) + mediafile_mtime = os.path.getmtime(self.find_media_file(item).path) self.assertEqualTimes(item.added, mediafile_mtime) self.assertEqualTimes(item.mtime, mediafile_mtime) self.assertEqualTimes(os.path.getmtime(item.path), diff --git a/test/test_importer.py b/test/test_importer.py index d1ef6ef18..ff2020ef8 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -125,14 +125,14 @@ class AutotagStub(object): artist = artist.replace('Tag', 'Applied') + id album = album.replace('Tag', 'Applied') + id - trackInfos = [] + track_infos = [] for i in range(tracks - missing): - trackInfos.append(self._make_track_match(artist, album, i + 1)) + track_infos.append(self._make_track_match(artist, album, i + 1)) return AlbumInfo( artist=artist, album=album, - tracks=trackInfos, + tracks=track_infos, va=False, album_id=u'albumid' + id, artist_id=u'artistid' + id, diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 82396f7c7..b397d2c21 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -167,16 +167,16 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self.assertEqual(res, [u'pop']) def test_get_genre(self): - MOCK_GENRES = {'track': u'1', 'album': u'2', 'artist': u'3'} + mock_genres = {'track': u'1', 'album': u'2', 'artist': u'3'} def mock_fetch_track_genre(self, obj=None): - return MOCK_GENRES['track'] + return mock_genres['track'] def mock_fetch_album_genre(self, obj): - return MOCK_GENRES['album'] + return mock_genres['album'] def mock_fetch_artist_genre(self, obj): - return MOCK_GENRES['artist'] + return mock_genres['artist'] lastgenre.LastGenrePlugin.fetch_track_genre = mock_fetch_track_genre lastgenre.LastGenrePlugin.fetch_album_genre = mock_fetch_album_genre @@ -184,7 +184,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self._setup_config(whitelist=False) item = _common.item() - item.genre = MOCK_GENRES['track'] + item.genre = mock_genres['track'] config['lastgenre'] = {'force': False} res = self.plugin._get_genre(item) @@ -192,17 +192,17 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): config['lastgenre'] = {'force': True, 'source': u'track'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['track'], u'track')) + self.assertEqual(res, (mock_genres['track'], u'track')) config['lastgenre'] = {'source': u'album'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['album'], u'album')) + self.assertEqual(res, (mock_genres['album'], u'album')) config['lastgenre'] = {'source': u'artist'} res = self.plugin._get_genre(item) - self.assertEqual(res, (MOCK_GENRES['artist'], u'artist')) + self.assertEqual(res, (mock_genres['artist'], u'artist')) - MOCK_GENRES['artist'] = None + mock_genres['artist'] = None res = self.plugin._get_genre(item) self.assertEqual(res, (item.genre, u'original')) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 2658232ae..13bffacdb 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -365,14 +365,14 @@ class LyricsGooglePluginTest(unittest.TestCase): not present in the title.""" s = self.source url = s['url'] + s['path'] - urlTitle = u'example.com | Beats song by John doe' + url_title = u'example.com | Beats song by John doe' # very small diffs (typo) are ok eg 'beats' vs 'beets' with same artist - self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'], + self.assertEqual(google.is_page_candidate(url, url_title, s['title'], s['artist']), True, url) # reject different title - urlTitle = u'example.com | seets bong lyrics by John doe' - self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'], + url_title = u'example.com | seets bong lyrics by John doe' + self.assertEqual(google.is_page_candidate(url, url_title, s['title'], s['artist']), False, url) def test_is_page_candidate_special_chars(self): diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 71fd796bd..ad83573da 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -168,7 +168,7 @@ class ImageStructureTestMixin(ArtTestMixin): self.assertEqual(cover.desc, u'album cover') self.assertEqual(mediafile.art, cover.data) - def assertExtendedImageAttributes(self, image, **kwargs): + def assertExtendedImageAttributes(self, image, **kwargs): # noqa """Ignore extended image attributes in the base tests. """ pass @@ -177,7 +177,7 @@ class ImageStructureTestMixin(ArtTestMixin): class ExtendedImageStructureTestMixin(ImageStructureTestMixin): """Checks for additional attributes in the image structure.""" - def assertExtendedImageAttributes(self, image, desc=None, type=None): + def assertExtendedImageAttributes(self, image, desc=None, type=None): # noqa self.assertEqual(image.desc, desc) self.assertEqual(image.type, type) @@ -660,7 +660,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, self.assertIsNone(mediafile.date) self.assertIsNone(mediafile.year) - def assertTags(self, mediafile, tags): + def assertTags(self, mediafile, tags): # noqa errors = [] for key, value in tags.items(): try: diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index 0fa800dfd..4ad9d00c4 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -43,14 +43,14 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.assertFalse(mpdstats.update_rating(None, True)) def test_get_item(self): - ITEM_PATH = '/foo/bar.flac' - item = Item(title=u'title', path=ITEM_PATH, id=1) + item_path = '/foo/bar.flac' + item = Item(title=u'title', path=item_path, id=1) item.add(self.lib) log = Mock() mpdstats = MPDStats(self.lib, log) - self.assertEqual(str(mpdstats.get_item(ITEM_PATH)), str(item)) + self.assertEqual(str(mpdstats.get_item(item_path)), str(item)) self.assertIsNone(mpdstats.get_item('/some/non-existing/path')) self.assertIn(u'item not found:', log.info.call_args[0][0]) @@ -60,13 +60,13 @@ class MPDStatsTest(unittest.TestCase, TestHelper): {'state': u'play', 'songid': 1, 'time': u'0:1'}, {'state': u'stop'}] EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt] - ITEM_PATH = '/foo/bar.flac' + item_path = '/foo/bar.flac' @patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{ "events.side_effect": EVENTS, "status.side_effect": STATUSES, - "playlist.return_value": {1: ITEM_PATH}})) - def test_run_MPDStats(self, mpd_mock): - item = Item(title=u'title', path=self.ITEM_PATH, id=1) + "playlist.return_value": {1: item_path}})) + def test_run_mpdstats(self, mpd_mock): + item = Item(title=u'title', path=self.item_path, id=1) item.add(self.lib) log = Mock() diff --git a/test/test_permissions.py b/test/test_permissions.py index 6dcf4d01c..a1b7ddd19 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -38,7 +38,7 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): def test_failing_to_set_permissions(self): self.do_thing(False) - def do_thing(self, expectSuccess): + def do_thing(self, expect_success): def get_stat(v): return os.stat( os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777 @@ -53,14 +53,14 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.importer.run() item = self.lib.items().get() - self.assertPerms(item.path, 'file', expectSuccess) + self.assertPerms(item.path, 'file', expect_success) for path in dirs_in_library(self.lib.directory, item.path): - self.assertPerms(path, 'dir', expectSuccess) + self.assertPerms(path, 'dir', expect_success) - def assertPerms(self, path, typ, expectSuccess): - for x in [(True, self.exp_perms[expectSuccess][typ], '!='), - (False, self.exp_perms[not expectSuccess][typ], '==')]: + def assertPerms(self, path, typ, expect_success): # noqa + for x in [(True, self.exp_perms[expect_success][typ], '!='), + (False, self.exp_perms[not expect_success][typ], '==')]: self.assertEqual(x[0], check_permissions(path, x[1]), msg=u'{} : {} {} {}'.format( path, oct(os.stat(path).st_mode), x[2], oct(x[1]))) diff --git a/test/test_query.py b/test/test_query.py index 7dd659313..5fb717c9c 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -35,11 +35,11 @@ from beets.library import Library, Item class TestHelper(helper.TestHelper): - def assertInResult(self, item, results): + def assertInResult(self, item, results): # noqa result_ids = map(lambda i: i.id, results) self.assertIn(item.id, result_ids) - def assertNotInResult(self, item, results): + def assertNotInResult(self, item, results): # noqa result_ids = map(lambda i: i.id, results) self.assertNotIn(item.id, result_ids) @@ -805,7 +805,7 @@ class NotQueryTest(DummyDataTestCase): - `test_type_xxx`: tests for the negation of a particular XxxQuery class. - `test_get_yyy`: tests on query strings (similar to `GetTest`) """ - def assertNegationProperties(self, q): + def assertNegationProperties(self, q): # noqa """Given a Query `q`, assert that: - q OR not(q) == all items - q AND not(q) == 0 diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index c30ba24d0..25f6727f0 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -88,15 +88,15 @@ class SmartPlaylistTest(unittest.TestCase): for name, (_, sort), _ in spl._unmatched_playlists) asseq = self.assertEqual # less cluttered code - S = FixedFieldSort # short cut since we're only dealing with this + sort = FixedFieldSort # short cut since we're only dealing with this asseq(sorts["no_sort"], NullSort()) - asseq(sorts["one_sort"], S(u'year')) + asseq(sorts["one_sort"], sort(u'year')) asseq(sorts["only_empty_sorts"], None) - asseq(sorts["one_non_empty_sort"], S(u'year')) + asseq(sorts["one_non_empty_sort"], sort(u'year')) asseq(sorts["multiple_sorts"], - MultipleSort([S('year'), S(u'genre', False)])) + MultipleSort([sort('year'), sort(u'genre', False)])) asseq(sorts["mixed"], - MultipleSort([S('year'), S(u'genre'), S(u'id', False)])) + MultipleSort([sort('year'), sort(u'genre'), sort(u'id', False)])) def test_matches(self): spl = SmartPlaylistPlugin() diff --git a/test/test_ui.py b/test/test_ui.py index fdc16aff9..4de5e9ed5 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -233,18 +233,18 @@ class ModifyTest(unittest.TestCase, TestHelper): def test_selective_modify(self): title = u"Tracktitle" album = u"album" - origArtist = u"composer" - newArtist = u"coverArtist" + original_artist = u"composer" + new_artist = u"coverArtist" for i in range(0, 10): self.add_item_fixture(title=u"{0}{1}".format(title, i), - artist=origArtist, + artist=original_artist, album=album) self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn', - title, u"artist={0}".format(newArtist)) - origItems = self.lib.items(u"artist:{0}".format(origArtist)) - newItems = self.lib.items(u"artist:{0}".format(newArtist)) - self.assertEqual(len(list(origItems)), 3) - self.assertEqual(len(list(newItems)), 7) + title, u"artist={0}".format(new_artist)) + original_items = self.lib.items(u"artist:{0}".format(original_artist)) + new_items = self.lib.items(u"artist:{0}".format(new_artist)) + self.assertEqual(len(list(original_items)), 3) + self.assertEqual(len(list(new_items)), 7) # Album Tests From 73924064edf92aa30bd43496d40c458dbcd4cfb5 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 27 Apr 2016 20:22:39 +0100 Subject: [PATCH 0716/2280] Rename ImageMagick version getter --- beets/util/artresizer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index e94f8c380..6970a7da1 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -218,7 +218,7 @@ class ArtResizer(object): @staticmethod def _check_method(): """Return a tuple indicating an available method and its version.""" - version = get_image_magick_version() + version = get_im_version() if version: return IMAGEMAGICK, version @@ -229,7 +229,7 @@ class ArtResizer(object): return WEBPROXY, (0) -def get_image_magick_version(): +def get_im_version(): """Return Image Magick version or None if it is unavailable Try invoking ImageMagick's "convert".""" try: From 8317a20bcd555e15f12a4f97897a31719bb19c57 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 27 Apr 2016 20:30:58 +0100 Subject: [PATCH 0717/2280] Use correct methods from art resizer --- beetsplug/thumbnails.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index da4a4027b..3977c78ef 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -34,7 +34,7 @@ from xdg import BaseDirectory from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs from beets import util -from beets.util.artresizer import ArtResizer, has_IM, has_PIL +from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") From 79d602b2a01c60575c10153f8f4d24db5d053fb3 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 27 Apr 2016 20:33:21 +0100 Subject: [PATCH 0718/2280] Use correct methods for ImageMagick and PIL info --- beetsplug/thumbnails.py | 4 ++-- test/test_thumbnails.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 3977c78ef..0e7fbc6e0 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -92,11 +92,11 @@ class ThumbnailsPlugin(BeetsPlugin): if not os.path.exists(dir): os.makedirs(dir) - if has_IM(): + if get_im_version(): self.write_metadata = write_metadata_im tool = "IM" else: - assert has_PIL() # since we're local + assert get_pil_version() # since we're local self.write_metadata = write_metadata_pil tool = "PIL" self._log.debug(u"using {0} to write metadata", tool) diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 5dd9551b7..30c5bb234 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -66,8 +66,8 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.os') @patch('beetsplug.thumbnails.ArtResizer') - @patch('beetsplug.thumbnails.has_IM') - @patch('beetsplug.thumbnails.has_PIL') + @patch('beetsplug.thumbnails.get_im_version') + @patch('beetsplug.thumbnails.get_pil_version') @patch('beetsplug.thumbnails.GioURI') def test_check_local_ok(self, mock_giouri, mock_pil, mock_im, mock_artresizer, mock_os): From 64e16b5004dce37aa7aefcc30c50d632cc13a089 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 00:59:45 +0100 Subject: [PATCH 0719/2280] Update confit to match pep8 naming standards --- beets/util/confit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 0b29928c8..28847e760 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -136,7 +136,7 @@ class ConfigSource(dict): ) @classmethod - def of(self, value): + def of(cls, value): """Given either a dictionary or a `ConfigSource` object, return a `ConfigSource` object. This lets a function accept either type of object as an argument. From 2a9305fba5b9d114fdc90cbbe507ea11f940d92f Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 02:26:14 +0100 Subject: [PATCH 0720/2280] Reorder shields and add new shields Reorder shields and add weekly PyPI downloads, GitHub issues and GitHub license shields. --- README.rst | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 1d865ec79..a0cd203a9 100644 --- a/README.rst +++ b/README.rst @@ -1,11 +1,21 @@ -.. image:: https://travis-ci.org/beetbox/beets.svg?branch=master - :target: https://travis-ci.org/beetbox/beets +.. image:: https://img.shields.io/github/license/beetbox/beets.svg + :target: https://github.com/beetbox/beets/blob/master/LICENSE + +.. image:: https://img.shields.io/github/issues/beetbox/beets.svg + :target: https://github.com/beetbox/beets/issues + +.. image:: http://img.shields.io/pypi/v/beets.svg + :target: https://pypi.python.org/pypi/beets + +.. image:: https://img.shields.io/pypi/dw/beets.svg + :target: https://pypi.python.org/pypi/beets#downloads .. image:: http://img.shields.io/codecov/c/github/beetbox/beets.svg :target: https://codecov.io/github/beetbox/beets -.. image:: http://img.shields.io/pypi/v/beets.svg - :target: https://pypi.python.org/pypi/beets +.. image:: https://travis-ci.org/beetbox/beets.svg?branch=master + :target: https://travis-ci.org/beetbox/beets + Beets is the media library management system for obsessive-compulsive music geeks. From 77b48bac7e63442f26f288942fd95a1f43c9f211 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 03:28:54 +0100 Subject: [PATCH 0721/2280] Disable pep8 name check and correct argument name --- beets/autotag/hooks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 4a89e6dc8..5c8e0e2c5 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -297,7 +297,7 @@ class Distance(object): self._penalties = {} @LazyClassProperty - def _weights(self): + def _weights(cls): # noqa """A dictionary from keys to floating-point weights. """ weights_view = config['match']['distance_weights'] From 46179850c504d0798f897df8c96fb9523a3f1fbd Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 03:30:27 +0100 Subject: [PATCH 0722/2280] Fix null sort broken by b1c58e9 --- beets/dbcore/query.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index ed20d320d..d344f9fef 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -841,8 +841,8 @@ class SlowFieldSort(FieldSort): class NullSort(Sort): """No sorting. Leave results unsorted.""" - def sort(self): - return self + def sort(self, items): + return items def __nonzero__(self): return self.__bool__() From 730e1ef175bd0d64faf28b2ba0fcdb4bd645c286 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 03:34:25 +0100 Subject: [PATCH 0723/2280] Revert change made to ordered enum test --- test/test_autotag.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/test_autotag.py b/test/test_autotag.py index bdc3ee2d4..71fbdad73 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -940,13 +940,13 @@ class EnumTest(_common.TestCase): Test Enum Subclasses defined in beets.util.enumeration """ def test_ordered_enum(self): - ordered_enum = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) - self.assertLess(ordered_enum.a, ordered_enum.b) - self.assertLess(ordered_enum.a, ordered_enum.c) - self.assertLess(ordered_enum.b, ordered_enum.c) - self.assertGreater(ordered_enum.b, ordered_enum.a) - self.assertGreater(ordered_enum.c, ordered_enum.a) - self.assertGreater(ordered_enum.c, ordered_enum.b) + OrderedEnumClass = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) # noqa + self.assertLess(OrderedEnumClass.a, OrderedEnumClass.b) + self.assertLess(OrderedEnumClass.a, OrderedEnumClass.c) + self.assertLess(OrderedEnumClass.b, OrderedEnumClass.c) + self.assertGreater(OrderedEnumClass.b, OrderedEnumClass.a) + self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.a) + self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.b) def suite(): From 3166fc44fe2ba66b6dbec0ecfe7b4232f876ee4b Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 03:41:23 +0100 Subject: [PATCH 0724/2280] Remove license and issue shields --- README.rst | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.rst b/README.rst index a0cd203a9..ad477beee 100644 --- a/README.rst +++ b/README.rst @@ -1,9 +1,3 @@ -.. image:: https://img.shields.io/github/license/beetbox/beets.svg - :target: https://github.com/beetbox/beets/blob/master/LICENSE - -.. image:: https://img.shields.io/github/issues/beetbox/beets.svg - :target: https://github.com/beetbox/beets/issues - .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets From 8c471581e07e662be070aaf725811301c4a4021d Mon Sep 17 00:00:00 2001 From: Guilherme Danno Date: Thu, 28 Apr 2016 00:17:19 -0300 Subject: [PATCH 0725/2280] Use the 'terminal_encoding' option for overriding the `sys.stdin.encoding` in some cases (#1964) * Use the 'terminal_encoding' option for overriding the `sys.stdin.encoding` in some cases * Add the documentation --- beets/ui/__init__.py | 18 ++++++++++-------- docs/changelog.rst | 2 ++ docs/reference/config.rst | 3 ++- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 9096a87da..aeb3b8f52 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -71,14 +71,16 @@ class UserError(Exception): # Encoding utilities. -def _in_encoding(): - """Get the encoding to use for *inputting* strings to the console. + + +def _in_encoding(default=u'utf-8'): + """Get the encoding to use for *inputting* strings from the console. + + :param default: the fallback sys.stdin encoding """ - try: - return sys.stdin.encoding or 'utf-8' - except LookupError: - # TODO: create user config - return 'utf-8' + + return config['terminal_encoding'].get() or getattr(sys.stdin, 'encoding', + default) def _out_encoding(): @@ -90,7 +92,7 @@ def _out_encoding(): return encoding # For testing: When sys.stdout is a StringIO under the test harness, - # it doesn't have an `encodiing` attribute. Just use UTF-8. + # it doesn't have an `encoding` attribute. Just use UTF-8. if not hasattr(sys.stdout, 'encoding'): return 'utf8' diff --git a/docs/changelog.rst b/docs/changelog.rst index 1844c4d87..073c2caa8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,8 @@ New features: * :doc:`/plugins/export`: A new plugin to export the data from queries to a json format. Thanks to :user:`GuilhermeHideki`. * :doc:`/reference/pathformat`: new functions: %first{} and %ifdef{} +* :doc:`/reference/config`: option ``terminal_encoding`` now works for some + inputs .. _fanart.tv: https://fanart.tv/ diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 2a93d2204..b074edf5c 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -268,7 +268,8 @@ terminal_encoding ~~~~~~~~~~~~~~~~~ The text encoding, as `known to Python`_, to use for messages printed to the -standard output. By default, this is determined automatically from the locale +standard output. It's also used to read messages from the standard input. +By default, this is determined automatically from the locale environment variables. .. _known to python: http://docs.python.org/2/library/codecs.html#standard-encodings From c4b11f889f2461e463ad11d4c4564e1615289b75 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 28 Apr 2016 17:15:25 +0200 Subject: [PATCH 0726/2280] lyrics: clean up import handling and source removal --- beetsplug/lyrics.py | 59 +++++++++++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index afd536394..072fd71ea 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -28,6 +28,18 @@ import urllib import warnings from HTMLParser import HTMLParseError +try: + from bs4 import SoupStrainer, BeautifulSoup + HAS_BEAUTIFUL_SOUP = True +except ImportError: + HAS_BEAUTIFUL_SOUP = False + +try: + import langdetect + HAS_LANGDETECT = True +except ImportError: + HAS_LANGDETECT = False + from beets import plugins from beets import ui @@ -415,11 +427,7 @@ def scrape_lyrics_from_html(html): """Scrape lyrics from a URL. If no lyrics can be found, return None instead. """ - try: - from bs4 import SoupStrainer, BeautifulSoup - except ImportError: - # TODO: refactor the plugin to get access to a logger here and log - # a warning + if not HAS_BEAUTIFUL_SOUP: return None if not html: @@ -593,18 +601,33 @@ class LyricsPlugin(plugins.BeetsPlugin): self.config['genius_api_key'].redact = True available_sources = list(self.SOURCES) - if not self.config['google_API_key'].get() and \ - 'google' in self.SOURCES: - available_sources.remove('google') - self.config['sources'] = plugins.sanitize_choices( + sources = plugins.sanitize_choices( self.config['sources'].as_str_seq(), available_sources) - self.backends = [self.SOURCE_BACKENDS[key](self.config, self._log) - for key in self.config['sources'].as_str_seq()] + if 'google' in sources: + if not self.config['google_API_key'].get(): + self._log.warn(u'To use the google lyrics source, you must ' + u'provide an API key in the configuration. ' + u'See the documentation for further details.') + available_sources.remove('google') + if not HAS_BEAUTIFUL_SOUP: + self._log.warn(u'To use the google lyrics source, you must ' + u'install the beautifulsoup4 module. See the ' + u'documentation for further details.') + available_sources.remove('google') + self.config['bing_lang_from'] = [ x.lower() for x in self.config['bing_lang_from'].as_str_seq()] self.bing_auth_token = None + if not HAS_LANGDETECT and self.config['bing_client_secret'].get(): + self._log.warn(u'To use bing translations, you need to ' + u'install the langdetect module. See the ' + u'documentation for further details.') + + self.backends = [self.SOURCE_BACKENDS[source](self.config, self._log) + for source in sources if source in available_sources] + def get_bing_access_token(self): params = { 'client_id': 'beets', @@ -675,20 +698,10 @@ class LyricsPlugin(plugins.BeetsPlugin): lyrics = u"\n\n---\n\n".join([l for l in lyrics if l]) - has_langdetect = False - if self.config['bing_client_secret'].get(): - try: - from langdetect import detect - has_langdetect = True - except ImportError: - self._log.warn(u'To use bing translations, you need to ' - u'install the langdetect module. See the ' - u'documentation for further details.') - if lyrics: self._log.info(u'fetched lyrics: {0}', item) - if has_langdetect: - lang_from = detect(lyrics) + if self.config['bing_client_secret'].get(): + lang_from = langdetect.detect(lyrics) if self.config['bing_lang_to'].get() != lang_from and ( not self.config['bing_lang_from'] or ( lang_from in self.config[ From 2928a16bd511e311decdabd900acc0b6f0e20007 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 28 Apr 2016 17:22:55 +0200 Subject: [PATCH 0727/2280] lyrics: actually disable translation when there's no langdetect --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 072fd71ea..115707f80 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -700,7 +700,7 @@ class LyricsPlugin(plugins.BeetsPlugin): if lyrics: self._log.info(u'fetched lyrics: {0}', item) - if self.config['bing_client_secret'].get(): + if HAS_LANGDETECT and self.config['bing_client_secret'].get(): lang_from = langdetect.detect(lyrics) if self.config['bing_lang_to'].get() != lang_from and ( not self.config['bing_lang_from'] or ( From c3c7da80619cb26607b132950ea9438fbc9d4c8c Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 28 Apr 2016 18:31:22 +0200 Subject: [PATCH 0728/2280] lyrics: simplify source handling a little --- beetsplug/lyrics.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 115707f80..b55fac9a7 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -609,12 +609,12 @@ class LyricsPlugin(plugins.BeetsPlugin): self._log.warn(u'To use the google lyrics source, you must ' u'provide an API key in the configuration. ' u'See the documentation for further details.') - available_sources.remove('google') + sources.remove('google') if not HAS_BEAUTIFUL_SOUP: self._log.warn(u'To use the google lyrics source, you must ' u'install the beautifulsoup4 module. See the ' u'documentation for further details.') - available_sources.remove('google') + sources.remove('google') self.config['bing_lang_from'] = [ x.lower() for x in self.config['bing_lang_from'].as_str_seq()] @@ -626,7 +626,7 @@ class LyricsPlugin(plugins.BeetsPlugin): u'documentation for further details.') self.backends = [self.SOURCE_BACKENDS[source](self.config, self._log) - for source in sources if source in available_sources] + for source in sources] def get_bing_access_token(self): params = { From ae9ece1e6216dfe3a7844360968822f6994c383a Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 29 Apr 2016 14:51:13 +0100 Subject: [PATCH 0729/2280] Make format extension optional The format extension defaults to the name of the format if it is not provided. --- beetsplug/convert.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index dd57918d6..80a0127c9 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -60,10 +60,10 @@ def get_format(fmt=None): try: format_info = config['convert']['formats'][fmt].get(dict) command = format_info['command'] - extension = format_info['extension'] + extension = format_info.get('extension', fmt) except KeyError: raise ui.UserError( - u'convert: format {0} needs "command" and "extension" fields' + u'convert: format {0} needs the "command" field' .format(fmt) ) except ConfigTypeError: From be897e964a18c3277b8080812371ca0a6fe79d08 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 29 Apr 2016 14:54:00 +0100 Subject: [PATCH 0730/2280] Specify the optionality of the file extension in documentation Also change "command-line" to "command" for accuracy. --- docs/plugins/convert.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index f5b258065..f2f28c63d 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -113,12 +113,12 @@ default. To convert the audio to `wav`, run ``beet convert -f wav``. This will also use the format key (`wav`) as the file extension. Each entry in the ``formats`` map consists of a key (the name of the -format) as well as the command and the possibly the file extension. +format) as well as the command and optionally the file extension. ``extension`` is the filename extension to be used for newly transcoded -files. If only the command is given as a string, the file extension -defaults to the format's name. ``command`` is the command-line to use -to transcode audio. The tokens ``$source`` and ``$dest`` in the command -are replaced with the paths to the existing and new file. +files. If only the command is given as a string or the extension is not +provided, the file extension defaults to the format's name. ``command`` is the +command to use to transcode audio. The tokens ``$source`` and ``$dest`` in the +command are replaced with the paths to the existing and new file. The plugin in comes with default commands for the most common audio formats: `mp3`, `alac`, `flac`, `aac`, `opus`, `ogg`, `wmv`. For From ab05fb83b7b64427786ed9512f76158b18185ec5 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 29 Apr 2016 18:24:45 +0100 Subject: [PATCH 0731/2280] Add convert extension changes to changelog --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 073c2caa8..529f41d52 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,7 @@ New features: * :doc:`/plugins/convert`: A new `album_art_maxwidth` lets you resize album art while copying it. +* :doc:`/plugins/convert`: Make `extension` optional for conversion formats. * :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option lets you preserve mtime of files after each write. * :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to a From 078a0702d3f9e68ad96d866890fcadf65efe26d4 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 29 Apr 2016 18:37:55 +0100 Subject: [PATCH 0732/2280] Move single line properties to the same line as the key --- tox.ini | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/tox.ini b/tox.ini index 6eba8395d..6c6818908 100644 --- a/tox.ini +++ b/tox.ini @@ -21,28 +21,23 @@ deps = pyxdg jellyfish python-mpd2 -commands = - nosetests {posargs} +commands = nosetests {posargs} [testenv:py27cov] basepython = python2.7 deps = {[testenv]deps} coverage -commands = - nosetests --show-skipped --with-coverage {posargs} +commands = nosetests --show-skipped --with-coverage {posargs} [testenv:py27setup] basepython = python2.7 -commands = - python ./setup.py test {posargs} +commands = python ./setup.py test {posargs} [testenv:docs] changedir = docs -deps = - sphinx -commands = - sphinx-build -W -q -b html . {envtmpdir}/html +deps = sphinx +commands = sphinx-build -W -q -b html . {envtmpdir}/html [testenv:flake8] deps = From 1dd6739218e8725dfed405166abe964611768b2b Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 29 Apr 2016 23:50:03 +0200 Subject: [PATCH 0733/2280] lyrics: fix a bug where the lyricswiki fetcher would try to unescape an empty (None) response and crash --- beetsplug/lyrics.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b55fac9a7..b6936e1be 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -347,10 +347,11 @@ class LyricsWiki(SymbolsReplaced): # Get the HTML fragment inside the appropriate HTML element and then # extract the text from it. html_frag = extract_text_in(html, u"
") - lyrics = _scrape_strip_cruft(html_frag, True) + if html_frag: + lyrics = _scrape_strip_cruft(html_frag, True) - if lyrics and 'Unfortunately, we are not licensed' not in lyrics: - return lyrics + if lyrics and 'Unfortunately, we are not licensed' not in lyrics: + return lyrics class LyricsCom(Backend): From 6b8019f60f98d1d557f34bb2b159855290b7f26e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 30 Apr 2016 15:12:07 -0700 Subject: [PATCH 0734/2280] Refine docs for the hook plugin --- docs/changelog.rst | 1 - docs/plugins/hook.rst | 38 +++++++++++++++++--------------------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index da20351dc..99ebc39f5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,7 +15,6 @@ New features: for a Microsoft Azure Marketplace free account. Thanks to :user:`Kraymer`. * :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. Albums are matched using the ``mb_releasegroupid`` tag. - * :doc:`/plugins/fetchart`: The ``enforce_ratio`` option was enhanced and now allows specifying a certain deviation that a valid image may have from being exactly square. diff --git a/docs/plugins/hook.rst b/docs/plugins/hook.rst index 2de736c7c..2c1dfec25 100644 --- a/docs/plugins/hook.rst +++ b/docs/plugins/hook.rst @@ -1,14 +1,10 @@ Hook Plugin -=============== +=========== -Internally, beets sends events to plugins when an action finishes. These can -range from importing a song (``import``) to beets exiting (``cli_exit``), and -provide a very flexible way to perform actions based on the events. This plugin -allows you to run commands when an event is emitted by beets, such as syncing -your library with another drive when the library is updated. - -Hooks are currently run in the order defined in the configuration, however this -is dependent on beets itself and it's consistency should not be depended upon. +Internally, beets uses *events* to tell plugins when something happens. For +example, one event fires when the importer finishes processes a song, and +another triggers just before the ``beet`` command exits. +The ``hook`` plugin lets you run commands in response to these events. .. _hook-configuration: @@ -23,27 +19,27 @@ file. The available options are: .. _individual-hook-configuration: -Individual Hook Configuration ------------------------------ +Configuring Each Hook +''''''''''''''''''''' -Each element of the ``hooks`` configuration option can be configured separately. -The available options are: +Each element under ``hooks`` should have these keys: -- **event**: The name of the event that should cause this hook to - execute. See the :ref:`plugin events ` documentation for a list +- **event**: The name of the event that will trigger this hook. + See the :ref:`plugin events ` documentation for a list of possible values. - **command**: The command to run when this hook executes. .. _command-substitution: Command Substitution --------------------- +'''''''''''''''''''' -Certain key words can be replaced in commands, allowing access to event -information such as the path of an album or the name of a song. This information -is accessed using the syntax ``{property_name}``, where ``property_name`` is the -name of an argument passed to the event. ``property_name`` can also be a key on -an argument passed to the event, such as ``{album.path}``. +Commands can access the parameters of events using `Python string +formatting`_. Use ``{name}`` in your command and the plugin will substitute it +with the named value. The name can also refer to a field, as in +``{album.path}``. + +.. _Python string formatting: https://www.python.org/dev/peps/pep-3101/ You can find a list of all available events and their arguments in the :ref:`plugin events ` documentation. From 4f596725ae628648925fb0f6d8a5d5c9dcbf468b Mon Sep 17 00:00:00 2001 From: Patrik Date: Sun, 1 May 2016 01:27:02 +0200 Subject: [PATCH 0735/2280] convert.py: Fix error message --- beetsplug/convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index dd57918d6..f7fd38085 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -208,7 +208,7 @@ class ConvertPlugin(BeetsPlugin): except OSError as exc: raise ui.UserError( u"convert: could invoke '{0}': {1}".format( - ' '.join(args), exc + ' '.join(ui.decargs(args)), exc ) ) From 2f608fce0a4e1f823e908f94d56933ee6e21555f Mon Sep 17 00:00:00 2001 From: Patrik Date: Sun, 1 May 2016 01:53:03 +0200 Subject: [PATCH 0736/2280] convert.py: Fix error message --- beetsplug/convert.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index f7fd38085..3a7e53d46 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -190,7 +190,7 @@ class ConvertPlugin(BeetsPlugin): }) if pretend: - self._log.info(' '.join(ui.decargs(args))) + self._log.info(u' '.join(ui.decargs(args))) return try: @@ -207,8 +207,8 @@ class ConvertPlugin(BeetsPlugin): raise except OSError as exc: raise ui.UserError( - u"convert: could invoke '{0}': {1}".format( - ' '.join(ui.decargs(args)), exc + u"convert: couldn't invoke '{0}': {1}".format( + u' '.join(ui.decargs(args)), exc ) ) From b9464d1ea48b0f7531242d03c5cef1a6003f0470 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 18:26:06 +0100 Subject: [PATCH 0737/2280] Use unicode for command formatting --- beetsplug/hook.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 81fb9a7f9..2b0bf2b0a 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -47,7 +47,9 @@ class HookPlugin(BeetsPlugin): self._log.error('invalid command "{0}"', command) return - formatted_command = command.format(event=event, **kwargs) + unicode_command = command.decode('utf-8') + formatted_command = unicode_command.format(event=event, + **kwargs) encoded_command = formatted_command.decode(_arg_encoding()) command_pieces = shlex.split(encoded_command) From 04bbdede3857dfcae5a2c8bd8b60f5ceb204f985 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 1 May 2016 13:04:35 -0700 Subject: [PATCH 0738/2280] hook: Typed configuration accessors --- beetsplug/hook.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 2b0bf2b0a..8f87e34da 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -36,8 +36,8 @@ class HookPlugin(BeetsPlugin): for hook_index in range(len(hooks)): hook = self.config['hooks'][hook_index] - hook_event = hook['event'].get() - hook_command = hook['command'].get() + hook_event = hook['event'].get(unicode) + hook_command = hook['command'].get(unicode) self.create_and_register_hook(hook_event, hook_command) From 576ec92992036512853deb1b4e03fb92d9dff5f7 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:21:40 +0100 Subject: [PATCH 0739/2280] Fix encoding for hook plugin - Add a AutoFieldCountFormatter formatter for auto field incrementation. - Add a CodingFormatter for formatting encoded strings. - Fix encoding for hook plugin using CodingFormatter. --- beetsplug/hook.py | 105 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 96 insertions(+), 9 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 2b0bf2b0a..3a3c8ea84 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -15,6 +15,7 @@ """Allows custom commands to be run when an event is emitted by beets""" from __future__ import division, absolute_import, print_function +import string import shlex import subprocess @@ -22,6 +23,88 @@ from beets.plugins import BeetsPlugin from beets.ui import _arg_encoding +# Sadly we need this class for {} support due to issue 13598 +# https://bugs.python.org/issue13598 +# https://bugs.python.org/file25816/issue13598.diff +class AutoFieldCountFormatter(string.Formatter): + def _vformat(self, format_string, args, kwargs, used_args, + recursion_depth): + if recursion_depth < 0: + raise ValueError('Max string recursion exceeded') + auto_field_count = 0 + # manual numbering + manual = None + result = [] + for literal_text, field_name, format_spec, conversion in \ + self.parse(format_string): + + # output the literal text + if literal_text: + result.append(literal_text) + + # if there's a field, output it + if field_name is not None: + # this is some markup, find the object and do + # the formatting + + # ensure we are consistent with numbering + if (field_name == "" and manual) or manual is False: + raise ValueError("cannot switch from manual field " + + "specification to automatic field " + + "numbering") + + # automatic numbering + if field_name == "": + manual = False + field_name = str(auto_field_count) + auto_field_count += 1 + + # manual numbering + else: + manual = True + + # given the field_name, find the object it references + # and the argument it came from + obj, arg_used = self.get_field(field_name, args, kwargs) + used_args.add(arg_used) + + # do any conversion on the resulting object + obj = self.convert_field(obj, conversion) + + # expand the format spec, if needed + format_spec = self._vformat(format_spec, args, kwargs, + used_args, recursion_depth - 1) + + # format the object and append to the result + result.append(self.format_field(obj, format_spec)) + + return ''.join(result) + + +class CodingFormatter(AutoFieldCountFormatter): + def __init__(self, coding): + self._coding = coding + + def format(self, format_string, *args, **kwargs): + try: + format_string = format_string.decode(self._coding) + except UnicodeEncodeError: + pass + + return super(CodingFormatter, self).format(format_string, *args, + **kwargs) + + def convert_field(self, value, conversion): + converted = super(CodingFormatter, self).convert_field(value, + conversion) + try: + converted = converted.decode(self._coding) + except UnicodeEncodeError: + pass + + return converted + + class HookPlugin(BeetsPlugin): """Allows custom commands to be run when an event is emitted by beets""" def __init__(self): @@ -47,18 +130,22 @@ class HookPlugin(BeetsPlugin): self._log.error('invalid command "{0}"', command) return - unicode_command = command.decode('utf-8') - formatted_command = unicode_command.format(event=event, - **kwargs) - encoded_command = formatted_command.decode(_arg_encoding()) - command_pieces = shlex.split(encoded_command) + encoding = _arg_encoding() + formatter = CodingFormatter(encoding) + formatted_command = formatter.format(command, event=event, + **kwargs) + encoded_formatted_command = formatted_command.encode(encoding) + command_pieces = shlex.split(encoded_formatted_command) + decoded_command_pieces = map(lambda piece: + piece.decode(encoding), + command_pieces) - self._log.debug('Running command "{0}" for event {1}', - encoded_command, event) + self._log.debug(u'running command "{0}" for event {1}', + formatted_command, event) try: - subprocess.Popen(command_pieces).wait() + subprocess.Popen(decoded_command_pieces).wait() except OSError as exc: - self._log.error('hook for {0} failed: {1}', event, exc) + self._log.error(u'hook for {0} failed: {1}', event, exc) self.register_listener(event, hook_function) From b4715d61e19d1ab50b918d53610b10026ed95a92 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:30:20 +0100 Subject: [PATCH 0740/2280] Fix over-indentation of wrapped code --- beetsplug/hook.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 3a3c8ea84..d3a1fbdb8 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -96,7 +96,7 @@ class CodingFormatter(AutoFieldCountFormatter): def convert_field(self, value, conversion): converted = super(CodingFormatter, self).convert_field(value, - conversion) + conversion) try: converted = converted.decode(self._coding) except UnicodeEncodeError: From e66981c4d837f8a8f93ce9fde17c17b57cb954d0 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:31:53 +0100 Subject: [PATCH 0741/2280] Use beets shlex_split instead of shlex.split --- beetsplug/hook.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index d3a1fbdb8..b2eec360c 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -16,11 +16,11 @@ from __future__ import division, absolute_import, print_function import string -import shlex import subprocess from beets.plugins import BeetsPlugin from beets.ui import _arg_encoding +from beets.util import shlex_split # Sadly we need this class for {} support due to issue 13598 @@ -134,17 +134,13 @@ class HookPlugin(BeetsPlugin): formatter = CodingFormatter(encoding) formatted_command = formatter.format(command, event=event, **kwargs) - encoded_formatted_command = formatted_command.encode(encoding) - command_pieces = shlex.split(encoded_formatted_command) - decoded_command_pieces = map(lambda piece: - piece.decode(encoding), - command_pieces) + command_pieces = shlex_split(formatted_command) self._log.debug(u'running command "{0}" for event {1}', formatted_command, event) try: - subprocess.Popen(decoded_command_pieces).wait() + subprocess.Popen(command_pieces).wait() except OSError as exc: self._log.error(u'hook for {0} failed: {1}', event, exc) From ba7004de6e731275a57749ef7aa3a2a8bfe75502 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:33:06 +0100 Subject: [PATCH 0742/2280] Remove unneeded AutoFieldCountFormatter --- beetsplug/hook.py | 60 +---------------------------------------------- 1 file changed, 1 insertion(+), 59 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index b2eec360c..a0faf4fe2 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -23,65 +23,7 @@ from beets.ui import _arg_encoding from beets.util import shlex_split -# Sadly we need this class for {} support due to issue 13598 -# https://bugs.python.org/issue13598 -# https://bugs.python.org/file25816/issue13598.diff -class AutoFieldCountFormatter(string.Formatter): - def _vformat(self, format_string, args, kwargs, used_args, - recursion_depth): - if recursion_depth < 0: - raise ValueError('Max string recursion exceeded') - auto_field_count = 0 - # manual numbering - manual = None - result = [] - for literal_text, field_name, format_spec, conversion in \ - self.parse(format_string): - - # output the literal text - if literal_text: - result.append(literal_text) - - # if there's a field, output it - if field_name is not None: - # this is some markup, find the object and do - # the formatting - - # ensure we are consistent with numbering - if (field_name == "" and manual) or manual is False: - raise ValueError("cannot switch from manual field " + - "specification to automatic field " + - "numbering") - - # automatic numbering - if field_name == "": - manual = False - field_name = str(auto_field_count) - auto_field_count += 1 - - # manual numbering - else: - manual = True - - # given the field_name, find the object it references - # and the argument it came from - obj, arg_used = self.get_field(field_name, args, kwargs) - used_args.add(arg_used) - - # do any conversion on the resulting object - obj = self.convert_field(obj, conversion) - - # expand the format spec, if needed - format_spec = self._vformat(format_spec, args, kwargs, - used_args, recursion_depth - 1) - - # format the object and append to the result - result.append(self.format_field(obj, format_spec)) - - return ''.join(result) - - -class CodingFormatter(AutoFieldCountFormatter): +class CodingFormatter(string.Formatter): def __init__(self, coding): self._coding = coding From 63caf1fceb94d185e73858c2b58c82bf5912b7c4 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:44:05 +0100 Subject: [PATCH 0743/2280] Add documentation for coding formatter --- beetsplug/hook.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index a0faf4fe2..99d7dc37d 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -24,10 +24,22 @@ from beets.util import shlex_split class CodingFormatter(string.Formatter): + """A custom string formatter that decodes the format string and it's + fields. + """ + def __init__(self, coding): + """Creates a new coding formatter with the provided coding.""" self._coding = coding def format(self, format_string, *args, **kwargs): + """Formats the provided string using the provided arguments and keyword + arguments. + + This method decodes the format string using the formatter's coding. + + See str.format and string.Formatter.format. + """ try: format_string = format_string.decode(self._coding) except UnicodeEncodeError: @@ -37,6 +49,12 @@ class CodingFormatter(string.Formatter): **kwargs) def convert_field(self, value, conversion): + """Converts the provided value given a conversion type. + + This method decodes the converted value using the formatter's coding. + + See string.Formatter.convert_field. + """ converted = super(CodingFormatter, self).convert_field(value, conversion) try: From 9f0db136752bd3feec37a5c28961e265ef3d5679 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 21:44:40 +0100 Subject: [PATCH 0744/2280] Remove unnecessary variable --- beetsplug/hook.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 99d7dc37d..2085e64c5 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -90,8 +90,7 @@ class HookPlugin(BeetsPlugin): self._log.error('invalid command "{0}"', command) return - encoding = _arg_encoding() - formatter = CodingFormatter(encoding) + formatter = CodingFormatter(_arg_encoding()) formatted_command = formatter.format(command, event=event, **kwargs) command_pieces = shlex_split(formatted_command) From 92af723682501b1f3550f52502c9079990370298 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sun, 1 May 2016 23:04:22 +0100 Subject: [PATCH 0745/2280] Format individual command pieces instead of whole command --- beetsplug/hook.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 2085e64c5..14ccbf099 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -91,12 +91,14 @@ class HookPlugin(BeetsPlugin): return formatter = CodingFormatter(_arg_encoding()) - formatted_command = formatter.format(command, event=event, - **kwargs) - command_pieces = shlex_split(formatted_command) + command_pieces = shlex_split(command) + + for i, piece in enumerate(command_pieces): + command_pieces[i] = formatter.format(piece, event=event, + **kwargs) self._log.debug(u'running command "{0}" for event {1}', - formatted_command, event) + u' '.join(command_pieces), event) try: subprocess.Popen(command_pieces).wait() From 2d36626d25215c3343621c5724180fb6935be222 Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Mon, 2 May 2016 01:53:20 +0200 Subject: [PATCH 0746/2280] convert plugin: Change the default ogg quality According to the `oggenc(1)` man page (in vorbis-tools), the default quality is 3, not 2. So we should use that. --- beetsplug/convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 3a7e53d46..f11204924 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -120,7 +120,7 @@ class ConvertPlugin(BeetsPlugin): u'opus': u'ffmpeg -i $source -y -vn -acodec libopus -ab 96k $dest', u'ogg': - u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 2 $dest', + u'ffmpeg -i $source -y -vn -acodec libvorbis -aq 3 $dest', u'wma': u'ffmpeg -i $source -y -vn -acodec wmav2 -vn $dest', }, From 37710edb55eb1b2026f54340aab1c55d1288c3e5 Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Mon, 2 May 2016 19:08:47 +0200 Subject: [PATCH 0747/2280] Document convert plugin ogg quality change --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 99ebc39f5..fc7072cdc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -47,6 +47,8 @@ Fixes: command can't be invoked. :bug:`1927` * :doc:`/plugins/fetchart`: Fix a crash in the Wikipedia backend on non-ASCII artist and album names. :bug:`1960` +* :doc:`/plugins/convert`: Change default `ogg` encoding quality from 2 to 3 + (to fit the default from the `oggenc(1)` manpage). :bug:`1982` 1.3.17 (February 7, 2016) From 195b3fb5207fe073b6a2a8c52817d63b8c56d12b Mon Sep 17 00:00:00 2001 From: pkel Date: Tue, 3 May 2016 20:33:17 +0200 Subject: [PATCH 0748/2280] Update location of noimport plugin --- docs/plugins/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 005b693e4..0664f303f 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -244,6 +244,6 @@ Here are a few of the plugins written by the beets community: .. _beets-alternatives: https://github.com/geigerzaehler/beets-alternatives .. _beets-follow: https://github.com/nolsto/beets-follow .. _beets-setlister: https://github.com/tomjaspers/beets-setlister -.. _beets-noimport: https://github.com/ttsda/beets-noimport +.. _beets-noimport: https://gitlab.com/tiago.dias/beets-noimport .. _whatlastgenre: https://github.com/YetAnotherNerd/whatlastgenre/tree/master/plugin/beets .. _beets-usertag: https://github.com/igordertigor/beets-usertag From 2038a40fa2a8013d34166f3670ccc0b57732990a Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 5 May 2016 11:27:28 +0100 Subject: [PATCH 0749/2280] Add write option to bpm plugin Add write option to bpm plugin and tidy up command function. --- beetsplug/bpm.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index ba284c042..4e7b202ac 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -54,6 +54,7 @@ class BPMPlugin(BeetsPlugin): self.config.add({ u'max_strokes': 3, u'overwrite': True, + u'write': False }) def commands(self): @@ -64,7 +65,9 @@ class BPMPlugin(BeetsPlugin): return [cmd] def command(self, lib, opts, args): - self.get_bpm(lib.items(ui.decargs(args))) + items = lib.items(ui.decargs(args)) + write = self.config['write'].get(bool) + self.get_bpm(items, write) def get_bpm(self, items, write=False): overwrite = self.config['overwrite'].get(bool) From df7b1b95519f2388966dc7c52e79743a963b4a64 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 5 May 2016 11:40:42 +0100 Subject: [PATCH 0750/2280] Add changelog entry --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 99ebc39f5..08d586263 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,8 @@ New features: source in a flexible field; for a usecase see the documentation. * :doc:`/plugins/export`: A new plugin to export the data from queries to a json format. Thanks to :user:`GuilhermeHideki`. +* :doc:`/plugins/bpm`: Add ``write`` option to write tracks after updating + their BPM. * :doc:`/reference/pathformat`: new functions: %first{} and %ifdef{} * :doc:`/reference/config`: option ``terminal_encoding`` now works for some inputs From 6935b6deff1a1f141f9767d62daa765c8d6e7fb5 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 5 May 2016 11:41:18 +0100 Subject: [PATCH 0751/2280] Add configuration documentation for bpm plugin --- docs/plugins/bpm.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/plugins/bpm.rst b/docs/plugins/bpm.rst index ce1f62298..f622ebc8d 100644 --- a/docs/plugins/bpm.rst +++ b/docs/plugins/bpm.rst @@ -22,6 +22,20 @@ for instance, with ``mpc`` you can do something like:: beet bpm $(mpc |head -1|tr -d "-") +Configuration +------------- + +To configure the plugin, make a ``bpm:`` section in your configuration file. +The available options are: + +- **max_strokes**: The maximum number of strokes to accept when tapping out the + BPM. + Default: 3. +- **overwrite**: Overwrite the track's existing BPM. + Default: ``yes``. +- **write**: Write the song's tags to file when the BPM is updated. + Default: ``no``. + Credit ------ From 4869db95090e90f129ded1289142a824f0b05d80 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 4 May 2016 22:29:02 -0400 Subject: [PATCH 0752/2280] Cache tox and pip directories for travis --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index f78612b7e..eeb59caa9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,6 +33,11 @@ before_install: after_success: - "[ ! -z $COVERAGE ] && codecov || true" +cache: + directories: + - .tox + - $HOME/.pip-cache/ + notifications: irc: channels: From dee2c0d07fb25797f919229d379b95f23f6119bb Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 5 May 2016 16:07:24 -0400 Subject: [PATCH 0753/2280] use pip specific caching directive in .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index eeb59caa9..cc1f96e94 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,9 +34,9 @@ after_success: - "[ ! -z $COVERAGE ] && codecov || true" cache: + pip: true directories: - .tox - - $HOME/.pip-cache/ notifications: irc: From 412bde5de2018c0770a7859cc3820ccab3404814 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:15:09 +0100 Subject: [PATCH 0754/2280] Add library to check if a file is hidden - Add `beets.util.hidden` which adds a `is_hidden` function to check whether or not a file is hidden on the current platform. - Add tests for `beets.util.hidden`. --- beets/util/hidden.py | 143 +++++++++++++++++++++++++++++++++++++++++++ test/test_hidden.py | 74 ++++++++++++++++++++++ 2 files changed, 217 insertions(+) create mode 100644 beets/util/hidden.py create mode 100644 test/test_hidden.py diff --git a/beets/util/hidden.py b/beets/util/hidden.py new file mode 100644 index 000000000..3d7022ae7 --- /dev/null +++ b/beets/util/hidden.py @@ -0,0 +1,143 @@ +"""Simple library to work out if a file is hidden on different platforms.""" + +import ctypes +import ctypes.util +import os.path +import sys + + +# Adjustments for CoreFoundation functions on OS X. +_CF_FUNCTION_MAPPINGS = { + 'CFRelease': { + 'argtypes': [ctypes.c_void_p], + 'restype': None + }, + 'CFURLCreateFromFileSystemRepresentation': { + 'argtypes': [ + ctypes.c_void_p, + ctypes.c_char_p, + ctypes.c_long, + ctypes.c_int + ], + 'restype': ctypes.c_void_p + }, + 'CFURLCopyResourcePropertyForKey': { + 'argtypes': [ + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p + ], + 'restype': ctypes.c_void_p + }, + 'CFBooleanGetValue': { + 'argtypes': [ctypes.c_void_p], + 'restype': ctypes.c_int + } +} + + +def _dict_attr_copy(source, destination): + """Copy dict values from source on to destination as attributes.""" + for k, v in source.iteritems(): + if isinstance(v, dict): + _dict_attr_copy(v, getattr(destination, k)) + else: + setattr(destination, k, v) + + +def _is_hidden_osx(path): + """Return whether or not a file is hidden on OS X. + + This uses CoreFoundation alongside CFURL to work out if a file has the + "hidden" flag. + """ + # Load CoreFoundation. + cf_path = ctypes.util.find_library('CoreFoundation') + cf = ctypes.cdll.LoadLibrary(cf_path) + + # Copy the adjustments on to the library. + _dict_attr_copy(_CF_FUNCTION_MAPPINGS, cf) + + # Create a URL from the path. + url = cf.CFURLCreateFromFileSystemRepresentation(None, path, len(path), + False) + + # Retrieve the hidden key. + is_hidden_key = ctypes.c_void_p.in_dll(cf, 'kCFURLIsHiddenKey') + + # Create a void pointer and get the address of it. + val = ctypes.c_void_p(0) + val_address = ctypes.addressof(val) + + # Get the value (whether or not the file is hidden) for the hidden key and + # store it in val. + success = cf.CFURLCopyResourcePropertyForKey(url, is_hidden_key, + val_address, None) + + # Check if we were able to get the value for the hidden key. + if success: + + # Retrieve the result as a boolean. + result = cf.CFBooleanGetValue(val) + + # Release the value and URL. + cf.CFRelease(val) + cf.CFRelease(url) + + return bool(result) + else: + return False + + +def _is_hidden_win(path): + """Return whether or not a file is hidden on Windows. + + This uses GetFileAttributes to work out if a file has the "hidden" flag + (FILE_ATTRIBUTE_HIDDEN). + """ + # FILE_ATTRIBUTE_HIDDEN = 2 (0x2) from GetFileAttributes documentation. + hidden_mask = 2 + + # Retrieve the attributes for the file. + attrs = ctypes.windll.kernel32.GetFileAttributesW(path) + + # Ensure we have valid attribues and compare them against the mask. + return attrs >= 0 and bool(attrs & hidden_mask) + + +def _is_hidden_dot(path): + """Return whether or not a file starts with a dot. + + Files starting with a dot are seen as "hidden" files on Unix-based OSes. + """ + return os.path.basename(path).startswith('.') + + +def is_hidden(path): + """Return whether or not a file is hidden. + + This method works differently depending on the platform it is called on. + + On OS X, it uses both the result of `is_hidden_osx` and `is_hidden_dot` to + work out if a file is hidden. + + On Windows, it uses the result of `is_hidden_win` to work out if a file is + hidden. + + On any other operating systems (i.e. Linux), it uses `is_hidden_dot` to + work out if a file is hidden. + """ + # Convert the path to unicode if it is not already. + if not isinstance(path, unicode): + path = path.decode('utf-8') + + # Run platform specific functions depending on the platform + if sys.platform == 'darwin': + return _is_hidden_osx(path) or _is_hidden_dot(path) + elif sys.platform == 'win32': + return _is_hidden_win(path) + else: + return _is_hidden_dot(path) + +__all__ = ['is_hidden'] diff --git a/test/test_hidden.py b/test/test_hidden.py new file mode 100644 index 000000000..a02282ef5 --- /dev/null +++ b/test/test_hidden.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Fabrice Laporte. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for the 'hidden' utility.""" + +from __future__ import division, absolute_import, print_function + +from test._common import unittest +import sys +import tempfile +from beets.util import hidden +import subprocess +import errno +import ctypes + + +class HiddenFileTest(unittest.TestCase): + def setUp(self): + pass + + def test_osx_hidden(self): + if not sys.platform == 'darwin': + self.skipTest('sys.platform is not darwin') + return + + with tempfile.NamedTemporaryFile(delete=False) as f: + try: + command = ["chflags", "hidden", f.name] + subprocess.Popen(command).wait() + except OSError as e: + if e.errno == errno.ENOENT: + self.skipTest("unable to find chflags") + else: + raise e + + self.assertTrue(hidden.is_hidden(f.name)) + + def test_windows_hidden(self): + if not sys.platform == 'windows': + self.skipTest('sys.platform is not windows') + return + + # FILE_ATTRIBUTE_HIDDEN = 2 (0x2) from GetFileAttributes documentation. + hidden_mask = 2 + + with tempfile.NamedTemporaryFile() as f: + # Hide the file using + success = ctypes.windll.kernel32.SetFileAttributesW(f.name, + hidden_mask) + + if not success: + self.skipTest("unable to set file attributes") + + self.assertTrue(hidden.is_hidden(f.name)) + + def test_other_hidden(self): + if sys.platform == 'darwin' or sys.platform == 'windows': + self.skipTest('sys.platform is known') + return + + with temfile.NamedTemporaryFile(prefix='.tmp') as f: + self.assertTrue(hidden.is_hidden(f.name)) From 4b4e788865955b97d4439bde785591fb3a85ccc5 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:35:43 +0100 Subject: [PATCH 0755/2280] Add `ignore_hidden` configuration property Add `ignore_hidden` top level configuration property, allowing hidden files to be ignored on import. --- beets/config_default.yaml | 1 + beets/importer.py | 5 ++++- beets/util/__init__.py | 14 ++++++++------ 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 5bc921167..dfe31ade8 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -26,6 +26,7 @@ import: clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information"] +ignore_hidden: yes replace: '[\\/]': _ '^\.': _ diff --git a/beets/importer.py b/beets/importer.py index e73a9e08f..f9cd138f4 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1451,8 +1451,11 @@ def albums_in_dir(path): """ collapse_pat = collapse_paths = collapse_items = None ignore = config['ignore'].as_str_seq() + ignore_hidden = config['ignore_hidden'].get(bool) - for root, dirs, files in sorted_walk(path, ignore=ignore, logger=log): + for root, dirs, files in sorted_walk(path, ignore=ignore, + ignore_hidden=ignore_hidden, + logger=log): items = [os.path.join(root, f) for f in files] # If we're currently collapsing the constituent directories in a # multi-disc album, check whether we should continue collapsing diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 4d46aecd2..327b312fa 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -26,6 +26,7 @@ import traceback import subprocess import platform import shlex +from beets.util import hidden MAX_FILENAME_LENGTH = 200 @@ -151,7 +152,7 @@ def ancestry(path): return out -def sorted_walk(path, ignore=(), logger=None): +def sorted_walk(path, ignore=(), ignore_hidden=False, logger=None): """Like `os.walk`, but yields things in case-insensitive sorted, breadth-first order. Directory and file names matching any glob pattern in `ignore` are skipped. If `logger` is provided, then @@ -185,10 +186,11 @@ def sorted_walk(path, ignore=(), logger=None): # Add to output as either a file or a directory. cur = os.path.join(path, base) - if os.path.isdir(syspath(cur)): - dirs.append(base) - else: - files.append(base) + if (ignore_hidden and not hidden.is_hidden(cur)) or not ignore_hidden: + if os.path.isdir(syspath(cur)): + dirs.append(base) + else: + files.append(base) # Sort lists (case-insensitive) and yield the current level. dirs.sort(key=bytes.lower) @@ -199,7 +201,7 @@ def sorted_walk(path, ignore=(), logger=None): for base in dirs: cur = os.path.join(path, base) # yield from sorted_walk(...) - for res in sorted_walk(cur, ignore, logger): + for res in sorted_walk(cur, ignore, ignore_hidden, logger): yield res From 38a3726b1b459a9e855fba85b9f8c221b0460ac3 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:45:45 +0100 Subject: [PATCH 0756/2280] Add documentation --- docs/reference/config.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index b074edf5c..e84dc4a17 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -91,6 +91,15 @@ importing. By default, this consists of ``.*``, ``*~``, and ``System Volume Information`` (i.e., beets ignores Unix-style hidden files, backup files, and a directory that appears at the root of some Windows filesystems). +ignore_hidden +~~~~~~~~~~~~~ + +Either ``yes`` or ``no``; whether to ignore hidden files when importing. On +Windows, the "Hidden" property of files is used to detect whether or not a file +is hidden. On OS X, the file's "IsHidden" flag is used to detect whether or not +a file is hidden. On both OS X and other platforms (excluding Windows), files +(and directories) starting with a dot are detected as hidden files. + .. _replace: replace @@ -799,6 +808,7 @@ Here's an example file:: timid: no log: beetslog.txt ignore: .AppleDouble ._* *~ .DS_Store + ignore_hidden: yes art_filename: albumart plugins: bpd pluginpath: ~/beets/myplugins From d13022e51975c0f1c38e85a0ff1b594cecd93e54 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:52:22 +0100 Subject: [PATCH 0757/2280] Use os.lstat instead of CoreFoundation and ctypes magic on OS X --- beets/util/hidden.py | 83 ++++---------------------------------------- 1 file changed, 6 insertions(+), 77 deletions(-) diff --git a/beets/util/hidden.py b/beets/util/hidden.py index 3d7022ae7..6d8fe58ac 100644 --- a/beets/util/hidden.py +++ b/beets/util/hidden.py @@ -1,91 +1,20 @@ """Simple library to work out if a file is hidden on different platforms.""" +import os +import stat import ctypes -import ctypes.util -import os.path import sys -# Adjustments for CoreFoundation functions on OS X. -_CF_FUNCTION_MAPPINGS = { - 'CFRelease': { - 'argtypes': [ctypes.c_void_p], - 'restype': None - }, - 'CFURLCreateFromFileSystemRepresentation': { - 'argtypes': [ - ctypes.c_void_p, - ctypes.c_char_p, - ctypes.c_long, - ctypes.c_int - ], - 'restype': ctypes.c_void_p - }, - 'CFURLCopyResourcePropertyForKey': { - 'argtypes': [ - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_void_p - ], - 'restype': ctypes.c_void_p - }, - 'CFBooleanGetValue': { - 'argtypes': [ctypes.c_void_p], - 'restype': ctypes.c_int - } -} - - -def _dict_attr_copy(source, destination): - """Copy dict values from source on to destination as attributes.""" - for k, v in source.iteritems(): - if isinstance(v, dict): - _dict_attr_copy(v, getattr(destination, k)) - else: - setattr(destination, k, v) - - def _is_hidden_osx(path): """Return whether or not a file is hidden on OS X. - This uses CoreFoundation alongside CFURL to work out if a file has the - "hidden" flag. + This uses os.lstat to work out if a file has the "hidden" flag. """ - # Load CoreFoundation. - cf_path = ctypes.util.find_library('CoreFoundation') - cf = ctypes.cdll.LoadLibrary(cf_path) + file_stat = os.lstat(path) - # Copy the adjustments on to the library. - _dict_attr_copy(_CF_FUNCTION_MAPPINGS, cf) - - # Create a URL from the path. - url = cf.CFURLCreateFromFileSystemRepresentation(None, path, len(path), - False) - - # Retrieve the hidden key. - is_hidden_key = ctypes.c_void_p.in_dll(cf, 'kCFURLIsHiddenKey') - - # Create a void pointer and get the address of it. - val = ctypes.c_void_p(0) - val_address = ctypes.addressof(val) - - # Get the value (whether or not the file is hidden) for the hidden key and - # store it in val. - success = cf.CFURLCopyResourcePropertyForKey(url, is_hidden_key, - val_address, None) - - # Check if we were able to get the value for the hidden key. - if success: - - # Retrieve the result as a boolean. - result = cf.CFBooleanGetValue(val) - - # Release the value and URL. - cf.CFRelease(val) - cf.CFRelease(url) - - return bool(result) + if hasattr(file_stat, 'st_flags') and hasattr(stat, 'UF_HIDDEN'): + return (file_stat.st_flags & stat.UF_HIDDEN) == stat.UF_HIDDEN else: return False From 506f1b7351ce70e3e730a277a85fe3b17fbe52c4 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:55:29 +0100 Subject: [PATCH 0758/2280] Fix tempfile spelling in hidden test --- test/test_hidden.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_hidden.py b/test/test_hidden.py index a02282ef5..1c2f44848 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -70,5 +70,5 @@ class HiddenFileTest(unittest.TestCase): self.skipTest('sys.platform is known') return - with temfile.NamedTemporaryFile(prefix='.tmp') as f: + with tempfile.NamedTemporaryFile(prefix='.tmp') as f: self.assertTrue(hidden.is_hidden(f.name)) From 99326192eb29d9c42c398092ea19b9b88d096e9c Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 00:55:55 +0100 Subject: [PATCH 0759/2280] Add missing copyright and future imports --- beets/util/hidden.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/beets/util/hidden.py b/beets/util/hidden.py index 6d8fe58ac..101e8c2d1 100644 --- a/beets/util/hidden.py +++ b/beets/util/hidden.py @@ -1,4 +1,20 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + """Simple library to work out if a file is hidden on different platforms.""" +from __future__ import division, absolute_import, print_function import os import stat From f8b1a2e565b055d90f15b2a6d7aa16031eb4e1f0 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 11:24:28 +0100 Subject: [PATCH 0760/2280] Remove unnecessary equality check - Remove unnecessary equality check and wrap the value in `bool`. - Remove unnecessary `bool` wrapping. --- beets/util/hidden.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/hidden.py b/beets/util/hidden.py index 101e8c2d1..262d371ea 100644 --- a/beets/util/hidden.py +++ b/beets/util/hidden.py @@ -30,7 +30,7 @@ def _is_hidden_osx(path): file_stat = os.lstat(path) if hasattr(file_stat, 'st_flags') and hasattr(stat, 'UF_HIDDEN'): - return (file_stat.st_flags & stat.UF_HIDDEN) == stat.UF_HIDDEN + return bool(file_stat.st_flags & stat.UF_HIDDEN) else: return False @@ -48,7 +48,7 @@ def _is_hidden_win(path): attrs = ctypes.windll.kernel32.GetFileAttributesW(path) # Ensure we have valid attribues and compare them against the mask. - return attrs >= 0 and bool(attrs & hidden_mask) + return attrs >= 0 and attrs & hidden_mask def _is_hidden_dot(path): From 78109d779e8a31f5bb0722e6c7466ba3ddb0698e Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 11:27:33 +0100 Subject: [PATCH 0761/2280] Update changelog to reflect addition of new option --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 99ebc39f5..e3ec794b5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ New features: inputs * New :doc:`/plugins/hook` that allows commands to be executed when an event is emitted by beets. :bug:`1561` :bug:`1603` +* :doc:`/reference/config`: New ``ignore_hidden`` configuration option allowing + platform-specific hidden files to be ignored on import. .. _fanart.tv: https://fanart.tv/ From 2d5c68cec90a751f3c252380f2597731b63fd80f Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 17:50:27 +0100 Subject: [PATCH 0762/2280] Remove write option from bpm and use import.write --- beetsplug/bpm.py | 5 ++--- docs/plugins/bpm.rst | 5 +++-- docs/reference/config.rst | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index 4e7b202ac..9166082e3 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -53,8 +53,7 @@ class BPMPlugin(BeetsPlugin): super(BPMPlugin, self).__init__() self.config.add({ u'max_strokes': 3, - u'overwrite': True, - u'write': False + u'overwrite': True }) def commands(self): @@ -66,7 +65,7 @@ class BPMPlugin(BeetsPlugin): def command(self, lib, opts, args): items = lib.items(ui.decargs(args)) - write = self.config['write'].get(bool) + write = ui.should_write() self.get_bpm(items, write) def get_bpm(self, items, write=False): diff --git a/docs/plugins/bpm.rst b/docs/plugins/bpm.rst index f622ebc8d..012c3903c 100644 --- a/docs/plugins/bpm.rst +++ b/docs/plugins/bpm.rst @@ -22,6 +22,9 @@ for instance, with ``mpc`` you can do something like:: beet bpm $(mpc |head -1|tr -d "-") +If :ref:`import.write ` is ``yes``, the song's tags are +written to disk. + Configuration ------------- @@ -33,8 +36,6 @@ The available options are: Default: 3. - **overwrite**: Overwrite the track's existing BPM. Default: ``yes``. -- **write**: Write the song's tags to file when the BPM is updated. - Default: ``no``. Credit ------ diff --git a/docs/reference/config.rst b/docs/reference/config.rst index b074edf5c..827b6855a 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -373,6 +373,8 @@ file that looks like this:: These options are available in this section: +.. _config-import-write: + write ~~~~~ From fcce9c02ac6f3ada1fa6e8579884a64b95dba039 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 17:51:21 +0100 Subject: [PATCH 0763/2280] Revert removal of trailing comma --- beetsplug/bpm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index 9166082e3..542a2b616 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -53,7 +53,7 @@ class BPMPlugin(BeetsPlugin): super(BPMPlugin, self).__init__() self.config.add({ u'max_strokes': 3, - u'overwrite': True + u'overwrite': True, }) def commands(self): From 9c2c331cfd630e610723f3f201c7dd0c3586b8a0 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 6 May 2016 17:54:12 +0100 Subject: [PATCH 0764/2280] Update changelog to reflect removal of write option --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 08d586263..6a779382a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,8 +22,8 @@ New features: source in a flexible field; for a usecase see the documentation. * :doc:`/plugins/export`: A new plugin to export the data from queries to a json format. Thanks to :user:`GuilhermeHideki`. -* :doc:`/plugins/bpm`: Add ``write`` option to write tracks after updating - their BPM. +* :doc:`/plugins/bpm`: Now uses ``import.write`` option to write tracks after + updating their BPM. * :doc:`/reference/pathformat`: new functions: %first{} and %ifdef{} * :doc:`/reference/config`: option ``terminal_encoding`` now works for some inputs From c1a168590c4418c18bf6b0066e6db509c039dd80 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 5 May 2016 21:46:29 -0400 Subject: [PATCH 0765/2280] add lost+found directory to default ignore list --- beets/config_default.yaml | 3 ++- docs/changelog.rst | 2 ++ docs/reference/config.rst | 7 ++++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index dfe31ade8..4c12c3df0 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -25,8 +25,9 @@ import: search_ids: [] clutter: ["Thumbs.DB", ".DS_Store"] -ignore: [".*", "*~", "System Volume Information"] +ignore: [".*", "*~", "System Volume Information", "lost+found"] ignore_hidden: yes + replace: '[\\/]': _ '^\.': _ diff --git a/docs/changelog.rst b/docs/changelog.rst index ca6738994..31cd892f7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -29,6 +29,8 @@ New features: emitted by beets. :bug:`1561` :bug:`1603` * :doc:`/reference/config`: New ``ignore_hidden`` configuration option allowing platform-specific hidden files to be ignored on import. +* :doc:`/reference/config`: option ``ignore`` now includes ``lost+found`` + directory by default .. _fanart.tv: https://fanart.tv/ diff --git a/docs/reference/config.rst b/docs/reference/config.rst index e84dc4a17..20e9fa6bc 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -87,9 +87,10 @@ ignore ~~~~~~ A list of glob patterns specifying file and directory names to be ignored when -importing. By default, this consists of ``.*``, ``*~``, and ``System Volume -Information`` (i.e., beets ignores Unix-style hidden files, backup files, and -a directory that appears at the root of some Windows filesystems). +importing. By default, this consists of ``.*``, ``*~``, ``System Volume +Information``, ``lost+found`` (i.e., beets ignores Unix-style hidden files, +backup files, and directories that appears at the root of some Linux and Windows +filesystems). ignore_hidden ~~~~~~~~~~~~~ From 0f4b454c206b6487207f2f7218232b3916ae45bd Mon Sep 17 00:00:00 2001 From: David Logie Date: Sun, 8 May 2016 16:43:45 +0100 Subject: [PATCH 0766/2280] Don't blow up if a subcommand has no help string. --- beets/ui/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index aeb3b8f52..933026b09 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -989,7 +989,8 @@ class SubcommandsOptionParser(CommonOptionsParser): result.append(name) help_width = formatter.width - help_position help_lines = textwrap.wrap(subcommand.help, help_width) - result.append("%*s%s\n" % (indent_first, "", help_lines[0])) + help_line = help_lines[0] if help_lines else '' + result.append("%*s%s\n" % (indent_first, "", help_line)) result.extend(["%*s%s\n" % (help_position, "", line) for line in help_lines[1:]]) formatter.dedent() From ef7cca4c1205466086c658a9f50cefb09b5da450 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 18 May 2016 11:24:34 -0700 Subject: [PATCH 0767/2280] Fix #2005: list AIFF as a lossless format --- beetsplug/convert.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 9debd6ca1..6463d2a1f 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -39,7 +39,7 @@ ALIASES = { u'vorbis': u'ogg', } -LOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav'] +LOSSLESS_FORMATS = ['ape', 'flac', 'alac', 'wav', 'aiff'] def replace_ext(path, ext): diff --git a/docs/changelog.rst b/docs/changelog.rst index 251057c20..c1a5e221a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -54,6 +54,8 @@ Fixes: artist and album names. :bug:`1960` * :doc:`/plugins/convert`: Change default `ogg` encoding quality from 2 to 3 (to fit the default from the `oggenc(1)` manpage). :bug:`1982` +* :doc:`/plugins/convert`: The `never_convert_lossy_files` option now + considers AIFF a lossless format. :bug:`2005` 1.3.17 (February 7, 2016) From 37b9360706bd1fb4ce90924116db837e615ac024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20=E2=80=9CFreso=E2=80=9D=20S=2E=20Olesen?= Date: Fri, 20 May 2016 01:01:16 +0200 Subject: [PATCH 0768/2280] acousticbrainz plugin: Access acousticbrainz.org over HTTPS. --- beetsplug/acousticbrainz.py | 2 +- docs/changelog.rst | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 6acea8140..507b3e049 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -22,7 +22,7 @@ import operator from beets import plugins, ui -ACOUSTIC_BASE = "http://acousticbrainz.org/" +ACOUSTIC_BASE = "https://acousticbrainz.org/" LEVELS = ["/low-level", "/high-level"] diff --git a/docs/changelog.rst b/docs/changelog.rst index c1a5e221a..7f2ffcd3a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -57,6 +57,11 @@ Fixes: * :doc:`/plugins/convert`: The `never_convert_lossy_files` option now considers AIFF a lossless format. :bug:`2005` +Other changes: + +* :doc:`/plugins/acousticbrainz`: AcousticBrainz lookups are now done over + HTTPS. Thanks to :user:`Freso`. :bug:`2007` + 1.3.17 (February 7, 2016) ------------------------- From fadb2da1200225dfa1d099330c4f0881b7c08cd2 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sat, 21 May 2016 07:33:38 +0200 Subject: [PATCH 0769/2280] Update lyrics.rst fix typo in url --- docs/plugins/lyrics.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 8b88c7ef8..992eb88c5 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -108,7 +108,7 @@ If you use default ``google_engine_ID``, we recommend limiting the sources to ``musixmatch google`` as the other sources are already included in the Google results. -.. _register for a Google API key: https://code.google.com/apis/console. +.. _register for a Google API key: https://code.google.com/apis/console Optionally, you can `define a custom search engine`_. Get your search engine's token and use it for your ``google_engine_ID`` configuration option. By From be4dc227fcdb1a6ace32b5d29e67d4a688b7f690 Mon Sep 17 00:00:00 2001 From: Lars Kruse Date: Tue, 24 May 2016 03:05:51 +0200 Subject: [PATCH 0770/2280] web: handle missing art gracefully --- beetsplug/web/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index ede4658a2..0cddc8746 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -218,7 +218,10 @@ def album_query(queries): @app.route('/album//art') def album_art(album_id): album = g.lib.get_album(album_id) - return flask.send_file(album.artpath) + if album.artpath: + return flask.send_file(album.artpath) + else: + return flask.abort(404) # Artists. From 1e591c8122b149c5f1e0ff893326e310c594514d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 24 May 2016 10:39:36 -0700 Subject: [PATCH 0771/2280] Changelog for #2011 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 7f2ffcd3a..465d25e71 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -56,6 +56,9 @@ Fixes: (to fit the default from the `oggenc(1)` manpage). :bug:`1982` * :doc:`/plugins/convert`: The `never_convert_lossy_files` option now considers AIFF a lossless format. :bug:`2005` +* :doc:`/plugins/web`: A proper 404 error, instead of an internal exception, + is returned when missing album art is requested. Thanks to + :user:`sumpfralle`. :bug:`2011` Other changes: From 18aef27402d67483176233a1b6320c50d09c557e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 00:11:31 -0400 Subject: [PATCH 0772/2280] Cover more float types in safe_cast Now input like `.` and `1.0.0` are handled --- beets/mediafile.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 1bd7b8a47..d7a4a4e2a 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -158,7 +158,8 @@ def _safe_cast(out_type, val): else: if not isinstance(val, basestring): val = unicode(val) - match = re.match(r'[\+-]?[0-9\.]+', val.strip()) + match = re.match(r'[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)', + val.strip()) if match: val = match.group(0) if val: From 5963595f32be0ff979ca3a6437cb693495471f7f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 00:16:41 -0400 Subject: [PATCH 0773/2280] Add safe_cast tests for . and 1.0.0 --- test/test_mediafile_edge.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 17121565b..180c6ca2d 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -132,6 +132,14 @@ class InvalidValueToleranceTest(unittest.TestCase): v = _sc(float, u'+') self.assertEqual(v, 0.0) + def test_safe_cast_float_with_dot_only(self): + v = _sc(float, u'.') + self.assertEqual(v, 0.0) + + def test_safe_cast_float_with_multiple_dots(self): + v = _sc(float, u'1.0.0') + self.assertEqual(v, 1.0) + class SafetyTest(unittest.TestCase, TestHelper): def setUp(self): From 15cc1282337383b08ec8770e61f70fc158fa5506 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 01:45:16 -0400 Subject: [PATCH 0774/2280] add safe_cast fixes to the changelog --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 465d25e71..a5cd54bad 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -59,6 +59,7 @@ Fixes: * :doc:`/plugins/web`: A proper 404 error, instead of an internal exception, is returned when missing album art is requested. Thanks to :user:`sumpfralle`. :bug:`2011` +* Handle more float edge cases in ``safe_cast``. :bug:`2014` Other changes: From 34f17fbf028e92a9f7980a0fd7a38b5a41ec2d97 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 21:30:54 -0400 Subject: [PATCH 0775/2280] remove unused TYPES_TYPE from confit --- beets/util/confit.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 28847e760..88f7c516c 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -22,7 +22,6 @@ import os import pkgutil import sys import yaml -import types import collections import re try: @@ -51,7 +50,6 @@ PY3 = sys.version_info[0] == 3 STRING = str if PY3 else unicode BASESTRING = str if PY3 else basestring NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) -TYPE_TYPES = (type,) if PY3 else (type, types.ClassType) def iter_first(sequence): From d50923553dcab7be7e5e202cd8532fdf6ef284bc Mon Sep 17 00:00:00 2001 From: Lars Kruse Date: Sun, 22 May 2016 21:25:24 +0200 Subject: [PATCH 0776/2280] web: add API functions for retrieving unique values of specific keys the following API paths are added: * /item/values/FIELD * /album/values/FIELD Both paths will deliver a json dictionary with the key 'values' containing a list of unique values belonging to the requested table and field. Sorting is possible by supplying the query argument "sort_key". This feature is useful for remote clients, e.g. Mopidy-Beets: * track genres: /item/unique/genre * track languages: /album/unique/language * album artists: /album/unique/albumartist?sort_key=albumartist_sort * album years: /album/unique/year --- beetsplug/web/__init__.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index ede4658a2..582eb1606 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -124,6 +124,16 @@ def resource_list(name): return make_responder +def _get_unique_table_field_values(model, field, sort_field): + """ retrieve all unique values belonging to a key from a model """ + if field not in model.all_keys() or sort_field not in model.all_keys(): + raise KeyError + with g.lib.transaction() as tx: + rows = tx.query('SELECT DISTINCT "{0}" FROM "{1}" ORDER BY "{2}"' + .format(field, model._table, sort_field)) + return [row[0] for row in rows] + + class IdListConverter(BaseConverter): """Converts comma separated lists of ids in urls to integer lists. """ @@ -194,6 +204,17 @@ def item_query(queries): return g.lib.items(queries) +@app.route('/item/values/') +def item_unique_field_values(key): + sort_key = flask.request.args.get('sort_key', key) + try: + values = _get_unique_table_field_values(beets.library.Item, key, + sort_key) + except KeyError: + return flask.abort(404) + return flask.jsonify(values=values) + + # Albums. @app.route('/album/') @@ -221,6 +242,17 @@ def album_art(album_id): return flask.send_file(album.artpath) +@app.route('/album/values/') +def album_unique_field_values(key): + sort_key = flask.request.args.get('sort_key', key) + try: + values = _get_unique_table_field_values(beets.library.Album, key, + sort_key) + except KeyError: + return flask.abort(404) + return flask.jsonify(values=values) + + # Artists. @app.route('/artist/') From cede0ed4660a76ea1b38bb65e10e10d416bbf3f4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 06:13:14 -0400 Subject: [PATCH 0777/2280] remove leading 0 when octal is unwanted --- test/test_types_plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 7af1a8d72..ed5a7552c 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -114,7 +114,7 @@ class TypesPluginTest(unittest.TestCase, TestHelper): self.modify(u'mydate=1999-01-01', u'artist:prince') old.load() - self.assertEqual(old['mydate'], mktime(1999, 01, 01)) + self.assertEqual(old['mydate'], mktime(1999, 1, 1)) self.modify(u'mydate=1999-12-30', u'artist:britney') new.load() From 7f41d5c188dfac5631500c1b44901f694afe1f32 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 06:12:23 -0400 Subject: [PATCH 0778/2280] use 0o prefix when we want octal --- test/test_files.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/test_files.py b/test/test_files.py index e3e4857c9..e27e317cb 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -103,15 +103,15 @@ class MoveTest(_common.TestCase): def test_read_only_file_copied_writable(self): # Make the source file read-only. - os.chmod(self.path, 0444) + os.chmod(self.path, 0o444) try: self.i.move(copy=True) self.assertTrue(os.access(self.i.path, os.W_OK)) finally: # Make everything writable so it can be cleaned up. - os.chmod(self.path, 0777) - os.chmod(self.i.path, 0777) + os.chmod(self.path, 0o777) + os.chmod(self.i.path, 0o777) def test_move_avoids_collision_with_existing_file(self): # Make a conflicting file at the destination. @@ -354,7 +354,7 @@ class ArtFileTest(_common.TestCase): newart = os.path.join(self.libdir, 'newart.jpg') touch(newart) - os.chmod(newart, 0400) # read-only + os.chmod(newart, 0o400) # read-only try: i2 = item() @@ -370,8 +370,8 @@ class ArtFileTest(_common.TestCase): finally: # Make everything writable so it can be cleaned up. - os.chmod(newart, 0777) - os.chmod(ai.artpath, 0777) + os.chmod(newart, 0o777) + os.chmod(ai.artpath, 0o777) def test_move_last_file_moves_albumart(self): oldartpath = self.lib.albums()[0].artpath From d6d7341314d171d2d9b86311000299746e4b5f79 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 06:14:40 -0400 Subject: [PATCH 0779/2280] use exec() in a python3 compatible way --- beets/util/functemplate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 5764807c3..b4097baba 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -134,7 +134,7 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): dis.dis(const) the_locals = {} - exec prog in {}, the_locals + exec(prog, {}, the_locals) return the_locals[name] From f1ecf0af1035416a451f567eb678f0aa5f3d9a7f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 22:40:55 -0400 Subject: [PATCH 0780/2280] remove unneeded if PY3 in iter_first --- beets/util/confit.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 88f7c516c..ac1cb7023 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -58,10 +58,7 @@ def iter_first(sequence): """ it = iter(sequence) try: - if PY3: - return next(it) - else: - return it.next() + return next(it) except StopIteration: raise ValueError() From a405a072f7950aaf898429ce9c0d7a413896873a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 26 May 2016 06:15:40 -0400 Subject: [PATCH 0781/2280] use reduce() from functools --- beets/autotag/match.py | 1 + beets/dbcore/query.py | 1 + beetsplug/acousticbrainz.py | 1 + 3 files changed, 3 insertions(+) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index e16b0dfaa..cfe184e71 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -29,6 +29,7 @@ from beets import config from beets.util import plurality from beets.autotag import hooks from beets.util.enumeration import OrderedEnum +from functools import reduce # Artist signals that indicate "various artists". These are used at the # album level to determine whether a given release is likely a VA diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index d344f9fef..caf380260 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -22,6 +22,7 @@ from operator import mul from beets import util from datetime import datetime, timedelta import unicodedata +from functools import reduce class ParsingError(ValueError): diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 507b3e049..df790b26f 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -21,6 +21,7 @@ import requests import operator from beets import plugins, ui +from functools import reduce ACOUSTIC_BASE = "https://acousticbrainz.org/" LEVELS = ["/low-level", "/high-level"] From a3b219d7c2c2fedd4b37d61c5a16e7c18b6b4c98 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 27 May 2016 00:56:00 -0400 Subject: [PATCH 0782/2280] Rebase our .gitignore on top of gitignore.io --- .gitignore | 105 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 76 insertions(+), 29 deletions(-) diff --git a/.gitignore b/.gitignore index cde892b3b..50a0f290c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,86 @@ - # general hidden files/directories - .DS_Store -.sconsign* -.svn -.tox -.coverage .idea -.ackrc # file patterns - -*.dylib -*.la -*.lo -*.o -*.pyc -*.pyo -*.so -*.tar.gz -*.tar.bz2 *~ -*.project -*.pydevproject -*.ropeproject -*.orig # Project Specific patterns - -dist/* -beets.egg-info/* -build/* -docs/_build/* man -htmlcov/* -.noseids -*.egg test/rsrc/lyrics/* + +# The rest is from https://www.gitignore.io/api/python + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Flask stuff: +instance/ +.webassets-cache + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# pyenv +.python-version + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject From 976606f5e692abab15fcc80211e1b625a1279858 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 27 May 2016 00:18:52 -0700 Subject: [PATCH 0783/2280] Changelog and thanks for #2010 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a5cd54bad..91166bd82 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -32,6 +32,8 @@ New features: platform-specific hidden files to be ignored on import. * :doc:`/reference/config`: option ``ignore`` now includes ``lost+found`` directory by default +* :doc:`/plugins/web`: A new `values` endpoint lets you get the distinct values + of a field. Thanks to :user:`sumpfralle`. :bug:`2010` .. _fanart.tv: https://fanart.tv/ From b99a6acc549d00cdb6968941889a26a2e69e9f8e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 27 May 2016 01:07:56 -0400 Subject: [PATCH 0784/2280] use next() instead of iter.next() throughout --- beets/dbcore/db.py | 6 +++--- beets/util/pipeline.py | 8 ++++---- test/test_dbcore.py | 2 +- test/test_pipeline.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index ba67dd6d1..61906a08d 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -609,8 +609,8 @@ class Results(object): it = iter(self) try: for i in range(n): - it.next() - return it.next() + next(it) + return next(it) except StopIteration: raise IndexError(u'result index {0} out of range'.format(n)) @@ -620,7 +620,7 @@ class Results(object): """ it = iter(self) try: - return it.next() + return next(it) except StopIteration: return None diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 9b134d1e7..bae06111c 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -248,7 +248,7 @@ class FirstPipelineThread(PipelineThread): # Get the value from the generator. try: - msg = self.coro.next() + msg = next(self.coro) except StopIteration: break @@ -281,7 +281,7 @@ class MiddlePipelineThread(PipelineThread): def run(self): try: # Prime the coroutine. - self.coro.next() + next(self.coro) while True: with self.abort_lock: @@ -326,7 +326,7 @@ class LastPipelineThread(PipelineThread): def run(self): # Prime the coroutine. - self.coro.next() + next(self.coro) try: while True: @@ -444,7 +444,7 @@ class Pipeline(object): # "Prime" the coroutines. for coro in coros[1:]: - coro.next() + next(coro) # Begin the pipeline. for out in coros[0]: diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 0098dc375..0782fc26a 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -609,7 +609,7 @@ class ResultsIteratorTest(unittest.TestCase): results = self.db._fetch(TestModel1) it1 = iter(results) it2 = iter(results) - it1.next() + next(it1) list(it2) self.assertEqual(len(list(it1)), 1) diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 2f5395fb5..2af10a336 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -133,7 +133,7 @@ class ExceptionTest(unittest.TestCase): pl = pipeline.Pipeline((_produce(), _exc_work())) pull = pl.pull() for i in range(3): - pull.next() + next(pull) self.assertRaises(TestException, pull.next) From 1ae6ce04dd8f0c7f0b948feb9c6f7d89d28eba13 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Fri, 27 May 2016 23:13:01 +0200 Subject: [PATCH 0785/2280] Run python-modernize across the codebase --- beets/autotag/hooks.py | 2 +- beets/library.py | 2 +- beets/ui/commands.py | 4 ++-- beets/util/confit.py | 2 +- beets/util/functemplate.py | 2 +- extra/release.py | 8 +++++--- test/test_thumbnails.py | 2 +- 7 files changed, 12 insertions(+), 10 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 5c8e0e2c5..8f0a98104 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -349,7 +349,7 @@ class Distance(object): # Convert distance into a negative float we can sort items in # ascending order (for keys, when the penalty is equal) and # still get the items with the biggest distance first. - return sorted(list_, key=lambda (key, dist): (0 - dist, key)) + return sorted(list_, key=lambda key_dist: (0 - key_dist[1], key_dist[0])) # Behave like a float. diff --git a/beets/library.py b/beets/library.py index ed1938671..bb6873d2d 100644 --- a/beets/library.py +++ b/beets/library.py @@ -559,7 +559,7 @@ class Item(LibModel): for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, (int, long)): + if isinstance(value, (int, int)): if value.bit_length() > 63: value = 0 self[key] = value diff --git a/beets/ui/commands.py b/beets/ui/commands.py index a2669e688..2d9f3cdb1 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -280,7 +280,7 @@ def show_change(cur_artist, cur_album, match): # Tracks. pairs = match.mapping.items() - pairs.sort(key=lambda (_, track_info): track_info.index) + pairs.sort(key=lambda __track_info: __track_info[1].index) # Build up LHS and RHS for track difference display. The `lines` list # contains ``(lhs, rhs, width)`` tuples where `width` is the length (in @@ -442,7 +442,7 @@ def summarize_items(items, singleton): else: # Enumerate all the formats by decreasing frequencies: for fmt, count in sorted(format_counts.items(), - key=lambda (f, c): (-c, f)): + key=lambda f_c: (-f_c[1], f_c[0])): summary_parts.append('{0} {1}'.format(fmt, count)) if items: diff --git a/beets/util/confit.py b/beets/util/confit.py index ac1cb7023..6d35667bc 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -49,7 +49,7 @@ REDACTED_TOMBSTONE = 'REDACTED' PY3 = sys.version_info[0] == 3 STRING = str if PY3 else unicode BASESTRING = str if PY3 else basestring -NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) +NUMERIC_TYPES = (int, float) if PY3 else (int, float, int) def iter_first(sequence): diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index b4097baba..16d21cd58 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -72,7 +72,7 @@ def ex_literal(val): """ if val is None: return ast.Name(b'None', ast.Load()) - elif isinstance(val, (int, float, long)): + elif isinstance(val, (int, float, int)): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) diff --git a/extra/release.py b/extra/release.py index 7bbc080c4..cf368c8f3 100755 --- a/extra/release.py +++ b/extra/release.py @@ -3,6 +3,8 @@ """A utility script for automating the beets release process. """ +from __future__ import absolute_import +from __future__ import print_function import click import os import re @@ -110,7 +112,7 @@ def bump_version(version): out_lines.append(line) if not found: - print("No pattern found in {}".format(filename)) + print(("No pattern found in {}".format(filename))) # Write the file back. with open(filename, 'w') as f: @@ -212,7 +214,7 @@ def changelog_as_markdown(): def changelog(): """Get the most recent version's changelog as Markdown. """ - print(changelog_as_markdown()) + print((changelog_as_markdown())) def get_version(index=0): @@ -233,7 +235,7 @@ def get_version(index=0): def version(): """Display the current version. """ - print(get_version()) + print((get_version())) @release.command() diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 30c5bb234..24a1bc92d 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -114,7 +114,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): self.assertEqual(ThumbnailsPlugin().get_uri, giouri_inst.uri) giouri_inst.available = False - self.assertEqual(ThumbnailsPlugin().get_uri.im_class, PathlibURI) + self.assertEqual(ThumbnailsPlugin().get_uri.__self__.__class__, PathlibURI) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @patch('beetsplug.thumbnails.ArtResizer') From 9518f28faaaee6327dcc0824684b1c21110fd33c Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Fri, 27 May 2016 23:15:21 +0200 Subject: [PATCH 0786/2280] Fix numeric types --- beets/library.py | 2 +- beets/util/confit.py | 2 +- beets/util/functemplate.py | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/beets/library.py b/beets/library.py index bb6873d2d..ed1938671 100644 --- a/beets/library.py +++ b/beets/library.py @@ -559,7 +559,7 @@ class Item(LibModel): for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, (int, int)): + if isinstance(value, (int, long)): if value.bit_length() > 63: value = 0 self[key] = value diff --git a/beets/util/confit.py b/beets/util/confit.py index 6d35667bc..ac1cb7023 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -49,7 +49,7 @@ REDACTED_TOMBSTONE = 'REDACTED' PY3 = sys.version_info[0] == 3 STRING = str if PY3 else unicode BASESTRING = str if PY3 else basestring -NUMERIC_TYPES = (int, float) if PY3 else (int, float, int) +NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) def iter_first(sequence): diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 16d21cd58..6c8e3e73b 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -34,6 +34,8 @@ import ast import dis import types +from .confit import NUMERIC_TYPES + SYMBOL_DELIM = u'$' FUNC_DELIM = u'%' GROUP_OPEN = u'{' @@ -72,7 +74,7 @@ def ex_literal(val): """ if val is None: return ast.Name(b'None', ast.Load()) - elif isinstance(val, (int, float, int)): + elif isinstance(val, NUMERIC_TYPES): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) From 0fc07c28bc08c840588c8e8c6efba610e73f0dc4 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Fri, 27 May 2016 23:16:07 +0200 Subject: [PATCH 0787/2280] Stylefixes --- beets/autotag/hooks.py | 3 ++- test/test_thumbnails.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 8f0a98104..1c0408e2f 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -349,7 +349,8 @@ class Distance(object): # Convert distance into a negative float we can sort items in # ascending order (for keys, when the penalty is equal) and # still get the items with the biggest distance first. - return sorted(list_, key=lambda key_dist: (0 - key_dist[1], key_dist[0])) + return sorted(list_, + key=lambda key_dist: (0 - key_dist[1], key_dist[0])) # Behave like a float. diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 24a1bc92d..152663091 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -114,7 +114,8 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): self.assertEqual(ThumbnailsPlugin().get_uri, giouri_inst.uri) giouri_inst.available = False - self.assertEqual(ThumbnailsPlugin().get_uri.__self__.__class__, PathlibURI) + self.assertEqual(ThumbnailsPlugin().get_uri.__self__.__class__, + PathlibURI) @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') @patch('beetsplug.thumbnails.ArtResizer') From 5c41a9e7670a14576d4be82d488027eda26a5897 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Fri, 27 May 2016 23:18:22 +0200 Subject: [PATCH 0788/2280] Remove superfluous parens --- extra/release.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extra/release.py b/extra/release.py index cf368c8f3..d8b1e9dac 100755 --- a/extra/release.py +++ b/extra/release.py @@ -112,7 +112,7 @@ def bump_version(version): out_lines.append(line) if not found: - print(("No pattern found in {}".format(filename))) + print("No pattern found in {}".format(filename)) # Write the file back. with open(filename, 'w') as f: @@ -214,7 +214,7 @@ def changelog_as_markdown(): def changelog(): """Get the most recent version's changelog as Markdown. """ - print((changelog_as_markdown())) + print(changelog_as_markdown()) def get_version(index=0): @@ -235,7 +235,7 @@ def get_version(index=0): def version(): """Display the current version. """ - print((get_version())) + print(get_version()) @release.command() From f2f18d9d566190aae98a4b7bea72320355dbb024 Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Fri, 27 May 2016 23:50:01 +0200 Subject: [PATCH 0789/2280] Fix variable names --- beets/autotag/hooks.py | 6 ++++-- beets/ui/commands.py | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 1c0408e2f..3de803899 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -349,8 +349,10 @@ class Distance(object): # Convert distance into a negative float we can sort items in # ascending order (for keys, when the penalty is equal) and # still get the items with the biggest distance first. - return sorted(list_, - key=lambda key_dist: (0 - key_dist[1], key_dist[0])) + return sorted( + list_, + key=lambda key_and_dist: (-key_and_dist[1], key_and_dist[0]) + ) # Behave like a float. diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 2d9f3cdb1..3f55d864e 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -280,7 +280,7 @@ def show_change(cur_artist, cur_album, match): # Tracks. pairs = match.mapping.items() - pairs.sort(key=lambda __track_info: __track_info[1].index) + pairs.sort(key=lambda item_and_track_info: item_and_track_info[1].index) # Build up LHS and RHS for track difference display. The `lines` list # contains ``(lhs, rhs, width)`` tuples where `width` is the length (in @@ -441,8 +441,10 @@ def summarize_items(items, singleton): summary_parts.append(items[0].format) else: # Enumerate all the formats by decreasing frequencies: - for fmt, count in sorted(format_counts.items(), - key=lambda f_c: (-f_c[1], f_c[0])): + for fmt, count in sorted( + format_counts.items(), + key=lambda fmt_and_count: (-fmt_and_count[1], fmt_and_count[0]) + ): summary_parts.append('{0} {1}'.format(fmt, count)) if items: From e82080aec68f684b9879c0378637f9b1cd332e5c Mon Sep 17 00:00:00 2001 From: Markus Unterwaditzer Date: Sat, 28 May 2016 01:22:11 +0200 Subject: [PATCH 0790/2280] Don't cache tox directory This appears to break pull requests and branches that introduce new dependencies See #1484 for example --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index cc1f96e94..3399b2bf8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,8 +35,6 @@ after_success: cache: pip: true - directories: - - .tox notifications: irc: From ce8d7bf9f10353ac1b1150934952b4a25ad587ce Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 27 May 2016 23:46:33 -0400 Subject: [PATCH 0791/2280] remove unittest2 import (py < 2.7) --- test/_common.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/_common.py b/test/_common.py index 33928fb66..4527942cf 100644 --- a/test/_common.py +++ b/test/_common.py @@ -21,13 +21,9 @@ import sys import os import tempfile import shutil +import unittest from contextlib import contextmanager -# Use unittest2 on Python < 2.7. -try: - import unittest2 as unittest -except ImportError: - import unittest # Mangle the search path to include the beets sources. sys.path.insert(0, '..') # noqa From 93c5e4b5a8dfe19bc03986836160a7a3d7a6e929 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 28 May 2016 00:20:01 -0400 Subject: [PATCH 0792/2280] Remove library import from __init__.py --- beets/__init__.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 57fa66b69..830477a9a 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -17,14 +17,11 @@ from __future__ import division, absolute_import, print_function import os -import beets.library from beets.util import confit __version__ = u'1.3.18' __author__ = u'Adrian Sampson ' -Library = beets.library.Library - class IncludeLazyConfig(confit.LazyConfig): """A version of Confit's LazyConfig that also merges in data from From 9b2e12613269ddd6dddde7fb3dec7a448523971e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 28 May 2016 17:24:55 -0400 Subject: [PATCH 0793/2280] remove __future__ import from py3 native release.py --- extra/release.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/extra/release.py b/extra/release.py index d8b1e9dac..7bbc080c4 100755 --- a/extra/release.py +++ b/extra/release.py @@ -3,8 +3,6 @@ """A utility script for automating the beets release process. """ -from __future__ import absolute_import -from __future__ import print_function import click import os import re From c330f3abc3addcfa40bcb9b376724b0d091d15d0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 29 May 2016 03:56:39 -0400 Subject: [PATCH 0794/2280] replace deprecated assert_() with assertTrue() --- test/test_autotag.py | 10 +++++----- test/test_files.py | 2 +- test/test_library.py | 26 +++++++++++++------------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/test/test_autotag.py b/test/test_autotag.py index 71fbdad73..00857ae97 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -47,7 +47,7 @@ class PluralityTest(_common.TestCase): def test_plurality_conflict(self): objs = [1, 1, 2, 2, 3] obj, freq = plurality(objs) - self.assert_(obj in (1, 2)) + self.assertTrue(obj in (1, 2)) self.assertEqual(freq, 2) def test_plurality_empty_sequence_raises_error(self): @@ -879,17 +879,17 @@ class StringDistanceTest(unittest.TestCase): def test_leading_the_has_lower_weight(self): dist1 = string_dist(u'XXX Band Name', u'Band Name') dist2 = string_dist(u'The Band Name', u'Band Name') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_parens_have_lower_weight(self): dist1 = string_dist(u'One .Two.', u'One') dist2 = string_dist(u'One (Two)', u'One') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_brackets_have_lower_weight(self): dist1 = string_dist(u'One .Two.', u'One') dist2 = string_dist(u'One [Two]', u'One') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_ep_label_has_zero_weight(self): dist = string_dist(u'My Song (EP)', u'My Song') @@ -898,7 +898,7 @@ class StringDistanceTest(unittest.TestCase): def test_featured_has_lower_weight(self): dist1 = string_dist(u'My Song blah Someone', u'My Song') dist2 = string_dist(u'My Song feat Someone', u'My Song') - self.assert_(dist2 < dist1) + self.assertTrue(dist2 < dist1) def test_postfix_the(self): dist = string_dist(u'The Song Title', u'Song Title, The') diff --git a/test/test_files.py b/test/test_files.py index e27e317cb..e302f0846 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -200,7 +200,7 @@ class AlbumFileTest(_common.TestCase): self.ai.store() self.i.load() - self.assert_('newAlbumName' in self.i.path) + self.assertTrue('newAlbumName' in self.i.path) def test_albuminfo_move_moves_file(self): oldpath = self.i.path diff --git a/test/test_library.py b/test/test_library.py index 4d6a51b93..af285048a 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -244,7 +244,7 @@ class DestinationTest(_common.TestCase): def test_path_with_format(self): self.lib.path_formats = [(u'default', u'$artist/$album ($format)')] p = self.i.destination() - self.assert_('(FLAC)' in p) + self.assertTrue('(FLAC)' in p) def test_heterogeneous_album_gets_single_directory(self): i1, i2 = item(), item() @@ -883,7 +883,7 @@ class ArtDestinationTest(_common.TestCase): def test_art_filename_respects_setting(self): art = self.ai.art_destination('something.jpg') - self.assert_('%sartimage.jpg' % os.path.sep in art) + self.assertTrue('%sartimage.jpg' % os.path.sep in art) def test_art_path_in_item_dir(self): art = self.ai.art_destination('something.jpg') @@ -893,7 +893,7 @@ class ArtDestinationTest(_common.TestCase): def test_art_path_sanitized(self): config['art_filename'] = u'artXimage' art = self.ai.art_destination('something.jpg') - self.assert_('artYimage' in art) + self.assertTrue('artYimage' in art) class PathStringTest(_common.TestCase): @@ -903,22 +903,22 @@ class PathStringTest(_common.TestCase): self.i = item(self.lib) def test_item_path_is_bytestring(self): - self.assert_(isinstance(self.i.path, bytes)) + self.assertTrue(isinstance(self.i.path, bytes)) def test_fetched_item_path_is_bytestring(self): i = list(self.lib.items())[0] - self.assert_(isinstance(i.path, bytes)) + self.assertTrue(isinstance(i.path, bytes)) def test_unicode_path_becomes_bytestring(self): self.i.path = u'unicodepath' - self.assert_(isinstance(self.i.path, bytes)) + self.assertTrue(isinstance(self.i.path, bytes)) def test_unicode_in_database_becomes_bytestring(self): self.lib._connection().execute(""" update items set path=? where id=? """, (self.i.id, u'somepath')) i = list(self.lib.items())[0] - self.assert_(isinstance(i.path, bytes)) + self.assertTrue(isinstance(i.path, bytes)) def test_special_chars_preserved_in_database(self): path = u'b\xe1r'.encode('utf8') @@ -939,13 +939,13 @@ class PathStringTest(_common.TestCase): def test_destination_returns_bytestring(self): self.i.artist = u'b\xe1r' dest = self.i.destination() - self.assert_(isinstance(dest, bytes)) + self.assertTrue(isinstance(dest, bytes)) def test_art_destination_returns_bytestring(self): self.i.artist = u'b\xe1r' alb = self.lib.add_album([self.i]) dest = alb.art_destination(u'image.jpg') - self.assert_(isinstance(dest, bytes)) + self.assertTrue(isinstance(dest, bytes)) def test_artpath_stores_special_chars(self): path = b'b\xe1r' @@ -958,17 +958,17 @@ class PathStringTest(_common.TestCase): def test_sanitize_path_with_special_chars(self): path = u'b\xe1r?' new_path = util.sanitize_path(path) - self.assert_(new_path.startswith(u'b\xe1r')) + self.assertTrue(new_path.startswith(u'b\xe1r')) def test_sanitize_path_returns_unicode(self): path = u'b\xe1r?' new_path = util.sanitize_path(path) - self.assert_(isinstance(new_path, unicode)) + self.assertTrue(isinstance(new_path, unicode)) def test_unicode_artpath_becomes_bytestring(self): alb = self.lib.add_album([self.i]) alb.artpath = u'somep\xe1th' - self.assert_(isinstance(alb.artpath, bytes)) + self.assertTrue(isinstance(alb.artpath, bytes)) def test_unicode_artpath_in_database_decoded(self): alb = self.lib.add_album([self.i]) @@ -977,7 +977,7 @@ class PathStringTest(_common.TestCase): (u'somep\xe1th', alb.id) ) alb = self.lib.get_album(alb.id) - self.assert_(isinstance(alb.artpath, bytes)) + self.assertTrue(isinstance(alb.artpath, bytes)) class MtimeTest(_common.TestCase): From a37a52633be4e62d3ea463e8df0b2ea2861ab81d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 29 May 2016 04:03:54 -0400 Subject: [PATCH 0795/2280] replace deprecated assertNotEquals() with assertNotEqual() --- test/test_library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index af285048a..60ea868fa 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1148,7 +1148,7 @@ class FilesizeTest(unittest.TestCase, TestHelper): def test_filesize(self): item = self.add_item_fixture() - self.assertNotEquals(item.filesize, 0) + self.assertNotEqual(item.filesize, 0) def test_nonexistent_file(self): item = beets.library.Item() From 662bc1858d4b80be9819a5f581e50e48850a83bc Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 29 May 2016 20:49:06 -0400 Subject: [PATCH 0796/2280] use list() on map() when we really want lists not iters --- beets/importer.py | 2 +- beets/ui/__init__.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index f9cd138f4..bfaa21a01 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -192,7 +192,7 @@ class ImportSession(object): # Normalize the paths. if self.paths: - self.paths = map(normpath, self.paths) + self.paths = list(map(normpath, self.paths)) def _setup_logging(self, loghandler): logger = logging.getLogger(__name__) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 933026b09..a75036c33 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -736,8 +736,8 @@ def show_path_changes(path_changes): sources, destinations = zip(*path_changes) # Ensure unicode output - sources = map(util.displayable_path, sources) - destinations = map(util.displayable_path, destinations) + sources = list(map(util.displayable_path, sources)) + destinations = list(map(util.displayable_path, destinations)) # Calculate widths for terminal split col_width = (term_width() - len(' -> ')) // 2 From 71b9fd785c0468c61214363ad138f115375b10f5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 29 May 2016 19:19:59 -0700 Subject: [PATCH 0797/2280] Revert "Do __name__ comparison with bytes and not unicode" This reverts commit 9c41c399131f86149d64029cd5eec116087d55e4. That commit used byte strings for the `if __name__ == '__main__'` pattern, which was necessary when we were doing unicode_literals. But it is wrong on Python 3, and now that we're liberated from unicode_literals, we need to go back to native strings for this comparison. --- beets/util/confit.py | 2 +- beets/util/functemplate.py | 2 +- beets/util/pipeline.py | 2 +- beetsplug/bpd/gstplayer.py | 2 +- test/lyrics_download_samples.py | 2 +- test/test_art.py | 2 +- test/test_autotag.py | 2 +- test/test_bucket.py | 2 +- test/test_config_command.py | 2 +- test/test_convert.py | 2 +- test/test_datequery.py | 2 +- test/test_dbcore.py | 2 +- test/test_echonest.py | 2 +- test/test_embedart.py | 2 +- test/test_fetchart.py | 2 +- test/test_files.py | 2 +- test/test_ftintitle.py | 2 +- test/test_ihate.py | 2 +- test/test_importadded.py | 2 +- test/test_importer.py | 2 +- test/test_importfeeds.py | 2 +- test/test_info.py | 2 +- test/test_keyfinder.py | 2 +- test/test_lastgenre.py | 2 +- test/test_library.py | 2 +- test/test_logging.py | 2 +- test/test_lyrics.py | 2 +- test/test_mb.py | 2 +- test/test_mbsync.py | 2 +- test/test_mediafile.py | 2 +- test/test_mediafile_edge.py | 2 +- test/test_permissions.py | 2 +- test/test_pipeline.py | 2 +- test/test_player.py | 2 +- test/test_plexupdate.py | 2 +- test/test_plugins.py | 2 +- test/test_query.py | 2 +- test/test_replaygain.py | 2 +- test/test_sort.py | 2 +- test/test_spotify.py | 2 +- test/test_template.py | 2 +- test/test_the.py | 2 +- test/test_types_plugin.py | 2 +- test/test_ui.py | 2 +- test/test_ui_importer.py | 2 +- test/test_vfs.py | 2 +- test/test_web.py | 2 +- test/test_zero.py | 2 +- test/testall.py | 2 +- 49 files changed, 49 insertions(+), 49 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index ac1cb7023..aa49f6f12 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -538,7 +538,7 @@ def _package_path(name): ``name == "__main__"``). """ loader = pkgutil.get_loader(name) - if loader is None or name == b'__main__': + if loader is None or name == '__main__': return None if hasattr(loader, 'get_filename'): diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 6c8e3e73b..d20ef3071 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -559,7 +559,7 @@ class Template(object): # Performance tests. -if __name__ == b'__main__': +if __name__ == '__main__': import timeit _tmpl = Template(u'foo $bar %baz{foozle $bar barzle} $bar') _vars = {'bar': 'qux'} diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index bae06111c..4c55b53be 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -459,7 +459,7 @@ class Pipeline(object): yield msg # Smoke test. -if __name__ == b'__main__': +if __name__ == '__main__': import time # Test a normally-terminating pipeline both in sequence and diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 70d0613d5..b64cd0094 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -214,7 +214,7 @@ def play_complicated(paths): while my_paths: time.sleep(1) -if __name__ == b'__main__': +if __name__ == '__main__': # A very simple command-line player. Just give it names of audio # files on the command line; these are all played in sequence. paths = [os.path.abspath(os.path.expanduser(p)) diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index 280f076a2..21c260146 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -54,5 +54,5 @@ def main(argv=None): with safe_open_w(fn) as f: f.write(html.encode('utf8')) -if __name__ == b'__main__': +if __name__ == "__main__": sys.exit(main()) diff --git a/test/test_art.py b/test/test_art.py index 44b3b9bd4..1bc40a287 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -631,5 +631,5 @@ class EnforceRatioConfigTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_autotag.py b/test/test_autotag.py index 00857ae97..61a4d5d6f 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -952,5 +952,5 @@ class EnumTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_bucket.py b/test/test_bucket.py index 395d2a546..daade86ad 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -164,5 +164,5 @@ class BucketPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_config_command.py b/test/test_config_command.py index f00594b80..77a370ce3 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -134,5 +134,5 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_convert.py b/test/test_convert.py index 679b70a4f..886614822 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -237,5 +237,5 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_datequery.py b/test/test_datequery.py index b978d7304..c139c0c4a 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -127,5 +127,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 0782fc26a..2ca3a6d23 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -658,5 +658,5 @@ class ResultsIteratorTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_echonest.py b/test/test_echonest.py index f19b901d6..8a8bbd780 100644 --- a/test/test_echonest.py +++ b/test/test_echonest.py @@ -189,5 +189,5 @@ class EchonestCliTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_embedart.py b/test/test_embedart.py index 145593829..3e3ce4bea 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -200,5 +200,5 @@ class ArtSimilarityTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_fetchart.py b/test/test_fetchart.py index 065905a87..db3fef8ec 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -54,5 +54,5 @@ class FetchartCliTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_files.py b/test/test_files.py index e302f0846..5af8bd5ef 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -627,5 +627,5 @@ class MkDirAllTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index b8fa90681..711b5daa6 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -181,5 +181,5 @@ class FtInTitlePluginTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ihate.py b/test/test_ihate.py index 6567d13be..1b23964ae 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -50,5 +50,5 @@ class IHatePluginTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importadded.py b/test/test_importadded.py index 6e003ed0f..bddd884f9 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -171,5 +171,5 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importer.py b/test/test_importer.py index ff2020ef8..4a8b20c90 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1854,5 +1854,5 @@ def mocked_get_recording_by_id(id_, includes=[], release_status=[], def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index df293ce63..158e8e51c 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -61,5 +61,5 @@ class ImportfeedsTestTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_info.py b/test/test_info.py index 77f88e7c4..0ac1f95dd 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -116,5 +116,5 @@ class InfoTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 90d65bd26..d459606cf 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -81,5 +81,5 @@ class KeyFinderTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index b397d2c21..19adab98a 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -216,5 +216,5 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_library.py b/test/test_library.py index 60ea868fa..17d526675 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1223,5 +1223,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_logging.py b/test/test_logging.py index 4cf6d1ccc..19d9b0e1e 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -296,5 +296,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 13bffacdb..7201de35a 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -390,5 +390,5 @@ class LyricsGooglePluginTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mb.py b/test/test_mb.py index 5333b2b8c..b4bfc82c7 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -491,5 +491,5 @@ class MBLibraryTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mbsync.py b/test/test_mbsync.py index 14d349a8f..8e4825888 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -131,5 +131,5 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mediafile.py b/test/test_mediafile.py index ad83573da..9fe4cae5b 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -956,5 +956,5 @@ class MediaFieldTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 180c6ca2d..bf86e7f2a 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -399,5 +399,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_permissions.py b/test/test_permissions.py index a1b7ddd19..d3eb6dc77 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -73,5 +73,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 2af10a336..e48a62f53 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -240,5 +240,5 @@ class StageDecoratorTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_player.py b/test/test_player.py index 7898fab68..c8fec446b 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -66,5 +66,5 @@ class CommandParseTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index a6c8741b3..2a2b1cbaf 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -124,5 +124,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_plugins.py b/test/test_plugins.py index ea1756852..c1a83ec21 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -559,5 +559,5 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_query.py b/test/test_query.py index 5fb717c9c..7a076a0ee 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -979,5 +979,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_replaygain.py b/test/test_replaygain.py index d0ceaf709..e3fdf18a6 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -167,5 +167,5 @@ class ReplayGainLdnsCliTest(ReplayGainCliTestBase, unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_sort.py b/test/test_sort.py index daaca262a..16b594c9c 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -536,5 +536,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_spotify.py b/test/test_spotify.py index 6f218c339..104497600 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -208,5 +208,5 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_template.py b/test/test_template.py index efc900034..3ec97bea4 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -276,5 +276,5 @@ class EvalTest(unittest.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_the.py b/test/test_the.py index 3d5c722be..422723386 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -64,5 +64,5 @@ class ThePluginTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index ed5a7552c..6a3df8051 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -151,5 +151,5 @@ def mktime(*args): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui.py b/test/test_ui.py index 4de5e9ed5..c8b6a99d3 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1299,5 +1299,5 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 7dbf1f533..4596e781a 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -148,5 +148,5 @@ class GlobalGroupAlbumsImportTest(TerminalImportSessionSetup, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_vfs.py b/test/test_vfs.py index 6ffaa859d..0b25a1031 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -45,5 +45,5 @@ class VFSTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_web.py b/test/test_web.py index 51f32567d..a8be83d73 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -109,5 +109,5 @@ class WebPluginTest(_common.LibTestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_zero.py b/test/test_zero.py index e223dd787..7b90e22b3 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -124,5 +124,5 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/testall.py b/test/testall.py index 68475e379..9148da8be 100755 --- a/test/testall.py +++ b/test/testall.py @@ -46,5 +46,5 @@ def suite(): s.addTest(__import__(modname).suite()) return s -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') From a5921f625cbba251c747251939b3eb4c98ddb16c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 01:03:18 -0400 Subject: [PATCH 0798/2280] readd deprecated plugins search with name == b'name' This is to make sure we can still load plugins based off official plugins between the time of https://github.com/beetbox/beets/commit/9c41c399131f86149d64029cd5eec116087d55e4 and https://github.com/beetbox/beets/commit/71b9fd785c0468c61214363ad138f115375b10f5 --- beets/util/confit.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index aa49f6f12..c778f183a 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -538,7 +538,8 @@ def _package_path(name): ``name == "__main__"``). """ loader = pkgutil.get_loader(name) - if loader is None or name == '__main__': + # name == b'main' is deprecated + if loader is None or name == '__main__' or name == b'main': return None if hasattr(loader, 'get_filename'): From c52394c499829a9959a7ce5c4b88e36f0b429b93 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 01:11:37 -0400 Subject: [PATCH 0799/2280] fix the rest of b'__main__': --- test/test_edit.py | 2 +- test/test_embyupdate.py | 2 +- test/test_hook.py | 2 +- test/test_ipfs.py | 2 +- test/test_mbsubmit.py | 2 +- test/test_metasync.py | 2 +- test/test_mpdstats.py | 2 +- test/test_play.py | 2 +- test/test_smartplaylist.py | 2 +- test/test_thumbnails.py | 2 +- test/test_ui_commands.py | 2 +- test/test_ui_init.py | 2 +- test/test_util.py | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 94bb2d937..669f6a2fa 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -424,5 +424,5 @@ class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index 3928ae390..dc4cad23c 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -209,5 +209,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_hook.py b/test/test_hook.py index fc4e7a7ee..9985fbbae 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -113,5 +113,5 @@ class HookTest(_common.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 87ca3f2ec..1c2972000 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -93,5 +93,5 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index e89ba2748..a33d8418b 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -68,5 +68,5 @@ class MBSubmitPluginTest(TerminalImportSessionSetup, unittest.TestCase, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_metasync.py b/test/test_metasync.py index f4a5f4d49..c21c16b12 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -123,5 +123,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index 4ad9d00c4..36f5d0d80 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -84,5 +84,5 @@ class MPDStatsTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_play.py b/test/test_play.py index a0f3a6e48..06d41e75e 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -123,5 +123,5 @@ class PlayPluginTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 25f6727f0..401b36570 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -224,5 +224,5 @@ def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 152663091..f3e2858ad 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -291,5 +291,5 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index e71db3ca9..29da4f456 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -119,5 +119,5 @@ class FieldsTest(_common.LibTestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 35fd99cc5..0628d3879 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -116,5 +116,5 @@ class InitTest(_common.LibTestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') diff --git a/test/test_util.py b/test/test_util.py index f6c42a2da..32028c9fb 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -180,5 +180,5 @@ class PathTruncationTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) -if __name__ == b'__main__': +if __name__ == '__main__': unittest.main(defaultTest='suite') From 358c60e43bcf5c5bbc80afb05b0f47e430c50682 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 01:58:05 -0400 Subject: [PATCH 0800/2280] reword a comment in mediafile --- beets/mediafile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index d7a4a4e2a..b0fb5d169 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -279,8 +279,8 @@ def _sc_encode(gain, peak): def _wider_test_jpeg(data): """Test for a jpeg file following the UNIX file implementation which - uses the magic bytes rather than just looking for the bytes b'JFIF' - or b'EXIF' at a fixed position. + uses the magic bytes rather than just looking for the bytes that + represent'JFIF' or 'EXIF' at a fixed position. """ if data[:2] == b'\xff\xd8': return 'jpeg' From 62ba435cd65027aad20f8f97762c624afd427d01 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 01:59:17 -0400 Subject: [PATCH 0801/2280] keyword args can't be bytes, so remove b' prefix --- beets/mediafile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index b0fb5d169..6c77d9664 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1070,7 +1070,7 @@ class MediaField(object): getting this property. """ - self.out_type = kwargs.get(b'out_type', unicode) + self.out_type = kwargs.get('out_type', unicode) self._styles = styles def styles(self, mutagen_file): @@ -1134,7 +1134,7 @@ class ListMediaField(MediaField): """Returns a ``MediaField`` descriptor that gets and sets the first item. """ - options = {b'out_type': self.out_type} + options = {'out_type': self.out_type} return MediaField(*self._styles, **options) @@ -1155,7 +1155,7 @@ class DateField(MediaField): storage styles do not return a value. """ super(DateField, self).__init__(*date_styles) - year_style = kwargs.get(b'year', None) + year_style = kwargs.get('year', None) if year_style: self._year_field = MediaField(*year_style) From 9193cb3f45d34bee30ff66367e3f53ca5889f79c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 15:43:12 -0400 Subject: [PATCH 0802/2280] Revert "readd deprecated plugins search with name == b'name'" This reverts commit a5921f625cbba251c747251939b3eb4c98ddb16c. --- beets/util/confit.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index c778f183a..aa49f6f12 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -538,8 +538,7 @@ def _package_path(name): ``name == "__main__"``). """ loader = pkgutil.get_loader(name) - # name == b'main' is deprecated - if loader is None or name == '__main__' or name == b'main': + if loader is None or name == '__main__': return None if hasattr(loader, 'get_filename'): From 88c5fe60692660b09e7c687ede147684d24470c4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 15:44:21 -0400 Subject: [PATCH 0803/2280] add missing space in mediafile comment --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 6c77d9664..c9489501e 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -280,7 +280,7 @@ def _sc_encode(gain, peak): def _wider_test_jpeg(data): """Test for a jpeg file following the UNIX file implementation which uses the magic bytes rather than just looking for the bytes that - represent'JFIF' or 'EXIF' at a fixed position. + represent 'JFIF' or 'EXIF' at a fixed position. """ if data[:2] == b'\xff\xd8': return 'jpeg' From 32d4545b5ea4025736ab7d08a27cbf559d863b31 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 16:32:34 -0400 Subject: [PATCH 0804/2280] set min-version to 2.7 in setup.cfg --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index b093a20b5..de1f48545 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,6 +4,7 @@ logging-clear-handlers=1 eval-attr="!=slow" [flake8] +min-version = 2.7 # Default pyflakes errors we ignore: # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) From cd1f79340f336adbfd0b04871b28b775bec09e07 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:03:36 -0400 Subject: [PATCH 0805/2280] remove explicit b' from sql query dict key names --- beets/dbcore/db.py | 4 ++-- beets/ui/commands.py | 2 +- test/test_dbcore.py | 2 +- test/test_library.py | 8 ++++---- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 61906a08d..3f701be59 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -562,13 +562,13 @@ class Results(object): 'SELECT * FROM {0} WHERE entity_id=?'.format( self.model_class._flex_table ), - (row[b'id'],) + (row['id'],) ) cols = dict(row) values = dict((k, v) for (k, v) in cols.items() if not k[:4] == 'flex') - flex_values = dict((row[b'key'], row[b'value']) for row in flex_rows) + flex_values = dict((row['key'], row['value']) for row in flex_rows) # Construct the Python object obj = self.model_class._awaken(self.db, values, flex_values) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 3f55d864e..867a47379 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -85,7 +85,7 @@ def _print_keys(query): returned row, with identation of 2 spaces. """ for row in query: - print_(' ' * 2 + row[b'key']) + print_(' ' * 2 + row['key']) def fields_func(lib, opts, args): diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 2ca3a6d23..bd51aea32 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -214,7 +214,7 @@ class ModelTest(unittest.TestCase): model.field_one = 123 model.store() row = self.db._connection().execute('select * from test').fetchone() - self.assertEqual(row[b'field_one'], 123) + self.assertEqual(row['field_one'], 123) def test_retrieve_by_id(self): model = TestModel1() diff --git a/test/test_library.py b/test/test_library.py index 17d526675..c9e007a94 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -63,7 +63,7 @@ class StoreTest(_common.LibTestCase): self.i.store() new_year = self.lib._connection().execute( 'select year from items where ' - 'title="the title"').fetchone()[b'year'] + 'title="the title"').fetchone()['year'] self.assertEqual(new_year, 1987) def test_store_only_writes_dirty_fields(self): @@ -72,7 +72,7 @@ class StoreTest(_common.LibTestCase): self.i.store() new_genre = self.lib._connection().execute( 'select genre from items where ' - 'title="the title"').fetchone()[b'genre'] + 'title="the title"').fetchone()['genre'] self.assertEqual(new_genre, original_genre) def test_store_clears_dirty_flags(self): @@ -91,7 +91,7 @@ class AddTest(_common.TestCase): self.lib.add(self.i) new_grouping = self.lib._connection().execute( 'select grouping from items ' - 'where composer="the composer"').fetchone()[b'grouping'] + 'where composer="the composer"').fetchone()['grouping'] self.assertEqual(new_grouping, self.i.grouping) def test_library_add_path_inserts_row(self): @@ -101,7 +101,7 @@ class AddTest(_common.TestCase): self.lib.add(i) new_grouping = self.lib._connection().execute( 'select grouping from items ' - 'where composer="the composer"').fetchone()[b'grouping'] + 'where composer="the composer"').fetchone()['grouping'] self.assertEqual(new_grouping, self.i.grouping) From 023ad9f48f730b98946364bfd30211f0f602fbb4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:29:57 -0400 Subject: [PATCH 0806/2280] remove b' from pipline sentinels --- beets/util/pipeline.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 4c55b53be..b5f777336 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -38,8 +38,8 @@ import Queue from threading import Thread, Lock import sys -BUBBLE = b'__PIPELINE_BUBBLE__' -POISON = b'__PIPELINE_POISON__' +BUBBLE = '__PIPELINE_BUBBLE__' +POISON = '__PIPELINE_POISON__' DEFAULT_QUEUE_SIZE = 16 From 7a1ca51c4951a249baae64d194aa66035c2d7c03 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:17:28 -0400 Subject: [PATCH 0807/2280] remove b' from platform checks --- beets/ui/__init__.py | 2 +- beets/util/__init__.py | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index a75036c33..291f93208 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -43,7 +43,7 @@ from beets.autotag import mb from beets.dbcore import query as db_query # On Windows platforms, use colorama to support "ANSI" terminal colors. -if sys.platform == b'win32': +if sys.platform == 'win32': try: import colorama except ImportError: diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 327b312fa..2e4c4de15 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -303,13 +303,13 @@ def _fsencoding(): UTF-8 (not MBCS). """ encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() - if encoding == b'mbcs': + if encoding == 'mbcs': # On Windows, a broken encoding known to Python as "MBCS" is # used for the filesystem. However, we only use the Unicode API # for Windows paths, so the encoding is actually immaterial so # we can avoid dealing with this nastiness. We arbitrarily # choose UTF-8. - encoding = b'utf8' + encoding = 'utf8' return encoding @@ -324,7 +324,7 @@ def bytestring_path(path): # On Windows, remove the magic prefix added by `syspath`. This makes # ``bytestring_path(syspath(X)) == X``, i.e., we can safely # round-trip through `syspath`. - if os.path.__name__ == b'ntpath' and path.startswith(WINDOWS_MAGIC_PREFIX): + if os.path.__name__ == 'ntpath' and path.startswith(WINDOWS_MAGIC_PREFIX): path = path[len(WINDOWS_MAGIC_PREFIX):] # Try to encode with default encodings, but fall back to UTF8. @@ -361,7 +361,7 @@ def syspath(path, prefix=True): *really* know what you're doing. """ # Don't do anything if we're not on windows - if os.path.__name__ != b'ntpath': + if os.path.__name__ != 'ntpath': return path if not isinstance(path, unicode): @@ -654,19 +654,19 @@ def cpu_count(): """ # Adapted from the soundconverter project: # https://github.com/kassoulet/soundconverter - if sys.platform == b'win32': + if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 - elif sys.platform == b'darwin': + elif sys.platform == 'darwin': try: num = int(command_output([b'/usr/sbin/sysctl', b'-n', b'hw.ncpu'])) except (ValueError, OSError, subprocess.CalledProcessError): num = 0 else: try: - num = os.sysconf(b'SC_NPROCESSORS_ONLN') + num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: @@ -693,7 +693,7 @@ def command_output(cmd, shell=False): cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - close_fds=platform.system() != b'Windows', + close_fds=platform.system() != 'Windows', shell=shell ) stdout, stderr = proc.communicate() From 28c0c95ed9a02618bd5bdc655a2b0230250e0ff6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:06:17 -0400 Subject: [PATCH 0808/2280] remove b' from struct (un)packing calls --- beets/mediafile.py | 6 +++--- beets/ui/__init__.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index c9489501e..a359a5b4f 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -181,7 +181,7 @@ def _unpack_asf_image(data): of exceptions (out-of-bounds, etc.). We should clean this up sometime so that the failure modes are well-defined. """ - type, size = struct.unpack_from(b' Date: Mon, 30 May 2016 21:19:15 -0400 Subject: [PATCH 0809/2280] use strings (not bytes) for flask responder names --- beetsplug/web/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 267022718..67d99db67 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -90,7 +90,7 @@ def resource(name): ) else: return flask.abort(404) - responder.__name__ = b'get_%s' % name.encode('utf8') + responder.__name__ = 'get_{0}'.format(name) return responder return make_responder @@ -104,7 +104,7 @@ def resource_query(name): json_generator(query_func(queries), root='results'), mimetype='application/json' ) - responder.__name__ = b'query_%s' % name.encode('utf8') + responder.__name__ = 'query_{0}'.format(name) return responder return make_responder @@ -119,7 +119,7 @@ def resource_list(name): json_generator(list_all(), root=name), mimetype='application/json' ) - responder.__name__ = b'all_%s' % name.encode('utf8') + responder.__name__ = 'all_{0}'.format(name) return responder return make_responder From 35c539b5a4d013e526294decf6ef3b61206b5900 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:29:30 -0400 Subject: [PATCH 0810/2280] remove b' from various web request respones --- test/test_art.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 1bc40a287..02d26f472 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -225,7 +225,7 @@ class AAOTest(UseThePlugin): match_querystring=True) def test_aao_scraper_finds_image(self): - body = b""" + body = """
@@ -238,7 +238,7 @@ class AAOTest(UseThePlugin): self.assertEqual(candidate.url, 'TARGET_URL') def test_aao_scraper_returns_no_result_when_no_image_present(self): - self.mock_response(self.AAO_URL, b'blah blah') + self.mock_response(self.AAO_URL, 'blah blah') album = _common.Bag(asin=self.ASIN) with self.assertRaises(StopIteration): next(self.source.get(album, self.extra)) @@ -260,21 +260,21 @@ class GoogleImageTest(UseThePlugin): def test_google_art_finds_image(self): album = _common.Bag(albumartist="some artist", album="some album") - json = b'{"items": [{"link": "url_to_the_image"}]}' + json = '{"items": [{"link": "url_to_the_image"}]}' self.mock_response(fetchart.GoogleImages.URL, json) candidate = next(self.source.get(album, self.extra)) self.assertEqual(candidate.url, 'url_to_the_image') def test_google_art_returns_no_result_when_error_received(self): album = _common.Bag(albumartist="some artist", album="some album") - json = b'{"error": {"errors": [{"reason": "some reason"}]}}' + json = '{"error": {"errors": [{"reason": "some reason"}]}}' self.mock_response(fetchart.GoogleImages.URL, json) with self.assertRaises(StopIteration): next(self.source.get(album, self.extra)) def test_google_art_returns_no_result_with_malformed_response(self): album = _common.Bag(albumartist="some artist", album="some album") - json = b"""bla blup""" + json = """bla blup""" self.mock_response(fetchart.GoogleImages.URL, json) with self.assertRaises(StopIteration): next(self.source.get(album, self.extra)) From 2a6e74bc27c4deba14f797bee00e4d297cd949fc Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 21:40:21 -0400 Subject: [PATCH 0811/2280] Remove bytes casting for non-path command args/opts --- beets/art.py | 6 +++--- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 8 ++++---- beetsplug/keyfinder.py | 2 +- beetsplug/replaygain.py | 18 +++++++++--------- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/beets/art.py b/beets/art.py index 7a65a2b80..b13de14d6 100644 --- a/beets/art.py +++ b/beets/art.py @@ -126,13 +126,13 @@ def check_art_similarity(log, item, imagepath, compare_threshold): # Converting images to grayscale tends to minimize the weight # of colors in the diff score. convert_proc = subprocess.Popen( - [b'convert', syspath(imagepath), syspath(art), - b'-colorspace', b'gray', b'MIFF:-'], + ['convert', syspath(imagepath), syspath(art), + '-colorspace', 'gray', 'MIFF:-'], stdout=subprocess.PIPE, close_fds=not is_windows, ) compare_proc = subprocess.Popen( - [b'compare', b'-metric', b'PHASH', b'-', b'null:'], + ['compare', '-metric', 'PHASH', '-', 'null:'], stdin=convert_proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 2e4c4de15..6ee24eb4d 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -661,7 +661,7 @@ def cpu_count(): num = 0 elif sys.platform == 'darwin': try: - num = int(command_output([b'/usr/sbin/sysctl', b'-n', b'hw.ncpu'])) + num = int(command_output(['/usr/sbin/sysctl', '-n', 'hw.ncpu'])) except (ValueError, OSError, subprocess.CalledProcessError): num = 0 else: diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 6970a7da1..50f6d7df1 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -91,8 +91,8 @@ def im_resize(maxwidth, path_in, path_out=None): # compatibility. try: util.command_output([ - b'convert', util.syspath(path_in, prefix=False), - b'-resize', b'{0}x^>'.format(maxwidth), + 'convert', util.syspath(path_in, prefix=False), + '-resize', '{0}x^>'.format(maxwidth), util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: @@ -119,7 +119,7 @@ def pil_getsize(path_in): def im_getsize(path_in): - cmd = [b'identify', b'-format', b'%w %h', + cmd = ['identify', '-format', '%w %h', util.syspath(path_in, prefix=False)] try: out = util.command_output(cmd) @@ -233,7 +233,7 @@ def get_im_version(): """Return Image Magick version or None if it is unavailable Try invoking ImageMagick's "convert".""" try: - out = util.command_output([b'identify', b'--version']) + out = util.command_output(['identify', '--version']) if 'imagemagick' in out.lower(): pattern = r".+ (\d+)\.(\d+)\.(\d+).*" diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index b6131a4b0..314a72028 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -59,7 +59,7 @@ class KeyFinderPlugin(BeetsPlugin): continue try: - output = util.command_output([bin, b'-f', + output = util.command_output([bin, '-f', util.syspath(item.path)]) except (subprocess.CalledProcessError, OSError) as exc: self._log.error(u'execution failed: {0}', exc) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 7bb2aa39a..6e69cb75a 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -102,9 +102,9 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = b'--' + bytes(config['method'].get(unicode)) + self.method = '--' + config['method'].get(unicode) - cmd = b'bs1770gain' + cmd = 'bs1770gain' try: call([cmd, self.method]) self.command = cmd @@ -195,7 +195,7 @@ class Bs1770gainBackend(Backend): # Construct shell command. cmd = [self.command] cmd = cmd + [self.method] - cmd = cmd + [b'-it'] + cmd = cmd + ['-it'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This @@ -267,9 +267,9 @@ class CommandBackend(Backend): ) else: # Check whether the program is in $PATH. - for cmd in (b'mp3gain', b'aacgain'): + for cmd in ('mp3gain', 'aacgain'): try: - call([cmd, b'-v']) + call([cmd, '-v']) self.command = cmd except OSError: pass @@ -334,14 +334,14 @@ class CommandBackend(Backend): # tag-writing; this turns the mp3gain/aacgain tool into a gain # calculator rather than a tag manipulator because we take care # of changing tags ourselves. - cmd = [self.command, b'-o', b'-s', b's'] + cmd = [self.command, '-o', '-s', 's'] if self.noclip: # Adjust to avoid clipping. - cmd = cmd + [b'-k'] + cmd = cmd + ['-k'] else: # Disable clipping warning. - cmd = cmd + [b'-c'] - cmd = cmd + [b'-d', bytes(self.gain_offset)] + cmd = cmd + ['-c'] + cmd = cmd + ['-d', self.gain_offset] cmd = cmd + [syspath(i.path) for i in items] self._log.debug(u'analyzing {0} files', len(items)) From e6ab231f722d7ed1129d1489685be204eb2fbec8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 22:00:42 -0400 Subject: [PATCH 0812/2280] Revert "Remove bytes casting for non-path command args/opts" This reverts commit 2a6e74bc27c4deba14f797bee00e4d297cd949fc. --- beets/art.py | 6 +++--- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 8 ++++---- beetsplug/keyfinder.py | 2 +- beetsplug/replaygain.py | 18 +++++++++--------- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/beets/art.py b/beets/art.py index b13de14d6..7a65a2b80 100644 --- a/beets/art.py +++ b/beets/art.py @@ -126,13 +126,13 @@ def check_art_similarity(log, item, imagepath, compare_threshold): # Converting images to grayscale tends to minimize the weight # of colors in the diff score. convert_proc = subprocess.Popen( - ['convert', syspath(imagepath), syspath(art), - '-colorspace', 'gray', 'MIFF:-'], + [b'convert', syspath(imagepath), syspath(art), + b'-colorspace', b'gray', b'MIFF:-'], stdout=subprocess.PIPE, close_fds=not is_windows, ) compare_proc = subprocess.Popen( - ['compare', '-metric', 'PHASH', '-', 'null:'], + [b'compare', b'-metric', b'PHASH', b'-', b'null:'], stdin=convert_proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 6ee24eb4d..2e4c4de15 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -661,7 +661,7 @@ def cpu_count(): num = 0 elif sys.platform == 'darwin': try: - num = int(command_output(['/usr/sbin/sysctl', '-n', 'hw.ncpu'])) + num = int(command_output([b'/usr/sbin/sysctl', b'-n', b'hw.ncpu'])) except (ValueError, OSError, subprocess.CalledProcessError): num = 0 else: diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 50f6d7df1..6970a7da1 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -91,8 +91,8 @@ def im_resize(maxwidth, path_in, path_out=None): # compatibility. try: util.command_output([ - 'convert', util.syspath(path_in, prefix=False), - '-resize', '{0}x^>'.format(maxwidth), + b'convert', util.syspath(path_in, prefix=False), + b'-resize', b'{0}x^>'.format(maxwidth), util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: @@ -119,7 +119,7 @@ def pil_getsize(path_in): def im_getsize(path_in): - cmd = ['identify', '-format', '%w %h', + cmd = [b'identify', b'-format', b'%w %h', util.syspath(path_in, prefix=False)] try: out = util.command_output(cmd) @@ -233,7 +233,7 @@ def get_im_version(): """Return Image Magick version or None if it is unavailable Try invoking ImageMagick's "convert".""" try: - out = util.command_output(['identify', '--version']) + out = util.command_output([b'identify', b'--version']) if 'imagemagick' in out.lower(): pattern = r".+ (\d+)\.(\d+)\.(\d+).*" diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index 314a72028..b6131a4b0 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -59,7 +59,7 @@ class KeyFinderPlugin(BeetsPlugin): continue try: - output = util.command_output([bin, '-f', + output = util.command_output([bin, b'-f', util.syspath(item.path)]) except (subprocess.CalledProcessError, OSError) as exc: self._log.error(u'execution failed: {0}', exc) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 6e69cb75a..7bb2aa39a 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -102,9 +102,9 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = '--' + config['method'].get(unicode) + self.method = b'--' + bytes(config['method'].get(unicode)) - cmd = 'bs1770gain' + cmd = b'bs1770gain' try: call([cmd, self.method]) self.command = cmd @@ -195,7 +195,7 @@ class Bs1770gainBackend(Backend): # Construct shell command. cmd = [self.command] cmd = cmd + [self.method] - cmd = cmd + ['-it'] + cmd = cmd + [b'-it'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This @@ -267,9 +267,9 @@ class CommandBackend(Backend): ) else: # Check whether the program is in $PATH. - for cmd in ('mp3gain', 'aacgain'): + for cmd in (b'mp3gain', b'aacgain'): try: - call([cmd, '-v']) + call([cmd, b'-v']) self.command = cmd except OSError: pass @@ -334,14 +334,14 @@ class CommandBackend(Backend): # tag-writing; this turns the mp3gain/aacgain tool into a gain # calculator rather than a tag manipulator because we take care # of changing tags ourselves. - cmd = [self.command, '-o', '-s', 's'] + cmd = [self.command, b'-o', b'-s', b's'] if self.noclip: # Adjust to avoid clipping. - cmd = cmd + ['-k'] + cmd = cmd + [b'-k'] else: # Disable clipping warning. - cmd = cmd + ['-c'] - cmd = cmd + ['-d', self.gain_offset] + cmd = cmd + [b'-c'] + cmd = cmd + [b'-d', bytes(self.gain_offset)] cmd = cmd + [syspath(i.path) for i in items] self._log.debug(u'analyzing {0} files', len(items)) From 330306bbe275344509888901525f4282ff9952c3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 30 May 2016 03:15:45 -0400 Subject: [PATCH 0813/2280] remove bytes casts from object/method resolution code --- beets/library.py | 2 +- beets/plugins.py | 11 +++++------ beets/ui/__init__.py | 2 +- beets/util/__init__.py | 2 +- beets/util/functemplate.py | 14 +++++++------- beetsplug/scrub.py | 32 ++++++++++++++++---------------- test/test_plugins.py | 4 ++-- 7 files changed, 33 insertions(+), 34 deletions(-) diff --git a/beets/library.py b/beets/library.py index ed1938671..99397013b 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1325,7 +1325,7 @@ class DefaultTemplateFunctions(object): additional context to the functions -- specifically, the Item being evaluated. """ - _prefix = b'tmpl_' + _prefix = 'tmpl_' def __init__(self, item=None, lib=None): """Parametrize the functions. If `item` or `lib` is None, then diff --git a/beets/plugins.py b/beets/plugins.py index ebc37796c..239f64fbb 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -28,7 +28,7 @@ import beets from beets import logging from beets import mediafile -PLUGIN_NAMESPACE = b'beetsplug' +PLUGIN_NAMESPACE = 'beetsplug' # Plugins using the Last.fm API can share the same API key. LASTFM_KEY = '2dc3914abf35f0d9c92d97d8f8e42b43' @@ -72,7 +72,7 @@ class BeetsPlugin(object): def __init__(self, name=None): """Perform one-time plugin setup. """ - self.name = name or self.__module__.decode('utf8').split('.')[-1] + self.name = name or self.__module__.split('.')[-1] self.config = beets.config[self.name] if not self.template_funcs: self.template_funcs = {} @@ -247,8 +247,7 @@ def load_plugins(names=()): BeetsPlugin subclasses desired. """ for name in names: - bname = name.encode('utf8') - modname = b'%s.%s' % (PLUGIN_NAMESPACE, bname) + modname = '{0}.{1}'.format(PLUGIN_NAMESPACE, name) try: try: namespace = __import__(modname, None, None) @@ -259,7 +258,7 @@ def load_plugins(names=()): else: raise else: - for obj in getattr(namespace, bname).__dict__.values(): + for obj in getattr(namespace, name).__dict__.values(): if isinstance(obj, type) and issubclass(obj, BeetsPlugin) \ and obj != BeetsPlugin and obj not in _classes: _classes.add(obj) @@ -313,7 +312,7 @@ def queries(): def types(model_cls): # Gives us `item_types` and `album_types` - attr_name = b'{0}_types'.format(model_cls.__name__.lower()) + attr_name = '{0}_types'.format(model_cls.__name__.lower()) types = {} for plugin in find_plugins(): plugin_types = getattr(plugin, attr_name, {}) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index e82f48434..797df44d3 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1132,7 +1132,7 @@ def _configure(options): # Add any additional config files specified with --config. This # special handling lets specified plugins get loaded before we # finish parsing the command line. - if getattr(options, b'config', None) is not None: + if getattr(options, 'config', None) is not None: config_path = options.config del options.config config.set_file(config_path) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 2e4c4de15..3cc270aee 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -713,7 +713,7 @@ def max_filename_length(path, limit=MAX_FILENAME_LENGTH): misreports its capacity). If it cannot be determined (e.g., on Windows), return `limit`. """ - if hasattr(os, b'statvfs'): + if hasattr(os, 'statvfs'): try: res = os.statvfs(path) except OSError: diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index d20ef3071..05f0892c2 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -43,8 +43,8 @@ GROUP_CLOSE = u'}' ARG_SEP = u',' ESCAPE_CHAR = u'$' -VARIABLE_PREFIX = b'__var_' -FUNCTION_PREFIX = b'__func_' +VARIABLE_PREFIX = '__var_' +FUNCTION_PREFIX = '__func_' class Environment(object): @@ -73,7 +73,7 @@ def ex_literal(val): value. """ if val is None: - return ast.Name(b'None', ast.Load()) + return ast.Name('None', ast.Load()) elif isinstance(val, NUMERIC_TYPES): return ast.Num(val) elif isinstance(val, bool): @@ -126,7 +126,7 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): mod = ast.Module([func_def]) ast.fix_missing_locations(mod) - prog = compile(mod, b'', b'exec') + prog = compile(mod, '', 'exec') # Debug: show bytecode. if debug: @@ -209,11 +209,11 @@ class Call(object): # Create a subexpression that joins the result components of # the arguments. arg_exprs.append(ex_call( - ast.Attribute(ex_literal(u''), b'join', ast.Load()), + ast.Attribute(ex_literal(u''), 'join', ast.Load()), [ex_call( - b'map', + 'map', [ - ex_rvalue(b'unicode'), + ex_rvalue('unicode'), ast.List(subexprs, ast.Load()), ] )], diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 66815ee31..ed4040d5b 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -26,21 +26,21 @@ from beets import config from beets import mediafile _MUTAGEN_FORMATS = { - b'asf': b'ASF', - b'apev2': b'APEv2File', - b'flac': b'FLAC', - b'id3': b'ID3FileType', - b'mp3': b'MP3', - b'mp4': b'MP4', - b'oggflac': b'OggFLAC', - b'oggspeex': b'OggSpeex', - b'oggtheora': b'OggTheora', - b'oggvorbis': b'OggVorbis', - b'oggopus': b'OggOpus', - b'trueaudio': b'TrueAudio', - b'wavpack': b'WavPack', - b'monkeysaudio': b'MonkeysAudio', - b'optimfrog': b'OptimFROG', + 'asf': 'ASF', + 'apev2': 'APEv2File', + 'flac': 'FLAC', + 'id3': 'ID3FileType', + 'mp3': 'MP3', + 'mp4': 'MP4', + 'oggflac': 'OggFLAC', + 'oggspeex': 'OggSpeex', + 'oggtheora': 'OggTheora', + 'oggvorbis': 'OggVorbis', + 'oggopus': 'OggOpus', + 'trueaudio': 'TrueAudio', + 'wavpack': 'WavPack', + 'monkeysaudio': 'MonkeysAudio', + 'optimfrog': 'OptimFROG', } @@ -78,7 +78,7 @@ class ScrubPlugin(BeetsPlugin): """ classes = [] for modname, clsname in _MUTAGEN_FORMATS.items(): - mod = __import__(b'mutagen.{0}'.format(modname), + mod = __import__('mutagen.{0}'.format(modname), fromlist=[clsname]) classes.append(getattr(mod, clsname)) return classes diff --git a/test/test_plugins.py b/test/test_plugins.py index c1a83ec21..421432909 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -323,9 +323,9 @@ class ListenersTest(unittest.TestCase, TestHelper): class DummyPlugin(plugins.BeetsPlugin): def __init__(self): super(DummyPlugin, self).__init__() - self.foo = Mock(__name__=b'foo') + self.foo = Mock(__name__='foo') self.register_listener('event_foo', self.foo) - self.bar = Mock(__name__=b'bar') + self.bar = Mock(__name__='bar') self.register_listener('event_bar', self.bar) d = DummyPlugin() From 81484529c97f77e2bdded31e8d80274719629f03 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 31 May 2016 00:12:26 -0400 Subject: [PATCH 0814/2280] remove b' from a few more stdlib calls --- beetsplug/convert.py | 4 ++-- beetsplug/fetchart.py | 4 ++-- beetsplug/lastgenre/__init__.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 6463d2a1f..de91604f5 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -185,8 +185,8 @@ class ConvertPlugin(BeetsPlugin): args = shlex.split(command) for i, arg in enumerate(args): args[i] = Template(arg).safe_substitute({ - b'source': source, - b'dest': dest, + 'source': source, + 'dest': dest, }) if pretend: diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a18e362e5..2cc362e4a 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -165,9 +165,9 @@ def _logged_get(log, *args, **kwargs): else: message = 'getting URL' - req = requests.Request(b'GET', *args, **req_kwargs) + req = requests.Request('GET', *args, **req_kwargs) with requests.Session() as s: - s.headers = {b'User-Agent': b'beets'} + s.headers = {'User-Agent': 'beets'} prepped = s.prepare_request(req) log.debug('{}: {}', message, prepped.url) return s.send(prepped, **send_kwargs) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index ad051c45c..a4b8f062b 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -126,7 +126,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): wl_filename = WHITELIST if wl_filename: wl_filename = normpath(wl_filename) - with open(wl_filename, b'r') as f: + with open(wl_filename, 'r') as f: for line in f: line = line.decode('utf8').strip().lower() if line and not line.startswith(u'#'): From 395877d903404d76702b7b3911165d5ce5e6add5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 30 May 2016 22:25:58 -0700 Subject: [PATCH 0815/2280] Remove the Echo Nest plugin :cry: (#1920) --- README.rst | 2 +- beetsplug/echonest.py | 500 -------------------------------- docs/changelog.rst | 4 + docs/plugins/acousticbrainz.rst | 3 +- docs/plugins/echonest.rst | 75 ----- docs/plugins/index.rst | 5 - setup.py | 2 - test/test_echonest.py | 193 ------------ 8 files changed, 6 insertions(+), 778 deletions(-) delete mode 100644 beetsplug/echonest.py delete mode 100644 docs/plugins/echonest.rst delete mode 100644 test/test_echonest.py diff --git a/README.rst b/README.rst index ad477beee..5e953c302 100644 --- a/README.rst +++ b/README.rst @@ -68,7 +68,7 @@ shockingly simple if you know a little Python. .. _acoustic fingerprints: http://beets.readthedocs.org/page/plugins/chroma.html .. _ReplayGain: http://beets.readthedocs.org/page/plugins/replaygain.html -.. _tempos: http://beets.readthedocs.org/page/plugins/echonest.html +.. _tempos: http://beets.readthedocs.org/page/plugins/acousticbrainz.html .. _genres: http://beets.readthedocs.org/page/plugins/lastgenre.html .. _album art: http://beets.readthedocs.org/page/plugins/fetchart.html .. _lyrics: http://beets.readthedocs.org/page/plugins/lyrics.html diff --git a/beetsplug/echonest.py b/beetsplug/echonest.py deleted file mode 100644 index a979972d8..000000000 --- a/beetsplug/echonest.py +++ /dev/null @@ -1,500 +0,0 @@ -# -*- coding: utf-8 -*- -# This file is part of beets. -# Copyright 2016, Adrian Sampson. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - -"""Fetch a variety of acoustic metrics from The Echo Nest. -""" -from __future__ import division, absolute_import, print_function - -import time -import socket -import os -import tempfile -from string import Template -import subprocess - -from beets import util, plugins, ui -from beets.dbcore import types -import pyechonest -import pyechonest.song -import pyechonest.track - -# If a request at the EchoNest fails, we want to retry the request RETRIES -# times and wait between retries for RETRY_INTERVAL seconds. -RETRIES = 10 -RETRY_INTERVAL = 10 - -DEVNULL = open(os.devnull, 'wb') -ALLOWED_FORMATS = ('MP3', 'OGG', 'AAC') -UPLOAD_MAX_SIZE = 50 * 1024 * 1024 - -# FIXME: use avconv? -CONVERT_COMMAND = u'ffmpeg -i $source -y -acodec libvorbis -vn -aq 2 $dest' -TRUNCATE_COMMAND = u'ffmpeg -t 300 -i $source'\ - u'-y -acodec libvorbis -vn -aq 2 $dest' - -# Maps attribute names from echonest to their field names in beets. -# The attributes are retrieved from a songs `audio_summary`. See: -# http://echonest.github.io/pyechonest/song.html#pyechonest.song.profile -ATTRIBUTES = { - 'energy': 'energy', - 'liveness': 'liveness', - 'speechiness': 'speechiness', - 'acousticness': 'acousticness', - 'danceability': 'danceability', - 'valence': 'valence', - 'tempo': 'bpm', -} - -# Types for the flexible fields added by `ATTRIBUTES` -FIELD_TYPES = { - 'energy': types.FLOAT, - 'liveness': types.FLOAT, - 'speechiness': types.FLOAT, - 'acousticness': types.FLOAT, - 'danceability': types.FLOAT, - 'valence': types.FLOAT, -} - -MUSICAL_SCALE = ['C', 'C#', 'D', 'D#', 'E' 'F', - 'F#', 'G', 'G#', 'A', 'A#', 'B'] - - -# We also use echonest_id (song_id) and echonest_fingerprint to speed up -# lookups. -ID_KEY = 'echonest_id' -FINGERPRINT_KEY = 'echonest_fingerprint' - - -def _splitstrip(string, delim=u','): - """Split string (at commas by default) and strip whitespace from the - pieces. - """ - return [s.strip() for s in string.split(delim)] - - -def diff(item1, item2): - """Score two Item objects according to the Echo Nest numerical - fields. - """ - result = 0.0 - for attr in ATTRIBUTES.values(): - if attr == 'bpm': - # BPM (tempo) is handled specially to normalize. - continue - - try: - result += abs( - float(item1.get(attr, None)) - - float(item2.get(attr, None)) - ) - except TypeError: - result += 1.0 - - try: - bpm1 = float(item1.get('bpm', None)) - bpm2 = float(item2.get('bpm', None)) - result += abs(bpm1 - bpm2) / max(bpm1, bpm2, 1) - except TypeError: - result += 1.0 - - return result - - -def similar(lib, src_item, threshold=0.15, fmt='${difference}: ${path}'): - for item in lib.items(): - if item.path != src_item.path: - d = diff(item, src_item) - if d < threshold: - s = fmt.replace('${difference}', '{:2.2f}'.format(d)) - ui.print_(format(item, s)) - - -class EchonestMetadataPlugin(plugins.BeetsPlugin): - - item_types = FIELD_TYPES - - def __init__(self): - super(EchonestMetadataPlugin, self).__init__() - self.config.add({ - 'auto': True, - 'apikey': u'NY2KTZHQ0QDSHBAP6', - 'upload': True, - 'convert': True, - 'truncate': True, - }) - self.config.add(ATTRIBUTES) - self.config['apikey'].redact = True - - pyechonest.config.ECHO_NEST_API_KEY = \ - self.config['apikey'].get(unicode) - - if self.config['auto']: - self.import_stages = [self.imported] - - def _echofun(self, func, **kwargs): - """Wrapper for requests to the EchoNest API. Will retry up to - RETRIES times and wait between retries for RETRY_INTERVAL - seconds. - """ - for i in range(RETRIES): - try: - result = func(**kwargs) - except pyechonest.util.EchoNestAPIError as e: - if e.code == 3: - # reached access limit per minute - self._log.debug(u'rate-limited on try {0}; waiting {1} ' - u'seconds', i + 1, RETRY_INTERVAL) - time.sleep(RETRY_INTERVAL) - elif e.code == 5: - # specified identifier does not exist - # no use in trying again. - self._log.debug(u'{0}', e) - return None - else: - self._log.error(u'{0}', e.args[0][0]) - return None - except (pyechonest.util.EchoNestIOError, socket.error) as e: - self._log.warn(u'IO error: {0}', e) - time.sleep(RETRY_INTERVAL) - except Exception as e: - # there was an error analyzing the track, status: error - self._log.debug(u'{0}', e) - return None - else: - break - else: - # If we exited the loop without breaking, then we used up all - # our allotted retries. - self._log.error(u'request failed repeatedly') - return None - return result - - def _pick_song(self, songs, item): - """Helper method to pick the best matching song from a list of songs - returned by the EchoNest. Compares artist, title and duration. If - the artist and title match and the duration difference is <= 1.0 - seconds, it's considered a match. - """ - if not songs: - self._log.debug(u'no songs found') - return - - pick = None - min_dist = item.length - for song in songs: - if song.artist_name.lower() == item.artist.lower() \ - and song.title.lower() == item.title.lower(): - dist = abs(item.length - song.audio_summary['duration']) - if dist < min_dist: - min_dist = dist - pick = song - if min_dist > 2.5: - return None - return pick - - def _flatten_song(self, song): - """Given an Echo Nest song object, return a flat dict containing - attributes we care about. If song is None, return None. - """ - if not song: - return - values = dict(song.audio_summary) - values['id'] = song.id - return values - - # "Profile" (ID-based) lookup. - - def profile(self, item): - """Do a lookup on the EchoNest by MusicBrainz ID. - """ - # Use an existing Echo Nest ID. - if ID_KEY in item: - enid = item[ID_KEY] - - # Look up the Echo Nest ID based on the MBID. - else: - if not item.mb_trackid: - self._log.debug(u'no ID available') - return - mbid = 'musicbrainz:track:{0}'.format(item.mb_trackid) - track = self._echofun(pyechonest.track.track_from_id, - identifier=mbid) - if not track: - self._log.debug(u'lookup by MBID failed') - return - enid = track.song_id - - # Use the Echo Nest ID to look up the song. - songs = self._echofun(pyechonest.song.profile, ids=enid, - buckets=['id:musicbrainz', 'audio_summary']) - return self._flatten_song(self._pick_song(songs, item)) - - # "Search" (metadata-based) lookup. - - def search(self, item): - """Search the item at the EchoNest by artist and title. - """ - songs = self._echofun(pyechonest.song.search, title=item.title, - results=100, artist=item.artist, - buckets=['id:musicbrainz', 'tracks', - 'audio_summary']) - return self._flatten_song(self._pick_song(songs, item)) - - # "Analyze" (upload the audio itself) method. - - def prepare_upload(self, item): - """Truncate and convert an item's audio file so it can be - uploaded to echonest. - - Return a ``(source, tmp)`` tuple where `source` is the path to - the file to be uploaded and `tmp` is a temporary file to be - deleted after the upload or `None`. - - If conversion or truncation fails, return `None`. - """ - source = item.path - tmp = None - if item.format not in ALLOWED_FORMATS: - if self.config['convert']: - tmp = source = self.convert(source) - if not tmp: - return - - if os.stat(source).st_size > UPLOAD_MAX_SIZE: - if self.config['truncate']: - source = self.truncate(source) - if tmp is not None: - util.remove(tmp) - tmp = source - else: - return - - if source: - return source, tmp - - def convert(self, source): - """Converts an item in an unsupported media format to ogg. Config - pending. - This is stolen from Jakob Schnitzers convert plugin. - """ - fd, dest = tempfile.mkstemp(b'.ogg') - os.close(fd) - - self._log.info(u'encoding {0} to {1}', - util.displayable_path(source), - util.displayable_path(dest)) - - opts = [] - for arg in CONVERT_COMMAND.split(): - arg = arg.encode('utf-8') - opts.append(Template(arg).substitute(source=source, dest=dest)) - - # Run the command. - try: - util.command_output(opts) - except (OSError, subprocess.CalledProcessError) as exc: - self._log.debug(u'encode failed: {0}', exc) - util.remove(dest) - return - - self._log.info(u'finished encoding {0}', util.displayable_path(source)) - return dest - - def truncate(self, source): - """Truncates an item to a size less than UPLOAD_MAX_SIZE.""" - fd, dest = tempfile.mkstemp(u'.ogg') - os.close(fd) - - self._log.info(u'truncating {0} to {1}', - util.displayable_path(source), - util.displayable_path(dest)) - - opts = [] - for arg in TRUNCATE_COMMAND.split(): - arg = arg.encode('utf-8') - opts.append(Template(arg).substitute(source=source, dest=dest)) - - # Run the command. - try: - util.command_output(opts) - except (OSError, subprocess.CalledProcessError) as exc: - self._log.debug(u'truncate failed: {0}', exc) - util.remove(dest) - return - - self._log.info(u'truncate encoding {0}', util.displayable_path(source)) - return dest - - def analyze(self, item): - """Upload the item to the EchoNest for analysis. May require to - convert the item to a supported media format. - """ - prepared = self.prepare_upload(item) - if not prepared: - self._log.debug(u'could not prepare file for upload') - return - - source, tmp = prepared - self._log.info(u'uploading file, please be patient') - track = self._echofun(pyechonest.track.track_from_filename, - filename=source) - if tmp is not None: - util.remove(tmp) - - if not track: - self._log.debug(u'failed to upload file') - return - - # Sometimes we have a track but no song. I guess this happens for - # new / unverified songs. We need to "extract" the audio_summary - # from the track object manually. I don't know why the - # pyechonest API handles tracks (merge audio_summary to __dict__) - # and songs (keep audio_summary in an extra attribute) - # differently. - # Maybe a patch for pyechonest could help? - - # First get the (limited) metadata from the track in case - # there's no associated song. - from_track = {} - for key in ATTRIBUTES: - try: - from_track[key] = getattr(track, key) - except AttributeError: - pass - from_track['duration'] = track.duration - - # Try to look up a song for the full metadata. - try: - song_id = track.song_id - except AttributeError: - return from_track - songs = self._echofun(pyechonest.song.profile, - ids=[song_id], track_ids=[track.id], - buckets=['audio_summary']) - if songs: - pick = self._pick_song(songs, item) - if pick: - return self._flatten_song(pick) - return from_track # Fall back to track metadata. - - # Shared top-level logic. - - def fetch_song(self, item): - """Try all methods to get a matching song object from the - EchoNest. If no method succeeds, return None. - """ - # There are four different ways to get a song. Each method is a - # callable that takes the Item as an argument. - methods = [self.profile, self.search] - if self.config['upload']: - methods.append(self.analyze) - - # Try each method in turn. - for method in methods: - song = method(item) - if song: - self._log.debug(u'got song through {0}: {1} [{2}]', - method.__name__, - item, - song.get('duration'), - ) - return song - - def apply_metadata(self, item, values, write=False): - """Copy the metadata from the dictionary of song information to - the item. - """ - # Update each field. - for k, v in values.iteritems(): - if k in ATTRIBUTES: - field = ATTRIBUTES[k] - self._log.debug(u'metadata: {0} = {1}', field, v) - if field == 'bpm': - item[field] = int(v) - else: - item[field] = v - if 'key' in values and 'mode' in values: - key = MUSICAL_SCALE[values['key'] - 1] - if values['mode'] == 0: # Minor key - key += 'm' - item['initial_key'] = key - if 'id' in values: - enid = values['id'] - self._log.debug(u'metadata: {0} = {1}', ID_KEY, enid) - item[ID_KEY] = enid - - # Write and save. - if write: - item.try_write() - item.store() - - # Automatic (on-import) metadata fetching. - - def imported(self, session, task): - """Import pipeline stage. - """ - for item in task.imported_items(): - song = self.fetch_song(item) - if song: - self.apply_metadata(item, song) - - # Explicit command invocation. - - def requires_update(self, item): - """Check if this item requires an update from the EchoNest (its - data is missing). - """ - for field in ATTRIBUTES.values(): - if not item.get(field): - return True - self._log.info(u'no update required') - return False - - def commands(self): - fetch_cmd = ui.Subcommand('echonest', - help=u'fetch metadata from The Echo Nest') - fetch_cmd.parser.add_option( - u'-f', u'--force', dest='force', - action='store_true', default=False, - help=u'(re-)download information from the EchoNest' - ) - - def fetch_func(lib, opts, args): - self.config.set_args(opts) - write = ui.should_write() - for item in lib.items(ui.decargs(args)): - self._log.info(u'{0}', item) - if self.config['force'] or self.requires_update(item): - song = self.fetch_song(item) - if song: - self.apply_metadata(item, song, write) - - fetch_cmd.func = fetch_func - - sim_cmd = ui.Subcommand('echosim', help=u'show related files') - sim_cmd.parser.add_option( - u'-t', u'--threshold', dest='threshold', action='store', - type='float', default=0.15, help=u'Set difference threshold' - ) - sim_cmd.parser.add_format_option() - - def sim_func(lib, opts, args): - self.config.set_args(opts) - for item in lib.items(ui.decargs(args)): - similar(lib, item, opts.threshold, opts.format) - - sim_cmd.func = sim_func - - return [fetch_cmd, sim_cmd] diff --git a/docs/changelog.rst b/docs/changelog.rst index 91166bd82..21d2fbe8d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -67,6 +67,10 @@ Other changes: * :doc:`/plugins/acousticbrainz`: AcousticBrainz lookups are now done over HTTPS. Thanks to :user:`Freso`. :bug:`2007` +* The :doc:`/plugins/echonest` has been removed. The API is `shutting down`_. + You might want to try the :doc:`/plugins/acousticbrainz` instead. + +.. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ 1.3.17 (February 7, 2016) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 9be9bede7..1e1b076f0 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -2,8 +2,7 @@ AcousticBrainz Plugin ===================== The ``acousticbrainz`` plugin gets acoustic-analysis information from the -`AcousticBrainz`_ project. The spirit is similar to the -:doc:`/plugins/echonest`. +`AcousticBrainz`_ project. .. _AcousticBrainz: http://acousticbrainz.org/ diff --git a/docs/plugins/echonest.rst b/docs/plugins/echonest.rst deleted file mode 100644 index 8ae7a11e6..000000000 --- a/docs/plugins/echonest.rst +++ /dev/null @@ -1,75 +0,0 @@ -Echo Nest Plugin -================ - -The ``echonest`` plugin fetches `acoustic attributes`_ from `the Echo Nest`_. -It automatically fills in the following attributes: - -- danceability -- energy -- liveness -- loudness -- speechiness -- bpm - -All attributes except ``bpm`` are stored in flexible attributes (i.e., not -in files' metadata). -See the Echo Nest's page on `acoustic attributes`_ for a detailed description. -(Their name for ``bpm`` is ``tempo``.) - -.. _the Echo Nest: http://the.echonest.com/ -.. _acoustic attributes: http://developer.echonest.com/acoustic-attributes.html - - -Installing Dependencies ------------------------ - -This plugin requires the pyechonest library in order to talk to the Echo Nest -API. At least version 8.0.1 is required. - -There are packages for most major linux distributions, you can download the -library from the Echo Nest, or you can install the library from `pip`_, -like so:: - - $ pip install pyechonest - -To transcode music for server-side analysis (optional, of course), install -the `ffmpeg`_ command-line tool. - -Finally, enable the ``echonest`` plugin in your configuration (see -:ref:`using-plugins`). - -.. _pip: http://pip.openplans.org/ -.. _FFmpeg: http://ffmpeg.org - - -Configuration -------------- - -To configure the plugin, make an ``echonest:`` section in your configuration -file. The available options are: - -- **apikey**: A custom EchoNest API key. You can `apply for your own`_ for - free from the EchoNest. - Default: beets' own Echo Nest API key. -- **auto**: Enable automatic metadata fetching during import. - Default: ``yes``. -- **upload**: Send files to the Echo Nest server if they can not be identified - by other means. - Default: ``yes``. -- **convert**: Because the Echo Nest server only supports a limited range of - file formats, the plugin automatically converts unsupported files to ``ogg``. - Default: ``yes``. -- **truncate**: Automatically truncate large files to their first 5 minutes - before uploading them to The Echo Nest server (as files with sizes greater - than 50MB are rejected). - Default: ``yes``. - -.. _apply for your own: http://developer.echonest.com/account/register - - -Running Manually ----------------- - -In addition to running automatically on import, the plugin can also be run -manually from the command line. Use the command ``beet echonest [QUERY]`` to -fetch acoustic attributes for albums matching a certain query. diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 0664f303f..39267a4b2 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -40,7 +40,6 @@ Each plugin has its own set of options that can be defined in a section bearing convert discogs duplicates - echonest edit embedart embyupdate @@ -100,8 +99,6 @@ Metadata * :doc:`acousticbrainz`: Fetch various AcousticBrainz metadata * :doc:`bpm`: Measure tempo using keystrokes. -* :doc:`echonest`: Automatically fetch `acoustic attributes`_ from - `the Echo Nest`_ (tempo, energy, danceability, ...). * :doc:`edit`: Edit metadata from a text editor. * :doc:`embedart`: Embed album art images into files' metadata. * :doc:`fetchart`: Fetch album cover art from various sources. @@ -122,8 +119,6 @@ Metadata * :doc:`scrub`: Clean extraneous metadata from music files. * :doc:`zero`: Nullify fields by pattern or unconditionally. -.. _Acoustic Attributes: http://developer.echonest.com/acoustic-attributes.html -.. _the Echo Nest: http://www.echonest.com .. _KeyFinder: http://www.ibrahimshaath.co.uk/keyfinder/ Path Formats diff --git a/setup.py b/setup.py index 3acd45e7c..4dcf5326f 100755 --- a/setup.py +++ b/setup.py @@ -100,7 +100,6 @@ setup( 'beautifulsoup4', 'flask', 'mock', - 'pyechonest', 'pylast', 'rarfile', 'responses', @@ -114,7 +113,6 @@ setup( 'fetchart': ['requests'], 'chroma': ['pyacoustid'], 'discogs': ['discogs-client>=2.1.0'], - 'echonest': ['pyechonest'], 'lastgenre': ['pylast'], 'mpdstats': ['python-mpd2'], 'web': ['flask', 'flask-cors'], diff --git a/test/test_echonest.py b/test/test_echonest.py deleted file mode 100644 index 8a8bbd780..000000000 --- a/test/test_echonest.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# This file is part of beets. -# Copyright 2016, Thomas Scholtes -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - - -from __future__ import division, absolute_import, print_function - -import os.path -from mock import Mock, patch - -from test._common import unittest, RSRC -from test.helper import TestHelper - -from beets.library import Item - - -class EchonestCliTest(unittest.TestCase, TestHelper): - def setUp(self): - try: - __import__('pyechonest') - except ImportError: - self.skipTest(u'pyechonest not available') - - self.setup_beets() - self.load_plugins('echonest') - # Prevent 'beet echonest' from writing files - self.config['import']['write'] = False - - def tearDown(self): - self.teardown_beets() - self.unload_plugins() - - @patch.object(Item, 'write') - @patch('pyechonest.song.profile') - @patch('pyechonest.track.track_from_id') - def test_mbid_profile(self, echonest_track, echonest_profile, item_write): - """Retrieve song info from MusicBrainz ID.""" - item = self.add_item(title='title', length=10, mb_trackid='1') - profile = self.profile(item, energy=0.5, tempo=120, key=2, mode=0) - echonest_profile.return_value = [profile] - echonest_track.return_value = Mock(song_id='echonestid') - - self.assertNotIn('energy', item) - self.assertNotEqual(item['bpm'], 120) - self.assertNotIn('initialkey', item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.5) - self.assertEqual(item['bpm'], 120) - self.assertEqual(item['initial_key'], 'C#m') - - @patch('pyechonest.track.track_from_id') - @patch('pyechonest.song.search') - def test_song_search(self, echonest_search, echonest_track): - item = self.add_item(title='title', length=10, mb_trackid='1') - echonest_search.return_value = [self.profile(item, energy=0.1)] - echonest_track.return_value = [] - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.1) - self.assertEqual(1, echonest_track.call_count) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - def test_analyze(self, echonest_track, echonest_search, echonest_profile): - item = self.add_item(title='title', length=10, - path=os.path.join(RSRC, 'min.mp3')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - self.assertEqual(1, echonest_search.call_count) - self.assertEqual(item.path, - echonest_track.call_args[1]['filename']) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'cp $source $dest') - def test_analyze_convert(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='FLAC', - path=os.path.join(RSRC, 'min.flac')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - # Assert uploaded file was converted - self.assertNotEqual(item.path, - echonest_track.call_args[1]['filename']) - - @patch('pyechonest.song.search') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'cp $source $dest') - def test_analyze_convert2(self, echonest_search): - self.add_item(format='FLAC', path=b'm\xc3\xacn.flac') - self.run_command('echonest') - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - @patch('beetsplug.echonest.CONVERT_COMMAND', 'false') - def test_analyze_convert_fail(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='FLAC', - path=os.path.join(RSRC, 'min.flac')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertNotIn('energy', item) - self.assertEqual(0, echonest_track.call_count) - - @patch('pyechonest.song.profile') - @patch('pyechonest.song.search') - @patch('pyechonest.track.track_from_filename') - # Force truncation - @patch('beetsplug.echonest.UPLOAD_MAX_SIZE', 0) - @patch('beetsplug.echonest.TRUNCATE_COMMAND', 'cp $source $dest') - def test_analyze_truncate(self, echonest_track, echonest_search, - echonest_profile): - item = self.add_item(title='title', length=10, format='MP3', - path=os.path.join(RSRC, 'min.mp3')) - echonest_search.return_value = [] - echonest_profile.return_value = [self.profile(item, energy=0.2)] - echonest_track.return_value = self.track(item) - - self.run_command('echonest') - item.load() - self.assertEqual(item['energy'], 0.2) - self.assertEqual(1, echonest_search.call_count) - self.assertNotEqual(item.path, - echonest_track.call_args[1]['filename']) - - def test_custom_field_range_query(self): - item = Item(liveness=2.2) - item.add(self.lib) - item = self.lib.items(u'liveness:2.2..3').get() - self.assertEqual(item['liveness'], 2.2) - - def profile(self, item, **values): - """Return a mock Echonest Profile object. - - The fields are set to match the item. Additional values are - passed to the `audio_summary` dictionary of the profile. - """ - audio_summary = {'duration': item.length} - audio_summary.update(values) - return Mock( - artist_name=item.artist, - title=item.title, - id='echonestid', - audio_summary=audio_summary - ) - - def track(self, item, **values): - """Return a mock Echonest Track object. - """ - values.update( - duration=item.length, - artist_name=item.artist, - title=item.title, - song_id='echonestid', - ) - return Mock(**values) - - -def suite(): - return unittest.TestLoader().loadTestsFromName(__name__) - -if __name__ == '__main__': - unittest.main(defaultTest='suite') From 2f4c7ee7a520302fdda57265af0b2e5a23f9004b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 30 May 2016 22:38:24 -0700 Subject: [PATCH 0816/2280] Simplify export plugins --- docs/plugins/export.rst | 97 +++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 51 deletions(-) diff --git a/docs/plugins/export.rst b/docs/plugins/export.rst index abf56c29c..4192f00c5 100644 --- a/docs/plugins/export.rst +++ b/docs/plugins/export.rst @@ -1,65 +1,32 @@ Export Plugin ============= -The ``export`` plugin lets you get data from the items and export the content to -a ``json`` file. +The ``export`` plugin lets you get data from the items and export the content +as `JSON`_. -Configuration -------------- -To configure the plugin, make a ``export:`` section in your configuration -file. The default options are:: +.. _JSON: http://www.json.org - export: - default_format: json - json: - formatting: - ensure_ascii: False - indent: 4 - separators: [',' , ': '] - sort_keys: true - -- **default_format**: Choose the format of the exported content. - Supports json only for now. - -Each format have their own options. - -The ``json`` formatting uses the `json`_ standard library options. -Using custom options overwrites all options at the same level. -The default options used here are: - -- **ensure_ascii**: All non-ASCII characters are escaped with `\uXXXX`, if true. - -- **indent**: The number of spaces for indentation. - -- **separators**: A ``(item_separator, dict_separator)`` tuple - -- **sort_keys**: Sorts the keys of the json - -.. _json: https://docs.python.org/2/library/json.html#basic-usage - -Using ------ - -Enable the ``export`` plugin (see :ref:`using-plugins` for help) and then add a -``export`` section to your :doc:`configuration file ` - -To use, you can enter a :doc:`query ` to get the data from -your library:: +Enable the ``export`` plugin (see :ref:`using-plugins` for help). Then, type ``beet export`` followed by a :doc:`query ` to get the data from +your library. For example, run this:: $ beet export beatles -If you just want to see specific properties you can use the -``--include-keys`` option to filter them. The argument is a -comma-separated list of simple glob patterns where ``*`` matches any -string. For example:: +to print a JSON file containing information about your Beatles tracks. - $ beet export -i 'title,mb*' beatles +Command-Line Options +-------------------- -Will only show the ``title`` property and all properties starting with -``mb``. You can add the ``-i`` option multiple times to the command -line. +The ``export`` command has these command-line options: -Additional command-line options include: +* ``--include-keys`` or ``-i``: Choose the properties to include in the output + data. The argument is a comma-separated list of simple glob patterns where + ``*`` matches any string. For example:: + + $ beet export -i 'title,mb*' beatles + + will include the ``title`` property and all properties starting with + ``mb``. You can add the ``-i`` option multiple times to the command + line. * ``--library`` or ``-l``: Show data from the library database instead of the files' tags. @@ -68,3 +35,31 @@ Additional command-line options include: the data in the console. * ``--append``: Appends the data to the file instead of writing. + +Configuration +------------- + +To configure the plugin, make a ``export:`` section in your configuration +file. Under the ``json`` key, these options are available: + +- **ensure_ascii**: Escape non-ASCII characters with `\uXXXX` entities. + +- **indent**: The number of spaces for indentation. + +- **separators**: A ``[item_separator, dict_separator]`` tuple. + +- **sort_keys**: Sorts the keys in JSON dictionaries. + +These options match the options from the `Python json module`_. + +.. _Python json module: https://docs.python.org/2/library/json.html#basic-usage + +The default options look like this:: + + export: + json: + formatting: + ensure_ascii: False + indent: 4 + separators: [',' , ': '] + sort_keys: true From da4bd64b182fdf860888a585055feb25359c3340 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 30 May 2016 22:40:30 -0700 Subject: [PATCH 0817/2280] Fix broken links to EchoNest docs --- docs/changelog.rst | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 21d2fbe8d..f76d68b27 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -67,7 +67,7 @@ Other changes: * :doc:`/plugins/acousticbrainz`: AcousticBrainz lookups are now done over HTTPS. Thanks to :user:`Freso`. :bug:`2007` -* The :doc:`/plugins/echonest` has been removed. The API is `shutting down`_. +* The ``echonest`` plugin has been removed. The API is `shutting down`_. You might want to try the :doc:`/plugins/acousticbrainz` instead. .. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ @@ -749,10 +749,10 @@ As usual, there are loads of little fixes and improvements: the field cannot be removed (i.e., when it does not exist, when it is a built-in field, or when it is a computed field). :bug:`1124` * The deprecated ``echonest_tempo`` plugin has been removed. Please use the - :doc:`/plugins/echonest` instead. -* :doc:`/plugins/echonest`: Fingerprint-based lookup has been removed in + ``echonest`` plugin instead. +* ``echonest`` plugin: Fingerprint-based lookup has been removed in accordance with `API changes`_. :bug:`1121` -* :doc:`/plugins/echonest`: Avoid a crash when the song has no duration +* ``echonest`` plugin: Avoid a crash when the song has no duration information. :bug:`896` * :doc:`/plugins/lyrics`: Avoid a crash when retrieving non-ASCII lyrics from the Google backend. :bug:`1135` :bug:`1136` @@ -886,7 +886,7 @@ And countless little improvements and fixes: * Fix an issue where modifying an album's field without actually changing it would not update the corresponding tracks to bring differing tracks back in line with the album. :bug:`856` -* :doc:`/plugins/echonest`: When communicating with the Echo Nest servers +* ``echonest`` plugin: When communicating with the Echo Nest servers fails repeatedly, log an error instead of exiting. :bug:`1096` * :doc:`/plugins/lyrics`: Avoid an error when the Google source returns a result without a title. Thanks to Alberto Leal. :bug:`1097` @@ -906,7 +906,7 @@ If you want to see all your songs in reverse chronological order, just type Flexible field types mean that some functionality that has previously only worked for built-in fields, like range queries, can now work with plugin- and -user-defined fields too. For starters, the :doc:`/plugins/echonest/` and +user-defined fields too. For starters, the ``echonest`` plugin and :doc:`/plugins/mpdstats` now mark the types of the fields they provide---so you can now say, for example, ``beet ls liveness:0.5..1.5`` for the Echo Nest "liveness" attribute. The :doc:`/plugins/types` makes it easy to specify field @@ -1150,14 +1150,14 @@ new in this release: * A new `initial_key` field is available in the database and files' tags. You can set the field manually using a command like ``beet modify initial_key=Am``. -* The :doc:`/plugins/echonest` sets the `initial_key` field if the data is +* The ``echonest`` plugin sets the `initial_key` field if the data is available. * A new :doc:`/plugins/keyfinder` runs a command-line tool to get the key from audio data and store it in the `initial_key` field. There are also many bug fixes and little enhancements: -* :doc:`/plugins/echonest`: Truncate files larger than 50MB before uploading for +* ``echonest`` plugin: Truncate files larger than 50MB before uploading for analysis. * :doc:`/plugins/fetchart`: Fix a crash when the server does not specify a content type. Thanks to Lee Reinhardt. @@ -1214,7 +1214,7 @@ New stuff: queries (combined with "or" logic). Album-level queries are also now possible and automatic playlist regeneration can now be disabled. Thanks to brilnius. -* :doc:`/plugins/echonest`: Echo Nest similarity now weights the tempo in +* ``echonest`` plugin: Echo Nest similarity now weights the tempo in better proportion to other metrics. Also, options were added to specify custom thresholds and output formats. Thanks to Adam M. * Added the :ref:`after_write ` plugin event. @@ -1235,7 +1235,7 @@ Fixes: legibility). * Fixed a regression that made it impossible to use the :ref:`modify-cmd` command to add new flexible fields. Thanks to brilnius. -* :doc:`/plugins/echonest`: Avoid crashing when the audio analysis fails. +* ``echonest`` plugin: Avoid crashing when the audio analysis fails. Thanks to Pedro Silva. * :doc:`/plugins/duplicates`: Fix checksumming command execution for files with quotation marks in their names. Thanks again to Pedro Silva. @@ -1311,7 +1311,7 @@ Unrelated new stuff: Other little fixes: -* :doc:`/plugins/echonest`: Tempo (BPM) is now always stored as an integer. +* ``echonest`` plugin: Tempo (BPM) is now always stored as an integer. Thanks to Heinz Wiesinger. * Fix Python 2.6 compatibility in some logging statements in :doc:`/plugins/chroma` and :doc:`/plugins/lastgenre`. @@ -1352,7 +1352,7 @@ Other little fixes: no changes are necessary. Thanks to brilnius. * :doc:`/plugins/fetchart`: When using the ``remote_priority`` config option, local image files are no longer completely ignored. -* :doc:`/plugins/echonest`: Fix an issue causing the plugin to appear twice in +* ``echonest`` plugin: Fix an issue causing the plugin to appear twice in the output of the ``beet version`` command. * :doc:`/plugins/lastgenre`: Fix an occasional crash when no tag weight was returned by Last.fm. @@ -1377,7 +1377,7 @@ into sync with your database. Thanks to Heinz Wiesinger. We added some plugins and overhauled some existing ones: -* The new :doc:`/plugins/echonest` plugin can fetch a wide range of `acoustic +* The new ``echonest`` plugin plugin can fetch a wide range of `acoustic attributes`_ from `The Echo Nest`_, including the "speechiness" and "liveness" of each track. The new plugin supersedes an older version (``echonest_tempo``) that only fetched the BPM field. Thanks to Pedro Silva From a440e44abdf0bf34d60a7a6d0fed194d71db11d2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 10:33:56 -0700 Subject: [PATCH 0818/2280] Proofread the changelog --- docs/changelog.rst | 75 ++++++++++++++++++++------------------- docs/reference/config.rst | 4 +++ 2 files changed, 42 insertions(+), 37 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f76d68b27..ccb6cf18d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,34 +4,40 @@ Changelog 1.3.18 (in development) ----------------------- +The ``echonest`` plugin has been removed in this version because the API it +used is `shutting down`_. You might want to try the +:doc:`/plugins/acousticbrainz` instead. + +.. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ + New features: -* :doc:`/plugins/convert`: A new `album_art_maxwidth` lets you resize album - art while copying it. +* :doc:`/plugins/convert`: A new `album_art_maxwidth` setting lets you resize + album art while copying it. * :doc:`/plugins/convert`: Make `extension` optional for conversion formats. + By default, the extension is the same as the name of the configured format. * :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option - lets you preserve mtime of files after each write. -* :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to a - configured `bing_lang_to` langage. Enabling translation require to register - for a Microsoft Azure Marketplace free account. Thanks to :user:`Kraymer`. + lets you preserve mtime of files even when beets updates their metadata. +* :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to + your native language using the Bing translation API. Thanks to + :user:`Kraymer`. * :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. - Albums are matched using the ``mb_releasegroupid`` tag. -* :doc:`/plugins/fetchart`: The ``enforce_ratio`` option was enhanced and now - allows specifying a certain deviation that a valid image may have from being - exactly square. +* :doc:`/plugins/fetchart`: The `enforce_ratio` option now lets you tolerate + images that are *almost* square but differ slightly from an exact 1:1 + aspect ratio. * :doc:`/plugins/fetchart`: The plugin can now optionally save the artwork's - source in a flexible field; for a usecase see the documentation. -* :doc:`/plugins/export`: A new plugin to export the data from queries to a - json format. Thanks to :user:`GuilhermeHideki`. -* :doc:`/reference/pathformat`: new functions: %first{} and %ifdef{} -* :doc:`/reference/config`: option ``terminal_encoding`` now works for some - inputs -* New :doc:`/plugins/hook` that allows commands to be executed when an event is - emitted by beets. :bug:`1561` :bug:`1603` -* :doc:`/reference/config`: New ``ignore_hidden`` configuration option allowing - platform-specific hidden files to be ignored on import. -* :doc:`/reference/config`: option ``ignore`` now includes ``lost+found`` - directory by default + source in an attribute in the database. +* The new :doc:`/plugins/export` can export data from beets' database as + JSON. Thanks to :user:`GuilhermeHideki`. +* There are two new functions for use in templates: ``%first`` and ``%ifdef``. + See :ref:`template-functions`. +* The :ref:`terminal_encoding` configuration option can now also override the + *input* encoding. (Previously, it only affected the encoding of the standard + *output* stream.) +* The new :doc:`/plugins/hook` lets you execute commands in response to beets + events. +* A new :ref:`ignore_hidden` configuration option lets you ignore files that + your OS marks as invisible. * :doc:`/plugins/web`: A new `values` endpoint lets you get the distinct values of a field. Thanks to :user:`sumpfralle`. :bug:`2010` @@ -39,38 +45,33 @@ New features: Fixes: -* Fix a problem with the :ref:`stats-cmd` in exact mode when filenames on - Windows use non-ASCII characters. :bug:`1891` +* Fix a problem with the :ref:`stats-cmd` command in exact mode when filenames + on Windows use non-ASCII characters. :bug:`1891` * Fix a crash when iTunes Sound Check tags contained invalid data. :bug:`1895` * :doc:`/plugins/mbcollection`: The plugin now redacts your MusicBrainz password in the ``beet config`` output. :bug:`1907` * :doc:`/plugins/scrub`: Fix an occasional problem where scrubbing on import - could undo the ``id3v23`` setting. :bug:`1903` + could undo the :ref:`id3v23` setting. :bug:`1903` * :doc:`/plugins/lyrics`: Add compatibility with some changes to the LyricsWiki page markup. :bug:`1912` :bug:`1909` -* :doc:`/plugins/lyrics`: Also fix retrieval from Musixmatch and the way we - guess the URL for lyrics. :bug:`1880` +* :doc:`/plugins/lyrics`: Fix retrieval from Musixmatch by improving the way + we guess the URL for lyrics on that service. :bug:`1880` * :doc:`/plugins/edit`: Fail gracefully when the configured text editor command can't be invoked. :bug:`1927` * :doc:`/plugins/fetchart`: Fix a crash in the Wikipedia backend on non-ASCII artist and album names. :bug:`1960` -* :doc:`/plugins/convert`: Change default `ogg` encoding quality from 2 to 3 - (to fit the default from the `oggenc(1)` manpage). :bug:`1982` +* :doc:`/plugins/convert`: Change the default `ogg` encoding quality from 2 to + 3 (to fit the default from the `oggenc(1)` manpage). :bug:`1982` * :doc:`/plugins/convert`: The `never_convert_lossy_files` option now considers AIFF a lossless format. :bug:`2005` * :doc:`/plugins/web`: A proper 404 error, instead of an internal exception, is returned when missing album art is requested. Thanks to :user:`sumpfralle`. :bug:`2011` -* Handle more float edge cases in ``safe_cast``. :bug:`2014` - -Other changes: - +* Tolerate more malformed floating-point numbers in metadata tags. :bug:`2014` +* The :ref:`ignore` configuration option now includes the ``lost+found`` + directory by default. * :doc:`/plugins/acousticbrainz`: AcousticBrainz lookups are now done over HTTPS. Thanks to :user:`Freso`. :bug:`2007` -* The ``echonest`` plugin has been removed. The API is `shutting down`_. - You might want to try the :doc:`/plugins/acousticbrainz` instead. - -.. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ 1.3.17 (February 7, 2016) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 20e9fa6bc..4ca54652a 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -83,6 +83,8 @@ have multiple paths, format them as a YAML list like so:: - /path/one - /path/two +.. _ignore: + ignore ~~~~~~ @@ -92,6 +94,8 @@ Information``, ``lost+found`` (i.e., beets ignores Unix-style hidden files, backup files, and directories that appears at the root of some Linux and Windows filesystems). +.. _ignore_hidden: + ignore_hidden ~~~~~~~~~~~~~ From dfe0730e223c9f657f6a2ae784255ed713a3b258 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 10:41:37 -0700 Subject: [PATCH 0819/2280] Reorganize changelog for release --- docs/changelog.rst | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ccb6cf18d..cac48caad 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,38 +4,47 @@ Changelog 1.3.18 (in development) ----------------------- +This update adds a new :doc:`/plugins/hook` that lets you integrate beets with +command-line tools and an :doc:`/plugins/export` that can dump data from the +beets database as JSON. You can also automatically translate lyrics using a +machine translation service. + The ``echonest`` plugin has been removed in this version because the API it used is `shutting down`_. You might want to try the :doc:`/plugins/acousticbrainz` instead. .. _shutting down: https://developer.spotify.com/news-stories/2016/03/29/api-improvements-update/ -New features: +Some of the larger new features: -* :doc:`/plugins/convert`: A new `album_art_maxwidth` setting lets you resize - album art while copying it. -* :doc:`/plugins/convert`: Make `extension` optional for conversion formats. - By default, the extension is the same as the name of the configured format. -* :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option - lets you preserve mtime of files even when beets updates their metadata. +* The new :doc:`/plugins/hook` lets you execute commands in response to beets + events. +* The new :doc:`/plugins/export` can export data from beets' database as + JSON. Thanks to :user:`GuilhermeHideki`. * :doc:`/plugins/lyrics`: The plugin can now translate the fetched lyrics to your native language using the Bing translation API. Thanks to :user:`Kraymer`. * :doc:`/plugins/fetchart`: Album art can now be fetched from `fanart.tv`_. + +Smaller new things: + +* There are two new functions available in templates: ``%first`` and ``%ifdef``. + See :ref:`template-functions`. +* :doc:`/plugins/convert`: A new `album_art_maxwidth` setting lets you resize + album art while copying it. +* :doc:`/plugins/convert`: The `extension` setting is now optional for + conversion formats. By default, the extension is the same as the name of the + configured format. +* :doc:`/plugins/importadded`: A new `preserve_write_mtimes` option + lets you preserve mtime of files even when beets updates their metadata. * :doc:`/plugins/fetchart`: The `enforce_ratio` option now lets you tolerate images that are *almost* square but differ slightly from an exact 1:1 aspect ratio. * :doc:`/plugins/fetchart`: The plugin can now optionally save the artwork's source in an attribute in the database. -* The new :doc:`/plugins/export` can export data from beets' database as - JSON. Thanks to :user:`GuilhermeHideki`. -* There are two new functions for use in templates: ``%first`` and ``%ifdef``. - See :ref:`template-functions`. * The :ref:`terminal_encoding` configuration option can now also override the *input* encoding. (Previously, it only affected the encoding of the standard *output* stream.) -* The new :doc:`/plugins/hook` lets you execute commands in response to beets - events. * A new :ref:`ignore_hidden` configuration option lets you ignore files that your OS marks as invisible. * :doc:`/plugins/web`: A new `values` endpoint lets you get the distinct values From 9bb6f1e893452549e300d2958a5b9deec50244d3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 10:42:56 -0700 Subject: [PATCH 0820/2280] Add date for 1.3.18 release --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index cac48caad..de67df09e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.18 (in development) ------------------------ +1.3.18 (May 31, 2016) +--------------------- This update adds a new :doc:`/plugins/hook` that lets you integrate beets with command-line tools and an :doc:`/plugins/export` that can dump data from the From 2b9f4773a901ee26920523642cca90c5123e8614 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 10:43:36 -0700 Subject: [PATCH 0821/2280] Version bump: 1.3.19 --- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index de67df09e..b0aa1e777 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.3.19 (in development) +----------------------- + +Changelog goes here! + + 1.3.18 (May 31, 2016) --------------------- diff --git a/docs/conf.py b/docs/conf.py index e6eae663a..33ef95398 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.3' -release = '1.3.18' +release = '1.3.19' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 4dcf5326f..30287fcf1 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.18', + version='1.3.19', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 33a4767eaf7aad62079cbb824eab808952a0171b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 11:48:29 -0700 Subject: [PATCH 0822/2280] Portable mock command for testing `convert` plugin --- beetsplug/convert.py | 7 ++++--- test/test_convert.py | 10 ++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index de91604f5..8c7f20e4d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -199,9 +199,10 @@ class ConvertPlugin(BeetsPlugin): # Something went wrong (probably Ctrl+C), remove temporary files self._log.info(u'Encoding {0} failed. Cleaning up...', util.displayable_path(source)) - self._log.debug(u'Command {0} exited with status {1}', - exc.cmd.decode('utf8', 'ignore'), - exc.returncode) + self._log.debug(u'Command {0} exited with status {1}: {2}', + args, + exc.returncode, + exc.output) util.remove(dest) util.prune_dirs(os.path.dirname(dest)) raise diff --git a/test/test_convert.py b/test/test_convert.py index 886614822..ef37466d7 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -35,10 +35,12 @@ class TestHelper(helper.TestHelper): if re.search('[^a-zA-Z0-9]', tag): raise ValueError(u"tag '{0}' must only contain letters and digits" .format(tag)) - # FIXME This is not portable. For windows we need to use our own - # python script that performs the same task. - return u'sh -c "cp \'$source\' \'$dest\'; ' \ - u'printf {0} >> \'$dest\'"'.format(tag) + + # A Python script that copies the file and appends a tag. + return u'python -c \'import sys; inf = open(sys.argv[1], "rb"); ' \ + u'outf = open(sys.argv[2], "wb"); ' \ + u'outf.write(inf.read()); ' \ + u'outf.write(b"{}")\' $source $dest'.format(tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From 1eb03a0de502de20c4a25beb4634fbf368d57151 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 13:12:32 -0700 Subject: [PATCH 0823/2280] Query tests: use normalized paths Match ordinary beets behavior by storing normalized paths in the database. This matters on Windows, where normalization adds backslashes and drive letters. --- test/helper.py | 9 +++++++++ test/test_query.py | 5 +++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/test/helper.py b/test/helper.py index 0f708b640..c10d8fad2 100644 --- a/test/helper.py +++ b/test/helper.py @@ -52,6 +52,7 @@ from beets import importer from beets.autotag.hooks import AlbumInfo, TrackInfo from beets.mediafile import MediaFile, Image from beets.ui import _arg_encoding +from beets import util # TODO Move AutotagMock here from test import _common @@ -306,11 +307,19 @@ class TestHelper(object): If `path` is not set in `values` it is set to `item.destination()`. """ + # When specifying a path, store it normalized (as beets does + # ordinarily). + if 'path' in values: + values['path'] = util.normpath(values['path']) + item = self.create_item(**values) item.add(self.lib) + + # Ensure every item has a path. if 'path' not in values: item['path'] = item.destination() item.store() + return item def add_item_fixture(self, **values): diff --git a/test/test_query.py b/test/test_query.py index 7a076a0ee..b9c87ff87 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -31,6 +31,7 @@ from beets.dbcore import types from beets.dbcore.query import (NoneQuery, ParsingError, InvalidQueryArgumentTypeError) from beets.library import Library, Item +from beets import util class TestHelper(helper.TestHelper): @@ -372,7 +373,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): super(PathQueryTest, self).setUp() # This is the item we'll try to match. - self.i.path = '/a/b/c.mp3' + self.i.path = util.normpath('/a/b/c.mp3') self.i.title = u'path item' self.i.album = u'path album' self.i.store() @@ -380,7 +381,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): # A second item for testing exclusion. i2 = _common.item() - i2.path = '/x/y/z.mp3' + i2.path = util.normpath('/x/y/z.mp3') i2.title = 'another item' i2.album = 'another album' self.lib.add(i2) From 5b2fb8dcdcb295adf494537302522573a76f78c7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 13:29:00 -0700 Subject: [PATCH 0824/2280] Queries with \ are path queries on Windows --- beets/library.py | 10 ++++++++-- docs/changelog.rst | 5 +++++ test/test_query.py | 3 +++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 99397013b..5ae0182e3 100644 --- a/beets/library.py +++ b/beets/library.py @@ -85,8 +85,14 @@ class PathQuery(dbcore.FieldQuery): colon = query_part.find(':') if colon != -1: query_part = query_part[:colon] - return (os.sep in query_part and - os.path.exists(syspath(normpath(query_part)))) + + # Test both `sep` and `altsep` (i.e., both slash and backslash on + # Windows). + return ( + (os.sep in query_part or + (os.altsep and os.altsep in query_part)) and + os.path.exists(syspath(normpath(query_part))) + ) def match(self, item): path = item.path if self.case_sensitive else item.path.lower() diff --git a/docs/changelog.rst b/docs/changelog.rst index b0aa1e777..dd4424332 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,11 @@ Changelog Changelog goes here! +Some fixes for Windows: + +* Queries are now detected as paths when they contain backslashes (in + addition to forward slashes). This only applies on Windows. + 1.3.18 (May 31, 2016) --------------------- diff --git a/test/test_query.py b/test/test_query.py index b9c87ff87..79bc11743 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -569,7 +569,10 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): @patch('beets.library.os') def test_path_sep_detection(self, mock_os): mock_os.sep = '/' + mock_os.altsep = None + mock_os.path.exists = lambda p: True is_path = beets.library.PathQuery.is_path_query + self.assertTrue(is_path('/foo/bar')) self.assertTrue(is_path('foo/bar')) self.assertTrue(is_path('foo/')) From 6ff7271ea0f78d28334ba0ede5d3d612add9ed24 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 13:46:44 -0700 Subject: [PATCH 0825/2280] Refactor convert command tests This lets us force the use of explicit path: queries on the command line instead of implicit path queries. This is more robust and works on Windows, which currently gets confused when path components start with `c:`. --- test/test_convert.py | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/test/test_convert.py b/test/test_convert.py index ef37466d7..f1baf3521 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -101,8 +101,22 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.assertTrue(os.path.isfile(item.path)) +class ConvertCommand(object): + """A mixin providing a utility method to run the `convert`command + in tests. + """ + def run_convert_path(self, path, *args): + """Run the `convert` command on a given path.""" + args = args + ('path:' + path,) + return self.run_command('convert', *args) + + def run_convert(self, *args): + """Run the `convert` command on `self.item`.""" + return self.run_convert_path(self.item.path, *args) + + @_common.slow_test() -class ConvertCliTest(unittest.TestCase, TestHelper): +class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): def setUp(self): self.setup_beets(disk=True) # Converter is threaded @@ -132,18 +146,18 @@ class ConvertCliTest(unittest.TestCase, TestHelper): def test_convert(self): with control_stdin('y'): - self.run_command('convert', self.item.path) + self.run_convert() converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFileTag(converted, 'mp3') def test_convert_with_auto_confirmation(self): - self.run_command('convert', '--yes', self.item.path) + self.run_convert('--yes') converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFileTag(converted, 'mp3') def test_rejecet_confirmation(self): with control_stdin('n'): - self.run_command('convert', self.item.path) + self.run_convert() converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFalse(os.path.isfile(converted)) @@ -151,14 +165,14 @@ class ConvertCliTest(unittest.TestCase, TestHelper): self.assertEqual(os.path.splitext(self.item.path)[1], '.ogg') with control_stdin('y'): - self.run_command('convert', '--keep-new', self.item.path) + self.run_convert('--keep-new') self.item.load() self.assertEqual(os.path.splitext(self.item.path)[1], '.mp3') def test_format_option(self): with control_stdin('y'): - self.run_command('convert', '--format', 'opus', self.item.path) + self.run_convert('--format', 'opus') converted = os.path.join(self.convert_dest, 'converted.ops') self.assertFileTag(converted, 'opus') @@ -171,7 +185,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper): image_data = f.read() with control_stdin('y'): - self.run_command('convert', self.item.path) + self.run_convert(self.item.path) converted = os.path.join(self.convert_dest, 'converted.mp3') mediafile = MediaFile(converted) self.assertEqual(mediafile.images[0].data, image_data) @@ -179,18 +193,18 @@ class ConvertCliTest(unittest.TestCase, TestHelper): def test_skip_existing(self): converted = os.path.join(self.convert_dest, 'converted.mp3') self.touch(converted, content='XXX') - self.run_command('convert', '--yes', self.item.path) + self.run_convert('--yes') with open(converted, 'r') as f: self.assertEqual(f.read(), 'XXX') def test_pretend(self): - self.run_command('convert', '--pretend', self.item.path) + self.run_convert('--pretend') converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFalse(os.path.exists(converted)) @_common.slow_test() -class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): +class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, ConvertCommand): """Test the effect of the `never_convert_lossy_files` option. """ @@ -216,7 +230,7 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): def test_transcode_from_lossles(self): [item] = self.add_item_fixtures(ext='flac') with control_stdin('y'): - self.run_command('convert', item.path) + self.run_convert_path(item.path) converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFileTag(converted, 'mp3') @@ -224,14 +238,14 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper): self.config['convert']['never_convert_lossy_files'] = False [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): - self.run_command('convert', item.path) + self.run_convert_path(item.path) converted = os.path.join(self.convert_dest, 'converted.mp3') self.assertFileTag(converted, 'mp3') def test_transcode_from_lossy_prevented(self): [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): - self.run_command('convert', item.path) + self.run_convert_path(item.path) converted = os.path.join(self.convert_dest, 'converted.ogg') self.assertNoFileTag(converted, 'mp3') From 17681145c2a78d34cd6fa733fc4762ff88b2f989 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 13:52:27 -0700 Subject: [PATCH 0826/2280] Fix a too-long line --- test/test_convert.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index f1baf3521..9c5166f42 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -204,7 +204,8 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): @_common.slow_test() -class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, ConvertCommand): +class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, + ConvertCommand): """Test the effect of the `never_convert_lossy_files` option. """ From 9e27c9e5ac54bd9161285b45646a4789b8a69952 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 15:19:34 -0700 Subject: [PATCH 0827/2280] Fix duplicated argument in test --- test/test_convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 9c5166f42..16f2f4799 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -185,7 +185,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): image_data = f.read() with control_stdin('y'): - self.run_convert(self.item.path) + self.run_convert() converted = os.path.join(self.convert_dest, 'converted.mp3') mediafile = MediaFile(converted) self.assertEqual(mediafile.images[0].data, image_data) From 469aee9848161e9d18adc1c93b5e820e66069e85 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 15:32:09 -0700 Subject: [PATCH 0828/2280] Correctly encode arguments in tests --- test/test_convert.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 16f2f4799..675c4be95 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -24,6 +24,7 @@ from test.helper import control_stdin from beets.mediafile import MediaFile from beets import util +from beets import ui class TestHelper(helper.TestHelper): @@ -107,7 +108,11 @@ class ConvertCommand(object): """ def run_convert_path(self, path, *args): """Run the `convert` command on a given path.""" - args = args + ('path:' + path,) + # The path is currently a filesystem bytestring. Convert it to + # an argument bytestring. + path = path.decode(util._fsencoding()).encode(ui._arg_encoding()) + + args = args + (b'path:' + path,) return self.run_command('convert', *args) def run_convert(self, *args): From 075cc10d1cf5390223b1f5ef43f6530a65394c24 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 15:34:17 -0700 Subject: [PATCH 0829/2280] Fix encoding for Windows path resolution --- beets/util/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 3cc270aee..e169b1f72 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -798,6 +798,7 @@ def _windows_long_path_name(short_path): """ if not isinstance(short_path, unicode): short_path = unicode(short_path) + short_path = short_path.decode(_fsencoding()) import ctypes buf = ctypes.create_unicode_buffer(260) From 2a9be125032bbb5289aca6d1dd2a4c93b181cf45 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 15:35:59 -0700 Subject: [PATCH 0830/2280] Fix partial commit of change --- beets/util/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index e169b1f72..e92f1a83b 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -797,7 +797,6 @@ def _windows_long_path_name(short_path): long path given a short filename. """ if not isinstance(short_path, unicode): - short_path = unicode(short_path) short_path = short_path.decode(_fsencoding()) import ctypes From 40369c6ab2d7058467572a627507456215c213c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 17:50:54 -0700 Subject: [PATCH 0831/2280] Move convert stub script to its own file --- test/rsrc/convert_stub.py | 20 ++++++++++++++++++++ test/test_convert.py | 6 ++---- 2 files changed, 22 insertions(+), 4 deletions(-) create mode 100755 test/rsrc/convert_stub.py diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py new file mode 100755 index 000000000..0f2dadd92 --- /dev/null +++ b/test/rsrc/convert_stub.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python + +"""A tiny tool used to test the `convert` plugin. It copies a file and appends +a specified text tag. +""" + +import sys + + +def convert(in_file, out_file, tag): + """Copy `in_file` to `out_file` and append the string `tag`. + """ + with open(out_file, 'wb') as out_f: + with open(in_file, 'rb') as in_f: + out_f.write(in_f.read()) + out_f.write(tag) + + +if __name__ == '__main__': + convert(sys.argv[1], sys.argv[2], sys.argv[3]) diff --git a/test/test_convert.py b/test/test_convert.py index 675c4be95..ac3a50c77 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -38,10 +38,8 @@ class TestHelper(helper.TestHelper): .format(tag)) # A Python script that copies the file and appends a tag. - return u'python -c \'import sys; inf = open(sys.argv[1], "rb"); ' \ - u'outf = open(sys.argv[2], "wb"); ' \ - u'outf.write(inf.read()); ' \ - u'outf.write(b"{}")\' $source $dest'.format(tag) + stub = os.path.join(_common.RSRC, 'convert_stub.py') + return u'python {} $source $dest {}'.format(stub, tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From fc3f64de95554a66e2ec64804acf9c6032dd7e7b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 17:52:32 -0700 Subject: [PATCH 0832/2280] Convert stub: Python 3 compatibility Important for systems where `python` is 3.x, like Arch, even when beets itself is running on Python 2. --- test/rsrc/convert_stub.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 0f2dadd92..aa0d2ea72 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -10,6 +10,10 @@ import sys def convert(in_file, out_file, tag): """Copy `in_file` to `out_file` and append the string `tag`. """ + # On Python 3, encode the tag argument as bytes. + if not isinstance(tag, bytes): + tag = tag.encode('utf8') + with open(out_file, 'wb') as out_f: with open(in_file, 'rb') as in_f: out_f.write(in_f.read()) From f96aa24a790a351cbd6cb2fbd8715676e3abe423 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 17:55:12 -0700 Subject: [PATCH 0833/2280] Convert stub: use __future__ imports Even tiny stubs can't escape the wrath of flake8! --- test/rsrc/convert_stub.py | 1 + test/test_convert.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index aa0d2ea72..747493134 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -4,6 +4,7 @@ a specified text tag. """ +from __future__ import division, absolute_import, print_function import sys diff --git a/test/test_convert.py b/test/test_convert.py index ac3a50c77..9e3c106bd 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -39,7 +39,7 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, 'convert_stub.py') - return u'python {} $source $dest {}'.format(stub, tag) + return u"python '{}' $source $dest {}".format(stub, tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From e8c8f9fb1403ada512fb2564854cb7556d180058 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 18:08:26 -0700 Subject: [PATCH 0834/2280] Possibly make the convert stub work on Windows --- test/rsrc/convert_stub.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 747493134..551f86077 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -6,6 +6,7 @@ a specified text tag. from __future__ import division, absolute_import, print_function import sys +import platform def convert(in_file, out_file, tag): @@ -15,6 +16,12 @@ def convert(in_file, out_file, tag): if not isinstance(tag, bytes): tag = tag.encode('utf8') + # On Windows, use Unicode paths. (The test harness gives them to us + # as UTF-8 bytes.) + if platform.system() == 'Windows': + in_file = in_file.decode('utf8') + out_file = in_file.decode('utf8') + with open(out_file, 'wb') as out_f: with open(in_file, 'rb') as in_f: out_f.write(in_f.read()) From 9f8b81a5ad1b91f72ddd14ef8aa16c413ce2bb42 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 31 May 2016 18:13:50 -0700 Subject: [PATCH 0835/2280] Fix variable reference in stub --- test/rsrc/convert_stub.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 551f86077..9fb044b4f 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -20,7 +20,7 @@ def convert(in_file, out_file, tag): # as UTF-8 bytes.) if platform.system() == 'Windows': in_file = in_file.decode('utf8') - out_file = in_file.decode('utf8') + out_file = out_file.decode('utf8') with open(out_file, 'wb') as out_f: with open(in_file, 'rb') as in_f: From 8dcd50b18f8106708e071a498b5ed602c281e66e Mon Sep 17 00:00:00 2001 From: pszxzsd Date: Wed, 1 Jun 2016 20:00:08 +0200 Subject: [PATCH 0836/2280] make bs1770gain calculate sample peak instead of true peak --- beetsplug/replaygain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 7bb2aa39a..2e215938d 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -195,7 +195,7 @@ class Bs1770gainBackend(Backend): # Construct shell command. cmd = [self.command] cmd = cmd + [self.method] - cmd = cmd + [b'-it'] + cmd = cmd + [b'-p'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This From 7744c6bd90099013d36bd3efdd596a3529d7cd70 Mon Sep 17 00:00:00 2001 From: pszxzsd Date: Thu, 2 Jun 2016 11:03:59 +0200 Subject: [PATCH 0837/2280] add changelog entry for bs1770gain peak fix --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index dd4424332..6c7c04496 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -11,6 +11,12 @@ Some fixes for Windows: * Queries are now detected as paths when they contain backslashes (in addition to forward slashes). This only applies on Windows. +Fixes: + +* :doc:`/plugins/replaygain`: The ``bs1770gain`` backend now correctly + calculates sample peak instead of true peak. This comes with a major + speed increase. :bug:`2031` + 1.3.18 (May 31, 2016) --------------------- From e71e17d92405cac86e889eda9a685cee27b2af73 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 10:17:02 -0700 Subject: [PATCH 0838/2280] Open image file as binary in tests --- log.txt | Bin 0 -> 621318 bytes test/test_convert.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 log.txt diff --git a/log.txt b/log.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a85a7db5fdefe0dda854b3be6667ef1acfa18ee GIT binary patch literal 621318 zcmezWFOMOgp_n0+p@boop_rkBp_oB|!HPiv&W~qEWJqMlXNYGgW=LizVn}2tU`S;s zVu)u*W5{I4V@P2rW{79VWXNSmWJqU7Wl&(yfa}$Rvp}X4F_bXqF*q_fGWauuKyA}x zP+-slLj{I>hHM621}+9ih7tw^h8(czsSH*Oh71Y}$qX3`i3~+x9!QNgg8~CKm+LZ= zF(@z?G1xJvf%VlueFAb<4nsaeIs?c}6$~X{n?R=2F%W_v`xF=;5TwJIArb7abcTF} zB8Ex^Plh~(G=_Yr3Wz!w2?|L+hJ1z+hG1~GB{O7#!!4B|1suwVumXh;W;jE_27j1Y zF$6P|Fcg8qE1dxpqR|Yo3_1)73_%R347p(2QyE+tDj1R(QW**uN*FR3@)`2LApmnH z$X{*@r3^U?ISiEyfefV#iQpIj#WBdOt_(#CMPUDWGNeFLh#xo{G8xJkQW=~X@)>f$ zX#kWW5UL?z2O?qV3%fr->8S{u3QHM^81ler3KYNb3?R{Bu**sq;u*>rG8j@B@)+X5 zv5%bY;u#8{YC-a#6od#{P@F?jH^_EE=@8^vSXxB58sd&jhAM_saC%PzyCD@Ero{}! z;M7@3MCu3G?gkD?M}{1RB!*IkT&%ePpDRE)Fqr`q9w5Jh(q0kR9iY$xrA<)$LPCge zZls@kK(2|Q#fZ_&{QXu788Z>8v+yN?|a=`7*B(P{ULp%d020?KQ zYL^p=$ANJf$X8WFr88Q&4^+B?dH|q!gtWjxsSH#`4XQng87jf!F`yniEDwQtdxUFT7jQ2hl-5E1 z1C?|s;Ql#ilmgTmBfj)T?XeN^zbkYc1k%R~f{qU4lWlhe!Fq|hHiAaBKqXi{cqAbc z?0!(+57ZXSV*r&Ept=uKSAbFlC>@tDBr;?}>sgRa$Y=nf>?0InZVbT;jtrnuhxj-F z#c3&Y3S5%pcFz2*I-LskTMoDl9vuHDdHKD!R; z0E;tF4}!Q6VK;_E2ADY^3}GbnHZffQ3JuT*Ca5h8>S;qpsu6Ahjc()buTax9pqM~z zZ-7z_Xp9b2LxRRyL2-l_(FC~_GR6u~18PS>Mpp@!`Sf>nCU_(x9^8V;0grzdG2}9U z(m%xY#o!SH&`2(5?44F&4k{7Kz`Y+(P6XAHmEdu9h#Szu9@L&9oD)DjBTz3K)MtgH zVB$+>P)U^vE~`oyaJi%aT(b~vrMbb!1ITd+Xm$cL-vP@1pppWVOCco~={eM$As;+< z0y2wwZlPc97)bY1GoMiE4^aI88rcK&|3Twpp!PawTmaP9h4joa!8HlKQWDhm0L^EC zat3HN4>pJ4!T`|=D$7A77x8%p;VRtj0oD2-7lTSrP^k&3lS{y}g1GbZK)G~a+y)wR z%4Yzz`*Og2Lr{K)#0aPb1!||IF@Q!G@wL{dA7Y?V8P+}mwOk=?gQXezrZZ4o0ZVJ3 zk_^-{0+oy~*U&R1L3&o8+7nb`W`bt{LA4iXem$81lppiJVxWF=5qM4>R}D)2I78$@ zP|C??0NDU)Pl3jTL8F|Y{tbOoQ3(TRq!K-}K=lVG9uvX+d3wekXsi%2a|=p8p!yUw z?oi88P!A0>?+y|LjnCj~4}roOxpXaH0L?#Cg8R^*k{i_X1epPv;msqVr3@O^0J#;G z)Y)Eo1jpH#Ws3OgHkT2W(DcX!PAq+l`@I1 z=Rr0gat)$>0+lVG5oFK`6HrKeO-_O?&X0-mqE6J<{Ut+VtU2|#08*nO2nuLX!R0ki~*ERK`X;RD{(Tw z?L|l}2GWCX6%*y904ObhRuY0n)Lk$EBB(!+ zPSY9_RCa@A{t#&vxmPea>_@GU5qXN1r8}rCQvz-ug5raIwF)A24pixd>;gnsgK{pt z@+qPR2wIH`;$?$po)F{M$ZiCU>w`vxA@Kxi3&exh?}B0w#Dk30mxI?9=P{6yn;y0& zL2ZeVKl%!>2b3!d;j8{Z{RU!vNe!DTz%%ajvk|!#rJt>!Ib6`V4QQtZeM1=3V+NJD zpgk(YjU!SXtDuo3kWWb|)v0SMXbb@~mImtIfZA-JaRmCsHnRUgr3$DIM*PSh`5^&m zD}wqpko9-8_c5r>1dVwRUyhUSJJ8$;Xm1e&1-jlP0v5qkI*lyA!!Kx3bv zz6m|!w3MNM0oDVeeF_4FC!{?F8W#f9MUWDjSerrXz(BP&@hw2aSS0coB51q{lutq9 zxS*8_p!HS6x*>oe2fVTrWHKm6RFW_{pA6OsYM+4Gv5h(f=UBWOo3YXpp_w@@ikBh zOKgl$$4yD#ee0m!F=%ZUsB{ADCI`(q#Y6XYf@*fqSU@TRXoYkJcn3OhEoJJs5VSS| zl-@!8P0*MIC{=@El)m8vYE{8jiGXq)XvPG&9ZP)qO`T9dEe$}ubkMj5XtgVS!v!>Z z4@xPZ9m}8<;qlLO6<7*y+n(k>#DK)b-o zp{GWG=z+;&pwS+X+dwr4s5hJpZds%6lLM6upp~rTx4Nm5_8}`bZn`hv8k6u|o@Kx@Asr2}Yp703)wX%6W>Ku#f20G}8HI~j-iu7KFCz@W~M z2A&VhWzYrhz*c8aU;yog1od(f89=)NvAM^SAq{#alma+6fND)pNe3D+gscQn{rE?Ur-4QS6FC>*ev?+iY92o%a7^Fez&Ky!p3y`WYxXru@d!i4mK z=D{k!HiBk5LGA(VEd%)q6lb9H0~xE<1)oI$lLNI`6u>)bAahEv9jVxCgM%tNcRF#d-`*45bX9)CTIY zLPoZbG6_`vBf<%mQ$Vo=Y76IqPhvyZ3M$J$W4oZ0Rv;I^QU|0o0_81avq1S3l#4;` z0nI>wbb$I;)N-2wbmtz#c2IcS36a-q^1xiC8_k%`RAaiq|kq*%L1fZ5G z$amPseqiIZp#CewOvIUYdf+wspwV2AEaZd*P#yq{fDu10focP&1ObHvDAos?i$EhD zpfCi@u7cL;XX5PHp!x~Kqjspl;u8`lusA?=VIp`J3+RkOQ0@V>D?zKyLF1I5vT>lo zmaw~FDj+Epl=ndATMoQ?L1iYWZ47Ejg4Q2_VighYpnL`?6$i?t#S9q?`3#`BQ&0;F zG>-=Ae}Y0Yo&i+mL&kfNU5%?&Mpgq!U(`;$q`MV4WkYI4Q2Ne+p58j}VLo_67`w}m z!*ig^GDK=1?AE~(_mEryYVUyBHTd%qOckuggz=rhC(e>uSHg71gHK|CjMRhX<#3W?Z~(2p1NEjrwJ4!B9xPQ+nmRzWPZk4c-6+WB zfldj<43Lw8ATzR{z6K};Kz$hcq(sm;ETA!QP`ZPK1uUdNbu+Q90G&YrGY8bt&I6wh z2{M)V(gW2kp!OB0-41Hkfbs|^eS-S#sAUBx+z72XK-HngKn=G-`m>-FNg&ffr9Nn< zENCAWC?A8yu|cCkpcWUQo&qei^%(pZQlX)S8iGFH^WZ__ZEoPx&p>M}h!0ibTnZY4 z#Meq0EUpC24uEnn$UUIZM^e%#ZNeASk_D|Cf|O;T)8s*;5TG&?G@k--V-W+SWsW;7 zfJ_0E%btCBn@&cWDWvUZiCLN0L|J^5{AU*O6)EIjjDonPJ!B@pfzIy?Jnf9WAKC)E>{&p zSB;TVRv^+Dxp9c>s=*wOm~NwYxS{qqK%-I>;L}Y&sU5T)IR|`~39fvY1U*kNl|hdI za$^T1WfC86==Ot31<*PakV`=8$Z+>UQW)rAJ7|YYCHO8Id~F44y9BiN2{iHws(;hK zyLbmGOh7FG(5g$w=s!JD1ZeIRWE*HtENEmup8*sKh%p0Dy99KqWhnz_G!J+Af-6oy zEw>Z~U+^tW1<+Y$;?pZ3*MZJ-1odS>_a%Tr3*`2};bLmVBxT_T+EV~JwHee;1huUb z89-}SK;<)uN3p6JQTU9_ziRcSnDGf3a zG=>0beG#9|Kr@-3wi@!dD`@p7Xl*FyyaPn}2wGzUDm6i;af5oIpwW9!9|N==2h?uC z*CRtML#gfFT<|#_Aisn5F@R24fs8sL*Db`Bs?>HHrc01x8q{J2?N!QUz&-ax+pq)e z3;>mYs9^63`4v+BfyO{VIR%uzVJ$IG4+J!7lnK5I4OITp&lRAOr2;(e0dm1W z*$e9XgL=lGo*JlEOv~6uj|bEch-WBc0Ih)orAN@tX?leSWb6eL2B7moK=mXjg@9@( zVq3`M>CH8*H=9w;6_H590=M$Z%qT2TR-uc2ic0FCN^$~jOhgTfe+D?x2J z@>}ENggXRJ&(%rb5hhrliW)f& z)d8waKyxXub{cX>f_enk)=GiKCPDQJ#5ExIf!1z=#^Y!cE}*#qP|X4I z8EB3G(w_#6#8ao-!t^D`PoVGx`4X}=5O&f%$fuAQ9Z(#gmg}_fJ+fOsc^6irgV>;Q zg;rqz^Ear61*$V}&nBU^VgtZ;w1WEk!O-&{LG2&><8hcV018=9=?N>fK&@%WiXhOO zA*lBh?gW({pcEYs-o;4&_yqM_A*YamcEEsg zG-#z5q)s3%-%uxA4P+RA$}mXJW3Z)aP-=#i>Y#Fk+%g6cN7(vjn7JI)UQnJVXN(fR zt;lQL5p^xH&7e^&Sj`S;jeu$z;_Fay><6_zVJ9#kN-|I%1+ zLFnNk$mlyHEa+`F=6Eq|?FX^_Ny^eAsGS392ZHtmf<~G^rytNe46wNYRP%v)!3LlP%eb{9#l4h+MmRx#31mU zmykKiVg^s}3^HUU2xJPj78drl4rH_oq7#%hLGc6XyAT&5v~mS(l>(?Y1@aHEZ5~>= z2UM4Xb}WH*=MghAM=f`NQYk34g665|8zYduEGV58Luc9Ooiai5i=eUJdZi` zx(U=%gSiIMz5u1%fpigaUkSv9jL3mPij*=9Hd01uFAm$x!a%tNRLg*B8&dlv)Cvp4 zDjLuT|3HNTs8#{3q#dYGAisY|Sv-KwErINSQa~GV)MZFy&;;++2jyT;+XQlI08BL^ z7lC%egL+kwdXV6SOXjB^1mnmjI-;M6d5X2C~;Li{Q-Va5t{gBZY$etb0u6@`@ z5G8JLWdMzNg4#ErIv!NJfl?%2vjeF#tadA^+EG$kn-*g^J#;sVq@0iCu0YS)5X2Wl^X#%@8QxuDV?#0Qnapp|qWH-gSv0ns2| zC@_H58iD4tbfIJ9p!F!A84Hl_K_P;C)&*(|Vul(u-33}>ih7?i=sXC}2|gfy<93w` z1L!1%JO;?TJ#q@pV*su3%z&;2#Gg8e^BW}XgXYIU=?By@0);7PH4$Q+87R%b(kLi( zfLsSlWuVvtjp~BJ8J3bjDFq@AG6%OmkzEMV3rPi#xmyJWNZAfb6`-C?E(3@KG7n<1 z0(gfhYU+f@fYd;I1xY=mpY+ZUV(QsHFuekw7_y+^~Y2?EwlO zP@V(D6)0Um+9{ya1Ip8&bOp+#pm>DDC}kxMD3uYHwnkkCI|B@qzd>s+N5c+Mdq8q0 zwz33&&KL~gM~MqT`42Sb4;nWD)l#6=4ul4cPJr$#hSa#A-E^S6s-X4+_VEf(ISATI z2HGzM>c4^R5eL!144_@PkUMTc{W#D}3a-&4)H)gAHqa@7pfMy+9}v{GMm7<&3KnD! zsC59-p$8tlg7^#5U9JqE8}mT5DX6q7VZeVzfhPlKCo-r+1D#>0zyKMu2i4t>HCCWo zlXV#s7-AS=80;Bh7?K&R7-Hb(krXq;FqANWTA?WnpxQAJ++NIOh=H!=2Za`Bm39nx z_Yvq^uN<%rkgE&8EYLnU(0D}-g8@S_Lkfc)Lly&Qr$sv0B+wWf_MQ0?gs}%0+{rtSV;!)gLJg6(p5apnXlC^@T+YpmsIBJXgtpe2|~tgHPlHje3GgNKpF_vGErEIygTq~j zon-^#Hc);CrSE~Y9d?ou{=7up)B+k;1Fdc@2d^~*t=@sv-}H0^tZo9G=K*TtfNC<( zx^MJT??HJAvJ(ZAV?ZTzJ_Bf-5h!)zaxZAd7GzgDq^1Gwk_EMMApJp5I}3kn30Dga zv_cb`mFO`837lnY&Muwd!3_FVs)PDqx$AIij z2j6f7Dm!5-DQA=>$%a02Ce z$gWjLyB1Quz(yqyZ8y-!5dQEiW&rgxVL2C);!{aji%7^_pna{NF;CE%W>`28Dj#U; zCRlG^@VE$+x1UtUr7%m zSULvn5eD_)KP|@SoR;B*>H-K4l-faKRG>A0pxI4OO$2H+5L=p)m!2SY!@>eo4naZ$bV?^^1`{-o z2&#Kv`w~H|1W=m-R33m_4BG1kI$apl$_Lfw^b0kJTS4<|pwI%HKLDx;K`l~HNPtdM z0L`1=yC(&fZy+@fNEhk(5nK3Sx(PH^2g<3C)iI#3qqjRjv+|(PU{F~FnvX^fAJBd+ z(8v_=wT}k_s7`>SR^rDEh;aifPKZfIv~vY$ObT@VKPXj!+FG=84QM?oXtWxX(?Rpd zpdAVW5jVuTgZA-5tV`$_N1!zWp#CcTas)zx!{w0TmHaDn* z1^F4WVi{p8arFcF_JZQ00KB&vR7Znc02=KBoj3^U#ezZvG$#tmDWEe8Kr|>V6Bicw z;FDL0FF}yq0y=*dvg(r95Fp<+%$5tN?F@+#(Ao{c?LE*gZcs@=yk9}JZyp0^HW5@i zgJuCi`l;jBUZVdYzy%a}i}5 zddrgI2H1BEK6hXy)n2sCO0I(-(@jt9jIXj~k$VgOXW z6W<;ry>vr_Iiwv=ZaA6(&`1Ras!R5L&km~eIL*q0BEcOlqNytE@-U*{uAL~ zts+oQf^-*w&WHx}3_!DKh_nxB4T9=d(3k?~v_Vivf!glG{KswsP_e0 zUj<4pgT<|o(g0K*Lt+{^ZGcK5(AutSa7zu8svu<*tPC0qVU2J9h)2I8xEk{0NQ_%%rLNFf!iJQ4G+-%z%&NX zcqpQ#1hsvTb0?_mBPB##}(-8jw~5qQyvDP6F+oEny(f zZJ@pq{?T~IehpB2F@*sXZiYB-poE1esGSmB?4^Zt-dsl$&gaWmgKp_EZDUsR>2nXMh zwVw&E908?tO6`S(JTak6x?P~M2h_#~#Ur9zA#N0ablX6+FevrF#%V!44N#qoyb1xd z&IB|I2^!zU?Prh)pmGt^X91OwpcPal;9HYIz&ELb#E@5XxiNt1AIN+ns3Zm1tciAW zI-2MSY=|3PcKaJBj98KRK#8#J;3%15AD1JuT(Zj2LO zn}Bi{=sYS=`UkbiK_NzXbe+`jBHlfqo#~+QZjd`bX%*ov>ZLW}U6apH%m6xd4^)GK zZYcoO^tjxCtVWN)13cmiYFFh!*EQlE$3Pz0hOCm+V*u^z2Bis5>IIbupxuX{k_nQk zLF*hra}%JtGY@UH0JQrSv@#r2*CV@$`tHWQA{62#(0o8SxJ^V`H;@x{s4fKUNdoms zLH+r7@SV+|5nRytP!R)Y%_wMBHmI}(?c{=-@BvEwCE(NRAtUIxLpGlQWELnjKv=}5 zJkZ_IAibdT;y@!j1L*=#n!^kaP-?_pp2FNtp1(n<9{0YzOa@Tv3lv|Vdo4Y{r)Q@! zAlG)phcRfy5n^2|s8)oG{6X5DkQ@l=HzJP#fo5Pqxf--;53-sb)H21D0+4M$=mfbO zH1-8rB~!xS$N(u>QgF7;u;(*mvq76BNd|44~Ww z%7cT!-Jo76sO1l8VS(lZKzmGwLh2yo?!g%Hp#BbWiiEV%k#i~RE@9AWDBP_(WHZQ5 z)u6H%wWh%CKI|bqur7tQ@jz`&Q22pvw*b+Q(vG-%1)6C(bLTpjmKGO9A96P|FuID*|bkfc9F0 z+UcNqe27blsdFH)<_vAsfJ}8}0IdZC&27MHFXCel)pa1#AblB7IXxKM2g%*2bs?nv z466M=H^zZ_TA+LjidT?2Q12hK5(3oQfP@P!m9W~C_)vF8+Wq4WK7ksvuMM>J43_VZ z@8u>w7O3M(#Qj%@k^t1B0M)jj6gRm2iOuz(_ypw;Trr4<>!IT}gqsQZZt$c}(5MDv zpE9V`2Fhum6gIfS98?}+-}_Fx(gC!ibhwrX^zj@0N&))&hqgJNdj6q2w^Pq8pm`!t zeg&14u<{VOP6O>61MM&ZjpTsVCc)ankop)|CGn*davcs@9{}ptgI2VG+Gvo`AyR5~ zQ11ccD$w{HsQn2F8_@X$pb;3*JOQ%HL9Jy>+lGS6%fPoFfkFr3Cs6$`7~=r6voIfg zUJSPIADpfRwaOtoSwJh;vcM-lfaZxnt4arxi$Q0Uq%ssRfLd#yS`akm59&jJQay71 zB`-a@fKOdPHWShACO$ucVjbib(27UUs5+$VfVmu$Pg5}L0jYn7-xg6AAr(dii&wZ3LK-Nox zM$SR)Zq%_VSega75k0q2%e|nJ^FX6Fh_O-Pa~h$PN`E(!o=WNO#(_?u#K$=CDHYL% z1Eo{g7!_!Q309JU%3aVnA}F1a7v`=Eu(kD|T%3+`-UTy!ak~yQrwCdb16%J38W{tv z6$Rxu^nHskpFl?V29G~LAqy%yKx-2qA)knIJsa|STv|S1LY;q3q6g76w;X5_aWa3RC17F`l7{A(Nqi%-R#QCLH_)Xlx9$(v92_4YUIiVFoUDW9A)HS3%Y! zfN~aORtHp{LiRI}mv5-!D$EoIs-sZdI*{(8B;668&OqyFL1hPM2LZ_MpiwdqA9RBP zXw(FBG6QJl6{Ic&E$u<}On~YtP&*D3o}dtf%xZ#IAQ9AZ5|k=IpI-A3K|~)-QNIO z*Me{@dG!({A&DBpl+;b2o=g!*BQ*u!HS~~q4^Y|yl`V+)M6`Lx3l-|sAPARGTF+6> zO^7r@ZVD&QE!fJgfsQj`-83+mU`hb`x?R4%ICXH-KD)Ep3C=g@fjF$aNp6M-1v27L(a-A;ql-we)l? za`{c!m{$~dyo~r(188g(bCoH%eO%DKY{(omXxs}l|CNI_jt-iWDq%n$d&4${h0QF` zTn1<)3p750ea{?nNWx|?u$hG1$004WK&!4mvuL2XRM1E|sD=Ucyg_{h(1;-^>4thP zL(ZF^m2Qx=OUP^SKyeBhEdYffX(N)LvpYaxiCFvN0^To}NM?Qng%Zqtu#uE_21vM; zGJsMDX#5;9t`1s_0h-SuEmR@<6DV^ps3ZfGXrOsB(CQRW_(A$YkU2EaTp#HCd{FHG z8vBRMRg%`yr%u?y+zRShgYpOFdPh*`4qO<5cCvz6h@g}Ss<$BP6+x~BwRS-10TjB3 zwYmf6Qc#_XzSJrXRAQzx3??@t>MT$w!g3U9-iMqV3^^}#Ao5c&_R}1^R#DJgDX7E;ser7ph0Okf=GH(ZK_vrd2Q=|+ z2F;N|ZZij+r471+8Bto1wJM7=4XXcB$nFtXMMO*iQdI+F1=s{@{ zQtQ&!eaNdBKqV`vR3&siK62j)`7{PlT>)zEfLfNI(OKBJ%%IjWC=Y_t5a?7aP~3pV zw-DvVU`Z{AbdBm4kjp{sQb^p8H(N&AbcAp@%$=YyMZ{PzC=O8L4b~4GJb3||A3&=e zK;CcP9WrBL^>KQwHWa(MourF6oOm|4P3bo zN*~BBfus}UHV>!`0vUY*)r+8WNkJ?7Kxv)ywfdm*aFJ~zek75wJ3%E2sB{F4yus=x zP|62|J1OIL^mZet*9nGn{P_KcUF-%fy zcV+;^E~o|r`46A!Ov&lL0hqlh2^Qkk63Bki`JmHKf1*TB!|c--Fuuppi^a z_@v|93j|YzJiZC)fr5I`pjik|n;f~_0vh{FWT=GSnL+Jz$VD0f|rCp#rgk9NR!?ESUk+zXY`lL8CLER15NN5knrHb^est2r?ZM znxHYRB=8O|(24f(43L``Ky2Fh6lO1N?V*0!$OYel335HCR3NUtDqu)sfaKZ$1~-Oa zGEe3O*#|05KxF{vOlHt7M$jBFzOfU2Llpy7X=1{4Do~CGnGNc#>oI_!0(cJ>%yv*p2c6vmu>)iR$Y;o|K=`tlL5Bfk6Ud$A z3?Q{2UxQBU1&zGJOaQe4A>oz;Rs%ZQ3eLk$IA}BNvVOS2nPY2|0Q2c{p5ftj6(J)Y{fz4fR z44^%cpfgkzpl3>fd;$pA?ya#n4o*;Kr_pr^)aCM z0=W*mt&mie!~oKf%>Y>;3%acclp;VW6O>{=CV_TSgK9?5jeMXu1FaAMts#Jg1tgUy zFeE_NoP$y*s67j6>m`8Ol%RABI@JplD%jlO$dJyE2o76NoKoLin4t%97dDrGLJU;L z#Dil3)M7=XSX`wnXiWu34??9LgAaIreF+01Kaz41J!sqrl%heSWT2h=pz;G01E4ki zAQyt-6k!{vR#gD!M)VX9QVVh!XgvpLwh}a|2`M}2=NI(y5;HD9r2wdA1f@GzS(?NE znqdW{d{F8Hr9$NN49OpmH58!xFF@%El-hC_6c|9M79eg7cu?^*#PTxf!vH<(rYk))|i2O2`VEY`5%(| zK)oB%QUatD0kw8vEgFzXpgavKS3xNRRHl~WY-xkiA)<{8I{6#aI>FVVfz=F%l!&Sy z)OG~vhqd!TH?7jwJ)m?0=>;SDRiID+^|?T&_(MV)R11R2Tsb>Y zJ_z@K!U2?9LGx{(yDdN~3qfmz5Gp{m3Mg+t@;Iml0o4hh^Z@b!ET%yzYH+w4l)@n4 z37R2AKm7>V{m5~FyR1UKTbQUC_uUXhe?CoE5F}8pvg^x)&5mpjmrJ9|Pn{ zL>LcLss!bAPzwn(lLjh1L3xTEZUL1lp!N`=^oeIkVgRj<0qxeOhYLXEA!v0Ds1*)6 zUlZgKP|F6fn+7r>0BSWs*8hRR2bOL@xOQ?)OQu=bac?ZOi;_A ziUHD-re`=Ij|UKEFZM7%zrB+9m_oP!5+~><{DV>v?lYRuYam*>4z_ob*fc|Jw}9?O z0fiB0%nOtQK{+23I-pVvGDZMfM>$wr2pW-rto8<#!k}^tG%5m$anN`SsOLN|X%0Ok z3Ar<#!HDQS7_DO+;Z{(60lMK3G#3M!BLFo*SqX1F8!_ zGX{_t0`1{QWJm(%5P#A$`p+If|r6Lf2pu-H* zE-nGb8mR0B^@c#BZiB^jpphKVEE#Cz2Q(i5Da%1^QqUMHs4ol}1s|C59J|{FOUQxR zu8>|Uq(=!GiG-A_pqdagq5+z3$YubID}ct-kX2HaM~Ls8;BqHq6biEU3e=_r^>+u> zeV`dZP+COp^TI+CHm?W^NziyYXnh|2LlNOh#5x;~U zH?Zyl?U2o60QILpqmQ5&56}uYP|pOik`FZJPOn&nrD{;g0qP?|MrJ`hBT(B2a;gGo z{Q_vk4rpc)G=E5cx6#{XQ0W9J2Ou-Fh`a_GK>&piWONo3Ca~}WjqD-D+=!pC!rt>G zzN`hg6m!fk9(-mCsCEUFZlH1&)UpH3mqKC{G$I0;pQcw#66?xh@c9nK;1wtXABLcH z)u1^`P;5g+Y(XIjS_=kRBLoWL3g}4`pk45wnfQSYPwXy+^eR9n8-Y?NDdVNIN}Ztm z3|grJN{0|PL3$jJKG?v=Ji>jT^;)2rJD7At@8B`8{!Wh(Z%>$og2AR7;KJx%%5@;PBsLcc!4F~lzhLaCbTY#Wa2ekTu zo~0pZb`LTa32NnlLK?I(qlh7!0aWuLQW&U40j+lg_1YmdBqIOPCVgS9!vf8ugF+0n z{sNzCVY}%Ei2a!pAucOd6fP@M)ErGmMQUT%Q&06=47pphSJBPEdj zG$^lv;xHY&9uCyn9Vi!qQW&I711niTW3r$?DkxkpLVW86Jsfen z669J)>Iap2$#ixhWL^Ri&!Dsh%6*{x2ugpD+5)s@4{{e{IzuV6hX<-p;u$I#Qo;N6 zh>v;D90aKD1l95g(?Gr_HDvL-8x-20d<<%>gI1P8ax=_7kiIIY^g&)FOG;~;`u+fo zS%dc3gTfwt{tDFA1?5Ok+@Sga6ow$TWPo?DL3|2ZF*T5}0!lOFt@DJO;7i>!f@uAM z$}~_&!)6CSy)jT2!rB#}&_}dN5$!3^hzw{vp59>!ig{2;3vvl)<_pyO0nHHSF_bcZ z@+7SG1nmg}jn#n4W{@92x(w9HBi42|2GBeVs5g+w0MbW% zc>v1mpjI&EIunSAw08lhl!1&Vg7zbT;tQ4sLF>dpqb;C#1f?xdUjfv+0qq_t1x*`NLGXNUv1-TlL z17LM8sC5CVlZkgXsGpn5;Kl$70Z`irHfH6^0NDc%2@!Jr0xG2{7?9mM7+eObkwEPe z&{!kLZJ_X{-ufU}y#vh?gYr43b_3Ntq=qEu3=NPO#Mexq7=+mjTZ4?;b_B6OeQi+c zBfZ543rW)51=$e|ni~S$$wGYG`7nT5xS((aonQuP+e6w7Aq)_6NV$CuwBHtF5~x-L zjTC@dilp?#sOc8aEij;-4QPE<4uSKyK%-H}r&UnX9k8|({lWtK`Cy<`OQ4hv8fyl% zr$99+t~N9A<13(3EkULdpMMbU0OcZ3+X<9!A^i+U8V0TTNCTfd06Kppg&~RPaW>Lj zlgj`~tDu?>R4c>AK|t*Z(0MPQK1~69l{dt7#OEwuxY@*q4zhb7;RDLiu(454Sb)ao zK{Yg}mIIv?MO;smQn!HC?8DY*!@>d7{sQe|0hMxyQjgdYnD#CLor4Cc-)QM3Q2qwZ zXoG4b&`AfNmL2i=CjdMu3u+MrGJtj^g34gxQwy@)pdJ?T$OdH86=WW$M+zCq0F5OO z8y1wg3{<*++LWNS1SpS#TnFhZgX#rHY5}eJ0__k5l|qP+BhRIvc55&LLND=Q2yrPW zBtd3C!U|C$A=;FnG67U}g3j0h#WyM82r`*G*A4#g1D$n)d|NLh$AL<2M3{nFY@oI8 zmEb-tC_R97aFLoC$q&WB=qB`WcjP&CP|1&+J3wtt&=@hO+$X;N0p(!w!wjGM5To=1 zoj-8dj~tqy_6aB-fm-CSxiU~$1ZurQX5HzNmvOljRQ^GFU!Z!RhygTO2XZT@%mmFL z4TM`!Qyi$K2aO#eay00iP0&0SsO1E5|G<^sgj|X}6hYw%T7wD6QN)i_QsV+sJR?kZ&ft#${k!hp1aKy4||juO!R8&I8I%80S-oZpFTb4m6Gqsw+XGv7nYE@g)^K+>BmF3{04Uauuk22hDka#*9E^=ip8Sp!yxQ z@)%MQfqLYi_yv`v$S3o)Nu zH-SP1)J6w|47T|_;`>^Zx&_p8fs6_udX|{3f{p3Y)?J|92&hZ|wXm5L=96)2*p!li)uRQ|w z#z3;5+v7naqM%+AWRwL&g7kx251~QjBB-51eCrnEKJwfPTMGqpEh3yi?f{h>kUAN} zLpGiEp$IC)5N&)!`;}OmLm5D$SD-c-s4RrFQ$V2viY3CamQ2Hm44#Jd35Zq(aEKqr2tgU`q(ZnTS1+YuvNpgILI9!@WxgW>^H zi^0~&fO0qSX9`p5b41S$H3neqK3awXDD8sgok|%%vpJwOQlJr}RB(R?v`PwJi3+-# z3DQCX-8|$BUP}t{0m39#By$L*$smS&@X6u|44~2Kbnq$fpjAJhvJKQb1D%}$+CL3i z%@3Ks1GU&e_Y6Zuhd{e^6c|8aB@Ccj3qXDW-8lfdQ2|sEf_8e~Itd(u2WkHtJJ z3`!%QbF`3G@_^C`vT3w&1I&$}+dV+%#vtw!0;O3wOd$f*C-y9O#@|69xtF4HKZ&NFoEMhYeb_3mQcQ zm36!fT<}^2bPopTyiZVX3Dgb*?Ir@eOYzESM0oCy!RUp5C z!X1<^A+;%}27}b8pczq+x^!?Y4OwRix)lVp8XPpf3%cnCxyM2qAA;&-$h-&0WuV)B zG8jr2av4Bv15j%Tw5kde8z6sy!Us8yK<8b6`q`jx0_}bQ-Swovpv$1k08$0oHwe1L z1G_3vUlqdo-9+=EUi1cf*$snnGLban@*l?e(*&8ZS^P0M*B!5*k$2LGleqCLNp~3K%l*_Sk6=N~mrFbHHo7Kr5qQ^*sIK z5;>fZ-3O|5AScw)-%YUDr!)q9Yt(2_27pG!Gr{-j;mYZt-FTpTpb#m_4SXUVXs!*E z(jo0RSlb(Ygaq@99MIS(sD1#o@`y{R)OG=AlnMPDTHJ9?ZQCJjBhac%P>U7Rt^%zh z#~=E>3{F^X7AHQ;LA@JLI|0->fy_&RN_tRF1(Y*Etr$@12bFAu!huqkV73uJZAQ>e zRY)t6w&4I8Ee6dXfVuqhL~B1oYz4JJKxrPbh6dyckPASqN9^?kB;8RO-k=f= zG?N6Xxsc--G|LZ~%>j+WflfCAjSkQ@>``3;DFx_fBWPVasJ4cTP(yYZ)6;fPUIX>x zK`Tt@XD_JD3tDvmN=umxpk6n<(i+5OPFMWdP+A7rpNMm;9TXmV4Ajh9Fgqdh zx{&k*n$ZB|Jy2eQ)RLh559tMf+y_!i|4;$h3R>#}q7g2H)rrXdpmn*3Tq1x}Wivl#ROFvsdtxC{|)1WW_ zt;(gR&7jefWCqZwA)wL~RBnJ;()28~Kx=j&CzsILR)kHc!NLn0?o_d?hAp+eB_xVP;Ut|O9VQ%fYvQ{#Ec0j z#$jv52!{shZcO6)h}i7|?G^^D>;lz1^syU}dgyH*ef)~t>H+0g(D*c{Ck84(LG5My zz6PyS1GOnr89W(W;4_GXM_n*&1@%fnqm~difNV$JLj#c|l*Xy&8c>fM)W!m>AOo$L z0p&E1%cvO|u)F}8X9Ud}DuCx|OBf0mKy$bt9`c-z5(B6{1Jx{`F;qmVEM`z*0L`Cf zFyu3URv@M_;98qREBka96rdw^kX|%oP8T$n3!16JDmYU2z2Vunfv(E2k_KMFJ>4dFR6fYw96d`>uBf_BP6M#MlP6d=8bo#nK* z9We(Qh_6bCxaV<8wt4*G%g3K>p*b> zD&;|Athjv*n%M`9)q?T}NEc{SmNFYbr2?o01u_{lDi7NKkqDlX$2Cp>Qb~O`fcym%Z*+wEzJ~Q(XzNSF>A0Yj23oHTN;{Ahx}Y;_KrJ6o+M}&2KxHVX zodwF>AUA;A0+~~T%;$k>Kiawgwp$2!%`~iEPk)<1^$O@Fd(d1k{&p2L(jBNg1MTSq zl`o~>(G}3#2dW!DyD;$eV5sX3(5?&6JTC6JF6xx72%m#aw*%z`(Ah1Zk`ojbp!q9M z`UmX`0p$VE{sz!_g`iy)pj-k{N87Z4>^{)yG0@5!T9&&A`#|+ReQP?PLdcX7IJAsgcJ}TT}GP zXQ;N)r(8uY$w4C>pl}D}VoAgVRHwq%Xefu>6P+O?F5ZOg2ETnz5ul|Agwy&avhW^KyIUL8G!66`j@nXY=`u7 zKxHwgmILJ%Q2&;e^$xO&Ky5)#eg)+RPz?*pvxw4hpz{i-1Ev->zBY8bfQtbq_wn2FtG_nF}*?>x6P%i_t z{|{6@gIeAodD{9MRN7Ft=SgZfP_O4n4VzJWeWdokNOb|CzX95b1Dcq1sAb&y&<}MsCf5TC$*U2i0Vta0k_FpgsoWJx@wpMa`ZkHQYgJ z&yx~6>6P-3QvqgM2hyqowRvD8il9^havN=PA+oFJU(yn?o${V1B`E{c76j#2+Vwms zaUH1SCa>p7s;!{80MO_N=-dOyntRatRM7l(DFbNz0ca+k)NxAC94hg1zAzVn_8g=! zfbPXXxP`R*L8`rwvz0)75=dI4Yz&+<+d-pJpc)xeSCBUrO^JPo5XKhUq?XW>xCA++ zli%~F)CH9H`zdh&q<)}fT1QQ7?BK{BpfZ}g@e|U*12%R+y;>J?ng%Iz z_b@k5I(|Zq&D0!0A>Dq|UM=Zs2r0D@f2@;MHdE>rEkPu*oUnpO3KIrC3X*Nor}l~pcyjAUVm!!N=XkD*!TzjFrjVCz}!Ios1N!6 zCV$+AbUQ)g5TG^|XdHslksoqwr+n;(Qd`McPeZz$$URdwo^J5L|J%%TIrzt3K|im#b^*^t^<|aF$sG)U@o9^Jcx9AsW}=%s_m4H1yN=n{@5n1gr>|T$SIxNaUjZF zK1YxqVF7COgK{XX#*!#;8>oyXXC#SKJ7J?Z)UESPs5FiQ+RK>806OWC z^m2kUH&A;_i4@zZF{VVmefVRZw&9NIbL2D+Y7LQdE+{DdlOGl!7f@qNiF_B3H>O0s zedLZQkzymQ#*|2L19irfNU;%AyHI;fi4^;(Ii^IZy_AkAkzzlhM@{W9CGuQBe!G)A z`{*^MM6T<|8&e|BHf$|UQhV3r**uW7Dk2BaW=x5c5P^;8;13U4#tF;?l#MBo<7djo zlt{4=G{yjFyMTO4+4--ewxCe=ZqcW-L$#CKQ5{l37`Yz{>NA2uoED=x)QMb|P;dN+nl3;s`$;>CnEVn0 zR(69a|SYXVrAe;aO5z;<_gNk zXQ+{KKy6h}KBwJC4K-W|su9Q=vmw`Z&?pUc&r0@ZNM}f=(wZDnYC+QNrRF*uQf-Ho zqM%+p=!|N_j(gDQ#h??fiy1&SIFnY&lI{x7>9wg0pqdZVUjX&zX&L6I<0$y&>FDWm zV!16sk(g7ko$m=sJSe>lj1o5?>KKsgK>d4iPp_tqD@qtZcRsDijw%JcO8cu9@y-rbkvQKumJTxV0jVL7XXzOh+7&VJ%WMC zr=YrmoDnus!-KjjSNs_Yz-w3Nw_=4-85^_cHTt@g z*-D>s6}e>%YQ=)W9n^xQZhx25kU(}7tdB>HmNYfoL26%<5{QU<6k2+FUZo+WL1os_r^RC1Ho?aXYsXYgfk9Do%a zq}xl)6&Mo_In%@GDt?WflG0yXTVWORX4`)M<_K)x%;Yj=`wA3equ zC~+O>qYC8PMrlize47WdRz>6hPzw;m1J$OWl~c5>%|W9Jpz##^ey3&K26F-VBRZtU zILt=!$8$)v5j3g*YAJz66)3%XiFCUuAIqW4PI5+aNVO5Uw+iYPfi{) zwUfH*1;QB;8OjFWoD1sMiyY>lHV-*#2dL)~%108Y5f|i)C{V**@K_XMpUoE@sGN z0PTQ^XGmfI?aeBJh7G;K17vp&18C=WE(2(`0&?G65Y#EJ{nAn~Lq7Pnz!ZjL@VO(PJRJ|dIS_Jh zASlmeGGx*%bU-Z`P`L-%OIHp~#~BQu6kWiOOJg^40>Rwz`)DE#SqNk&EUxpz+lCoz>vtGz>vgH%8<^W!vHcZ6|6^@ z!Ggh(!4j+*6jmTxKqY_?gE2!qH2>#8X;3(VL_sAdBu?`g3djsaPX-qTV}>#YkUhkg zkr4Iq46xB8P#y%84dj(cDS^(8bpw@u~ygV9wCDYJNRoGlU zbkY!J`iGQFgF7dqhB>Sa4cf(2#8AqR#sI1tAbDUg#ss840BRBBfnADlKj^eZP^%)3 z!H@womH=wOfO0P=PRQ-$f^Nn#W^hGopAz5V28{+IN|AU5kQ+g*1W=g+a#uVh0l>7Z6$F$1!TKs`uUYZjEdK>b-z4l4ksTTtEtoy`Zjr3ZB1F=$K#RQrHZ45(KM z>Y>7Rm%>`Tpw=bmjAKy0n4I)NjBhbp_MjYB#DH*lF1SAniiJuBkc&aR1yG+B)Kh@e zn}gl`1>oNKP;@t_=RDNhoew^Vc<`rlPx(Ae+5 zW!@?Uhz6B~pK(0b}`QR&MkVmO2z~%bjcQa`G4pbL`Vj!IX)FTCrXn|_XVsOa_ zOCO+mAGEq0)NcZnn4r)HwXjN|qrBwKk_0nkGJy6wx-z7J$B&X3N*Ibss82z9L8Uv0 zj%UbVfQ*$w+z%;S4CO<}S^_fAf7*MEy)}GKien71zP=5unx&f50 zK;v32dK}3yB`8t-2&pt3O+97ZMJQ9DpS1YhWo=Pp-< zAci0Ye}*75mkqQ_+!#RR3uyiZRQ`ZwDm@uMGmW6$W(k8U1E}W)VuM1&k0GByfdSNi zO99WpfXYYEnhnrs3aCy4=}W%rx7Q0)wwc>%RAL1i$gJSk!T#RTG%abi*|OdqHZ z32SK=Gw3k{fX5(m;iCtj61|uq06bTf&H&0GxY7`2S(640C6F#iOAVC2VI>fD7l1+x zlm|h6KpykOu9_0};!5+NkVW@DWbO~N+9U@&9}Nm`&|GQ(ctir^UQkS8&y|D2<%n`* z@VOf_Gns>PEU5rIX9>Ei1(c3b8T1&O7)lwE7?QyAn8c?>&{ztnJO{0H0rlo{!20QD zFDTs?f@gd|W2lfh5ZtL9G*3&ppCP3MC@+D03<*DcDHYvTXYi;Ky8aM`3-F=Wz0MPmn(5M|`MHlfQHBfFQKV8w<#h^X(pwv!$7`if4fY;|B!k_p! zr97We!*bZfkkf)wI$j^@f44_%* zLyfk#FxUR)YJD5EgkoMNnA_TIUPuSAoX& zK`RPCJx|;r53vo@|AVl|wYP{N9Xx9=@V0_h=YsktpuT4cLkhTeLTmpgfmgnQ<{M~j z6R4%1%K#eL2dxYTjUYirP(Uk6X>B)Xj1@Fi0-8~PjOWwZMo`&Nj;BWpNwbuuUQizl zWD+R1fM&Ts`4u$QM9sX4eUt=p<1Q!`^TGRYKw~Dj$0cFo^OX9x9NaF;1CK&M#*-lZ zP|$6$5O>fzUJ1JZv`+&vt`1R~0xn%3sUOrLrF~fn%F~dwF`%>o3L99-0&3ObUXulj zB~V=IF@XA{i2Mp^gMn&p;%hO`OgLy{3^Y;2E8j z{sQeT0FC*8R@#F~I+!cy<#U)DK&9S5x&vYNz@)_zhH~)DWVphCaM?wzv%m&X8F zB?@wL2??uuK&|#-aQk+kTmW)4DBXivWw3qVpi~N(H6}MiNC|()eh$!jV^F;Z=?UX6 zS&?HM78l_Rp#4#xyo9S9!<=bM1@HfcxkP6fpP1HO`i3>nI0Z_>TvIFD-Vq=?hJ7J-s zzyMmC4w}mbwJR<-Y>iQyZdmB-DlG0uz)@`7+ z6sS)DN~r_kPEhR(T7wA+LD0MiB3j zyATmy=snVba~-G`Q_cX%nXoZmP&o{mtpUX$NFGvu6@&Ndfp+)PD(z&0PnjjvHHbA7 zu+bY@w-RAxCMaA$f?b{Pl3i&AiV?7xEyl3ix^u$XH%9iP&Psf8s`Dc zCnDPoV#D@Jg6b1`xdpVE5M&=Hbt3W+ZEc6-0#FV}f}i3Gaswy~K&=>ax6*#X$HP z{cJ8|H-JVyKqm~4(j)Q(pSA@GE8@qk@VSAUwi-EZNM#^y?u;C>K{K16StwG=5_0T9 zv^$a0EvU37z12-!`$0WgP+tJlRs*%4Kz)BiiAPM{rlx!7m9FrYC-jRK!tNND_#xyj zdc_l>zDLwI^ot$rw$sb+$UX+05Dsa>g7PZpEDTU6fYJtN#RTDzebCttpn8Lxwg|F2 zFnf8#wcjbRA74EL@)N0bA;>Mrtuk`TFMMtyCw)-EP2|>R)UcbH^&4&71Ija?JVbtd zM@#n&RN5g_-VanhBkZoh5ub$IIZ*M6y#^bo*u?G{`i2dx{{va&26(DiYycmcEtt$temZSh)XAi1(ilF-=A*;q9YaL;#6Bs}vuAsFd2@DG0 zwcMbcy@YPk0F7vXMjf!vuMpE7M=zgXJ|?_U0bw^}Wes8$1=98a&G6921)y9F8fCyW z%1B>VppPbk(g`T6K(h$6a0x8NKx>FWJGMY)ZzJbfQ0Rcx)Pmdrn%xD>!-3K(L>zQi z5hC0akmhX(ubu_nMgdB{3Jj#!2b%dr4I^S~1*Iua?f}gnLiPrL=9@vga%mB!xNNIr z0EHlAew<$Rf18WuR|UQ70+ngBEL*Xa1E4w|b#$3tz6JF{Kr;)p zwGVQy7^pr)pXUaxC?#%fAZX_`sAeE%1Oc=j5ab5XPCCTC^kVQTOwg_!Vth|M`$4V% ztriB2{X%w_z|sWrt|;W$N9x%PswF{ZTZ7j6gJwZNsh!ro2c5?WYI%ZMu8^4|P^pDH z4ozzp41|54c~wLTgUnNd=F&iE5i)iLX=Q`zM9{nlWUm}3h0`N6^1$=0khNT()%f(V z7i148y+P6d=(a@=541lBRKA0DU_jyt5o)v!3BoQy>>j4Ct3dGqYKu&jJ^AF7R@l!}0mTZ$e&ktj(%M#(l$Z$nLA4WT1v_Yl4m3{&au5AN z9}%Xobq=6>Lh1?!;zI)YrXf&00qU24dUlY#!^#YX3>FM#45kd4XlGC(!V6TpgVwdt zI^AIIdq(6=NJ)zvc8HV%DSKh=rFBdqy9u<~5;VIB+Kmb7wS#s_gYN$W)d8SzhV=hH zeWZK_h$}&5AxIYCdivE6$>4jfK%>;4``IDx0qszM?4QECRRH7z(3(PAAqpzHK&LMx zG9d0I&|?TO z)ZT~m3_*L>LAfx80hBKhJ^;0xL4HBD1^3L)K)7&VT?gtdRWJ;|aTf#f|wb_JU4G1GULOD{VmYprExgh)@Kr zf&s0+fvvTHlo_C!9+X!=C+LB0W>H{(rG;V=&ZmR420^FmLt+o)CeTTFpjZZteSumY zFk2uaX|OnhsR!-r1kt(g&3LKy7})xr}A!Rx}-GV65NKLCCpHm~}l3tQh%VyY| zBXWHz5_TE-5n2MSr44Jsc&;Q{hLs0IhEjso3RgGf6d^`Kq= z{`;Ij`YDYqkWHYzF*cWh+y$!PK&?$sC_-AEAW__-8w24c!sk0s!&Q)39#Fa^JV!ze z`>@3beSC`FX4vXMkRNGXmJ~BoGJwY5@)>d%VD>`FQpmm$(Ar;G=3CG`7@*P%RKtO8 zj{x;{K=+!0_M?H?BoH@&Ze#(~hQzxBw2Bhce$b1mZ5xjVYfprTgwm|Dg2i6scJPTTn2^tXr-8D5ZVFQ}e0=3gXEhbRS0orQ@t7mAN zdJ#5*=Al7j)SzAnz3qnen;>Nf?llykvJDhIi1sQuITqn(M9mIbrvMTM?b-p=r=WGC z`FQVWpr2bH`GsET01+mjwgsYv1_~WW8im9XIVC-{VhgqY8F=?V+Fr1l2$X&xZW@S` zjOiB4vnL12b)Yq{pjPc*u^&{0K)D)}=8^a4fy5{;b&&g=NerNq_CP&j z&^#D&YNl;2M|K0qmxy^uV*7dIpf?95%HS3_-58rq-NG&zu0W`~& z$bcy6ak&N*LZFmNO23>|;X`i!hF0zY%^8E%snI&UqQ@1ij0NrQg`^&+C@zDxfl{6nrNezVUBu!<2cYP)?ps$U>wIc*H8wJ{f0UARCl}MnFhRjZY&Xxe#1({O>m6D*=BQdj) zpz#$@`w!Im29@ow*-uaiLC%OOW*{#Y!OmP7jBZN-pUw?h`3s4o!4z(wyF&B9?i-9D zH~7;XsH{T1T>+NDL47LZJPOJ^pz;E>e+x_VpwbMK*Fkq{=P^(tH-OfEfXV^v^+zc~ zCIe(ec`mrz$Ybzl0FB>6PN4whK~Osn)Xps;uv;8+-xg>`IOyaPNY4^9{tc^7aMhx; zbPcFB%3;7=LetW2Sh)*o!y`g>AVQ%Ce48+6#AR^B4k$-}(h2U`o0jndx^E6N>jX*l z0}(HY3@PB9U7)%aG@}PvIS9*M@5|E2vwLi7~7_+LeREhY=)af!drP{}Z3%QFY+55Bba#(7ZI{)H}#p63{*p z(3~e|r$r(|68Lsx)Uzl+Cslx4Rm=c6wF@-64(fk_)|sT^9PvSvjIh0CxLk)>N8`5< zG%t&OP7Y`s1XNmqdG2{Xyvy6fUrs2DuEB`eA)ENU8+YPM}jOQW%J-kw}kY zLaxgP$7c~kIRmKY4G9~}SVT{y)Nm`VelmG3M&ue|M^=cBbJAQ&TJ27)7#$pWm9&r| z$IZy`oXJ3q9F6@{KTz3=$eZ!tu^!O4HEJsocR5%N-ZKe0eFd}@1(biN<62xHjGF2p zWeY5AfqKKBUO@%}s0V3m}jH?dB6?&K}3qYX+ zDy>1Q;X$*_pqX{Z`4u2Hf_gci^}dwXZn#_oYU_Z~TLlATpE0P80JRQ4r=w7AD`pD@ zUDu;i9jd8 zfzEx-U;v$<2x(7)PM*nQK-`>5$Q^kMkX?nuy8^Vz6f}wf8U=^#PX>iPXq+D8LfmT@ zAoaNqG`~=4BWTVFv`-zBA3(8D0`6zv_b>JA2F*@GLJnjEABI}) zfRzdK@iippf&2?ffv~X>(6}im{6T4gcJ2VhG^mtEO=+Ms2s#x6QUcT8cJx|_9xkAL zoI}>mAyPLi>}lsa(3}FI%pzu9jqycnp>gg;Du!84qY*)!tH zOJsXMtrSpwMO*toqim2iEU4WDDFGoZTu|Q{w3-K0cY=EPpfgGEwGqknF?JV#TCboH z22ih=HX)7OUeGPSr3|2W0F{=Y@Q7ysjfjC}ya>%vQ8xq-;f_3R3p!~B)QeAK0PREo z^*kUgNm_&vavVT*%Ye$0OmOHx_CSD6>IaS05~?+c2^r*ZNl4mPU;y3H25Oan{0izZ zfa(!QZvoU&Mje?1_VEt036$DEYdS#f8G70Z$|az( z8niYUG!jCa@(DGq(=%1ms+NU>8?sLzA|RjA(oRsRKubG7{d<`Cpw>31{;UA6mjSht zXpu5OHiAYpAU*^2B|v>CP|gSC4N&hE60(S}riCj&E&%xzG=c(~F#&}GtTv#PogiO> z)+B-IWKc~^t57awK%7VmTKNPEXIl6R5mU6U@iFT%(6~?m1E^I2YJoxesf2wA%Cp3` zu@QEF(kO8?1!*>b(jG_$s9u28#?Ty8Uh$4JSyVQu=PMF`RopP|P;fBm!K->aa^9u4metSXt6+mNV zZs55X$mk*QX$aJo$2C_As<}Wj%AgdCtd6+R6Y^H%f_x6@>w!vi#J&QM2&C_q310aG z>JdYBxDsk<1%PLKL9Jj?!UWV>2kAl7pOEn!&4oi2S{x78VM(zjV zPZgkhd|)OK?{nPtBjSSAZb0O4P#+FdnscGaz&j9|DAJN2CeT z<_Rcs7c4CdM3@k=8`P%-sR6b8K&>LsNHXkv0{p3zwqb(LUASWrRO&%iwZL{m46Gjz zIS+M&mzJ&q&5(g+;y|@MA{WupMo_OEREr^x@qx-c(3&_R%_aNs=fYMSv`1Bl*>7cp+G}aC(Er<&h>beWmo=jr^-8TU$u|ck( zk1Ig6FJ#n@zP<<5|DYBDXtf*U%uz@#1)T!}nmq>H)e2fW0NQCppO65})InMaurt;N zi@QK4eSlhlAlFqffY#=L%4Wj7t6=c{Tx6Y|;FGd*8H#b<3xwHk1f6;XSy6;(KcP`q z>bL-uKS4DSsP_O_)d6bw;1dDD{Fy(Ll2+_)9cug$kxS20kP}y&h1xPivRJ#_>RD5tKSX^$BQo5NKs%0eC$j z^2i_c;sen}0o8DzxjWEZ6ChvbG3YWVF@VxVI)f4e=tfFVo&w$IqyS!}2|A5Ufgu5W z2MB1i6Xfbth6D!Cz5&RX0c`vbW-_ED1zLX(O4)i0AgBPoH5juLNA@i!Okm-I-{;}r zzBVZ35?^A%TnVbDFjF9?zK7KD)VCR7HmF{JofCr39#Cr-v|n zN#q%2L>Wn{-GL0H43PBz#D_Ps&7d{`Xon&G^#s^_O+A}IH6bx0v$SvpF?Aue>;;u5 z`3$hW1Ssu+R(XKRHqdAiC^doF){tC`KOI13;6W<|K{>4mydxJh;sG(+nE})e2Gzol z`h=9TF;U$Jn#%!=(1Y9t3I%j?2g;S876f|R0uNz|D<~{rK7_Qr zAfZBPOb&!^vH1byA4uv1rFYc+Fh~v&??cUp2$zHWfzOYy_#7-g1hqDj!Fw7&DGoF; z0jl2yi|eS9pRlJk@?&E7mlyQ$A-&58`umC=Vc<>KTB_FUW`yvPx1*H00eXkUOLb7(lZOpcWrw-6$!o0?_OV$Zeo= zN+7MkdV+KpdJ$H8lb_K2S6=tSYHR!FMy2|fzk@7p9LBVrX;na--1d`K1FvUY)%i9 zra`?DP(KT@+6uI07jyz|JOd~%gXCcTfy{UeHs63k8Pw7PjZ{Hm0W^Yzdv^k8EgR_k zK;-@_a@k0JXk&(43IizIL3`~$eQZ!UiCpdvOqw9hm7shF8l4%;ZUogqpta7R6bV}A z2HK$l8Hr40$i{pA2<_4UBtL;%1{y<0&t%kcy0 zM$n1dpfz8R(jOF}pzwqApFk{-2zu-jvn~u26ZrCfFaxO7m=4~D3Q1L@l((S!$wB8_ zgYr4Zg&>zA+)SO+NqrY$mI)9ygM0yNrBYH7P|L-jQWP{6ff%U-xe#;~87Q1V;XRmB z1b){KuC#&8t%Et0AdiTG`W}cpj3|Tg&;HZ0TqtIM%;O=aR?zL1pxzVc1S&+_4+b~l zj%QG77B*{uaPwd&8Ib$cu<`)W*P+CP)GPfF?t$#G1+6w494FhX%FJK`upad6hGOMruH(*nni{6RU*WIS_6_)cv^YRYWeOPdFjm1WH?=elwz! zg~c$vY68%ja?p5R2?J>MAGF#GGzJd2t0x=0@(JWd&^Q#NP5`N(PbeYxKoKzn%8?M4 zfLPd4J~euwAz6B%0AGX0cag3={bqE zt^|!o<}qY5Ktgh$T#0(d2k10g&}b9nULTkXi@~b{LF1;N)$XYE8FK1CZcl*PVnyJa z?ICRo&|EnvRe{#B!s;tTJu$e_527W4>LZZ*VQmvosRQbVf!a@lEoC9x4|6T3HbJ!f zKyF9PF+<5Gpq-(h+G;4LD@44Y`UVkmpc4!rr7fsD1D$nL0^WszfA=_Q-UO`))nlM- zDF$;fWGovsok4b8fM$e1<3ONPH+a$+sMin5&!9F0q?SX?5s(>z!B>Y6ayKGn4X(P6 zcy}Y0xu7(I94`Z1Ph^1iMuFCjf=&&u1m{S?r9Y_mRl=ah;K=}C5#K69whuHf4@#Aw zk#}0!3CgRG^9n&DxR6={RBMCIf=*({Vu18HNpk_jJYVox`Jgq*p!45}4}~NKSV)8R zAAtI?pwR|$$|P(A>;AJj(1cXua99<+jpTJ8n4 z{Xpj*!@?JI+W^Sd6%3Gl?x6l5C$r0ybwd%|Rp_w}S@{i$YtZR*xMp+*&P}ke z1EoPo$kHq1K&=Q+dkHi`32MV5ms}t@P<{vPI3hO8Kz(9_d8Dpc1KEhs4H|_6wSYiv zIZ$f_(oX~3epUf4Tk{w|DG!w2hz~7lyAR}A&@N}tnSS_2`q0xBW$pl#0FeE&pt22A z_JZ;`q#Pw27NHCf*AQPyfl>h|bwI`rK)OM30kRiz`V1}X1ohHEr5&gToChxBGoZ8n zw6G1dDi~7#W->tbLnHd1pf)yW#U7}v1D!(;TCYyI8<6|fkW>U(@c`;Ef>ug_>;Sbq zLAP@%GZ-_NGFYPZvoT!^8`FwsfZezNsv$u61C(b#rh{$}1l8N1d7=n5jpnMEk_Y7Jw z1Ujt>HMT+J3~W{!RR)$H@wI9}Wg@6mNUc;!jC&#b;XyZng4WtVaua9`Iw;M8#^OOa z9F*Hj8Ip)-&ywzPSgjy**6Lc))ZGER5*y7En7I)P4ZfgrE?Bsci5XOPz+z>vxB@m43+nTN+Fi5_6XaL`jVa=8xq({M zpgmf83{l|o2=a+4AF;2EhP1*!X#vzngzYE*?W_ikgW)Qjsp$gH_zNfeLMh%+@oc|3hp0K(`p! zG7KIFau4DjEl__EaiV|%18NPb%aF*R$)Lla0KPd3RC0k%f`Qd>$mhp^)F4(WD1g^} zz{d4J?KqIFx(tH{g4_cdQ-R!32Pz3*`%6Hhy`Y(C1@L}zP_F~jw+8tLRCeVsfKJK* ztxPRp&}6Uz_puci6u>98fbzEjgA#)?gB3#zLn!nv+G2(nh7tx)NTx7=`hkfIxePH3 zE)1X(UqPp;fyOLAJLF;*+!;V2?7;wPf5$K&?!^V^2esBqz$QUhpmqlp!K;Sg8_pvlFuRQ20-TxfkGT~!VzdcAL@u0vVTE6Xi#rTfdNuJ zfJ#RV26d$PC}051pr$kE!E*(Ir4F_kRO5q6d{F2@PLKf2dDt@KGUzdYQXHuF2O4L= zpMnCQqgWu7MhxZ*G2k9H5jD!vIRZAQ1!$dkQfGj}jq= zR6GO7y`a<%8a)N^ki!L3Q|2(FG3bHMj{@DU16uj1z+lUu08Z%;IY@5=)f8xC4Rn@JHh6y{sJ{Xm zKLwc#$u9-q)Qvoc3ahm<1~jgX7z`K;pl$=5>5AP?$e{olu_<8yt+)lLhr~Z6R+Y9^3>!x@jN8@lb4u?~{ zLd(2DOS4Dw;b=Y_&4&Zu<{iz4qxo<&ACBfjP~Una^utHnG(*3ilYxa9uRV% z(it?n2wDj;x{d>~qHA;=2kk>(bR7qxodaquLe^Dh1*0OPG69W6^o%hJ)Zbl}TUTDF&Pn++;EC@({Bn?G{R28HZs zxD2+nIiqVi@UI*JrCQXr9IgzIS$oh44WOIjKs$nA^ZUqaG(c?74r7Qs=oAWA%L25Q z7_@H`VFKtBh$Qe`BSj3A;B^F}Cvyy@)g1;5Cg50s#Tw|`2FSV%Sj-b%%>g=#BavbB zBo4^FX~g*(2-fIH9H2Q((AuHVlQ>}Ox@f&$VJ{Dr#!RSdGkQ+5d zS8xz}f(Wb~J$e#{0{CPs(5leU(^Q6TSPa!sk1bI>d0C3tuLaGfQf~(Vruo!08|2!dIJQFTa2XAg!F0OH z=n4+XS8!A^fbRGJt9pKu!V&-7N?@`vh|KJg7_|KE`OT66BttbACH$ZX9&32I77d z#JUUYcV>WY;XppY9cBXP#s$!w-k=*|KzA#~Gr-aSC`3S~E`V_K=)EZnr3|C@rhwLE zjGngvY7v6&P=e(U%u{$qS8LEd1V&eDjIP!gU9B;CZwhGj!|1&!pqv1@A(Xm3|Ir>U zY7cjGRD5()9MaE4O&6mhP4wN*Gnx-a^WkVd9G#sSot*-WMS#X35bMZE4U^HbbhIoT zElWqsQc}x}(Kat;n|Jt@rJy>dc*v}*1GzR8e0Dhb_2Ovy#!TO%VKN#fkekvez1y1j z8U4|_Q-Z+dF6Ma~u$g+$2^*OVl&#jtWdN-JKwYT;Gapo%5+7f*R|#^@@LsE7#$bT; zoDIxa!nIyQogr`Zj17j-Gd4zVNzq^c&0@jAK@;361g&WrU9~X~AuzgXV|3L9Xs#Nx zeu`fAm?8Rrqi1YDR`8CVu`zna#?Tqfp>!l?_>Rhr#vvC2qI4e}!KQpRkd`BSqxo=j zrg3zpadf6}w4A2AoE|MpN6XUDvUId89W6_7m8GCrB3Fi?)6WOFSAoHWfp|C5vaLR9 z_UKGMb!PfU`{zSthZ^BLPyF2e=&B9Kstp&0d0G0p5hcE3_g4{ElS6LV`SmIb^0gA0u=|F1M|+i^dU!am)i7c(!m(DP7`lE2bovS64wQI?M1~ZG z6oz;PL>z;{2(*d=grgbM84^d&#~3{ygJE<%$LRSOMGPej@eBnFiQx5k1A9Wq=z5OP z^&F$?IY!rW43+WR(J>yxc-K%J&lruv(Kv+kkw?cY6&NTz*>rUN3Y3;c=dVC_<`yty zGJtlHfW{ukPZvYAUKy(H9<2{Y>qAf(1{y6!p3fYr>3OKSdo&*og?tFA+wixU22(tO zTsyMo9LaBo45oM-jYH5~>?7y=$Dvw>jkLO90bU;gTH%t&kjoIm06L{4nW2;+7rbVsgrS%rhQXZy6zU!fr3^_7F-WKE z#xQ`^!+_StAXtc%7kUf@43!K@;J5(A4kZ2z8O#~Xz+#}&PC)UO3SM0k&w#pqqXcXx zC=DP?1g+%&t>yv6B&hWUTE79pqiZ-o@l-InhGTRM2gB$Zj?pz7rQmYem7$2Chyhf4 zf_8?2iK@c3|S21-vU8w3kTM|0rfW1!E5wDwJ@koE@3ETC<2d) zD=_3RmSh1_cIU?EuvVAoCGDp>PIAh9Cw%22Tb*21pN4i$M!~?iMUm zAa;UQ2ZCxMke#p+6vPLO_<>f8mM}o>CK)l(D? zB%fh)&I)v2SP}zh6;>((C`>XKKx@Y--(yP4v4GJy913IQLuZ^EQhVZeFD=vaP&Ior zACBh3(YfQ%GdV!LuaVGpq-8lhT9%HMrL-tZLA^Xs$bx$Mv@oB#W`kTiIPQcP&5xj% z1&s|UFwnBxqovuSaX9qjke2CV)NIh0@aR5>f!qf%uxXIk*$2cvRZxinIzu8Eyyk#< z^BcP0bqb*R-4bg#k1Jk;;(9kOrNzwPna< z&|^qsNM-6!s-OjN)*s4RctFMjTp=r48ipSNEKo=3+VhB z$n9Jp@nV$PC=I+G2(+3OwDt$Kh89%TgG%8N@Ofw&40#NowVEdjjE?Dm zMyE#SjYsE=K_kSY^Twm|#)#S!lp;tOw;e4@N6XUDxyI4CMpDa-(Xn>Sv36>drH~QB zp|Xz_wsSW!!1ttpc4H=i@9_ZLp#r*lGzYx;0=5GbBv0yD9H2AXK|511?@`eK?=mGm z-e|89)Q%s{t2m4q3>YlI`*K06!IAG#0o^hSY9}J!mI7jfPI*Ax4Gdbpk-`8uV?v!F zageX%uw*br@^2ACDMKDZJp5D&kgwyxw+n#QvlKBDfNvInut8}7H2(*}qvvrz!UVKy z8#!D?&*R8tC;;z{hlJ1Qc^sqbIY!rWjGo5;*g+Xo3 zk$sNdXnP)%en4%N;oY7`ZQp`gA)xhZ@$ggOKy7%~?S~*Xq&<&%Z(<4fo=i|!f!ewt zjM>K5VNd{{Kc~(R%b*GFw}I5rc5NKYH=wf$K_>)()|G==?4W)M_VeUWLu0hH4?Bks zduSOljGn#+O2r@yIn4@`;z0Mt+A@Gn#sZyZl>|Pi8#I3d>L-r2_6wlBX+%hXP7X^1 z->8ePT%h$il12;$3rQ3Ffsqpg0>UOUif z&?O9`t$tA20HyZf-Reg@Ga1xs!Pn{s?V`liT@qK$PUx6wiOdx1(vP}>}YL9KOA83I}h44T)#J~BSq1Av4PsN@?R z?FZGc5DZF5pdJP&mlrdD=D|kq+8MoTCkuL;oB{*rR6fv+jCliSGsGGnP(B0I{~!z+<43I7N3{A&M_2EI*J_To@DoQ*V+61IK!n4< zj&M`Ig%2tZ23IQ|W_}<(<=l<*YG1wCmC()!)mk9w*Kh4 zp5eK!2Q+UES-B0G!A)cU)w{V2AUcyFnIW4Y9(*22G5Cy$JO)txtNA2m?evWP}T~ojtHTP>!c3D)vKdkt zDjCY*;*fX)nL*o<5th18_urzYGi-aD3>nNBEWqvu&8j1>UIL{?Q2GX?R}hUWor6*W z$cG>dO7}SoX$*P{i44WyTmU*{1e8un8B!TEz~KT)@sLo4Uv18BnIvq?BQyJa()xBK1L4BXoe&Pbq3HH zhdhQd2GDAe66l_fVunfvP+0?-#Rc`25OD=b#Tg8m;BZ1$2MKGC9Lyftrc30|0-d%3 zirp9n(Ah+w)CMZ!Ky2)LoFOP(9}YBcPK2Kg)mey6fmSRs52-qsVnWN<2dvI8TD=AyAqFiRUta<}&labyGY8XgvWa{}wR7N(j*YU68(f2GE&wpmd9? zE=&XW@IiS4k}~xe+|Wdv8FCmhM|3?%&CzmD?15S_$n^wf9AGQYOi)TQPhTt7w$fp~ETF~1B!f?(1E5=cJ8Znrmtf>O^1rixj7(nNk@iOSryWr4 zk7t0i#2~8(K_NP7_Q(hmP#a!>p%hv_f>x7)YEw|lKb@hJ0aQPfFl2)J-=Nc`^TD+N z==?rV{}ZGdbXp5cH)zdu2?P52OVBxg1>h5!KzT3*+^>g}N07EC=*%7v3q+eUq%c%4 z7&D|X-{`%FC?8okD(G=i$HQezSIdz+X~>*6hI?5$qb;=(~1}>!E57_!6(en z#?6Fs4szM20B(zbc78zC>|^Ssd=)=>*)cG6$6%>9M(YeNq*|HOIs-ZF!s=sCnkBaV zg_t!1wHQEU2&fbQwctVJ3}{pw)QibyNQa)y1lkKV+-DR(buXxe0qSjl=rnN48#KxS zYRQa_p@7=1kP;k}WNl5pb-#I8yC`g0*!csdYF|AO5o8;(D+pz z_|67nlra>9ZsOt}l*>S^TM!26fQ++aA5j<`ApwOtsD}fYa{!G4jE<0i+H{b)D%8=9 z(Ge0zc%Y7HAm=ww3m7!wmdY?XLPCu?8Wgsut@qJZE+RZe&!Z>hJbLur&FIL;=!gzz zwj4C(3F_UzMgl-1q@Z>aX(Kv=Yh(m;ws8tWHbX8$`j8nJL3T4{xsN(tiQKy!9T@?o zV9;n9y++hWM@B|RM)0o_p@l4{Ou)VN1T-HA8o7mxK7(#G1eM>Qaa+)6E^LgX2)s4` zG%^6%Hw#*cP=d1NG7UUK49ZWSxv3n6R0hyWlM)6`hCGH4@O%|WEC6Xv$_+fmjcPMw z7MS>vF50UEg&n=;0I5B40-9MsjTvm~Ps~tm2SkjWz*b{|Oab+86B%+C@TCw?h=E2> zKp4~-AUui!G8x%@qbp57^Q55hl_cmoI#5{BcFhfP-w3oSW^|VYt5js|o(Ib>b%a9M4F9`nO{ zRAq4W^35627!n!s7(i=XhtB#3gquOR15smx#$X1zmye#BN6WF%atvPz4Q2q%G=olY z0Ih{nU`Pe;zXA0EK&iO^sh>Ey27>r80Z_R>T2CL;*95Ka2CZs^_4)LW_EL`a>p|%h zH109@Rz#qex!Bi4pzbSy#W83_1-6kNSb6}ZBv9K6gvss2gL<**47v=U(-t8kJ0R0& z+mD6$Z*=bnqVyfzI|5oy4_f<*zGikL_UH#+Zyvd)KiZQYs8x5!1eAv2utN4WAa;+9&ehX;zb>f1TnyeZN9tZ(L{AmQ0`d z3Q`!18PXXt7z!9HhDB>+CHP}j+_`m8Qj6AdEhT= zkkjvIFP}QSd{CGsGE{<3X9VrDjt8Hz1UpR)v~mKpCJuWKA9Px20r+gO5(d!jJO!OqPpS-lTgiw^4dA#^}e3CJGW&gdgrS0Mj` z=9OZ==XhgF-`GMEbay=RXbHjxn103{dZ4otL2X4)z5$($2I~8O&TKAbfSePV1dc6) zxuCO|a~L4uiW+8m;GHlqy|8oohC&z`q1?!WJ4BE}FrJ~Dp$O{Zc!pdCV}?=&4JZvd zVGeY*RR%chKs{#22~9&KRhglM2c}PvL!ulU3K`(DjX|dz=P`hC7wEKKn9ni81#+5( zIzuA(G-c3z!l1i_(-;%ruoL<~y%~@%KsTetFhHO^n1-C~1zJ}EDq|q4E3mDv0G;4n zz<_)z8S1%YAU&YmPyjZy1X?>Kf%A72Lm5~UGSUR8@ASbku$&JnrSzcb3DO%Qwr-;4 zI0P;`K_Q1IyFg(%JbH%sTY>}Iqs0{$nBuS$09xG#$`_#3eIxsfEY!1E;u%2uH9@=l za~KT3XP&}lDUer(g4+6sbHwx*d>D|=74w0v>dhHFT^xL(E2y-iY;GGC2OyImdvHPV zgdFC24A|O0mN;6J_~IN?et}vhAPg$yAuU1Nr(val+mX2pmEigcrkl2HLqvFFFo4>s zpt^PRq;S%98yYd7o|*<~+l`(Sj(V;#X(2k8_HWX5wI_0(2jzIodKS9~to8-9kA~72 z;RydiTH!-yOac_rpc529r=7t1(V*1>piv=gHHH!1lfgl~aENYDtb=L@5FU=>rHB}Z z^e{mFMT8}&RZscMBEpW*R5fx_750)6n<%XG9PPWn+Q7Kmv4(W-yMRgvY_UcgF_3Ne zYax&d>fcjA{t5&{n;pg?t`B3#V1RO01wuEz*oXKYR6Bw0Hv{z%KzHYj_F_<5_>ggI z&@9vFX}(DeqpR8!7(lsgq}+FeXn#T4c*K^}uzDEO9vtn(a4~>NS=x^GfI@n-7Xvv5 z2Q(uI+LxXIz6n+Vd~+CRmZ*fG1U%~ontueg~Mbk9s0nTci7~Mo!PQm?4Fsk|CX; zjG<)6^jwkM3~GZQQZD8=0dh}ZwC75{o4H5l-yx%bm??6!=SuwUBjQzp$^l&Gih^$K z1NB!c!K04J44_r&*mou6Fd)=`)`}u{$oGPb?m~jBr>FG(0az~+b*(5O%(1T&H9?tU z1@${i7(y8e7(gii)Ds0^;^I+b0Pe1U)kmOR284WS#$d=`0q#42#sC!<;u%2uf%3pR zH9%}+9~U!#&eSPlNM-=7IM8DN-IWX4Nda0P4Y~<7ogp8*@)@*d8g_e07>J<(06U;wp76&NZQAY=KUv3-ckU^+l9BBpf@QiIyU2kC^EMeTL& zAd?X-1U&}iv;p!h=ISVj3Xr}`22g1MQWe6G&j8zP4m!^Uw3=6e0XbAbcUB`}6f~EQ zh!M~pt4eSTDKO+RfMzW~VOIdY1yD}F7G@y75)*D9lL>_xD4i3BVYvYmPouj%K&OP|GJxvsV(^~gbcWITJ0CnA zF!)EC5oO?L{XKH(Z%|pRz%W?qZrav6w5zv4bq^_ZH!*b(s5XT3MTu|w&^G))X=SwD zCazte3+~r|(gpE-VcM$%xd&Ho8@cBJnl%RTL3^W1M*H31-Wlj@I!H-5Q0J(R_Par6 zK7e|5*jp$gsoxDMiy^6zntRJZ<-_2scSh@N%El`|X=SwD9J5nRKXp#%N7GT9bpvWkyHPL1T}DV+0*kI*-=ml#ZN(S}vnKaM0PS zps|I~k#kUO4@wgtO#6N{@iu_mgR2LQT9boXY@q&50RyBrUdjNvM+J1c8mu3vhjg1J zWbO+x{xdoQuE0Rs-D0p97@Ywh?TL@p-_)4-29=BSt-nDwIx++?_%V1g_(9L2MlMBZ zvw8qzE9C4u_4t-=MG?t-~p)nTgj63Tx8qaM0RH(3&<- zn;+CGhwQ8dt^EV73msjXK3b!X*65=(`asl3qjTh=bL5~gZx9|`la77{3TU@cA_Hib zO$I|e1BeBhDFKbZjE<+nS}&kAz@sbMXgza)SY0)`qYPA5fiSGR0)-8IPCFbdE2>9p z?a^8rlmkE*mJ2}T@#s!6&`vVcS{rnqStj_l8_+7ZQidGxKEZe}SpvROXmnJ4bW|NQ zGBer-AMJyW_Q475aR#-vM)#M2?xqBtp8%pk=MO{XE^zIo2i4QWVM=Oq(AYF_wt!TE zF!AHw_*GKNERZ?4N7qxqJ@8}(P+uImRtNRTM{DxYo#HtRuv4f;Yx2>We6%JXt;s>> z+bDo{RFBS&>6(VBX+rXH=SM{8gRiCr z%`bt*cp!5M@eIWbl?-_d$qexfY2Y&qbHOK5mN1kuVgP)xUTYeBIM zTHO-EK%CEwu=pHwVkzP#5M&=Cj~tKQo&rk8pxjZ)ki>u*W}wq!M{iF7* z%^iX41l?T+O8X!?VQalWe9%e8Akz@7snNRDk zkdTAiM5@7%$B@VX%4@|8pm`+F>IYDn3lr630Nv{q&j32bFqr|gq9mR{kD&~HdU`Pf zXw(7{`i=|`Gcy@rx0|{$6oK2wMc`OhX8@hb4m*EZok4*C;xbZhoB_EMw1WiJ0)yNM zjG4kvZ%hT94GwC#fx-xsmLRwHfkvD_JCswvXM-m)B!Ta01)cf?npXpzNDev!YSe5{ z>kPD02XvQh9s@C9GPrK21xwG2j1!?2nkf4N(3^} zG&)iR8j}OHJwPpM(6|Js#Q|!6gT`eB+nx>d77q5Y7En*n6luf(Hd;Y=d=ivmU@b&Y z&5nQE1yo)@+KY%5mnOWGIk?82Mn_}bzB5L-nF`e20*zaP`VEkgD%24yaiG(keAot2ZCmw-95p)7NC_Q279UWOfgeAR3 z7Dmfn(8x4sR1!3M0J`xLHmZx9c0oOVP%a0hSz_BSqazCb43IM*+!zuWK(}Fn_V%QL zNAf+vr68!~S%TDl1@*H1z;}g$`r5E@e$aiXpprF}0aOlyO3f5#yOj8tpuI{^$_N4X zjX*OXpqYSVhHM6qk3fE*#<)QMLnQ-fTsEH}kHLt+oB>p`fM!Z!7(n+tg8J{El^ux; zAbS(RqwJvi2~^*K`UxP_`QVxgRC8e;69C-~jC^MNX%&(BuJfQRp>S2Mx7cvThY$r^=3j=7!v<7$vtO$A|2q+#wp#rM+ z5i@15(8O%t(H~5To{5GK=YTN8{uH_fSF#X87`PEjlpm! z_VNVv22Xt9f}GYsbMv6~Gst(?>j_Znk+^ySWCjS+VDN`6p{0xIi4HHse6-2Ru`k=K#pp#D^J$leM9Vpx(`>;Uu222FB0tT_(MFTu)3u-NZY7CGL zRJAbsXq(!|4I@hi3kKvcLih{jZcsWx9;F7A(B{Xd}k7PKZZ zlVP-FNB*jc;oY(W%@-rrxa6iTP+kVr%^w`dG-s2^5YGS_vr1toV8{pG&rSp!N%>#h1^J4OR)-Wrf-j)(5xl5P7ed4S>2w*kk63MkOS5O>i59((JPKg_d9Z40r?c!2Qb%zVh`2VFja_N3~Fx=rgL!m zd$fm#=+~Fv=mih;9v-3u8tv18Mo~fI)}T2zP|n2FryFejxzWB{Dg$|IkP4t99ix3Y zVn^eV)q(N|u911<5Jim4j*iBIMjAk^W>8z1_?7U(z0YQZ(zZnO*|4V~P`U%PwLlor zu0+(;>EJPUSl$MWv6D6iuLqv{0M!Jbu?NsjJkacHD!BCva;X7yJq5`A(Uu#iRS)X> zf?{oSY`&HOTRUoWY#w!76qJJzb1I-Y2g=tn!ty(EnE~llkGA7L;SDOSKo~S*1X{@p z*$WO@GXYwY0~!ATm3g2M@1eF!9b4Rwj>#jp)$p-FsRLI#4s=QZ=;Ta9-w0P5u9yL| zD+aV~2^1TN43!L^u|Ckqz8*s`Tn@Ct0$I+P!H2xtP#p{kapYAI z_~HfI+6Yh!2YIv$W+rH54Jc-j%U4j!0hK8rjA)4!f%jC!<2Z*3G>@&$fSIl!Bfq5# zpuHuaH4-4ZkW&h1j2&hlZChP19}{~L)#w>qpc(`g>!5b{=ows~7BOt39JGF7ummkvp7Dlg^MOX-GZ|vQGXNmBfWm5YCn#vf47A1oTj>Z2CDc|lZXR*#Yd|#x zbxz|V#cjl_e4xx_kdq^DhYqR?abX2ot4;n{7NGD!q~! zVj$I^7ClTi_FWc`)d7&z<%!^3Nx1jBW;5h4m@(usWHTh8tjSGh&||0s?c0P5opk?A81709TH=6eo>K5>q@Z2gp!&)kd_KAd z1L#~L)O7`jItH@J5LRv%<5(GE#9+o?2%a+ol`IMju>1g-4Myk&#TaP(2!ug3>TnyI z#$D$S*CHXW#6j)j;N!viKcHD@(2jA?taJeb=zayzS~idfDCWrT`#^eQpjgH?22F1{ zkb6+ays5eC9&|<(XwNce1Uv~kTZ}Ib=q(5GJ#A;jDBXb#N^_vv6VwXFzFT&5_dW71 zVA$^Y(cSl;-E*Kb&2t$bCkcSkI;d^|;o-ge9#rChYV#!Uem~F&BKYcN#0WLMo#yy= z;A689G@}e!2Ld@20yJ9~!jQp$?k> z0J@>eoxv4J6c(ejodrU)cVKNsP&*aVC)i6T(0X~0zaVWN;zAg;)<6%(0Py%jDnkGR zX#Hs>Lj?nJUMGL&KdP;uumxdy*T?wm1Gxvau7=Iff!1b$>R1qs7^eZ9n*mDwpc5kV z89-+g6)}MJsDtJgQW=UF;*s_~f=)96oiYMCJtK`Fk)f0!hXHg}1Ss9YY|%qHHvn>X zj5Bx#8e~*xWS$Q|pSf#DXk(kDHe)cy*u$U5P{iQEkk3%gkOv+W1C{t7jF_1Q#VAM> zXx0Oy3OOavZyyTC6`&aoV&<0(8BkA|0qMo%15iEz`4@x{eg?JTLG>OeAAojaLH6H6 zZkQ+n-zEXmN89og_#0G0LryW!V<=+CWdN;bN@Yl8K;DA` zato-Af`tOUU1s=NvdDH}OQl8(CMf&=k==vrYGiQ@hBR;~lmo8CL1)53>XCHt8MUC0 z0PVYj-Sbflt|dWbAE>1aYWEaD`x~Ipz>HDKd}GRhdge1Cbdi07>KYAjeWk|$aycv= zf_#L{m!LDRL2VY$4o1+9Ur_A{8WRBJP1?ngDOy^?RL8nQ8 z?p*_ozM#4SPzo-yGZ+dPQW&xsKr)CH7^Id4iGgZ+#7Qc83@Hpr42W?Qe60xb zbz3fwxEpP;fJUo8sT-1}2Ik~vP%Q$f(O|52hS3(wXp0518V*##L3$sUtu9cx0IHus zxES0!9&NF3F@QpY+AWsh)&3e@z8P&zjgi~$O^}X(XlK%^jR_m^1C4}%QeZLoEDp%{0EiDci7yj8at5lq zKxccPx5Y=t$3W*9((|4XSQ``4djhpPM_Zeq8<$4M#~^2c!NyiVITqCREMS0*ZjH7! zQAea8qcpT=ZH~5RK=lVKC611dfm#xn=d6=6K9<3d#8AMH#*oC2f!109wRMWn#OO0F zMvL|e^4)9k;2or(oAu%u@)@(1(ilLdC4*1k2Av@> zx*rELTRZ&s{4V$f>h;lF|%HbMky_ogx+R{S`5El5xgWpwNjbp8)$?=vVgKb|Yk!52(%powPW*-gBg`_k_&m4|JOu(Ru{A zXLJk_a(7@R!{`_!<{SuRC(?|zAV*t}qb*3n=j&85WHDqifK~+-j_5H+#Q8a(d#dsn zK&L0AGayb39NjB4+IAeNZAS%$!P9OWZ8MIx89{vq?CWMm+l-+60V=1A7)Ixd{c!vjw4ce!MtGx(mU4r)4fK=%*Ku(N?@twgt+ec51hNM^O&1)iJ4L$rp>v)yG zXXS!Ub^@I#fPHNsF>wy7mq2wBDAz&u*?`*3ARZ{bT^R})O2Mf`1AMy<=!}L$a9;y7 zr>(~Ty15~d0d(hjF+((i0YfZ!uP11aRwCGq2zk(6E{Hf}7S53Ybowi3Mi_KrAn05Z zR|e$%uR22vLj^+`LmHS)VXy$xFn%h70hn(9r41Pj7`zzV7(5x=P{a)w4555<+JM0W zDuc`d*$FcfW*6vWR+zXmTn|VDrh+gH3TcQ>2&)|)>L5NI9)2M%&Okn{0H5OvN*kb5 z1WPTDv`3sNh%`U=)q{LIl47_5e6lmO;w2ecc7aj~D8(4U%PL4&2NO47Fh(hL3>b`{ ze3&>SeIfM2%0`Gfgg8VU%sg~)n7@)4OrYk2%mKx51%n~997ebaBv-+JC|^yXdSG@C zOT)||mxkE`@hi-425>*X++_xJA86$w$lahYE@6ma$b*W5?j?ofJ&=z<@qro+6%0uX z5VJsa4M-jl7BIVEZh^%MjE2d>!WAYCG0y;MF2c<)b?9MY$WRM)EzBmE$uJXPIv^$> zVi;nRA%hWvB7-4=Bh(Z~m>7anwJ}2=1L#CaP}rC=C^3LWS3&V^0!?ie(9~%Or4ymF z0fPmDGJ_M?#3ZO#GL$xCFl7h=%cMX>(ijXFR2YmIKqsGr!q5V2IwBqn8DMUL#FHVk z-UppH15$6ukjS9QpvDlxpbozAL5snJ!IS}XhlT}%C4&`%GXv;8YBvUV1`h^L1}}zS zh7g8OhA@V3h6sj8hA4()2FU#=pg2xv$Y981$YKDslu8-O7|Izc7%Ca6!0xqx<~a*! zIkY52a>mhnqvty#}aCeCDa^C z21~I0mQZsNq2?q)%}Ip1ClP8+BGjBjs5yyHa}uHEBtp$e0>?2VwIo5!N`jgNOV>$I zvyz}@B|*(ff|`{CH7gnFrevr&uzZpXbyG6boMfmu$xw5Wq2_>2ItPVC3e=nws5vQ6 z_oP70Nr9S^0yPKL226pP1G*0wWKJqHZKXoZONE*TisMwMnW<1SQ=w+2Ld{Htx-AuI zW-8Q=X;3rMpk}5)%}j%umj*R24QgH*)VwsPd1+AdKxY?#+=#tw1?4YD{fQ_?VL2F< zqhUFn7#iebQ2xcG7G^fFG|U`Gx}iqd3JMEYdV!Unu=Iy0tzhnh*^BNDNa+SDFF`&A znThE(NclmyY(lC^|EnZX!ZvVuYYRH{Pso5D+0NQn!n-9V+P z3N+<{a*Hb1Ww11E2u-`#%39=-mYi}He;Er2SyIbdkdFs{c?n1iis1^F11qDd`ZVRZr`7bk<$I--1l<#*IF29c}LbGZS7J=6q<4p_}@ z!2pwimF=Ki(6Ar47n z2>qz)5aJMZFn#Fauy{moV^Vkg0_0t3&`50s-sLc(bVQL^F3xwO*Fgs~A zhC%J|3z(0oJB9%{6_D5y0f{>U6EuDSx}&d@0koFhhQWqGfq_^XAa~lsZs1E~0L}S; z?%4yG1UipUM)f0nrVwPR0z(OdjOuQN5(d!xj{<`MxL<=hCuq+AnoEpi&}YbF&}2{m zt03MzFh7G%V*%}*1&tPfPRuR^-@6DBq0GM!9~0{ym}@|%gwpR6QqUNd6GJG2J9q{+ zm;n+Npp_D!TMtvg_nCn9N`U5fK`q`AhC~L?=nQDq4s?TX216o49(Yy`l!`%a2c1a@ zIpK7$m<_qZIF|wBUeKB7pf#N-;IuM0-8)pnd1Sgfk0GByfdRHg7PO}bG{X#8BMT}? z5*c8#&I;f&ic1;tz&rIp;vm&l45;TLW6ta+f^TAig)Zv4Wzg(BXtx{av`G+M0KS)~ zk|C1;G{yv((TBK2kD-zwks+5MhhWNw*`&Y#nu7l%zD;C6FC+9AAmIsHkpi;QlfjR{ zjlmxpE})o4mUU&w1M2~WBdC<5b$o-?X(T~o4U{54d)5^gkn7qQ2IP7+h5^*#g4CPn zwXGgQJ_G3dU(`?~Jq$p*SMnG@H9g2Rpjs7F$ACg|U_%AuFTx>1T&RFj0x7j!IYSWx zq*emCg8W(tv_1w@0)Xze#bqY87(;a{C@%8AH9e?J2J#E&j5?63Qov~ml5!F2xL_#? zRGxuu&(4Lmyl8n-1ZdS$5d&z14YAHgm%)gkg29+Uk0FbpfFT{NT%(r12bZrvv4a|W z_)9fhse)8jF}O0Iij1!6q|J%pu-L#B2iVqinlKnZS5boQn*o&?pi~dJnFo|M zKYAetf0H}RX$)Jl?A|Thr#Fn|EBOkOHRRN_F zP+M+rjC_D{38;;Lzr_OUeUd)PL~HYD>2_M14Jsc7&nQJ2Ll#3CLkYNV90Mj{yNU@~}V1SkOkWo=WdhzEDWRr1?Qh;(i$aSEc1nbeE_8G9LK!_pw z<@ByikZTW+4{(Jq{xE{okf~@rLQoz<4F~+@(4x(OSj}D}53QFIg zniKzs=+Mr$$m5HM917`8fzq=pLj^+#LlFb0l?obXCOlRH(nZNE9H?!a4<7FXm1NW& z3r=GI-C%0~UOf#d4N|d;>|hHC)SQh?g(rhA1E@3x%~=&QfJP&W89@De(EYifG8)vk z0gY)TGJyKGkn?oYz_;Tp;ib22a=%N~OsC7f^`?>ZzcPBv>;jFcdR@ zZXqsUC;;EVn9iU_Vfl@%tR=QjGCB@~e@`!{T>&})1~UE&+Sv=+LFfj>H|`Vwsuw_GJs^xc8iLq`OX*%;gsF(x zfYDvQBV#QfY~39wmBH8}g9iC{bl30jPUWCDrdDc(t(qO&D`r7HM&6wUTfGURVJk&p zt3P3UVriH;=tgRpW8CQb|u%E!pN5zzI(%qEtG>8D=V3W|5! zGSlMm@9)SRviP)h4lN)TienGCJ#*SZ59G4*N`W^l|enCD4h2GFP zVF8j($=~q{@-gHDj=^`r0>p3B-ti0aF{LLefaV)O=>*oE28~if_~>ORYWafLIR;UO z;KTOy!c3&*j$e?EL1i_>EufQR2J@+9)acbgd`zw06RJ7nn+?(lN+qb~A@0Qg`PssO*N=2df>(r(xzm z>Q>CQENpBAa;6My*DuJ&^xXLiN>2kjh5_<1$Q8IwFB|-07_`{+3tDFc+6e@j4+8B9 zC2ij?C`|FKaKXO@2h`>Qt??jzH6Uo6!@!w6xK>^cY*-A{I2^q02CbnOJgYeq8L}Ai z8L}Cwz$ei`cJd7NJ*UWSCR9Qpuek)R9|G;%rQe=Y#H>4F)fb`lHi%s|h_#%cl?X}T zbJ!94_dq3j33&f9VnrBY9S6id(Eb9@dL7V;805X9sG+9EfX$tR*JL4dAzVtIbykR# z1Niq5g33-*f8eiGhT7`W(G^knchrH>Irg1#h_s7sJq)M>gzR+EU;ypa0quwz-5Uog zg@)RCD02qvJHv>Je^B}Xt%L$$#JZ(Kq&o>lS3`mNT(Dj>wy`0|7$!^wVHyL?<}#}%V@ATW&H zfdEM*=%;go#$!kCKp6aIa)a_QWVD_9S^B{`Lk~%rsnC<_!Ht|2pe~}K;(zU7zUy7 z3y_aN?P1ueBS?Bjv^xp$AuTZ6?Px;sF!LdGA?@4Qkdx~{=^f!_nB6e9Kvo7L+yaw_ zwY_2TurPzsFnJh_?)QPZ0|6Arusg>FZVY2|HIysEU^v}>bTt&{%SrU3 zo|A3NV2SmdY+~~OsO|!-g#uyZ^-zejvLSUs0rYN{p?^j;(HUkZP(eW>k5z~|G!HHLtk z2ZqWS_Q-A~Hs6BOf%XZ}cIOkw7Hl`}Aw~rttwK=xC%pS*g#onM8B!{Y zX)P$e{gAuw9ne_kF?kg+XZ0&aff|JqFmlSP&W_8o-dl0K4lngaOi4fZP{_Ez|}| z3=}dU&>IL+!FNL^Gh~DB<<4cuX8`SbQvi>H4c?I-NKB+MKxjzVV?P-iwCc|sT+Tph zM37pL597hN;$ce#pwI!0bbzor1Bg^*C}se$R2d-m>lQPBM(Y#7xAP`}?>di%-x#C8 zfEXdk1>d2X%z%(BW{74mV2EYVWY7VhQwK5~l73Pd6d34rzZxXehzmVX_#sXfk7tNy zC}IHJhm0Ib2p=cn*dqryj{(*) z7(jPHAlEIRmPRx~DT6wLBm7=^kQk(PLA|pX)RsrTqePDZ1Qi$*8EhF87$`Rh6he zBuvRg*YhHm@L~{k_XiTpgTlCJAh$vQ4GD&0@++p`i0!z zg05PD!DLXy9LPtInhkVov>}561L#Bmh}%IWK5|@wLeGT(G7F*r&R+@)pj2YaU<|%- z1#|-oBprZCP*7?H-H-qZH_)vg3Jjn=Ehz0G$^y{+hZPJ6GfTjy7WgrM^ngk`2p^;# z!~>1-L2eHrwpJXN@z!t#M}{BoJrufO1ADxP7Lhj!-i*89;dk6fdp}us8+P zBI*pF)=>&WDY&!-wFe+BgUlf+Fo1FhsBD3ZdB9wVFin9$9c#@CS@8t&IU-a+_K`AX zgxaD7nUfB_k%yY5g33?OeLtX^DM2$wARmJ2Z%jKtdBcstADlY|zK%ey&G5SwlmJ5+aB4;Bz@@O99p8Kz*XoF+E~O2SF(bghAy4XcPoA<^k$m!sfSNeSUh5>49pM zY=&fpN`}-yKBh;EOF?Ri8Is|34{}Hkw=q4CUrCEOQd;Anbcz^%1C8g>a!e0o8)zhN z;K%hqE+O2C0;xi6*N%?ufmS~u!en%8Z***rivf`yK%0@|}laL-xi28Xbq(_8n2iw>lB_R*;%g7zuBPQfPYG7?_ z)ciXb%1oH+hE{or-PNdNCE->nOa*Lq8?-8YbZifOwN^R2WZR?U5hypcc_c9@`@va>#9K)ci~Pu|48l2kOH>_LG426%F?C5*DVY zu0|~@VIy~h>Cv%0P@f#vnk~@&3DCMd*h(7mM)yD^G-x#$$d-Xy!3S~$;q-v40;FT; z>;nRYE@TKo#M-D;lUyv+l$5t)_>S{oQnaDaIX9O03_wK@602;Lb^(jVo?iMo)uARH2 z#y_O@02&_z?Er@CLj=V#D27Q{0Yf}PIZ^BVKt3TYKS08R zo-PKt5rmOL9N%g`3mWasC1!!D1iDHpi?P8YxO|q9OLd&g2D>h+CC!&OYlwr z&~8LX`wCP>gVHc$H$Wc4=zd)-@SX|S-cCrkfOez8S{$SMbw~H>f>yGQ?$;gY5)f3% z(Yp^zTHOk2`9jLsf$zss;&Rl!ENYk!w{bsG!wE5xHWbn$!nL5WGW@fLsPRnu@ged< z9^{viJnlz0~$mROdfjN;2Y61q0xvQ z>@>x}6LP5QMo4L|gTfPi)X$Q^gaI@fnhZXH4AK`J9rGJKqYu%y8{Nk{x{nv%KHkAv zGUA^7K%{L@tApO-Q>29#sLW0Q-xmTpsS-59Q@~Kb0K1zr2E3Cg8GI%jq-_8?Ul+sz z(bQ}?z`_jV9>@uTgFD>l7iOf?z_3sp4MF62O4JY>%;R*VgfW44`w-LHmwzjlUtQ(PQvH(gEs+gGO3L z@4f(yMu2K@*vLmQ_?&9;?;8X4=s+WZs4;~7bUa)mY`EeXlrli$WFQP0w}GsvL%z!a zHm0V5l0Njn=ftDBNCUhY4{`oBapO$};PbsftMnji{S?5bdxJ*tKyCwJ)U-UXJdk^^ z=Ook>gNRxYH1d-NJ}Ets0dz(=Xyq2@#QO{e&^^PD{FcH1T4M+~RT~r%*w?)x+W=a# zlEMI5%c#cyx|axcn~5Vd2d6NM=0n=$LtHU|?fiR71~c%8HE4yA0{CP*M1Dp#2b3CM zD+ftWGoW+{%EKUxJs%@>bs?u0&>8qJy|5CTersBh{g0fYv4x`r%Bi2oB@}j_!F+`~ zL|hpP8A`#uFAXpWIq6!D0pSwReFBKk1hqu+7~&an89?`jfbIz)u7opWFkvtQkJMQ( zm@ybJm@=3$=rI^GfP4fS4~MBSXD~xiW6EH{V98*_U;$1!_~#fAvas1kP#Y3*8vy7g z6zZN33<_V6`Jfp)NRNo}eYV)s!{`kept585-;jYl_J`jc8Pphi0ksDqa|xLF5Y>Di zhJ1#6hHU7ZodQECLjm}94#<2R^=7&(7;+gZ8L}917;?e$e%NNZKzn;q!R;PcO-IP} zAq zRA&(iS&+LyXUBue7SJgRpwmS_J--sLIfzgJ$%DcJbo(13bia`T_)aTG-pd1vgIr+1pvPdsU=FUK@wp#=h$EMN@eIhf zon$cNGh~8oBNXD~*#K%6fY!ZN67&J6ua?h{#-P9e8s`J`Vn8?kf_f~VTY*4kK>9c- z1Wm&4Qb?)*-L4I4=YdKLQ0@Z7KIjf8%0gk(Y)~#l&Fw=qOa}9P>4VvALp8o}m65Rf zJRogk^2=aEtq1CXgJ$9K!R-uC%>pWQ5IrnHELaZ=RHKfb;fNZVs3RSqlg&WwLXha_ zXc*{ROVItCpz-&ivH}!2S0ctvu#Zn$G8m9C8b&CMfbu42oCkzKZC}h$Y((pMbo2|< zLn#5b&<1t{46=3&a^o^={0kJ5sAFIz45kbQ43-R_aa52jp^_IS4=aH|wZZ5Z7^odx z0>AGRluu|o+6xMGNI!0L1sbT=4C<+a_GN?mN}zcz&>hr}du&l}iN#))j*fxB=C_c0 z#*ltEXk-OcE+A4Is85bMazL*!Fwp1(sOO%;U^F@gHaZ5zpujLX28Nmw@sIl;mww1O z9W?qgItB&`h0!rEQ27e#C4t)cp!>){wJPXjlT>hv7GEuZKkW_OF%i&uf?NhrSmZMl zfX@jZspGGMdCUzqT0R<23Jileo`!BYfEcett~*D^MhAAqAk219AH|J`yQ`7Mpb_I< z1q`4WHc*{c1f6|FUWWwgRgSJ11ceZ2g=HRiUK}*XoWlURBPfS~-lHF&8X43(1+4-G z&25)3ppJkO8YMMkFkmpEXq=Q#dI6TIr z@iaO@2wTgKTHYX!Tp_p2M^{h6#sKltpwfew5khQdACB%S28AAIuR3H00%(SCIIp8L zWH4qhCvt?4yz~MJPtfQf2!m>3d?SP*450iD8tK$vfRwPg4Cwo4LHCq{)`Wug0%b7h zF@Sb*lpyV;)nLeFfX!7P)M-L*mjStgwky^^buVb#fZQ=#3zU_upb=+KsDV}|Ax2UW z;Y2ueK`T~aD}WIufX-L|or?l;DQtIgG6U$u+!SzXK#Y^xZO7%Ca^ z7>XDwNEovP)gO?PSP9(llgnG`{*FJzkaPW-|f_6ZI z>c!E$v!H$CpxJs*c?$~>(1_1aSjRR}M<|f%H01Id)^?|K4<;fVAln2RLm=>SP8|oR1_+o|@b(;}*%?CbP@z)unbsM7O#a?@ob1uYa-3D5V zuE2mgGKwhEKz;SWzeansZUgllLGy{l44_s#ed;#YSO;MmHX1T|x&WwVMO|AN&p>Fr zlhE2o(B6AcUkqfn9=KNqVxiiC=*^Fwzd5+aWkEa3O~GTMpgt`A6F4bNIiL|u&`321 zgL?6lj+ukbm;{YwCBjF>kym{~Msh)R4el5i2_xg6adFVdI4A|6u31JM9XDq%WiVm@ ztyrf2=s3u2ISlzI=jqun*f4<3&m&ytfK-4?Ky7i4p7~kAP|Og+fC!b*Rn4QTnlbYU z>R2!Sp6SpTMKEGWWT*tsK4y%LkTc{ljE;~)&PzicUmG1opw{}u(NP4@DyJgo3KPo8 zSX!>(!&QFMXA}X^5&_MsP@~=%nIq)XsM|(I$VX>?A-h`;Cnt}NkdKa#gT`%P=d7oJ zM;MD3M(Z|EeT8V_AlIU>*V#dTl=Zd0^hP!}on?N=bw5kWZd5X4072ZhQ&E~`KrM98=rjmp9}Nes*9YD7ron)|Iy{r17(V8Wyrvwq z>JxNYG;CeCBLnDW29O^?cQS$2L8GqXMBIm=0KTzK0h|*+r*VSj|3P+xTuEG+qRRj) zRX}ZQ`kg6DN*kV*{Tf=DjVSkr#tb7zgaEbhM$i3++!+K~M-N)* z3A*EQw2c8tOQ2c@RQo~pFbwtGYM}ZTv}dc5K?yw54r=k`F{CnpR(ylbvN8mVLgwE= zElbFH3eb67#HI~Uc!AmxAUxWZfTSV9Bq-ECZ57B#?4TaOXj@`rg$1^@1SnNdYfb{2 z`P4BR;BJ2OH1|3ITAd82n~GYp0?3(!q4 zpk1G&wkIGZ3aAC4z%bf|fR!$UXi%t)wjnZ!y73hMx}MRxY_xyu13v2x(FX$UjRmbB z1nq_e-E#_CBLG@$4jPq59t|U}UUOxr0FQiv#z#RjZ=>Vx16_xKPBuoq1&_Sc04kRu zbs2JPhCFKqS}P8kIm={7WQb-kV2EV^_0d5)9W$V(st_7IS7(6S5+1{Vd`~!Nhr2EV zXa@u+Boo2+eaA3B)_K9oxEO{Q2GCk#&|Fdu1BeImC1{@+gbiY4gICR#F=R6sz*T@+ zc*P7w49N_jb?-$`@eBq~-awo$1u+BLE_={94UqNMpztYWPzRd;Qg07t4L$#W{6VOW zhRMTv3ZVLWaL!MlrcZ=BLB0g>$m^Y>nu^%BH8NK&q2?=4zQfE_pgAT|V-#S7DHhWCSY(Iv42GEUoF!c%yo(wJwpj!<L1o`J?AZDfs zxfY>PfgzV6lOdfU1AOBEDE%rhgfTdR>v+V>BO&wfw;BRgJr67n8r?Kt&;#EVO4u~WSPCp8(0A*CYA4K< z%%i7?fJzKdD1c%gbbcFU;S5PTi436G4^V#`bn*vv#tsL1Y!6ftkXMt9?!2bW&TB*| z3hG%Q@;9h`3`)hY78GF`*2aRAAdvHn3K&WlO2OxdfaZKb?cQ_-L`_NB9y?v|xfUQd z;Xf^uzOo?qxM97$h)@p}Hp2%B8NzoIL1q$>@8}-wzbY^&F*q|=F~l&0g2ydEy)JBh zFc*e=hGd3P2GFiy(AgfKeTnYi-4Y%Qr3^`EyA)yVLXb(IGq^zc4!Io-i3x1$#w@@m zJYpMxB|a^H($moHy@L9^pk8V!Lq51?2@B7m+Iyvqe?aj}xJ-qpfR(JE+7nWGQonQs zxd&uEd9^cg{)h*UUO?PQO;bTFTF9v*BeVC4nhvq&s?pvnXay^1G@bOm_E7A-g7Q}x z1E>vG$}o6(upn1~S~Z9e1&QD^DGYFcdN5 zgLmM8`p=+IPskZzps{pNzdoA5g29R*mdN>8A8^_Ntsel5cxE!BF{Cko`t6{x@Ms3| zXK(cwKoEA%1LY=xLI{LG=ahkb32ME9d<=6hVjLc{)($p)p}=4OJ*yuwYl}PwUBZAq z1C2ia3>t+4&2E5ZpFuGS8uJ5Yz0$DGZQ( z&Xo+f)=z01uA2gt+@L&;Uh+~t?u;!4u#G&M zFj!#SNrW2Dp!5JMBS0k}W?ZU+O;KmiWk_Ryuwna85i6u%buh>zP&xqBOo);A0ES8i z&?ppW$1&(UN6>1gOz;>xs3i%iZ*-wI)MPV&_S%C+*kiyq%7AVqL$E;hVeXo;M7!M! zxh(;jB?a{ZK<)vh?Q-x4e+IaW1i2N2L2jsE&|?6tkOGyxpn2OgaLXf?L4yI`sxJ+O zcyJ2>)Jg%JNdc;hK{M_UKWH$3YE(!)4BCMWYQrFlz(Sr{;RW*twzL2`LlZeQVDl@? zJ)kf_$Sc5CL!^R34PSVGT2i1Hr~(GasfM5$4>Bs9!;k}B^#JM{*KJw0#SqEXAS=G`@uV& z0y=9!0lvx-6xX1V1vGAu4xU+tjCz8^6u_qpLe@lq)=YugRn%^U7BJ*7{qWHOX8 z#DIIhptB7@E1mQhDj7f{^f}<1lLS6L1l0ck((Lk>dgUlz?hD0_K zHm;@)UDX5XQ-MZP5cfjTs;5kjxgg(R?_Hy=h5+R_NG~BCTt0(N{K#Pd&G2C#GY8d< zh*ff+JcoQTy$|#Tot)8}M$?>z9Ol^jqM-XTjKTe7P@N6Aj}jEus54NYv2xIS7id*5 zYW#!J4=Cq>F!tOBnhnul0M*!_+g3q+DM%e&&Hx&T&4cd32A$sp$|ayW9yGfKaswp2 zL3;3z^i)jb$T=mpA1J}=>Rd1kCB9IF~_Z&xq{er*sgqn9iZB@uhB8Xo=t|LW1 zDCCjX41vNN)MEg(3=t+mdI_}I%T)@VDYF2t#0QN}BKr@-2lZefGnb%IeT17pm?nmY|+JDI*K0xe;Uzq;3SIB@hphR>?ONy~YIj z3zSDO?LZ!vfz+VX8?!>KHIe-dnmL8-jRVz~nC?RLJMr}>A(JSn6GzPkwQxZ-D=621 zPFsM?Fi?_eAuS@1nTXnYG@Pj)&d7ZWMCpKN0Z^lkv3!P~~8)g3&QPP!ABb zm4&Mp3fk#BItl?wF_76JP-+Ct5rBGEpitC=uCoI5(Ltk~pf)dJuAA1o&LBN^NFARJ z9&5v#5jOd?FQrb8pBPg>ex+Y;8(W(O zkxD3Off8#9$iKvd3;n``Q2T=vpMlDE$Y>jC{RryefL51)e2?0yz|DiTH$ZJzNEtmk z3PIaC5){&qKJMr!#ONplWK{|+M~LV)JBKqV(4f08<~g}=rbyk=vc zGZ?(?9lGI6s1-n2m?LsCX1f4nGVWFYx(uvU0P0gh)}v8(USg=7f`eRY;u?i8!np$h zy$9^Wkk5cv8!@^T0<=7Jq$6Y#0wFQ>f=F>}{LD7bYMdgHkO$Mn`bvCd6zAvEhTS#W6Y(0a`&0 z+7AX=mkc^54>T4JS@{Gy=@fK^8)U2nwAV-hycP)0>uv~ zzCe3_KH;Z0qrRU?J81WfVA{M`%pmpctG<#ppm2! z2GELU4Te1M&Ua951??~dl_Q|_NH9@N20ey&2FNL4pq=g@wjR<+6U7V~46vS?BLl=t z#42jYzGsjtK&81l_@od}iUpP3pgWBqE*rSnP>@?7JF}2;52#eZT{EN0jMmhkxFxQ{ z9$m2rO6#CH22^i@&X^gfF%VdMkzP|9F_>Z9H;G=if$DBZU6sQ?&6SGi_Keolpmapd zyE;JSA8NmIboUhKG?>wKOQ6yVRC0m#fzWsN)M!mj&M5~VJ)qo-{iFl*k`%eb9-Y+( zrS+j*QyVjwkX%z6QE^WJdiolPH8m*rDIndc0-5=ue{BtNhZchZ(kY0bnYVlfk5V0Gj_! zWC(_ejGh7vIt2^V7pDFxz?h+rZ3Nts0sGzQ_+uQDQb45<2;&?7RtJyqfzBPuXUJv% zt>grqv=|A5onDa=!W!E26gcH ziZMi8T1%Z7?Qvzc7oij$AEC79z!sA922yE5>y63%41O54b)EonGRavU%_C2 z0gV})7)%)~7z`O)7z`Nf7;3?_9Qx=UEIG1k;3`ot#bIR(s24iA8zG({jUkZ% zbV@EL$EJf@KKbC91C+u*r=o)9Z9zBJgHCqOWB{Eijk`?*Iybcle9t|yYCVPka1ROH zlmLbt23XH%B)64ldq037gE4~vgDKLO1!zXHgaNcZ47A4=lzTwsGYEs)0g&^;Ky#XD z;B)$t88jHQz^5ywGZceO(PGeoo)`^T_YV?>oIwvVgSPu!K`koKiULrp5;VICS_^?I z)nRK98Z%ge{Qyes$mdg%lM9eT4$)2ooh$(AKV(49qSRn;1K&moQZZCQ$rL4&(0zp6 z-^k};0}eU08#Gf6Dm#WsNSUF`+hGp_ zD;S~~KvVM*9t*a(Vdo8?eVdHF^)IYjF{|0+gpf zJW#6+a!LRx{RUK1A){WP5f9WIbC`C}a{WJQd4uf2(e?kM>;FM@%;@@mP#?DhJnl!! zQ3d3@2Wt6(T0x-FVRZdJs9iJg7*sA}pZUOE4}tC_%VUTK_gZkB3K~IgwYWIX9jwlSAad9vESifjB;uLDDA-F8P{kKG3fdkQemZ#m1LSKEM)(|5 zMuK>t8*gEG1JqlF)mfmp0rdu9{bpEMN=nZeg^R+WKv9V9Y9_JVQTQLAz~1r4s1g z7tsCfklW2r%O~U(KYED-Do+q871R$y9cdW7ePDR*Fo(5VMsFVgwE-b{3bbDm)XD>e z38b3M7>k3o5Fw+d_;Mir^aslSxO#n{yp7o^z$F4}Er3QLMrYay z^_~#<2f1_w&CrhawLu{;7|%R{^^76)C1kD+dus#KpToSVz!+s-9+bOaCX%08K&F8D znjj1+dxlp}8@47KedGYUuj$dt9_?WdmHFvx2GD#}2}2IJtqa;uk8OS$y*)eH!v?iA z2<>aZUh0j`XM@H7AuTdcc?`nCaUCr7*dOg-lhVTmjs79ZC*(FDW{HG-v=3AV;%oPh z_Pp`;d=M>g&_0d=hD-)f>zh!h;y06)^RBcs8#(=f#(qF8DQeE?BElNkCRljm>QQ2f zkM=P^BW#FX184;==%zN%YCF)mRiL=b$9a}KXm4sFLnQ-fg*Hf6CBx{9EWKuAA>oa^ zUue!?3|{F8YCRyYQpO&;pb`qyvH)Ss9v@_8UV{O7wJj*0fyShA8B!Q*8Pvh&)n+i{ zL+?$;R0&Hbu)XKD;9KkU81xvb8EP3~81fj@p{Kcl+%OP5B7C7~iV~Wzo+Bh&u!kL} zv;&1CXm-|>p^%{zycPl$hM>MV#6DPffL7w7hmjrwD7HZRN5-r11>wDuXa;{ud_L2D#X&-wzL=?w~X$l6`n+>HlXeVoKl z$WY9X!~nVr59G%r23SuCG}4j5kjkLI5W`Txkjh}f016|}s*Vzd7zPD~Xz;$lQt*yg z&=@EvrNuIU+^h$mc?5+y%qJilkk=rC%tzlX3TppAR{McW1kF@{))yn@DnNQ*vlSpV zXnd3sUx4hx?-P&@bQu)D{({5>vL8wq(0xE!J1~&}5&o#54_Z|K3VRvVk0{}u$N<_C zn#llKJ+Ht3l7-y|4eGsu+I=7wCo=dkK-7dVfa+h+d2z6rVvxK&11R?@Fo0@V5MLYW zL)3Iex$i(`Q{RV#djFlrVrs^D4pXf@oQD5z3XI))H**rviM(6J%!sA-(u}+{h+_N)}KH4An$X zn;X)81NEIyS0{jUgGywO45%Fp3Nujo4lAKSF#$T;G?5{XAq5eeWpw9rR zM~k36NaFgCh~3Dbxm3_zeo)N^I@bl%@&u(ske?tqo-he36F~J4?v^rTHz&(7(=yDJP=nPlTc}1WV zyPz>@MEe7k2O8H0wZ~w)YCz$j&H(9IqmG+mw;O$AnDEGUHiIPtq@`sB9-pU%>p`xD zm8FDeSXm1S5r{iLJztPNASVZbM*JbGg~;y-g4_c#AJO8Y{H**m@adeOQ;!nCW9Or5 zlR#q{!+&iOdb}f6B@s&L2zgkVA8lVi+83ZxML~BrWP)cildN5@APXxFAdU55jT3GD3) z(78>Z`WX}>$ZHcwNfV&*9oAX^^~oWlCde)Tttkf8B$*6}4ABe*44^q=Sc`(VHUMpF zVMB&0h8*y0eId9O2Blt5IxS`Zowf^U#eiB0pm8J6X)K6cH4stId;(~{3n2`N49G1~2w#E05!@OCjm?6_KtZcI zKqet%VJj&>qWH}B1J55K^0@+oCxZ(EXnYkkRtuRegv{vUGX*q81&R?+I~7v8g3eQg zjCvy6gjjO}T5+JjfRG{9wT=uhl?veVTGJUa7(o69xlMr~jKL8cyNI!3LcRyN8#E&Z zOCPASzKBo($%DcJG6DfwuaXHKfk*+Dc_7580os!fu^TcT z3tHJlIHa8!Aai)2HVnwbRIraBy(!S>2`JZLOC6XhU?E93j7k}j!E1CttGqz#p zwOj=GrWkx4J}3=?W;8&tOdA_Oy-v`KZ6(3b0J1=xhThf6*pP${C8lGuf#GQvm+_lE{z-zO4at2R60L zq-9#bmFGZXub`e7q+bsz1#p$8gu(+>s-gGMASE^awj8o7tX&5wL8w1gG}KlN5b7s^ z_Bn$_;6ZDPu-`lb8vR9&6;OX|wC4=!Q__F+IdWbEt?dALr8v3ZNE0sI>+fOB$N}X4?1%6wk)5IZuuMSFN0R91T&2Gm&t3r<0`jC`^zJ}FHWt#?Pz})bqowqVx#xWM*GW%we+}I zpcXIoRrbgs3mO>*jZ$Op7gvFA8OvwTV~B#XK>O=pyG%ycqtR~e7!mT==8O#)j8M)L zhqX>oPnd_qEhrs;dbc2q=;4Ce-5?%l-UE3*Hsp3!(0ErKg9ZcWHb&6QE2wM&-DsD} zpvM5J2|@Edpk5}iHzR?@iXro`hTu^}e7!GZxq<14QNA(?7JH*BqCoQ-kdaeR`U7Fe z9Et)1OjtS7scx3-;tpNyn`NeIvHr+St|NQyTD2rK&c+IVgTYY$lfCb z22lG3G^+vH)1d&KJqEcDVVVMiIs+`e5i6lUV+Z85G-=Qcy>D_k`zY=$(NL7kzJ0kjSUw970OJbrBeJ?n+gX(dMBTL%!eDP&F?e;!82!g4bx z#0KZMCVGxSjR8=2gWOJDxk^j3VQ~v`Z$1NTo#xwT84$?TGT55DQkmkG9qztu@fOV4yZV zs4W0l9S6!KptC5_!8f#nZe#uN_wbU-WH zhfce|k^wS*0UC9N?DYV(D?srIxbb& zrP-rnJfMChFA6cXfLH5gB=5CbtA1?bFjYUV4y*D zau9fTA!xUm83X8KK}7uyYS}|-d{YKf20aE71|tRw2FN%jNGEI+j4Oi+_}+$K25$yW xh5!az24e;j@cavCk3kXm9M@t7TLx38Xc~Bw2sAPZTK^1^F<~%<_U%FD0s!mTrG@|i literal 0 HcmV?d00001 diff --git a/test/test_convert.py b/test/test_convert.py index 9e3c106bd..0eef2f714 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -184,7 +184,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): image_path = os.path.join(_common.RSRC, 'image-2x3.jpg') self.album.artpath = image_path self.album.store() - with open(os.path.join(image_path)) as f: + with open(os.path.join(image_path), 'rb') as f: image_data = f.read() with control_stdin('y'): From 23f39982bc3d1322e2b86c932fa68e2de5c7f9ad Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 11:33:52 -0700 Subject: [PATCH 0839/2280] Remove accidentally-added log file --- log.txt | Bin 621318 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 log.txt diff --git a/log.txt b/log.txt deleted file mode 100644 index 9a85a7db5fdefe0dda854b3be6667ef1acfa18ee..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 621318 zcmezWFOMOgp_n0+p@boop_rkBp_oB|!HPiv&W~qEWJqMlXNYGgW=LizVn}2tU`S;s zVu)u*W5{I4V@P2rW{79VWXNSmWJqU7Wl&(yfa}$Rvp}X4F_bXqF*q_fGWauuKyA}x zP+-slLj{I>hHM621}+9ih7tw^h8(czsSH*Oh71Y}$qX3`i3~+x9!QNgg8~CKm+LZ= zF(@z?G1xJvf%VlueFAb<4nsaeIs?c}6$~X{n?R=2F%W_v`xF=;5TwJIArb7abcTF} zB8Ex^Plh~(G=_Yr3Wz!w2?|L+hJ1z+hG1~GB{O7#!!4B|1suwVumXh;W;jE_27j1Y zF$6P|Fcg8qE1dxpqR|Yo3_1)73_%R347p(2QyE+tDj1R(QW**uN*FR3@)`2LApmnH z$X{*@r3^U?ISiEyfefV#iQpIj#WBdOt_(#CMPUDWGNeFLh#xo{G8xJkQW=~X@)>f$ zX#kWW5UL?z2O?qV3%fr->8S{u3QHM^81ler3KYNb3?R{Bu**sq;u*>rG8j@B@)+X5 zv5%bY;u#8{YC-a#6od#{P@F?jH^_EE=@8^vSXxB58sd&jhAM_saC%PzyCD@Ero{}! z;M7@3MCu3G?gkD?M}{1RB!*IkT&%ePpDRE)Fqr`q9w5Jh(q0kR9iY$xrA<)$LPCge zZls@kK(2|Q#fZ_&{QXu788Z>8v+yN?|a=`7*B(P{ULp%d020?KQ zYL^p=$ANJf$X8WFr88Q&4^+B?dH|q!gtWjxsSH#`4XQng87jf!F`yniEDwQtdxUFT7jQ2hl-5E1 z1C?|s;Ql#ilmgTmBfj)T?XeN^zbkYc1k%R~f{qU4lWlhe!Fq|hHiAaBKqXi{cqAbc z?0!(+57ZXSV*r&Ept=uKSAbFlC>@tDBr;?}>sgRa$Y=nf>?0InZVbT;jtrnuhxj-F z#c3&Y3S5%pcFz2*I-LskTMoDl9vuHDdHKD!R; z0E;tF4}!Q6VK;_E2ADY^3}GbnHZffQ3JuT*Ca5h8>S;qpsu6Ahjc()buTax9pqM~z zZ-7z_Xp9b2LxRRyL2-l_(FC~_GR6u~18PS>Mpp@!`Sf>nCU_(x9^8V;0grzdG2}9U z(m%xY#o!SH&`2(5?44F&4k{7Kz`Y+(P6XAHmEdu9h#Szu9@L&9oD)DjBTz3K)MtgH zVB$+>P)U^vE~`oyaJi%aT(b~vrMbb!1ITd+Xm$cL-vP@1pppWVOCco~={eM$As;+< z0y2wwZlPc97)bY1GoMiE4^aI88rcK&|3Twpp!PawTmaP9h4joa!8HlKQWDhm0L^EC zat3HN4>pJ4!T`|=D$7A77x8%p;VRtj0oD2-7lTSrP^k&3lS{y}g1GbZK)G~a+y)wR z%4Yzz`*Og2Lr{K)#0aPb1!||IF@Q!G@wL{dA7Y?V8P+}mwOk=?gQXezrZZ4o0ZVJ3 zk_^-{0+oy~*U&R1L3&o8+7nb`W`bt{LA4iXem$81lppiJVxWF=5qM4>R}D)2I78$@ zP|C??0NDU)Pl3jTL8F|Y{tbOoQ3(TRq!K-}K=lVG9uvX+d3wekXsi%2a|=p8p!yUw z?oi88P!A0>?+y|LjnCj~4}roOxpXaH0L?#Cg8R^*k{i_X1epPv;msqVr3@O^0J#;G z)Y)Eo1jpH#Ws3OgHkT2W(DcX!PAq+l`@I1 z=Rr0gat)$>0+lVG5oFK`6HrKeO-_O?&X0-mqE6J<{Ut+VtU2|#08*nO2nuLX!R0ki~*ERK`X;RD{(Tw z?L|l}2GWCX6%*y904ObhRuY0n)Lk$EBB(!+ zPSY9_RCa@A{t#&vxmPea>_@GU5qXN1r8}rCQvz-ug5raIwF)A24pixd>;gnsgK{pt z@+qPR2wIH`;$?$po)F{M$ZiCU>w`vxA@Kxi3&exh?}B0w#Dk30mxI?9=P{6yn;y0& zL2ZeVKl%!>2b3!d;j8{Z{RU!vNe!DTz%%ajvk|!#rJt>!Ib6`V4QQtZeM1=3V+NJD zpgk(YjU!SXtDuo3kWWb|)v0SMXbb@~mImtIfZA-JaRmCsHnRUgr3$DIM*PSh`5^&m zD}wqpko9-8_c5r>1dVwRUyhUSJJ8$;Xm1e&1-jlP0v5qkI*lyA!!Kx3bv zz6m|!w3MNM0oDVeeF_4FC!{?F8W#f9MUWDjSerrXz(BP&@hw2aSS0coB51q{lutq9 zxS*8_p!HS6x*>oe2fVTrWHKm6RFW_{pA6OsYM+4Gv5h(f=UBWOo3YXpp_w@@ikBh zOKgl$$4yD#ee0m!F=%ZUsB{ADCI`(q#Y6XYf@*fqSU@TRXoYkJcn3OhEoJJs5VSS| zl-@!8P0*MIC{=@El)m8vYE{8jiGXq)XvPG&9ZP)qO`T9dEe$}ubkMj5XtgVS!v!>Z z4@xPZ9m}8<;qlLO6<7*y+n(k>#DK)b-o zp{GWG=z+;&pwS+X+dwr4s5hJpZds%6lLM6upp~rTx4Nm5_8}`bZn`hv8k6u|o@Kx@Asr2}Yp703)wX%6W>Ku#f20G}8HI~j-iu7KFCz@W~M z2A&VhWzYrhz*c8aU;yog1od(f89=)NvAM^SAq{#alma+6fND)pNe3D+gscQn{rE?Ur-4QS6FC>*ev?+iY92o%a7^Fez&Ky!p3y`WYxXru@d!i4mK z=D{k!HiBk5LGA(VEd%)q6lb9H0~xE<1)oI$lLNI`6u>)bAahEv9jVxCgM%tNcRF#d-`*45bX9)CTIY zLPoZbG6_`vBf<%mQ$Vo=Y76IqPhvyZ3M$J$W4oZ0Rv;I^QU|0o0_81avq1S3l#4;` z0nI>wbb$I;)N-2wbmtz#c2IcS36a-q^1xiC8_k%`RAaiq|kq*%L1fZ5G z$amPseqiIZp#CewOvIUYdf+wspwV2AEaZd*P#yq{fDu10focP&1ObHvDAos?i$EhD zpfCi@u7cL;XX5PHp!x~Kqjspl;u8`lusA?=VIp`J3+RkOQ0@V>D?zKyLF1I5vT>lo zmaw~FDj+Epl=ndATMoQ?L1iYWZ47Ejg4Q2_VighYpnL`?6$i?t#S9q?`3#`BQ&0;F zG>-=Ae}Y0Yo&i+mL&kfNU5%?&Mpgq!U(`;$q`MV4WkYI4Q2Ne+p58j}VLo_67`w}m z!*ig^GDK=1?AE~(_mEryYVUyBHTd%qOckuggz=rhC(e>uSHg71gHK|CjMRhX<#3W?Z~(2p1NEjrwJ4!B9xPQ+nmRzWPZk4c-6+WB zfldj<43Lw8ATzR{z6K};Kz$hcq(sm;ETA!QP`ZPK1uUdNbu+Q90G&YrGY8bt&I6wh z2{M)V(gW2kp!OB0-41Hkfbs|^eS-S#sAUBx+z72XK-HngKn=G-`m>-FNg&ffr9Nn< zENCAWC?A8yu|cCkpcWUQo&qei^%(pZQlX)S8iGFH^WZ__ZEoPx&p>M}h!0ibTnZY4 z#Meq0EUpC24uEnn$UUIZM^e%#ZNeASk_D|Cf|O;T)8s*;5TG&?G@k--V-W+SWsW;7 zfJ_0E%btCBn@&cWDWvUZiCLN0L|J^5{AU*O6)EIjjDonPJ!B@pfzIy?Jnf9WAKC)E>{&p zSB;TVRv^+Dxp9c>s=*wOm~NwYxS{qqK%-I>;L}Y&sU5T)IR|`~39fvY1U*kNl|hdI za$^T1WfC86==Ot31<*PakV`=8$Z+>UQW)rAJ7|YYCHO8Id~F44y9BiN2{iHws(;hK zyLbmGOh7FG(5g$w=s!JD1ZeIRWE*HtENEmup8*sKh%p0Dy99KqWhnz_G!J+Af-6oy zEw>Z~U+^tW1<+Y$;?pZ3*MZJ-1odS>_a%Tr3*`2};bLmVBxT_T+EV~JwHee;1huUb z89-}SK;<)uN3p6JQTU9_ziRcSnDGf3a zG=>0beG#9|Kr@-3wi@!dD`@p7Xl*FyyaPn}2wGzUDm6i;af5oIpwW9!9|N==2h?uC z*CRtML#gfFT<|#_Aisn5F@R24fs8sL*Db`Bs?>HHrc01x8q{J2?N!QUz&-ax+pq)e z3;>mYs9^63`4v+BfyO{VIR%uzVJ$IG4+J!7lnK5I4OITp&lRAOr2;(e0dm1W z*$e9XgL=lGo*JlEOv~6uj|bEch-WBc0Ih)orAN@tX?leSWb6eL2B7moK=mXjg@9@( zVq3`M>CH8*H=9w;6_H590=M$Z%qT2TR-uc2ic0FCN^$~jOhgTfe+D?x2J z@>}ENggXRJ&(%rb5hhrliW)f& z)d8waKyxXub{cX>f_enk)=GiKCPDQJ#5ExIf!1z=#^Y!cE}*#qP|X4I z8EB3G(w_#6#8ao-!t^D`PoVGx`4X}=5O&f%$fuAQ9Z(#gmg}_fJ+fOsc^6irgV>;Q zg;rqz^Ear61*$V}&nBU^VgtZ;w1WEk!O-&{LG2&><8hcV018=9=?N>fK&@%WiXhOO zA*lBh?gW({pcEYs-o;4&_yqM_A*YamcEEsg zG-#z5q)s3%-%uxA4P+RA$}mXJW3Z)aP-=#i>Y#Fk+%g6cN7(vjn7JI)UQnJVXN(fR zt;lQL5p^xH&7e^&Sj`S;jeu$z;_Fay><6_zVJ9#kN-|I%1+ zLFnNk$mlyHEa+`F=6Eq|?FX^_Ny^eAsGS392ZHtmf<~G^rytNe46wNYRP%v)!3LlP%eb{9#l4h+MmRx#31mU zmykKiVg^s}3^HUU2xJPj78drl4rH_oq7#%hLGc6XyAT&5v~mS(l>(?Y1@aHEZ5~>= z2UM4Xb}WH*=MghAM=f`NQYk34g665|8zYduEGV58Luc9Ooiai5i=eUJdZi` zx(U=%gSiIMz5u1%fpigaUkSv9jL3mPij*=9Hd01uFAm$x!a%tNRLg*B8&dlv)Cvp4 zDjLuT|3HNTs8#{3q#dYGAisY|Sv-KwErINSQa~GV)MZFy&;;++2jyT;+XQlI08BL^ z7lC%egL+kwdXV6SOXjB^1mnmjI-;M6d5X2C~;Li{Q-Va5t{gBZY$etb0u6@`@ z5G8JLWdMzNg4#ErIv!NJfl?%2vjeF#tadA^+EG$kn-*g^J#;sVq@0iCu0YS)5X2Wl^X#%@8QxuDV?#0Qnapp|qWH-gSv0ns2| zC@_H58iD4tbfIJ9p!F!A84Hl_K_P;C)&*(|Vul(u-33}>ih7?i=sXC}2|gfy<93w` z1L!1%JO;?TJ#q@pV*su3%z&;2#Gg8e^BW}XgXYIU=?By@0);7PH4$Q+87R%b(kLi( zfLsSlWuVvtjp~BJ8J3bjDFq@AG6%OmkzEMV3rPi#xmyJWNZAfb6`-C?E(3@KG7n<1 z0(gfhYU+f@fYd;I1xY=mpY+ZUV(QsHFuekw7_y+^~Y2?EwlO zP@V(D6)0Um+9{ya1Ip8&bOp+#pm>DDC}kxMD3uYHwnkkCI|B@qzd>s+N5c+Mdq8q0 zwz33&&KL~gM~MqT`42Sb4;nWD)l#6=4ul4cPJr$#hSa#A-E^S6s-X4+_VEf(ISATI z2HGzM>c4^R5eL!144_@PkUMTc{W#D}3a-&4)H)gAHqa@7pfMy+9}v{GMm7<&3KnD! zsC59-p$8tlg7^#5U9JqE8}mT5DX6q7VZeVzfhPlKCo-r+1D#>0zyKMu2i4t>HCCWo zlXV#s7-AS=80;Bh7?K&R7-Hb(krXq;FqANWTA?WnpxQAJ++NIOh=H!=2Za`Bm39nx z_Yvq^uN<%rkgE&8EYLnU(0D}-g8@S_Lkfc)Lly&Qr$sv0B+wWf_MQ0?gs}%0+{rtSV;!)gLJg6(p5apnXlC^@T+YpmsIBJXgtpe2|~tgHPlHje3GgNKpF_vGErEIygTq~j zon-^#Hc);CrSE~Y9d?ou{=7up)B+k;1Fdc@2d^~*t=@sv-}H0^tZo9G=K*TtfNC<( zx^MJT??HJAvJ(ZAV?ZTzJ_Bf-5h!)zaxZAd7GzgDq^1Gwk_EMMApJp5I}3kn30Dga zv_cb`mFO`837lnY&Muwd!3_FVs)PDqx$AIij z2j6f7Dm!5-DQA=>$%a02Ce z$gWjLyB1Quz(yqyZ8y-!5dQEiW&rgxVL2C);!{aji%7^_pna{NF;CE%W>`28Dj#U; zCRlG^@VE$+x1UtUr7%m zSULvn5eD_)KP|@SoR;B*>H-K4l-faKRG>A0pxI4OO$2H+5L=p)m!2SY!@>eo4naZ$bV?^^1`{-o z2&#Kv`w~H|1W=m-R33m_4BG1kI$apl$_Lfw^b0kJTS4<|pwI%HKLDx;K`l~HNPtdM z0L`1=yC(&fZy+@fNEhk(5nK3Sx(PH^2g<3C)iI#3qqjRjv+|(PU{F~FnvX^fAJBd+ z(8v_=wT}k_s7`>SR^rDEh;aifPKZfIv~vY$ObT@VKPXj!+FG=84QM?oXtWxX(?Rpd zpdAVW5jVuTgZA-5tV`$_N1!zWp#CcTas)zx!{w0TmHaDn* z1^F4WVi{p8arFcF_JZQ00KB&vR7Znc02=KBoj3^U#ezZvG$#tmDWEe8Kr|>V6Bicw z;FDL0FF}yq0y=*dvg(r95Fp<+%$5tN?F@+#(Ao{c?LE*gZcs@=yk9}JZyp0^HW5@i zgJuCi`l;jBUZVdYzy%a}i}5 zddrgI2H1BEK6hXy)n2sCO0I(-(@jt9jIXj~k$VgOXW z6W<;ry>vr_Iiwv=ZaA6(&`1Ras!R5L&km~eIL*q0BEcOlqNytE@-U*{uAL~ zts+oQf^-*w&WHx}3_!DKh_nxB4T9=d(3k?~v_Vivf!glG{KswsP_e0 zUj<4pgT<|o(g0K*Lt+{^ZGcK5(AutSa7zu8svu<*tPC0qVU2J9h)2I8xEk{0NQ_%%rLNFf!iJQ4G+-%z%&NX zcqpQ#1hsvTb0?_mBPB##}(-8jw~5qQyvDP6F+oEny(f zZJ@pq{?T~IehpB2F@*sXZiYB-poE1esGSmB?4^Zt-dsl$&gaWmgKp_EZDUsR>2nXMh zwVw&E908?tO6`S(JTak6x?P~M2h_#~#Ur9zA#N0ablX6+FevrF#%V!44N#qoyb1xd z&IB|I2^!zU?Prh)pmGt^X91OwpcPal;9HYIz&ELb#E@5XxiNt1AIN+ns3Zm1tciAW zI-2MSY=|3PcKaJBj98KRK#8#J;3%15AD1JuT(Zj2LO zn}Bi{=sYS=`UkbiK_NzXbe+`jBHlfqo#~+QZjd`bX%*ov>ZLW}U6apH%m6xd4^)GK zZYcoO^tjxCtVWN)13cmiYFFh!*EQlE$3Pz0hOCm+V*u^z2Bis5>IIbupxuX{k_nQk zLF*hra}%JtGY@UH0JQrSv@#r2*CV@$`tHWQA{62#(0o8SxJ^V`H;@x{s4fKUNdoms zLH+r7@SV+|5nRytP!R)Y%_wMBHmI}(?c{=-@BvEwCE(NRAtUIxLpGlQWELnjKv=}5 zJkZ_IAibdT;y@!j1L*=#n!^kaP-?_pp2FNtp1(n<9{0YzOa@Tv3lv|Vdo4Y{r)Q@! zAlG)phcRfy5n^2|s8)oG{6X5DkQ@l=HzJP#fo5Pqxf--;53-sb)H21D0+4M$=mfbO zH1-8rB~!xS$N(u>QgF7;u;(*mvq76BNd|44~Ww z%7cT!-Jo76sO1l8VS(lZKzmGwLh2yo?!g%Hp#BbWiiEV%k#i~RE@9AWDBP_(WHZQ5 z)u6H%wWh%CKI|bqur7tQ@jz`&Q22pvw*b+Q(vG-%1)6C(bLTpjmKGO9A96P|FuID*|bkfc9F0 z+UcNqe27blsdFH)<_vAsfJ}8}0IdZC&27MHFXCel)pa1#AblB7IXxKM2g%*2bs?nv z466M=H^zZ_TA+LjidT?2Q12hK5(3oQfP@P!m9W~C_)vF8+Wq4WK7ksvuMM>J43_VZ z@8u>w7O3M(#Qj%@k^t1B0M)jj6gRm2iOuz(_ypw;Trr4<>!IT}gqsQZZt$c}(5MDv zpE9V`2Fhum6gIfS98?}+-}_Fx(gC!ibhwrX^zj@0N&))&hqgJNdj6q2w^Pq8pm`!t zeg&14u<{VOP6O>61MM&ZjpTsVCc)ankop)|CGn*davcs@9{}ptgI2VG+Gvo`AyR5~ zQ11ccD$w{HsQn2F8_@X$pb;3*JOQ%HL9Jy>+lGS6%fPoFfkFr3Cs6$`7~=r6voIfg zUJSPIADpfRwaOtoSwJh;vcM-lfaZxnt4arxi$Q0Uq%ssRfLd#yS`akm59&jJQay71 zB`-a@fKOdPHWShACO$ucVjbib(27UUs5+$VfVmu$Pg5}L0jYn7-xg6AAr(dii&wZ3LK-Nox zM$SR)Zq%_VSega75k0q2%e|nJ^FX6Fh_O-Pa~h$PN`E(!o=WNO#(_?u#K$=CDHYL% z1Eo{g7!_!Q309JU%3aVnA}F1a7v`=Eu(kD|T%3+`-UTy!ak~yQrwCdb16%J38W{tv z6$Rxu^nHskpFl?V29G~LAqy%yKx-2qA)knIJsa|STv|S1LY;q3q6g76w;X5_aWa3RC17F`l7{A(Nqi%-R#QCLH_)Xlx9$(v92_4YUIiVFoUDW9A)HS3%Y! zfN~aORtHp{LiRI}mv5-!D$EoIs-sZdI*{(8B;668&OqyFL1hPM2LZ_MpiwdqA9RBP zXw(FBG6QJl6{Ic&E$u<}On~YtP&*D3o}dtf%xZ#IAQ9AZ5|k=IpI-A3K|~)-QNIO z*Me{@dG!({A&DBpl+;b2o=g!*BQ*u!HS~~q4^Y|yl`V+)M6`Lx3l-|sAPARGTF+6> zO^7r@ZVD&QE!fJgfsQj`-83+mU`hb`x?R4%ICXH-KD)Ep3C=g@fjF$aNp6M-1v27L(a-A;ql-we)l? za`{c!m{$~dyo~r(188g(bCoH%eO%DKY{(omXxs}l|CNI_jt-iWDq%n$d&4${h0QF` zTn1<)3p750ea{?nNWx|?u$hG1$004WK&!4mvuL2XRM1E|sD=Ucyg_{h(1;-^>4thP zL(ZF^m2Qx=OUP^SKyeBhEdYffX(N)LvpYaxiCFvN0^To}NM?Qng%Zqtu#uE_21vM; zGJsMDX#5;9t`1s_0h-SuEmR@<6DV^ps3ZfGXrOsB(CQRW_(A$YkU2EaTp#HCd{FHG z8vBRMRg%`yr%u?y+zRShgYpOFdPh*`4qO<5cCvz6h@g}Ss<$BP6+x~BwRS-10TjB3 zwYmf6Qc#_XzSJrXRAQzx3??@t>MT$w!g3U9-iMqV3^^}#Ao5c&_R}1^R#DJgDX7E;ser7ph0Okf=GH(ZK_vrd2Q=|+ z2F;N|ZZij+r471+8Bto1wJM7=4XXcB$nFtXMMO*iQdI+F1=s{@{ zQtQ&!eaNdBKqV`vR3&siK62j)`7{PlT>)zEfLfNI(OKBJ%%IjWC=Y_t5a?7aP~3pV zw-DvVU`Z{AbdBm4kjp{sQb^p8H(N&AbcAp@%$=YyMZ{PzC=O8L4b~4GJb3||A3&=e zK;CcP9WrBL^>KQwHWa(MourF6oOm|4P3bo zN*~BBfus}UHV>!`0vUY*)r+8WNkJ?7Kxv)ywfdm*aFJ~zek75wJ3%E2sB{F4yus=x zP|62|J1OIL^mZet*9nGn{P_KcUF-%fy zcV+;^E~o|r`46A!Ov&lL0hqlh2^Qkk63Bki`JmHKf1*TB!|c--Fuuppi^a z_@v|93j|YzJiZC)fr5I`pjik|n;f~_0vh{FWT=GSnL+Jz$VD0f|rCp#rgk9NR!?ESUk+zXY`lL8CLER15NN5knrHb^est2r?ZM znxHYRB=8O|(24f(43L``Ky2Fh6lO1N?V*0!$OYel335HCR3NUtDqu)sfaKZ$1~-Oa zGEe3O*#|05KxF{vOlHt7M$jBFzOfU2Llpy7X=1{4Do~CGnGNc#>oI_!0(cJ>%yv*p2c6vmu>)iR$Y;o|K=`tlL5Bfk6Ud$A z3?Q{2UxQBU1&zGJOaQe4A>oz;Rs%ZQ3eLk$IA}BNvVOS2nPY2|0Q2c{p5ftj6(J)Y{fz4fR z44^%cpfgkzpl3>fd;$pA?ya#n4o*;Kr_pr^)aCM z0=W*mt&mie!~oKf%>Y>;3%acclp;VW6O>{=CV_TSgK9?5jeMXu1FaAMts#Jg1tgUy zFeE_NoP$y*s67j6>m`8Ol%RABI@JplD%jlO$dJyE2o76NoKoLin4t%97dDrGLJU;L z#Dil3)M7=XSX`wnXiWu34??9LgAaIreF+01Kaz41J!sqrl%heSWT2h=pz;G01E4ki zAQyt-6k!{vR#gD!M)VX9QVVh!XgvpLwh}a|2`M}2=NI(y5;HD9r2wdA1f@GzS(?NE znqdW{d{F8Hr9$NN49OpmH58!xFF@%El-hC_6c|9M79eg7cu?^*#PTxf!vH<(rYk))|i2O2`VEY`5%(| zK)oB%QUatD0kw8vEgFzXpgavKS3xNRRHl~WY-xkiA)<{8I{6#aI>FVVfz=F%l!&Sy z)OG~vhqd!TH?7jwJ)m?0=>;SDRiID+^|?T&_(MV)R11R2Tsb>Y zJ_z@K!U2?9LGx{(yDdN~3qfmz5Gp{m3Mg+t@;Iml0o4hh^Z@b!ET%yzYH+w4l)@n4 z37R2AKm7>V{m5~FyR1UKTbQUC_uUXhe?CoE5F}8pvg^x)&5mpjmrJ9|Pn{ zL>LcLss!bAPzwn(lLjh1L3xTEZUL1lp!N`=^oeIkVgRj<0qxeOhYLXEA!v0Ds1*)6 zUlZgKP|F6fn+7r>0BSWs*8hRR2bOL@xOQ?)OQu=bac?ZOi;_A ziUHD-re`=Ij|UKEFZM7%zrB+9m_oP!5+~><{DV>v?lYRuYam*>4z_ob*fc|Jw}9?O z0fiB0%nOtQK{+23I-pVvGDZMfM>$wr2pW-rto8<#!k}^tG%5m$anN`SsOLN|X%0Ok z3Ar<#!HDQS7_DO+;Z{(60lMK3G#3M!BLFo*SqX1F8!_ zGX{_t0`1{QWJm(%5P#A$`p+If|r6Lf2pu-H* zE-nGb8mR0B^@c#BZiB^jpphKVEE#Cz2Q(i5Da%1^QqUMHs4ol}1s|C59J|{FOUQxR zu8>|Uq(=!GiG-A_pqdagq5+z3$YubID}ct-kX2HaM~Ls8;BqHq6biEU3e=_r^>+u> zeV`dZP+COp^TI+CHm?W^NziyYXnh|2LlNOh#5x;~U zH?Zyl?U2o60QILpqmQ5&56}uYP|pOik`FZJPOn&nrD{;g0qP?|MrJ`hBT(B2a;gGo z{Q_vk4rpc)G=E5cx6#{XQ0W9J2Ou-Fh`a_GK>&piWONo3Ca~}WjqD-D+=!pC!rt>G zzN`hg6m!fk9(-mCsCEUFZlH1&)UpH3mqKC{G$I0;pQcw#66?xh@c9nK;1wtXABLcH z)u1^`P;5g+Y(XIjS_=kRBLoWL3g}4`pk45wnfQSYPwXy+^eR9n8-Y?NDdVNIN}Ztm z3|grJN{0|PL3$jJKG?v=Ji>jT^;)2rJD7At@8B`8{!Wh(Z%>$og2AR7;KJx%%5@;PBsLcc!4F~lzhLaCbTY#Wa2ekTu zo~0pZb`LTa32NnlLK?I(qlh7!0aWuLQW&U40j+lg_1YmdBqIOPCVgS9!vf8ugF+0n z{sNzCVY}%Ei2a!pAucOd6fP@M)ErGmMQUT%Q&06=47pphSJBPEdj zG$^lv;xHY&9uCyn9Vi!qQW&I711niTW3r$?DkxkpLVW86Jsfen z669J)>Iap2$#ixhWL^Ri&!Dsh%6*{x2ugpD+5)s@4{{e{IzuV6hX<-p;u$I#Qo;N6 zh>v;D90aKD1l95g(?Gr_HDvL-8x-20d<<%>gI1P8ax=_7kiIIY^g&)FOG;~;`u+fo zS%dc3gTfwt{tDFA1?5Ok+@Sga6ow$TWPo?DL3|2ZF*T5}0!lOFt@DJO;7i>!f@uAM z$}~_&!)6CSy)jT2!rB#}&_}dN5$!3^hzw{vp59>!ig{2;3vvl)<_pyO0nHHSF_bcZ z@+7SG1nmg}jn#n4W{@92x(w9HBi42|2GBeVs5g+w0MbW% zc>v1mpjI&EIunSAw08lhl!1&Vg7zbT;tQ4sLF>dpqb;C#1f?xdUjfv+0qq_t1x*`NLGXNUv1-TlL z17LM8sC5CVlZkgXsGpn5;Kl$70Z`irHfH6^0NDc%2@!Jr0xG2{7?9mM7+eObkwEPe z&{!kLZJ_X{-ufU}y#vh?gYr43b_3Ntq=qEu3=NPO#Mexq7=+mjTZ4?;b_B6OeQi+c zBfZ543rW)51=$e|ni~S$$wGYG`7nT5xS((aonQuP+e6w7Aq)_6NV$CuwBHtF5~x-L zjTC@dilp?#sOc8aEij;-4QPE<4uSKyK%-H}r&UnX9k8|({lWtK`Cy<`OQ4hv8fyl% zr$99+t~N9A<13(3EkULdpMMbU0OcZ3+X<9!A^i+U8V0TTNCTfd06Kppg&~RPaW>Lj zlgj`~tDu?>R4c>AK|t*Z(0MPQK1~69l{dt7#OEwuxY@*q4zhb7;RDLiu(454Sb)ao zK{Yg}mIIv?MO;smQn!HC?8DY*!@>d7{sQe|0hMxyQjgdYnD#CLor4Cc-)QM3Q2qwZ zXoG4b&`AfNmL2i=CjdMu3u+MrGJtj^g34gxQwy@)pdJ?T$OdH86=WW$M+zCq0F5OO z8y1wg3{<*++LWNS1SpS#TnFhZgX#rHY5}eJ0__k5l|qP+BhRIvc55&LLND=Q2yrPW zBtd3C!U|C$A=;FnG67U}g3j0h#WyM82r`*G*A4#g1D$n)d|NLh$AL<2M3{nFY@oI8 zmEb-tC_R97aFLoC$q&WB=qB`WcjP&CP|1&+J3wtt&=@hO+$X;N0p(!w!wjGM5To=1 zoj-8dj~tqy_6aB-fm-CSxiU~$1ZurQX5HzNmvOljRQ^GFU!Z!RhygTO2XZT@%mmFL z4TM`!Qyi$K2aO#eay00iP0&0SsO1E5|G<^sgj|X}6hYw%T7wD6QN)i_QsV+sJR?kZ&ft#${k!hp1aKy4||juO!R8&I8I%80S-oZpFTb4m6Gqsw+XGv7nYE@g)^K+>BmF3{04Uauuk22hDka#*9E^=ip8Sp!yxQ z@)%MQfqLYi_yv`v$S3o)Nu zH-SP1)J6w|47T|_;`>^Zx&_p8fs6_udX|{3f{p3Y)?J|92&hZ|wXm5L=96)2*p!li)uRQ|w z#z3;5+v7naqM%+AWRwL&g7kx251~QjBB-51eCrnEKJwfPTMGqpEh3yi?f{h>kUAN} zLpGiEp$IC)5N&)!`;}OmLm5D$SD-c-s4RrFQ$V2viY3CamQ2Hm44#Jd35Zq(aEKqr2tgU`q(ZnTS1+YuvNpgILI9!@WxgW>^H zi^0~&fO0qSX9`p5b41S$H3neqK3awXDD8sgok|%%vpJwOQlJr}RB(R?v`PwJi3+-# z3DQCX-8|$BUP}t{0m39#By$L*$smS&@X6u|44~2Kbnq$fpjAJhvJKQb1D%}$+CL3i z%@3Ks1GU&e_Y6Zuhd{e^6c|8aB@Ccj3qXDW-8lfdQ2|sEf_8e~Itd(u2WkHtJJ z3`!%QbF`3G@_^C`vT3w&1I&$}+dV+%#vtw!0;O3wOd$f*C-y9O#@|69xtF4HKZ&NFoEMhYeb_3mQcQ zm36!fT<}^2bPopTyiZVX3Dgb*?Ir@eOYzESM0oCy!RUp5C z!X1<^A+;%}27}b8pczq+x^!?Y4OwRix)lVp8XPpf3%cnCxyM2qAA;&-$h-&0WuV)B zG8jr2av4Bv15j%Tw5kde8z6sy!Us8yK<8b6`q`jx0_}bQ-Swovpv$1k08$0oHwe1L z1G_3vUlqdo-9+=EUi1cf*$snnGLban@*l?e(*&8ZS^P0M*B!5*k$2LGleqCLNp~3K%l*_Sk6=N~mrFbHHo7Kr5qQ^*sIK z5;>fZ-3O|5AScw)-%YUDr!)q9Yt(2_27pG!Gr{-j;mYZt-FTpTpb#m_4SXUVXs!*E z(jo0RSlb(Ygaq@99MIS(sD1#o@`y{R)OG=AlnMPDTHJ9?ZQCJjBhac%P>U7Rt^%zh z#~=E>3{F^X7AHQ;LA@JLI|0->fy_&RN_tRF1(Y*Etr$@12bFAu!huqkV73uJZAQ>e zRY)t6w&4I8Ee6dXfVuqhL~B1oYz4JJKxrPbh6dyckPASqN9^?kB;8RO-k=f= zG?N6Xxsc--G|LZ~%>j+WflfCAjSkQ@>``3;DFx_fBWPVasJ4cTP(yYZ)6;fPUIX>x zK`Tt@XD_JD3tDvmN=umxpk6n<(i+5OPFMWdP+A7rpNMm;9TXmV4Ajh9Fgqdh zx{&k*n$ZB|Jy2eQ)RLh559tMf+y_!i|4;$h3R>#}q7g2H)rrXdpmn*3Tq1x}Wivl#ROFvsdtxC{|)1WW_ zt;(gR&7jefWCqZwA)wL~RBnJ;()28~Kx=j&CzsILR)kHc!NLn0?o_d?hAp+eB_xVP;Ut|O9VQ%fYvQ{#Ec0j z#$jv52!{shZcO6)h}i7|?G^^D>;lz1^syU}dgyH*ef)~t>H+0g(D*c{Ck84(LG5My zz6PyS1GOnr89W(W;4_GXM_n*&1@%fnqm~difNV$JLj#c|l*Xy&8c>fM)W!m>AOo$L z0p&E1%cvO|u)F}8X9Ud}DuCx|OBf0mKy$bt9`c-z5(B6{1Jx{`F;qmVEM`z*0L`Cf zFyu3URv@M_;98qREBka96rdw^kX|%oP8T$n3!16JDmYU2z2Vunfv(E2k_KMFJ>4dFR6fYw96d`>uBf_BP6M#MlP6d=8bo#nK* z9We(Qh_6bCxaV<8wt4*G%g3K>p*b> zD&;|Athjv*n%M`9)q?T}NEc{SmNFYbr2?o01u_{lDi7NKkqDlX$2Cp>Qb~O`fcym%Z*+wEzJ~Q(XzNSF>A0Yj23oHTN;{Ahx}Y;_KrJ6o+M}&2KxHVX zodwF>AUA;A0+~~T%;$k>Kiawgwp$2!%`~iEPk)<1^$O@Fd(d1k{&p2L(jBNg1MTSq zl`o~>(G}3#2dW!DyD;$eV5sX3(5?&6JTC6JF6xx72%m#aw*%z`(Ah1Zk`ojbp!q9M z`UmX`0p$VE{sz!_g`iy)pj-k{N87Z4>^{)yG0@5!T9&&A`#|+ReQP?PLdcX7IJAsgcJ}TT}GP zXQ;N)r(8uY$w4C>pl}D}VoAgVRHwq%Xefu>6P+O?F5ZOg2ETnz5ul|Agwy&avhW^KyIUL8G!66`j@nXY=`u7 zKxHwgmILJ%Q2&;e^$xO&Ky5)#eg)+RPz?*pvxw4hpz{i-1Ev->zBY8bfQtbq_wn2FtG_nF}*?>x6P%i_t z{|{6@gIeAodD{9MRN7Ft=SgZfP_O4n4VzJWeWdokNOb|CzX95b1Dcq1sAb&y&<}MsCf5TC$*U2i0Vta0k_FpgsoWJx@wpMa`ZkHQYgJ z&yx~6>6P-3QvqgM2hyqowRvD8il9^havN=PA+oFJU(yn?o${V1B`E{c76j#2+Vwms zaUH1SCa>p7s;!{80MO_N=-dOyntRatRM7l(DFbNz0ca+k)NxAC94hg1zAzVn_8g=! zfbPXXxP`R*L8`rwvz0)75=dI4Yz&+<+d-pJpc)xeSCBUrO^JPo5XKhUq?XW>xCA++ zli%~F)CH9H`zdh&q<)}fT1QQ7?BK{BpfZ}g@e|U*12%R+y;>J?ng%Iz z_b@k5I(|Zq&D0!0A>Dq|UM=Zs2r0D@f2@;MHdE>rEkPu*oUnpO3KIrC3X*Nor}l~pcyjAUVm!!N=XkD*!TzjFrjVCz}!Ios1N!6 zCV$+AbUQ)g5TG^|XdHslksoqwr+n;(Qd`McPeZz$$URdwo^J5L|J%%TIrzt3K|im#b^*^t^<|aF$sG)U@o9^Jcx9AsW}=%s_m4H1yN=n{@5n1gr>|T$SIxNaUjZF zK1YxqVF7COgK{XX#*!#;8>oyXXC#SKJ7J?Z)UESPs5FiQ+RK>806OWC z^m2kUH&A;_i4@zZF{VVmefVRZw&9NIbL2D+Y7LQdE+{DdlOGl!7f@qNiF_B3H>O0s zedLZQkzymQ#*|2L19irfNU;%AyHI;fi4^;(Ii^IZy_AkAkzzlhM@{W9CGuQBe!G)A z`{*^MM6T<|8&e|BHf$|UQhV3r**uW7Dk2BaW=x5c5P^;8;13U4#tF;?l#MBo<7djo zlt{4=G{yjFyMTO4+4--ewxCe=ZqcW-L$#CKQ5{l37`Yz{>NA2uoED=x)QMb|P;dN+nl3;s`$;>CnEVn0 zR(69a|SYXVrAe;aO5z;<_gNk zXQ+{KKy6h}KBwJC4K-W|su9Q=vmw`Z&?pUc&r0@ZNM}f=(wZDnYC+QNrRF*uQf-Ho zqM%+p=!|N_j(gDQ#h??fiy1&SIFnY&lI{x7>9wg0pqdZVUjX&zX&L6I<0$y&>FDWm zV!16sk(g7ko$m=sJSe>lj1o5?>KKsgK>d4iPp_tqD@qtZcRsDijw%JcO8cu9@y-rbkvQKumJTxV0jVL7XXzOh+7&VJ%WMC zr=YrmoDnus!-KjjSNs_Yz-w3Nw_=4-85^_cHTt@g z*-D>s6}e>%YQ=)W9n^xQZhx25kU(}7tdB>HmNYfoL26%<5{QU<6k2+FUZo+WL1os_r^RC1Ho?aXYsXYgfk9Do%a zq}xl)6&Mo_In%@GDt?WflG0yXTVWORX4`)M<_K)x%;Yj=`wA3equ zC~+O>qYC8PMrlize47WdRz>6hPzw;m1J$OWl~c5>%|W9Jpz##^ey3&K26F-VBRZtU zILt=!$8$)v5j3g*YAJz66)3%XiFCUuAIqW4PI5+aNVO5Uw+iYPfi{) zwUfH*1;QB;8OjFWoD1sMiyY>lHV-*#2dL)~%108Y5f|i)C{V**@K_XMpUoE@sGN z0PTQ^XGmfI?aeBJh7G;K17vp&18C=WE(2(`0&?G65Y#EJ{nAn~Lq7Pnz!ZjL@VO(PJRJ|dIS_Jh zASlmeGGx*%bU-Z`P`L-%OIHp~#~BQu6kWiOOJg^40>Rwz`)DE#SqNk&EUxpz+lCoz>vtGz>vgH%8<^W!vHcZ6|6^@ z!Ggh(!4j+*6jmTxKqY_?gE2!qH2>#8X;3(VL_sAdBu?`g3djsaPX-qTV}>#YkUhkg zkr4Iq46xB8P#y%84dj(cDS^(8bpw@u~ygV9wCDYJNRoGlU zbkY!J`iGQFgF7dqhB>Sa4cf(2#8AqR#sI1tAbDUg#ss840BRBBfnADlKj^eZP^%)3 z!H@womH=wOfO0P=PRQ-$f^Nn#W^hGopAz5V28{+IN|AU5kQ+g*1W=g+a#uVh0l>7Z6$F$1!TKs`uUYZjEdK>b-z4l4ksTTtEtoy`Zjr3ZB1F=$K#RQrHZ45(KM z>Y>7Rm%>`Tpw=bmjAKy0n4I)NjBhbp_MjYB#DH*lF1SAniiJuBkc&aR1yG+B)Kh@e zn}gl`1>oNKP;@t_=RDNhoew^Vc<`rlPx(Ae+5 zW!@?Uhz6B~pK(0b}`QR&MkVmO2z~%bjcQa`G4pbL`Vj!IX)FTCrXn|_XVsOa_ zOCO+mAGEq0)NcZnn4r)HwXjN|qrBwKk_0nkGJy6wx-z7J$B&X3N*Ibss82z9L8Uv0 zj%UbVfQ*$w+z%;S4CO<}S^_fAf7*MEy)}GKien71zP=5unx&f50 zK;v32dK}3yB`8t-2&pt3O+97ZMJQ9DpS1YhWo=Pp-< zAci0Ye}*75mkqQ_+!#RR3uyiZRQ`ZwDm@uMGmW6$W(k8U1E}W)VuM1&k0GByfdSNi zO99WpfXYYEnhnrs3aCy4=}W%rx7Q0)wwc>%RAL1i$gJSk!T#RTG%abi*|OdqHZ z32SK=Gw3k{fX5(m;iCtj61|uq06bTf&H&0GxY7`2S(640C6F#iOAVC2VI>fD7l1+x zlm|h6KpykOu9_0};!5+NkVW@DWbO~N+9U@&9}Nm`&|GQ(ctir^UQkS8&y|D2<%n`* z@VOf_Gns>PEU5rIX9>Ei1(c3b8T1&O7)lwE7?QyAn8c?>&{ztnJO{0H0rlo{!20QD zFDTs?f@gd|W2lfh5ZtL9G*3&ppCP3MC@+D03<*DcDHYvTXYi;Ky8aM`3-F=Wz0MPmn(5M|`MHlfQHBfFQKV8w<#h^X(pwv!$7`if4fY;|B!k_p! zr97We!*bZfkkf)wI$j^@f44_%* zLyfk#FxUR)YJD5EgkoMNnA_TIUPuSAoX& zK`RPCJx|;r53vo@|AVl|wYP{N9Xx9=@V0_h=YsktpuT4cLkhTeLTmpgfmgnQ<{M~j z6R4%1%K#eL2dxYTjUYirP(Uk6X>B)Xj1@Fi0-8~PjOWwZMo`&Nj;BWpNwbuuUQizl zWD+R1fM&Ts`4u$QM9sX4eUt=p<1Q!`^TGRYKw~Dj$0cFo^OX9x9NaF;1CK&M#*-lZ zP|$6$5O>fzUJ1JZv`+&vt`1R~0xn%3sUOrLrF~fn%F~dwF`%>o3L99-0&3ObUXulj zB~V=IF@XA{i2Mp^gMn&p;%hO`OgLy{3^Y;2E8j z{sQeT0FC*8R@#F~I+!cy<#U)DK&9S5x&vYNz@)_zhH~)DWVphCaM?wzv%m&X8F zB?@wL2??uuK&|#-aQk+kTmW)4DBXivWw3qVpi~N(H6}MiNC|()eh$!jV^F;Z=?UX6 zS&?HM78l_Rp#4#xyo9S9!<=bM1@HfcxkP6fpP1HO`i3>nI0Z_>TvIFD-Vq=?hJ7J-s zzyMmC4w}mbwJR<-Y>iQyZdmB-DlG0uz)@`7+ z6sS)DN~r_kPEhR(T7wA+LD0MiB3j zyATmy=snVba~-G`Q_cX%nXoZmP&o{mtpUX$NFGvu6@&Ndfp+)PD(z&0PnjjvHHbA7 zu+bY@w-RAxCMaA$f?b{Pl3i&AiV?7xEyl3ix^u$XH%9iP&Psf8s`Dc zCnDPoV#D@Jg6b1`xdpVE5M&=Hbt3W+ZEc6-0#FV}f}i3Gaswy~K&=>ax6*#X$HP z{cJ8|H-JVyKqm~4(j)Q(pSA@GE8@qk@VSAUwi-EZNM#^y?u;C>K{K16StwG=5_0T9 zv^$a0EvU37z12-!`$0WgP+tJlRs*%4Kz)BiiAPM{rlx!7m9FrYC-jRK!tNND_#xyj zdc_l>zDLwI^ot$rw$sb+$UX+05Dsa>g7PZpEDTU6fYJtN#RTDzebCttpn8Lxwg|F2 zFnf8#wcjbRA74EL@)N0bA;>Mrtuk`TFMMtyCw)-EP2|>R)UcbH^&4&71Ija?JVbtd zM@#n&RN5g_-VanhBkZoh5ub$IIZ*M6y#^bo*u?G{`i2dx{{va&26(DiYycmcEtt$temZSh)XAi1(ilF-=A*;q9YaL;#6Bs}vuAsFd2@DG0 zwcMbcy@YPk0F7vXMjf!vuMpE7M=zgXJ|?_U0bw^}Wes8$1=98a&G6921)y9F8fCyW z%1B>VppPbk(g`T6K(h$6a0x8NKx>FWJGMY)ZzJbfQ0Rcx)Pmdrn%xD>!-3K(L>zQi z5hC0akmhX(ubu_nMgdB{3Jj#!2b%dr4I^S~1*Iua?f}gnLiPrL=9@vga%mB!xNNIr z0EHlAew<$Rf18WuR|UQ70+ngBEL*Xa1E4w|b#$3tz6JF{Kr;)p zwGVQy7^pr)pXUaxC?#%fAZX_`sAeE%1Oc=j5ab5XPCCTC^kVQTOwg_!Vth|M`$4V% ztriB2{X%w_z|sWrt|;W$N9x%PswF{ZTZ7j6gJwZNsh!ro2c5?WYI%ZMu8^4|P^pDH z4ozzp41|54c~wLTgUnNd=F&iE5i)iLX=Q`zM9{nlWUm}3h0`N6^1$=0khNT()%f(V z7i148y+P6d=(a@=541lBRKA0DU_jyt5o)v!3BoQy>>j4Ct3dGqYKu&jJ^AF7R@l!}0mTZ$e&ktj(%M#(l$Z$nLA4WT1v_Yl4m3{&au5AN z9}%Xobq=6>Lh1?!;zI)YrXf&00qU24dUlY#!^#YX3>FM#45kd4XlGC(!V6TpgVwdt zI^AIIdq(6=NJ)zvc8HV%DSKh=rFBdqy9u<~5;VIB+Kmb7wS#s_gYN$W)d8SzhV=hH zeWZK_h$}&5AxIYCdivE6$>4jfK%>;4``IDx0qszM?4QECRRH7z(3(PAAqpzHK&LMx zG9d0I&|?TO z)ZT~m3_*L>LAfx80hBKhJ^;0xL4HBD1^3L)K)7&VT?gtdRWJ;|aTf#f|wb_JU4G1GULOD{VmYprExgh)@Kr zf&s0+fvvTHlo_C!9+X!=C+LB0W>H{(rG;V=&ZmR420^FmLt+o)CeTTFpjZZteSumY zFk2uaX|OnhsR!-r1kt(g&3LKy7})xr}A!Rx}-GV65NKLCCpHm~}l3tQh%VyY| zBXWHz5_TE-5n2MSr44Jsc&;Q{hLs0IhEjso3RgGf6d^`Kq= z{`;Ij`YDYqkWHYzF*cWh+y$!PK&?$sC_-AEAW__-8w24c!sk0s!&Q)39#Fa^JV!ze z`>@3beSC`FX4vXMkRNGXmJ~BoGJwY5@)>d%VD>`FQpmm$(Ar;G=3CG`7@*P%RKtO8 zj{x;{K=+!0_M?H?BoH@&Ze#(~hQzxBw2Bhce$b1mZ5xjVYfprTgwm|Dg2i6scJPTTn2^tXr-8D5ZVFQ}e0=3gXEhbRS0orQ@t7mAN zdJ#5*=Al7j)SzAnz3qnen;>Nf?llykvJDhIi1sQuITqn(M9mIbrvMTM?b-p=r=WGC z`FQVWpr2bH`GsET01+mjwgsYv1_~WW8im9XIVC-{VhgqY8F=?V+Fr1l2$X&xZW@S` zjOiB4vnL12b)Yq{pjPc*u^&{0K)D)}=8^a4fy5{;b&&g=NerNq_CP&j z&^#D&YNl;2M|K0qmxy^uV*7dIpf?95%HS3_-58rq-NG&zu0W`~& z$bcy6ak&N*LZFmNO23>|;X`i!hF0zY%^8E%snI&UqQ@1ij0NrQg`^&+C@zDxfl{6nrNezVUBu!<2cYP)?ps$U>wIc*H8wJ{f0UARCl}MnFhRjZY&Xxe#1({O>m6D*=BQdj) zpz#$@`w!Im29@ow*-uaiLC%OOW*{#Y!OmP7jBZN-pUw?h`3s4o!4z(wyF&B9?i-9D zH~7;XsH{T1T>+NDL47LZJPOJ^pz;E>e+x_VpwbMK*Fkq{=P^(tH-OfEfXV^v^+zc~ zCIe(ec`mrz$Ybzl0FB>6PN4whK~Osn)Xps;uv;8+-xg>`IOyaPNY4^9{tc^7aMhx; zbPcFB%3;7=LetW2Sh)*o!y`g>AVQ%Ce48+6#AR^B4k$-}(h2U`o0jndx^E6N>jX*l z0}(HY3@PB9U7)%aG@}PvIS9*M@5|E2vwLi7~7_+LeREhY=)af!drP{}Z3%QFY+55Bba#(7ZI{)H}#p63{*p z(3~e|r$r(|68Lsx)Uzl+Cslx4Rm=c6wF@-64(fk_)|sT^9PvSvjIh0CxLk)>N8`5< zG%t&OP7Y`s1XNmqdG2{Xyvy6fUrs2DuEB`eA)ENU8+YPM}jOQW%J-kw}kY zLaxgP$7c~kIRmKY4G9~}SVT{y)Nm`VelmG3M&ue|M^=cBbJAQ&TJ27)7#$pWm9&r| z$IZy`oXJ3q9F6@{KTz3=$eZ!tu^!O4HEJsocR5%N-ZKe0eFd}@1(biN<62xHjGF2p zWeY5AfqKKBUO@%}s0V3m}jH?dB6?&K}3qYX+ zDy>1Q;X$*_pqX{Z`4u2Hf_gci^}dwXZn#_oYU_Z~TLlATpE0P80JRQ4r=w7AD`pD@ zUDu;i9jd8 zfzEx-U;v$<2x(7)PM*nQK-`>5$Q^kMkX?nuy8^Vz6f}wf8U=^#PX>iPXq+D8LfmT@ zAoaNqG`~=4BWTVFv`-zBA3(8D0`6zv_b>JA2F*@GLJnjEABI}) zfRzdK@iippf&2?ffv~X>(6}im{6T4gcJ2VhG^mtEO=+Ms2s#x6QUcT8cJx|_9xkAL zoI}>mAyPLi>}lsa(3}FI%pzu9jqycnp>gg;Du!84qY*)!tH zOJsXMtrSpwMO*toqim2iEU4WDDFGoZTu|Q{w3-K0cY=EPpfgGEwGqknF?JV#TCboH z22ih=HX)7OUeGPSr3|2W0F{=Y@Q7ysjfjC}ya>%vQ8xq-;f_3R3p!~B)QeAK0PREo z^*kUgNm_&vavVT*%Ye$0OmOHx_CSD6>IaS05~?+c2^r*ZNl4mPU;y3H25Oan{0izZ zfa(!QZvoU&Mje?1_VEt036$DEYdS#f8G70Z$|az( z8niYUG!jCa@(DGq(=%1ms+NU>8?sLzA|RjA(oRsRKubG7{d<`Cpw>31{;UA6mjSht zXpu5OHiAYpAU*^2B|v>CP|gSC4N&hE60(S}riCj&E&%xzG=c(~F#&}GtTv#PogiO> z)+B-IWKc~^t57awK%7VmTKNPEXIl6R5mU6U@iFT%(6~?m1E^I2YJoxesf2wA%Cp3` zu@QEF(kO8?1!*>b(jG_$s9u28#?Ty8Uh$4JSyVQu=PMF`RopP|P;fBm!K->aa^9u4metSXt6+mNV zZs55X$mk*QX$aJo$2C_As<}Wj%AgdCtd6+R6Y^H%f_x6@>w!vi#J&QM2&C_q310aG z>JdYBxDsk<1%PLKL9Jj?!UWV>2kAl7pOEn!&4oi2S{x78VM(zjV zPZgkhd|)OK?{nPtBjSSAZb0O4P#+FdnscGaz&j9|DAJN2CeT z<_Rcs7c4CdM3@k=8`P%-sR6b8K&>LsNHXkv0{p3zwqb(LUASWrRO&%iwZL{m46Gjz zIS+M&mzJ&q&5(g+;y|@MA{WupMo_OEREr^x@qx-c(3&_R%_aNs=fYMSv`1Bl*>7cp+G}aC(Er<&h>beWmo=jr^-8TU$u|ck( zk1Ig6FJ#n@zP<<5|DYBDXtf*U%uz@#1)T!}nmq>H)e2fW0NQCppO65})InMaurt;N zi@QK4eSlhlAlFqffY#=L%4Wj7t6=c{Tx6Y|;FGd*8H#b<3xwHk1f6;XSy6;(KcP`q z>bL-uKS4DSsP_O_)d6bw;1dDD{Fy(Ll2+_)9cug$kxS20kP}y&h1xPivRJ#_>RD5tKSX^$BQo5NKs%0eC$j z^2i_c;sen}0o8DzxjWEZ6ChvbG3YWVF@VxVI)f4e=tfFVo&w$IqyS!}2|A5Ufgu5W z2MB1i6Xfbth6D!Cz5&RX0c`vbW-_ED1zLX(O4)i0AgBPoH5juLNA@i!Okm-I-{;}r zzBVZ35?^A%TnVbDFjF9?zK7KD)VCR7HmF{JofCr39#Cr-v|n zN#q%2L>Wn{-GL0H43PBz#D_Ps&7d{`Xon&G^#s^_O+A}IH6bx0v$SvpF?Aue>;;u5 z`3$hW1Ssu+R(XKRHqdAiC^doF){tC`KOI13;6W<|K{>4mydxJh;sG(+nE})e2Gzol z`h=9TF;U$Jn#%!=(1Y9t3I%j?2g;S876f|R0uNz|D<~{rK7_Qr zAfZBPOb&!^vH1byA4uv1rFYc+Fh~v&??cUp2$zHWfzOYy_#7-g1hqDj!Fw7&DGoF; z0jl2yi|eS9pRlJk@?&E7mlyQ$A-&58`umC=Vc<>KTB_FUW`yvPx1*H00eXkUOLb7(lZOpcWrw-6$!o0?_OV$Zeo= zN+7MkdV+KpdJ$H8lb_K2S6=tSYHR!FMy2|fzk@7p9LBVrX;na--1d`K1FvUY)%i9 zra`?DP(KT@+6uI07jyz|JOd~%gXCcTfy{UeHs63k8Pw7PjZ{Hm0W^Yzdv^k8EgR_k zK;-@_a@k0JXk&(43IizIL3`~$eQZ!UiCpdvOqw9hm7shF8l4%;ZUogqpta7R6bV}A z2HK$l8Hr40$i{pA2<_4UBtL;%1{y<0&t%kcy0 zM$n1dpfz8R(jOF}pzwqApFk{-2zu-jvn~u26ZrCfFaxO7m=4~D3Q1L@l((S!$wB8_ zgYr4Zg&>zA+)SO+NqrY$mI)9ygM0yNrBYH7P|L-jQWP{6ff%U-xe#;~87Q1V;XRmB z1b){KuC#&8t%Et0AdiTG`W}cpj3|Tg&;HZ0TqtIM%;O=aR?zL1pxzVc1S&+_4+b~l zj%QG77B*{uaPwd&8Ib$cu<`)W*P+CP)GPfF?t$#G1+6w494FhX%FJK`upad6hGOMruH(*nni{6RU*WIS_6_)cv^YRYWeOPdFjm1WH?=elwz! zg~c$vY68%ja?p5R2?J>MAGF#GGzJd2t0x=0@(JWd&^Q#NP5`N(PbeYxKoKzn%8?M4 zfLPd4J~euwAz6B%0AGX0cag3={bqE zt^|!o<}qY5Ktgh$T#0(d2k10g&}b9nULTkXi@~b{LF1;N)$XYE8FK1CZcl*PVnyJa z?ICRo&|EnvRe{#B!s;tTJu$e_527W4>LZZ*VQmvosRQbVf!a@lEoC9x4|6T3HbJ!f zKyF9PF+<5Gpq-(h+G;4LD@44Y`UVkmpc4!rr7fsD1D$nL0^WszfA=_Q-UO`))nlM- zDF$;fWGovsok4b8fM$e1<3ONPH+a$+sMin5&!9F0q?SX?5s(>z!B>Y6ayKGn4X(P6 zcy}Y0xu7(I94`Z1Ph^1iMuFCjf=&&u1m{S?r9Y_mRl=ah;K=}C5#K69whuHf4@#Aw zk#}0!3CgRG^9n&DxR6={RBMCIf=*({Vu18HNpk_jJYVox`Jgq*p!45}4}~NKSV)8R zAAtI?pwR|$$|P(A>;AJj(1cXua99<+jpTJ8n4 z{Xpj*!@?JI+W^Sd6%3Gl?x6l5C$r0ybwd%|Rp_w}S@{i$YtZR*xMp+*&P}ke z1EoPo$kHq1K&=Q+dkHi`32MV5ms}t@P<{vPI3hO8Kz(9_d8Dpc1KEhs4H|_6wSYiv zIZ$f_(oX~3epUf4Tk{w|DG!w2hz~7lyAR}A&@N}tnSS_2`q0xBW$pl#0FeE&pt22A z_JZ;`q#Pw27NHCf*AQPyfl>h|bwI`rK)OM30kRiz`V1}X1ohHEr5&gToChxBGoZ8n zw6G1dDi~7#W->tbLnHd1pf)yW#U7}v1D!(;TCYyI8<6|fkW>U(@c`;Ef>ug_>;Sbq zLAP@%GZ-_NGFYPZvoT!^8`FwsfZezNsv$u61C(b#rh{$}1l8N1d7=n5jpnMEk_Y7Jw z1Ujt>HMT+J3~W{!RR)$H@wI9}Wg@6mNUc;!jC&#b;XyZng4WtVaua9`Iw;M8#^OOa z9F*Hj8Ip)-&ywzPSgjy**6Lc))ZGER5*y7En7I)P4ZfgrE?Bsci5XOPz+z>vxB@m43+nTN+Fi5_6XaL`jVa=8xq({M zpgmf83{l|o2=a+4AF;2EhP1*!X#vzngzYE*?W_ikgW)Qjsp$gH_zNfeLMh%+@oc|3hp0K(`p! zG7KIFau4DjEl__EaiV|%18NPb%aF*R$)Lla0KPd3RC0k%f`Qd>$mhp^)F4(WD1g^} zz{d4J?KqIFx(tH{g4_cdQ-R!32Pz3*`%6Hhy`Y(C1@L}zP_F~jw+8tLRCeVsfKJK* ztxPRp&}6Uz_puci6u>98fbzEjgA#)?gB3#zLn!nv+G2(nh7tx)NTx7=`hkfIxePH3 zE)1X(UqPp;fyOLAJLF;*+!;V2?7;wPf5$K&?!^V^2esBqz$QUhpmqlp!K;Sg8_pvlFuRQ20-TxfkGT~!VzdcAL@u0vVTE6Xi#rTfdNuJ zfJ#RV26d$PC}051pr$kE!E*(Ir4F_kRO5q6d{F2@PLKf2dDt@KGUzdYQXHuF2O4L= zpMnCQqgWu7MhxZ*G2k9H5jD!vIRZAQ1!$dkQfGj}jq= zR6GO7y`a<%8a)N^ki!L3Q|2(FG3bHMj{@DU16uj1z+lUu08Z%;IY@5=)f8xC4Rn@JHh6y{sJ{Xm zKLwc#$u9-q)Qvoc3ahm<1~jgX7z`K;pl$=5>5AP?$e{olu_<8yt+)lLhr~Z6R+Y9^3>!x@jN8@lb4u?~{ zLd(2DOS4Dw;b=Y_&4&Zu<{iz4qxo<&ACBfjP~Una^utHnG(*3ilYxa9uRV% z(it?n2wDj;x{d>~qHA;=2kk>(bR7qxodaquLe^Dh1*0OPG69W6^o%hJ)Zbl}TUTDF&Pn++;EC@({Bn?G{R28HZs zxD2+nIiqVi@UI*JrCQXr9IgzIS$oh44WOIjKs$nA^ZUqaG(c?74r7Qs=oAWA%L25Q z7_@H`VFKtBh$Qe`BSj3A;B^F}Cvyy@)g1;5Cg50s#Tw|`2FSV%Sj-b%%>g=#BavbB zBo4^FX~g*(2-fIH9H2Q((AuHVlQ>}Ox@f&$VJ{Dr#!RSdGkQ+5d zS8xz}f(Wb~J$e#{0{CPs(5leU(^Q6TSPa!sk1bI>d0C3tuLaGfQf~(Vruo!08|2!dIJQFTa2XAg!F0OH z=n4+XS8!A^fbRGJt9pKu!V&-7N?@`vh|KJg7_|KE`OT66BttbACH$ZX9&32I77d z#JUUYcV>WY;XppY9cBXP#s$!w-k=*|KzA#~Gr-aSC`3S~E`V_K=)EZnr3|C@rhwLE zjGngvY7v6&P=e(U%u{$qS8LEd1V&eDjIP!gU9B;CZwhGj!|1&!pqv1@A(Xm3|Ir>U zY7cjGRD5()9MaE4O&6mhP4wN*Gnx-a^WkVd9G#sSot*-WMS#X35bMZE4U^HbbhIoT zElWqsQc}x}(Kat;n|Jt@rJy>dc*v}*1GzR8e0Dhb_2Ovy#!TO%VKN#fkekvez1y1j z8U4|_Q-Z+dF6Ma~u$g+$2^*OVl&#jtWdN-JKwYT;Gapo%5+7f*R|#^@@LsE7#$bT; zoDIxa!nIyQogr`Zj17j-Gd4zVNzq^c&0@jAK@;361g&WrU9~X~AuzgXV|3L9Xs#Nx zeu`fAm?8Rrqi1YDR`8CVu`zna#?Tqfp>!l?_>Rhr#vvC2qI4e}!KQpRkd`BSqxo=j zrg3zpadf6}w4A2AoE|MpN6XUDvUId89W6_7m8GCrB3Fi?)6WOFSAoHWfp|C5vaLR9 z_UKGMb!PfU`{zSthZ^BLPyF2e=&B9Kstp&0d0G0p5hcE3_g4{ElS6LV`SmIb^0gA0u=|F1M|+i^dU!am)i7c(!m(DP7`lE2bovS64wQI?M1~ZG z6oz;PL>z;{2(*d=grgbM84^d&#~3{ygJE<%$LRSOMGPej@eBnFiQx5k1A9Wq=z5OP z^&F$?IY!rW43+WR(J>yxc-K%J&lruv(Kv+kkw?cY6&NTz*>rUN3Y3;c=dVC_<`yty zGJtlHfW{ukPZvYAUKy(H9<2{Y>qAf(1{y6!p3fYr>3OKSdo&*og?tFA+wixU22(tO zTsyMo9LaBo45oM-jYH5~>?7y=$Dvw>jkLO90bU;gTH%t&kjoIm06L{4nW2;+7rbVsgrS%rhQXZy6zU!fr3^_7F-WKE z#xQ`^!+_StAXtc%7kUf@43!K@;J5(A4kZ2z8O#~Xz+#}&PC)UO3SM0k&w#pqqXcXx zC=DP?1g+%&t>yv6B&hWUTE79pqiZ-o@l-InhGTRM2gB$Zj?pz7rQmYem7$2Chyhf4 zf_8?2iK@c3|S21-vU8w3kTM|0rfW1!E5wDwJ@koE@3ETC<2d) zD=_3RmSh1_cIU?EuvVAoCGDp>PIAh9Cw%22Tb*21pN4i$M!~?iMUm zAa;UQ2ZCxMke#p+6vPLO_<>f8mM}o>CK)l(D? zB%fh)&I)v2SP}zh6;>((C`>XKKx@Y--(yP4v4GJy913IQLuZ^EQhVZeFD=vaP&Ior zACBh3(YfQ%GdV!LuaVGpq-8lhT9%HMrL-tZLA^Xs$bx$Mv@oB#W`kTiIPQcP&5xj% z1&s|UFwnBxqovuSaX9qjke2CV)NIh0@aR5>f!qf%uxXIk*$2cvRZxinIzu8Eyyk#< z^BcP0bqb*R-4bg#k1Jk;;(9kOrNzwPna< z&|^qsNM-6!s-OjN)*s4RctFMjTp=r48ipSNEKo=3+VhB z$n9Jp@nV$PC=I+G2(+3OwDt$Kh89%TgG%8N@Ofw&40#NowVEdjjE?Dm zMyE#SjYsE=K_kSY^Twm|#)#S!lp;tOw;e4@N6XUDxyI4CMpDa-(Xn>Sv36>drH~QB zp|Xz_wsSW!!1ttpc4H=i@9_ZLp#r*lGzYx;0=5GbBv0yD9H2AXK|511?@`eK?=mGm z-e|89)Q%s{t2m4q3>YlI`*K06!IAG#0o^hSY9}J!mI7jfPI*Ax4Gdbpk-`8uV?v!F zageX%uw*br@^2ACDMKDZJp5D&kgwyxw+n#QvlKBDfNvInut8}7H2(*}qvvrz!UVKy z8#!D?&*R8tC;;z{hlJ1Qc^sqbIY!rWjGo5;*g+Xo3 zk$sNdXnP)%en4%N;oY7`ZQp`gA)xhZ@$ggOKy7%~?S~*Xq&<&%Z(<4fo=i|!f!ewt zjM>K5VNd{{Kc~(R%b*GFw}I5rc5NKYH=wf$K_>)()|G==?4W)M_VeUWLu0hH4?Bks zduSOljGn#+O2r@yIn4@`;z0Mt+A@Gn#sZyZl>|Pi8#I3d>L-r2_6wlBX+%hXP7X^1 z->8ePT%h$il12;$3rQ3Ffsqpg0>UOUif z&?O9`t$tA20HyZf-Reg@Ga1xs!Pn{s?V`liT@qK$PUx6wiOdx1(vP}>}YL9KOA83I}h44T)#J~BSq1Av4PsN@?R z?FZGc5DZF5pdJP&mlrdD=D|kq+8MoTCkuL;oB{*rR6fv+jCliSGsGGnP(B0I{~!z+<43I7N3{A&M_2EI*J_To@DoQ*V+61IK!n4< zj&M`Ig%2tZ23IQ|W_}<(<=l<*YG1wCmC()!)mk9w*Kh4 zp5eK!2Q+UES-B0G!A)cU)w{V2AUcyFnIW4Y9(*22G5Cy$JO)txtNA2m?evWP}T~ojtHTP>!c3D)vKdkt zDjCY*;*fX)nL*o<5th18_urzYGi-aD3>nNBEWqvu&8j1>UIL{?Q2GX?R}hUWor6*W z$cG>dO7}SoX$*P{i44WyTmU*{1e8un8B!TEz~KT)@sLo4Uv18BnIvq?BQyJa()xBK1L4BXoe&Pbq3HH zhdhQd2GDAe66l_fVunfvP+0?-#Rc`25OD=b#Tg8m;BZ1$2MKGC9Lyftrc30|0-d%3 zirp9n(Ah+w)CMZ!Ky2)LoFOP(9}YBcPK2Kg)mey6fmSRs52-qsVnWN<2dvI8TD=AyAqFiRUta<}&labyGY8XgvWa{}wR7N(j*YU68(f2GE&wpmd9? zE=&XW@IiS4k}~xe+|Wdv8FCmhM|3?%&CzmD?15S_$n^wf9AGQYOi)TQPhTt7w$fp~ETF~1B!f?(1E5=cJ8Znrmtf>O^1rixj7(nNk@iOSryWr4 zk7t0i#2~8(K_NP7_Q(hmP#a!>p%hv_f>x7)YEw|lKb@hJ0aQPfFl2)J-=Nc`^TD+N z==?rV{}ZGdbXp5cH)zdu2?P52OVBxg1>h5!KzT3*+^>g}N07EC=*%7v3q+eUq%c%4 z7&D|X-{`%FC?8okD(G=i$HQezSIdz+X~>*6hI?5$qb;=(~1}>!E57_!6(en z#?6Fs4szM20B(zbc78zC>|^Ssd=)=>*)cG6$6%>9M(YeNq*|HOIs-ZF!s=sCnkBaV zg_t!1wHQEU2&fbQwctVJ3}{pw)QibyNQa)y1lkKV+-DR(buXxe0qSjl=rnN48#KxS zYRQa_p@7=1kP;k}WNl5pb-#I8yC`g0*!csdYF|AO5o8;(D+pz z_|67nlra>9ZsOt}l*>S^TM!26fQ++aA5j<`ApwOtsD}fYa{!G4jE<0i+H{b)D%8=9 z(Ge0zc%Y7HAm=ww3m7!wmdY?XLPCu?8Wgsut@qJZE+RZe&!Z>hJbLur&FIL;=!gzz zwj4C(3F_UzMgl-1q@Z>aX(Kv=Yh(m;ws8tWHbX8$`j8nJL3T4{xsN(tiQKy!9T@?o zV9;n9y++hWM@B|RM)0o_p@l4{Ou)VN1T-HA8o7mxK7(#G1eM>Qaa+)6E^LgX2)s4` zG%^6%Hw#*cP=d1NG7UUK49ZWSxv3n6R0hyWlM)6`hCGH4@O%|WEC6Xv$_+fmjcPMw z7MS>vF50UEg&n=;0I5B40-9MsjTvm~Ps~tm2SkjWz*b{|Oab+86B%+C@TCw?h=E2> zKp4~-AUui!G8x%@qbp57^Q55hl_cmoI#5{BcFhfP-w3oSW^|VYt5js|o(Ib>b%a9M4F9`nO{ zRAq4W^35627!n!s7(i=XhtB#3gquOR15smx#$X1zmye#BN6WF%atvPz4Q2q%G=olY z0Ih{nU`Pe;zXA0EK&iO^sh>Ey27>r80Z_R>T2CL;*95Ka2CZs^_4)LW_EL`a>p|%h zH109@Rz#qex!Bi4pzbSy#W83_1-6kNSb6}ZBv9K6gvss2gL<**47v=U(-t8kJ0R0& z+mD6$Z*=bnqVyfzI|5oy4_f<*zGikL_UH#+Zyvd)KiZQYs8x5!1eAv2utN4WAa;+9&ehX;zb>f1TnyeZN9tZ(L{AmQ0`d z3Q`!18PXXt7z!9HhDB>+CHP}j+_`m8Qj6AdEhT= zkkjvIFP}QSd{CGsGE{<3X9VrDjt8Hz1UpR)v~mKpCJuWKA9Px20r+gO5(d!jJO!OqPpS-lTgiw^4dA#^}e3CJGW&gdgrS0Mj` z=9OZ==XhgF-`GMEbay=RXbHjxn103{dZ4otL2X4)z5$($2I~8O&TKAbfSePV1dc6) zxuCO|a~L4uiW+8m;GHlqy|8oohC&z`q1?!WJ4BE}FrJ~Dp$O{Zc!pdCV}?=&4JZvd zVGeY*RR%chKs{#22~9&KRhglM2c}PvL!ulU3K`(DjX|dz=P`hC7wEKKn9ni81#+5( zIzuA(G-c3z!l1i_(-;%ruoL<~y%~@%KsTetFhHO^n1-C~1zJ}EDq|q4E3mDv0G;4n zz<_)z8S1%YAU&YmPyjZy1X?>Kf%A72Lm5~UGSUR8@ASbku$&JnrSzcb3DO%Qwr-;4 zI0P;`K_Q1IyFg(%JbH%sTY>}Iqs0{$nBuS$09xG#$`_#3eIxsfEY!1E;u%2uH9@=l za~KT3XP&}lDUer(g4+6sbHwx*d>D|=74w0v>dhHFT^xL(E2y-iY;GGC2OyImdvHPV zgdFC24A|O0mN;6J_~IN?et}vhAPg$yAuU1Nr(val+mX2pmEigcrkl2HLqvFFFo4>s zpt^PRq;S%98yYd7o|*<~+l`(Sj(V;#X(2k8_HWX5wI_0(2jzIodKS9~to8-9kA~72 z;RydiTH!-yOac_rpc529r=7t1(V*1>piv=gHHH!1lfgl~aENYDtb=L@5FU=>rHB}Z z^e{mFMT8}&RZscMBEpW*R5fx_750)6n<%XG9PPWn+Q7Kmv4(W-yMRgvY_UcgF_3Ne zYax&d>fcjA{t5&{n;pg?t`B3#V1RO01wuEz*oXKYR6Bw0Hv{z%KzHYj_F_<5_>ggI z&@9vFX}(DeqpR8!7(lsgq}+FeXn#T4c*K^}uzDEO9vtn(a4~>NS=x^GfI@n-7Xvv5 z2Q(uI+LxXIz6n+Vd~+CRmZ*fG1U%~ontueg~Mbk9s0nTci7~Mo!PQm?4Fsk|CX; zjG<)6^jwkM3~GZQQZD8=0dh}ZwC75{o4H5l-yx%bm??6!=SuwUBjQzp$^l&Gih^$K z1NB!c!K04J44_r&*mou6Fd)=`)`}u{$oGPb?m~jBr>FG(0az~+b*(5O%(1T&H9?tU z1@${i7(y8e7(gii)Ds0^;^I+b0Pe1U)kmOR284WS#$d=`0q#42#sC!<;u%2uf%3pR zH9%}+9~U!#&eSPlNM-=7IM8DN-IWX4Nda0P4Y~<7ogp8*@)@*d8g_e07>J<(06U;wp76&NZQAY=KUv3-ckU^+l9BBpf@QiIyU2kC^EMeTL& zAd?X-1U&}iv;p!h=ISVj3Xr}`22g1MQWe6G&j8zP4m!^Uw3=6e0XbAbcUB`}6f~EQ zh!M~pt4eSTDKO+RfMzW~VOIdY1yD}F7G@y75)*D9lL>_xD4i3BVYvYmPouj%K&OP|GJxvsV(^~gbcWITJ0CnA zF!)EC5oO?L{XKH(Z%|pRz%W?qZrav6w5zv4bq^_ZH!*b(s5XT3MTu|w&^G))X=SwD zCazte3+~r|(gpE-VcM$%xd&Ho8@cBJnl%RTL3^W1M*H31-Wlj@I!H-5Q0J(R_Par6 zK7e|5*jp$gsoxDMiy^6zntRJZ<-_2scSh@N%El`|X=SwD9J5nRKXp#%N7GT9bpvWkyHPL1T}DV+0*kI*-=ml#ZN(S}vnKaM0PS zps|I~k#kUO4@wgtO#6N{@iu_mgR2LQT9boXY@q&50RyBrUdjNvM+J1c8mu3vhjg1J zWbO+x{xdoQuE0Rs-D0p97@Ywh?TL@p-_)4-29=BSt-nDwIx++?_%V1g_(9L2MlMBZ zvw8qzE9C4u_4t-=MG?t-~p)nTgj63Tx8qaM0RH(3&<- zn;+CGhwQ8dt^EV73msjXK3b!X*65=(`asl3qjTh=bL5~gZx9|`la77{3TU@cA_Hib zO$I|e1BeBhDFKbZjE<+nS}&kAz@sbMXgza)SY0)`qYPA5fiSGR0)-8IPCFbdE2>9p z?a^8rlmkE*mJ2}T@#s!6&`vVcS{rnqStj_l8_+7ZQidGxKEZe}SpvROXmnJ4bW|NQ zGBer-AMJyW_Q475aR#-vM)#M2?xqBtp8%pk=MO{XE^zIo2i4QWVM=Oq(AYF_wt!TE zF!AHw_*GKNERZ?4N7qxqJ@8}(P+uImRtNRTM{DxYo#HtRuv4f;Yx2>We6%JXt;s>> z+bDo{RFBS&>6(VBX+rXH=SM{8gRiCr z%`bt*cp!5M@eIWbl?-_d$qexfY2Y&qbHOK5mN1kuVgP)xUTYeBIM zTHO-EK%CEwu=pHwVkzP#5M&=Cj~tKQo&rk8pxjZ)ki>u*W}wq!M{iF7* z%^iX41l?T+O8X!?VQalWe9%e8Akz@7snNRDk zkdTAiM5@7%$B@VX%4@|8pm`+F>IYDn3lr630Nv{q&j32bFqr|gq9mR{kD&~HdU`Pf zXw(7{`i=|`Gcy@rx0|{$6oK2wMc`OhX8@hb4m*EZok4*C;xbZhoB_EMw1WiJ0)yNM zjG4kvZ%hT94GwC#fx-xsmLRwHfkvD_JCswvXM-m)B!Ta01)cf?npXpzNDev!YSe5{ z>kPD02XvQh9s@C9GPrK21xwG2j1!?2nkf4N(3^} zG&)iR8j}OHJwPpM(6|Js#Q|!6gT`eB+nx>d77q5Y7En*n6luf(Hd;Y=d=ivmU@b&Y z&5nQE1yo)@+KY%5mnOWGIk?82Mn_}bzB5L-nF`e20*zaP`VEkgD%24yaiG(keAot2ZCmw-95p)7NC_Q279UWOfgeAR3 z7Dmfn(8x4sR1!3M0J`xLHmZx9c0oOVP%a0hSz_BSqazCb43IM*+!zuWK(}Fn_V%QL zNAf+vr68!~S%TDl1@*H1z;}g$`r5E@e$aiXpprF}0aOlyO3f5#yOj8tpuI{^$_N4X zjX*OXpqYSVhHM6qk3fE*#<)QMLnQ-fTsEH}kHLt+oB>p`fM!Z!7(n+tg8J{El^ux; zAbS(RqwJvi2~^*K`UxP_`QVxgRC8e;69C-~jC^MNX%&(BuJfQRp>S2Mx7cvThY$r^=3j=7!v<7$vtO$A|2q+#wp#rM+ z5i@15(8O%t(H~5To{5GK=YTN8{uH_fSF#X87`PEjlpm! z_VNVv22Xt9f}GYsbMv6~Gst(?>j_Znk+^ySWCjS+VDN`6p{0xIi4HHse6-2Ru`k=K#pp#D^J$leM9Vpx(`>;Uu222FB0tT_(MFTu)3u-NZY7CGL zRJAbsXq(!|4I@hi3kKvcLih{jZcsWx9;F7A(B{Xd}k7PKZZ zlVP-FNB*jc;oY(W%@-rrxa6iTP+kVr%^w`dG-s2^5YGS_vr1toV8{pG&rSp!N%>#h1^J4OR)-Wrf-j)(5xl5P7ed4S>2w*kk63MkOS5O>i59((JPKg_d9Z40r?c!2Qb%zVh`2VFja_N3~Fx=rgL!m zd$fm#=+~Fv=mih;9v-3u8tv18Mo~fI)}T2zP|n2FryFejxzWB{Dg$|IkP4t99ix3Y zVn^eV)q(N|u911<5Jim4j*iBIMjAk^W>8z1_?7U(z0YQZ(zZnO*|4V~P`U%PwLlor zu0+(;>EJPUSl$MWv6D6iuLqv{0M!Jbu?NsjJkacHD!BCva;X7yJq5`A(Uu#iRS)X> zf?{oSY`&HOTRUoWY#w!76qJJzb1I-Y2g=tn!ty(EnE~llkGA7L;SDOSKo~S*1X{@p z*$WO@GXYwY0~!ATm3g2M@1eF!9b4Rwj>#jp)$p-FsRLI#4s=QZ=;Ta9-w0P5u9yL| zD+aV~2^1TN43!L^u|Ckqz8*s`Tn@Ct0$I+P!H2xtP#p{kapYAI z_~HfI+6Yh!2YIv$W+rH54Jc-j%U4j!0hK8rjA)4!f%jC!<2Z*3G>@&$fSIl!Bfq5# zpuHuaH4-4ZkW&h1j2&hlZChP19}{~L)#w>qpc(`g>!5b{=ows~7BOt39JGF7ummkvp7Dlg^MOX-GZ|vQGXNmBfWm5YCn#vf47A1oTj>Z2CDc|lZXR*#Yd|#x zbxz|V#cjl_e4xx_kdq^DhYqR?abX2ot4;n{7NGD!q~! zVj$I^7ClTi_FWc`)d7&z<%!^3Nx1jBW;5h4m@(usWHTh8tjSGh&||0s?c0P5opk?A81709TH=6eo>K5>q@Z2gp!&)kd_KAd z1L#~L)O7`jItH@J5LRv%<5(GE#9+o?2%a+ol`IMju>1g-4Myk&#TaP(2!ug3>TnyI z#$D$S*CHXW#6j)j;N!viKcHD@(2jA?taJeb=zayzS~idfDCWrT`#^eQpjgH?22F1{ zkb6+ays5eC9&|<(XwNce1Uv~kTZ}Ib=q(5GJ#A;jDBXb#N^_vv6VwXFzFT&5_dW71 zVA$^Y(cSl;-E*Kb&2t$bCkcSkI;d^|;o-ge9#rChYV#!Uem~F&BKYcN#0WLMo#yy= z;A689G@}e!2Ld@20yJ9~!jQp$?k> z0J@>eoxv4J6c(ejodrU)cVKNsP&*aVC)i6T(0X~0zaVWN;zAg;)<6%(0Py%jDnkGR zX#Hs>Lj?nJUMGL&KdP;uumxdy*T?wm1Gxvau7=Iff!1b$>R1qs7^eZ9n*mDwpc5kV z89-+g6)}MJsDtJgQW=UF;*s_~f=)96oiYMCJtK`Fk)f0!hXHg}1Ss9YY|%qHHvn>X zj5Bx#8e~*xWS$Q|pSf#DXk(kDHe)cy*u$U5P{iQEkk3%gkOv+W1C{t7jF_1Q#VAM> zXx0Oy3OOavZyyTC6`&aoV&<0(8BkA|0qMo%15iEz`4@x{eg?JTLG>OeAAojaLH6H6 zZkQ+n-zEXmN89og_#0G0LryW!V<=+CWdN;bN@Yl8K;DA` zato-Af`tOUU1s=NvdDH}OQl8(CMf&=k==vrYGiQ@hBR;~lmo8CL1)53>XCHt8MUC0 z0PVYj-Sbflt|dWbAE>1aYWEaD`x~Ipz>HDKd}GRhdge1Cbdi07>KYAjeWk|$aycv= zf_#L{m!LDRL2VY$4o1+9Ur_A{8WRBJP1?ngDOy^?RL8nQ8 z?p*_ozM#4SPzo-yGZ+dPQW&xsKr)CH7^Id4iGgZ+#7Qc83@Hpr42W?Qe60xb zbz3fwxEpP;fJUo8sT-1}2Ik~vP%Q$f(O|52hS3(wXp0518V*##L3$sUtu9cx0IHus zxES0!9&NF3F@QpY+AWsh)&3e@z8P&zjgi~$O^}X(XlK%^jR_m^1C4}%QeZLoEDp%{0EiDci7yj8at5lq zKxccPx5Y=t$3W*9((|4XSQ``4djhpPM_Zeq8<$4M#~^2c!NyiVITqCREMS0*ZjH7! zQAea8qcpT=ZH~5RK=lVKC611dfm#xn=d6=6K9<3d#8AMH#*oC2f!109wRMWn#OO0F zMvL|e^4)9k;2or(oAu%u@)@(1(ilLdC4*1k2Av@> zx*rELTRZ&s{4V$f>h;lF|%HbMky_ogx+R{S`5El5xgWpwNjbp8)$?=vVgKb|Yk!52(%powPW*-gBg`_k_&m4|JOu(Ru{A zXLJk_a(7@R!{`_!<{SuRC(?|zAV*t}qb*3n=j&85WHDqifK~+-j_5H+#Q8a(d#dsn zK&L0AGayb39NjB4+IAeNZAS%$!P9OWZ8MIx89{vq?CWMm+l-+60V=1A7)Ixd{c!vjw4ce!MtGx(mU4r)4fK=%*Ku(N?@twgt+ec51hNM^O&1)iJ4L$rp>v)yG zXXS!Ub^@I#fPHNsF>wy7mq2wBDAz&u*?`*3ARZ{bT^R})O2Mf`1AMy<=!}L$a9;y7 zr>(~Ty15~d0d(hjF+((i0YfZ!uP11aRwCGq2zk(6E{Hf}7S53Ybowi3Mi_KrAn05Z zR|e$%uR22vLj^+`LmHS)VXy$xFn%h70hn(9r41Pj7`zzV7(5x=P{a)w4555<+JM0W zDuc`d*$FcfW*6vWR+zXmTn|VDrh+gH3TcQ>2&)|)>L5NI9)2M%&Okn{0H5OvN*kb5 z1WPTDv`3sNh%`U=)q{LIl47_5e6lmO;w2ecc7aj~D8(4U%PL4&2NO47Fh(hL3>b`{ ze3&>SeIfM2%0`Gfgg8VU%sg~)n7@)4OrYk2%mKx51%n~997ebaBv-+JC|^yXdSG@C zOT)||mxkE`@hi-425>*X++_xJA86$w$lahYE@6ma$b*W5?j?ofJ&=z<@qro+6%0uX z5VJsa4M-jl7BIVEZh^%MjE2d>!WAYCG0y;MF2c<)b?9MY$WRM)EzBmE$uJXPIv^$> zVi;nRA%hWvB7-4=Bh(Z~m>7anwJ}2=1L#CaP}rC=C^3LWS3&V^0!?ie(9~%Or4ymF z0fPmDGJ_M?#3ZO#GL$xCFl7h=%cMX>(ijXFR2YmIKqsGr!q5V2IwBqn8DMUL#FHVk z-UppH15$6ukjS9QpvDlxpbozAL5snJ!IS}XhlT}%C4&`%GXv;8YBvUV1`h^L1}}zS zh7g8OhA@V3h6sj8hA4()2FU#=pg2xv$Y981$YKDslu8-O7|Izc7%Ca6!0xqx<~a*! zIkY52a>mhnqvty#}aCeCDa^C z21~I0mQZsNq2?q)%}Ip1ClP8+BGjBjs5yyHa}uHEBtp$e0>?2VwIo5!N`jgNOV>$I zvyz}@B|*(ff|`{CH7gnFrevr&uzZpXbyG6boMfmu$xw5Wq2_>2ItPVC3e=nws5vQ6 z_oP70Nr9S^0yPKL226pP1G*0wWKJqHZKXoZONE*TisMwMnW<1SQ=w+2Ld{Htx-AuI zW-8Q=X;3rMpk}5)%}j%umj*R24QgH*)VwsPd1+AdKxY?#+=#tw1?4YD{fQ_?VL2F< zqhUFn7#iebQ2xcG7G^fFG|U`Gx}iqd3JMEYdV!Unu=Iy0tzhnh*^BNDNa+SDFF`&A znThE(NclmyY(lC^|EnZX!ZvVuYYRH{Pso5D+0NQn!n-9V+P z3N+<{a*Hb1Ww11E2u-`#%39=-mYi}He;Er2SyIbdkdFs{c?n1iis1^F11qDd`ZVRZr`7bk<$I--1l<#*IF29c}LbGZS7J=6q<4p_}@ z!2pwimF=Ki(6Ar47n z2>qz)5aJMZFn#Fauy{moV^Vkg0_0t3&`50s-sLc(bVQL^F3xwO*Fgs~A zhC%J|3z(0oJB9%{6_D5y0f{>U6EuDSx}&d@0koFhhQWqGfq_^XAa~lsZs1E~0L}S; z?%4yG1UipUM)f0nrVwPR0z(OdjOuQN5(d!xj{<`MxL<=hCuq+AnoEpi&}YbF&}2{m zt03MzFh7G%V*%}*1&tPfPRuR^-@6DBq0GM!9~0{ym}@|%gwpR6QqUNd6GJG2J9q{+ zm;n+Npp_D!TMtvg_nCn9N`U5fK`q`AhC~L?=nQDq4s?TX216o49(Yy`l!`%a2c1a@ zIpK7$m<_qZIF|wBUeKB7pf#N-;IuM0-8)pnd1Sgfk0GByfdRHg7PO}bG{X#8BMT}? z5*c8#&I;f&ic1;tz&rIp;vm&l45;TLW6ta+f^TAig)Zv4Wzg(BXtx{av`G+M0KS)~ zk|C1;G{yv((TBK2kD-zwks+5MhhWNw*`&Y#nu7l%zD;C6FC+9AAmIsHkpi;QlfjR{ zjlmxpE})o4mUU&w1M2~WBdC<5b$o-?X(T~o4U{54d)5^gkn7qQ2IP7+h5^*#g4CPn zwXGgQJ_G3dU(`?~Jq$p*SMnG@H9g2Rpjs7F$ACg|U_%AuFTx>1T&RFj0x7j!IYSWx zq*emCg8W(tv_1w@0)Xze#bqY87(;a{C@%8AH9e?J2J#E&j5?63Qov~ml5!F2xL_#? zRGxuu&(4Lmyl8n-1ZdS$5d&z14YAHgm%)gkg29+Uk0FbpfFT{NT%(r12bZrvv4a|W z_)9fhse)8jF}O0Iij1!6q|J%pu-L#B2iVqinlKnZS5boQn*o&?pi~dJnFo|M zKYAetf0H}RX$)Jl?A|Thr#Fn|EBOkOHRRN_F zP+M+rjC_D{38;;Lzr_OUeUd)PL~HYD>2_M14Jsc7&nQJ2Ll#3CLkYNV90Mj{yNU@~}V1SkOkWo=WdhzEDWRr1?Qh;(i$aSEc1nbeE_8G9LK!_pw z<@ByikZTW+4{(Jq{xE{okf~@rLQoz<4F~+@(4x(OSj}D}53QFIg zniKzs=+Mr$$m5HM917`8fzq=pLj^+#LlFb0l?obXCOlRH(nZNE9H?!a4<7FXm1NW& z3r=GI-C%0~UOf#d4N|d;>|hHC)SQh?g(rhA1E@3x%~=&QfJP&W89@De(EYifG8)vk z0gY)TGJyKGkn?oYz_;Tp;ib22a=%N~OsC7f^`?>ZzcPBv>;jFcdR@ zZXqsUC;;EVn9iU_Vfl@%tR=QjGCB@~e@`!{T>&})1~UE&+Sv=+LFfj>H|`Vwsuw_GJs^xc8iLq`OX*%;gsF(x zfYDvQBV#QfY~39wmBH8}g9iC{bl30jPUWCDrdDc(t(qO&D`r7HM&6wUTfGURVJk&p zt3P3UVriH;=tgRpW8CQb|u%E!pN5zzI(%qEtG>8D=V3W|5! zGSlMm@9)SRviP)h4lN)TienGCJ#*SZ59G4*N`W^l|enCD4h2GFP zVF8j($=~q{@-gHDj=^`r0>p3B-ti0aF{LLefaV)O=>*oE28~if_~>ORYWafLIR;UO z;KTOy!c3&*j$e?EL1i_>EufQR2J@+9)acbgd`zw06RJ7nn+?(lN+qb~A@0Qg`PssO*N=2df>(r(xzm z>Q>CQENpBAa;6My*DuJ&^xXLiN>2kjh5_<1$Q8IwFB|-07_`{+3tDFc+6e@j4+8B9 zC2ij?C`|FKaKXO@2h`>Qt??jzH6Uo6!@!w6xK>^cY*-A{I2^q02CbnOJgYeq8L}Ai z8L}Cwz$ei`cJd7NJ*UWSCR9Qpuek)R9|G;%rQe=Y#H>4F)fb`lHi%s|h_#%cl?X}T zbJ!94_dq3j33&f9VnrBY9S6id(Eb9@dL7V;805X9sG+9EfX$tR*JL4dAzVtIbykR# z1Niq5g33-*f8eiGhT7`W(G^knchrH>Irg1#h_s7sJq)M>gzR+EU;ypa0quwz-5Uog zg@)RCD02qvJHv>Je^B}Xt%L$$#JZ(Kq&o>lS3`mNT(Dj>wy`0|7$!^wVHyL?<}#}%V@ATW&H zfdEM*=%;go#$!kCKp6aIa)a_QWVD_9S^B{`Lk~%rsnC<_!Ht|2pe~}K;(zU7zUy7 z3y_aN?P1ueBS?Bjv^xp$AuTZ6?Px;sF!LdGA?@4Qkdx~{=^f!_nB6e9Kvo7L+yaw_ zwY_2TurPzsFnJh_?)QPZ0|6Arusg>FZVY2|HIysEU^v}>bTt&{%SrU3 zo|A3NV2SmdY+~~OsO|!-g#uyZ^-zejvLSUs0rYN{p?^j;(HUkZP(eW>k5z~|G!HHLtk z2ZqWS_Q-A~Hs6BOf%XZ}cIOkw7Hl`}Aw~rttwK=xC%pS*g#onM8B!{Y zX)P$e{gAuw9ne_kF?kg+XZ0&aff|JqFmlSP&W_8o-dl0K4lngaOi4fZP{_Ez|}| z3=}dU&>IL+!FNL^Gh~DB<<4cuX8`SbQvi>H4c?I-NKB+MKxjzVV?P-iwCc|sT+Tph zM37pL597hN;$ce#pwI!0bbzor1Bg^*C}se$R2d-m>lQPBM(Y#7xAP`}?>di%-x#C8 zfEXdk1>d2X%z%(BW{74mV2EYVWY7VhQwK5~l73Pd6d34rzZxXehzmVX_#sXfk7tNy zC}IHJhm0Ib2p=cn*dqryj{(*) z7(jPHAlEIRmPRx~DT6wLBm7=^kQk(PLA|pX)RsrTqePDZ1Qi$*8EhF87$`Rh6he zBuvRg*YhHm@L~{k_XiTpgTlCJAh$vQ4GD&0@++p`i0!z zg05PD!DLXy9LPtInhkVov>}561L#Bmh}%IWK5|@wLeGT(G7F*r&R+@)pj2YaU<|%- z1#|-oBprZCP*7?H-H-qZH_)vg3Jjn=Ehz0G$^y{+hZPJ6GfTjy7WgrM^ngk`2p^;# z!~>1-L2eHrwpJXN@z!t#M}{BoJrufO1ADxP7Lhj!-i*89;dk6fdp}us8+P zBI*pF)=>&WDY&!-wFe+BgUlf+Fo1FhsBD3ZdB9wVFin9$9c#@CS@8t&IU-a+_K`AX zgxaD7nUfB_k%yY5g33?OeLtX^DM2$wARmJ2Z%jKtdBcstADlY|zK%ey&G5SwlmJ5+aB4;Bz@@O99p8Kz*XoF+E~O2SF(bghAy4XcPoA<^k$m!sfSNeSUh5>49pM zY=&fpN`}-yKBh;EOF?Ri8Is|34{}Hkw=q4CUrCEOQd;Anbcz^%1C8g>a!e0o8)zhN z;K%hqE+O2C0;xi6*N%?ufmS~u!en%8Z***rivf`yK%0@|}laL-xi28Xbq(_8n2iw>lB_R*;%g7zuBPQfPYG7?_ z)ciXb%1oH+hE{or-PNdNCE->nOa*Lq8?-8YbZifOwN^R2WZR?U5hypcc_c9@`@va>#9K)ci~Pu|48l2kOH>_LG426%F?C5*DVY zu0|~@VIy~h>Cv%0P@f#vnk~@&3DCMd*h(7mM)yD^G-x#$$d-Xy!3S~$;q-v40;FT; z>;nRYE@TKo#M-D;lUyv+l$5t)_>S{oQnaDaIX9O03_wK@602;Lb^(jVo?iMo)uARH2 z#y_O@02&_z?Er@CLj=V#D27Q{0Yf}PIZ^BVKt3TYKS08R zo-PKt5rmOL9N%g`3mWasC1!!D1iDHpi?P8YxO|q9OLd&g2D>h+CC!&OYlwr z&~8LX`wCP>gVHc$H$Wc4=zd)-@SX|S-cCrkfOez8S{$SMbw~H>f>yGQ?$;gY5)f3% z(Yp^zTHOk2`9jLsf$zss;&Rl!ENYk!w{bsG!wE5xHWbn$!nL5WGW@fLsPRnu@ged< z9^{viJnlz0~$mROdfjN;2Y61q0xvQ z>@>x}6LP5QMo4L|gTfPi)X$Q^gaI@fnhZXH4AK`J9rGJKqYu%y8{Nk{x{nv%KHkAv zGUA^7K%{L@tApO-Q>29#sLW0Q-xmTpsS-59Q@~Kb0K1zr2E3Cg8GI%jq-_8?Ul+sz z(bQ}?z`_jV9>@uTgFD>l7iOf?z_3sp4MF62O4JY>%;R*VgfW44`w-LHmwzjlUtQ(PQvH(gEs+gGO3L z@4f(yMu2K@*vLmQ_?&9;?;8X4=s+WZs4;~7bUa)mY`EeXlrli$WFQP0w}GsvL%z!a zHm0V5l0Njn=ftDBNCUhY4{`oBapO$};PbsftMnji{S?5bdxJ*tKyCwJ)U-UXJdk^^ z=Ook>gNRxYH1d-NJ}Ets0dz(=Xyq2@#QO{e&^^PD{FcH1T4M+~RT~r%*w?)x+W=a# zlEMI5%c#cyx|axcn~5Vd2d6NM=0n=$LtHU|?fiR71~c%8HE4yA0{CP*M1Dp#2b3CM zD+ftWGoW+{%EKUxJs%@>bs?u0&>8qJy|5CTersBh{g0fYv4x`r%Bi2oB@}j_!F+`~ zL|hpP8A`#uFAXpWIq6!D0pSwReFBKk1hqu+7~&an89?`jfbIz)u7opWFkvtQkJMQ( zm@ybJm@=3$=rI^GfP4fS4~MBSXD~xiW6EH{V98*_U;$1!_~#fAvas1kP#Y3*8vy7g z6zZN33<_V6`Jfp)NRNo}eYV)s!{`kept585-;jYl_J`jc8Pphi0ksDqa|xLF5Y>Di zhJ1#6hHU7ZodQECLjm}94#<2R^=7&(7;+gZ8L}917;?e$e%NNZKzn;q!R;PcO-IP} zAq zRA&(iS&+LyXUBue7SJgRpwmS_J--sLIfzgJ$%DcJbo(13bia`T_)aTG-pd1vgIr+1pvPdsU=FUK@wp#=h$EMN@eIhf zon$cNGh~8oBNXD~*#K%6fY!ZN67&J6ua?h{#-P9e8s`J`Vn8?kf_f~VTY*4kK>9c- z1Wm&4Qb?)*-L4I4=YdKLQ0@Z7KIjf8%0gk(Y)~#l&Fw=qOa}9P>4VvALp8o}m65Rf zJRogk^2=aEtq1CXgJ$9K!R-uC%>pWQ5IrnHELaZ=RHKfb;fNZVs3RSqlg&WwLXha_ zXc*{ROVItCpz-&ivH}!2S0ctvu#Zn$G8m9C8b&CMfbu42oCkzKZC}h$Y((pMbo2|< zLn#5b&<1t{46=3&a^o^={0kJ5sAFIz45kbQ43-R_aa52jp^_IS4=aH|wZZ5Z7^odx z0>AGRluu|o+6xMGNI!0L1sbT=4C<+a_GN?mN}zcz&>hr}du&l}iN#))j*fxB=C_c0 z#*ltEXk-OcE+A4Is85bMazL*!Fwp1(sOO%;U^F@gHaZ5zpujLX28Nmw@sIl;mww1O z9W?qgItB&`h0!rEQ27e#C4t)cp!>){wJPXjlT>hv7GEuZKkW_OF%i&uf?NhrSmZMl zfX@jZspGGMdCUzqT0R<23Jileo`!BYfEcett~*D^MhAAqAk219AH|J`yQ`7Mpb_I< z1q`4WHc*{c1f6|FUWWwgRgSJ11ceZ2g=HRiUK}*XoWlURBPfS~-lHF&8X43(1+4-G z&25)3ppJkO8YMMkFkmpEXq=Q#dI6TIr z@iaO@2wTgKTHYX!Tp_p2M^{h6#sKltpwfew5khQdACB%S28AAIuR3H00%(SCIIp8L zWH4qhCvt?4yz~MJPtfQf2!m>3d?SP*450iD8tK$vfRwPg4Cwo4LHCq{)`Wug0%b7h zF@Sb*lpyV;)nLeFfX!7P)M-L*mjStgwky^^buVb#fZQ=#3zU_upb=+KsDV}|Ax2UW z;Y2ueK`T~aD}WIufX-L|or?l;DQtIgG6U$u+!SzXK#Y^xZO7%Ca^ z7>XDwNEovP)gO?PSP9(llgnG`{*FJzkaPW-|f_6ZI z>c!E$v!H$CpxJs*c?$~>(1_1aSjRR}M<|f%H01Id)^?|K4<;fVAln2RLm=>SP8|oR1_+o|@b(;}*%?CbP@z)unbsM7O#a?@ob1uYa-3D5V zuE2mgGKwhEKz;SWzeansZUgllLGy{l44_s#ed;#YSO;MmHX1T|x&WwVMO|AN&p>Fr zlhE2o(B6AcUkqfn9=KNqVxiiC=*^Fwzd5+aWkEa3O~GTMpgt`A6F4bNIiL|u&`321 zgL?6lj+ukbm;{YwCBjF>kym{~Msh)R4el5i2_xg6adFVdI4A|6u31JM9XDq%WiVm@ ztyrf2=s3u2ISlzI=jqun*f4<3&m&ytfK-4?Ky7i4p7~kAP|Og+fC!b*Rn4QTnlbYU z>R2!Sp6SpTMKEGWWT*tsK4y%LkTc{ljE;~)&PzicUmG1opw{}u(NP4@DyJgo3KPo8 zSX!>(!&QFMXA}X^5&_MsP@~=%nIq)XsM|(I$VX>?A-h`;Cnt}NkdKa#gT`%P=d7oJ zM;MD3M(Z|EeT8V_AlIU>*V#dTl=Zd0^hP!}on?N=bw5kWZd5X4072ZhQ&E~`KrM98=rjmp9}Nes*9YD7ron)|Iy{r17(V8Wyrvwq z>JxNYG;CeCBLnDW29O^?cQS$2L8GqXMBIm=0KTzK0h|*+r*VSj|3P+xTuEG+qRRj) zRX}ZQ`kg6DN*kV*{Tf=DjVSkr#tb7zgaEbhM$i3++!+K~M-N)* z3A*EQw2c8tOQ2c@RQo~pFbwtGYM}ZTv}dc5K?yw54r=k`F{CnpR(ylbvN8mVLgwE= zElbFH3eb67#HI~Uc!AmxAUxWZfTSV9Bq-ECZ57B#?4TaOXj@`rg$1^@1SnNdYfb{2 z`P4BR;BJ2OH1|3ITAd82n~GYp0?3(!q4 zpk1G&wkIGZ3aAC4z%bf|fR!$UXi%t)wjnZ!y73hMx}MRxY_xyu13v2x(FX$UjRmbB z1nq_e-E#_CBLG@$4jPq59t|U}UUOxr0FQiv#z#RjZ=>Vx16_xKPBuoq1&_Sc04kRu zbs2JPhCFKqS}P8kIm={7WQb-kV2EV^_0d5)9W$V(st_7IS7(6S5+1{Vd`~!Nhr2EV zXa@u+Boo2+eaA3B)_K9oxEO{Q2GCk#&|Fdu1BeImC1{@+gbiY4gICR#F=R6sz*T@+ zc*P7w49N_jb?-$`@eBq~-awo$1u+BLE_={94UqNMpztYWPzRd;Qg07t4L$#W{6VOW zhRMTv3ZVLWaL!MlrcZ=BLB0g>$m^Y>nu^%BH8NK&q2?=4zQfE_pgAT|V-#S7DHhWCSY(Iv42GEUoF!c%yo(wJwpj!<L1o`J?AZDfs zxfY>PfgzV6lOdfU1AOBEDE%rhgfTdR>v+V>BO&wfw;BRgJr67n8r?Kt&;#EVO4u~WSPCp8(0A*CYA4K< z%%i7?fJzKdD1c%gbbcFU;S5PTi436G4^V#`bn*vv#tsL1Y!6ftkXMt9?!2bW&TB*| z3hG%Q@;9h`3`)hY78GF`*2aRAAdvHn3K&WlO2OxdfaZKb?cQ_-L`_NB9y?v|xfUQd z;Xf^uzOo?qxM97$h)@p}Hp2%B8NzoIL1q$>@8}-wzbY^&F*q|=F~l&0g2ydEy)JBh zFc*e=hGd3P2GFiy(AgfKeTnYi-4Y%Qr3^`EyA)yVLXb(IGq^zc4!Io-i3x1$#w@@m zJYpMxB|a^H($moHy@L9^pk8V!Lq51?2@B7m+Iyvqe?aj}xJ-qpfR(JE+7nWGQonQs zxd&uEd9^cg{)h*UUO?PQO;bTFTF9v*BeVC4nhvq&s?pvnXay^1G@bOm_E7A-g7Q}x z1E>vG$}o6(upn1~S~Z9e1&QD^DGYFcdN5 zgLmM8`p=+IPskZzps{pNzdoA5g29R*mdN>8A8^_Ntsel5cxE!BF{Cko`t6{x@Ms3| zXK(cwKoEA%1LY=xLI{LG=ahkb32ME9d<=6hVjLc{)($p)p}=4OJ*yuwYl}PwUBZAq z1C2ia3>t+4&2E5ZpFuGS8uJ5Yz0$DGZQ( z&Xo+f)=z01uA2gt+@L&;Uh+~t?u;!4u#G&M zFj!#SNrW2Dp!5JMBS0k}W?ZU+O;KmiWk_Ryuwna85i6u%buh>zP&xqBOo);A0ES8i z&?ppW$1&(UN6>1gOz;>xs3i%iZ*-wI)MPV&_S%C+*kiyq%7AVqL$E;hVeXo;M7!M! zxh(;jB?a{ZK<)vh?Q-x4e+IaW1i2N2L2jsE&|?6tkOGyxpn2OgaLXf?L4yI`sxJ+O zcyJ2>)Jg%JNdc;hK{M_UKWH$3YE(!)4BCMWYQrFlz(Sr{;RW*twzL2`LlZeQVDl@? zJ)kf_$Sc5CL!^R34PSVGT2i1Hr~(GasfM5$4>Bs9!;k}B^#JM{*KJw0#SqEXAS=G`@uV& z0y=9!0lvx-6xX1V1vGAu4xU+tjCz8^6u_qpLe@lq)=YugRn%^U7BJ*7{qWHOX8 z#DIIhptB7@E1mQhDj7f{^f}<1lLS6L1l0ck((Lk>dgUlz?hD0_K zHm;@)UDX5XQ-MZP5cfjTs;5kjxgg(R?_Hy=h5+R_NG~BCTt0(N{K#Pd&G2C#GY8d< zh*ff+JcoQTy$|#Tot)8}M$?>z9Ol^jqM-XTjKTe7P@N6Aj}jEus54NYv2xIS7id*5 zYW#!J4=Cq>F!tOBnhnul0M*!_+g3q+DM%e&&Hx&T&4cd32A$sp$|ayW9yGfKaswp2 zL3;3z^i)jb$T=mpA1J}=>Rd1kCB9IF~_Z&xq{er*sgqn9iZB@uhB8Xo=t|LW1 zDCCjX41vNN)MEg(3=t+mdI_}I%T)@VDYF2t#0QN}BKr@-2lZefGnb%IeT17pm?nmY|+JDI*K0xe;Uzq;3SIB@hphR>?ONy~YIj z3zSDO?LZ!vfz+VX8?!>KHIe-dnmL8-jRVz~nC?RLJMr}>A(JSn6GzPkwQxZ-D=621 zPFsM?Fi?_eAuS@1nTXnYG@Pj)&d7ZWMCpKN0Z^lkv3!P~~8)g3&QPP!ABb zm4&Mp3fk#BItl?wF_76JP-+Ct5rBGEpitC=uCoI5(Ltk~pf)dJuAA1o&LBN^NFARJ z9&5v#5jOd?FQrb8pBPg>ex+Y;8(W(O zkxD3Off8#9$iKvd3;n``Q2T=vpMlDE$Y>jC{RryefL51)e2?0yz|DiTH$ZJzNEtmk z3PIaC5){&qKJMr!#ONplWK{|+M~LV)JBKqV(4f08<~g}=rbyk=vc zGZ?(?9lGI6s1-n2m?LsCX1f4nGVWFYx(uvU0P0gh)}v8(USg=7f`eRY;u?i8!np$h zy$9^Wkk5cv8!@^T0<=7Jq$6Y#0wFQ>f=F>}{LD7bYMdgHkO$Mn`bvCd6zAvEhTS#W6Y(0a`&0 z+7AX=mkc^54>T4JS@{Gy=@fK^8)U2nwAV-hycP)0>uv~ zzCe3_KH;Z0qrRU?J81WfVA{M`%pmpctG<#ppm2! z2GELU4Te1M&Ua951??~dl_Q|_NH9@N20ey&2FNL4pq=g@wjR<+6U7V~46vS?BLl=t z#42jYzGsjtK&81l_@od}iUpP3pgWBqE*rSnP>@?7JF}2;52#eZT{EN0jMmhkxFxQ{ z9$m2rO6#CH22^i@&X^gfF%VdMkzP|9F_>Z9H;G=if$DBZU6sQ?&6SGi_Keolpmapd zyE;JSA8NmIboUhKG?>wKOQ6yVRC0m#fzWsN)M!mj&M5~VJ)qo-{iFl*k`%eb9-Y+( zrS+j*QyVjwkX%z6QE^WJdiolPH8m*rDIndc0-5=ue{BtNhZchZ(kY0bnYVlfk5V0Gj_! zWC(_ejGh7vIt2^V7pDFxz?h+rZ3Nts0sGzQ_+uQDQb45<2;&?7RtJyqfzBPuXUJv% zt>grqv=|A5onDa=!W!E26gcH ziZMi8T1%Z7?Qvzc7oij$AEC79z!sA922yE5>y63%41O54b)EonGRavU%_C2 z0gV})7)%)~7z`O)7z`Nf7;3?_9Qx=UEIG1k;3`ot#bIR(s24iA8zG({jUkZ% zbV@EL$EJf@KKbC91C+u*r=o)9Z9zBJgHCqOWB{Eijk`?*Iybcle9t|yYCVPka1ROH zlmLbt23XH%B)64ldq037gE4~vgDKLO1!zXHgaNcZ47A4=lzTwsGYEs)0g&^;Ky#XD z;B)$t88jHQz^5ywGZceO(PGeoo)`^T_YV?>oIwvVgSPu!K`koKiULrp5;VICS_^?I z)nRK98Z%ge{Qyes$mdg%lM9eT4$)2ooh$(AKV(49qSRn;1K&moQZZCQ$rL4&(0zp6 z-^k};0}eU08#Gf6Dm#WsNSUF`+hGp_ zD;S~~KvVM*9t*a(Vdo8?eVdHF^)IYjF{|0+gpf zJW#6+a!LRx{RUK1A){WP5f9WIbC`C}a{WJQd4uf2(e?kM>;FM@%;@@mP#?DhJnl!! zQ3d3@2Wt6(T0x-FVRZdJs9iJg7*sA}pZUOE4}tC_%VUTK_gZkB3K~IgwYWIX9jwlSAad9vESifjB;uLDDA-F8P{kKG3fdkQemZ#m1LSKEM)(|5 zMuK>t8*gEG1JqlF)mfmp0rdu9{bpEMN=nZeg^R+WKv9V9Y9_JVQTQLAz~1r4s1g z7tsCfklW2r%O~U(KYED-Do+q871R$y9cdW7ePDR*Fo(5VMsFVgwE-b{3bbDm)XD>e z38b3M7>k3o5Fw+d_;Mir^aslSxO#n{yp7o^z$F4}Er3QLMrYay z^_~#<2f1_w&CrhawLu{;7|%R{^^76)C1kD+dus#KpToSVz!+s-9+bOaCX%08K&F8D znjj1+dxlp}8@47KedGYUuj$dt9_?WdmHFvx2GD#}2}2IJtqa;uk8OS$y*)eH!v?iA z2<>aZUh0j`XM@H7AuTdcc?`nCaUCr7*dOg-lhVTmjs79ZC*(FDW{HG-v=3AV;%oPh z_Pp`;d=M>g&_0d=hD-)f>zh!h;y06)^RBcs8#(=f#(qF8DQeE?BElNkCRljm>QQ2f zkM=P^BW#FX184;==%zN%YCF)mRiL=b$9a}KXm4sFLnQ-fg*Hf6CBx{9EWKuAA>oa^ zUue!?3|{F8YCRyYQpO&;pb`qyvH)Ss9v@_8UV{O7wJj*0fyShA8B!Q*8Pvh&)n+i{ zL+?$;R0&Hbu)XKD;9KkU81xvb8EP3~81fj@p{Kcl+%OP5B7C7~iV~Wzo+Bh&u!kL} zv;&1CXm-|>p^%{zycPl$hM>MV#6DPffL7w7hmjrwD7HZRN5-r11>wDuXa;{ud_L2D#X&-wzL=?w~X$l6`n+>HlXeVoKl z$WY9X!~nVr59G%r23SuCG}4j5kjkLI5W`Txkjh}f016|}s*Vzd7zPD~Xz;$lQt*yg z&=@EvrNuIU+^h$mc?5+y%qJilkk=rC%tzlX3TppAR{McW1kF@{))yn@DnNQ*vlSpV zXnd3sUx4hx?-P&@bQu)D{({5>vL8wq(0xE!J1~&}5&o#54_Z|K3VRvVk0{}u$N<_C zn#llKJ+Ht3l7-y|4eGsu+I=7wCo=dkK-7dVfa+h+d2z6rVvxK&11R?@Fo0@V5MLYW zL)3Iex$i(`Q{RV#djFlrVrs^D4pXf@oQD5z3XI))H**rviM(6J%!sA-(u}+{h+_N)}KH4An$X zn;X)81NEIyS0{jUgGywO45%Fp3Nujo4lAKSF#$T;G?5{XAq5eeWpw9rR zM~k36NaFgCh~3Dbxm3_zeo)N^I@bl%@&u(ske?tqo-he36F~J4?v^rTHz&(7(=yDJP=nPlTc}1WV zyPz>@MEe7k2O8H0wZ~w)YCz$j&H(9IqmG+mw;O$AnDEGUHiIPtq@`sB9-pU%>p`xD zm8FDeSXm1S5r{iLJztPNASVZbM*JbGg~;y-g4_c#AJO8Y{H**m@adeOQ;!nCW9Or5 zlR#q{!+&iOdb}f6B@s&L2zgkVA8lVi+83ZxML~BrWP)cildN5@APXxFAdU55jT3GD3) z(78>Z`WX}>$ZHcwNfV&*9oAX^^~oWlCde)Tttkf8B$*6}4ABe*44^q=Sc`(VHUMpF zVMB&0h8*y0eId9O2Blt5IxS`Zowf^U#eiB0pm8J6X)K6cH4stId;(~{3n2`N49G1~2w#E05!@OCjm?6_KtZcI zKqet%VJj&>qWH}B1J55K^0@+oCxZ(EXnYkkRtuRegv{vUGX*q81&R?+I~7v8g3eQg zjCvy6gjjO}T5+JjfRG{9wT=uhl?veVTGJUa7(o69xlMr~jKL8cyNI!3LcRyN8#E&Z zOCPASzKBo($%DcJG6DfwuaXHKfk*+Dc_7580os!fu^TcT z3tHJlIHa8!Aai)2HVnwbRIraBy(!S>2`JZLOC6XhU?E93j7k}j!E1CttGqz#p zwOj=GrWkx4J}3=?W;8&tOdA_Oy-v`KZ6(3b0J1=xhThf6*pP${C8lGuf#GQvm+_lE{z-zO4at2R60L zq-9#bmFGZXub`e7q+bsz1#p$8gu(+>s-gGMASE^awj8o7tX&5wL8w1gG}KlN5b7s^ z_Bn$_;6ZDPu-`lb8vR9&6;OX|wC4=!Q__F+IdWbEt?dALr8v3ZNE0sI>+fOB$N}X4?1%6wk)5IZuuMSFN0R91T&2Gm&t3r<0`jC`^zJ}FHWt#?Pz})bqowqVx#xWM*GW%we+}I zpcXIoRrbgs3mO>*jZ$Op7gvFA8OvwTV~B#XK>O=pyG%ycqtR~e7!mT==8O#)j8M)L zhqX>oPnd_qEhrs;dbc2q=;4Ce-5?%l-UE3*Hsp3!(0ErKg9ZcWHb&6QE2wM&-DsD} zpvM5J2|@Edpk5}iHzR?@iXro`hTu^}e7!GZxq<14QNA(?7JH*BqCoQ-kdaeR`U7Fe z9Et)1OjtS7scx3-;tpNyn`NeIvHr+St|NQyTD2rK&c+IVgTYY$lfCb z22lG3G^+vH)1d&KJqEcDVVVMiIs+`e5i6lUV+Z85G-=Qcy>D_k`zY=$(NL7kzJ0kjSUw970OJbrBeJ?n+gX(dMBTL%!eDP&F?e;!82!g4bx z#0KZMCVGxSjR8=2gWOJDxk^j3VQ~v`Z$1NTo#xwT84$?TGT55DQkmkG9qztu@fOV4yZV zs4W0l9S6!KptC5_!8f#nZe#uN_wbU-WH zhfce|k^wS*0UC9N?DYV(D?srIxbb& zrP-rnJfMChFA6cXfLH5gB=5CbtA1?bFjYUV4y*D zau9fTA!xUm83X8KK}7uyYS}|-d{YKf20aE71|tRw2FN%jNGEI+j4Oi+_}+$K25$yW xh5!az24e;j@cavCk3kXm9M@t7TLx38Xc~Bw2sAPZTK^1^F<~%<_U%FD0s!mTrG@|i From 07c95a1bf16bf86c640436208dda828cc7df0181 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 11:39:05 -0700 Subject: [PATCH 0840/2280] Require an imaging backend for fuzzy ratio tests These fail outright if we don't have a way to get image sizes (e.g., ImageMagick). --- test/test_art.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index 02d26f472..1b12b76f6 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -561,21 +561,25 @@ class ArtForAlbumTest(UseThePlugin): self._assertImageIsValidArt(self.IMG_500x490, True) def test_respect_enforce_ratio_px_above(self): + self._require_backend() self.plugin.enforce_ratio = True self.plugin.margin_px = 5 self._assertImageIsValidArt(self.IMG_500x490, False) def test_respect_enforce_ratio_px_below(self): + self._require_backend() self.plugin.enforce_ratio = True self.plugin.margin_px = 15 self._assertImageIsValidArt(self.IMG_500x490, True) def test_respect_enforce_ratio_percent_above(self): + self._require_backend() self.plugin.enforce_ratio = True self.plugin.margin_percent = (500 - 490) / 500 * 0.5 self._assertImageIsValidArt(self.IMG_500x490, False) def test_respect_enforce_ratio_percent_below(self): + self._require_backend() self.plugin.enforce_ratio = True self.plugin.margin_percent = (500 - 490) / 500 * 1.5 self._assertImageIsValidArt(self.IMG_500x490, True) From 82640260c266aae3a895dfdd934b21a149aa1dad Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 11:41:25 -0700 Subject: [PATCH 0841/2280] Tests: don't unload the beetsplug module This was added in 1666f883e3f6a497971b484c9ba875df2f6693a2 back in 2013. I'm not sure why this *ever* worked to get beetsplug to point to the right directory, but I believe it was superseded by the path manipulation in aa07eb95518da255b739a2c6c19a06ca98b513c3, added in 2014. And now, it's causing problems on Windows, where for some reason it's causing `import beetsplug.x` to silently succeed but yield an empty `beetsplug`, without `x` in the namespace. --- test/testall.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/test/testall.py b/test/testall.py index 9148da8be..aebda21ee 100755 --- a/test/testall.py +++ b/test/testall.py @@ -27,13 +27,6 @@ pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) os.chdir(pkgpath) -# Make sure we use local version of beetsplug and not system namespaced version -# for tests -try: - del sys.modules["beetsplug"] -except KeyError: - pass - def suite(): s = unittest.TestSuite() @@ -46,5 +39,6 @@ def suite(): s.addTest(__import__(modname).suite()) return s + if __name__ == '__main__': unittest.main(defaultTest='suite') From 2228e0e8e170299f71585b00777f4e3e9fc6d31e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 11:52:56 -0700 Subject: [PATCH 0842/2280] More binary-mode open in tests --- test/test_embedart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 3e3ce4bea..2e240cb41 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -57,7 +57,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): def _setup_data(self, artpath=None): if not artpath: artpath = self.small_artpath - with open(syspath(artpath)) as f: + with open(syspath(artpath), 'rb') as f: self.image_data = f.read() def tearDown(self): From 581fba62883e15f08ed0be5ef02b555107b85d8e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 11:58:14 -0700 Subject: [PATCH 0843/2280] lyrics: Avoid crash when enabling google If you *both* haven't set an API key *and* BeautifulSoup wasn't installed, the list.remove() call would crash. (This came up when running the tests on a fresh machine without many dependencies.) --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b6936e1be..105dfa341 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -611,7 +611,7 @@ class LyricsPlugin(plugins.BeetsPlugin): u'provide an API key in the configuration. ' u'See the documentation for further details.') sources.remove('google') - if not HAS_BEAUTIFUL_SOUP: + elif not HAS_BEAUTIFUL_SOUP: self._log.warn(u'To use the google lyrics source, you must ' u'install the beautifulsoup4 module. See the ' u'documentation for further details.') From 9ed9faf24674a243425e2fca865831a48a1f4a49 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 18:52:32 -0400 Subject: [PATCH 0844/2280] add some b' to paths in sort tests --- test/test_sort.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_sort.py b/test/test_sort.py index 16b594c9c..d10bd5759 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -153,10 +153,10 @@ class SortFixedFieldTest(DummyDataTestCase): q = u'' sort = dbcore.query.FixedFieldSort('path', True) results = self.lib.items(q, sort) - self.assertEqual(results[0]['path'], '/path0.mp3') - self.assertEqual(results[1]['path'], '/patH1.mp3') - self.assertEqual(results[2]['path'], '/paTH2.mp3') - self.assertEqual(results[3]['path'], '/PATH3.mp3') + self.assertEqual(results[0]['path'], b'/path0.mp3') + self.assertEqual(results[1]['path'], b'/patH1.mp3') + self.assertEqual(results[2]['path'], b'/paTH2.mp3') + self.assertEqual(results[3]['path'], b'/PATH3.mp3') class SortFlexFieldTest(DummyDataTestCase): From 6c661c43279e243950a05f4fcfaf04ad0694522f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 17:15:47 -0400 Subject: [PATCH 0845/2280] Replace __cmp__ with rich comparisons for Distance --- beets/autotag/hooks.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 3de803899..d0e3d9c75 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -17,6 +17,7 @@ from __future__ import division, absolute_import, print_function from collections import namedtuple +from functools import total_ordering import re from beets import logging @@ -288,6 +289,7 @@ class LazyClassProperty(object): return self.value +@total_ordering class Distance(object): """Keeps track of multiple distance penalties. Provides a single weighted distance for all penalties as well as a weighted distance @@ -354,10 +356,13 @@ class Distance(object): key=lambda key_and_dist: (-key_and_dist[1], key_and_dist[0]) ) + def __eq__(self, other): + return self.distance == other + # Behave like a float. - def __cmp__(self, other): - return cmp(self.distance, other) + def __lt__(self, other): + return self.distance < other def __float__(self): return self.distance From 82df8d18df2d34ba1410a40a921d7f0d074755ab Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Tue, 31 May 2016 18:37:11 +0100 Subject: [PATCH 0846/2280] Update tox configuration - Add support for Python 3 testing. - Add Python 3.3, 3.4 and 3.5 tests to Travis and AppVeyor. - Allow arguments to be passed to tox from test matrix. - Simplify tox configuration so that we now only have `test`, `flake8` and `docs` tasks. --- .travis.yml | 23 ++++++++++++++++++----- appveyor.yml | 22 ++++++++++++++++++---- setup.cfg | 1 - tox.ini | 37 +++++++++++++++++-------------------- 4 files changed, 53 insertions(+), 30 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3399b2bf8..6b3a60e8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,13 +4,26 @@ sudo: false matrix: include: - python: 2.7 - env: {TOX_ENV: py27cov, COVERAGE: 1} + env: {TOX_ENV: py27-test, TOX_ARGS: --show-skipped --with-coverage, COVERAGE: 1} + - python: 3.3 + env: {TOX_ENV: py33-test, TOX_ARGS: --show-skipped} + - python: 3.4 + env: {TOX_ENV: py34-test, TOX_ARGS: --show-skipped} + - python: 3.5 + env: {TOX_ENV: py35-test, TOX_ARGS: --show-skipped} - python: pypy - env: {TOX_ENV: pypy} + env: {TOX_ENV: pypy-test, TOX_ARGS: --show-skipped} - python: 2.7 - env: {TOX_ENV: docs, NONTEST: 1} + env: {TOX_ENV: py27-flake8, TOX_ARGS: --min-version=2.7} + - python: 3.3 + env: {TOX_ENV: py33-flake8, TOX_ARGS: --min-version=3.3} - python: 2.7 - env: {TOX_ENV: flake8, NONTEST: 1} + env: {TOX_ENV: docs} + allow_failures: + - python: 3.3 + - python: 3.4 + - python: 3.5 + - python: pypy3 # Non-Python dependencies. addons: @@ -25,7 +38,7 @@ install: - travis_retry pip install tox sphinx - travis_retry tox -e $TOX_ENV --notest -script: tox -e $TOX_ENV +script: tox -e $TOX_ENV -- $TOX_ARGS # Report coverage to codecov.io. before_install: diff --git a/appveyor.yml b/appveyor.yml index be561eaaf..6e79877f6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -4,17 +4,31 @@ deploy: off environment: matrix: - - PYTHON: "C:\\Python27" - TOXENV: py27 + - PYTHON: C:\Python27 + TOX_ENV: py27-test + TOX_ARGS: --show-skipped + - PYTHON: C:\Python33 + TOX_ENV: py33-test + TOX_ARGS: --show-skipped + - PYTHON: C:\Python34 + TOX_ENV: py34-test + TOX_ARGS: --show-skipped + - PYTHON: C:\Python35 + TOX_ENV: py35-test + TOX_ARGS: --show-skipped # Install Tox for running tests. install: - "%PYTHON%/Scripts/pip.exe install tox" + - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" test_script: - - "%PYTHON%/Scripts/tox.exe" + - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% -- %TOX_ARGS%" # Allow all failures for now: the tests don't yet pass! matrix: allow_failures: - - TOXENV: py27 + - TOX_ENV: py27-test + - TOX_ENV: py33-test + - TOX_ENV: py34-test + - TOX_ENV: py35-test diff --git a/setup.cfg b/setup.cfg index de1f48545..b093a20b5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,6 @@ logging-clear-handlers=1 eval-attr="!=slow" [flake8] -min-version = 2.7 # Default pyflakes errors we ignore: # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) diff --git a/tox.ini b/tox.ini index 6c6818908..41a97e61c 100644 --- a/tox.ini +++ b/tox.ini @@ -4,9 +4,9 @@ # and then run "tox" from this directory. [tox] -envlist = py27, pypy, docs, flake8 +envlist = test, flake8, docs -[testenv] +[_test] deps = beautifulsoup4 flask @@ -21,27 +21,24 @@ deps = pyxdg jellyfish python-mpd2 -commands = nosetests {posargs} - -[testenv:py27cov] -basepython = python2.7 -deps = - {[testenv]deps} coverage -commands = nosetests --show-skipped --with-coverage {posargs} -[testenv:py27setup] -basepython = python2.7 -commands = python ./setup.py test {posargs} - -[testenv:docs] -changedir = docs -deps = sphinx -commands = sphinx-build -W -q -b html . {envtmpdir}/html - -[testenv:flake8] +[_flake8] deps = flake8 flake8-future-import pep8-naming -commands = flake8 beets beetsplug beet test setup.py docs +files = beets beetsplug beet test setup.py docs + +[testenv] +deps = + test: {[_test]deps} + flake8: {[_flake8]deps} +commands = + test: nosetests {posargs} + flake8: flake8 {posargs:--min-version=2.7} {[_flake8]files} + +[testenv:docs] +basepython = python2.7 +deps = sphinx +commands = sphinx-build -W -q -b html docs {envtmpdir}/html {posargs} From 89088ad7509f177787310ab55281cdc76698012d Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 3 Jun 2016 00:51:53 +0100 Subject: [PATCH 0847/2280] Remove unused pypy3 test ignore --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6b3a60e8f..d07277cba 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,7 +23,6 @@ matrix: - python: 3.3 - python: 3.4 - python: 3.5 - - python: pypy3 # Non-Python dependencies. addons: From 7467ebaacad85d96b4153d319b423961b5d23f1b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 21:27:09 -0400 Subject: [PATCH 0848/2280] check for imagemagick in command_output with b\' --- beets/util/artresizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 6970a7da1..a07249865 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -235,7 +235,7 @@ def get_im_version(): try: out = util.command_output([b'identify', b'--version']) - if 'imagemagick' in out.lower(): + if b'imagemagick' in out.lower(): pattern = r".+ (\d+)\.(\d+)\.(\d+).*" match = re.search(pattern, out) if match: From 85864eb747f29501074e559b196b565a4aa8deec Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 3 Jun 2016 02:32:09 +0100 Subject: [PATCH 0849/2280] Add specific versions for environments in tox --- tox.ini | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tox.ini b/tox.ini index 41a97e61c..b62c7a6d4 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = test, flake8, docs +envlist = py{27,33,34,35}-{test,cov}, py{27,33}-flake8, docs [_test] deps = @@ -31,12 +31,21 @@ deps = files = beets beetsplug beet test setup.py docs [testenv] +basepython = + py27: python2.7 + py33: python3.3 + py34: python3.4 + py35: python3.5 +passenv = + NOSE_SHOW_SKIPPED # Undocumented feature of nose-show-skipped. deps = - test: {[_test]deps} - flake8: {[_flake8]deps} + {test,cov}: {[_test]deps} + py{27,33}-flake8: {[_flake8]deps} commands = + cov: nosetests --with-coverage {posargs} test: nosetests {posargs} - flake8: flake8 {posargs:--min-version=2.7} {[_flake8]files} + py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} + py33-flake8: flake8 --min-version 3.3 {posargs} {[_flake8]files} [testenv:docs] basepython = python2.7 From e7f70c896dc8882cef1fa698237b0897aac2f884 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 21:34:35 -0400 Subject: [PATCH 0850/2280] check imagemagick output with bytes regex too --- beets/util/artresizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index a07249865..11a1fac28 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -236,7 +236,7 @@ def get_im_version(): out = util.command_output([b'identify', b'--version']) if b'imagemagick' in out.lower(): - pattern = r".+ (\d+)\.(\d+)\.(\d+).*" + pattern = br".+ (\d+)\.(\d+)\.(\d+).*" match = re.search(pattern, out) if match: return (int(match.group(1)), From bd93d66c4764b8ed284a16682da500b3628efc20 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 3 Jun 2016 02:42:50 +0100 Subject: [PATCH 0851/2280] Remove unneeded environment variables in tests --- .travis.yml | 21 +++++++++++++-------- appveyor.yml | 9 ++++----- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/.travis.yml b/.travis.yml index d07277cba..d5611deb5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,22 +1,27 @@ language: python sudo: false +env: + global: + # Undocumented feature of nose-show-skipped. + NOSE_SHOW_SKIPPED: 1 + matrix: include: - python: 2.7 - env: {TOX_ENV: py27-test, TOX_ARGS: --show-skipped --with-coverage, COVERAGE: 1} + env: {TOX_ENV: py27-cov, COVERAGE: 1} - python: 3.3 - env: {TOX_ENV: py33-test, TOX_ARGS: --show-skipped} + env: {TOX_ENV: py33-test} - python: 3.4 - env: {TOX_ENV: py34-test, TOX_ARGS: --show-skipped} + env: {TOX_ENV: py34-test} - python: 3.5 - env: {TOX_ENV: py35-test, TOX_ARGS: --show-skipped} + env: {TOX_ENV: py35-test} - python: pypy - env: {TOX_ENV: pypy-test, TOX_ARGS: --show-skipped} + env: {TOX_ENV: pypy-test} - python: 2.7 - env: {TOX_ENV: py27-flake8, TOX_ARGS: --min-version=2.7} + env: {TOX_ENV: py27-flake8} - python: 3.3 - env: {TOX_ENV: py33-flake8, TOX_ARGS: --min-version=3.3} + env: {TOX_ENV: py33-flake8} - python: 2.7 env: {TOX_ENV: docs} allow_failures: @@ -37,7 +42,7 @@ install: - travis_retry pip install tox sphinx - travis_retry tox -e $TOX_ENV --notest -script: tox -e $TOX_ENV -- $TOX_ARGS +script: tox -e $TOX_ENV # Report coverage to codecov.io. before_install: diff --git a/appveyor.yml b/appveyor.yml index 6e79877f6..ca9e5a520 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,19 +3,18 @@ build: off deploy: off environment: + # Undocumented feature of nose-show-skipped. + NOSE_SHOW_SKIPPED: 1 + matrix: - PYTHON: C:\Python27 TOX_ENV: py27-test - TOX_ARGS: --show-skipped - PYTHON: C:\Python33 TOX_ENV: py33-test - TOX_ARGS: --show-skipped - PYTHON: C:\Python34 TOX_ENV: py34-test - TOX_ARGS: --show-skipped - PYTHON: C:\Python35 TOX_ENV: py35-test - TOX_ARGS: --show-skipped # Install Tox for running tests. install: @@ -23,7 +22,7 @@ install: - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" test_script: - - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% -- %TOX_ARGS%" + - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV%" # Allow all failures for now: the tests don't yet pass! matrix: From 10ce4fa8c57f18b28eaca45055429a5636a1970b Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 3 Jun 2016 02:44:37 +0100 Subject: [PATCH 0852/2280] Re-add min-version for flake8 in setup.cfg --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index b093a20b5..099704f2e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,6 +4,7 @@ logging-clear-handlers=1 eval-attr="!=slow" [flake8] +min-version=2.7 # Default pyflakes errors we ignore: # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) From fa7afba327bd44a4fd1caaeaf11c1a0e83bdf1f1 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Fri, 3 Jun 2016 02:47:12 +0100 Subject: [PATCH 0853/2280] Remove basepython so any version can be used --- tox.ini | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tox.ini b/tox.ini index b62c7a6d4..13ac09f5e 100644 --- a/tox.ini +++ b/tox.ini @@ -31,11 +31,6 @@ deps = files = beets beetsplug beet test setup.py docs [testenv] -basepython = - py27: python2.7 - py33: python3.3 - py34: python3.4 - py35: python3.5 passenv = NOSE_SHOW_SKIPPED # Undocumented feature of nose-show-skipped. deps = From 0051bdb50660f79927271593c6f15cda09e3b0a5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 21:33:33 -0700 Subject: [PATCH 0854/2280] lyrics: Avoid a spurious warning --- beetsplug/lyrics.py | 9 ++++++--- docs/changelog.rst | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 105dfa341..aa526c870 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -607,9 +607,12 @@ class LyricsPlugin(plugins.BeetsPlugin): if 'google' in sources: if not self.config['google_API_key'].get(): - self._log.warn(u'To use the google lyrics source, you must ' - u'provide an API key in the configuration. ' - u'See the documentation for further details.') + # We log a *debug* message here because the default + # configuration includes `google`. This way, the source + # is silent by default but can be enabled just by + # setting an API key. + self._log.debug(u'Disabling google source: ' + u'no API key configured.') sources.remove('google') elif not HAS_BEAUTIFUL_SOUP: self._log.warn(u'To use the google lyrics source, you must ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 6c7c04496..9c02bd7a3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,6 +16,9 @@ Fixes: * :doc:`/plugins/replaygain`: The ``bs1770gain`` backend now correctly calculates sample peak instead of true peak. This comes with a major speed increase. :bug:`2031` +* :doc:`/plugins/lyrics`: Turn off a spurious warning introduced in the last + version about a Google API key, which appeared even when you hadn't tried to + enable the Google lyrics source. 1.3.18 (May 31, 2016) From a1030195f740530e376374e25c12d3966081dc5a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Jun 2016 22:16:29 -0700 Subject: [PATCH 0855/2280] Expand changelog to cover 581fba6 --- docs/changelog.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 9c02bd7a3..a6bdb064c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -16,9 +16,9 @@ Fixes: * :doc:`/plugins/replaygain`: The ``bs1770gain`` backend now correctly calculates sample peak instead of true peak. This comes with a major speed increase. :bug:`2031` -* :doc:`/plugins/lyrics`: Turn off a spurious warning introduced in the last - version about a Google API key, which appeared even when you hadn't tried to - enable the Google lyrics source. +* :doc:`/plugins/lyrics`: Avoid a crash and a spurious warning introduced in + the last version about a Google API key, which appeared even when you hadn't + tried to enable the Google lyrics source. 1.3.18 (May 31, 2016) From 7ab0964826f6919731b508b9fbaf69ae337573ca Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 3 Jun 2016 16:10:31 -0400 Subject: [PATCH 0856/2280] add C901 (function complexity)to flake8 ignore list I'm adding this both as a TODO item and to work around flake8 preferring global ($HOME) configuration over project --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 099704f2e..32d3e06ad 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,6 +9,7 @@ min-version=2.7 # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) # - E731: do not assign a lambda expression, use a def +# - C901: function/method complexity # `flake8-future-import` errors we ignore: # - FI50: `__future__` import "division" present # - FI51: `__future__` import "absolute_import" present @@ -16,4 +17,4 @@ min-version=2.7 # - FI53: `__future__` import "print_function" present # - FI14: `__future__` import "unicode_literals" missing # - FI15: `__future__` import "generator_stop" missing -ignore=E241,E221,E731,FI50,FI51,FI12,FI53,FI14,FI15 +ignore=C901,E241,E221,E731,FI50,FI51,FI12,FI53,FI14,FI15 From 42d642f1f603645ca8c3f6b0a17cd3048ef857c8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 3 Jun 2016 16:18:58 -0400 Subject: [PATCH 0857/2280] use codecs module to decode to hex in _sc_decode 'hex' doesn't exist as a decoder for bytes in py3 --- beets/mediafile.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index a359a5b4f..466ab99c9 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -45,6 +45,7 @@ import mutagen.flac import mutagen.monkeysaudio import mutagen.asf import mutagen.aiff +import codecs import datetime import re import base64 @@ -222,7 +223,7 @@ def _sc_decode(soundcheck): # SoundCheck tags consist of 10 numbers, each represented by 8 # characters of ASCII hex preceded by a space. try: - soundcheck = soundcheck.replace(b' ', b'').decode('hex') + soundcheck = codecs.decode(soundcheck.replace(b' ', b''), 'hex') soundcheck = struct.unpack('!iiiiiiiiii', soundcheck) except (struct.error, TypeError): # SoundCheck isn't in the format we expect, so return default From 2f9aa41614a9d7c98696178598e4969ef0f37d0c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 11:56:09 -0700 Subject: [PATCH 0858/2280] Clean up SQLite connections in test harness Windows complains that we can't remove the test database file if open connections remain. --- beets/dbcore/db.py | 10 ++++++++++ test/helper.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 3f701be59..d1f91389f 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -733,6 +733,16 @@ class Database(object): self._connections[thread_id] = conn return conn + def _close(self): + """Close the current thread's connection to the underlying + SQLite database. + """ + thread_id = threading.current_thread().ident + with self._shared_map_lock: + if thread_id in self._connections: + self._connections[thread_id].close() + del self._connections[thread_id] + @contextlib.contextmanager def _tx_stack(self): """A context manager providing access to the current thread's diff --git a/test/helper.py b/test/helper.py index c10d8fad2..197a85d78 100644 --- a/test/helper.py +++ b/test/helper.py @@ -188,7 +188,7 @@ class TestHelper(object): self.lib = Library(dbpath, self.libdir) def teardown_beets(self): - del self.lib._connections + self.lib._close() if 'BEETSDIR' in os.environ: del os.environ['BEETSDIR'] self.remove_temp_dir() From 574f3bc732053abdac6e06063afde6082e5c8651 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:03:30 -0700 Subject: [PATCH 0859/2280] Main function closes its library --- beets/ui/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 797df44d3..675bc63cc 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1233,6 +1233,7 @@ def _raw_main(args, lib=None): from beets.ui.commands import config_edit return config_edit() + test_lib = bool(lib) subcommands, plugins, lib = _setup(options, lib) parser.add_subcommand(*subcommands) @@ -1240,6 +1241,9 @@ def _raw_main(args, lib=None): subcommand.func(lib, suboptions, subargs) plugins.send('cli_exit', lib=lib) + if not test_lib: + # Clean up the library unless it came from the test harness. + lib._close() def main(args=None): From f1b81bc60c5873984cc4bc36514a48631efe8e6c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:14:50 -0700 Subject: [PATCH 0860/2280] Close all threads' connections --- beets/dbcore/db.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index d1f91389f..2745ea4c6 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -734,14 +734,11 @@ class Database(object): return conn def _close(self): - """Close the current thread's connection to the underlying - SQLite database. + """Close the all connections to the underlying SQLite database. """ thread_id = threading.current_thread().ident with self._shared_map_lock: - if thread_id in self._connections: - self._connections[thread_id].close() - del self._connections[thread_id] + self._connections.clear() @contextlib.contextmanager def _tx_stack(self): From b752a58ed6e8c99be853048ca484588487867ece Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:16:41 -0700 Subject: [PATCH 0861/2280] Improve a couple of docstrings --- beets/dbcore/db.py | 4 +++- beetsplug/convert.py | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 2745ea4c6..226a97f7a 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -734,7 +734,9 @@ class Database(object): return conn def _close(self): - """Close the all connections to the underlying SQLite database. + """Close the all connections to the underlying SQLite database + from all threads. This does not render the database object + unusable; new connections can still be opened on demand. """ thread_id = threading.current_thread().ident with self._shared_map_lock: diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 8c7f20e4d..b88a20d4c 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -219,6 +219,9 @@ class ConvertPlugin(BeetsPlugin): def convert_item(self, dest_dir, keep_new, path_formats, fmt, pretend=False): + """A pipeline thread that converts `Item` objects from a + library. + """ command, ext = get_format(fmt) item, original, converted = None, None, None while True: From 2021c82a8b113548672773d8438acc69e497ef65 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:23:40 -0700 Subject: [PATCH 0862/2280] Remove an unused variable That's what I get for coding on Windows without my flake8 plugin! --- beets/dbcore/db.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 226a97f7a..dda08bc6a 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -738,7 +738,6 @@ class Database(object): from all threads. This does not render the database object unusable; new connections can still be opened on demand. """ - thread_id = threading.current_thread().ident with self._shared_map_lock: self._connections.clear() From 60b4172a59f510772a50c105ba77339768c990a3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:26:51 -0700 Subject: [PATCH 0863/2280] Tests: don't use None as a path stand-in This triggered a crash in `syspath` on Windows. --- test/test_embedart.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 2e240cb41..abd9a6f96 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -175,26 +175,26 @@ class ArtSimilarityTest(unittest.TestCase): # everything is fine proc.returncode = 0 proc.communicate.return_value = "10", "tagada" - self.assertTrue(art.check_art_similarity(log, None, None, 20)) - self.assertFalse(art.check_art_similarity(log, None, None, 5)) + self.assertTrue(art.check_art_similarity(log, b'path', b'path', 20)) + self.assertFalse(art.check_art_similarity(log, b'path', b'path', 5)) # small failure proc.returncode = 1 proc.communicate.return_value = "tagada", "10" - self.assertTrue(art.check_art_similarity(log, None, None, 20)) - self.assertFalse(art.check_art_similarity(log, None, None, 5)) + self.assertTrue(art.check_art_similarity(log, b'path', b'path', 20)) + self.assertFalse(art.check_art_similarity(log, b'path', b'path', 5)) # bigger failure proc.returncode = 2 - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) # IM result parsing problems proc.returncode = 0 proc.communicate.return_value = "foo", "bar" - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) proc.returncode = 1 - self.assertIsNone(art.check_art_similarity(log, None, None, 20)) + self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) def suite(): From 746aecad2b117bc1635bea5259cc4a3165bcdf1a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:28:47 -0700 Subject: [PATCH 0864/2280] Fix a sys.platform check in hidden test --- test/test_hidden.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_hidden.py b/test/test_hidden.py index 1c2f44848..2238c9ef2 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -66,7 +66,7 @@ class HiddenFileTest(unittest.TestCase): self.assertTrue(hidden.is_hidden(f.name)) def test_other_hidden(self): - if sys.platform == 'darwin' or sys.platform == 'windows': + if sys.platform == 'darwin' or sys.platform == 'win32': self.skipTest('sys.platform is known') return From 5db8f69bc1f475b3f094978555889e5cfcab6208 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 5 Jun 2016 12:37:05 -0700 Subject: [PATCH 0865/2280] Fix invocation signature for check_art_similarity The second argument is an Item, not a filename. --- test/test_embedart.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index abd9a6f96..dd70d5e84 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -171,30 +171,31 @@ class ArtSimilarityTest(unittest.TestCase): mock_extract.return_value = True proc = mock_subprocess.Popen.return_value log = logging.getLogger('beets.embedart') + item = _common.item() # everything is fine proc.returncode = 0 proc.communicate.return_value = "10", "tagada" - self.assertTrue(art.check_art_similarity(log, b'path', b'path', 20)) - self.assertFalse(art.check_art_similarity(log, b'path', b'path', 5)) + self.assertTrue(art.check_art_similarity(log, item, b'path', 20)) + self.assertFalse(art.check_art_similarity(log, item, b'path', 5)) # small failure proc.returncode = 1 proc.communicate.return_value = "tagada", "10" - self.assertTrue(art.check_art_similarity(log, b'path', b'path', 20)) - self.assertFalse(art.check_art_similarity(log, b'path', b'path', 5)) + self.assertTrue(art.check_art_similarity(log, item, b'path', 20)) + self.assertFalse(art.check_art_similarity(log, item, b'path', 5)) # bigger failure proc.returncode = 2 - self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) + self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) # IM result parsing problems proc.returncode = 0 proc.communicate.return_value = "foo", "bar" - self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) + self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) proc.returncode = 1 - self.assertIsNone(art.check_art_similarity(log, b'path', b'path', 20)) + self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) def suite(): From cf397277d2147e2e1d6eb7c008941cb2a7ee13b1 Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Mon, 6 Jun 2016 12:23:42 +0100 Subject: [PATCH 0866/2280] Support Homebrew's bash-completion2 --- beets/ui/commands.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 867a47379..f66312238 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1666,6 +1666,7 @@ BASH_COMPLETION_PATHS = map(syspath, [ u'/usr/share/local/bash-completion/bash_completion', u'/opt/local/share/bash-completion/bash_completion', # SmartOS u'/usr/local/etc/bash_completion', # Homebrew + u'/usr/local/share/bash-completion/bash_completion', # Homebrew bash-completion2 ]) From 2fed1cf3f22e7f3279c4ba423a67b50e86e24595 Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Mon, 6 Jun 2016 17:11:09 +0100 Subject: [PATCH 0867/2280] formatting --- beets/ui/commands.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index f66312238..ae1b7cdfc 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1664,9 +1664,12 @@ BASH_COMPLETION_PATHS = map(syspath, [ u'/etc/bash_completion', u'/usr/share/bash-completion/bash_completion', u'/usr/share/local/bash-completion/bash_completion', - u'/opt/local/share/bash-completion/bash_completion', # SmartOS - u'/usr/local/etc/bash_completion', # Homebrew - u'/usr/local/share/bash-completion/bash_completion', # Homebrew bash-completion2 + # SmartOS + u'/opt/local/share/bash-completion/bash_completion', + # Homebrew + u'/usr/local/etc/bash_completion', + # Homebrew bash-completion2 + u'/usr/local/share/bash-completion/bash_completion', ]) From bfa56b1d8d12979ef9ab72baa0eaf829f3a6158f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 10:08:30 -0700 Subject: [PATCH 0868/2280] Tests: fix mocking of `art.extract` --- test/test_embedart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index dd70d5e84..44b692362 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -168,7 +168,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): @patch('beets.art.extract') class ArtSimilarityTest(unittest.TestCase): def test_imagemagick_response(self, mock_extract, mock_subprocess): - mock_extract.return_value = True + mock_extract.return_value = b'extracted_path' proc = mock_subprocess.Popen.return_value log = logging.getLogger('beets.embedart') item = _common.item() From a9573cea0cc44dcf96ed8ee215a75e6f308d52f9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 10:21:30 -0700 Subject: [PATCH 0869/2280] Avoid Windows path prefix for ImageMagick --- beets/art.py | 16 ++++++++++++---- docs/changelog.rst | 2 ++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/beets/art.py b/beets/art.py index 7a65a2b80..06b4f8455 100644 --- a/beets/art.py +++ b/beets/art.py @@ -124,15 +124,23 @@ def check_art_similarity(log, item, imagepath, compare_threshold): is_windows = platform.system() == "Windows" # Converting images to grayscale tends to minimize the weight - # of colors in the diff score. + # of colors in the diff score. So we first convert both images + # to grayscale and then pipe them into the `compare` command. + # On Windows, ImageMagick doesn't support the magic \\?\ prefix + # on paths, so we pass `prefix=False` to `syspath`. + convert_cmd = [b'convert', syspath(imagepath, prefix=False), + syspath(art, prefix=False), + b'-colorspace', b'gray', b'MIFF:-'] + compare_cmd = [b'compare', b'-metric', b'PHASH', b'-', b'null:'] + log.debug(u'comparing images with pipeline {} | {}', + convert_cmd, compare_cmd) convert_proc = subprocess.Popen( - [b'convert', syspath(imagepath), syspath(art), - b'-colorspace', b'gray', b'MIFF:-'], + convert_cmd, stdout=subprocess.PIPE, close_fds=not is_windows, ) compare_proc = subprocess.Popen( - [b'compare', b'-metric', b'PHASH', b'-', b'null:'], + compare_cmd, stdin=convert_proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, diff --git a/docs/changelog.rst b/docs/changelog.rst index a6bdb064c..0199d7c54 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,8 @@ Some fixes for Windows: * Queries are now detected as paths when they contain backslashes (in addition to forward slashes). This only applies on Windows. +* :doc:`/plugins/embedart`: Image similarity comparison with ImageMagick + should now work on Windows. Fixes: From ad74da11498068324cdddc8cef24811f25498ce7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 10:58:25 -0700 Subject: [PATCH 0870/2280] Refactor similarity tests The upshot is we can now compare the two Popen invocations independently. --- test/test_embedart.py | 71 ++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 44b692362..8c6871574 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -17,7 +17,7 @@ from __future__ import division, absolute_import, print_function import os.path import shutil -from mock import patch +from mock import patch, MagicMock import tempfile from test import _common @@ -167,35 +167,58 @@ class EmbedartCliTest(_common.TestCase, TestHelper): @patch('beets.art.subprocess') @patch('beets.art.extract') class ArtSimilarityTest(unittest.TestCase): - def test_imagemagick_response(self, mock_extract, mock_subprocess): + def setUp(self): + self.item = _common.item() + self.log = logging.getLogger('beets.embedart') + + def _similarity(self, threshold): + return art.check_art_similarity(self.log, self.item, b'path', + threshold) + + def _popen(self, status=0, stdout="", stderr=""): + """Create a mock `Popen` object.""" + popen = MagicMock(returncode=status) + popen.communicate.return_value = stdout, stderr + return popen + + def _mock_popens(self, mock_extract, mock_subprocess, convert_status=0, + convert_stdout="", convert_stderr=""): mock_extract.return_value = b'extracted_path' - proc = mock_subprocess.Popen.return_value - log = logging.getLogger('beets.embedart') - item = _common.item() + mock_subprocess.Popen.side_effect = [ + # The `convert` call. + self._popen(), + # The `compare` call. + self._popen(convert_status, convert_stdout, convert_stderr), + ] - # everything is fine - proc.returncode = 0 - proc.communicate.return_value = "10", "tagada" - self.assertTrue(art.check_art_similarity(log, item, b'path', 20)) - self.assertFalse(art.check_art_similarity(log, item, b'path', 5)) + def test_compare_success_similar(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") + self.assertTrue(self._similarity(20)) - # small failure - proc.returncode = 1 - proc.communicate.return_value = "tagada", "10" - self.assertTrue(art.check_art_similarity(log, item, b'path', 20)) - self.assertFalse(art.check_art_similarity(log, item, b'path', 5)) + def test_compare_success_different(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") + self.assertFalse(self._similarity(5)) - # bigger failure - proc.returncode = 2 - self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) + def test_compare_status1_similar(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") + self.assertTrue(self._similarity(20)) - # IM result parsing problems - proc.returncode = 0 - proc.communicate.return_value = "foo", "bar" - self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) + def test_compare_status1_different(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") + self.assertFalse(self._similarity(5)) - proc.returncode = 1 - self.assertIsNone(art.check_art_similarity(log, item, b'path', 20)) + def test_compare_failed(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 2, "out", "10") + self.assertIsNone(self._similarity(20)) + + def test_compare_parsing_error(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 0, "foo", "bar") + self.assertIsNone(self._similarity(20)) + + def test_compare_parsing_error_and_failure(self, mock_extract, + mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, 1, "foo", "bar") + self.assertIsNone(self._similarity(20)) def suite(): From 1c1c73b06241ff8c8ca300e991addfa279f150a8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:01:10 -0700 Subject: [PATCH 0871/2280] Check for `convert` failures --- beets/art.py | 10 ++++++++-- test/test_embedart.py | 12 ++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/beets/art.py b/beets/art.py index 06b4f8455..2d6c25cb7 100644 --- a/beets/art.py +++ b/beets/art.py @@ -149,9 +149,15 @@ def check_art_similarity(log, item, imagepath, compare_threshold): convert_proc.stdout.close() stdout, stderr = compare_proc.communicate() + if convert_proc.returncode: + log.debug( + u'ImageMagick convert failed with status {}', + convert_proc.returncode, + ) + return if compare_proc.returncode: if compare_proc.returncode != 1: - log.debug(u'IM phashes compare failed for {0}, {1}', + log.debug(u'ImageMagick compare failed: {0}, {1}', displayable_path(imagepath), displayable_path(art)) return @@ -165,7 +171,7 @@ def check_art_similarity(log, item, imagepath, compare_threshold): log.debug(u'IM output is not a number: {0!r}', out_str) return - log.debug(u'compare PHASH score is {0}', phash_diff) + log.debug(u'ImageMagick copmare score: {0}', phash_diff) return phash_diff <= compare_threshold return True diff --git a/test/test_embedart.py b/test/test_embedart.py index 8c6871574..123bc4ff4 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -181,14 +181,14 @@ class ArtSimilarityTest(unittest.TestCase): popen.communicate.return_value = stdout, stderr return popen - def _mock_popens(self, mock_extract, mock_subprocess, convert_status=0, - convert_stdout="", convert_stderr=""): + def _mock_popens(self, mock_extract, mock_subprocess, compare_status=0, + compare_stdout="", compare_stderr="", convert_status=0): mock_extract.return_value = b'extracted_path' mock_subprocess.Popen.side_effect = [ # The `convert` call. - self._popen(), + self._popen(convert_status), # The `compare` call. - self._popen(convert_status, convert_stdout, convert_stderr), + self._popen(compare_status, compare_stdout, compare_stderr), ] def test_compare_success_similar(self, mock_extract, mock_subprocess): @@ -220,6 +220,10 @@ class ArtSimilarityTest(unittest.TestCase): self._mock_popens(mock_extract, mock_subprocess, 1, "foo", "bar") self.assertIsNone(self._similarity(20)) + def test_convert_failure(self, mock_extract, mock_subprocess): + self._mock_popens(mock_extract, mock_subprocess, convert_status=1) + self.assertIsNone(self._similarity(20)) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From b9845f29db4d8a49b1b6c06c95e0a1037a38540d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:16:50 -0700 Subject: [PATCH 0872/2280] Capture `convert`'s stderr We were leaking errors to the console without this. --- beets/art.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/beets/art.py b/beets/art.py index 2d6c25cb7..f3455445b 100644 --- a/beets/art.py +++ b/beets/art.py @@ -137,6 +137,7 @@ def check_art_similarity(log, item, imagepath, compare_threshold): convert_proc = subprocess.Popen( convert_cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, close_fds=not is_windows, ) compare_proc = subprocess.Popen( @@ -146,15 +147,23 @@ def check_art_similarity(log, item, imagepath, compare_threshold): stderr=subprocess.PIPE, close_fds=not is_windows, ) - convert_proc.stdout.close() - stdout, stderr = compare_proc.communicate() + # Check the convert output. We're not interested in the + # standard output; that gets piped to the next stage. + convert_proc.stdout.close() + convert_stderr = convert_proc.stderr.read() + convert_proc.stderr.close() + convert_proc.wait() if convert_proc.returncode: log.debug( - u'ImageMagick convert failed with status {}', + u'ImageMagick convert failed with status {}: {!r}', convert_proc.returncode, + convert_stderr, ) return + + # Check the compare output. + stdout, stderr = compare_proc.communicate() if compare_proc.returncode: if compare_proc.returncode != 1: log.debug(u'ImageMagick compare failed: {0}, {1}', From 00dece4dc2857973f2d7cf03ebd599519b53c843 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:22:53 -0700 Subject: [PATCH 0873/2280] Shorter default envlist for tox (#2035) Now just typing `tox` or `detox` runs some sensible defaults. (This excludes Python 3 and coverage.) You can request other environments explicitly with `-e`. --- tox.ini | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 13ac09f5e..afca278d7 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,10 @@ # and then run "tox" from this directory. [tox] -envlist = py{27,33,34,35}-{test,cov}, py{27,33}-flake8, docs +envlist = py27-test, py27-flake8, docs + +# The exhaustive list of environments is: +# envlist = py{27,33,34,35}-{test,cov}, py{27,33}-flake8, docs [_test] deps = From 8359b9e90f6c3672d276c53a8fb01c32e7c9c18e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:30:38 -0700 Subject: [PATCH 0874/2280] Tests: path equality assertion --- test/_common.py | 10 ++++++++++ test/test_importer.py | 14 +++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/test/_common.py b/test/_common.py index 4527942cf..2f230c304 100644 --- a/test/_common.py +++ b/test/_common.py @@ -30,6 +30,7 @@ sys.path.insert(0, '..') # noqa import beets.library from beets import importer, logging from beets.ui import commands +from beets import util import beets # Make sure the development versions of the plugins are used @@ -171,6 +172,15 @@ class TestCase(unittest.TestCase): self.assertFalse(os.path.exists(path), u'file exists: {!r}'.format((path))) + def assert_equal_path(self, a, b): + """Check that two paths are equal.""" + # The common case. + if a == b: + return + + self.assertEqual(util.normpath(a), util.normpath(b), + u'paths not equal: {!r} and {!r}'.format(a, b)) + class LibTestCase(TestCase): """A test case that includes an in-memory library object (`lib`) and diff --git a/test/test_importer.py b/test/test_importer.py index 4a8b20c90..5a076cfd6 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -341,7 +341,7 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): ) self.assertExists(filename) self.assertTrue(os.path.islink(filename)) - self.assertEqual(os.readlink(filename), mediafile.path) + self.assert_equal_path(os.readlink(filename), mediafile.path) def create_archive(session): @@ -836,8 +836,8 @@ class ImportExistingTest(_common.TestCase, ImportHelper): def test_outside_file_is_copied(self): config['import']['copy'] = False self.setup_importer.run() - self.assertEqual(self.lib.items().get().path, - self.import_media[0].path) + self.assert_equal_path(self.lib.items().get().path, + self.import_media[0].path) config['import']['copy'] = True self._setup_import_session() @@ -847,14 +847,14 @@ class ImportExistingTest(_common.TestCase, ImportHelper): 'Applied Title 1.mp3') self.assert_file_in_lib(new_path) - self.assertEqual(self.lib.items().get().path, - os.path.join(self.libdir, new_path)) + self.assert_equal_path(self.lib.items().get().path, + os.path.join(self.libdir, new_path)) def test_outside_file_is_moved(self): config['import']['copy'] = False self.setup_importer.run() - self.assertEqual(self.lib.items().get().path, - self.import_media[0].path) + self.assert_equal_path(self.lib.items().get().path, + self.import_media[0].path) self._setup_import_session(move=True) self.importer.add_choice(importer.action.APPLY) From a5b7489dd11c13fe3d5d633ee6defc34f5e3d1f7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:40:04 -0700 Subject: [PATCH 0875/2280] Use new assertion in config tests --- test/_common.py | 40 ++++++++++++++++++++++------------------ test/test_ui.py | 26 +++++++++++++++----------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/test/_common.py b/test/_common.py index 2f230c304..ab73481c3 100644 --- a/test/_common.py +++ b/test/_common.py @@ -123,9 +123,30 @@ def import_session(lib=None, loghandler=None, paths=[], query=[], cli=False): return cls(lib, loghandler, paths, query) +class Assertions(object): + """A mixin with additional unit test assertions.""" + + def assertExists(self, path): # noqa + self.assertTrue(os.path.exists(path), + u'file does not exist: {!r}'.format(path)) + + def assertNotExists(self, path): # noqa + self.assertFalse(os.path.exists(path), + u'file exists: {!r}'.format((path))) + + def assert_equal_path(self, a, b): + """Check that two paths are equal.""" + # The common case. + if a == b: + return + + self.assertEqual(util.normpath(a), util.normpath(b), + u'paths are not equal: {!r} and {!r}'.format(a, b)) + + # A test harness for all beets tests. # Provides temporary, isolated configuration. -class TestCase(unittest.TestCase): +class TestCase(unittest.TestCase, Assertions): """A unittest.TestCase subclass that saves and restores beets' global configuration. This allows tests to make temporary modifications that will then be automatically removed when the test @@ -164,23 +185,6 @@ class TestCase(unittest.TestCase): beets.config.clear() beets.config._materialized = False - def assertExists(self, path): # noqa - self.assertTrue(os.path.exists(path), - u'file does not exist: {!r}'.format(path)) - - def assertNotExists(self, path): # noqa - self.assertFalse(os.path.exists(path), - u'file exists: {!r}'.format((path))) - - def assert_equal_path(self, a, b): - """Check that two paths are equal.""" - # The common case. - if a == b: - return - - self.assertEqual(util.normpath(a), util.normpath(b), - u'paths not equal: {!r} and {!r}'.format(a, b)) - class LibTestCase(TestCase): """A test case that includes an in-memory library object (`lib`) and diff --git a/test/test_ui.py b/test/test_ui.py index c8b6a99d3..ca3c6cbdf 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -635,7 +635,7 @@ class InputTest(_common.TestCase): @_common.slow_test() -class ConfigTest(unittest.TestCase, TestHelper): +class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def setUp(self): self.setup_beets() @@ -821,10 +821,14 @@ class ConfigTest(unittest.TestCase, TestHelper): file.write('statefile: state') ui._raw_main(['--config', cli_config_path, 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(self.user_config_dir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.user_config_dir, 'state')) + self.assert_equal_path( + config['library'].as_filename(), + os.path.join(self.user_config_dir, 'beets.db') + ) + self.assert_equal_path( + config['statefile'].as_filename(), + os.path.join(self.user_config_dir, 'state') + ) def test_cli_config_paths_resolve_relative_to_beetsdir(self): os.environ['BEETSDIR'] = self.beetsdir @@ -835,16 +839,16 @@ class ConfigTest(unittest.TestCase, TestHelper): file.write('statefile: state') ui._raw_main(['--config', cli_config_path, 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + self.assert_equal_path(config['library'].as_filename(), + os.path.join(self.beetsdir, 'beets.db')) + self.assert_equal_path(config['statefile'].as_filename(), + os.path.join(self.beetsdir, 'state')) def test_command_line_option_relative_to_working_dir(self): os.chdir(self.temp_dir) ui._raw_main(['--library', 'foo.db', 'test']) - self.assertEqual(config['library'].as_filename(), - os.path.join(os.getcwd(), 'foo.db')) + self.assert_equal_path(config['library'].as_filename(), + os.path.join(os.getcwd(), 'foo.db')) def test_cli_config_file_loads_plugin_commands(self): plugin_path = os.path.join(_common.RSRC, 'beetsplug') From 8bf1f868fa2fba6773cc31fb93931731a151264b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:46:51 -0700 Subject: [PATCH 0876/2280] Fix comparison in a library type test --- test/test_library.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index c9e007a94..9d386a7a2 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1189,8 +1189,9 @@ class LibraryFieldTypesTest(unittest.TestCase): self.assertEqual('/tmp', t.format('/tmp')) self.assertEqual(u'/tmp/\xe4lbum', t.format(u'/tmp/\u00e4lbum')) # parse - self.assertEqual(b'/tmp', t.parse('/tmp')) - self.assertEqual(b'/tmp/\xc3\xa4lbum', t.parse(u'/tmp/\u00e4lbum/')) + self.assertEqual(np(b'/tmp'), t.parse('/tmp')) + self.assertEqual(np(b'/tmp/\xc3\xa4lbum'), + t.parse(u'/tmp/\u00e4lbum/')) def test_musicalkey(self): t = beets.library.MusicalKey() From 2322962cf817b366cb79511c156cf44fb7581ae4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:51:32 -0700 Subject: [PATCH 0877/2280] Fix another sys.platform check --- test/test_hidden.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_hidden.py b/test/test_hidden.py index 2238c9ef2..f808af99f 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -48,7 +48,7 @@ class HiddenFileTest(unittest.TestCase): self.assertTrue(hidden.is_hidden(f.name)) def test_windows_hidden(self): - if not sys.platform == 'windows': + if not sys.platform == 'win32': self.skipTest('sys.platform is not windows') return From 90f4c77ea03fdfc6bdea0a7bd57b40fc7e2a3eae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 11:53:27 -0700 Subject: [PATCH 0878/2280] Skip permissions tests on Windows --- test/test_permissions.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_permissions.py b/test/test_permissions.py index d3eb6dc77..4f5d05747 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -5,6 +5,7 @@ from __future__ import division, absolute_import, print_function import os +import platform from mock import patch, Mock from test._common import unittest @@ -39,6 +40,9 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.do_thing(False) def do_thing(self, expect_success): + if platform.system() == 'Windows': + self.skipTest('permissions not available on Windows') + def get_stat(v): return os.stat( os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777 From 8b62aa828cd7d373d8487c3e244d0896818fe359 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Jun 2016 12:17:17 -0700 Subject: [PATCH 0879/2280] Fix KeyFinder test assertion --- test/test_keyfinder.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index d459606cf..00952fe14 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -20,6 +20,7 @@ from test._common import unittest from test.helper import TestHelper from beets.library import Item +from beets import util class KeyFinderTest(unittest.TestCase, TestHelper): @@ -45,7 +46,7 @@ class KeyFinderTest(unittest.TestCase, TestHelper): item.load() self.assertEqual(item['initial_key'], 'C#m') self.command_output.assert_called_with( - ['KeyFinder', '-f', item.path]) + ['KeyFinder', '-f', util.syspath(item.path)]) def test_add_key_on_import(self): self.command_output.return_value = 'dbm' From f7f249f6c6319ac19d949b1cc977ad9d5c90eb30 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 01:05:32 -0400 Subject: [PATCH 0880/2280] wrap map() in a list() where necessary for py3 It's slightly more inefficient during the py3 transition, but I still think it's worth minimizing the diff for. --- beets/autotag/match.py | 2 +- beets/dbcore/db.py | 6 +++--- beets/ui/__init__.py | 2 +- beets/ui/commands.py | 7 +++++-- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index cfe184e71..9870f157f 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -412,7 +412,7 @@ def tag_album(items, search_artist=None, search_album=None, id_info = match_by_id(items) if id_info: _add_candidate(items, candidates, id_info) - rec = _recommendation(candidates.values()) + rec = _recommendation(list(candidates.values())) log.debug(u'Album ID match recommendation is {0}', rec) if candidates and not config['import']['timid']: # If we have a very good MBID match, return immediately. diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index dda08bc6a..1c6d066c3 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -267,9 +267,9 @@ class Model(object): `computed` parameter controls whether computed (plugin-provided) fields are included in the key list. """ - base_keys = list(self._fields) + self._values_flex.keys() + base_keys = list(self._fields) + list(self._values_flex.keys()) if computed: - return base_keys + self._getters().keys() + return base_keys + list(self._getters().keys()) else: return base_keys @@ -278,7 +278,7 @@ class Model(object): """Get a list of available keys for objects of this type. Includes fixed and computed fields. """ - return list(cls._fields) + cls._getters().keys() + return list(cls._fields) + list(cls._getters().keys()) # Act like a dictionary. diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 675bc63cc..39a046fba 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1086,7 +1086,7 @@ def _load_plugins(config): """Load the plugins specified in the configuration. """ paths = config['pluginpath'].get(confit.StrSeq(split=False)) - paths = map(util.normpath, paths) + paths = list(map(util.normpath, paths)) log.debug(u'plugin paths: {0}', util.displayable_path(paths)) import beetsplug diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 867a47379..ea635284b 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -279,7 +279,7 @@ def show_change(cur_artist, cur_album, match): print_(' '.join(info)) # Tracks. - pairs = match.mapping.items() + pairs = list(match.mapping.items()) pairs.sort(key=lambda item_and_track_info: item_and_track_info[1].index) # Build up LHS and RHS for track difference display. The `lines` list @@ -1730,7 +1730,10 @@ def completion_script(commands): # Fields yield u" fields='%s'\n" % ' '.join( - set(library.Item._fields.keys() + library.Album._fields.keys()) + set( + list(library.Item._fields.keys()) + + list(library.Album._fields.keys()) + ) ) # Command options From be474b3f5254d265798ff3a45a3a2248a6de4b2f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 4 Jun 2016 21:20:07 -0400 Subject: [PATCH 0881/2280] wrap a call to filter in a list() There are other filters like this in the master branch, but 2to3 converts them into list comprehensions. We'll deal with those later --- test/test_mediafile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 9fe4cae5b..0ee93ef42 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -194,8 +194,8 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): self.assertEqual(len(mediafile.images), 3) # WMA does not preserve the order, so we have to work around this - image = filter(lambda i: i.mime_type == 'image/tiff', - mediafile.images)[0] + image = list(filter(lambda i: i.mime_type == 'image/tiff', + mediafile.images))[0] self.assertExtendedImageAttributes( image, desc=u'the composer', type=ImageType.composer) From 790b1b515379a77538edf2e763733a68f8fa56d1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 8 Jun 2016 00:17:18 -0400 Subject: [PATCH 0882/2280] replace some filter/map calls with list comps These are places where the surrounding/calling code needs a list, not an iter. --- beets/autotag/hooks.py | 4 ++-- beetsplug/missing.py | 2 +- beetsplug/spotify.py | 7 +++---- test/test_query.py | 4 ++-- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index d0e3d9c75..92a7b8e29 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -547,7 +547,7 @@ def albums_for_id(album_id): for a in plugin_albums: plugins.send(u'albuminfo_received', info=a) candidates.extend(plugin_albums) - return filter(None, candidates) + return [a for a in candidates if a] def tracks_for_id(track_id): @@ -557,7 +557,7 @@ def tracks_for_id(track_id): for t in plugin_tracks: plugins.send(u'trackinfo_received', info=t) candidates.extend(plugin_tracks) - return filter(None, candidates) + return [t for t in candidates if t] def album_candidates(items, artist, album, va_likely): diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 8fff659fe..b99a70d9e 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -133,7 +133,7 @@ class MissingPlugin(BeetsPlugin): def _missing(self, album): """Query MusicBrainz to determine items missing from `album`. """ - item_mbids = map(lambda x: x.mb_trackid, album.items()) + item_mbids = [x.mb_trackid for x in album.items()] if len([i for i in album.items()]) < album.albumtotal: # fetch missing items # TODO: Implement caching that without breaking other stuff diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 081a027f2..77df15790 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -124,9 +124,8 @@ class SpotifyPlugin(BeetsPlugin): # Apply market filter if requested region_filter = self.config['region_filter'].get() if region_filter: - r_data = filter( - lambda x: region_filter in x['available_markets'], r_data - ) + r_data = [x for x in r_data if region_filter + in x['available_markets']] # Simplest, take the first result chosen_result = None @@ -163,7 +162,7 @@ class SpotifyPlugin(BeetsPlugin): def output_results(self, results): if results: - ids = map(lambda x: x['id'], results) + ids = [x['id'] for x in results] if self.config['mode'].get() == "open": self._log.info(u'Attempting to open Spotify with playlist') spotify_url = self.playlist_partial + ",".join(ids) diff --git a/test/test_query.py b/test/test_query.py index 79bc11743..7f45b1c68 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -37,11 +37,11 @@ from beets import util class TestHelper(helper.TestHelper): def assertInResult(self, item, results): # noqa - result_ids = map(lambda i: i.id, results) + result_ids = [i.id for i in results] self.assertIn(item.id, result_ids) def assertNotInResult(self, item, results): # noqa - result_ids = map(lambda i: i.id, results) + result_ids = [i.id for i in results] self.assertNotIn(item.id, result_ids) From 7c39462ae6c8d178dc338944a2480a48838e19a3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 2 Jun 2016 01:07:02 -0400 Subject: [PATCH 0883/2280] add a __bool__ to Results in db.py --- beets/dbcore/db.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 1c6d066c3..a07a19997 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -593,6 +593,11 @@ class Results(object): return self._row_count def __nonzero__(self): + """Does this result contain any objects? + """ + return self.__bool__() + + def __bool__(self): """Does this result contain any objects? """ return bool(len(self)) From 1dc61491c69c66cd28f76c254eb5ddb707d9eafc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 09:36:00 -0700 Subject: [PATCH 0884/2280] Remove a bogus bash-completion path (#2038) --- beets/ui/commands.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 797b25209..d35922c65 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1663,13 +1663,11 @@ def print_completion(*args): BASH_COMPLETION_PATHS = map(syspath, [ u'/etc/bash_completion', u'/usr/share/bash-completion/bash_completion', - u'/usr/share/local/bash-completion/bash_completion', + u'/usr/local/share/bash-completion/bash_completion', # SmartOS u'/opt/local/share/bash-completion/bash_completion', - # Homebrew + # Homebrew (before bash-completion2) u'/usr/local/etc/bash_completion', - # Homebrew bash-completion2 - u'/usr/local/share/bash-completion/bash_completion', ]) From 9898cb16786c254aa996a16d353dff2a68fcde54 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 09:37:26 -0700 Subject: [PATCH 0885/2280] Changelog/thanks for #2038 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0199d7c54..6fc835c61 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -21,6 +21,8 @@ Fixes: * :doc:`/plugins/lyrics`: Avoid a crash and a spurious warning introduced in the last version about a Google API key, which appeared even when you hadn't tried to enable the Google lyrics source. +* Fix a hard-coded path to ``bash-completion`` to work better with Homebrew + installations. Thanks to :user:`bismark`. :bug:`2038` 1.3.18 (May 31, 2016) From 93e614c739ffc07ee07e66f431896be8228d3698 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 09:47:45 -0700 Subject: [PATCH 0886/2280] Tests for _{in,out}_encoding (#2041) --- test/test_ui.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index ca3c6cbdf..4476720e2 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1300,6 +1300,30 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): ({'album': None, 'path': None, 'format': None}, [])) +class EncodingTest(_common.TestCase): + """Tests for the `terminal_encoding` config option and our + `_in_encoding` and `_out_encoding` utility functions. + """ + + def out_encoding_overridden(self): + config['terminal_encoding'] = 'fake_encoding' + self.assertEqual(ui._out_encoding(), 'fake_encoding') + + def in_encoding_overridden(self): + config['terminal_encoding'] = 'fake_encoding' + self.assertEqual(ui._in_encoding(), 'fake_encoding') + + def out_encoding_default_utf8(self): + with patch('sys.stdout') as stdout: + stdout.encoding = None + self.assertEqual(ui._out_encoding(), 'utf8') + + def in_encoding_default_utf8(self): + with patch('sys.stdin') as stdin: + stdin.encoding = None + self.assertEqual(ui._in_encoding(), 'utf8') + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 27bd4c5570ead2df48371080f4ad3d2de46df3e6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 09:51:29 -0700 Subject: [PATCH 0887/2280] Fix #2041: encoding detection when stdin is a pipe --- beets/ui/__init__.py | 27 ++++++++++++++++----------- docs/changelog.rst | 2 ++ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 39a046fba..a2739189e 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -73,32 +73,37 @@ class UserError(Exception): # Encoding utilities. -def _in_encoding(default=u'utf-8'): +def _in_encoding(): """Get the encoding to use for *inputting* strings from the console. - - :param default: the fallback sys.stdin encoding """ - - return config['terminal_encoding'].get() or getattr(sys.stdin, 'encoding', - default) + return _stream_encoding(sys.stdin) def _out_encoding(): """Get the encoding to use for *outputting* strings to the console. """ + return _stream_encoding(sys.stdout) + + +def _stream_encoding(stream, default='utf8'): + """A helper for `_in_encoding` and `_out_encoding`: get the stream's + preferred encoding, using a configured override or a default + fallback if neither is not specified. + """ # Configured override? encoding = config['terminal_encoding'].get() if encoding: return encoding - # For testing: When sys.stdout is a StringIO under the test harness, - # it doesn't have an `encoding` attribute. Just use UTF-8. - if not hasattr(sys.stdout, 'encoding'): - return 'utf8' + # For testing: When sys.stdout or sys.stdin is a StringIO under the + # test harness, it doesn't have an `encoding` attribute. Just use + # UTF-8. + if not hasattr(stream, 'encoding'): + return default # Python's guessed output stream encoding, or UTF-8 as a fallback # (e.g., when piped to a file). - return sys.stdout.encoding or 'utf8' + return stream.encoding or default def _arg_encoding(): diff --git a/docs/changelog.rst b/docs/changelog.rst index 6fc835c61..2596a8ba5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,8 @@ Fixes: tried to enable the Google lyrics source. * Fix a hard-coded path to ``bash-completion`` to work better with Homebrew installations. Thanks to :user:`bismark`. :bug:`2038` +* Fix a crash introduced in the previous version when the standard input was + connected to a Unix pipe. :bug:`2041` 1.3.18 (May 31, 2016) From f400a2431ebf3cced352abe8e267bc743a8f0893 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 10:20:25 -0700 Subject: [PATCH 0888/2280] fetchart: Fix path types on Windows --- beetsplug/fetchart.py | 8 +++++--- docs/changelog.rst | 2 ++ test/helper.py | 4 ++-- test/test_fetchart.py | 3 ++- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 2cc362e4a..f131bd9d5 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -31,6 +31,7 @@ from beets import util from beets import config from beets.util.artresizer import ArtResizer from beets.util import confit +from beets.util import syspath, bytestring_path try: import itunes @@ -599,15 +600,16 @@ class FileSystem(LocalArtSource): cautious = extra['cautious'] for path in paths: - if not os.path.isdir(path): + if not os.path.isdir(syspath(path)): continue # Find all files that look like images in the directory. images = [] - for fn in os.listdir(path): + for fn in os.listdir(syspath(path)): + fn = bytestring_path(fn) for ext in IMAGE_EXTENSIONS: if fn.lower().endswith(b'.' + ext.encode('utf8')) and \ - os.path.isfile(os.path.join(path, fn)): + os.path.isfile(syspath(os.path.join(path, fn))): images.append(fn) # Look for "preferred" filenames. diff --git a/docs/changelog.rst b/docs/changelog.rst index 2596a8ba5..1069552c0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,8 @@ Some fixes for Windows: addition to forward slashes). This only applies on Windows. * :doc:`/plugins/embedart`: Image similarity comparison with ImageMagick should now work on Windows. +* :doc:`/plugins/fetchart`: The plugin should work more reliably with + non-ASCII paths. Fixes: diff --git a/test/helper.py b/test/helper.py index 197a85d78..3196e265e 100644 --- a/test/helper.py +++ b/test/helper.py @@ -454,9 +454,9 @@ class TestHelper(object): parent = os.path.dirname(path) if not os.path.isdir(parent): - os.makedirs(parent) + os.makedirs(util.syspath(parent)) - with open(path, 'a+') as f: + with open(util.syspath(path), 'a+') as f: f.write(content) return path diff --git a/test/test_fetchart.py b/test/test_fetchart.py index db3fef8ec..52e7758b8 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import os from test._common import unittest from test.helper import TestHelper +from beets import util class FetchartCliTest(unittest.TestCase, TestHelper): @@ -41,7 +42,7 @@ class FetchartCliTest(unittest.TestCase, TestHelper): self.album.load() self.assertEqual(self.album['artpath'], cover_path) - with open(cover_path, 'r') as f: + with open(util.syspath(cover_path), 'r') as f: self.assertEqual(f.read(), 'IMAGE') def test_filesystem_does_not_pick_up_folder(self): From f79daacb7bb4e446920549f2b9d1bffc34384e74 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 10:23:35 -0700 Subject: [PATCH 0889/2280] Fix a hard-coded path separator in a test --- test/test_importfeeds.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index 158e8e51c..adb2885c7 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -43,7 +43,8 @@ class ImportfeedsTestTest(unittest.TestCase): def test_playlist_in_subdir(self): config['importfeeds']['formats'] = 'm3u' - config['importfeeds']['m3u_name'] = 'subdir/imported.m3u' + config['importfeeds']['m3u_name'] = \ + os.path.join('subdir', 'imported.m3u') album = Album(album='album/name', id=1) item_path = os.path.join('path', 'to', 'item') item = Item(title='song', album_id=1, path=item_path) From 416593fbf83b247483c57cc8d8dc260c0457e6db Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 10:31:05 -0700 Subject: [PATCH 0890/2280] Split path detection tests --- test/test_query.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 7f45b1c68..92fc57495 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -581,18 +581,31 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assertFalse(is_path('foo:bar/')) self.assertFalse(is_path('foo:/bar')) - def test_path_detection(self): - # cover existence test + def test_detect_absolute_path(self): + # Don't patch `os.path.exists`; we'll actually create a file when + # it exists. self.patcher_exists.stop() is_path = beets.library.PathQuery.is_path_query try: - self.touch(b'foo/bar') - # test absolute + self.touch(os.path.join('foo', 'bar')) + self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo/bar'))) self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo'))) self.assertFalse(is_path(b'foo/bar')) + finally: + # Restart the `os.path.exists` patch. + self.patcher_exists.start() + + def test_detect_relative_path(self): + self.patcher_exists.stop() + is_path = beets.library.PathQuery.is_path_query + + try: + self.touch(os.path.join('foo', 'bar')) + + # Temporarily change directory so relative paths work. cur_dir = os.getcwd() try: os.chdir(self.temp_dir) @@ -602,6 +615,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assertFalse(is_path(b'bar')) finally: os.chdir(cur_dir) + finally: self.patcher_exists.start() From bea77370c483a46bfb048ae925f4780c0e8b9472 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 10:34:21 -0700 Subject: [PATCH 0891/2280] Simpler absolute path detection test --- test/test_query.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 92fc57495..355488a39 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -588,11 +588,17 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): is_path = beets.library.PathQuery.is_path_query try: - self.touch(os.path.join('foo', 'bar')) + path = self.touch(os.path.join('foo', 'bar')) - self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo/bar'))) - self.assertTrue(is_path(os.path.join(self.temp_dir, b'foo'))) - self.assertFalse(is_path(b'foo/bar')) + # The file itself. + self.assertTrue(is_path(path)) + + # The parent directory. + parent = os.path.dirname(path) + self.assertTrue(is_path(parent)) + + # Some non-existent path. + self.assertFalse(is_path(path + b'baz')) finally: # Restart the `os.path.exists` patch. From 847c3bbfef3430a5053bb47213b85807fa32410a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 10:41:32 -0700 Subject: [PATCH 0892/2280] Don't test absolute paths as queries on Windows --- test/test_query.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/test_query.py b/test/test_query.py index 355488a39..4595cf827 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -32,6 +32,7 @@ from beets.dbcore.query import (NoneQuery, ParsingError, InvalidQueryArgumentTypeError) from beets.library import Library, Item from beets import util +import platform class TestHelper(helper.TestHelper): @@ -582,6 +583,11 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assertFalse(is_path('foo:/bar')) def test_detect_absolute_path(self): + if platform.system() == 'Windows': + # Because the absolute path begins with something like C:, we + # can't disambiguate it from an ordinary query. + self.skipTest('Windows absolute paths do not work as queries') + # Don't patch `os.path.exists`; we'll actually create a file when # it exists. self.patcher_exists.stop() From 34b3cf36b79e915defd6e0c25ecd7a2066b609b6 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 8 Jun 2016 19:22:24 +0100 Subject: [PATCH 0893/2280] Add --force option to beet remove --- beets/ui/commands.py | 42 ++++++++++++++++++++++++------------------ test/test_ui.py | 4 ++-- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index d35922c65..75cae066c 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1194,31 +1194,33 @@ default_commands.append(update_cmd) # remove: Remove items from library, delete files. -def remove_items(lib, query, album, delete): +def remove_items(lib, query, album, delete, force): """Remove items matching query from lib. If album, then match and remove whole albums. If delete, also remove files from disk. """ # Get the matching items. items, albums = _do_query(lib, query, album) - # Prepare confirmation with user. - print_() - if delete: - fmt = u'$path - $title' - prompt = u'Really DELETE %i file%s (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') - else: - fmt = '' - prompt = u'Really remove %i item%s from the library (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') + # Confirm file removal if not forcing removal. + if not force: + # Prepare confirmation with user. + print_() + if delete: + fmt = u'$path - $title' + prompt = u'Really DELETE %i file%s (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') + else: + fmt = '' + prompt = u'Really remove %i item%s from the library (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') - # Show all the items. - for item in items: - ui.print_(format(item, fmt)) + # Show all the items. + for item in items: + ui.print_(format(item, fmt)) - # Confirm with user. - if not ui.input_yn(prompt, True): - return + # Confirm with user. + if not ui.input_yn(prompt, True): + return # Remove (and possibly delete) items. with lib.transaction(): @@ -1227,7 +1229,7 @@ def remove_items(lib, query, album, delete): def remove_func(lib, opts, args): - remove_items(lib, decargs(args), opts.album, opts.delete) + remove_items(lib, decargs(args), opts.album, opts.delete, opts.force) remove_cmd = ui.Subcommand( @@ -1237,6 +1239,10 @@ remove_cmd.parser.add_option( u"-d", u"--delete", action="store_true", help=u"also remove files from disk" ) +remove_cmd.parser.add_option( + u"-f", u"--force", action="store_true", + help=u"do not ask when removing items" +) remove_cmd.parser.add_album_option() remove_cmd.func = remove_func default_commands.append(remove_cmd) diff --git a/test/test_ui.py b/test/test_ui.py index 4476720e2..f91fe2798 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -134,14 +134,14 @@ class RemoveTest(_common.TestCase): def test_remove_items_no_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, u'', False, False) + commands.remove_items(self.lib, u'', False, False, False) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertTrue(os.path.exists(self.i.path)) def test_remove_items_with_delete(self): self.io.addinput('y') - commands.remove_items(self.lib, u'', False, True) + commands.remove_items(self.lib, u'', False, True, False) items = self.lib.items() self.assertEqual(len(list(items)), 0) self.assertFalse(os.path.exists(self.i.path)) From 0d2923e4ea546a6a7aebcf9ce6e337ade3d1c65f Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 8 Jun 2016 19:26:19 +0100 Subject: [PATCH 0894/2280] Add documentation for beet remove --force --- docs/reference/cli.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index faae67ee6..93b9b6253 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -211,7 +211,7 @@ remove `````` :: - beet remove [-ad] QUERY + beet remove [-adf] QUERY Remove music from your library. @@ -219,6 +219,7 @@ This command uses the same :doc:`query ` syntax as the ``list`` command. You'll be shown a list of the files that will be removed and asked to confirm. By default, this just removes entries from the library database; it doesn't touch the files on disk. To actually delete the files, use ``beet remove -d``. +If you do not want to be prompted to remove the files, use ``beet remove -f``. .. _modify-cmd: From 3f8a85c82544c998bdc9dc9cb08ec4afde3f3961 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 8 Jun 2016 19:26:42 +0100 Subject: [PATCH 0895/2280] Add tests for force deletion (without input) --- test/test_ui.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index f91fe2798..d40bfe3b7 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -146,6 +146,18 @@ class RemoveTest(_common.TestCase): self.assertEqual(len(list(items)), 0) self.assertFalse(os.path.exists(self.i.path)) + def test_remove_items_with_force_no_delete(self): + commands.remove_items(self.lib, u'', False, False, True) + items = self.lib.items() + self.assertEqual(len(list(items)), 0) + self.assertTrue(os.path.exists(self.i.path)) + + def test_remove_items_with_force_delete(self): + commands.remove_items(self.lib, u'', False, True, True) + items = self.lib.items() + self.assertEqual(len(list(items)), 0) + self.assertFalse(os.path.exists(self.i.path)) + class ModifyTest(unittest.TestCase, TestHelper): From bcb19c4b56f237a0e36727a9f130c2c4628a2abe Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 8 Jun 2016 19:29:56 +0100 Subject: [PATCH 0896/2280] Add beet remove --force option to changelog --- docs/changelog.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1069552c0..ddd6a22ca 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,10 @@ Changelog 1.3.19 (in development) ----------------------- -Changelog goes here! +New features: + +* A new ``--force`` option for :ref:`remove-cmd` allows removal of items + without prompting beforehand. Some fixes for Windows: From d1714ce114f8b494b9e1456c6bff65f137f2f360 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Wed, 8 Jun 2016 19:33:59 +0100 Subject: [PATCH 0897/2280] Add reference to bug for beet remove --force --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ddd6a22ca..64b582450 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,7 +7,7 @@ Changelog New features: * A new ``--force`` option for :ref:`remove-cmd` allows removal of items - without prompting beforehand. + without prompting beforehand. :bug:`2042` Some fixes for Windows: From 2c7e7d77279bb735e867ab5bfaafd1b392c73b5a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 12:59:45 -0700 Subject: [PATCH 0898/2280] Portable paths in mpdstats tests --- test/test_mpdstats.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index 36f5d0d80..febf292d8 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -21,6 +21,7 @@ from test.helper import TestHelper from beets.library import Item from beetsplug.mpdstats import MPDStats +from beets import util class MPDStatsTest(unittest.TestCase, TestHelper): @@ -43,7 +44,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): self.assertFalse(mpdstats.update_rating(None, True)) def test_get_item(self): - item_path = '/foo/bar.flac' + item_path = util.normpath('/foo/bar.flac') item = Item(title=u'title', path=item_path, id=1) item.add(self.lib) @@ -60,7 +61,7 @@ class MPDStatsTest(unittest.TestCase, TestHelper): {'state': u'play', 'songid': 1, 'time': u'0:1'}, {'state': u'stop'}] EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt] - item_path = '/foo/bar.flac' + item_path = util.normpath('/foo/bar.flac') @patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{ "events.side_effect": EVENTS, "status.side_effect": STATUSES, From 9717940c9b0dd5acf91d4b846380286b172343d7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 8 Jun 2016 23:03:45 -0700 Subject: [PATCH 0899/2280] Cross-platform relative path in test --- test/test_play.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 06d41e75e..4b979a001 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -44,11 +44,12 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.unload_plugins() def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', - expected_playlist=u'{}\n'): + expected_playlist=None): self.run_command('play', *args) self.open_mock.assert_called_once_with(ANY, expected_cmd) - exp_playlist = expected_playlist.format(self.item.path.decode('utf-8')) + expected_playlist = expected_playlist or self.item.path.decode('utf-8') + exp_playlist = expected_playlist + u'\n' with open(self.open_mock.call_args[0][0][0], 'r') as playlist: self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) @@ -70,7 +71,9 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' - self.do_test(expected_cmd='echo', expected_playlist=u'..{}\n') + path = os.path.relpath(self.item.path, '/something') + playlist = path.decode('utf8') + self.do_test(expected_cmd='echo', expected_playlist=playlist) def test_use_folders(self): self.config['play']['command'] = None From 2fefd2471a3e0b5b88b05eb8465e7935e969fcce Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 9 Jun 2016 09:39:44 -0700 Subject: [PATCH 0900/2280] Use our higher-level assertions for files --- test/test_importer.py | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 5a076cfd6..bc0109ba1 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -354,7 +354,7 @@ def create_archive(session): return path -class RmTempTest(unittest.TestCase, ImportHelper): +class RmTempTest(unittest.TestCase, ImportHelper, _common.Assertions): """Tests that temporarily extracted archives are properly removed after usage. """ @@ -374,9 +374,9 @@ class RmTempTest(unittest.TestCase, ImportHelper): archive_task.extract() tmp_path = archive_task.toppath self._setup_import_session(autotag=False, import_dir=tmp_path) - self.assertTrue(os.path.exists(tmp_path)) + self.assertExists(tmp_path) archive_task.finalize(self) - self.assertFalse(os.path.exists(tmp_path)) + self.assertNotExists(tmp_path) class ImportZipTest(unittest.TestCase, ImportHelper): @@ -1074,7 +1074,8 @@ def test_album_info(): return album_info -class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): +class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, + _common.Assertions): def setUp(self): self.setup_beets() @@ -1098,12 +1099,12 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): def test_remove_duplicate_album(self): item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertFalse(os.path.isfile(item.path)) + self.assertExists(item.path) self.assertEqual(len(self.lib.albums()), 1) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() @@ -1113,7 +1114,7 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): config['import']['autotag'] = False item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) # Imported item has the same artist and album as the one in the # library. @@ -1128,7 +1129,7 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.assertEqual(len(self.lib.albums()), 2) self.assertEqual(len(self.lib.items()), 2) @@ -1162,7 +1163,8 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper): return album -class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper): +class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, + _common.Assertions): def setUp(self): self.setup_beets() @@ -1193,12 +1195,12 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper): def test_remove_duplicate(self): item = self.lib.items().get() self.assertEqual(item.mb_trackid, u'old trackid') - self.assertTrue(os.path.isfile(item.path)) + self.assertExists(item.path) self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertFalse(os.path.isfile(item.path)) + self.assertExists(item.path) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() self.assertEqual(item.mb_trackid, u'new trackid') @@ -1511,7 +1513,7 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.assertEqual(len(items), 3) -class ReimportTest(unittest.TestCase, ImportHelper): +class ReimportTest(unittest.TestCase, ImportHelper, _common.Assertions): """Test "re-imports", in which the autotagging machinery is used for music that's already in the library. @@ -1604,9 +1606,9 @@ class ReimportTest(unittest.TestCase, ImportHelper): new_album = self._album() new_artpath = new_album.art_destination(art_source) self.assertEqual(new_album.artpath, new_artpath) - self.assertTrue(os.path.exists(new_artpath)) + self.assertExists(new_artpath) if new_artpath != old_artpath: - self.assertFalse(os.path.exists(old_artpath)) + self.assertNotExists(old_artpath) class ImportPretendTest(_common.TestCase, ImportHelper): From e508daea63aa013914ba694b533779764beb1c65 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 9 Jun 2016 09:43:24 -0700 Subject: [PATCH 0901/2280] Use syspath for existence checks --- test/_common.py | 4 ++-- test/test_embedart.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/_common.py b/test/_common.py index ab73481c3..ecdde1a6c 100644 --- a/test/_common.py +++ b/test/_common.py @@ -127,11 +127,11 @@ class Assertions(object): """A mixin with additional unit test assertions.""" def assertExists(self, path): # noqa - self.assertTrue(os.path.exists(path), + self.assertTrue(os.path.exists(util.syspath(path)), u'file does not exist: {!r}'.format(path)) def assertNotExists(self, path): # noqa - self.assertFalse(os.path.exists(path), + self.assertFalse(os.path.exists(util.syspath(path)), u'file exists: {!r}'.format((path))) def assert_equal_path(self, a, b): diff --git a/test/test_embedart.py b/test/test_embedart.py index 123bc4ff4..e58350352 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -161,7 +161,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.run_command('extractart', '-n', 'extracted') - self.assertExists(syspath(os.path.join(albumpath, b'extracted.png'))) + self.assertExists(os.path.join(albumpath, b'extracted.png')) @patch('beets.art.subprocess') From a45dcdc674ca852da1cd419f965ca9ac84d80746 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 9 Jun 2016 09:58:10 -0700 Subject: [PATCH 0902/2280] Fix Windows env vars for config test --- test/test_ui.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index d40bfe3b7..40da6cc44 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -652,11 +652,16 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.setup_beets() # Don't use the BEETSDIR from `helper`. Instead, we point the home - # directory there. Some tests will set `BEETSDIR` themselves. + # directory there. Some tests will set `BEETSDIR` themselves. del os.environ['BEETSDIR'] self._old_home = os.environ.get('HOME') os.environ['HOME'] = self.temp_dir + # Also set APPDATA, the Windows equivalent of setting $HOME. + self._old_appdata = os.environ.get('APPDATA') + os.environ['APPDATA'] = \ + os.path.join(self.temp_dir, 'AppData', 'Roaming') + self._orig_cwd = os.getcwd() self.test_cmd = self._make_test_cmd() commands.default_commands.append(self.test_cmd) @@ -685,6 +690,10 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.chdir(self._orig_cwd) if self._old_home is not None: os.environ['HOME'] = self._old_home + if self._old_appdata is None: + del os.environ['APPDATA'] + else: + os.environ['APPDATA'] = self._old_appdata self.teardown_beets() def _make_test_cmd(self): From 0f8fc339521ef97faa9f814eb24e3ff6cc299496 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 9 Jun 2016 10:23:24 -0700 Subject: [PATCH 0903/2280] Fix inverted assertion sense I broke this in 2fefd24 by using the wrong assertion. --- test/test_importer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index bc0109ba1..e83f9e89c 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1104,7 +1104,7 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertExists(item.path) + self.assertNotExists(item.path) self.assertEqual(len(self.lib.albums()), 1) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() @@ -1200,7 +1200,7 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, self.importer.default_resolution = self.importer.Resolution.REMOVE self.importer.run() - self.assertExists(item.path) + self.assertNotExists(item.path) self.assertEqual(len(self.lib.items()), 1) item = self.lib.items().get() self.assertEqual(item.mb_trackid, u'new trackid') From 26a17a37033618e99de6934cc808bfda58b3830e Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 9 Jun 2016 19:23:54 +0100 Subject: [PATCH 0904/2280] Remove trailing whitespace added in a45dcdc --- test/test_ui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index 40da6cc44..158fe7b70 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -652,7 +652,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.setup_beets() # Don't use the BEETSDIR from `helper`. Instead, we point the home - # directory there. Some tests will set `BEETSDIR` themselves. + # directory there. Some tests will set `BEETSDIR` themselves. del os.environ['BEETSDIR'] self._old_home = os.environ.get('HOME') os.environ['HOME'] = self.temp_dir From 02165fc3a9077ba0c091928b8f58a323a46a0215 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 9 Jun 2016 23:53:40 -0400 Subject: [PATCH 0905/2280] open lastgenre whitelist in binary mode --- beetsplug/lastgenre/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index a4b8f062b..97daafb6b 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -126,7 +126,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): wl_filename = WHITELIST if wl_filename: wl_filename = normpath(wl_filename) - with open(wl_filename, 'r') as f: + with open(wl_filename, 'rb') as f: for line in f: line = line.decode('utf8').strip().lower() if line and not line.startswith(u'#'): From ab67727283919b9b43f37abb7a2a7de9d51fe37e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 00:09:15 -0400 Subject: [PATCH 0906/2280] wrap the cover_names map with a list in fetchart most `cover_names` users expect to operate on a list --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index f131bd9d5..3514956f7 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -704,7 +704,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): self.enforce_ratio = True cover_names = self.config['cover_names'].as_str_seq() - self.cover_names = map(util.bytestring_path, cover_names) + self.cover_names = list(map(util.bytestring_path, cover_names)) self.cautious = self.config['cautious'].get(bool) self.store_source = self.config['store_source'].get(bool) From a274b4e73789a7f4d40c8ef69eaf1993a3880277 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 01:58:27 -0400 Subject: [PATCH 0907/2280] read and write the pickled statefile as binary Pickle files should be treated as binary files --- beets/importer.py | 4 ++-- test/test_importer.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index bfaa21a01..ca035dc7d 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -69,7 +69,7 @@ class ImportAbort(Exception): def _open_state(): """Reads the state file, returning a dictionary.""" try: - with open(config['statefile'].as_filename()) as f: + with open(config['statefile'].as_filename(), 'rb') as f: return pickle.load(f) except Exception as exc: # The `pickle` module can emit all sorts of exceptions during @@ -83,7 +83,7 @@ def _open_state(): def _save_state(state): """Writes the state dictionary out to disk.""" try: - with open(config['statefile'].as_filename(), 'w') as f: + with open(config['statefile'].as_filename(), 'wb') as f: pickle.dump(state, f) except IOError as exc: log.error(u'state file could not be written: {0}', exc) diff --git a/test/test_importer.py b/test/test_importer.py index e83f9e89c..8f372e841 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1341,8 +1341,8 @@ class IncrementalImportTest(unittest.TestCase, TestHelper): def test_invalid_state_file(self): importer = self.create_importer() - with open(self.config['statefile'].as_filename(), 'w') as f: - f.write('000') + with open(self.config['statefile'].as_filename(), 'wb') as f: + f.write(b'000') importer.run() self.assertEqual(len(self.lib.albums()), 1) From 78139e60e8002e9d3ff62e8a3d5c765c12de2c40 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 02:18:10 -0400 Subject: [PATCH 0908/2280] add missing b's in _unpack_asf_image --- beets/mediafile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 466ab99c9..f55c9e821 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -184,12 +184,12 @@ def _unpack_asf_image(data): """ type, size = struct.unpack_from(' Date: Fri, 10 Jun 2016 02:22:11 -0400 Subject: [PATCH 0909/2280] add missing b' in discogs query regex --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 62a78a5ff..996155fd9 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -200,7 +200,7 @@ class DiscogsPlugin(BeetsPlugin): query = re.sub(r'(?u)\W+', ' ', query).encode('ascii', "replace") # Strip medium information from query, Things like "CD1" and "disk 1" # can also negate an otherwise positive result. - query = re.sub(r'(?i)\b(CD|disc)\s*\d+', '', query) + query = re.sub(br'(?i)\b(CD|disc)\s*\d+', '', query) try: releases = self.discogs_client.search(query, type='release').page(1) From 5e62b39f75b364b1ae82474c88d85c331226f7c1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 02:30:00 -0400 Subject: [PATCH 0910/2280] replace TEMPORARY with FIXME in discogs plugin We're more likely to search for this later by FIXME. NOTE: the bug is fixed, but the versions with the fix may not be widely distributed yet --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 996155fd9..85010d3a2 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -194,7 +194,7 @@ class DiscogsPlugin(BeetsPlugin): # cause a query to return no results, even if they match the artist or # album title. Use `re.UNICODE` flag to avoid stripping non-english # word characters. - # TEMPORARY: Encode as ASCII to work around a bug: + # FIXME: Encode as ASCII to work around a bug: # https://github.com/beetbox/beets/issues/1051 # When the library is fixed, we should encode as UTF-8. query = re.sub(r'(?u)\W+', ' ', query).encode('ascii', "replace") From 69c9fb8b0741bec2adc25c5f1b51ca55adb8e89f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 02:52:58 -0400 Subject: [PATCH 0911/2280] check dirname result against b'' in fetchart --- beetsplug/embedart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 71b05f370..948da6291 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -107,7 +107,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): else: filename = bytestring_path(opts.filename or config['art_filename'].get()) - if os.path.dirname(filename) != '': + if os.path.dirname(filename) != b'': self._log.error( u"Only specify a name rather than a path for -n") return From 9b8913abdfb42da1fc1b9343007f4bb3237bb169 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 03:29:30 -0400 Subject: [PATCH 0912/2280] explicitly decode json responses in web tests --- test/test_web.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/test_web.py b/test/test_web.py index a8be83d73..51a55f33d 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -32,14 +32,14 @@ class WebPluginTest(_common.LibTestCase): def test_get_all_items(self): response = self.client.get('/item/') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['items']), 2) def test_get_single_item_by_id(self): response = self.client.get('/item/1') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(response.json['id'], 1) @@ -47,7 +47,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_multiple_items_by_id(self): response = self.client.get('/item/1,2') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['items']), 2) @@ -60,14 +60,14 @@ class WebPluginTest(_common.LibTestCase): def test_get_item_empty_query(self): response = self.client.get('/item/query/') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['items']), 2) def test_get_simple_item_query(self): response = self.client.get('/item/query/another') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['results']), 1) @@ -76,7 +76,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_all_albums(self): response = self.client.get('/album/') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] @@ -84,7 +84,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_single_album_by_id(self): response = self.client.get('/album/2') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(response.json['id'], 2) @@ -92,7 +92,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_multiple_albums_by_id(self): response = self.client.get('/album/1,2') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] @@ -100,7 +100,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_album_empty_query(self): response = self.client.get('/album/query/') - response.json = json.loads(response.data) + response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['albums']), 2) From daac41668eeb46e7be986d0053dc2942c88d5a4d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 03:46:25 -0400 Subject: [PATCH 0913/2280] use util.displayable_path in more tests --- test/test_filefilter.py | 2 +- test/test_importer.py | 10 ++++++---- test/test_library.py | 8 ++++---- test/test_plugins.py | 12 ++++++------ 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/test/test_filefilter.py b/test/test_filefilter.py index 9e6a71099..e9f7565eb 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -131,7 +131,7 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): def test_import_nothing(self): config['filefilter']['path'] = 'not_there' - self.__run(['No files imported from %s' % self.import_dir]) + self.__run(['No files imported from %s' % displayable_path(self.import_dir)]) # Global options def test_import_global(self): diff --git a/test/test_importer.py b/test/test_importer.py index 8f372e841..6024a0799 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -616,6 +616,7 @@ class ImportTest(_common.TestCase, ImportHelper): with capture_log() as logs: self.importer.run() + import_dir = displayable_path(import_dir) self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_empty_directory_singleton_warning(self): @@ -625,6 +626,7 @@ class ImportTest(_common.TestCase, ImportHelper): with capture_log() as logs: self.importer.run() + import_dir = displayable_path(import_dir) self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_asis_no_data_source(self): @@ -1671,17 +1673,17 @@ class ImportPretendTest(_common.TestCase, ImportHelper): logs = self.__run(self.import_paths) self.assertEqual(logs, [ - 'Singleton: %s' % self.import_files[0], - 'Singleton: %s' % self.import_paths[1]]) + 'Singleton: %s' % displayable_path(self.import_files[0]), + 'Singleton: %s' % displayable_path(self.import_paths[1])]) def test_import_album_pretend(self): logs = self.__run(self.import_paths, singletons=False) self.assertEqual(logs, [ 'Album: %s' % displayable_path(self.import_paths[0]), - ' %s' % self.import_files[0], + ' %s' % displayable_path(self.import_files[0]), 'Album: %s' % displayable_path(self.import_paths[1]), - ' %s' % self.import_paths[1]]) + ' %s' % displayable_path(self.import_paths[1])]) def test_import_pretend_empty(self): logs = self.__run([self.empty_path]) diff --git a/test/test_library.py b/test/test_library.py index 9d386a7a2..357e6df3d 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -358,28 +358,28 @@ class DestinationTest(_common.TestCase): self.i.artist = u'' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] - p = self.i.destination() + p = util.displayable_path(self.i.destination()) self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') def test_albumartist_falls_back_to_artist(self): self.i.artist = u'trackartist' self.i.albumartist = u'' self.lib.path_formats = [(u'default', u'$albumartist')] - p = self.i.destination() + p = util.displayable_path(self.i.destination()) self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'trackartist') def test_artist_overrides_albumartist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] - p = self.i.destination() + p = util.displayable_path(self.i.destination()) self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'theartist') def test_albumartist_overrides_artist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$albumartist')] - p = self.i.destination() + p = util.displayable_path(self.i.destination()) self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') def test_unicode_normalized_nfd_on_mac(self): diff --git a/test/test_plugins.py b/test/test_plugins.py index 421432909..4435fdd24 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -22,7 +22,7 @@ import itertools from beets.importer import SingletonImportTask, SentinelImportTask, \ ArchiveImportTask, action -from beets import plugins, config, ui +from beets import plugins, config, ui, util from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile @@ -224,9 +224,9 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): logs = [line for line in logs if not line.startswith( u'Sending event:')] self.assertEqual(logs, [ - u'Album: {0}'.format(os.path.join(self.import_dir, 'album')), - u' {0}'.format(self.file_paths[0]), - u' {0}'.format(self.file_paths[1]), + u'Album: {0}'.format(util.displayable_path(os.path.join(self.import_dir, b'album'))), + u' {0}'.format(util.displayable_path(self.file_paths[0])), + u' {0}'.format(util.displayable_path(self.file_paths[1])), ]) def test_import_task_created_with_plugin(self): @@ -267,8 +267,8 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): logs = [line for line in logs if not line.startswith( u'Sending event:')] self.assertEqual(logs, [ - u'Singleton: {0}'.format(self.file_paths[0]), - u'Singleton: {0}'.format(self.file_paths[1]), + u'Singleton: {0}'.format(util.displayable_path(self.file_paths[0])), + u'Singleton: {0}'.format(util.displayable_path(self.file_paths[1])), ]) From 6eb1de5405cdd78fb8fa7237675c3d6525b1b194 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 04:08:59 -0400 Subject: [PATCH 0914/2280] fix linelengths from displayable_path --- test/test_filefilter.py | 3 ++- test/test_plugins.py | 15 +++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/test/test_filefilter.py b/test/test_filefilter.py index e9f7565eb..56da5ef25 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -131,7 +131,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): def test_import_nothing(self): config['filefilter']['path'] = 'not_there' - self.__run(['No files imported from %s' % displayable_path(self.import_dir)]) + self.__run(['No files imported from %s' % displayable_path( + self.import_dir)]) # Global options def test_import_global(self): diff --git a/test/test_plugins.py b/test/test_plugins.py index 4435fdd24..f02a55cf1 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -22,10 +22,12 @@ import itertools from beets.importer import SingletonImportTask, SentinelImportTask, \ ArchiveImportTask, action -from beets import plugins, config, ui, util +from beets import plugins, config, ui from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile +from beets.util import displayable_path + from test.test_importer import ImportHelper, AutotagStub from test.test_ui_importer import TerminalImportSessionSetup from test._common import unittest, RSRC @@ -224,9 +226,10 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): logs = [line for line in logs if not line.startswith( u'Sending event:')] self.assertEqual(logs, [ - u'Album: {0}'.format(util.displayable_path(os.path.join(self.import_dir, b'album'))), - u' {0}'.format(util.displayable_path(self.file_paths[0])), - u' {0}'.format(util.displayable_path(self.file_paths[1])), + u'Album: {0}'.format(displayable_path( + os.path.join(self.import_dir, b'album'))), + u' {0}'.format(displayable_path(self.file_paths[0])), + u' {0}'.format(displayable_path(self.file_paths[1])), ]) def test_import_task_created_with_plugin(self): @@ -267,8 +270,8 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): logs = [line for line in logs if not line.startswith( u'Sending event:')] self.assertEqual(logs, [ - u'Singleton: {0}'.format(util.displayable_path(self.file_paths[0])), - u'Singleton: {0}'.format(util.displayable_path(self.file_paths[1])), + u'Singleton: {0}'.format(displayable_path(self.file_paths[0])), + u'Singleton: {0}'.format(displayable_path(self.file_paths[1])), ]) From 61695edc3b200aed98ea088db8106801753580ed Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 04:01:35 -0400 Subject: [PATCH 0915/2280] write file tags (for tag tests) in binary mode --- test/test_convert.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_convert.py b/test/test_convert.py index 0eef2f714..2959fc582 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -44,9 +44,10 @@ class TestHelper(helper.TestHelper): def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. """ + tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), u'{0} is not a file'.format(path)) - with open(path) as f: + with open(path, 'rb') as f: f.seek(-len(tag), os.SEEK_END) self.assertEqual(f.read(), tag, u'{0} is not tagged with {1}'.format(path, tag)) @@ -55,9 +56,10 @@ class TestHelper(helper.TestHelper): """Assert that the path is a file and the files content does not end with `tag`. """ + tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), u'{0} is not a file'.format(path)) - with open(path) as f: + with open(path, 'rb') as f: f.seek(-len(tag), os.SEEK_END) self.assertNotEqual(f.read(), tag, u'{0} is unexpectedly tagged with {1}' From 4e4a91989550c0d2fa7cc8489813d93d0cd6b568 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 04:52:55 -0400 Subject: [PATCH 0916/2280] write to tempfile in binary in embedart test --- test/test_embedart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index e58350352..dbad87968 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -113,7 +113,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): logging.getLogger('beets.embedart').setLevel(logging.DEBUG) handle, tmp_path = tempfile.mkstemp() - os.write(handle, u'I am not an image.') + os.write(handle, b'I am not an image.') os.close(handle) try: From 9204604a7cc234be7527e34079348a25ec8617be Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 10 Jun 2016 12:49:08 -0700 Subject: [PATCH 0917/2280] Fix path types in albums_in_dir tests --- test/test_importer.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 6024a0799..73d1ceb1d 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -39,6 +39,7 @@ from beets import autotag from beets.autotag import AlbumInfo, TrackInfo, AlbumMatch from beets import config from beets import logging +from beets import util class AutotagStub(object): @@ -1406,8 +1407,8 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.base = os.path.abspath(os.path.join(self.temp_dir, b'tempdir')) os.mkdir(self.base) - name = b'CAT' if ascii else u'C\xc1T'.encode('utf8') - name_alt_case = b'CAt' if ascii else u'C\xc1t'.encode('utf8') + name = b'CAT' if ascii else util.bytestring_path(u'C\xc1T') + name_alt_case = b'CAt' if ascii else util.bytestring_path(u'C\xc1t') self.dirs = [ # Nested album, multiple subdirs. @@ -1451,10 +1452,10 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): self.files = [self._normalize_path(p) for p in self.files] for path in self.dirs: - os.mkdir(path) + os.mkdir(util.syspath(path)) if files: for path in self.files: - _mkmp3(path) + _mkmp3(util.syspath(path)) def _normalize_path(self, path): """Normalize a path's Unicode combining form according to the From e346c288866d10727df075933ff62abcd84253df Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 10 Jun 2016 15:29:13 -0700 Subject: [PATCH 0918/2280] ImageMagick check uses `convert`, not `identify` See #670 for details. This reverts a change from a0c38a07a6d99ae8bb7461f1122ee34d70d2cd65. This caused problems on Windows, but the fundamental problem is more general. --- beets/util/artresizer.py | 8 +++++--- test/test_embedart.py | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 11a1fac28..8f7ae7514 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -231,9 +231,10 @@ class ArtResizer(object): def get_im_version(): """Return Image Magick version or None if it is unavailable - Try invoking ImageMagick's "convert".""" + Try invoking ImageMagick's "convert". + """ try: - out = util.command_output([b'identify', b'--version']) + out = util.command_output([b'convert', b'--version']) if b'imagemagick' in out.lower(): pattern = br".+ (\d+)\.(\d+)\.(\d+).*" @@ -244,7 +245,8 @@ def get_im_version(): int(match.group(3))) return (0,) - except (subprocess.CalledProcessError, OSError): + except (subprocess.CalledProcessError, OSError) as exc: + log.debug(u'ImageMagick check `convert --version` failed: {}', exc) return None diff --git a/test/test_embedart.py b/test/test_embedart.py index dbad87968..27939112b 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -35,7 +35,7 @@ def require_artresizer_compare(test): def wrapper(*args, **kwargs): if not ArtResizer.shared.can_compare: - raise unittest.SkipTest() + raise unittest.SkipTest("compare not available") else: return test(*args, **kwargs) From 41d9739323e57e50a477ad2b4526966d8a00a5c9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 10 Jun 2016 15:54:57 -0700 Subject: [PATCH 0919/2280] Enable Windows tests on AppVeyor (fix #670) --- appveyor.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index ca9e5a520..ef3ba8bcc 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -27,7 +27,6 @@ test_script: # Allow all failures for now: the tests don't yet pass! matrix: allow_failures: - - TOX_ENV: py27-test - TOX_ENV: py33-test - TOX_ENV: py34-test - TOX_ENV: py35-test From ea7f9948394430e64ba488a7fb480331dd3baf48 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 02:11:14 -0400 Subject: [PATCH 0920/2280] make the entire RSRC path a bytestring --- test/_common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/_common.py b/test/_common.py index ecdde1a6c..f2913e4dc 100644 --- a/test/_common.py +++ b/test/_common.py @@ -40,7 +40,7 @@ beetsplug.__path__ = [os.path.abspath( )] # Test resources path. -RSRC = os.path.join(os.path.dirname(__file__), b'rsrc') +RSRC = util.bytestring_path(os.path.join(os.path.dirname(__file__), 'rsrc')) # Propagate to root loger so nosetest can capture it log = logging.getLogger('beets') From e97d93b8f5a9464888ee26c5ab48a41c9adfe05f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 03:00:30 -0400 Subject: [PATCH 0921/2280] introduce a PLUGINPATH attr to _common test I consider this a test global option. It should help split up the ui tests a bit --- test/_common.py | 1 + test/test_ui.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/test/_common.py b/test/_common.py index f2913e4dc..a3388b88e 100644 --- a/test/_common.py +++ b/test/_common.py @@ -41,6 +41,7 @@ beetsplug.__path__ = [os.path.abspath( # Test resources path. RSRC = util.bytestring_path(os.path.join(os.path.dirname(__file__), 'rsrc')) +PLUGINPATH = os.path.join(os.path.dirname(__file__), 'rsrc', 'beetsplug') # Propagate to root loger so nosetest can capture it log = logging.getLogger('beets') diff --git a/test/test_ui.py b/test/test_ui.py index 158fe7b70..feb2c53d9 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1105,7 +1105,7 @@ class PathFormatTest(_common.TestCase): @_common.slow_test() class PluginTest(_common.TestCase): def test_plugin_command_from_pluginpath(self): - config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] + config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] ui._raw_main(['test']) @@ -1114,7 +1114,7 @@ class PluginTest(_common.TestCase): class CompletionTest(_common.TestCase): def test_completion(self): # Load plugin commands - config['pluginpath'] = [os.path.join(_common.RSRC, 'beetsplug')] + config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] # Tests run in bash From ed4ce6214b62b9c346e7b63b744d7f7ab9716129 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 03:11:34 -0400 Subject: [PATCH 0922/2280] remove pyechonest from tox config --- tox.ini | 1 - 1 file changed, 1 deletion(-) diff --git a/tox.ini b/tox.ini index afca278d7..22d4aba2a 100644 --- a/tox.ini +++ b/tox.ini @@ -16,7 +16,6 @@ deps = mock nose nose-show-skipped - pyechonest pylast rarfile responses>=0.3.0 From f8bdf7498ff43606bfdaf3c02f0ab219627767d4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 03:33:50 -0400 Subject: [PATCH 0923/2280] use _common.PLUGINPATH in one more place Not sure how I missed it, but I did --- test/test_ui.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index feb2c53d9..7c46afc2f 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -872,11 +872,9 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.path.join(os.getcwd(), 'foo.db')) def test_cli_config_file_loads_plugin_commands(self): - plugin_path = os.path.join(_common.RSRC, 'beetsplug') - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') with open(cli_config_path, 'w') as file: - file.write('pluginpath: %s\n' % plugin_path) + file.write('pluginpath: %s\n' % _common.PLUGINPATH) file.write('plugins: test') ui._raw_main(['--config', cli_config_path, 'plugin']) From 2b222d6091183540032138830ffe9f3b0ddd4341 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 03:51:23 -0400 Subject: [PATCH 0924/2280] remove outdated ordereddict dep from setup.py --- setup.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 30287fcf1..c0cf15354 100755 --- a/setup.py +++ b/setup.py @@ -93,8 +93,7 @@ setup( 'musicbrainzngs>=0.4', 'pyyaml', 'jellyfish', - ] + (['colorama'] if (sys.platform == 'win32') else []) + - (['ordereddict'] if sys.version_info < (2, 7, 0) else []), + ] + (['colorama'] if (sys.platform == 'win32') else []), tests_require=[ 'beautifulsoup4', From fff1458a9e0cf38c9d03e93bd922c4a57ece6642 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 21:26:23 -0400 Subject: [PATCH 0925/2280] introduce PATH_SEP attr to beets.util This is needed for various path tests that expect to operate on bytestrings --- beets/util/__init__.py | 3 +++ test/test_library.py | 12 ++++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index e92f1a83b..1ead27583 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -334,6 +334,9 @@ def bytestring_path(path): return path.encode('utf8') +PATH_SEP = bytestring_path(os.sep) + + def displayable_path(path, separator=u'; '): """Attempts to decode a bytestring path to a unicode object for the purpose of displaying it to the user. If the `path` argument is a diff --git a/test/test_library.py b/test/test_library.py index 357e6df3d..291b782b9 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -223,7 +223,7 @@ class DestinationTest(_common.TestCase): def test_destination_long_names_truncated(self): self.i.title = u'X' * 300 self.i.artist = u'Y' * 300 - for c in self.i.destination().split(os.path.sep): + for c in self.i.destination().split(util.PATH_SEP): self.assertTrue(len(c) <= 255) def test_destination_long_names_keep_extension(self): @@ -359,28 +359,28 @@ class DestinationTest(_common.TestCase): self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'something') def test_albumartist_falls_back_to_artist(self): self.i.artist = u'trackartist' self.i.albumartist = u'' self.lib.path_formats = [(u'default', u'$albumartist')] p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'trackartist') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'trackartist') def test_artist_overrides_albumartist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'theartist') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'theartist') def test_albumartist_overrides_artist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$albumartist')] p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(os.path.sep, 1)[1], u'something') + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'something') def test_unicode_normalized_nfd_on_mac(self): instr = unicodedata.normalize('NFC', u'caf\xe9') @@ -883,7 +883,7 @@ class ArtDestinationTest(_common.TestCase): def test_art_filename_respects_setting(self): art = self.ai.art_destination('something.jpg') - self.assertTrue('%sartimage.jpg' % os.path.sep in art) + self.assertTrue('%sartimage.jpg' % util.PATH_SEP in art) def test_art_path_in_item_dir(self): art = self.ai.art_destination('something.jpg') From 6c969ae58c9bdce293915b6419641d41bd40df24 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 11 Jun 2016 21:29:17 -0400 Subject: [PATCH 0926/2280] remove some incorrect displayable_path in library tests These were noticed by @sampsyo in the review of https://github.com/beetbox/beets/commit/daac41668eeb46e7be986d0053dc2942c88d5a4d --- test/test_library.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 291b782b9..3afe3c0dd 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -358,29 +358,29 @@ class DestinationTest(_common.TestCase): self.i.artist = u'' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] - p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'something') + p = self.i.destination() + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'something') def test_albumartist_falls_back_to_artist(self): self.i.artist = u'trackartist' self.i.albumartist = u'' self.lib.path_formats = [(u'default', u'$albumartist')] - p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'trackartist') + p = self.i.destination() + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'trackartist') def test_artist_overrides_albumartist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$artist')] - p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'theartist') + p = self.i.destination() + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'theartist') def test_albumartist_overrides_artist(self): self.i.artist = u'theartist' self.i.albumartist = u'something' self.lib.path_formats = [(u'default', u'$albumartist')] - p = util.displayable_path(self.i.destination()) - self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], u'something') + p = self.i.destination() + self.assertEqual(p.rsplit(util.PATH_SEP, 1)[1], b'something') def test_unicode_normalized_nfd_on_mac(self): instr = unicodedata.normalize('NFC', u'caf\xe9') From a76de9518318e6d401585c8a69f84d5da7085a9a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 12 Jun 2016 01:19:39 -0400 Subject: [PATCH 0927/2280] return a bytestring path from RemoteArtSource --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 3514956f7..5eb120a65 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -243,7 +243,7 @@ class RemoteArtSource(ArtSource): fh.write(chunk) self._log.debug(u'downloaded art to: {0}', util.displayable_path(fh.name)) - candidate.path = fh.name + candidate.path = util.bytestring_path(fh.name) return except (IOError, requests.RequestException, TypeError) as exc: From 10dda13d2afef9733253e9d20d6928c968c32023 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 12 Jun 2016 18:03:08 -0400 Subject: [PATCH 0928/2280] remove unneeded bytes casting from test_mb --- test/test_mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mb.py b/test/test_mb.py index b4bfc82c7..43656451d 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -66,7 +66,7 @@ class MBAlbumInfoTest(_common.TestCase): for i, recording in enumerate(tracks): track = { 'recording': recording, - 'position': bytes(i + 1), + 'position': i + 1, } if track_length: # Track lengths are distinct from recording lengths. From 92950ec5320a96e1513db9d54a3e648622a0295c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 12 Jun 2016 18:17:27 -0400 Subject: [PATCH 0929/2280] wrap keys() result in a list() in importadded tests --- test/test_importadded.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_importadded.py b/test/test_importadded.py index bddd884f9..80491aa0a 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -156,7 +156,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): # Newer Item path mtimes as if Beets had modified them modify_mtimes(items_added_before.keys(), offset=10000) # Reimport - import_dir = os.path.dirname(items_added_before.keys()[0]) + import_dir = os.path.dirname(list(items_added_before.keys())[0]) self._setup_import_session(import_dir=import_dir, singletons=True) self.importer.run() # Verify the reimported items From 4dd43f10813c45e9594a0064236e8e2538316f79 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 12 Jun 2016 20:27:01 -0400 Subject: [PATCH 0930/2280] write to the m3u file in binary mode in importfeeds --- beetsplug/importfeeds.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index d046ddc47..0d9e50616 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -61,7 +61,7 @@ def _write_m3u(m3u_path, items_paths): """Append relative paths to items into m3u file. """ mkdirall(m3u_path) - with open(syspath(m3u_path), 'a') as f: + with open(syspath(m3u_path), 'ab') as f: for path in items_paths: f.write(path + b'\n') From 6745759ea5680eead23b90bfd9b744ba822d7127 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 13 Jun 2016 05:18:09 -0400 Subject: [PATCH 0931/2280] open even more files in binary mode * play plugin * smartplaylist plugin --- beetsplug/play.py | 2 +- beetsplug/smartplaylist.py | 2 +- test/test_play.py | 4 ++-- test/test_smartplaylist.py | 8 ++++---- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index fa70f2bc0..465d8e6d5 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -148,7 +148,7 @@ class PlayPlugin(BeetsPlugin): def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. """ - m3u = NamedTemporaryFile('w', suffix='.m3u', delete=False) + m3u = NamedTemporaryFile('wb', suffix='.m3u', delete=False) for item in paths_list: m3u.write(item + b'\n') m3u.close() diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index f6d7f7157..98092952e 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -196,7 +196,7 @@ class SmartPlaylistPlugin(BeetsPlugin): for m3u in m3us: m3u_path = normpath(os.path.join(playlist_dir, m3u)) mkdirall(m3u_path) - with open(syspath(m3u_path), 'w') as f: + with open(syspath(m3u_path), 'wb') as f: for path in m3us[m3u]: f.write(path + b'\n') self._log.info(u"{0} playlists updated", len(self._matched_playlists)) diff --git a/test/test_play.py b/test/test_play.py index 4b979a001..cd0f4211c 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -50,7 +50,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.open_mock.assert_called_once_with(ANY, expected_cmd) expected_playlist = expected_playlist or self.item.path.decode('utf-8') exp_playlist = expected_playlist + u'\n' - with open(self.open_mock.call_args[0][0][0], 'r') as playlist: + with open(self.open_mock.call_args[0][0][0], 'rb') as playlist: self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) def test_basic(self): @@ -81,7 +81,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', '-a', 'nice') self.open_mock.assert_called_once_with(ANY, open_anything()) - playlist = open(self.open_mock.call_args[0][0][0], 'r') + playlist = open(self.open_mock.call_args[0][0][0], 'rb') self.assertEqual(u'{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), playlist.read().decode('utf-8')) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 401b36570..e1ce36951 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -173,7 +173,7 @@ class SmartPlaylistTest(unittest.TestCase): m3u_filepath = path.join(dir, pl[0]) self.assertTrue(path.exists(m3u_filepath)) - with open(syspath(m3u_filepath), 'r') as f: + with open(syspath(m3u_filepath), 'rb') as f: content = f.read() rmtree(dir) @@ -205,18 +205,18 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): self.run_with_output(u'splupdate', u'my_playlist') m3u_path = path.join(self.temp_dir, 'my_playlist.m3u') self.assertTrue(path.exists(m3u_path)) - with open(m3u_path, 'r') as f: + with open(m3u_path, 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) self.run_with_output(u'splupdate', u'my_playlist.m3u') - with open(m3u_path, 'r') as f: + with open(m3u_path, 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") remove(m3u_path) self.run_with_output(u'splupdate') for name in (u'my_playlist.m3u', u'all.m3u'): - with open(path.join(self.temp_dir, name), 'r') as f: + with open(path.join(self.temp_dir, name), 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") From ffa46a185c07a32a024092505d327bbe163bce86 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 10 Jun 2016 05:39:31 -0400 Subject: [PATCH 0932/2280] bytestring normalization Make sure many/most strings that touch the filesystem are converted explicitly to bytestrings rather than implictly. --- beets/importer.py | 15 ++-- beets/library.py | 2 +- test/helper.py | 17 ++-- test/test_art.py | 46 +++++------ test/test_convert.py | 34 ++++---- test/test_embedart.py | 2 +- test/test_filefilter.py | 23 +++--- test/test_files.py | 126 ++++++++++++++--------------- test/test_importadded.py | 4 +- test/test_importer.py | 150 +++++++++++++++++----------------- test/test_ipfs.py | 2 + test/test_library.py | 157 ++++++++++++++++++------------------ test/test_mediafile.py | 13 +-- test/test_mediafile_edge.py | 57 +++++++------ test/test_play.py | 2 +- test/test_plugins.py | 12 +-- test/test_query.py | 10 +-- test/test_smartplaylist.py | 2 +- test/test_thumbnails.py | 3 +- test/test_ui.py | 50 ++++++------ test/test_ui_commands.py | 6 +- 21 files changed, 380 insertions(+), 353 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index ca035dc7d..b190329ce 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1439,8 +1439,8 @@ def group_albums(session): task = pipeline.multiple(tasks) -MULTIDISC_MARKERS = (r'dis[ck]', r'cd') -MULTIDISC_PAT_FMT = r'^(.*%s[\W_]*)\d' +MULTIDISC_MARKERS = (br'dis[ck]', br'cd') +MULTIDISC_PAT_FMT = br'^(.*%s[\W_]*)\d' def albums_in_dir(path): @@ -1483,7 +1483,9 @@ def albums_in_dir(path): # named in this way. start_collapsing = False for marker in MULTIDISC_MARKERS: - marker_pat = re.compile(MULTIDISC_PAT_FMT % marker, re.I) + # We're using replace on %s due to lack of .format() on bytestrings + p = MULTIDISC_PAT_FMT.replace(b'%s', marker) + marker_pat = re.compile(p, re.I) match = marker_pat.match(os.path.basename(root)) # Is this directory the root of a nested multi-disc album? @@ -1497,8 +1499,10 @@ def albums_in_dir(path): if not subdir_pat: match = marker_pat.match(subdir) if match: + match_group = re.escape(match.group(1)) subdir_pat = re.compile( - br'^%s\d' % re.escape(match.group(1)), re.I + b''.join([b'^', match_group, br'\d']), + re.I ) else: start_collapsing = False @@ -1520,7 +1524,8 @@ def albums_in_dir(path): # Set the current pattern to match directories with the same # prefix as this one, followed by a digit. collapse_pat = re.compile( - br'^%s\d' % re.escape(match.group(1)), re.I + b''.join([b'^', re.escape(match.group(1)), br'\d']), + re.I ) break diff --git a/beets/library.py b/beets/library.py index 5ae0182e3..b9d9d4ffc 100644 --- a/beets/library.py +++ b/beets/library.py @@ -48,7 +48,7 @@ class PathQuery(dbcore.FieldQuery): and case-sensitive otherwise. """ - escape_re = re.compile(r'[\\_%]') + escape_re = re.compile(br'[\\_%]') escape_char = b'\\' def __init__(self, field, pattern, fast=True, case_sensitive=None): diff --git a/test/helper.py b/test/helper.py index 3196e265e..db3de22aa 100644 --- a/test/helper.py +++ b/test/helper.py @@ -177,7 +177,7 @@ class TestHelper(object): self.config['ui']['color'] = False self.config['threaded'] = False - self.libdir = os.path.join(self.temp_dir, 'libdir') + self.libdir = os.path.join(self.temp_dir, b'libdir') os.mkdir(self.libdir) self.config['directory'] = self.libdir @@ -227,13 +227,13 @@ class TestHelper(object): Copies the specified number of files to a subdirectory of `self.temp_dir` and creates a `TestImportSession` for this path. """ - import_dir = os.path.join(self.temp_dir, 'import') + import_dir = os.path.join(self.temp_dir, b'import') if not os.path.isdir(import_dir): os.mkdir(import_dir) album_no = 0 while album_count: - album = u'album {0}'.format(album_no) + album = util.bytestring_path(u'album {0}'.format(album_no)) album_dir = os.path.join(import_dir, album) if os.path.exists(album_dir): album_no += 1 @@ -245,8 +245,9 @@ class TestHelper(object): album_item_count = item_count while album_item_count: title = u'track {0}'.format(track_no) - src = os.path.join(_common.RSRC, 'full.mp3') - dest = os.path.join(album_dir, '{0}.mp3'.format(title)) + src = os.path.join(_common.RSRC, b'full.mp3') + title_file = util.bytestring_path('{0}.mp3'.format(title)) + dest = os.path.join(album_dir, title_file) if os.path.exists(dest): track_no += 1 continue @@ -342,7 +343,7 @@ class TestHelper(object): """ # TODO base this on `add_item()` items = [] - path = os.path.join(_common.RSRC, 'full.' + ext) + path = os.path.join(_common.RSRC, b'full.' + ext) for i in range(count): item = Item.from_path(bytes(path)) item.album = u'\u00e4lbum {0}'.format(i) # Check unicode paths @@ -388,8 +389,8 @@ class TestHelper(object): mediafile = MediaFile(path) imgs = [] for img_ext in images: - img_path = os.path.join(_common.RSRC, - 'image-2x3.{0}'.format(img_ext)) + file = util.bytestring_path('image-2x3.{0}'.format(img_ext)) + img_path = os.path.join(_common.RSRC, file) with open(img_path, 'rb') as f: imgs.append(Image(f.read())) mediafile.images = imgs diff --git a/test/test_art.py b/test/test_art.py index 1b12b76f6..348835c4c 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -58,7 +58,7 @@ class FetchImageTest(UseThePlugin): def setUp(self): super(FetchImageTest, self).setUp() - self.dpath = os.path.join(self.temp_dir, 'arttest') + self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} @@ -78,7 +78,7 @@ class FetchImageTest(UseThePlugin): class FSArtTest(UseThePlugin): def setUp(self): super(FSArtTest, self).setUp() - self.dpath = os.path.join(self.temp_dir, 'arttest') + self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) self.source = fetchart.FileSystem(logger, self.plugin.config) @@ -87,23 +87,23 @@ class FSArtTest(UseThePlugin): 'paths': [self.dpath]} def test_finds_jpg_in_directory(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) + _common.touch(os.path.join(self.dpath, b'a.jpg')) candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, os.path.join(self.dpath, 'a.jpg')) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'a.jpg')) def test_appropriately_named_file_takes_precedence(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) - _common.touch(os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'a.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) candidate = next(self.source.get(None, self.extra)) - self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_non_image_file_not_identified(self): - _common.touch(os.path.join(self.dpath, 'a.txt')) + _common.touch(os.path.join(self.dpath, b'a.txt')) with self.assertRaises(StopIteration): next(self.source.get(None, self.extra)) def test_cautious_skips_fallback(self): - _common.touch(os.path.join(self.dpath, 'a.jpg')) + _common.touch(os.path.join(self.dpath, b'a.jpg')) self.extra['cautious'] = True with self.assertRaises(StopIteration): next(self.source.get(None, self.extra)) @@ -135,7 +135,7 @@ class CombinedTest(UseThePlugin): def setUp(self): super(CombinedTest, self).setUp() - self.dpath = os.path.join(self.temp_dir, 'arttest') + self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) @responses.activate @@ -157,12 +157,12 @@ class CombinedTest(UseThePlugin): self.assertIsNone(candidate) def test_main_interface_gives_precedence_to_fs_art(self): - _common.touch(os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) - self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_main_interface_falls_back_to_amazon(self): self.mock_response(self.AMAZON_URL) @@ -198,12 +198,12 @@ class CombinedTest(UseThePlugin): self.assertEqual(len(responses.calls), 0) def test_local_only_gets_fs_image(self): - _common.touch(os.path.join(self.dpath, 'art.jpg')) + _common.touch(os.path.join(self.dpath, b'art.jpg')) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath], local_only=True) self.assertIsNotNone(candidate) - self.assertEqual(candidate.path, os.path.join(self.dpath, 'art.jpg')) + self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) self.assertEqual(len(responses.calls), 0) @@ -387,7 +387,7 @@ class ArtImporterTest(UseThePlugin): super(ArtImporterTest, self).setUp() # Mock the album art fetcher to always return our test file. - self.art_file = os.path.join(self.temp_dir, 'tmpcover.jpg') + self.art_file = os.path.join(self.temp_dir, b'tmpcover.jpg') _common.touch(self.art_file) self.old_afa = self.plugin.art_for_album self.afa_response = fetchart.Candidate(logger, path=self.art_file) @@ -401,9 +401,9 @@ class ArtImporterTest(UseThePlugin): self.libpath = os.path.join(self.temp_dir, 'tmplib.blb') self.libdir = os.path.join(self.temp_dir, 'tmplib') os.mkdir(self.libdir) - os.mkdir(os.path.join(self.libdir, 'album')) - itempath = os.path.join(self.libdir, 'album', 'test.mp3') - shutil.copyfile(os.path.join(_common.RSRC, 'full.mp3'), itempath) + os.mkdir(os.path.join(self.libdir, b'album')) + itempath = os.path.join(self.libdir, b'album', b'test.mp3') + shutil.copyfile(os.path.join(_common.RSRC, b'full.mp3'), itempath) self.lib = library.Library(self.libpath) self.i = _common.item() self.i.path = itempath @@ -445,7 +445,7 @@ class ArtImporterTest(UseThePlugin): if should_exist: self.assertEqual( artpath, - os.path.join(os.path.dirname(self.i.path), 'cover.jpg') + os.path.join(os.path.dirname(self.i.path), b'cover.jpg') ) self.assertExists(artpath) else: @@ -474,7 +474,7 @@ class ArtImporterTest(UseThePlugin): self.assertNotExists(self.art_file) def test_do_not_delete_original_if_already_in_place(self): - artdest = os.path.join(os.path.dirname(self.i.path), 'cover.jpg') + artdest = os.path.join(os.path.dirname(self.i.path), b'cover.jpg') shutil.copyfile(self.art_file, artdest) self.afa_response = fetchart.Candidate(logger, path=artdest) self._fetch_art(True) @@ -497,9 +497,9 @@ class ArtForAlbumTest(UseThePlugin): configuration (e.g., minwidth, enforce_ratio) """ - IMG_225x225 = os.path.join(_common.RSRC, 'abbey.jpg') - IMG_348x348 = os.path.join(_common.RSRC, 'abbey-different.jpg') - IMG_500x490 = os.path.join(_common.RSRC, 'abbey-similar.jpg') + IMG_225x225 = os.path.join(_common.RSRC, b'abbey.jpg') + IMG_348x348 = os.path.join(_common.RSRC, b'abbey-different.jpg') + IMG_500x490 = os.path.join(_common.RSRC, b'abbey-similar.jpg') def setUp(self): super(ArtForAlbumTest, self).setUp() diff --git a/test/test_convert.py b/test/test_convert.py index 2959fc582..d3a1206be 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -38,7 +38,7 @@ class TestHelper(helper.TestHelper): .format(tag)) # A Python script that copies the file and appends a tag. - stub = os.path.join(_common.RSRC, 'convert_stub.py') + stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') return u"python '{}' $source $dest {}".format(stub, tag) def assertFileTag(self, path, tag): # noqa @@ -75,7 +75,7 @@ class ImportConvertTest(unittest.TestCase, TestHelper): self.load_plugins('convert') self.config['convert'] = { - 'dest': os.path.join(self.temp_dir, 'convert'), + 'dest': os.path.join(self.temp_dir, b'convert'), 'command': self.tagged_copy_cmd('convert'), # Enforce running convert 'max_bitrate': 1, @@ -130,7 +130,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): self.load_plugins('convert') self.convert_dest = util.bytestring_path( - os.path.join(self.temp_dir, 'convert_dest') + os.path.join(self.temp_dir, b'convert_dest') ) self.config['convert'] = { 'dest': self.convert_dest, @@ -152,38 +152,38 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): def test_convert(self): with control_stdin('y'): self.run_convert() - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_convert_with_auto_confirmation(self): self.run_convert('--yes') - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_rejecet_confirmation(self): with control_stdin('n'): self.run_convert() - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFalse(os.path.isfile(converted)) def test_convert_keep_new(self): - self.assertEqual(os.path.splitext(self.item.path)[1], '.ogg') + self.assertEqual(os.path.splitext(self.item.path)[1], b'.ogg') with control_stdin('y'): self.run_convert('--keep-new') self.item.load() - self.assertEqual(os.path.splitext(self.item.path)[1], '.mp3') + self.assertEqual(os.path.splitext(self.item.path)[1], b'.mp3') def test_format_option(self): with control_stdin('y'): self.run_convert('--format', 'opus') - converted = os.path.join(self.convert_dest, 'converted.ops') + converted = os.path.join(self.convert_dest, b'converted.ops') self.assertFileTag(converted, 'opus') def test_embed_album_art(self): self.config['convert']['embed'] = True - image_path = os.path.join(_common.RSRC, 'image-2x3.jpg') + image_path = os.path.join(_common.RSRC, b'image-2x3.jpg') self.album.artpath = image_path self.album.store() with open(os.path.join(image_path), 'rb') as f: @@ -191,12 +191,12 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): with control_stdin('y'): self.run_convert() - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') mediafile = MediaFile(converted) self.assertEqual(mediafile.images[0].data, image_data) def test_skip_existing(self): - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.touch(converted, content='XXX') self.run_convert('--yes') with open(converted, 'r') as f: @@ -204,7 +204,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): def test_pretend(self): self.run_convert('--pretend') - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFalse(os.path.exists(converted)) @@ -218,7 +218,7 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, self.setup_beets(disk=True) # Converter is threaded self.load_plugins('convert') - self.convert_dest = os.path.join(self.temp_dir, 'convert_dest') + self.convert_dest = os.path.join(self.temp_dir, b'convert_dest') self.config['convert'] = { 'dest': self.convert_dest, 'paths': {'default': 'converted'}, @@ -237,7 +237,7 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, [item] = self.add_item_fixtures(ext='flac') with control_stdin('y'): self.run_convert_path(item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_transcode_from_lossy(self): @@ -245,14 +245,14 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): self.run_convert_path(item.path) - converted = os.path.join(self.convert_dest, 'converted.mp3') + converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') def test_transcode_from_lossy_prevented(self): [item] = self.add_item_fixtures(ext='ogg') with control_stdin('y'): self.run_convert_path(item.path) - converted = os.path.join(self.convert_dest, 'converted.ogg') + converted = os.path.join(self.convert_dest, b'converted.ogg') self.assertNoFileTag(converted, 'mp3') diff --git a/test/test_embedart.py b/test/test_embedart.py index 27939112b..2bb357001 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -153,7 +153,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.abbey_similarpath)) def test_non_ascii_album_path(self): - resource_path = os.path.join(_common.RSRC, 'image.mp3').encode('utf8') + resource_path = os.path.join(_common.RSRC, b'image.mp3') album = self.add_album_fixture() trackpath = album.items()[0].path albumpath = album.path diff --git a/test/test_filefilter.py b/test/test_filefilter.py index 56da5ef25..09b6d94a4 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -27,7 +27,7 @@ from test.helper import capture_log from test.test_importer import ImportHelper from beets import config from beets.mediafile import MediaFile -from beets.util import displayable_path +from beets.util import displayable_path, bytestring_path from beetsplug.filefilter import FileFilterPlugin @@ -43,7 +43,7 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): def __copy_file(self, dest_path, metadata): # Copy files - resource_path = os.path.join(_common.RSRC, 'full.mp3') + resource_path = os.path.join(_common.RSRC, b'full.mp3') shutil.copy(resource_path, dest_path) medium = MediaFile(dest_path) # Set metadata @@ -52,13 +52,13 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): medium.save() def __create_import_dir(self, count): - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - self.artist_path = os.path.join(self.import_dir, 'artist') - self.album_path = os.path.join(self.artist_path, 'album') - self.misc_path = os.path.join(self.import_dir, 'misc') + self.artist_path = os.path.join(self.import_dir, b'artist') + self.album_path = os.path.join(self.artist_path, b'album') + self.misc_path = os.path.join(self.import_dir, b'misc') os.makedirs(self.album_path) os.makedirs(self.misc_path) @@ -74,8 +74,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): for i in range(count): metadata['track'] = i + 1 metadata['title'] = 'Tag Title Album %d' % (i + 1) - dest_path = os.path.join(self.album_path, - '%02d - track.mp3' % (i + 1)) + track_file = bytestring_path('%02d - track.mp3' % (i + 1)) + dest_path = os.path.join(self.album_path, track_file) self.__copy_file(dest_path, metadata) self.album_paths.append(dest_path) @@ -84,8 +84,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): for i in range(count): metadata['track'] = i + 10 metadata['title'] = 'Tag Title Artist %d' % (i + 1) - dest_path = os.path.join(self.artist_path, - 'track_%d.mp3' % (i + 1)) + track_file = bytestring_path('track_%d.mp3' % (i + 1)) + dest_path = os.path.join(self.artist_path, track_file) self.__copy_file(dest_path, metadata) self.artist_paths.append(dest_path) @@ -94,7 +94,8 @@ class FileFilterPluginTest(unittest.TestCase, ImportHelper): metadata['artist'] = 'Artist %d' % (i + 42) metadata['track'] = i + 5 metadata['title'] = 'Tag Title Misc %d' % (i + 1) - dest_path = os.path.join(self.misc_path, 'track_%d.mp3' % (i + 1)) + track_file = bytestring_path('track_%d.mp3' % (i + 1)) + dest_path = os.path.join(self.misc_path, track_file) self.__copy_file(dest_path, metadata) self.misc_paths.append(dest_path) diff --git a/test/test_files.py b/test/test_files.py index 5af8bd5ef..884aa40d0 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -34,8 +34,8 @@ class MoveTest(_common.TestCase): super(MoveTest, self).setUp() # make a temporary file - self.path = join(self.temp_dir, 'temp.mp3') - shutil.copy(join(_common.RSRC, 'full.mp3'), self.path) + self.path = join(self.temp_dir, b'temp.mp3') + shutil.copy(join(_common.RSRC, b'full.mp3'), self.path) # add it to a temporary library self.lib = beets.library.Library(':memory:') @@ -43,7 +43,7 @@ class MoveTest(_common.TestCase): self.lib.add(self.i) # set up the destination - self.libdir = join(self.temp_dir, 'testlibdir') + self.libdir = join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) self.lib.directory = self.libdir self.lib.path_formats = [('default', @@ -51,9 +51,9 @@ class MoveTest(_common.TestCase): self.i.artist = 'one' self.i.album = 'two' self.i.title = 'three' - self.dest = join(self.libdir, 'one', 'two', 'three.mp3') + self.dest = join(self.libdir, b'one', b'two', b'three.mp3') - self.otherdir = join(self.temp_dir, 'testotherdir') + self.otherdir = join(self.temp_dir, b'testotherdir') def test_move_arrives(self): self.i.move() @@ -61,7 +61,7 @@ class MoveTest(_common.TestCase): def test_move_to_custom_dir(self): self.i.move(basedir=self.otherdir) - self.assertExists(join(self.otherdir, 'one', 'two', 'three.mp3')) + self.assertExists(join(self.otherdir, b'one', b'two', b'three.mp3')) def test_move_departs(self): self.i.move() @@ -182,7 +182,7 @@ class AlbumFileTest(_common.TestCase): self.lib = beets.library.Library(':memory:') self.lib.path_formats = \ [('default', join('$albumartist', '$album', '$title'))] - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) # Make a file for the item. @@ -192,7 +192,7 @@ class AlbumFileTest(_common.TestCase): # Make an album. self.ai = self.lib.add_album((self.i,)) # Alternate destination dir. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def test_albuminfo_move_changes_paths(self): self.ai.album = u'newAlbumName' @@ -200,7 +200,7 @@ class AlbumFileTest(_common.TestCase): self.ai.store() self.i.load() - self.assertTrue('newAlbumName' in self.i.path) + self.assertTrue(b'newAlbumName' in self.i.path) def test_albuminfo_move_moves_file(self): oldpath = self.i.path @@ -226,7 +226,7 @@ class AlbumFileTest(_common.TestCase): self.ai.move(basedir=self.otherdir) self.i.load() self.ai.store() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) class ArtFileTest(_common.TestCase): @@ -235,7 +235,7 @@ class ArtFileTest(_common.TestCase): # Make library and item. self.lib = beets.library.Library(':memory:') - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) self.i.path = self.i.destination() @@ -250,7 +250,7 @@ class ArtFileTest(_common.TestCase): self.ai.artpath = self.art self.ai.store() # Alternate destination dir. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def test_art_deleted_when_items_deleted(self): self.assertTrue(os.path.exists(self.art)) @@ -279,12 +279,12 @@ class ArtFileTest(_common.TestCase): self.assertNotExists(self.art) newart = self.lib.get_album(self.i).artpath self.assertExists(newart) - self.assertTrue('testotherdir' in newart) + self.assertTrue(b'testotherdir' in newart) def test_setart_copies_image(self): os.remove(self.art) - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path @@ -300,7 +300,7 @@ class ArtFileTest(_common.TestCase): os.remove(self.art) # Original art. - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path @@ -314,7 +314,7 @@ class ArtFileTest(_common.TestCase): self.assertTrue(os.path.exists(ai.artpath)) def test_setart_to_existing_but_unset_art_works(self): - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path @@ -331,7 +331,7 @@ class ArtFileTest(_common.TestCase): self.assertTrue(os.path.exists(ai.artpath)) def test_setart_to_conflicting_file_gets_new_path(self): - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) i2 = item() i2.path = self.i.path @@ -352,7 +352,7 @@ class ArtFileTest(_common.TestCase): def test_setart_sets_permissions(self): os.remove(self.art) - newart = os.path.join(self.libdir, 'newart.jpg') + newart = os.path.join(self.libdir, b'newart.jpg') touch(newart) os.chmod(newart, 0o400) # read-only @@ -382,7 +382,7 @@ class ArtFileTest(_common.TestCase): self.ai.items()[0].move() artpath = self.lib.albums()[0].artpath - self.assertTrue(u'different_album' in artpath) + self.assertTrue(b'different_album' in artpath) self.assertExists(artpath) self.assertNotExists(oldartpath) @@ -399,7 +399,7 @@ class ArtFileTest(_common.TestCase): self.i.move() artpath = self.lib.albums()[0].artpath - self.assertFalse(u'different_album' in artpath) + self.assertFalse(b'different_album' in artpath) self.assertEqual(artpath, oldartpath) self.assertExists(oldartpath) @@ -410,7 +410,7 @@ class RemoveTest(_common.TestCase): # Make library and item. self.lib = beets.library.Library(':memory:') - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') self.lib.directory = self.libdir self.i = item(self.lib) self.i.path = self.i.destination() @@ -428,13 +428,13 @@ class RemoveTest(_common.TestCase): def test_removing_last_item_preserves_nonempty_dir(self): parent = os.path.dirname(self.i.path) - touch(os.path.join(parent, 'dummy.txt')) + touch(os.path.join(parent, b'dummy.txt')) self.i.remove(True) self.assertExists(parent) def test_removing_last_item_prunes_dir_with_blacklisted_file(self): parent = os.path.dirname(self.i.path) - touch(os.path.join(parent, '.DS_Store')) + touch(os.path.join(parent, b'.DS_Store')) self.i.remove(True) self.assertNotExists(parent) @@ -448,13 +448,13 @@ class RemoveTest(_common.TestCase): self.assertExists(self.libdir) def test_removing_item_outside_of_library_deletes_nothing(self): - self.lib.directory = os.path.join(self.temp_dir, 'xxx') + self.lib.directory = os.path.join(self.temp_dir, b'xxx') parent = os.path.dirname(self.i.path) self.i.remove(True) self.assertExists(parent) def test_removing_last_item_in_album_with_albumart_prunes_dir(self): - artfile = os.path.join(self.temp_dir, 'testart.jpg') + artfile = os.path.join(self.temp_dir, b'testart.jpg') touch(artfile) self.ai.set_art(artfile) self.ai.store() @@ -469,7 +469,7 @@ class SoftRemoveTest(_common.TestCase): def setUp(self): super(SoftRemoveTest, self).setUp() - self.path = os.path.join(self.temp_dir, 'testfile') + self.path = os.path.join(self.temp_dir, b'testfile') touch(self.path) def test_soft_remove_deletes_file(self): @@ -478,7 +478,7 @@ class SoftRemoveTest(_common.TestCase): def test_soft_remove_silent_on_no_file(self): try: - util.remove(self.path + 'XXX', True) + util.remove(self.path + b'XXX', True) except OSError: self.fail(u'OSError when removing path') @@ -487,11 +487,11 @@ class SafeMoveCopyTest(_common.TestCase): def setUp(self): super(SafeMoveCopyTest, self).setUp() - self.path = os.path.join(self.temp_dir, 'testfile') + self.path = os.path.join(self.temp_dir, b'testfile') touch(self.path) - self.otherpath = os.path.join(self.temp_dir, 'testfile2') + self.otherpath = os.path.join(self.temp_dir, b'testfile2') touch(self.otherpath) - self.dest = self.path + '.dest' + self.dest = self.path + b'.dest' def test_successful_move(self): util.move(self.path, self.dest) @@ -524,9 +524,9 @@ class PruneTest(_common.TestCase): def setUp(self): super(PruneTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - self.sub = os.path.join(self.base, 'subdir') + self.sub = os.path.join(self.base, b'subdir') os.mkdir(self.sub) def test_prune_existent_directory(self): @@ -535,7 +535,7 @@ class PruneTest(_common.TestCase): self.assertNotExists(self.sub) def test_prune_nonexistent_directory(self): - util.prune_dirs(os.path.join(self.sub, 'another'), self.base) + util.prune_dirs(os.path.join(self.sub, b'another'), self.base) self.assertExists(self.base) self.assertNotExists(self.sub) @@ -544,37 +544,37 @@ class WalkTest(_common.TestCase): def setUp(self): super(WalkTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - touch(os.path.join(self.base, 'y')) - touch(os.path.join(self.base, 'x')) - os.mkdir(os.path.join(self.base, 'd')) - touch(os.path.join(self.base, 'd', 'z')) + touch(os.path.join(self.base, b'y')) + touch(os.path.join(self.base, b'x')) + os.mkdir(os.path.join(self.base, b'd')) + touch(os.path.join(self.base, b'd', b'z')) def test_sorted_files(self): res = list(util.sorted_walk(self.base)) self.assertEqual(len(res), 2) self.assertEqual(res[0], - (self.base, ['d'], ['x', 'y'])) + (self.base, [b'd'], [b'x', b'y'])) self.assertEqual(res[1], - (os.path.join(self.base, 'd'), [], ['z'])) + (os.path.join(self.base, b'd'), [], [b'z'])) def test_ignore_file(self): - res = list(util.sorted_walk(self.base, ('x',))) + res = list(util.sorted_walk(self.base, (b'x',))) self.assertEqual(len(res), 2) self.assertEqual(res[0], - (self.base, ['d'], ['y'])) + (self.base, [b'd'], [b'y'])) self.assertEqual(res[1], - (os.path.join(self.base, 'd'), [], ['z'])) + (os.path.join(self.base, b'd'), [], [b'z'])) def test_ignore_directory(self): - res = list(util.sorted_walk(self.base, ('d',))) + res = list(util.sorted_walk(self.base, (b'd',))) self.assertEqual(len(res), 1) self.assertEqual(res[0], - (self.base, [], ['x', 'y'])) + (self.base, [], [b'x', b'y'])) def test_ignore_everything(self): - res = list(util.sorted_walk(self.base, ('*',))) + res = list(util.sorted_walk(self.base, (b'*',))) self.assertEqual(len(res), 1) self.assertEqual(res[0], (self.base, [], [])) @@ -584,43 +584,43 @@ class UniquePathTest(_common.TestCase): def setUp(self): super(UniquePathTest, self).setUp() - self.base = os.path.join(self.temp_dir, 'testdir') + self.base = os.path.join(self.temp_dir, b'testdir') os.mkdir(self.base) - touch(os.path.join(self.base, 'x.mp3')) - touch(os.path.join(self.base, 'x.1.mp3')) - touch(os.path.join(self.base, 'x.2.mp3')) - touch(os.path.join(self.base, 'y.mp3')) + touch(os.path.join(self.base, b'x.mp3')) + touch(os.path.join(self.base, b'x.1.mp3')) + touch(os.path.join(self.base, b'x.2.mp3')) + touch(os.path.join(self.base, b'y.mp3')) def test_new_file_unchanged(self): - path = util.unique_path(os.path.join(self.base, 'z.mp3')) - self.assertEqual(path, os.path.join(self.base, 'z.mp3')) + path = util.unique_path(os.path.join(self.base, b'z.mp3')) + self.assertEqual(path, os.path.join(self.base, b'z.mp3')) def test_conflicting_file_appends_1(self): - path = util.unique_path(os.path.join(self.base, 'y.mp3')) - self.assertEqual(path, os.path.join(self.base, 'y.1.mp3')) + path = util.unique_path(os.path.join(self.base, b'y.mp3')) + self.assertEqual(path, os.path.join(self.base, b'y.1.mp3')) def test_conflicting_file_appends_higher_number(self): - path = util.unique_path(os.path.join(self.base, 'x.mp3')) - self.assertEqual(path, os.path.join(self.base, 'x.3.mp3')) + path = util.unique_path(os.path.join(self.base, b'x.mp3')) + self.assertEqual(path, os.path.join(self.base, b'x.3.mp3')) def test_conflicting_file_with_number_increases_number(self): - path = util.unique_path(os.path.join(self.base, 'x.1.mp3')) - self.assertEqual(path, os.path.join(self.base, 'x.3.mp3')) + path = util.unique_path(os.path.join(self.base, b'x.1.mp3')) + self.assertEqual(path, os.path.join(self.base, b'x.3.mp3')) class MkDirAllTest(_common.TestCase): def test_parent_exists(self): - path = os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + path = os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') util.mkdirall(path) self.assertTrue(os.path.isdir( - os.path.join(self.temp_dir, 'foo', 'bar', 'baz') + os.path.join(self.temp_dir, b'foo', b'bar', b'baz') )) def test_child_does_not_exist(self): - path = os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + path = os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') util.mkdirall(path) self.assertTrue(not os.path.exists( - os.path.join(self.temp_dir, 'foo', 'bar', 'baz', 'qux.mp3') + os.path.join(self.temp_dir, b'foo', b'bar', b'baz', b'qux.mp3') )) diff --git a/test/test_importadded.py b/test/test_importadded.py index 80491aa0a..474f56384 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -127,7 +127,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): for item_path, added_after in items_added_after.iteritems(): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + - item_path) + util.displayable_path(item_path)) def test_import_singletons_with_added_dates(self): self.config['import']['singletons'] = True @@ -165,7 +165,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): for item_path, added_after in items_added_after.iteritems(): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + - item_path) + util.displayable_path(item_path)) def suite(): diff --git a/test/test_importer.py b/test/test_importer.py index 73d1ceb1d..93a034ee6 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -30,7 +30,7 @@ from mock import patch from test import _common from test._common import unittest -from beets.util import displayable_path +from beets.util import displayable_path, bytestring_path from test.helper import TestImportSession, TestHelper, has_program, capture_log from beets import importer from beets.importer import albums_in_dir @@ -169,14 +169,14 @@ class ImportHelper(TestHelper): :param count: Number of files to create """ - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - album_path = os.path.join(self.import_dir, 'the_album') + album_path = os.path.join(self.import_dir, b'the_album') os.makedirs(album_path) - resource_path = os.path.join(_common.RSRC, 'full.mp3') + resource_path = os.path.join(_common.RSRC, b'full.mp3') metadata = { 'artist': u'Tag Artist', @@ -189,7 +189,10 @@ class ImportHelper(TestHelper): self.media_files = [] for i in range(count): # Copy files - medium_path = os.path.join(album_path, 'track_%d.mp3' % (i + 1)) + medium_path = os.path.join( + album_path, + bytestring_path('track_%d.mp3' % (i + 1)) + ) shutil.copy(resource_path, medium_path) medium = MediaFile(medium_path) @@ -256,8 +259,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_threaded_import_copy_arrives(self): config['threaded'] = True @@ -265,8 +268,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_import_with_move_deletes_import_files(self): config['import']['move'] = True @@ -280,19 +283,19 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def test_import_with_move_prunes_directory_empty(self): config['import']['move'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) def test_import_with_move_prunes_with_extra_clutter(self): - f = open(os.path.join(self.import_dir, 'the_album', 'alog.log'), 'w') + f = open(os.path.join(self.import_dir, b'the_album', b'alog.log'), 'w') f.close() config['clutter'] = ['*.log'] config['import']['move'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) def test_threaded_import_move_arrives(self): config['import']['move'] = True @@ -301,8 +304,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): self.importer.run() for mediafile in self.import_media: self.assert_file_in_lib( - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title - ) + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title))) def test_threaded_import_move_deletes_import(self): config['import']['move'] = True @@ -327,9 +330,9 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def test_import_with_delete_prunes_directory_empty(self): config['import']['delete'] = True - self.assertExists(os.path.join(self.import_dir, 'the_album')) + self.assertExists(os.path.join(self.import_dir, b'the_album')) self.importer.run() - self.assertNotExists(os.path.join(self.import_dir, 'the_album')) + self.assertNotExists(os.path.join(self.import_dir, b'the_album')) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_import_link_arrives(self): @@ -338,7 +341,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): for mediafile in self.import_media: filename = os.path.join( self.libdir, - 'Tag Artist', 'Tag Album', '%s.mp3' % mediafile.title + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title)) ) self.assertExists(filename) self.assertTrue(os.path.islink(filename)) @@ -460,7 +464,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('singletons', 'Tag Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Tag Title 1.mp3') def test_apply_candidate_adds_track(self): self.assertEqual(self.lib.items().get(), None) @@ -479,7 +483,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assert_file_in_lib('singletons', u'Applied Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Applied Title 1.mp3') def test_skip_does_not_add_first_track(self): self.importer.add_choice(importer.action.SKIP) @@ -494,12 +498,12 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 1) def test_import_single_files(self): - resource_path = os.path.join(_common.RSRC, u'empty.mp3') - single_path = os.path.join(self.import_dir, u'track_2.mp3') + resource_path = os.path.join(_common.RSRC, b'empty.mp3') + single_path = os.path.join(self.import_dir, b'track_2.mp3') shutil.copy(resource_path, single_path) import_files = [ - os.path.join(self.import_dir, u'the_album'), + os.path.join(self.import_dir, b'the_album'), single_path ] self._setup_import_session(singletons=False) @@ -545,7 +549,8 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('Tag Artist', 'Tag Album', 'Tag Title 1.mp3') + self.assert_file_in_lib( + b'Tag Artist', b'Tag Album', b'Tag Title 1.mp3') def test_apply_candidate_adds_album(self): self.assertEqual(self.lib.albums().get(), None) @@ -567,13 +572,13 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.run() self.assert_file_in_lib( - 'Applied Artist', 'Applied Album', 'Applied Title 1.mp3' - ) + b'Applied Artist', b'Applied Album', b'Applied Title 1.mp3') def test_apply_with_move_deletes_import(self): config['import']['move'] = True - import_file = os.path.join(self.import_dir, 'the_album', 'track_1.mp3') + import_file = os.path.join( + self.import_dir, b'the_album', b'track_1.mp3') self.assertExists(import_file) self.importer.add_choice(importer.action.APPLY) @@ -583,7 +588,8 @@ class ImportTest(_common.TestCase, ImportHelper): def test_apply_with_delete_deletes_import(self): config['import']['delete'] = True - import_file = os.path.join(self.import_dir, 'the_album', 'track_1.mp3') + import_file = os.path.join(self.import_dir, + b'the_album', b'track_1.mp3') self.assertExists(import_file) self.importer.add_choice(importer.action.APPLY) @@ -597,8 +603,8 @@ class ImportTest(_common.TestCase, ImportHelper): def test_skip_non_album_dirs(self): self.assertTrue(os.path.isdir( - os.path.join(self.import_dir, 'the_album'))) - self.touch('cruft', dir=self.import_dir) + os.path.join(self.import_dir, b'the_album'))) + self.touch(b'cruft', dir=self.import_dir) self.importer.add_choice(importer.action.APPLY) self.importer.run() self.assertEqual(len(self.lib.albums()), 1) @@ -611,8 +617,8 @@ class ImportTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 1) def test_empty_directory_warning(self): - import_dir = os.path.join(self.temp_dir, 'empty') - self.touch('non-audio', dir=import_dir) + import_dir = os.path.join(self.temp_dir, b'empty') + self.touch(b'non-audio', dir=import_dir) self._setup_import_session(import_dir=import_dir) with capture_log() as logs: self.importer.run() @@ -621,8 +627,8 @@ class ImportTest(_common.TestCase, ImportHelper): self.assertIn(u'No files imported from {0}'.format(import_dir), logs) def test_empty_directory_singleton_warning(self): - import_dir = os.path.join(self.temp_dir, 'empty') - self.touch('non-audio', dir=import_dir) + import_dir = os.path.join(self.temp_dir, b'empty') + self.touch(b'non-audio', dir=import_dir) self._setup_import_session(import_dir=import_dir, singletons=True) with capture_log() as logs: self.importer.run() @@ -671,7 +677,7 @@ class ImportTracksTest(_common.TestCase, ImportHelper): self.importer.add_choice(importer.action.APPLY) self.importer.add_choice(importer.action.APPLY) self.importer.run() - self.assert_file_in_lib('singletons', 'Applied Title 1.mp3') + self.assert_file_in_lib(b'singletons', b'Applied Title 1.mp3') class ImportCompilationTest(_common.TestCase, ImportHelper): @@ -809,14 +815,14 @@ class ImportExistingTest(_common.TestCase, ImportHelper): medium.title = u'New Title' medium.save() - old_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + old_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(old_path) self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_in_lib('Applied Artist', 'Applied Album', - 'New Title.mp3') + self.assert_file_in_lib(b'Applied Artist', b'Applied Album', + b'New Title.mp3') self.assert_file_not_in_lib(old_path) def test_asis_updated_without_copy_does_not_move_file(self): @@ -825,15 +831,15 @@ class ImportExistingTest(_common.TestCase, ImportHelper): medium.title = u'New Title' medium.save() - old_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + old_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(old_path) config['import']['copy'] = False self.importer.add_choice(importer.action.ASIS) self.importer.run() - self.assert_file_not_in_lib('Applied Artist', 'Applied Album', - 'New Title.mp3') + self.assert_file_not_in_lib(b'Applied Artist', b'Applied Album', + b'New Title.mp3') self.assert_file_in_lib(old_path) def test_outside_file_is_copied(self): @@ -846,8 +852,8 @@ class ImportExistingTest(_common.TestCase, ImportHelper): self._setup_import_session() self.importer.add_choice(importer.action.APPLY) self.importer.run() - new_path = os.path.join('Applied Artist', 'Applied Album', - 'Applied Title 1.mp3') + new_path = os.path.join(b'Applied Artist', b'Applied Album', + b'Applied Title 1.mp3') self.assert_file_in_lib(new_path) self.assert_equal_path(self.lib.items().get().path, @@ -1122,7 +1128,7 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, # Imported item has the same artist and album as the one in the # library. import_file = os.path.join(self.importer.paths[0], - 'album 0', 'track 0.mp3') + b'album 0', b'track 0.mp3') import_file = MediaFile(import_file) import_file.artist = item['artist'] import_file.albumartist = item['artist'] @@ -1351,7 +1357,7 @@ class IncrementalImportTest(unittest.TestCase, TestHelper): def _mkmp3(path): - shutil.copyfile(os.path.join(_common.RSRC, 'min.mp3'), path) + shutil.copyfile(os.path.join(_common.RSRC, b'min.mp3'), path) class AlbumsInDirTest(_common.TestCase): @@ -1359,20 +1365,20 @@ class AlbumsInDirTest(_common.TestCase): super(AlbumsInDirTest, self).setUp() # create a directory structure for testing - self.base = os.path.abspath(os.path.join(self.temp_dir, 'tempdir')) + self.base = os.path.abspath(os.path.join(self.temp_dir, b'tempdir')) os.mkdir(self.base) - os.mkdir(os.path.join(self.base, 'album1')) - os.mkdir(os.path.join(self.base, 'album2')) - os.mkdir(os.path.join(self.base, 'more')) - os.mkdir(os.path.join(self.base, 'more', 'album3')) - os.mkdir(os.path.join(self.base, 'more', 'album4')) + os.mkdir(os.path.join(self.base, b'album1')) + os.mkdir(os.path.join(self.base, b'album2')) + os.mkdir(os.path.join(self.base, b'more')) + os.mkdir(os.path.join(self.base, b'more', b'album3')) + os.mkdir(os.path.join(self.base, b'more', b'album4')) - _mkmp3(os.path.join(self.base, 'album1', 'album1song1.mp3')) - _mkmp3(os.path.join(self.base, 'album1', 'album1song2.mp3')) - _mkmp3(os.path.join(self.base, 'album2', 'album2song.mp3')) - _mkmp3(os.path.join(self.base, 'more', 'album3', 'album3song.mp3')) - _mkmp3(os.path.join(self.base, 'more', 'album4', 'album4song.mp3')) + _mkmp3(os.path.join(self.base, b'album1', b'album1song1.mp3')) + _mkmp3(os.path.join(self.base, b'album1', b'album1song2.mp3')) + _mkmp3(os.path.join(self.base, b'album2', b'album2song.mp3')) + _mkmp3(os.path.join(self.base, b'more', b'album3', b'album3song.mp3')) + _mkmp3(os.path.join(self.base, b'more', b'album4', b'album4song.mp3')) def test_finds_all_albums(self): albums = list(albums_in_dir(self.base)) @@ -1381,16 +1387,16 @@ class AlbumsInDirTest(_common.TestCase): def test_separates_contents(self): found = [] for _, album in albums_in_dir(self.base): - found.append(re.search(r'album(.)song', album[0]).group(1)) - self.assertTrue('1' in found) - self.assertTrue('2' in found) - self.assertTrue('3' in found) - self.assertTrue('4' in found) + found.append(re.search(br'album(.)song', album[0]).group(1)) + self.assertTrue(b'1' in found) + self.assertTrue(b'2' in found) + self.assertTrue(b'3' in found) + self.assertTrue(b'4' in found) def test_finds_multiple_songs(self): for _, album in albums_in_dir(self.base): - n = re.search(r'album(.)song', album[0]).group(1) - if n == '1': + n = re.search(br'album(.)song', album[0]).group(1) + if n == b'1': self.assertEqual(len(album), 2) else: self.assertEqual(len(album), 1) @@ -1600,7 +1606,7 @@ class ReimportTest(unittest.TestCase, ImportHelper, _common.Assertions): def test_reimported_item_preserves_art(self): self._setup_session() - art_source = os.path.join(_common.RSRC, 'abbey.jpg') + art_source = os.path.join(_common.RSRC, b'abbey.jpg') replaced_album = self._album() replaced_album.set_art(art_source) replaced_album.store() @@ -1638,21 +1644,21 @@ class ImportPretendTest(_common.TestCase, ImportHelper): def __create_import_dir(self): self._create_import_dir(1) - resource_path = os.path.join(_common.RSRC, u'empty.mp3') - single_path = os.path.join(self.import_dir, u'track_2.mp3') + resource_path = os.path.join(_common.RSRC, b'empty.mp3') + single_path = os.path.join(self.import_dir, b'track_2.mp3') shutil.copy(resource_path, single_path) self.import_paths = [ - os.path.join(self.import_dir, u'the_album'), + os.path.join(self.import_dir, b'the_album'), single_path ] self.import_files = [ displayable_path( - os.path.join(self.import_paths[0], u'track_1.mp3')), + os.path.join(self.import_paths[0], b'track_1.mp3')), displayable_path(single_path) ] def __create_empty_import_dir(self): - path = os.path.join(self.temp_dir, 'empty') + path = os.path.join(self.temp_dir, b'empty') os.makedirs(path) self.empty_path = path diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 1c2972000..61f10dc92 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -17,6 +17,7 @@ from __future__ import division, absolute_import, print_function from mock import patch from beets import library +from beets.util import bytestring_path from beetsplug.ipfs import IPFSPlugin from test import _common @@ -53,6 +54,7 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): want_path = '/ipfs/{0}/{1}'.format(test_album.ipfs, os.path.basename( want_item.path)) + want_path = bytestring_path(want_path) self.assertEqual(check_item.path, want_path) self.assertEqual(check_item.ipfs, want_item.ipfs) self.assertEqual(check_item.title, want_item.title) diff --git a/test/test_library.py b/test/test_library.py index 3afe3c0dd..19b987d58 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -36,7 +36,7 @@ from beets import util from beets import plugins from beets import config from beets.mediafile import MediaFile -from beets.util import syspath +from beets.util import syspath, bytestring_path from test.helper import TestHelper # Shortcut to path normalization. @@ -96,7 +96,7 @@ class AddTest(_common.TestCase): def test_library_add_path_inserts_row(self): i = beets.library.Item.from_path( - os.path.join(_common.RSRC, 'full.mp3') + os.path.join(_common.RSRC, b'full.mp3') ) self.lib.add(i) new_grouping = self.lib._connection().execute( @@ -148,17 +148,17 @@ class DestinationTest(_common.TestCase): config.read(user=False, defaults=True) def test_directory_works_with_trailing_slash(self): - self.lib.directory = 'one/' + self.lib.directory = b'one/' self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_directory_works_without_trailing_slash(self): - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [(u'default', u'two')] self.assertEqual(self.i.destination(), np('one/two')) def test_destination_substitues_metadata_values(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.path_formats = [(u'default', u'$album/$artist $title')] self.i.title = 'three' self.i.artist = 'two' @@ -167,21 +167,21 @@ class DestinationTest(_common.TestCase): np('base/one/two three')) def test_destination_preserves_extension(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.audioformat' self.assertEqual(self.i.destination(), np('base/the title.audioformat')) def test_lower_case_extension(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.path_formats = [(u'default', u'$title')] self.i.path = 'hey.MP3' self.assertEqual(self.i.destination(), np('base/the title.mp3')) def test_destination_pads_some_indices(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.path_formats = [(u'default', u'$track $tracktotal $disc $disctotal $bpm')] self.i.track = 1 @@ -193,7 +193,7 @@ class DestinationTest(_common.TestCase): np('base/01 02 03 04 5')) def test_destination_pads_date_values(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.path_formats = [(u'default', u'$year-$month-$day')] self.i.year = 1 self.i.month = 2 @@ -204,21 +204,21 @@ class DestinationTest(_common.TestCase): def test_destination_escapes_slashes(self): self.i.album = 'one/two' dest = self.i.destination() - self.assertTrue('one' in dest) - self.assertTrue('two' in dest) - self.assertFalse('one/two' in dest) + self.assertTrue(b'one' in dest) + self.assertTrue(b'two' in dest) + self.assertFalse(b'one/two' in dest) def test_destination_escapes_leading_dot(self): self.i.album = '.something' dest = self.i.destination() - self.assertTrue('something' in dest) - self.assertFalse('/.' in dest) + self.assertTrue(b'something' in dest) + self.assertFalse(b'/.' in dest) def test_destination_preserves_legitimate_slashes(self): self.i.artist = 'one' self.i.album = 'two' dest = self.i.destination() - self.assertTrue(os.path.join('one', 'two') in dest) + self.assertTrue(os.path.join(b'one', b'two') in dest) def test_destination_long_names_truncated(self): self.i.title = u'X' * 300 @@ -228,23 +228,23 @@ class DestinationTest(_common.TestCase): def test_destination_long_names_keep_extension(self): self.i.title = u'X' * 300 - self.i.path = 'something.extn' + self.i.path = b'something.extn' dest = self.i.destination() - self.assertEqual(dest[-5:], '.extn') + self.assertEqual(dest[-5:], b'.extn') def test_distination_windows_removes_both_separators(self): self.i.title = 'one \\ two / three.mp3' with _common.platform_windows(): p = self.i.destination() - self.assertFalse('one \\ two' in p) - self.assertFalse('one / two' in p) - self.assertFalse('two \\ three' in p) - self.assertFalse('two / three' in p) + self.assertFalse(b'one \\ two' in p) + self.assertFalse(b'one / two' in p) + self.assertFalse(b'two \\ three' in p) + self.assertFalse(b'two / three' in p) def test_path_with_format(self): self.lib.path_formats = [(u'default', u'$artist/$album ($format)')] p = self.i.destination() - self.assertTrue('(FLAC)' in p) + self.assertTrue(b'(FLAC)' in p) def test_heterogeneous_album_gets_single_directory(self): i1, i2 = item(), item() @@ -257,14 +257,14 @@ class DestinationTest(_common.TestCase): def test_default_path_for_non_compilations(self): self.i.comp = False self.lib.add_album([self.i]) - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [(u'default', u'two'), (u'comp:true', u'three')] self.assertEqual(self.i.destination(), np('one/two')) def test_singleton_path(self): i = item(self.lib) - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ (u'default', u'two'), (u'singleton:true', u'four'), @@ -275,7 +275,7 @@ class DestinationTest(_common.TestCase): def test_comp_before_singleton_path(self): i = item(self.lib) i.comp = True - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ (u'default', u'two'), (u'comp:true', u'three'), @@ -286,7 +286,7 @@ class DestinationTest(_common.TestCase): def test_comp_path(self): self.i.comp = True self.lib.add_album([self.i]) - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ (u'default', u'two'), (u'comp:true', u'three'), @@ -297,7 +297,7 @@ class DestinationTest(_common.TestCase): self.i.comp = True self.lib.add_album([self.i]) self.i.albumtype = u'sometype' - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ (u'default', u'two'), (u'albumtype:sometype', u'four'), @@ -309,7 +309,7 @@ class DestinationTest(_common.TestCase): self.i.comp = True self.lib.add_album([self.i]) self.i.albumtype = u'sometype' - self.lib.directory = 'one' + self.lib.directory = b'one' self.lib.path_formats = [ (u'default', u'two'), (u'albumtype:anothertype', u'four'), @@ -416,13 +416,13 @@ class DestinationTest(_common.TestCase): def test_asciify_and_replace(self): config['asciify_paths'] = True self.lib.replacements = [(re.compile(u'"'), u'q')] - self.lib.directory = 'lib' + self.lib.directory = b'lib' self.lib.path_formats = [(u'default', u'$title')] self.i.title = u'\u201c\u00f6\u2014\u00cf\u201d' self.assertEqual(self.i.destination(), np('lib/qo--Iq')) def test_destination_with_replacements(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'a'), u'e')] self.lib.path_formats = [(u'default', u'$album/$title')] self.i.title = u'foo' @@ -432,7 +432,7 @@ class DestinationTest(_common.TestCase): @unittest.skip('unimplemented: #359') def test_destination_with_empty_component(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] self.lib.path_formats = [(u'default', u'$album/$artist/$title')] self.i.title = u'three' @@ -444,7 +444,7 @@ class DestinationTest(_common.TestCase): @unittest.skip('unimplemented: #359') def test_destination_with_empty_final_component(self): - self.lib.directory = 'base' + self.lib.directory = b'base' self.lib.replacements = [(re.compile(r'^$'), u'_')] self.lib.path_formats = [(u'default', u'$album/$title')] self.i.title = u'' @@ -466,7 +466,7 @@ class DestinationTest(_common.TestCase): # The final path should reflect the replacement. dest = self.i.destination() - self.assertEqual(dest[-2:], u'XZ') + self.assertEqual(dest[-2:], b'XZ') def test_legalize_path_one_for_many_replacement(self): # Use a replacement that should always replace the last X in any @@ -482,7 +482,7 @@ class DestinationTest(_common.TestCase): # The final path should ignore the user replacement and create a path # of the correct length, containing Xs. dest = self.i.destination() - self.assertEqual(dest[-2:], u'XX') + self.assertEqual(dest[-2:], b'XX') class ItemFormattedMappingTest(_common.LibTestCase): @@ -561,7 +561,7 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): def setUp(self): super(DestinationFunctionTest, self).setUp() self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' + self.lib.directory = b'/base' self.lib.path_formats = [(u'default', u'path')] self.i = item(self.lib) @@ -571,98 +571,98 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): def test_upper_case_literal(self): self._setf(u'%upper{foo}') - self._assert_dest('/base/FOO') + self._assert_dest(b'/base/FOO') def test_upper_case_variable(self): self._setf(u'%upper{$title}') - self._assert_dest('/base/THE TITLE') + self._assert_dest(b'/base/THE TITLE') def test_title_case_variable(self): self._setf(u'%title{$title}') - self._assert_dest('/base/The Title') + self._assert_dest(b'/base/The Title') def test_left_variable(self): self._setf(u'%left{$title, 3}') - self._assert_dest('/base/the') + self._assert_dest(b'/base/the') def test_right_variable(self): self._setf(u'%right{$title,3}') - self._assert_dest('/base/tle') + self._assert_dest(b'/base/tle') def test_if_false(self): self._setf(u'x%if{,foo}') - self._assert_dest('/base/x') + self._assert_dest(b'/base/x') def test_if_false_value(self): self._setf(u'x%if{false,foo}') - self._assert_dest('/base/x') + self._assert_dest(b'/base/x') def test_if_true(self): self._setf(u'%if{bar,foo}') - self._assert_dest('/base/foo') + self._assert_dest(b'/base/foo') def test_if_else_false(self): self._setf(u'%if{,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_if_else_false_value(self): self._setf(u'%if{false,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_if_int_value(self): self._setf(u'%if{0,foo,baz}') - self._assert_dest('/base/baz') + self._assert_dest(b'/base/baz') def test_nonexistent_function(self): self._setf(u'%foo{bar}') - self._assert_dest('/base/%foo{bar}') + self._assert_dest(b'/base/%foo{bar}') def test_if_def_field_return_self(self): self.i.bar = 3 self._setf(u'%ifdef{bar}') - self._assert_dest('/base/3') + self._assert_dest(b'/base/3') def test_if_def_field_not_defined(self): self._setf(u' %ifdef{bar}/$artist') - self._assert_dest('/base/the artist') + self._assert_dest(b'/base/the artist') def test_if_def_field_not_defined_2(self): self._setf(u'$artist/%ifdef{bar}') - self._assert_dest('/base/the artist') + self._assert_dest(b'/base/the artist') def test_if_def_true(self): self._setf(u'%ifdef{artist,cool}') - self._assert_dest('/base/cool') + self._assert_dest(b'/base/cool') def test_if_def_true_complete(self): self.i.series = "Now" self._setf(u'%ifdef{series,$series Series,Albums}/$album') - self._assert_dest('/base/Now Series/the album') + self._assert_dest(b'/base/Now Series/the album') def test_if_def_false_complete(self): self._setf(u'%ifdef{plays,$plays,not_played}') - self._assert_dest('/base/not_played') + self._assert_dest(b'/base/not_played') def test_first(self): self.i.genres = "Pop; Rock; Classical Crossover" self._setf(u'%first{$genres}') - self._assert_dest('/base/Pop') + self._assert_dest(b'/base/Pop') def test_first_skip(self): self.i.genres = "Pop; Rock; Classical Crossover" self._setf(u'%first{$genres,1,2}') - self._assert_dest('/base/Classical Crossover') + self._assert_dest(b'/base/Classical Crossover') def test_first_different_sep(self): self._setf(u'%first{Alice / Bob / Eve,2,0, / , & }') - self._assert_dest('/base/Alice & Bob') + self._assert_dest(b'/base/Alice & Bob') class DisambiguationTest(_common.TestCase, PathFormattingMixin): def setUp(self): super(DisambiguationTest, self).setUp() self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' + self.lib.directory = b'/base' self.lib.path_formats = [(u'default', u'path')] self.i1 = item() @@ -680,33 +680,33 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self.lib._connection().close() def test_unique_expands_to_disambiguating_year(self): - self._assert_dest('/base/foo [2001]/the title', self.i1) + self._assert_dest(b'/base/foo [2001]/the title', self.i1) def test_unique_with_default_arguments_uses_albumtype(self): album2 = self.lib.get_album(self.i1) album2.albumtype = u'bar' album2.store() self._setf(u'foo%aunique{}/$title') - self._assert_dest('/base/foo [bar]/the title', self.i1) + self._assert_dest(b'/base/foo [bar]/the title', self.i1) def test_unique_expands_to_nothing_for_distinct_albums(self): album2 = self.lib.get_album(self.i2) album2.album = u'different album' album2.store() - self._assert_dest('/base/foo/the title', self.i1) + self._assert_dest(b'/base/foo/the title', self.i1) def test_use_fallback_numbers_when_identical(self): album2 = self.lib.get_album(self.i2) album2.year = 2001 album2.store() - self._assert_dest('/base/foo 1/the title', self.i1) - self._assert_dest('/base/foo 2/the title', self.i2) + self._assert_dest(b'/base/foo 1/the title', self.i1) + self._assert_dest(b'/base/foo 2/the title', self.i2) def test_unique_falls_back_to_second_distinguishing_field(self): self._setf(u'foo%aunique{albumartist album,month year}/$title') - self._assert_dest('/base/foo [2001]/the title', self.i1) + self._assert_dest(b'/base/foo [2001]/the title', self.i1) def test_unique_sanitized(self): album2 = self.lib.get_album(self.i2) @@ -716,7 +716,7 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): album2.store() album1.store() self._setf(u'foo%aunique{albumartist album,albumtype}/$title') - self._assert_dest('/base/foo [foo_bar]/the title', self.i1) + self._assert_dest(b'/base/foo [foo_bar]/the title', self.i1) class PluginDestinationTest(_common.TestCase): @@ -736,7 +736,7 @@ class PluginDestinationTest(_common.TestCase): plugins.item_field_getters = field_getters self.lib = beets.library.Library(':memory:') - self.lib.directory = '/base' + self.lib.directory = b'/base' self.lib.path_formats = [(u'default', u'$artist $foo')] self.i = item(self.lib) @@ -747,28 +747,28 @@ class PluginDestinationTest(_common.TestCase): def _assert_dest(self, dest): with _common.platform_posix(): the_dest = self.i.destination() - self.assertEqual(the_dest, '/base/' + dest) + self.assertEqual(the_dest, b'/base/' + dest) def test_undefined_value_not_substituted(self): - self._assert_dest(u'the artist $foo') + self._assert_dest(b'the artist $foo') def test_plugin_value_not_substituted(self): self._tv_map = { 'foo': 'bar', } - self._assert_dest(u'the artist bar') + self._assert_dest(b'the artist bar') def test_plugin_value_overrides_attribute(self): self._tv_map = { 'artist': 'bar', } - self._assert_dest(u'bar $foo') + self._assert_dest(b'bar $foo') def test_plugin_value_sanitized(self): self._tv_map = { 'foo': 'bar/baz', } - self._assert_dest(u'the artist bar_baz') + self._assert_dest(b'the artist bar_baz') class AlbumInfoTest(_common.TestCase): @@ -790,7 +790,7 @@ class AlbumInfoTest(_common.TestCase): ai.artpath = '/my/great/art' ai.store() new_ai = self.lib.get_album(self.i) - self.assertEqual(new_ai.artpath, '/my/great/art') + self.assertEqual(new_ai.artpath, b'/my/great/art') def test_albuminfo_for_two_items_doesnt_duplicate_row(self): i2 = item(self.lib) @@ -883,7 +883,8 @@ class ArtDestinationTest(_common.TestCase): def test_art_filename_respects_setting(self): art = self.ai.art_destination('something.jpg') - self.assertTrue('%sartimage.jpg' % util.PATH_SEP in art) + new_art = bytestring_path('%sartimage.jpg' % os.path.sep) + self.assertTrue(new_art in art) def test_art_path_in_item_dir(self): art = self.ai.art_destination('something.jpg') @@ -893,7 +894,7 @@ class ArtDestinationTest(_common.TestCase): def test_art_path_sanitized(self): config['art_filename'] = u'artXimage' art = self.ai.art_destination('something.jpg') - self.assertTrue('artYimage' in art) + self.assertTrue(b'artYimage' in art) class PathStringTest(_common.TestCase): @@ -983,8 +984,8 @@ class PathStringTest(_common.TestCase): class MtimeTest(_common.TestCase): def setUp(self): super(MtimeTest, self).setUp() - self.ipath = os.path.join(self.temp_dir, 'testfile.mp3') - shutil.copy(os.path.join(_common.RSRC, 'full.mp3'), self.ipath) + self.ipath = os.path.join(self.temp_dir, b'testfile.mp3') + shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.ipath) self.i = beets.library.Item.from_path(self.ipath) self.lib = beets.library.Library(':memory:') self.lib.add(self.i) @@ -1079,7 +1080,7 @@ class WriteTest(unittest.TestCase, TestHelper): def test_write_nonexistant(self): item = self.create_item() - item.path = '/path/does/not/exist' + item.path = b'/path/does/not/exist' with self.assertRaises(beets.library.ReadError): item.write() @@ -1097,7 +1098,7 @@ class WriteTest(unittest.TestCase, TestHelper): def test_write_with_custom_path(self): item = self.add_item_fixture() - custom_path = os.path.join(self.temp_dir, 'custom.mp3') + custom_path = os.path.join(self.temp_dir, b'custom.mp3') shutil.copy(syspath(item.path), syspath(custom_path)) item['artist'] = 'new artist' @@ -1126,7 +1127,7 @@ class WriteTest(unittest.TestCase, TestHelper): class ItemReadTest(unittest.TestCase): def test_unreadable_raise_read_error(self): - unreadable = os.path.join(_common.RSRC, 'image-2x3.png') + unreadable = os.path.join(_common.RSRC, b'image-2x3.png') item = beets.library.Item() with self.assertRaises(beets.library.ReadError) as cm: item.read(unreadable) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 0ee93ef42..8e8d0a2bf 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -40,7 +40,8 @@ class ArtTestMixin(object): @property def png_data(self): if not self._png_data: - with open(os.path.join(_common.RSRC, 'image-2x3.png'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.png') + with open(image_file, 'rb') as f: self._png_data = f.read() return self._png_data _png_data = None @@ -48,7 +49,8 @@ class ArtTestMixin(object): @property def jpg_data(self): if not self._jpg_data: - with open(os.path.join(_common.RSRC, 'image-2x3.jpg'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.jpg') + with open(image_file, 'rb') as f: self._jpg_data = f.read() return self._jpg_data _jpg_data = None @@ -56,7 +58,8 @@ class ArtTestMixin(object): @property def tiff_data(self): if not self._jpg_data: - with open(os.path.join(_common.RSRC, 'image-2x3.tiff'), 'rb') as f: + image_file = os.path.join(_common.RSRC, b'image-2x3.tiff') + with open(image_file, 'rb') as f: self._jpg_data = f.read() return self._jpg_data _jpg_data = None @@ -931,13 +934,13 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): class MediaFieldTest(unittest.TestCase): def test_properties_from_fields(self): - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') mediafile = MediaFile(path) for field in MediaFile.fields(): self.assertTrue(hasattr(mediafile, field)) def test_properties_from_readable_fields(self): - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') mediafile = MediaFile(path) for field in MediaFile.readable_fields(): self.assertTrue(hasattr(mediafile, field)) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index bf86e7f2a..26d88ae74 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -23,6 +23,8 @@ import shutil from test import _common from test._common import unittest from test.helper import TestHelper + +from beets.util import bytestring_path import beets.mediafile @@ -35,7 +37,7 @@ class EdgeTest(unittest.TestCase): # This is very hard to produce, so this is just the first 8192 # bytes of a file found "in the wild". emptylist = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 'emptylist.mp3') + os.path.join(_common.RSRC, b'emptylist.mp3') ) genre = emptylist.genre self.assertEqual(genre, None) @@ -44,7 +46,7 @@ class EdgeTest(unittest.TestCase): # Ensures that release times delimited by spaces are ignored. # Amie Street produces such files. space_time = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 'space_time.mp3') + os.path.join(_common.RSRC, b'space_time.mp3') ) self.assertEqual(space_time.year, 2009) self.assertEqual(space_time.month, 9) @@ -54,7 +56,7 @@ class EdgeTest(unittest.TestCase): # Ensures that release times delimited by Ts are ignored. # The iTunes Store produces such files. t_time = beets.mediafile.MediaFile( - os.path.join(_common.RSRC, 't_time.m4a') + os.path.join(_common.RSRC, b't_time.m4a') ) self.assertEqual(t_time.year, 1987) self.assertEqual(t_time.month, 3) @@ -63,19 +65,20 @@ class EdgeTest(unittest.TestCase): def test_tempo_with_bpm(self): # Some files have a string like "128 BPM" in the tempo field # rather than just a number. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'bpm.mp3')) + f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, b'bpm.mp3')) self.assertEqual(f.bpm, 128) def test_discc_alternate_field(self): # Different taggers use different vorbis comments to reflect # the disc and disc count fields: ensure that the alternative # style works. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'discc.ogg')) + f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, b'discc.ogg')) self.assertEqual(f.disc, 4) self.assertEqual(f.disctotal, 5) def test_old_ape_version_bitrate(self): - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, 'oldape.ape')) + media_file = os.path.join(_common.RSRC, b'oldape.ape') + f = beets.mediafile.MediaFile(media_file) self.assertEqual(f.bitrate, 0) def test_only_magic_bytes_jpeg(self): @@ -83,7 +86,7 @@ class EdgeTest(unittest.TestCase): # such aren't recognized by imghdr. Ensure that this still works thanks # to our own follow up mimetype detection based on # https://github.com/file/file/blob/master/magic/Magdir/jpeg#L12 - f = open(os.path.join(_common.RSRC, 'only-magic-bytes.jpg'), 'rb') + f = open(os.path.join(_common.RSRC, b'only-magic-bytes.jpg'), 'rb') jpg_data = f.read() self.assertEqual( beets.mediafile._image_mime_type(jpg_data), @@ -93,7 +96,7 @@ class EdgeTest(unittest.TestCase): # Make sure we don't crash when the iTunes SoundCheck field contains # non-ASCII binary data. f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, - 'soundcheck-nonascii.m4a')) + b'soundcheck-nonascii.m4a')) self.assertEqual(f.rg_track_gain, 0.0) @@ -159,34 +162,34 @@ class SafetyTest(unittest.TestCase, TestHelper): def test_corrupt_mp3_raises_unreadablefileerror(self): # Make sure we catch Mutagen reading errors appropriately. - self._exccheck('corrupt.mp3', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.mp3', beets.mediafile.UnreadableFileError) def test_corrupt_mp4_raises_unreadablefileerror(self): - self._exccheck('corrupt.m4a', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.m4a', beets.mediafile.UnreadableFileError) def test_corrupt_flac_raises_unreadablefileerror(self): - self._exccheck('corrupt.flac', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.flac', beets.mediafile.UnreadableFileError) def test_corrupt_ogg_raises_unreadablefileerror(self): - self._exccheck('corrupt.ogg', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ogg', beets.mediafile.UnreadableFileError) def test_invalid_ogg_header_raises_unreadablefileerror(self): - self._exccheck('corrupt.ogg', beets.mediafile.UnreadableFileError, + self._exccheck(b'corrupt.ogg', beets.mediafile.UnreadableFileError, 'OggS\x01vorbis') def test_corrupt_monkeys_raises_unreadablefileerror(self): - self._exccheck('corrupt.ape', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ape', beets.mediafile.UnreadableFileError) def test_invalid_extension_raises_filetypeerror(self): - self._exccheck('something.unknown', beets.mediafile.FileTypeError) + self._exccheck(b'something.unknown', beets.mediafile.FileTypeError) def test_magic_xml_raises_unreadablefileerror(self): - self._exccheck('nothing.xml', beets.mediafile.UnreadableFileError, + self._exccheck(b'nothing.xml', beets.mediafile.UnreadableFileError, "ftyp") @unittest.skipIf(not hasattr(os, 'symlink'), u'platform lacks symlink') def test_broken_symlink(self): - fn = os.path.join(_common.RSRC, 'brokenlink') + fn = os.path.join(_common.RSRC, b'brokenlink') os.symlink('does_not_exist', fn) try: self.assertRaises(IOError, @@ -197,7 +200,7 @@ class SafetyTest(unittest.TestCase, TestHelper): class SideEffectsTest(unittest.TestCase): def setUp(self): - self.empty = os.path.join(_common.RSRC, 'empty.mp3') + self.empty = os.path.join(_common.RSRC, b'empty.mp3') def test_opening_tagless_file_leaves_untouched(self): old_mtime = os.stat(self.empty).st_mtime @@ -209,8 +212,8 @@ class SideEffectsTest(unittest.TestCase): class MP4EncodingTest(unittest.TestCase, TestHelper): def setUp(self): self.create_temp_dir() - src = os.path.join(_common.RSRC, 'full.m4a') - self.path = os.path.join(self.temp_dir, 'test.m4a') + src = os.path.join(_common.RSRC, b'full.m4a') + self.path = os.path.join(self.temp_dir, b'test.m4a') shutil.copy(src, self.path) self.mf = beets.mediafile.MediaFile(self.path) @@ -228,8 +231,8 @@ class MP4EncodingTest(unittest.TestCase, TestHelper): class MP3EncodingTest(unittest.TestCase, TestHelper): def setUp(self): self.create_temp_dir() - src = os.path.join(_common.RSRC, 'full.mp3') - self.path = os.path.join(self.temp_dir, 'test.mp3') + src = os.path.join(_common.RSRC, b'full.mp3') + self.path = os.path.join(self.temp_dir, b'test.mp3') shutil.copy(src, self.path) self.mf = beets.mediafile.MediaFile(self.path) @@ -254,7 +257,7 @@ class ZeroLengthMediaFile(beets.mediafile.MediaFile): class MissingAudioDataTest(unittest.TestCase): def setUp(self): super(MissingAudioDataTest, self).setUp() - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') self.mf = ZeroLengthMediaFile(path) def test_bitrate_with_zero_length(self): @@ -265,7 +268,7 @@ class MissingAudioDataTest(unittest.TestCase): class TypeTest(unittest.TestCase): def setUp(self): super(TypeTest, self).setUp() - path = os.path.join(_common.RSRC, 'full.mp3') + path = os.path.join(_common.RSRC, b'full.mp3') self.mf = beets.mediafile.MediaFile(path) def test_year_integer_in_string(self): @@ -331,8 +334,10 @@ class SoundCheckTest(unittest.TestCase): class ID3v23Test(unittest.TestCase, TestHelper): def _make_test(self, ext='mp3', id3v23=False): self.create_temp_dir() - src = os.path.join(_common.RSRC, 'full.{0}'.format(ext)) - self.path = os.path.join(self.temp_dir, 'test.{0}'.format(ext)) + src = os.path.join(_common.RSRC, + bytestring_path('full.{0}'.format(ext))) + self.path = os.path.join(self.temp_dir, + bytestring_path('test.{0}'.format(ext))) shutil.copy(src, self.path) return beets.mediafile.MediaFile(self.path, id3v23=id3v23) diff --git a/test/test_play.py b/test/test_play.py index cd0f4211c..469377c75 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -71,7 +71,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' - path = os.path.relpath(self.item.path, '/something') + path = os.path.relpath(self.item.path, b'/something') playlist = path.decode('utf8') self.do_test(expected_cmd='echo', expected_playlist=playlist) diff --git a/test/test_plugins.py b/test/test_plugins.py index f02a55cf1..d45e317ca 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -26,7 +26,7 @@ from beets import plugins, config, ui from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile -from beets.util import displayable_path +from beets.util import displayable_path, bytestring_path from test.test_importer import ImportHelper, AutotagStub from test.test_ui_importer import TerminalImportSessionSetup @@ -177,7 +177,7 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): def __copy_file(self, dest_path, metadata): # Copy files - resource_path = os.path.join(RSRC, 'full.mp3') + resource_path = os.path.join(RSRC, b'full.mp3') shutil.copy(resource_path, dest_path) medium = MediaFile(dest_path) # Set metadata @@ -186,11 +186,11 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): medium.save() def __create_import_dir(self, count): - self.import_dir = os.path.join(self.temp_dir, 'testsrcdir') + self.import_dir = os.path.join(self.temp_dir, b'testsrcdir') if os.path.isdir(self.import_dir): shutil.rmtree(self.import_dir) - self.album_path = os.path.join(self.import_dir, 'album') + self.album_path = os.path.join(self.import_dir, b'album') os.makedirs(self.album_path) metadata = { @@ -205,8 +205,8 @@ class EventsTest(unittest.TestCase, ImportHelper, TestHelper): for i in range(count): metadata['track'] = i + 1 metadata['title'] = u'Tag Title Album %d' % (i + 1) - dest_path = os.path.join(self.album_path, - '%02d - track.mp3' % (i + 1)) + track_file = bytestring_path('%02d - track.mp3' % (i + 1)) + dest_path = os.path.join(self.album_path, track_file) self.__copy_file(dest_path, metadata) self.file_paths.append(dest_path) diff --git a/test/test_query.py b/test/test_query.py index 4595cf827..2f8014015 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -492,7 +492,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, [u'path album']) def test_escape_underscore(self): - self.add_album(path='/a/_/title.mp3', title=u'with underscore', + self.add_album(path=b'/a/_/title.mp3', title=u'with underscore', album=u'album with underscore') q = u'path:/a/_' results = self.lib.items(q) @@ -502,7 +502,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, [u'album with underscore']) def test_escape_percent(self): - self.add_album(path='/a/%/title.mp3', title=u'with percent', + self.add_album(path=b'/a/%/title.mp3', title=u'with percent', album=u'album with percent') q = u'path:/a/%' results = self.lib.items(q) @@ -512,7 +512,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, [u'album with percent']) def test_escape_backslash(self): - self.add_album(path=r'/a/\x/title.mp3', title=u'with backslash', + self.add_album(path=br'/a/\x/title.mp3', title=u'with backslash', album=u'album with backslash') q = u'path:/a/\\\\x' results = self.lib.items(q) @@ -522,7 +522,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assert_albums_matched(results, [u'album with backslash']) def test_case_sensitivity(self): - self.add_album(path='/A/B/C2.mp3', title=u'caps path') + self.add_album(path=b'/A/B/C2.mp3', title=u'caps path') makeq = partial(beets.library.PathQuery, u'path', '/A/B') @@ -615,7 +615,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): is_path = beets.library.PathQuery.is_path_query try: - self.touch(os.path.join('foo', 'bar')) + self.touch(os.path.join(b'foo', b'bar')) # Temporarily change directory so relative paths work. cur_dir = os.getcwd() diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index e1ce36951..dd8d7ca36 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -149,7 +149,7 @@ class SmartPlaylistTest(unittest.TestCase): def test_playlist_update(self): spl = SmartPlaylistPlugin() - i = Mock(path='/tagada.mp3') + i = Mock(path=b'/tagada.mp3') i.evaluate_template.side_effect = lambda x, _: x q = Mock() a_q = Mock() diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index f3e2858ad..06dd0a8e9 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -23,6 +23,7 @@ from shutil import rmtree from test._common import unittest from test.helper import TestHelper +from beets.util import bytestring_path from beetsplug.thumbnails import (ThumbnailsPlugin, NORMAL_DIR, LARGE_DIR, write_metadata_im, write_metadata_pil, PathlibURI, GioURI) @@ -183,7 +184,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): @patch('beetsplug.thumbnails.ThumbnailsPlugin._check_local_ok') def test_make_dolphin_cover_thumbnail(self, _): plugin = ThumbnailsPlugin() - tmp = mkdtemp() + tmp = bytestring_path(mkdtemp()) album = Mock(path=tmp, artpath=os.path.join(tmp, b"cover.jpg")) plugin.make_dolphin_cover_thumbnail(album) diff --git a/test/test_ui.py b/test/test_ui.py index 7c46afc2f..0ca4f7115 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -123,12 +123,13 @@ class RemoveTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) # Copy a file into the library. self.lib = library.Library(':memory:', self.libdir) - self.i = library.Item.from_path(os.path.join(_common.RSRC, 'full.mp3')) + item_path = os.path.join(_common.RSRC, b'full.mp3') + self.i = library.Item.from_path(item_path) self.lib.add(self.i) self.i.move(True) @@ -411,11 +412,11 @@ class MoveTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) - self.itempath = os.path.join(self.libdir, 'srcfile') - shutil.copy(os.path.join(_common.RSRC, 'full.mp3'), self.itempath) + self.itempath = os.path.join(self.libdir, b'srcfile') + shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.itempath) # Add a file to the library but don't copy it in yet. self.lib = library.Library(':memory:', self.libdir) @@ -424,7 +425,7 @@ class MoveTest(_common.TestCase): self.album = self.lib.add_album([self.i]) # Alternate destination directory. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def _move(self, query=(), dest=None, copy=False, album=False, pretend=False): @@ -433,54 +434,54 @@ class MoveTest(_common.TestCase): def test_move_item(self): self._move() self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_copy_item(self): self._move(copy=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertExists(self.itempath) def test_move_album(self): self._move(album=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_copy_album(self): self._move(copy=True, album=True) self.i.load() - self.assertTrue('testlibdir' in self.i.path) + self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertExists(self.itempath) def test_move_item_custom_dir(self): self._move(dest=self.otherdir) self.i.load() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_move_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() - self.assertTrue('testotherdir' in self.i.path) + self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) def test_pretend_move_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() - self.assertIn('srcfile', self.i.path) + self.assertIn(b'srcfile', self.i.path) def test_pretend_move_album(self): self._move(album=True, pretend=True) self.i.load() - self.assertIn('srcfile', self.i.path) + self.assertIn(b'srcfile', self.i.path) class UpdateTest(_common.TestCase): @@ -489,17 +490,18 @@ class UpdateTest(_common.TestCase): self.io.install() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') # Copy a file into the library. self.lib = library.Library(':memory:', self.libdir) - self.i = library.Item.from_path(os.path.join(_common.RSRC, 'full.mp3')) + item_path = os.path.join(_common.RSRC, b'full.mp3') + self.i = library.Item.from_path(item_path) self.lib.add(self.i) self.i.move(True) self.album = self.lib.add_album([self.i]) # Album art. - artfile = os.path.join(self.temp_dir, 'testart.jpg') + artfile = os.path.join(self.temp_dir, b'testart.jpg') _common.touch(artfile) self.album.set_art(artfile) self.album.store() @@ -545,7 +547,7 @@ class UpdateTest(_common.TestCase): mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue(u'differentTitle' in item.path) + self.assertTrue(b'differentTitle' in item.path) def test_modified_metadata_not_moved(self): mf = MediaFile(self.i.path) @@ -553,7 +555,7 @@ class UpdateTest(_common.TestCase): mf.save() self._update(move=False) item = self.lib.items().get() - self.assertTrue(u'differentTitle' not in item.path) + self.assertTrue(b'differentTitle' not in item.path) def test_modified_album_metadata_moved(self): mf = MediaFile(self.i.path) @@ -561,7 +563,7 @@ class UpdateTest(_common.TestCase): mf.save() self._update(move=True) item = self.lib.items().get() - self.assertTrue(u'differentAlbum' in item.path) + self.assertTrue(b'differentAlbum' in item.path) def test_modified_album_metadata_art_moved(self): artpath = self.album.artpath @@ -758,7 +760,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements - self.assertEqual(replacements, [(re.compile(ur'[xy]'), b'z')]) + self.assertEqual(replacements, [(re.compile(ur'[xy]'), 'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: @@ -988,7 +990,7 @@ class ShowChangeTest(_common.TestCase): self.items = [_common.item()] self.items[0].track = 1 - self.items[0].path = '/path/to/file.mp3' + self.items[0].path = b'/path/to/file.mp3' self.info = autotag.AlbumInfo( u'the album', u'album id', u'the artist', u'artist id', [ autotag.TrackInfo(u'the title', u'track id', index=1) @@ -1143,7 +1145,7 @@ class CompletionTest(_common.TestCase): tester.stdin.writelines(completion_script) # Load test suite. - test_script = os.path.join(_common.RSRC, 'test_completion.sh') + test_script = os.path.join(_common.RSRC, b'test_completion.sh') with open(test_script, 'r') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() @@ -1160,7 +1162,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): self.setup_beets() self.lib = library.Library(':memory:') self.item = _common.item() - self.item.path = 'xxx/yyy' + self.item.path = b'xxx/yyy' self.lib.add(self.item) self.lib.add_album([self.item]) diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index 29da4f456..5cd1131eb 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -33,16 +33,16 @@ class QueryTest(_common.TestCase): def setUp(self): super(QueryTest, self).setUp() - self.libdir = os.path.join(self.temp_dir, 'testlibdir') + self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) # Add a file to the library but don't copy it in yet. self.lib = library.Library(':memory:', self.libdir) # Alternate destination directory. - self.otherdir = os.path.join(self.temp_dir, 'testotherdir') + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') - def add_item(self, filename='srcfile', templatefile='full.mp3'): + def add_item(self, filename=b'srcfile', templatefile=b'full.mp3'): itempath = os.path.join(self.libdir, filename) shutil.copy(os.path.join(_common.RSRC, templatefile), itempath) item = library.Item.from_path(itempath) From 622945e2a944d0b55d68d6be10e6dd6c6cec095d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 00:28:00 -0400 Subject: [PATCH 0933/2280] wrap importer match keys in list() since we need one --- beets/importer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index b190329ce..a785b23a5 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -499,7 +499,7 @@ class ImportTask(BaseImportTask): if self.choice_flag in (action.ASIS, action.RETAG): return list(self.items) elif self.choice_flag == action.APPLY: - return self.match.mapping.keys() + return list(self.match.mapping.keys()) else: assert False From 0f4b907ff5b22399c5000e3eb5eeb3f8855eee10 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 00:28:46 -0400 Subject: [PATCH 0934/2280] wrap filter()s in a list() in replaygain plugin --- beetsplug/replaygain.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 2e215938d..c58a1db9b 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -286,7 +286,7 @@ class CommandBackend(Backend): """Computes the track gain of the given tracks, returns a list of TrackGain objects. """ - supported_items = filter(self.format_supported, items) + supported_items = list(filter(self.format_supported, items)) output = self.compute_gain(supported_items, False) return output @@ -297,7 +297,7 @@ class CommandBackend(Backend): # TODO: What should be done when not all tracks in the album are # supported? - supported_items = filter(self.format_supported, album.items()) + supported_items = list(filter(self.format_supported, album.items())) if len(supported_items) != len(album.items()): self._log.debug(u'tracks are of unsupported format') return AlbumGain(None, []) From 8fa71f78feb4e09c46079e881f2f2e2c8686ef3d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 00:44:43 -0400 Subject: [PATCH 0935/2280] decode bytes from .encode() in lyrics plugin --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index aa526c870..1bce066c9 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -503,7 +503,7 @@ class Google(Backend): try: text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') - text = unicode(re.sub('[-\s]+', ' ', text)) + text = unicode(re.sub('[-\s]+', ' ', text.decode('utf-8'))) except UnicodeDecodeError: self._log.exception(u"Failing to normalize '{0}'", text) return text From 3112a18463eef4e946c95feb81f9be3f99b04cc5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 00:51:12 -0400 Subject: [PATCH 0936/2280] treat ctypes .value as bytes in thumbnails plugin --- beetsplug/thumbnails.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 0e7fbc6e0..d6d4ff356 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -232,7 +232,7 @@ def copy_c_string(c_string): # work. A more surefire way would be to allocate a ctypes buffer and copy # the data with `memcpy` or somesuch. s = ctypes.cast(c_string, ctypes.c_char_p).value - return '' + s + return b'' + s class GioURI(URIGetter): From ef727854f1f0c2b489ba0f4ea4154aab8d620ad8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 01:28:13 -0400 Subject: [PATCH 0937/2280] treat default perms as str in permission plugin tests --- test/test_permissions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index 4f5d05747..0d78a7c1b 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -21,8 +21,8 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): self.load_plugins('permissions') self.config['permissions'] = { - 'file': 777, - 'dir': 777} + 'file': '777', + 'dir': '777'} def tearDown(self): self.teardown_beets() From ebff5a599ceab606d9c451f9ea9751f7ab5abdf6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 01:29:35 -0400 Subject: [PATCH 0938/2280] treat filenames as bytestrings in perm plugin tests --- test/test_permissions.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/test_permissions.py b/test/test_permissions.py index 0d78a7c1b..c6b1837b4 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -45,14 +45,16 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): def get_stat(v): return os.stat( - os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777 + os.path.join(self.temp_dir, b'import', *v)).st_mode & 0o777 self.importer = self.create_importer() typs = ['file', 'dir'] + + track_file = (b'album 0', b'track 0.mp3') self.exp_perms = { True: {k: convert_perm(self.config['permissions'][k].get()) for k in typs}, - False: {k: get_stat(v) - for (k, v) in zip(typs, (('album 0', 'track 0.mp3'), ()))}} + False: {k: get_stat(v) for (k, v) in zip(typs, (track_file, ()))} + } self.importer.run() item = self.lib.items().get() From 4b2c4ced6ce1f8323a6403736154d447cb8d12ea Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 01:55:47 -0400 Subject: [PATCH 0939/2280] wrap extra_ops.keys() in a list in ui/commands --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 75cae066c..d2270c662 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -754,7 +754,7 @@ class TerminalImportSession(importer.ImportSession): _, _, candidates, rec = autotag.tag_album( task.items, search_ids=search_id.split() ) - elif choice in extra_ops.keys(): + elif choice in list(extra_ops.keys()): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) if isinstance(post_choice, importer.action): From 4413e2ed94bb2ab9e89c6aa3c9942793b9feb62f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 02:01:41 -0400 Subject: [PATCH 0940/2280] make Distance a hashable object It previously was hashable, until we added `__eq__`, so we must now do it explicitly --- beets/autotag/hooks.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 92a7b8e29..0d9030b2c 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -356,6 +356,9 @@ class Distance(object): key=lambda key_and_dist: (-key_and_dist[1], key_and_dist[0]) ) + def __hash__(self): + return id(self) + def __eq__(self, other): return self.distance == other From 0a5c6ce4c0f234005f7c5f60bd39bc0886201ed1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 03:38:21 -0400 Subject: [PATCH 0941/2280] open tempfile in edit plugin in text mode --- beetsplug/edit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 5c7796ee8..c8522849d 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -242,7 +242,7 @@ class EditPlugin(plugins.BeetsPlugin): old_data = [flatten(o, fields) for o in objs] # Set up a temporary file with the initial data for editing. - new = NamedTemporaryFile(suffix='.yaml', delete=False) + new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) old_str = dump(old_data) new.write(old_str) new.close() From 8e1bc1622821f479cec269293983270f3a721cea Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 03:47:59 -0400 Subject: [PATCH 0942/2280] set default perms as strings in perms plugin itself I originally changed them to octal in my py3 branch, but they are gonna end up as strings anyways, so I figured we should just use them that way by default. --- beetsplug/permissions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 0de8978c0..cf06a96d5 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -45,8 +45,8 @@ class Permissions(BeetsPlugin): # Adding defaults. self.config.add({ - u'file': 644, - u'dir': 755 + u'file': '644', + u'dir': '755' }) self.register_listener('item_imported', permissions) From 44380db6e8dc6ed5e656b00444b6171accd90562 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 03:50:29 -0400 Subject: [PATCH 0943/2280] If the permission is an int, then simply return it It doesn't seem necessary to convert it, and if it does, then we're missing a test --- beetsplug/permissions.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index cf06a96d5..b2c5e7fb0 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -16,11 +16,10 @@ from beets.util import ancestry def convert_perm(perm): - """If the perm is a int it will first convert it to a string and back - to an oct int. Else it just converts it to oct. + """If the perm is a int then just return it, otherwise convert it to oct. """ if isinstance(perm, int): - return int(bytes(perm), 8) + return perm else: return int(perm, 8) From ba2cfcd32944f7d6d1b4a9af2350948efb54750e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 04:32:54 -0400 Subject: [PATCH 0944/2280] bytestringify subdir paths in importer.albums_in_dir --- beets/importer.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/importer.py b/beets/importer.py index a785b23a5..4209a4831 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1494,6 +1494,7 @@ def albums_in_dir(path): start_collapsing = True subdir_pat = None for subdir in dirs: + subdir = util.bytestring_path(subdir) # The first directory dictates the pattern for # the remaining directories. if not subdir_pat: From a1314b7bda29dd532f0efc435fd0524b9e19294c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 21:48:41 -0400 Subject: [PATCH 0945/2280] move spotify test json to json files --- test/rsrc/spotify/missing_request.json | 11 +++ test/rsrc/spotify/track_request.json | 89 ++++++++++++++++++ test/test_spotify.py | 125 +++---------------------- 3 files changed, 114 insertions(+), 111 deletions(-) create mode 100644 test/rsrc/spotify/missing_request.json create mode 100644 test/rsrc/spotify/track_request.json diff --git a/test/rsrc/spotify/missing_request.json b/test/rsrc/spotify/missing_request.json new file mode 100644 index 000000000..b18ceb859 --- /dev/null +++ b/test/rsrc/spotify/missing_request.json @@ -0,0 +1,11 @@ +{ + "tracks" : { + "href" : "https://api.spotify.com/v1/search?query=duifhjslkef+album%3Alkajsdflakjsd+artist%3A&offset=0&limit=20&type=track", + "items" : [ ], + "limit" : 20, + "next" : null, + "offset" : 0, + "previous" : null, + "total" : 0 + } +} \ No newline at end of file diff --git a/test/rsrc/spotify/track_request.json b/test/rsrc/spotify/track_request.json new file mode 100644 index 000000000..5d6fb252e --- /dev/null +++ b/test/rsrc/spotify/track_request.json @@ -0,0 +1,89 @@ +{ + "tracks":{ + "href":"https://api.spotify.com/v1/search?query=Happy+album%3ADespicable+Me+2+artist%3APharrell+Williams&offset=0&limit=20&type=track", + "items":[ + { + "album":{ + "album_type":"compilation", + "available_markets":[ + "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", + "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", + "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", + "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", + "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", + "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", + "SK", "SV", "TR", "TW", "US", "UY" + ], + "external_urls":{ + "spotify":"https://open.spotify.com/album/5l3zEmMrOhOzG8d8s83GOL" + }, + "href":"https://api.spotify.com/v1/albums/5l3zEmMrOhOzG8d8s83GOL", + "id":"5l3zEmMrOhOzG8d8s83GOL", + "images":[ + { + "height":640, + "width":640, + "url":"https://i.scdn.co/image/cb7905340c132365bbaee3f17498f062858382e8" + }, + { + "height":300, + "width":300, + "url":"https://i.scdn.co/image/af369120f0b20099d6784ab31c88256113f10ffb" + }, + { + "height":64, + "width":64, + "url":"https://i.scdn.co/image/9dad385ddf2e7db0bef20cec1fcbdb08689d9ae8" + } + ], + "name":"Despicable Me 2 (Original Motion Picture Soundtrack)", + "type":"album", + "uri":"spotify:album:5l3zEmMrOhOzG8d8s83GOL" + }, + "artists":[ + { + "external_urls":{ + "spotify":"https://open.spotify.com/artist/2RdwBSPQiwcmiDo9kixcl8" + }, + "href":"https://api.spotify.com/v1/artists/2RdwBSPQiwcmiDo9kixcl8", + "id":"2RdwBSPQiwcmiDo9kixcl8", + "name":"Pharrell Williams", + "type":"artist", + "uri":"spotify:artist:2RdwBSPQiwcmiDo9kixcl8" + } + ], + "available_markets":[ + "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", + "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", + "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", + "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", + "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", + "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", + "SK", "SV", "TR", "TW", "US", "UY" + ], + "disc_number":1, + "duration_ms":233305, + "explicit":false, + "external_ids":{ + "isrc":"USQ4E1300686" + }, + "external_urls":{ + "spotify":"https://open.spotify.com/track/6NPVjNh8Jhru9xOmyQigds" + }, + "href":"https://api.spotify.com/v1/tracks/6NPVjNh8Jhru9xOmyQigds", + "id":"6NPVjNh8Jhru9xOmyQigds", + "name":"Happy", + "popularity":89, + "preview_url":"https://p.scdn.co/mp3-preview/6b00000be293e6b25f61c33e206a0c522b5cbc87", + "track_number":4, + "type":"track", + "uri":"spotify:track:6NPVjNh8Jhru9xOmyQigds" + } + ], + "limit":20, + "next":null, + "offset":0, + "previous":null, + "total":1 + } +} diff --git a/test/test_spotify.py b/test/test_spotify.py index 104497600..721d4f953 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -4,8 +4,10 @@ from __future__ import division, absolute_import, print_function -from test import _common +import os import responses + +from test import _common from test._common import unittest from beets import config from beets.library import Item @@ -49,20 +51,11 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): @responses.activate def test_missing_request(self): - response_body = bytes( - '{' - '"tracks" : {' - '"href" : "https://api.spotify.com/v1/search?query=duifhjslkef' - '+album%3Alkajsdflakjsd+artist%3A&offset=0&limit=20&type=track",' - '"items" : [ ],' - '"limit" : 20,' - '"next" : null,' - '"offset" : 0,' - '"previous" : null,' - '"total" : 0' - '}' - '}' - ) + json_file = os.path.join(_common.RSRC, b'spotify', + b'missing_request.json') + with open(json_file, 'rb') as f: + response_body = f.read() + responses.add(responses.GET, 'https://api.spotify.com/v1/search', body=response_body, status=200, content_type='application/json') @@ -85,102 +78,12 @@ class SpotifyPluginTest(_common.TestCase, TestHelper): @responses.activate def test_track_request(self): - response_body = bytes( - '{' - '"tracks" : {' - '"href" : "https://api.spotify.com/v1/search?query=Happy+album%3A' - 'Despicable+Me+2+artist%3APharrell+Williams&offset=0&limit=20' - '&type=track",' - '"items" : [ {' - '"album" : {' - '"album_type" : "compilation",' - '"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG",' - '"BO", "BR", "CA", "CH", "CL", "CO",' - '"CR", "CY", "CZ", "DE", "DK", "DO",' - '"EC", "EE", "ES", "FI", "FR", "GB",' - '"GR", "GT", "HK", "HN", "HU", "IE",' - '"IS", "IT", "LI", "LT", "LU", "LV",' - '"MC", "MT", "MX", "MY", "NI", "NL",' - '"NO", "NZ", "PA", "PE", "PH", "PL",' - '"PT", "PY", "RO", "SE", "SG", "SI",' - '"SK", "SV", "TR", "TW", "US", "UY" ],' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/album/' - '5l3zEmMrOhOzG8d8s83GOL"' - '},' - '"href" : "https://api.spotify.com/v1/albums/' - '5l3zEmMrOhOzG8d8s83GOL",' - '"id" : "5l3zEmMrOhOzG8d8s83GOL",' - '"images" : [ {' - '"height" : 640,' - '"url" : "https://i.scdn.co/image/cb7905340c132365bb' - 'aee3f17498f062858382e8",' - '"width" : 640' - '}, {' - '"height" : 300,' - '"url" : "https://i.scdn.co/image/af369120f0b20099' - 'd6784ab31c88256113f10ffb",' - '"width" : 300' - '}, {' - '"height" : 64,' - '"url" : "https://i.scdn.co/image/' - '9dad385ddf2e7db0bef20cec1fcbdb08689d9ae8",' - '"width" : 64' - '} ],' - '"name" : "Despicable Me 2 (Original Motion Picture Soundtrack)",' - '"type" : "album",' - '"uri" : "spotify:album:5l3zEmMrOhOzG8d8s83GOL"' - '},' - '"artists" : [ {' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/artist/' - '2RdwBSPQiwcmiDo9kixcl8"' - '},' - '"href" : "https://api.spotify.com/v1/artists/' - '2RdwBSPQiwcmiDo9kixcl8",' - '"id" : "2RdwBSPQiwcmiDo9kixcl8",' - '"name" : "Pharrell Williams",' - '"type" : "artist",' - '"uri" : "spotify:artist:2RdwBSPQiwcmiDo9kixcl8"' - '} ],' - '"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO",' - '"BR", "CA", "CH", "CL", "CO", "CR", "CY",' - '"CZ", "DE", "DK", "DO", "EC", "EE", "ES",' - '"FI", "FR", "GB", "GR", "GT", "HK", "HN",' - '"HU", "IE", "IS", "IT", "LI", "LT", "LU",' - '"LV", "MC", "MT", "MX", "MY", "NI", "NL",' - '"NO", "NZ", "PA", "PE", "PH", "PL", "PT",' - '"PY", "RO", "SE", "SG", "SI", "SK", "SV",' - '"TR", "TW", "US", "UY" ],' - '"disc_number" : 1,' - '"duration_ms" : 233305,' - '"explicit" : false,' - '"external_ids" : {' - '"isrc" : "USQ4E1300686"' - '},' - '"external_urls" : {' - '"spotify" : "https://open.spotify.com/track/' - '6NPVjNh8Jhru9xOmyQigds"' - '},' - '"href" : "https://api.spotify.com/v1/tracks/' - '6NPVjNh8Jhru9xOmyQigds",' - '"id" : "6NPVjNh8Jhru9xOmyQigds",' - '"name" : "Happy",' - '"popularity" : 89,' - '"preview_url" : "https://p.scdn.co/mp3-preview/' - '6b00000be293e6b25f61c33e206a0c522b5cbc87",' - '"track_number" : 4,' - '"type" : "track",' - '"uri" : "spotify:track:6NPVjNh8Jhru9xOmyQigds"' - '} ],' - '"limit" : 20,' - '"next" : null,' - '"offset" : 0,' - '"previous" : null,' - '"total" : 1' - '}' - '}' - ) + + json_file = os.path.join(_common.RSRC, b'spotify', + b'track_request.json') + with open(json_file, 'rb') as f: + response_body = f.read() + responses.add(responses.GET, 'https://api.spotify.com/v1/search', body=response_body, status=200, content_type='application/json') From 4fbad7dd67d2f4ac4ff42574b4d8a27270764d22 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 23:12:20 -0400 Subject: [PATCH 0946/2280] bytestringify path in file_filter --- beetsplug/filefilter.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index 72b5ea9ea..d3537a535 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function import re from beets import config +from beets import util from beets.plugins import BeetsPlugin from beets.importer import SingletonImportTask @@ -69,6 +70,7 @@ class FileFilterPlugin(BeetsPlugin): of the file given in full_path. """ import_config = dict(config['import']) + full_path = util.bytestring_path(full_path) if 'singletons' not in import_config or not import_config[ 'singletons']: # Album From be942c45957722dabf05623b6481a94178c64d7e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 00:07:52 -0400 Subject: [PATCH 0947/2280] complete more bytestrings in test_embedart --- test/test_embedart.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 2bb357001..2f47e8f25 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -45,10 +45,10 @@ def require_artresizer_compare(test): class EmbedartCliTest(_common.TestCase, TestHelper): - small_artpath = os.path.join(_common.RSRC, 'image-2x3.jpg') - abbey_artpath = os.path.join(_common.RSRC, 'abbey.jpg') - abbey_similarpath = os.path.join(_common.RSRC, 'abbey-similar.jpg') - abbey_differentpath = os.path.join(_common.RSRC, 'abbey-different.jpg') + small_artpath = os.path.join(_common.RSRC, b'image-2x3.jpg') + abbey_artpath = os.path.join(_common.RSRC, b'abbey.jpg') + abbey_similarpath = os.path.join(_common.RSRC, b'abbey-similar.jpg') + abbey_differentpath = os.path.join(_common.RSRC, b'abbey-different.jpg') def setUp(self): self.setup_beets() # Converter is threaded From 038593764722cfb171424eeff085af5338f550e4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 14 Jun 2016 23:51:15 -0400 Subject: [PATCH 0948/2280] complete more bytestrings in test_art --- test/test_art.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_art.py b/test/test_art.py index 348835c4c..f88f2f1cf 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -113,7 +113,7 @@ class FSArtTest(UseThePlugin): next(self.source.get(None, self.extra)) def test_precedence_amongst_correct_files(self): - images = ['front-cover.jpg', 'front.jpg', 'back.jpg'] + images = [b'front-cover.jpg', b'front.jpg', b'back.jpg'] paths = [os.path.join(self.dpath, i) for i in images] for p in paths: _common.touch(p) From 7df59d5e305d8725d8313d669799d424c9afa3e5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 01:12:28 -0400 Subject: [PATCH 0949/2280] catch codecs hex encoding errors too (from binascii) binascii is used internally by codecs, and I didn't initially know that --- beets/mediafile.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index f55c9e821..1251cee26 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -49,6 +49,7 @@ import codecs import datetime import re import base64 +import binascii import math import struct import imghdr @@ -225,7 +226,7 @@ def _sc_decode(soundcheck): try: soundcheck = codecs.decode(soundcheck.replace(b' ', b''), 'hex') soundcheck = struct.unpack('!iiiiiiiiii', soundcheck) - except (struct.error, TypeError): + except (struct.error, TypeError, binascii.Error): # SoundCheck isn't in the format we expect, so return default # values. return 0.0, 0.0 From a02a1f0201ddf5b644d74f9498ff1dce54c0a1af Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 03:34:03 -0400 Subject: [PATCH 0950/2280] cast year ints to str, not bytes in bucket plugin This seems to work equally well in py2/3 --- beetsplug/bucket.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index 21acb1f1e..7ce0d0d43 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -137,9 +137,10 @@ def str2fmt(s): def format_span(fmt, yearfrom, yearto, fromnchars, tonchars): """Return a span string representation. """ - args = (bytes(yearfrom)[-fromnchars:]) + args = (str(yearfrom)[-fromnchars:]) if tonchars: - args = (bytes(yearfrom)[-fromnchars:], bytes(yearto)[-tonchars:]) + args = (str(yearfrom)[-fromnchars:], str(yearto)[-tonchars:]) + return fmt % args From 7c7720185713113b178fe74ecdec29f6410d14e0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 04:13:11 -0400 Subject: [PATCH 0951/2280] bytestringify clutter/ignore paths in utils/__init__ --- beets/util/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 1ead27583..9bd4ca529 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -158,8 +158,9 @@ def sorted_walk(path, ignore=(), ignore_hidden=False, logger=None): pattern in `ignore` are skipped. If `logger` is provided, then warning messages are logged there when a directory cannot be listed. """ - # Make sure the path isn't a Unicode string. + # Make sure the pathes aren't Unicode strings. path = bytestring_path(path) + ignore = [bytestring_path(i) for i in ignore] # Get all the directories and files at this level. try: @@ -264,6 +265,7 @@ def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')): if not os.path.exists(directory): # Directory gone already. continue + clutter = [bytestring_path(c) for c in clutter] if fnmatch_all(os.listdir(directory), clutter): # Directory contains only clutter (or nothing). try: From cb549554856083c1a59246274d00931b350f77d0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 23:54:53 -0400 Subject: [PATCH 0952/2280] more bytecasting in smartplaylist plugin --- beetsplug/smartplaylist.py | 7 +++++-- test/test_smartplaylist.py | 12 ++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 98092952e..1ccb37030 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -20,7 +20,7 @@ from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui -from beets.util import mkdirall, normpath, syspath +from beets.util import mkdirall, normpath, syspath, bytestring_path from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import MultipleSort, ParsingError @@ -165,6 +165,7 @@ class SmartPlaylistPlugin(BeetsPlugin): len(self._matched_playlists)) playlist_dir = self.config['playlist_dir'].as_filename() + playlist_dir = bytestring_path(playlist_dir) relative_to = self.config['relative_to'].get() if relative_to: relative_to = normpath(relative_to) @@ -194,9 +195,11 @@ class SmartPlaylistPlugin(BeetsPlugin): m3us[m3u_name].append(item_path) # Now iterate through the m3us that we need to generate for m3u in m3us: - m3u_path = normpath(os.path.join(playlist_dir, m3u)) + m3u_path = normpath(os.path.join(playlist_dir, + bytestring_path(m3u))) mkdirall(m3u_path) with open(syspath(m3u_path), 'wb') as f: for path in m3us[m3u]: f.write(path + b'\n') + self._log.info(u"{0} playlists updated", len(self._matched_playlists)) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index dd8d7ca36..2f0f261d7 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -25,7 +25,7 @@ from beetsplug.smartplaylist import SmartPlaylistPlugin from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import NullSort, MultipleSort, FixedFieldSort -from beets.util import syspath +from beets.util import syspath, bytestring_path from beets.ui import UserError from beets import config @@ -156,10 +156,10 @@ class SmartPlaylistTest(unittest.TestCase): lib = Mock() lib.items.return_value = [i] lib.albums.return_value = [] - pl = 'my_playlist.m3u', (q, None), (a_q, None) + pl = b'my_playlist.m3u', (q, None), (a_q, None) spl._matched_playlists = [pl] - dir = mkdtemp() + dir = bytestring_path(mkdtemp()) config['smartplaylist']['relative_to'] = False config['smartplaylist']['playlist_dir'] = dir try: @@ -177,7 +177,7 @@ class SmartPlaylistTest(unittest.TestCase): content = f.read() rmtree(dir) - self.assertEqual(content, "/tagada.mp3\n") + self.assertEqual(content, b'/tagada.mp3\n') class SmartPlaylistCLITest(unittest.TestCase, TestHelper): @@ -203,7 +203,7 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): self.run_with_output(u'splupdate', u'tagada') self.run_with_output(u'splupdate', u'my_playlist') - m3u_path = path.join(self.temp_dir, 'my_playlist.m3u') + m3u_path = path.join(self.temp_dir, b'my_playlist.m3u') self.assertTrue(path.exists(m3u_path)) with open(m3u_path, 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") @@ -215,7 +215,7 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): remove(m3u_path) self.run_with_output(u'splupdate') - for name in (u'my_playlist.m3u', u'all.m3u'): + for name in (b'my_playlist.m3u', b'all.m3u'): with open(path.join(self.temp_dir, name), 'rb') as f: self.assertEqual(f.read(), self.item.path + b"\n") From 167544bcbee48e97213b327ab9a7ceb721845dbb Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 02:43:01 -0400 Subject: [PATCH 0953/2280] add F405 to flake8 ignore list --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 32d3e06ad..79e453fbc 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,6 +9,7 @@ min-version=2.7 # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) # - E731: do not assign a lambda expression, use a def +# - F405 object may be undefined, or defined from star imports # - C901: function/method complexity # `flake8-future-import` errors we ignore: # - FI50: `__future__` import "division" present @@ -17,4 +18,4 @@ min-version=2.7 # - FI53: `__future__` import "print_function" present # - FI14: `__future__` import "unicode_literals" missing # - FI15: `__future__` import "generator_stop" missing -ignore=C901,E241,E221,E731,FI50,FI51,FI12,FI53,FI14,FI15 +ignore=C901,E241,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 From 4e5ac89b2a5055118db8c2d1a4606124f2198024 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 15 Jun 2016 04:14:01 -0400 Subject: [PATCH 0954/2280] bytstringify path in _mediafile_fixture --- test/test_mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 8e8d0a2bf..12f41d9a7 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -678,7 +678,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, self.fail('\n '.join(errors)) def _mediafile_fixture(self, name): - name = name + '.' + self.extension + name = bytestring_path(name + '.' + self.extension) src = os.path.join(_common.RSRC, name) target = os.path.join(self.temp_dir, name) shutil.copy(src, target) From fd01faa241db90e749149848e3ee81a48b088295 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 04:02:19 -0400 Subject: [PATCH 0955/2280] add missing bytestring_path import :( --- test/test_mediafile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 12f41d9a7..180249d91 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -31,6 +31,7 @@ from beets.mediafile import MediaFile, MediaField, Image, \ ASFStorageStyle, ImageType, CoverArtField from beets.library import Item from beets.plugins import BeetsPlugin +from beets.util import bytestring_path class ArtTestMixin(object): From d3d52da012706433bba0726df6149c7ea95c79e2 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 04:08:28 -0400 Subject: [PATCH 0956/2280] bytestringify paths in filefilter plugin --- beetsplug/filefilter.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/beetsplug/filefilter.py b/beetsplug/filefilter.py index d3537a535..23dac5746 100644 --- a/beetsplug/filefilter.py +++ b/beetsplug/filefilter.py @@ -20,7 +20,7 @@ from __future__ import division, absolute_import, print_function import re from beets import config -from beets import util +from beets.util import bytestring_path from beets.plugins import BeetsPlugin from beets.importer import SingletonImportTask @@ -36,14 +36,15 @@ class FileFilterPlugin(BeetsPlugin): self.path_album_regex = \ self.path_singleton_regex = \ - re.compile(self.config['path'].get()) + re.compile(bytestring_path(self.config['path'].get())) if 'album_path' in self.config: - self.path_album_regex = re.compile(self.config['album_path'].get()) + self.path_album_regex = re.compile( + bytestring_path(self.config['album_path'].get())) if 'singleton_path' in self.config: self.path_singleton_regex = re.compile( - self.config['singleton_path'].get()) + bytestring_path(self.config['singleton_path'].get())) def import_task_created_event(self, session, task): if task.items and len(task.items) > 0: @@ -70,7 +71,7 @@ class FileFilterPlugin(BeetsPlugin): of the file given in full_path. """ import_config = dict(config['import']) - full_path = util.bytestring_path(full_path) + full_path = bytestring_path(full_path) if 'singletons' not in import_config or not import_config[ 'singletons']: # Album From 3ea9706f4e9d59b1818fdc7ba5ea1bd6cb1fce7a Mon Sep 17 00:00:00 2001 From: Gondlar Date: Thu, 16 Jun 2016 18:53:55 +0200 Subject: [PATCH 0957/2280] Clarify which fields are searched by default --- docs/reference/query.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 82a16869d..2f3366d4c 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -13,7 +13,7 @@ This command:: $ beet list love -will show all tracks matching the query string ``love``. Any unadorned word like this matches *anywhere* in a track's metadata, so you'll see all the tracks with "love" in their title, in their album name, in the artist, and so on. +will show all tracks matching the query string ``love``. By default any unadorned word like this matches in a track's title, artist, album name, album artist, genre and comments. See below on how to search other fields. For example, this is what I might see when I run the command above:: From 36b3b20422b98f8637c5cee44a5b5aa357a932be Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 21:28:41 -0400 Subject: [PATCH 0958/2280] bytestringify test_lyrics --- test/test_lyrics.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 7201de35a..9136131c1 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -27,7 +27,7 @@ from mock import MagicMock from test._common import unittest from beetsplug import lyrics from beets.library import Item -from beets.util import confit +from beets.util import confit, bytestring_path from beets import logging log = logging.getLogger('beets.test_lyrics') @@ -179,7 +179,9 @@ def url_to_filename(url): url = re.sub(r'https?://|www.', '', url) fn = "".join(x for x in url if (x.isalnum() or x == '/')) fn = fn.split('/') - fn = os.path.join(LYRICS_ROOT_DIR, fn[0], fn[-1]) + '.txt' + fn = os.path.join(LYRICS_ROOT_DIR, + bytestring_path(fn[0]), + bytestring_path(fn[-1] + '.txt')) return fn @@ -211,8 +213,8 @@ def is_lyrics_content_ok(title, text): keywords = LYRICS_TEXTS[google.slugify(title)] return all(x in text.lower() for x in keywords) -LYRICS_ROOT_DIR = os.path.join(_common.RSRC, 'lyrics') -LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, 'lyricstext.yaml')) +LYRICS_ROOT_DIR = os.path.join(_common.RSRC, b'lyrics') +LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, b'lyricstext.yaml')) DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') DEFAULT_SOURCES = [ From a903b57daeb1b878ad1c1e86dcb3ce0d1fbdc35c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 21:46:31 -0400 Subject: [PATCH 0959/2280] encode the passwords passed to hashlib in embyupdate --- beetsplug/embyupdate.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 38f8929e5..1237762fe 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -36,8 +36,8 @@ def password_data(username, password): """ return { 'username': username, - 'password': hashlib.sha1(password).hexdigest(), - 'passwordMd5': hashlib.md5(password).hexdigest() + 'password': hashlib.sha1(password.encode('utf-8')).hexdigest(), + 'passwordMd5': hashlib.md5(password.encode('utf-8')).hexdigest() } From 52f2ab2547b29a5baa04e6d8779b961a9a906457 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:00:45 -0400 Subject: [PATCH 0960/2280] encode uri passed to hashlib in thumbnails plugin --- beetsplug/thumbnails.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index d6d4ff356..0c1ec2b83 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -162,7 +162,7 @@ class ThumbnailsPlugin(BeetsPlugin): See http://standards.freedesktop.org/thumbnail-spec/latest/x227.html """ uri = self.get_uri(path) - hash = md5(uri).hexdigest() + hash = md5(uri.encode('utf-8')).hexdigest() return b"{0}.png".format(hash) def add_tags(self, album, image_path): From 15c07613bf50c0764ad77aeb882fdb132feeee68 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:04:24 -0400 Subject: [PATCH 0961/2280] decode the filename written to .desktop file --- beetsplug/thumbnails.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 0c1ec2b83..94ca70962 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -183,7 +183,8 @@ class ThumbnailsPlugin(BeetsPlugin): return artfile = os.path.split(album.artpath)[1] with open(outfilename, 'w') as f: - f.write(b"[Desktop Entry]\nIcon=./{0}".format(artfile)) + f.write('[Desktop Entry]\n') + f.write('Icon=./{0}'.format(artfile.decode('utf-8'))) f.close() self._log.debug(u"Wrote file {0}", util.displayable_path(outfilename)) From b602faabb8e1963b20941f9b67411fe01da7abcf Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:10:49 -0400 Subject: [PATCH 0962/2280] more bytestringification in thumbnails plugin --- beetsplug/thumbnails.py | 2 +- test/test_thumbnails.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 94ca70962..ce0a9490e 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -163,7 +163,7 @@ class ThumbnailsPlugin(BeetsPlugin): """ uri = self.get_uri(path) hash = md5(uri.encode('utf-8')).hexdigest() - return b"{0}.png".format(hash) + return util.bytestring_path("{0}.png".format(hash)) def add_tags(self, album, image_path): """Write required metadata to the thumbnail diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 06dd0a8e9..0454ae0d7 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -59,7 +59,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): plugin.add_tags(album, b"/path/to/thumbnail") - metadata = {"Thumb::URI": b"COVER_URI", + metadata = {"Thumb::URI": "COVER_URI", "Thumb::MTime": u"12345"} plugin.write_metadata.assert_called_once_with(b"/path/to/thumbnail", metadata) @@ -135,7 +135,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): album = Mock(artpath=path_to_art) mock_util.syspath.side_effect = lambda x: x - plugin.thumbnail_file_name = Mock(return_value="md5") + plugin.thumbnail_file_name = Mock(return_value=b'md5') mock_os.path.exists.return_value = False def os_stat(target): @@ -268,7 +268,7 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): def test_thumbnail_file_name(self, mock_basedir): plug = ThumbnailsPlugin() plug.get_uri = Mock(return_value=u"file:///my/uri") - self.assertEqual(plug.thumbnail_file_name("idontcare"), + self.assertEqual(plug.thumbnail_file_name(b'idontcare'), b"9488f5797fbe12ffb316d607dfd93d04.png") def test_uri(self): From 3184599faad4f855cdc805a1586c44ba5677ae74 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:17:45 -0400 Subject: [PATCH 0963/2280] compare bytes to bytes in library TemplateTest --- test/test_library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index 19b987d58..4cd922910 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1052,7 +1052,7 @@ class TemplateTest(_common.LibTestCase): self.assertEqual(u"{0}".format(album), u"foö bar") self.assertEqual(u"{0:$tagada}".format(album), u"togodo") self.assertEqual(unicode(album), u"foö bar") - self.assertEqual(str(album), b"fo\xc3\xb6 bar") + self.assertEqual(bytes(album), b"fo\xc3\xb6 bar") config['format_item'] = 'bar $foo' item = beets.library.Item() From 411e4957b0a3a55546067151750cdd36de6ed429 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:35:28 -0400 Subject: [PATCH 0964/2280] bytestringify replace_ext in convert plugin --- beetsplug/convert.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index b88a20d4c..5f7ede949 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -47,7 +47,8 @@ def replace_ext(path, ext): The new extension must not contain a leading dot. """ - return os.path.splitext(path)[0] + b'.' + ext + path = os.path.splitext(path)[0] + '.' + ext + return util.bytestring_path(path) def get_format(fmt=None): From 1088df7242e69defd5bba362c616934d41797d54 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:40:16 -0400 Subject: [PATCH 0965/2280] bytestringify some more paths in test helper --- test/helper.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/helper.py b/test/helper.py index db3de22aa..012e4303a 100644 --- a/test/helper.py +++ b/test/helper.py @@ -327,8 +327,9 @@ class TestHelper(object): """Add an item with an actual audio file to the library. """ item = self.create_item(**values) - extension = item['format'].lower() - item['path'] = os.path.join(_common.RSRC, 'min.' + extension) + extension = item['format'].lower().encode('utf-8') + item['path'] = os.path.join(_common.RSRC, + util.bytestring_path('min.' + extension)) item.add(self.lib) item.move(copy=True) item.store() @@ -343,9 +344,9 @@ class TestHelper(object): """ # TODO base this on `add_item()` items = [] - path = os.path.join(_common.RSRC, b'full.' + ext) + path = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) for i in range(count): - item = Item.from_path(bytes(path)) + item = Item.from_path(path) item.album = u'\u00e4lbum {0}'.format(i) # Check unicode paths item.title = u't\u00eftle {0}'.format(i) item.add(self.lib) @@ -358,7 +359,7 @@ class TestHelper(object): """Add an album with files to the database. """ items = [] - path = os.path.join(_common.RSRC, 'full.' + ext) + path = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) for i in range(track_count): item = Item.from_path(bytes(path)) item.album = u'\u00e4lbum' # Check unicode paths @@ -380,7 +381,7 @@ class TestHelper(object): specified extension a cover art image is added to the media file. """ - src = os.path.join(_common.RSRC, 'full.' + ext) + src = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) handle, path = mkstemp() os.close(handle) shutil.copyfile(src, path) From 12136e1d32fc340104ce0315caeface741fdf48e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 16 Jun 2016 23:59:51 -0400 Subject: [PATCH 0966/2280] adapt is_url checking for bytestring paths --- beetsplug/mpdstats.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 2b6422942..b1a01b52e 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -40,9 +40,10 @@ mpd_config = config['mpd'] def is_url(path): """Try to determine if the path is an URL. """ + if isinstance(path, bytes): # if it's bytes, then it's a path + return False return path.split('://', 1)[0] in ['http', 'https'] - # Use the MPDClient internals to get unicode. # see http://www.tarmack.eu/code/mpdunicode.py for the general idea class MPDClient(mpd.MPDClient): From fff0439b06854e33670f6e3b3789b4e51b6bb1f3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 00:09:22 -0400 Subject: [PATCH 0967/2280] add missing blank line in mpdstats --- beetsplug/mpdstats.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index b1a01b52e..fedf3276c 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -44,6 +44,7 @@ def is_url(path): return False return path.split('://', 1)[0] in ['http', 'https'] + # Use the MPDClient internals to get unicode. # see http://www.tarmack.eu/code/mpdunicode.py for the general idea class MPDClient(mpd.MPDClient): From cf5ab2617af6de3e2e1e426dc5acf1260091ca0e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 01:16:53 -0400 Subject: [PATCH 0968/2280] reorient bytestring_path code in convert replace_ext --- beetsplug/convert.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 5f7ede949..21a348bab 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -47,8 +47,8 @@ def replace_ext(path, ext): The new extension must not contain a leading dot. """ - path = os.path.splitext(path)[0] + '.' + ext - return util.bytestring_path(path) + ext_dot = util.bytestring_path('.' + ext) + return os.path.splitext(path)[0] + ext_dot def get_format(fmt=None): From 60a961a7519f56e519d6b2879a7c27496e046dcb Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 00:11:41 -0400 Subject: [PATCH 0969/2280] remove an unnecessary .encode() in create_item_fixture --- test/helper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helper.py b/test/helper.py index 012e4303a..9335a7d6b 100644 --- a/test/helper.py +++ b/test/helper.py @@ -327,7 +327,7 @@ class TestHelper(object): """Add an item with an actual audio file to the library. """ item = self.create_item(**values) - extension = item['format'].lower().encode('utf-8') + extension = item['format'].lower() item['path'] = os.path.join(_common.RSRC, util.bytestring_path('min.' + extension)) item.add(self.lib) From a0a9e2f22d0f429da0663a5b1abacc122035df57 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 01:40:16 -0400 Subject: [PATCH 0970/2280] mark itunes library files as bytestrings --- test/test_metasync.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_metasync.py b/test/test_metasync.py index c21c16b12..785a3381a 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -36,9 +36,9 @@ def _is_windows(): class MetaSyncTest(_common.TestCase, TestHelper): itunes_library_unix = os.path.join(_common.RSRC, - 'itunes_library_unix.xml') + b'itunes_library_unix.xml') itunes_library_windows = os.path.join(_common.RSRC, - 'itunes_library_windows.xml') + b'itunes_library_windows.xml') def setUp(self): self.setup_beets() From 4bbfe85c66856d6e110f0bf229fac15e04d02c2e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 01:48:27 -0400 Subject: [PATCH 0971/2280] is_path_query takes unicode, so do that test_query This fixes all but one instance that I'm not yet sure how to fix --- test/test_query.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 2f8014015..146d0d3c1 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -604,7 +604,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): self.assertTrue(is_path(parent)) # Some non-existent path. - self.assertFalse(is_path(path + b'baz')) + self.assertFalse(is_path(path + u'baz')) finally: # Restart the `os.path.exists` patch. @@ -621,10 +621,10 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): cur_dir = os.getcwd() try: os.chdir(self.temp_dir) - self.assertTrue(is_path(b'foo/')) - self.assertTrue(is_path(b'foo/bar')) - self.assertTrue(is_path(b'foo/bar:tagada')) - self.assertFalse(is_path(b'bar')) + self.assertTrue(is_path(u'foo/')) + self.assertTrue(is_path(u'foo/bar')) + self.assertTrue(is_path(u'foo/bar:tagada')) + self.assertFalse(is_path(u'bar')) finally: os.chdir(cur_dir) From fda391132355001148476737451686e26d67909a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 01:58:49 -0400 Subject: [PATCH 0972/2280] bytestringify touch call in PathQueryTest --- test/test_query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_query.py b/test/test_query.py index 146d0d3c1..707d9d182 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -594,7 +594,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): is_path = beets.library.PathQuery.is_path_query try: - path = self.touch(os.path.join('foo', 'bar')) + path = self.touch(os.path.join(b'foo', b'bar')) # The file itself. self.assertTrue(is_path(path)) From 7dcf160d0bf16d3daf24581305799d0d6f220fcc Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 02:32:57 -0400 Subject: [PATCH 0973/2280] make sure extract() in art handles bytestring paths --- beets/art.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/art.py b/beets/art.py index f3455445b..bf1d03a0a 100644 --- a/beets/art.py +++ b/beets/art.py @@ -25,7 +25,7 @@ from tempfile import NamedTemporaryFile import imghdr import os -from beets.util import displayable_path, syspath +from beets.util import displayable_path, syspath, bytestring_path from beets.util.artresizer import ArtResizer from beets import mediafile @@ -188,7 +188,7 @@ def check_art_similarity(log, item, imagepath, compare_threshold): def extract(log, outpath, item): art = get_art(log, item) - + outpath = bytestring_path(outpath) if not art: log.info(u'No album art present in {0}, skipping.', item) return @@ -199,7 +199,7 @@ def extract(log, outpath, item): log.warning(u'Unknown image type in {0}.', displayable_path(item.path)) return - outpath += b'.' + ext + outpath += bytestring_path('.' + ext) log.info(u'Extracting album art from: {0} to: {1}', item, displayable_path(outpath)) From 1c761c60fbf064abd7d58876f23b4ba1d072019e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 03:30:42 -0400 Subject: [PATCH 0974/2280] bytstringify extra cover_names in fetchart --- beetsplug/fetchart.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 5eb120a65..7f40e83f6 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -595,8 +595,9 @@ class FileSystem(LocalArtSource): paths = extra['paths'] if not paths: return - cover_names = extra['cover_names'] - cover_pat = br"(\b|_)({0})(\b|_)".format(b'|'.join(cover_names)) + cover_names = list(map(util.bytestring_path, extra['cover_names'])) + cover_names_str = b'|'.join(cover_names) + cover_pat = br''.join([br"(\b|_)(", cover_names_str, br")(\b|_)"]) cautious = extra['cautious'] for path in paths: From 4e2c2a9a2e377e718dc3ef0998b15ba339eb9be5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 04:03:00 -0400 Subject: [PATCH 0975/2280] add noqa to py3 type checks This prevents `F821 undefined name` warnings --- beets/util/confit.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index aa49f6f12..38b9d3428 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -47,9 +47,9 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else unicode -BASESTRING = str if PY3 else basestring -NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) +STRING = str if PY3 else unicode # noqa +BASESTRING = str if PY3 else basestring # noqa +NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa def iter_first(sequence): From 93e510c1c7f7974532cfa45d130583c6a632f591 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 05:26:21 -0400 Subject: [PATCH 0976/2280] remove an unnecessary b' in test_fetchart --- test/test_fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_fetchart.py b/test/test_fetchart.py index 52e7758b8..5def538eb 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -26,7 +26,7 @@ class FetchartCliTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('fetchart') - self.config['fetchart']['cover_names'] = b'c\xc3\xb6ver.jpg' + self.config['fetchart']['cover_names'] = 'c\xc3\xb6ver.jpg' self.config['art_filename'] = 'mycover' self.album = self.add_album() From ab2703136044becb98bc23233f878f22c14b8758 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 23:04:14 -0400 Subject: [PATCH 0977/2280] handle byte values when _safe_cast out_type is float --- beets/mediafile.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 1251cee26..4701600d5 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -158,7 +158,9 @@ def _safe_cast(out_type, val): if isinstance(val, int) or isinstance(val, float): return float(val) else: - if not isinstance(val, basestring): + if isinstance(val, bytes): + val = val.decode('utf8', 'ignore') + else: val = unicode(val) match = re.match(r'[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)', val.strip()) From a1609ec548d931c023ad3de808196ab08abcf248 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 23:39:17 -0400 Subject: [PATCH 0978/2280] use strings for *StorageStyle keys, not bytes --- beets/mediafile.py | 104 ++++++++++++++++++++--------------------- test/test_mediafile.py | 8 ++-- 2 files changed, 56 insertions(+), 56 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 4701600d5..e80cd65d9 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -592,7 +592,7 @@ class MP4StorageStyle(StorageStyle): def serialize(self, value): value = super(MP4StorageStyle, self).serialize(value) - if self.key.startswith(b'----:') and isinstance(value, unicode): + if self.key.startswith('----:') and isinstance(value, unicode): value = value.encode('utf8') return value @@ -667,7 +667,7 @@ class MP4ImageStorageStyle(MP4ListStorageStyle): """Store images as MPEG-4 image atoms. Values are `Image` objects. """ def __init__(self, **kwargs): - super(MP4ImageStorageStyle, self).__init__(key=b'covr', **kwargs) + super(MP4ImageStorageStyle, self).__init__(key='covr', **kwargs) def deserialize(self, data): return Image(data) @@ -1547,25 +1547,25 @@ class MediaFile(object): title = MediaField( MP3StorageStyle('TIT2'), - MP4StorageStyle(b"\xa9nam"), + MP4StorageStyle('\xa9nam'), StorageStyle('TITLE'), ASFStorageStyle('Title'), ) artist = MediaField( MP3StorageStyle('TPE1'), - MP4StorageStyle(b"\xa9ART"), + MP4StorageStyle('\xa9ART'), StorageStyle('ARTIST'), ASFStorageStyle('Author'), ) album = MediaField( MP3StorageStyle('TALB'), - MP4StorageStyle(b"\xa9alb"), + MP4StorageStyle('\xa9alb'), StorageStyle('ALBUM'), ASFStorageStyle('WM/AlbumTitle'), ) genres = ListMediaField( MP3ListStorageStyle('TCON'), - MP4ListStorageStyle(b"\xa9gen"), + MP4ListStorageStyle('\xa9gen'), ListStorageStyle('GENRE'), ASFStorageStyle('WM/Genre'), ) @@ -1573,19 +1573,19 @@ class MediaFile(object): composer = MediaField( MP3StorageStyle('TCOM'), - MP4StorageStyle(b"\xa9wrt"), + MP4StorageStyle('\xa9wrt'), StorageStyle('COMPOSER'), ASFStorageStyle('WM/Composer'), ) grouping = MediaField( MP3StorageStyle('TIT1'), - MP4StorageStyle(b"\xa9grp"), + MP4StorageStyle('\xa9grp'), StorageStyle('GROUPING'), ASFStorageStyle('WM/ContentGroupDescription'), ) track = MediaField( MP3SlashPackStorageStyle('TRCK', pack_pos=0), - MP4TupleStorageStyle(b'trkn', index=0), + MP4TupleStorageStyle('trkn', index=0), StorageStyle('TRACK'), StorageStyle('TRACKNUMBER'), ASFStorageStyle('WM/TrackNumber'), @@ -1593,7 +1593,7 @@ class MediaFile(object): ) tracktotal = MediaField( MP3SlashPackStorageStyle('TRCK', pack_pos=1), - MP4TupleStorageStyle(b'trkn', index=1), + MP4TupleStorageStyle('trkn', index=1), StorageStyle('TRACKTOTAL'), StorageStyle('TRACKC'), StorageStyle('TOTALTRACKS'), @@ -1602,7 +1602,7 @@ class MediaFile(object): ) disc = MediaField( MP3SlashPackStorageStyle('TPOS', pack_pos=0), - MP4TupleStorageStyle(b'disk', index=0), + MP4TupleStorageStyle('disk', index=0), StorageStyle('DISC'), StorageStyle('DISCNUMBER'), ASFStorageStyle('WM/PartOfSet'), @@ -1610,7 +1610,7 @@ class MediaFile(object): ) disctotal = MediaField( MP3SlashPackStorageStyle('TPOS', pack_pos=1), - MP4TupleStorageStyle(b'disk', index=1), + MP4TupleStorageStyle('disk', index=1), StorageStyle('DISCTOTAL'), StorageStyle('DISCC'), StorageStyle('TOTALDISCS'), @@ -1619,13 +1619,13 @@ class MediaFile(object): ) lyrics = MediaField( MP3DescStorageStyle(key='USLT'), - MP4StorageStyle(b"\xa9lyr"), + MP4StorageStyle('\xa9lyr'), StorageStyle('LYRICS'), ASFStorageStyle('WM/Lyrics'), ) comments = MediaField( MP3DescStorageStyle(key='COMM'), - MP4StorageStyle(b"\xa9cmt"), + MP4StorageStyle('\xa9cmt'), StorageStyle('DESCRIPTION'), StorageStyle('COMMENT'), ASFStorageStyle('WM/Comments'), @@ -1633,111 +1633,111 @@ class MediaFile(object): ) bpm = MediaField( MP3StorageStyle('TBPM'), - MP4StorageStyle(b'tmpo', as_type=int), + MP4StorageStyle('tmpo', as_type=int), StorageStyle('BPM'), ASFStorageStyle('WM/BeatsPerMinute'), out_type=int, ) comp = MediaField( MP3StorageStyle('TCMP'), - MP4BoolStorageStyle(b'cpil'), + MP4BoolStorageStyle('cpil'), StorageStyle('COMPILATION'), ASFStorageStyle('WM/IsCompilation', as_type=bool), out_type=bool, ) albumartist = MediaField( MP3StorageStyle('TPE2'), - MP4StorageStyle(b'aART'), + MP4StorageStyle('aART'), StorageStyle('ALBUM ARTIST'), StorageStyle('ALBUMARTIST'), ASFStorageStyle('WM/AlbumArtist'), ) albumtype = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Type'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Type'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Type'), StorageStyle('MUSICBRAINZ_ALBUMTYPE'), ASFStorageStyle('MusicBrainz/Album Type'), ) label = MediaField( MP3StorageStyle('TPUB'), - MP4StorageStyle(b'----:com.apple.iTunes:Label'), - MP4StorageStyle(b'----:com.apple.iTunes:publisher'), + MP4StorageStyle('----:com.apple.iTunes:Label'), + MP4StorageStyle('----:com.apple.iTunes:publisher'), StorageStyle('LABEL'), StorageStyle('PUBLISHER'), # Traktor ASFStorageStyle('WM/Publisher'), ) artist_sort = MediaField( MP3StorageStyle('TSOP'), - MP4StorageStyle(b"soar"), + MP4StorageStyle('soar'), StorageStyle('ARTISTSORT'), ASFStorageStyle('WM/ArtistSortOrder'), ) albumartist_sort = MediaField( MP3DescStorageStyle(u'ALBUMARTISTSORT'), - MP4StorageStyle(b"soaa"), + MP4StorageStyle('soaa'), StorageStyle('ALBUMARTISTSORT'), ASFStorageStyle('WM/AlbumArtistSortOrder'), ) asin = MediaField( MP3DescStorageStyle(u'ASIN'), - MP4StorageStyle(b"----:com.apple.iTunes:ASIN"), + MP4StorageStyle('----:com.apple.iTunes:ASIN'), StorageStyle('ASIN'), ASFStorageStyle('MusicBrainz/ASIN'), ) catalognum = MediaField( MP3DescStorageStyle(u'CATALOGNUMBER'), - MP4StorageStyle(b"----:com.apple.iTunes:CATALOGNUMBER"), + MP4StorageStyle('----:com.apple.iTunes:CATALOGNUMBER'), StorageStyle('CATALOGNUMBER'), ASFStorageStyle('WM/CatalogNo'), ) disctitle = MediaField( MP3StorageStyle('TSST'), - MP4StorageStyle(b"----:com.apple.iTunes:DISCSUBTITLE"), + MP4StorageStyle('----:com.apple.iTunes:DISCSUBTITLE'), StorageStyle('DISCSUBTITLE'), ASFStorageStyle('WM/SetSubTitle'), ) encoder = MediaField( MP3StorageStyle('TENC'), - MP4StorageStyle(b"\xa9too"), + MP4StorageStyle('\xa9too'), StorageStyle('ENCODEDBY'), StorageStyle('ENCODER'), ASFStorageStyle('WM/EncodedBy'), ) script = MediaField( MP3DescStorageStyle(u'Script'), - MP4StorageStyle(b"----:com.apple.iTunes:SCRIPT"), + MP4StorageStyle('----:com.apple.iTunes:SCRIPT'), StorageStyle('SCRIPT'), ASFStorageStyle('WM/Script'), ) language = MediaField( MP3StorageStyle('TLAN'), - MP4StorageStyle(b"----:com.apple.iTunes:LANGUAGE"), + MP4StorageStyle('----:com.apple.iTunes:LANGUAGE'), StorageStyle('LANGUAGE'), ASFStorageStyle('WM/Language'), ) country = MediaField( MP3DescStorageStyle('MusicBrainz Album Release Country'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz " - b"Album Release Country"), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz ' + 'Album Release Country'), StorageStyle('RELEASECOUNTRY'), ASFStorageStyle('MusicBrainz/Album Release Country'), ) albumstatus = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Status'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz Album Status"), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Status'), StorageStyle('MUSICBRAINZ_ALBUMSTATUS'), ASFStorageStyle('MusicBrainz/Album Status'), ) media = MediaField( MP3StorageStyle('TMED'), - MP4StorageStyle(b"----:com.apple.iTunes:MEDIA"), + MP4StorageStyle('----:com.apple.iTunes:MEDIA'), StorageStyle('MEDIA'), ASFStorageStyle('WM/Media'), ) albumdisambig = MediaField( # This tag mapping was invented for beets (not used by Picard, etc). MP3DescStorageStyle(u'MusicBrainz Album Comment'), - MP4StorageStyle(b"----:com.apple.iTunes:MusicBrainz Album Comment"), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Comment'), StorageStyle('MUSICBRAINZ_ALBUMCOMMENT'), ASFStorageStyle('MusicBrainz/Album Comment'), ) @@ -1745,7 +1745,7 @@ class MediaFile(object): # Release date. date = DateField( MP3StorageStyle('TDRC'), - MP4StorageStyle(b"\xa9day"), + MP4StorageStyle('\xa9day'), StorageStyle('DATE'), ASFStorageStyle('WM/Year'), year=(StorageStyle('YEAR'),)) @@ -1757,7 +1757,7 @@ class MediaFile(object): # *Original* release date. original_date = DateField( MP3StorageStyle('TDOR'), - MP4StorageStyle(b'----:com.apple.iTunes:ORIGINAL YEAR'), + MP4StorageStyle('----:com.apple.iTunes:ORIGINAL YEAR'), StorageStyle('ORIGINALDATE'), ASFStorageStyle('WM/OriginalReleaseYear')) @@ -1768,13 +1768,13 @@ class MediaFile(object): # Nonstandard metadata. artist_credit = MediaField( MP3DescStorageStyle(u'Artist Credit'), - MP4StorageStyle(b"----:com.apple.iTunes:Artist Credit"), + MP4StorageStyle('----:com.apple.iTunes:Artist Credit'), StorageStyle('ARTIST_CREDIT'), ASFStorageStyle('beets/Artist Credit'), ) albumartist_credit = MediaField( MP3DescStorageStyle(u'Album Artist Credit'), - MP4StorageStyle(b"----:com.apple.iTunes:Album Artist Credit"), + MP4StorageStyle('----:com.apple.iTunes:Album Artist Credit'), StorageStyle('ALBUMARTIST_CREDIT'), ASFStorageStyle('beets/Album Artist Credit'), ) @@ -1788,31 +1788,31 @@ class MediaFile(object): # MusicBrainz IDs. mb_trackid = MediaField( MP3UFIDStorageStyle(owner='http://musicbrainz.org'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Track Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Track Id'), StorageStyle('MUSICBRAINZ_TRACKID'), ASFStorageStyle('MusicBrainz/Track Id'), ) mb_albumid = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Id'), StorageStyle('MUSICBRAINZ_ALBUMID'), ASFStorageStyle('MusicBrainz/Album Id'), ) mb_artistid = MediaField( MP3DescStorageStyle(u'MusicBrainz Artist Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Artist Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Artist Id'), StorageStyle('MUSICBRAINZ_ARTISTID'), ASFStorageStyle('MusicBrainz/Artist Id'), ) mb_albumartistid = MediaField( MP3DescStorageStyle(u'MusicBrainz Album Artist Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Album Artist Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Album Artist Id'), StorageStyle('MUSICBRAINZ_ALBUMARTISTID'), ASFStorageStyle('MusicBrainz/Album Artist Id'), ) mb_releasegroupid = MediaField( MP3DescStorageStyle(u'MusicBrainz Release Group Id'), - MP4StorageStyle(b'----:com.apple.iTunes:MusicBrainz Release Group Id'), + MP4StorageStyle('----:com.apple.iTunes:MusicBrainz Release Group Id'), StorageStyle('MUSICBRAINZ_RELEASEGROUPID'), ASFStorageStyle('MusicBrainz/Release Group Id'), ) @@ -1820,13 +1820,13 @@ class MediaFile(object): # Acoustid fields. acoustid_fingerprint = MediaField( MP3DescStorageStyle(u'Acoustid Fingerprint'), - MP4StorageStyle(b'----:com.apple.iTunes:Acoustid Fingerprint'), + MP4StorageStyle('----:com.apple.iTunes:Acoustid Fingerprint'), StorageStyle('ACOUSTID_FINGERPRINT'), ASFStorageStyle('Acoustid/Fingerprint'), ) acoustid_id = MediaField( MP3DescStorageStyle(u'Acoustid Id'), - MP4StorageStyle(b'----:com.apple.iTunes:Acoustid Id'), + MP4StorageStyle('----:com.apple.iTunes:Acoustid Id'), StorageStyle('ACOUSTID_ID'), ASFStorageStyle('Acoustid/Id'), ) @@ -1847,11 +1847,11 @@ class MediaFile(object): id3_lang='eng' ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_track_gain', - float_places=2, suffix=b' dB' + '----:com.apple.iTunes:replaygain_track_gain', + float_places=2, suffix=' dB' ), MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', + '----:com.apple.iTunes:iTunNORM', index=0 ), StorageStyle( @@ -1874,7 +1874,7 @@ class MediaFile(object): float_places=2, suffix=u' dB' ), MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', + '----:com.apple.iTunes:iTunNORM', index=1 ), StorageStyle( @@ -1902,11 +1902,11 @@ class MediaFile(object): id3_lang='eng' ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_track_peak', + '----:com.apple.iTunes:replaygain_track_peak', float_places=6 ), MP4SoundCheckStorageStyle( - b'----:com.apple.iTunes:iTunNORM', + '----:com.apple.iTunes:iTunNORM', index=1 ), StorageStyle(u'REPLAYGAIN_TRACK_PEAK', float_places=6), @@ -1923,7 +1923,7 @@ class MediaFile(object): float_places=6 ), MP4StorageStyle( - b'----:com.apple.iTunes:replaygain_album_peak', + '----:com.apple.iTunes:replaygain_album_peak', float_places=6 ), StorageStyle(u'REPLAYGAIN_ALBUM_PEAK', float_places=6), @@ -1933,7 +1933,7 @@ class MediaFile(object): initial_key = MediaField( MP3StorageStyle('TKEY'), - MP4StorageStyle(b'----:com.apple.iTunes:initialkey'), + MP4StorageStyle('----:com.apple.iTunes:initialkey'), StorageStyle('INITIALKEY'), ASFStorageStyle('INITIALKEY'), ) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 180249d91..c38921360 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -297,10 +297,10 @@ class GenreListTestMixin(object): field_extension = MediaField( - MP3DescStorageStyle(b'customtag'), - MP4StorageStyle(b'----:com.apple.iTunes:customtag'), - StorageStyle(b'customtag'), - ASFStorageStyle(b'customtag'), + MP3DescStorageStyle('customtag'), + MP4StorageStyle('----:com.apple.iTunes:customtag'), + StorageStyle('customtag'), + ASFStorageStyle('customtag'), ) From 66431ab4ded5de3a1bda3f772c2d7121b99f1c14 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 17 Jun 2016 23:58:35 -0400 Subject: [PATCH 0979/2280] treat tag values as strings in ReadWriteTestBase --- test/test_mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index c38921360..e2fdd9fce 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -695,7 +695,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, # ReplayGain is float tags[key] = 1.0 else: - tags[key] = b'value\u2010%s' % key + tags[key] = 'value\u2010%s' % key for key in ['disc', 'disctotal', 'track', 'tracktotal', 'bpm']: tags[key] = 1 From 33d451ed2d736702acb97cf21a217522bacd6c57 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 18 Jun 2016 02:11:24 -0400 Subject: [PATCH 0980/2280] switch basestring for bytes in HumanReadableException We already check for unicode first, so this shouldn't cause any issues on py2 --- beets/util/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 9bd4ca529..0628f324b 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -67,7 +67,7 @@ class HumanReadableException(Exception): """Get the reason as a string.""" if isinstance(self.reason, unicode): return self.reason - elif isinstance(self.reason, basestring): # Byte string. + elif isinstance(self.reason, bytes): return self.reason.decode('utf8', 'ignore') elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError return self.reason.strerror From bc88dae726a1a811ae301c23fa15ca91b7c26e72 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 18 Jun 2016 02:35:43 -0400 Subject: [PATCH 0981/2280] rework basestring check in BytesQuery This makes it possible for this query to work in both py2 and py3, since strings are bytes in py2 --- beets/dbcore/query.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index caf380260..8e2075f37 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -246,9 +246,7 @@ class BytesQuery(MatchQuery): # Use a buffer representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. - if isinstance(self.pattern, basestring): - # Implicitly coerce Unicode strings to their bytes - # equivalents. + if isinstance(self.pattern, (unicode, bytes)): if isinstance(self.pattern, unicode): self.pattern = self.pattern.encode('utf8') self.buf_pattern = buffer(self.pattern) From da5fb855574fe6b1f8054cd224deeffa10bd6b02 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 18 Jun 2016 03:16:33 -0400 Subject: [PATCH 0982/2280] only import OrderedDict from collections in confit This was only necessary in <=2.6 --- beets/util/confit.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 38b9d3428..c20422f10 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -24,10 +24,7 @@ import sys import yaml import collections import re -try: - from collections import OrderedDict -except ImportError: - from ordereddict import OrderedDict +from collections import OrderedDict UNIX_DIR_VAR = 'XDG_CONFIG_HOME' UNIX_DIR_FALLBACK = '~/.config' From 2669b3594588a5a7f8c0826326b593e03a280e6b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 18 Jun 2016 03:23:14 -0400 Subject: [PATCH 0983/2280] handle bytes in a py3 compatible way in confit This applies to Subview and Filename. However, the Filename support isn't complete, since we can't implicitly convert bytes to strings in py3. Confit doesn't seem to have a way to handle this. --- beets/util/confit.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index c20422f10..057f85a1f 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -481,11 +481,11 @@ class Subview(ConfigView): self.name += '.' if isinstance(self.key, int): self.name += u'#{0}'.format(self.key) - elif isinstance(self.key, BASESTRING): - if isinstance(self.key, bytes): - self.name += self.key.decode('utf8') - else: + elif isinstance(self.key, (bytes, BASESTRING)): + if isinstance(self.key, STRING): self.name += self.key + else: + self.name += self.key.decode('utf8') else: self.name += repr(self.key) @@ -1341,7 +1341,7 @@ class Filename(Template): def value(self, view, template=None): path, source = view.first() - if not isinstance(path, BASESTRING): + if not isinstance(path, (bytes, BASESTRING)): self.fail( u'must be a filename, not {0}'.format(type(path).__name__), view, From a73ad99dd80378e48dc9219e8ba18cc82918b218 Mon Sep 17 00:00:00 2001 From: Dixon Xavier Date: Sun, 19 Jun 2016 12:53:37 +0530 Subject: [PATCH 0984/2280] Add new importer configuration to deal with duplicate items --- beets/config_default.yaml | 1 + beets/importer.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 4c12c3df0..fa77a82dc 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -23,6 +23,7 @@ import: group_albums: no pretend: false search_ids: [] + duplicate_action: ask clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information", "lost+found"] diff --git a/beets/importer.py b/beets/importer.py index 4209a4831..25daefe4e 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1327,7 +1327,24 @@ def resolve_duplicates(session, task): log.debug(u'found duplicates: {}'.format( [o.id for o in found_duplicates] )) - session.resolve_duplicate(task, found_duplicates) + + # Get the default action to follow from config. + duplicate_action = config['import']['duplicate_action'].get() + log.debug(u'default action for duplicates: {0}', duplicate_action) + + if duplicate_action == 'skip': + # Skip new. + task.set_choice(action.SKIP) + elif duplicate_action == 'keep': + # Keep both. Do nothing; leave the choice intact. + pass + elif duplicate_action == 'remove': + # Remove old. + task.should_remove_duplicates = True + else: + # No default action set; ask the session. + session.resolve_duplicate(task, found_duplicates) + session.log_choice(task, True) From fbcc8dbf1ec4e6354e5b75214126da924f8edc0c Mon Sep 17 00:00:00 2001 From: Dixon Xavier Date: Sun, 19 Jun 2016 12:54:27 +0530 Subject: [PATCH 0985/2280] Update changelog and documentation --- docs/changelog.rst | 2 ++ docs/reference/config.rst | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 64b582450..b350381af 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,8 @@ New features: * A new ``--force`` option for :ref:`remove-cmd` allows removal of items without prompting beforehand. :bug:`2042` +* A new importer configuration :ref:`duplicate_action` controls how + duplicate albums or tracks treated in import task. :bug:`185` Some fixes for Windows: diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 4ca54652a..11310ac0c 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -550,6 +550,17 @@ with the ``-a`` flag to the :ref:`import-cmd` command.) Default: ``yes``. +.. _duplicate_action + +duplicate_action +~~~~~~~~~~~~~~~~ + +Either ``skip``, ``keep``, ``remove``, or ``ask``. Controls how duplicates +are treated in import task. "skip" means that new item(album or track) will be +skiped; "keep" means keep both old and new items; "remove" means remove old +item; "ask" means the user should be prompted for the action each time. +The default is ``ask``. + .. _musicbrainz-config: From 80ca527f76d75aa549b3e2f6654fec65de1fdd3f Mon Sep 17 00:00:00 2001 From: Dixon Xavier Date: Sun, 19 Jun 2016 13:20:54 +0530 Subject: [PATCH 0986/2280] Fix typo in documentation --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 11310ac0c..0892aaa30 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -550,7 +550,7 @@ with the ``-a`` flag to the :ref:`import-cmd` command.) Default: ``yes``. -.. _duplicate_action +.. _duplicate_action: duplicate_action ~~~~~~~~~~~~~~~~ From 366a6d7fb29708e7380a500ceff4af1b79af997d Mon Sep 17 00:00:00 2001 From: Dixon Xavier Date: Mon, 20 Jun 2016 00:35:47 +0530 Subject: [PATCH 0987/2280] add validation for configuration --- beets/importer.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 25daefe4e..120a3ddb8 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1329,16 +1329,21 @@ def resolve_duplicates(session, task): )) # Get the default action to follow from config. - duplicate_action = config['import']['duplicate_action'].get() + duplicate_action = config['import']['duplicate_action'].as_choice({ + u'skip': u's', + u'keep': u'k', + u'remove': u'r', + u'ask' : u'a', + }) log.debug(u'default action for duplicates: {0}', duplicate_action) - if duplicate_action == 'skip': + if duplicate_action == u's': # Skip new. task.set_choice(action.SKIP) - elif duplicate_action == 'keep': + elif duplicate_action == u'k': # Keep both. Do nothing; leave the choice intact. pass - elif duplicate_action == 'remove': + elif duplicate_action == u'r': # Remove old. task.should_remove_duplicates = True else: From 4d75d4c06326f8e3a83bf75f5fb8c51f34b40b34 Mon Sep 17 00:00:00 2001 From: Dixon Xavier Date: Mon, 20 Jun 2016 00:52:09 +0530 Subject: [PATCH 0988/2280] Fix lint error --- beets/importer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index 120a3ddb8..60aeb2f2b 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1333,7 +1333,7 @@ def resolve_duplicates(session, task): u'skip': u's', u'keep': u'k', u'remove': u'r', - u'ask' : u'a', + u'ask': u'a', }) log.debug(u'default action for duplicates: {0}', duplicate_action) From 0917e675d7667e8f7b292f0f6cbab080d002fb7e Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Sun, 19 Jun 2016 22:06:55 +0200 Subject: [PATCH 0989/2280] bpg: Converted gstplayer.py to GStreamer 1.0 --- beetsplug/bpd/gstplayer.py | 61 ++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index b64cd0094..652079df8 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -21,16 +21,17 @@ from __future__ import division, absolute_import, print_function import sys import time -import gobject import thread import os import copy import urllib -import pygst -pygst.require('0.10') -import gst # noqa +import gi +gi.require_version('Gst', '1.0') +from gi.repository import GObject, Gst +GObject.threads_init() +Gst.init(None) class GstPlayer(object): """A music player abstracting GStreamer's Playbin element. @@ -57,8 +58,19 @@ class GstPlayer(object): # Set up the Gstreamer player. From the pygst tutorial: # http://pygstdocs.berlios.de/pygst-tutorial/playbin.html - self.player = gst.element_factory_make("playbin2", "player") - fakesink = gst.element_factory_make("fakesink", "fakesink") + #### + # Updated to GStreamer 1.0 with: + # https://wiki.ubuntu.com/Novacut/GStreamer1.0 + self.player = Gst.ElementFactory.make("playbin", "player") + + if self.player == None: + raise RuntimeError("Could not create playbin") + + fakesink = Gst.ElementFactory.make("fakesink", "fakesink") + + if fakesink == None: + raise RuntimeError("Could not create fakesink") + self.player.set_property("video-sink", fakesink) bus = self.player.get_bus() bus.add_signal_watch() @@ -74,21 +86,21 @@ class GstPlayer(object): """Returns the current state flag of the playbin.""" # gst's get_state function returns a 3-tuple; we just want the # status flag in position 1. - return self.player.get_state()[1] + return self.player.get_state(Gst.CLOCK_TIME_NONE)[1] def _handle_message(self, bus, message): """Callback for status updates from GStreamer.""" - if message.type == gst.MESSAGE_EOS: + if message.type == Gst.MessageType.EOS: # file finished playing - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None if self.finished_callback: self.finished_callback() - elif message.type == gst.MESSAGE_ERROR: + elif message.type == Gst.MessageType.ERROR: # error - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) err, debug = message.parse_error() print(u"Error: {0}".format(err)) self.playing = False @@ -109,27 +121,27 @@ class GstPlayer(object): """Immediately begin playing the audio file at the given path. """ - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) if isinstance(path, unicode): path = path.encode('utf8') uri = 'file://' + urllib.quote(path) self.player.set_property("uri", uri) - self.player.set_state(gst.STATE_PLAYING) + self.player.set_state(Gst.State.PLAYING) self.playing = True def play(self): """If paused, resume playback.""" - if self._get_state() == gst.STATE_PAUSED: - self.player.set_state(gst.STATE_PLAYING) + if self._get_state() == Gst.State.PAUSED: + self.player.set_state(Gst.State.PLAYING) self.playing = True def pause(self): """Pause playback.""" - self.player.set_state(gst.STATE_PAUSED) + self.player.set_state(Gst.State.PAUSED) def stop(self): """Halt playback.""" - self.player.set_state(gst.STATE_NULL) + self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None @@ -140,10 +152,9 @@ class GstPlayer(object): play_file() or play(). """ # If we don't use the MainLoop, messages are never sent. - gobject.threads_init() def start(): - loop = gobject.MainLoop() + loop = GObject.MainLoop() loop.run() thread.start_new_thread(start, ()) @@ -152,14 +163,14 @@ class GstPlayer(object): values are integers in seconds. If no stream is available, returns (0, 0). """ - fmt = gst.Format(gst.FORMAT_TIME) + fmt = Gst.Format(Gst.Format.TIME) try: - pos = self.player.query_position(fmt, None)[0] / (10 ** 9) - length = self.player.query_duration(fmt, None)[0] / (10 ** 9) + pos = self.player.query_position(fmt)[1] / (10 ** 9) + length = self.player.query_duration(fmt)[1] / (10 ** 9) self.cached_time = (pos, length) return (pos, length) - except gst.QueryError: + except Exception: # Stream not ready. For small gaps of time, for instance # after seeking, the time values are unavailable. For this # reason, we cache recent. @@ -175,9 +186,9 @@ class GstPlayer(object): self.stop() return - fmt = gst.Format(gst.FORMAT_TIME) + fmt = Gst.Format(Gst.Format.TIME) ns = position * 10 ** 9 # convert to nanoseconds - self.player.seek_simple(fmt, gst.SEEK_FLAG_FLUSH, ns) + self.player.seek_simple(fmt, Gst.SeekFlags.FLUSH, ns) # save new cached time self.cached_time = (position, cur_len) From 09322530ca35b2571783ab69f4128447a61f54e8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 19 Jun 2016 22:30:58 -0400 Subject: [PATCH 0990/2280] replace 2 map() calls with a list comprehension --- beets/importer.py | 2 +- beetsplug/info.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 60aeb2f2b..072c2ad5b 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -331,7 +331,7 @@ class ImportSession(object): been imported in a previous session. """ if self.is_resuming(toppath) \ - and all(map(lambda p: progress_element(toppath, p), paths)): + and all([progress_element(toppath, p) for p in paths]): return True if self.config['incremental'] \ and tuple(paths) in self.history_dirs: diff --git a/beetsplug/info.py b/beetsplug/info.py index 29bff7a29..d29d9b45f 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -230,7 +230,7 @@ def make_key_filter(include): def filter_(data): filtered = dict() for key, value in data.items(): - if any(map(lambda m: m.match(key), matchers)): + if any([m.match(key) for m in matchers]): filtered[key] = value return filtered From e1ede6827bfd204e2d53ec289881c8d9116a56b1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 19 Jun 2016 22:33:40 -0400 Subject: [PATCH 0991/2280] replace a filter() on search_ids with a list comp --- beets/autotag/match.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 9870f157f..ba657cedb 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -462,7 +462,7 @@ def tag_item(item, search_artist=None, search_title=None, candidates = {} # First, try matching by MusicBrainz ID. - trackids = search_ids or filter(None, [item.mb_trackid]) + trackids = search_ids or [t for t in [item.mb_trackid] if t] if trackids: for trackid in trackids: log.debug(u'Searching for track ID: {0}', trackid) From 705557a5d269bfdea5fd084b72efeb8df64d3aa3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 19 Jun 2016 22:55:31 -0400 Subject: [PATCH 0992/2280] add six as a new dependency for beets --- setup.py | 1 + tox.ini | 1 + 2 files changed, 2 insertions(+) diff --git a/setup.py b/setup.py index c0cf15354..0ec655730 100755 --- a/setup.py +++ b/setup.py @@ -86,6 +86,7 @@ setup( }, install_requires=[ + 'six', 'enum34>=1.0.4', 'mutagen>=1.27', 'munkres', diff --git a/tox.ini b/tox.ini index 22d4aba2a..fe05a52fa 100644 --- a/tox.ini +++ b/tox.ini @@ -24,6 +24,7 @@ deps = jellyfish python-mpd2 coverage + six [_flake8] deps = From 196176f1802e4b4d62b530ea8a5aafb7864248f8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 19 Jun 2016 22:56:14 -0400 Subject: [PATCH 0993/2280] use six.integer_types in library --- beets/library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index b9d9d4ffc..93441ef9c 100644 --- a/beets/library.py +++ b/beets/library.py @@ -23,6 +23,7 @@ import unicodedata import time import re from unidecode import unidecode +import six from beets import logging from beets.mediafile import MediaFile, MutagenError, UnreadableFileError @@ -565,7 +566,7 @@ class Item(LibModel): for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, (int, long)): + if isinstance(value, six.integer_types): if value.bit_length() > 63: value = 0 self[key] = value From ae4fd64d3a5fba39731abd2ba05d085f4d4a456c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:15:28 -0400 Subject: [PATCH 0994/2280] Revert "use six.integer_types in library" for now It will return post bugfix release This reverts commit 196176f1802e4b4d62b530ea8a5aafb7864248f8. --- beets/library.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 93441ef9c..b9d9d4ffc 100644 --- a/beets/library.py +++ b/beets/library.py @@ -23,7 +23,6 @@ import unicodedata import time import re from unidecode import unidecode -import six from beets import logging from beets.mediafile import MediaFile, MutagenError, UnreadableFileError @@ -566,7 +565,7 @@ class Item(LibModel): for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, six.integer_types): + if isinstance(value, (int, long)): if value.bit_length() > 63: value = 0 self[key] = value From 5208cfcaed09059ac64cf653fd5022585f2e4887 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:16:18 -0400 Subject: [PATCH 0995/2280] Revert "add six as a new dependency for beets" for now It will return after the next bugfix release This reverts commit 705557a5d269bfdea5fd084b72efeb8df64d3aa3. --- setup.py | 1 - tox.ini | 1 - 2 files changed, 2 deletions(-) diff --git a/setup.py b/setup.py index 0ec655730..c0cf15354 100755 --- a/setup.py +++ b/setup.py @@ -86,7 +86,6 @@ setup( }, install_requires=[ - 'six', 'enum34>=1.0.4', 'mutagen>=1.27', 'munkres', diff --git a/tox.ini b/tox.ini index fe05a52fa..22d4aba2a 100644 --- a/tox.ini +++ b/tox.ini @@ -24,7 +24,6 @@ deps = jellyfish python-mpd2 coverage - six [_flake8] deps = From 5613d9d4ea2f6a69e179508d2ebd541a8bef9267 Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Mon, 20 Jun 2016 18:09:37 +0200 Subject: [PATCH 0996/2280] bpd: Added correct error check for query_position/query_duration --- beetsplug/bpd/__init__.py | 2 +- beetsplug/bpd/gstplayer.py | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 33deda02c..5ec88c745 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -1167,7 +1167,7 @@ class BPDPlugin(BeetsPlugin): server.run() except NoGstreamerError: global_log.error(u'Gstreamer Python bindings not found.') - global_log.error(u'Install "python-gst0.10", "py27-gst-python", ' + global_log.error(u'Install "python-gst-1.0" ' u'or similar package to use BPD.') def commands(self): diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 652079df8..feb909ea0 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -33,6 +33,9 @@ from gi.repository import GObject, Gst GObject.threads_init() Gst.init(None) +class QueryError(Exception): + pass + class GstPlayer(object): """A music player abstracting GStreamer's Playbin element. @@ -165,12 +168,20 @@ class GstPlayer(object): """ fmt = Gst.Format(Gst.Format.TIME) try: - pos = self.player.query_position(fmt)[1] / (10 ** 9) - length = self.player.query_duration(fmt)[1] / (10 ** 9) + posq = self.player.query_position(fmt) + if not posq[0]: + raise QueryError("query_position failed") + pos = posq[1] / (10 ** 9) + + lengthq = self.player.query_duration(fmt) + if not lengthq[0]: + raise QueryError("query_duration failed") + length = lengthq[1] / (10 ** 9) + self.cached_time = (pos, length) return (pos, length) - except Exception: + except QueryError: # Stream not ready. For small gaps of time, for instance # after seeking, the time values are unavailable. For this # reason, we cache recent. From 9fd227c8ccf2293b9265d46d16f3da0787c157f1 Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Mon, 20 Jun 2016 18:22:07 +0200 Subject: [PATCH 0997/2280] Fixed flake8 errors --- beetsplug/bpd/gstplayer.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index feb909ea0..b361bdfe0 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -27,9 +27,10 @@ import copy import urllib import gi -gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst +gi.require_version('Gst', '1.0') + GObject.threads_init() Gst.init(None) @@ -66,12 +67,12 @@ class GstPlayer(object): # https://wiki.ubuntu.com/Novacut/GStreamer1.0 self.player = Gst.ElementFactory.make("playbin", "player") - if self.player == None: + if self.player is None: raise RuntimeError("Could not create playbin") fakesink = Gst.ElementFactory.make("fakesink", "fakesink") - if fakesink == None: + if fakesink is None: raise RuntimeError("Could not create fakesink") self.player.set_property("video-sink", fakesink) @@ -154,11 +155,13 @@ class GstPlayer(object): Call this function before trying to play any music with play_file() or play(). """ + # If we don't use the MainLoop, messages are never sent. def start(): loop = GObject.MainLoop() loop.run() + thread.start_new_thread(start, ()) def time(self): @@ -230,12 +233,14 @@ def play_complicated(paths): def next_song(): my_paths.pop(0) p.play_file(my_paths[0]) + p = GstPlayer(next_song) p.run() p.play_file(my_paths[0]) while my_paths: time.sleep(1) + if __name__ == '__main__': # A very simple command-line player. Just give it names of audio # files on the command line; these are all played in sequence. From 7b154cedd7fec0777f15d5841982bd01b70ef53f Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Mon, 20 Jun 2016 18:29:46 +0200 Subject: [PATCH 0998/2280] Added double line spacings between definitions --- beetsplug/bpd/gstplayer.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index b361bdfe0..0d6d0ffd4 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -34,9 +34,11 @@ gi.require_version('Gst', '1.0') GObject.threads_init() Gst.init(None) + class QueryError(Exception): pass + class GstPlayer(object): """A music player abstracting GStreamer's Playbin element. From f9ed53a096489581a5ccd75018c5deda972d46eb Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Mon, 20 Jun 2016 18:44:37 +0200 Subject: [PATCH 0999/2280] Multiple corrections as advised in the codereview --- beetsplug/bpd/__init__.py | 2 +- beetsplug/bpd/gstplayer.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 5ec88c745..ea1b0082e 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -1167,7 +1167,7 @@ class BPDPlugin(BeetsPlugin): server.run() except NoGstreamerError: global_log.error(u'Gstreamer Python bindings not found.') - global_log.error(u'Install "python-gst-1.0" ' + global_log.error(u'Install "gstreamer1.0" and "python-gi"' u'or similar package to use BPD.') def commands(self): diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 0d6d0ffd4..326739a7a 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -25,13 +25,13 @@ import thread import os import copy import urllib +from beets import ui import gi -from gi.repository import GObject, Gst +from gi.repository import GLib, Gst gi.require_version('Gst', '1.0') -GObject.threads_init() Gst.init(None) @@ -70,12 +70,12 @@ class GstPlayer(object): self.player = Gst.ElementFactory.make("playbin", "player") if self.player is None: - raise RuntimeError("Could not create playbin") + raise ui.UserError("Could not create playbin") fakesink = Gst.ElementFactory.make("fakesink", "fakesink") if fakesink is None: - raise RuntimeError("Could not create fakesink") + raise ui.UserError("Could not create fakesink") self.player.set_property("video-sink", fakesink) bus = self.player.get_bus() @@ -161,7 +161,7 @@ class GstPlayer(object): # If we don't use the MainLoop, messages are never sent. def start(): - loop = GObject.MainLoop() + loop = GLib.MainLoop() loop.run() thread.start_new_thread(start, ()) From a48a4c9a7c6a7dbac6a0e1487e8e18cb18e5dc70 Mon Sep 17 00:00:00 2001 From: Philipp Beckmann Date: Mon, 20 Jun 2016 18:56:11 +0200 Subject: [PATCH 1000/2280] bpd: edited the changelog and updated the requirements in the plugin docs --- docs/changelog.rst | 2 +- docs/plugins/bpd.rst | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b350381af..f5ea1e3c2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,7 @@ New features: without prompting beforehand. :bug:`2042` * A new importer configuration :ref:`duplicate_action` controls how duplicate albums or tracks treated in import task. :bug:`185` +* The plugin `bpd` was upgraded from GStreamer 0.10 to 1.0 :bug:`2057` Some fixes for Windows: @@ -33,7 +34,6 @@ Fixes: * Fix a crash introduced in the previous version when the standard input was connected to a Unix pipe. :bug:`2041` - 1.3.18 (May 31, 2016) --------------------- diff --git a/docs/plugins/bpd.rst b/docs/plugins/bpd.rst index eed0f2833..60e84a92f 100644 --- a/docs/plugins/bpd.rst +++ b/docs/plugins/bpd.rst @@ -24,8 +24,7 @@ with its Python bindings) on your system. .. _homebrew-versions: https://github.com/Homebrew/homebrew-versions -* On Linux, it's likely that you already have gst-python. (If not, your - distribution almost certainly has a package for it.) +* On Linux, you need to install GStreamer 1.0 and the GObject bindings for python. Under ubuntu, they are called `python-gi` and `gstreamer1.0`. * On Windows, you may want to try `GStreamer WinBuilds`_ (cavet emptor: I haven't tried this). From 7fa31883962742ead0746ffa175c1d9292277e54 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 20 Jun 2016 10:32:38 -0700 Subject: [PATCH 1001/2280] Docs tweaks for #2062 --- docs/changelog.rst | 3 ++- docs/plugins/bpd.rst | 13 +++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f5ea1e3c2..6f0333582 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,7 +10,8 @@ New features: without prompting beforehand. :bug:`2042` * A new importer configuration :ref:`duplicate_action` controls how duplicate albums or tracks treated in import task. :bug:`185` -* The plugin `bpd` was upgraded from GStreamer 0.10 to 1.0 :bug:`2057` +* :doc:`/plugins/bpd`: The plugin now uses the modern GStreamer 1.0 instead of + the old 0.10. Thanks to :user:`philippbeckmann`. :bug:`2057` :bug:`2062` Some fixes for Windows: diff --git a/docs/plugins/bpd.rst b/docs/plugins/bpd.rst index 60e84a92f..9c55594a7 100644 --- a/docs/plugins/bpd.rst +++ b/docs/plugins/bpd.rst @@ -16,24 +16,21 @@ Dependencies Before you can use BPD, you'll need the media library called GStreamer (along with its Python bindings) on your system. -* On Mac OS X, you can use `MacPorts`_ or `Homebrew`_. For MacPorts, just run - ``port install py27-gst-python``. For Homebrew, the appropriate formulae are - in `homebrew-versions`_, so run ``brew tap homebrew/versions`` and then - ``brew install gst-python010``. (Note that you'll need the Mac OS X - Developer Tools in either case.) +* On Mac OS X, you can use `Homebrew`_. Run ``brew install gstreamer`` and then + ``brew install pygobject3``. .. _homebrew-versions: https://github.com/Homebrew/homebrew-versions -* On Linux, you need to install GStreamer 1.0 and the GObject bindings for python. Under ubuntu, they are called `python-gi` and `gstreamer1.0`. +* On Linux, you need to install GStreamer 1.0 and the GObject bindings for + python. Under Ubuntu, they are called `python-gi` and `gstreamer1.0`. -* On Windows, you may want to try `GStreamer WinBuilds`_ (cavet emptor: I +* On Windows, you may want to try `GStreamer WinBuilds`_ (caveat emptor: I haven't tried this). You will also need the various GStreamer plugin packages to make everything work. See the :doc:`/plugins/chroma` documentation for more information on installing GStreamer plugins. -.. _MacPorts: http://www.macports.org/ .. _GStreamer WinBuilds: http://www.gstreamer-winbuild.ylatuya.es/ .. _Homebrew: http://mxcl.github.com/homebrew/ From 08c9bd84d8b8dfcbc1563b1f5f2a13b3d19d1b11 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 21 Jun 2016 02:30:20 +0200 Subject: [PATCH 1002/2280] fetchart: testcase for wrong server-side extensions (#2053) --- test/test_art.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index f88f2f1cf..58b15d8e5 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -46,7 +46,7 @@ class UseThePlugin(_common.TestCase): class FetchImageTest(UseThePlugin): - URL = 'http://example.com' + URL = 'http://example.com/test.jpg' @responses.activate def run(self, *args, **kwargs): @@ -61,18 +61,23 @@ class FetchImageTest(UseThePlugin): self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} + self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): self.mock_response('image/watercolour') - candidate = fetchart.Candidate(logger, url=self.URL) - self.source.fetch_image(candidate, self.extra) - self.assertEqual(candidate.path, None) + self.source.fetch_image(self.candidate, self.extra) + self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): self.mock_response('image/jpeg') - candidate = fetchart.Candidate(logger, url=self.URL) - self.source.fetch_image(candidate, self.extra) - self.assertNotEqual(candidate.path, None) + self.source.fetch_image(self.candidate, self.extra) + self.assertNotEqual(self.candidate.path, None) + + def test_extension_set_by_content_type(self): + self.mock_response('image/png') + self.source.fetch_image(self.candidate, self.extra) + self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') + self.assertExists(self.candidate.path) class FSArtTest(UseThePlugin): From c4617c2c1fb4b64a1317f73350ebe2170d2262d0 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 21 Jun 2016 10:57:45 +0200 Subject: [PATCH 1003/2280] fetchart: do not hardcode the downloaded extension to jpg, fixes #2053 --- beetsplug/fetchart.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 7f40e83f6..e10a35270 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -39,9 +39,11 @@ try: except ImportError: HAVE_ITUNES = False -IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg'] -CONTENT_TYPES = ('image/jpeg', 'image/png') -DOWNLOAD_EXTENSION = '.jpg' +CONTENT_TYPES = { + 'image/jpeg': [b'jpg', b'jpeg'], + 'image/png': [b'png'] +} +IMAGE_EXTENSIONS = [ext for exts in CONTENT_TYPES.values() for ext in exts] class Candidate(object): @@ -227,8 +229,8 @@ class RemoteArtSource(ArtSource): try: with closing(self.request(candidate.url, stream=True, message=u'downloading image')) as resp: - if 'Content-Type' not in resp.headers \ - or resp.headers['Content-Type'] not in CONTENT_TYPES: + ct = resp.headers.get('Content-Type', None) + if ct not in CONTENT_TYPES: self._log.debug( u'not a supported image: {}', resp.headers.get('Content-Type') or u'no content type', @@ -237,7 +239,7 @@ class RemoteArtSource(ArtSource): return # Generate a temporary file with the correct extension. - with NamedTemporaryFile(suffix=DOWNLOAD_EXTENSION, + with NamedTemporaryFile(suffix=b'.' + CONTENT_TYPES[ct][0], delete=False) as fh: for chunk in resp.iter_content(chunk_size=1024): fh.write(chunk) From 85d6ef4a8039e446cbdd144da6aefd2cff7531e0 Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Tue, 21 Jun 2016 11:02:16 +0200 Subject: [PATCH 1004/2280] Revive Beatport plugin with support for OAuth API (#1989) --- beetsplug/beatport.py | 382 ++++++++++++++++++++++++++++++++++++++++++ setup.py | 1 + 2 files changed, 383 insertions(+) create mode 100644 beetsplug/beatport.py diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py new file mode 100644 index 000000000..9abf22c1e --- /dev/null +++ b/beetsplug/beatport.py @@ -0,0 +1,382 @@ +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Adds Beatport release and track search support to the autotagger +""" +import json +import re +from datetime import datetime, timedelta + +from requests_oauthlib import OAuth1Session +from requests_oauthlib.oauth1_session import (TokenRequestDenied, TokenMissing, + VerifierMissing) + +import beets +import beets.ui +from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance +from beets.plugins import BeetsPlugin +from beets.util import confit + + +AUTH_ERRORS = (TokenRequestDenied, TokenMissing, VerifierMissing) +USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) + + +class BeatportAPIError(Exception): + pass + + +class BeatportObject(object): + def __init__(self, data): + self.beatport_id = data['id'] + self.name = unicode(data['name']) + if 'releaseDate' in data: + self.release_date = datetime.strptime(data['releaseDate'], + '%Y-%m-%d') + if 'artists' in data: + self.artists = [(x['id'], unicode(x['name'])) + for x in data['artists']] + if 'genres' in data: + self.genres = [unicode(x['name']) + for x in data['genres']] + + +class BeatportClient(object): + _api_base = 'https://oauth-api.beatport.com' + + def __init__(self, c_key, c_secret, auth_key=None, auth_secret=None): + self.api = OAuth1Session( + client_key=c_key, client_secret=c_secret, + resource_owner_key=auth_key, + resource_owner_secret=auth_secret, + callback_uri='oob') + self.api.headers = {'User-Agent': USER_AGENT} + + def get_authorize_url(self): + self.api.fetch_request_token( + self._make_url('/identity/1/oauth/request-token')) + return self.api.authorization_url( + self._make_url('/identity/1/oauth/authorize')) + + def get_access_token(self, auth_data): + self.api.parse_authorization_response( + "http://beets.io/auth?" + auth_data) + access_data = self.api.fetch_access_token( + self._make_url('/identity/1/oauth/access-token')) + return access_data['oauth_token'], access_data['oauth_token_secret'] + + def search(self, query, release_type='release', details=True): + response = self._get('catalog/3/search', + query=query, perPage=5, + facets=['fieldType:{0}'.format(release_type)]) + for item in response: + if release_type == 'release': + if details: + release = self.get_release(item['id']) + else: + release = BeatportRelease(item) + yield release + elif release_type == 'track': + yield BeatportTrack(item) + + def get_release(self, beatport_id): + response = self._get('/catalog/3/releases', id=beatport_id) + release = BeatportRelease(response[0]) + release.tracks = self.get_release_tracks(beatport_id) + return release + + def get_release_tracks(self, beatport_id): + response = self._get('/catalog/3/tracks', releaseId=beatport_id) + return [BeatportTrack(t) for t in response] + + def get_track(self, beatport_id): + response = self._get('/catalog/3/tracks', id=beatport_id) + return BeatportTrack(response[0]) + + def _make_url(self, endpoint): + if not endpoint.startswith('/'): + endpoint = '/' + endpoint + return self._api_base + endpoint + + def _get(self, endpoint, **kwargs): + try: + response = self.api.get(self._make_url(endpoint), params=kwargs) + except Exception as e: + raise BeatportAPIError("Error connection to Beatport API: {}" + .format(e.message)) + if not response: + raise BeatportAPIError( + "Error {0.status_code} for '{0.request.path_url}" + .format(response)) + return response.json()['results'] + + +class BeatportRelease(BeatportObject): + def __unicode__(self): + if len(self.artists) < 4: + artist_str = ", ".join(x[1] for x in self.artists) + else: + artist_str = "Various Artists" + return u"".format( + artist_str, + self.name, + self.catalog_number, + ) + + def __repr__(self): + return unicode(self).encode('utf8') + + def __init__(self, data): + BeatportObject.__init__(self, data) + if 'catalogNumber' in data: + self.catalog_number = data['catalogNumber'] + if 'label' in data: + self.label_name = data['label']['name'] + if 'category' in data: + self.category = data['category'] + if 'slug' in data: + self.url = "http://beatport.com/release/{0}/{1}".format( + data['slug'], data['id']) + + +class BeatportTrack(BeatportObject): + def __unicode__(self): + artist_str = ", ".join(x[1] for x in self.artists) + return (u"" + .format(artist_str, self.name, self.mix_name)) + + def __repr__(self): + return unicode(self).encode('utf8') + + def __init__(self, data): + BeatportObject.__init__(self, data) + if 'title' in data: + self.title = unicode(data['title']) + if 'mixName' in data: + self.mix_name = unicode(data['mixName']) + self.length = timedelta(milliseconds=data.get('lengthMs', 0) or 0) + if not self.length: + try: + min, sec = data.get('length', '0:0').split(':') + self.length = timedelta(minutes=int(min), seconds=int(sec)) + except ValueError: + pass + if 'slug' in data: + self.url = "http://beatport.com/track/{0}/{1}".format(data['slug'], + data['id']) + + +class BeatportPlugin(BeetsPlugin): + def __init__(self): + super(BeatportPlugin, self).__init__() + self.config.add({ + 'apikey': '57713c3906af6f5def151b33601389176b37b429', + 'apisecret': 'b3fe08c93c80aefd749fe871a16cd2bb32e2b954', + 'tokenfile': 'beatport_token.json', + 'source_weight': 0.5, + }) + self.config['apikey'].redact = True + self.config['apisecret'].redact = True + self.discogs_client = None + self.register_listener('import_begin', self.setup) + + def setup(self, session=None): + c_key = self.config['apikey'].get(unicode) + c_secret = self.config['apisecret'].get(unicode) + + # Get the OAuth token from a file or log in. + try: + with open(self._tokenfile()) as f: + tokendata = json.load(f) + except IOError: + # No token yet. Generate one. + token, secret = self.authenticate(c_key, c_secret) + else: + token = tokendata['token'] + secret = tokendata['secret'] + + self.beatport_api = BeatportClient(c_key, c_secret, token, secret) + + def authenticate(self, c_key, c_secret): + # Get the link for the OAuth page. + auth_client = BeatportClient(c_key, c_secret) + try: + url = auth_client.get_authorize_url() + except AUTH_ERRORS as e: + self._log.debug(u'authentication error: {0}', e) + raise beets.ui.UserError(u'communication with Beatport failed') + + beets.ui.print_(u"To authenticate with Beatport, visit:") + beets.ui.print_(url) + + # Ask for the verifier data and validate it. + data = beets.ui.input_(u"Enter the string displayed in your browser:") + try: + token, secret = auth_client.get_access_token(data) + except AUTH_ERRORS as e: + self._log.debug(u'authentication error: {0}', e) + raise beets.ui.UserError(u'Beatport token request failed') + + # Save the token for later use. + self._log.debug(u'Beatport token {0}, secret {1}', token, secret) + with open(self._tokenfile(), 'w') as f: + json.dump({'token': token, 'secret': secret}, f) + + return token, secret + + def _tokenfile(self): + """Get the path to the JSON file for storing the OAuth token. + """ + return self.config['tokenfile'].get(confit.Filename(in_app_dir=True)) + + def album_distance(self, items, album_info, mapping): + """Returns the beatport source weight and the maximum source weight + for albums. + """ + dist = Distance() + if album_info.data_source == 'Beatport': + dist.add('source', self.config['source_weight'].as_number()) + return dist + + def track_distance(self, item, track_info): + """Returns the beatport source weight and the maximum source weight + for individual tracks. + """ + dist = Distance() + if track_info.data_source == 'Beatport': + dist.add('source', self.config['source_weight'].as_number()) + return dist + + def candidates(self, items, artist, release, va_likely): + """Returns a list of AlbumInfo objects for beatport search results + matching release and artist (if not various). + """ + if va_likely: + query = release + else: + query = '%s %s' % (artist, release) + try: + return self._get_releases(query) + except BeatportAPIError as e: + self._log.debug(u'API Error: {0} (query: {1})', e, query) + return [] + + def item_candidates(self, item, artist, title): + """Returns a list of TrackInfo objects for beatport search results + matching title and artist. + """ + query = '%s %s' % (artist, title) + try: + return self._get_tracks(query) + except BeatportAPIError as e: + self._log.debug(u'API Error: {0} (query: {1})', e, query) + return [] + + def album_for_id(self, release_id): + """Fetches a release by its Beatport ID and returns an AlbumInfo object + or None if the release is not found. + """ + self._log.debug(u'Searching for release {0}', release_id) + match = re.search(r'(^|beatport\.com/release/.+/)(\d+)$', release_id) + if not match: + return None + release = self.client.get_release(match.group(2)) + album = self._get_album_info(release) + return album + + def track_for_id(self, track_id): + """Fetches a track by its Beatport ID and returns a TrackInfo object + or None if the track is not found. + """ + self._log.debug(u'Searching for track {0}', track_id) + match = re.search(r'(^|beatport\.com/track/.+/)(\d+)$', track_id) + if not match: + return None + bp_track = self.client.get_track(match.group(2)) + track = self._get_track_info(bp_track) + return track + + def _get_releases(self, query): + """Returns a list of AlbumInfo objects for a beatport search query. + """ + # Strip non-word characters from query. Things like "!" and "-" can + # cause a query to return no results, even if they match the artist or + # album title. Use `re.UNICODE` flag to avoid stripping non-english + # word characters. + query = re.sub(r'\W+', ' ', query, re.UNICODE) + # Strip medium information from query, Things like "CD1" and "disk 1" + # can also negate an otherwise positive result. + query = re.sub(r'\b(CD|disc)\s*\d+', '', query, re.I) + albums = [self._get_album_info(x) + for x in self.client.search(query).results] + return albums + + def _get_album_info(self, release): + """Returns an AlbumInfo object for a Beatport Release object. + """ + va = len(release.artists) > 3 + artist, artist_id = self._get_artist(release.artists) + if va: + artist = u"Various Artists" + tracks = [self._get_track_info(x, index=idx) + for idx, x in enumerate(release.tracks, 1)] + + return AlbumInfo(album=release.name, album_id=release.beatport_id, + artist=artist, artist_id=artist_id, tracks=tracks, + albumtype=release.category, va=va, + year=release.release_date.year, + month=release.release_date.month, + day=release.release_date.day, + label=release.label_name, + catalognum=release.catalog_number, media=u'Digital', + data_source=u'Beatport', data_url=release.url) + + def _get_track_info(self, track, index=None): + """Returns a TrackInfo object for a Beatport Track object. + """ + title = track.name + if track.mix_name != u"Original Mix": + title += u" ({0})".format(track.mix_name) + artist, artist_id = self._get_artist(track.artists) + length = track.length.total_seconds() + + return TrackInfo(title=title, track_id=track.beatport_id, + artist=artist, artist_id=artist_id, + length=length, index=index, + data_source=u'Beatport', data_url=track.url) + + def _get_artist(self, artists): + """Returns an artist string (all artists) and an artist_id (the main + artist) for a list of Beatport release or track artists. + """ + artist_id = None + bits = [] + for artist in artists: + if not artist_id: + artist_id = artist[0] + name = artist[1] + # Strip disambiguation number. + name = re.sub(r' \(\d+\)$', '', name) + # Move articles to the front. + name = re.sub(r'^(.*?), (a|an|the)$', r'\2 \1', name, flags=re.I) + bits.append(name) + artist = ', '.join(bits).replace(' ,', ',') or None + return artist, artist_id + + def _get_tracks(self, query): + """Returns a list of TrackInfo objects for a Beatport query. + """ + bp_tracks = self.client.search(query, release_type='track').results + tracks = [self._get_track_info(x) for x in bp_tracks] + return tracks diff --git a/setup.py b/setup.py index c0cf15354..03d7c5833 100755 --- a/setup.py +++ b/setup.py @@ -112,6 +112,7 @@ setup( 'fetchart': ['requests'], 'chroma': ['pyacoustid'], 'discogs': ['discogs-client>=2.1.0'], + 'beatport': ['requests-oauthlib>=0.6.1'], 'lastgenre': ['pylast'], 'mpdstats': ['python-mpd2'], 'web': ['flask', 'flask-cors'], From c4835336a5bdfa92d4f577a13a2bcf4bf9256189 Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Tue, 21 Jun 2016 11:20:16 +0200 Subject: [PATCH 1005/2280] Fix PEP8 checks --- beetsplug/beatport.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 9abf22c1e..77f2f3c91 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -14,6 +14,8 @@ """Adds Beatport release and track search support to the autotagger """ +from __future__ import division, absolute_import, print_function + import json import re from datetime import datetime, timedelta From ae0269372ce03a3a9d601dd8a4e87fd41736a5b7 Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Tue, 21 Jun 2016 21:39:25 +0200 Subject: [PATCH 1006/2280] Docstrings for beatport.BeatportClient --- beetsplug/beatport.py | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 77f2f3c91..f2c731469 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -58,6 +58,17 @@ class BeatportClient(object): _api_base = 'https://oauth-api.beatport.com' def __init__(self, c_key, c_secret, auth_key=None, auth_secret=None): + """ Initiate the client with OAuth information. + + For the initial authentication with the backend `auth_key` and + `auth_secret` can be `None`. Use `get_authorize_url` and + `get_access_token` to obtain them for subsequent uses of the API. + + :param c_key: OAuth1 client key + :param c_secret: OAuth1 client secret + :param auth_key: OAuth1 resource owner key + :param auth_secret: OAuth1 resource owner secret + """ self.api = OAuth1Session( client_key=c_key, client_secret=c_secret, resource_owner_key=auth_key, @@ -66,12 +77,35 @@ class BeatportClient(object): self.api.headers = {'User-Agent': USER_AGENT} def get_authorize_url(self): + """ Generate the URL for the user to authorize the application. + + Retrieves a request token from the Beatport API and returns the + corresponding authorization URL on their end that the user has + to visit. + + This is the first step of the initial authorization process with the + API. Once the user has visited the URL, call + :py:method:`get_access_token` with the displayed data to complete + the process. + + :returns: Authorization URL for the user to visit + :rtype: unicode + """ self.api.fetch_request_token( self._make_url('/identity/1/oauth/request-token')) return self.api.authorization_url( self._make_url('/identity/1/oauth/authorize')) def get_access_token(self, auth_data): + """ Obtain the final access token and secret for the API. + + :param auth_data: URL-encoded authorization data as displayed at + the authorization url (obtained via + :py:meth:`get_authorize_url`) after signing in + :type auth_data: unicode + :returns: OAuth resource owner key and secret + :rtype: (unicode, unicode) tuple + """ self.api.parse_authorization_response( "http://beets.io/auth?" + auth_data) access_data = self.api.fetch_access_token( @@ -79,6 +113,20 @@ class BeatportClient(object): return access_data['oauth_token'], access_data['oauth_token_secret'] def search(self, query, release_type='release', details=True): + """ Perform a search of the Beatport catalogue. + + :param query: Query string + :param release_type: Type of releases to search for, can be + 'release' or 'track' + :param details: Retrieve additional information about the + search results. Currently this will fetch + the tracklist for releases and do nothing for + tracks + :returns: Search results + :rtype: generator that yields + py:class:`BeatportRelease` or + :py:class:`BeatportTrack` + """ response = self._get('catalog/3/search', query=query, perPage=5, facets=['fieldType:{0}'.format(release_type)]) @@ -93,25 +141,49 @@ class BeatportClient(object): yield BeatportTrack(item) def get_release(self, beatport_id): + """ Get information about a single release. + + :param beatport_id: Beatport ID of the release + :returns: The matching release + :rtype: :py:class:`BeatportRelease` + """ response = self._get('/catalog/3/releases', id=beatport_id) release = BeatportRelease(response[0]) release.tracks = self.get_release_tracks(beatport_id) return release def get_release_tracks(self, beatport_id): + """ Get all tracks for a given release. + + :param beatport_id: Beatport ID of the release + :returns: Tracks in the matching release + :rtype: list of :py:class:`BeatportTrack` + """ response = self._get('/catalog/3/tracks', releaseId=beatport_id) return [BeatportTrack(t) for t in response] def get_track(self, beatport_id): + """ Get information about a single track. + + :param beatport_id: Beatport ID of the track + :returns: The matching track + :rtype: :py:class:`BeatportTrack` + """ response = self._get('/catalog/3/tracks', id=beatport_id) return BeatportTrack(response[0]) def _make_url(self, endpoint): + """ Get complete URL for a given API endpoint. """ if not endpoint.startswith('/'): endpoint = '/' + endpoint return self._api_base + endpoint def _get(self, endpoint, **kwargs): + """ Perform a GET request on a given API endpoint. + + Automatically extracts result data from the response and converts HTTP + exceptions into :py:class:`BeatportAPIError` objects. + """ try: response = self.api.get(self._make_url(endpoint), params=kwargs) except Exception as e: From 00bce6de2c490b73a7be7c5e173a021cb2d355e8 Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Tue, 21 Jun 2016 21:46:53 +0200 Subject: [PATCH 1007/2280] Documentation for beatport plugin --- docs/plugins/beatport.rst | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs/plugins/beatport.rst diff --git a/docs/plugins/beatport.rst b/docs/plugins/beatport.rst new file mode 100644 index 000000000..da77cd4cd --- /dev/null +++ b/docs/plugins/beatport.rst @@ -0,0 +1,36 @@ +Beatport Plugin +=============== + +The ``beatport`` plugin adds support for querying the `Beatport`_ catalogue +during the autotagging process. This can potentially be helpful for users +whose collection includes a lot of diverse electronic music releases, for which +both MusicBrainz and (to a lesser degree) Discogs show no matches. + +Installation +------------ + +To use the ``beatport`` plugin, first enable it in your configuration (see +:ref:`using-plugins`). Then, install the `requests`_ and `requests_oauthlib`_ +libraries (which we need for querying and authorizing with the Beatport API) +by typing:: + + pip install requests requests_oauthlib + +You will also need to register for a `Beatport`_ account. The first time you +run the :ref:`import-cmd` command after enabling the plugin, it will ask you +to authorize with Beatport by visiting the site in a browser. On the site +you will be asked to enter your username and password to authorize beets +to query the Beatport API. You will then be displayed with a single line of +text that you should paste into your terminal. This will store the +authentication data for subsequent runs and you will not be required to +repeat the above steps. + +Matches from Beatport should now show up alongside matches +from MusicBrainz and other sources. + +If you have a Beatport ID or a URL for a release or track you want to tag, you +can just enter one of the two at the "enter Id" prompt in the importer. + +.. _requests: http://docs.python-requests.org/en/latest/ +.. _requests_oauthlib: https://github.com/requests/requests-oauthlib +.. _Beatport: http://beatport.com From 7f98b456fc1727a5137c5824ec36f1f712aece8c Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Tue, 21 Jun 2016 22:22:18 +0200 Subject: [PATCH 1008/2280] Include beatport docs in plugin index --- docs/plugins/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 39267a4b2..58464060b 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -33,6 +33,7 @@ Each plugin has its own set of options that can be defined in a section bearing acousticbrainz badfiles + beatport bpd bpm bucket From 351b6f8c9dcbda124e464432bb663de863de1ed2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Jun 2016 14:29:14 -0700 Subject: [PATCH 1009/2280] Remove raw Unicode literals (fix #2069) PEP 414 didn't add `ur"..."` literals to Python 3. So for hybrid 2/3 compatibility, these had to be replaced with ordinary Unicode string literals. This was only painful for one string; the others were only raw strings by convention. (All were regexes.) --- beets/autotag/mb.py | 2 +- beetsplug/replaygain.py | 6 +++--- test/test_ui.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index e64da8d5c..2e8109fb9 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -376,7 +376,7 @@ def _parse_id(s): no ID can be found, return None. """ # Find the first thing that looks like a UUID/MBID. - match = re.search(ur'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) + match = re.search(u'[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}', s) if match: return match.group() diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index c58a1db9b..a1e573361 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -222,9 +222,9 @@ class Bs1770gainBackend(Backend): out = [] data = text.decode('utf8', errors='ignore') regex = re.compile( - ur'(\s{2,2}\[\d+\/\d+\].*?|\[ALBUM\].*?)' - '(?=\s{2,2}\[\d+\/\d+\]|\s{2,2}\[ALBUM\]' - ':|done\.\s)', re.DOTALL | re.UNICODE) + u'(\\s{2,2}\\[\\d+\\/\\d+\\].*?|\\[ALBUM\\].*?)' + '(?=\\s{2,2}\\[\\d+\\/\\d+\\]|\\s{2,2}\\[ALBUM\\]' + ':|done\\.\\s)', re.DOTALL | re.UNICODE) results = re.findall(regex, data) for parts in results[0:num_lines]: part = parts.split(b'\n') diff --git a/test/test_ui.py b/test/test_ui.py index 0ca4f7115..e52e7eba9 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -760,7 +760,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements - self.assertEqual(replacements, [(re.compile(ur'[xy]'), 'z')]) + self.assertEqual(replacements, [(re.compile(u'[xy]'), 'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: @@ -769,8 +769,8 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['test']) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ - (re.compile(ur'[xy]'), u'z'), - (re.compile(ur'foo'), u'bar'), + (re.compile(u'[xy]'), u'z'), + (re.compile(u'foo'), u'bar'), ]) def test_cli_config_option(self): From 829c4318f0c40872f0b1b4bd51a5ec10dad53ce1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Jun 2016 14:35:44 -0700 Subject: [PATCH 1010/2280] Changelog for #2067 (revived Beatport plugin) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 6f0333582..c4c0ce581 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,9 @@ New features: duplicate albums or tracks treated in import task. :bug:`185` * :doc:`/plugins/bpd`: The plugin now uses the modern GStreamer 1.0 instead of the old 0.10. Thanks to :user:`philippbeckmann`. :bug:`2057` :bug:`2062` +* :doc:`/plugins/beatport`: This metadata source plugin has arisen from the + dead! It now works with Beatport's new OAuth-based API. Thanks to + :user:`jbaiter`. :bug:`1989` :bug:`2067` Some fixes for Windows: From 5909c9ee89725de02176f5b9c8424b0b0cddb26a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Jun 2016 15:02:05 -0700 Subject: [PATCH 1011/2280] Fix #2051: don't try to sort None I found the point in the test harnesses where None was introduced as a value for `TrackInfo.index`. Just using zero works fine. --- test/test_importer.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 93a034ee6..a1b0cd895 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -98,7 +98,8 @@ class AutotagStub(object): track_id=u'trackid', artist=artist.replace('Tag', 'Applied'), artist_id=u'artistid', - length=1 + length=1, + index=0, ) def album_for_id(self, mbid): @@ -112,7 +113,8 @@ class AutotagStub(object): title=u'Applied Title %d' % number, track_id=u'match %d' % number, artist=artist, - length=1 + length=1, + index=0, ) def _make_album_match(self, artist, album, tracks, distance=0, missing=0): @@ -1072,6 +1074,7 @@ def test_album_info(): track_info = TrackInfo( title=u'new title', track_id=u'trackid', + index=0, ) album_info = AlbumInfo( artist=u'artist', @@ -1189,6 +1192,7 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, artist=u'artist', title=u'title', track_id=u'new trackid', + index=0, ) self.match_track.return_value = iter([track_info]) From 133c82b1ab896cbe49614ccc9d4ed7e476c37076 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Jun 2016 15:15:24 -0700 Subject: [PATCH 1012/2280] Fix #2063: properly decode format CLI argument --- beets/ui/__init__.py | 9 ++++++++- docs/changelog.rst | 2 ++ test/test_ui.py | 9 +++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index a2739189e..80a2abfea 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -804,7 +804,14 @@ class CommonOptionsParser(optparse.OptionParser, object): if store_true: setattr(parser.values, option.dest, True) - value = fmt or value and unicode(value) or '' + # Use the explicitly specified format, or the string from the option. + if fmt: + value = fmt + elif value: + value, = decargs([value]) + else: + value = u'' + parser.values.format = value if target: config[target._format_config_key].set(value) diff --git a/docs/changelog.rst b/docs/changelog.rst index c4c0ce581..aabc10b96 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -37,6 +37,8 @@ Fixes: installations. Thanks to :user:`bismark`. :bug:`2038` * Fix a crash introduced in the previous version when the standard input was connected to a Unix pipe. :bug:`2041` +* Fix a crash when specifying non-ASCII format strings on the command line + with the ``-f`` option to many commands. :bug:`2063` 1.3.18 (May 31, 2016) --------------------- diff --git a/test/test_ui.py b/test/test_ui.py index e52e7eba9..d14febbff 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1184,12 +1184,17 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): self.assertEqual(l, u'xxx\n') def test_format_option(self): - l = self.run_with_output(u'ls', u'-f', '$artist') + l = self.run_with_output(u'ls', u'-f', u'$artist') self.assertEqual(l, u'the artist\n') - l = self.run_with_output(u'ls', u'-a', u'-f', '$albumartist') + l = self.run_with_output(u'ls', u'-a', u'-f', u'$albumartist') self.assertEqual(l, u'the album artist\n') + def test_format_option_unicode(self): + l = self.run_with_output(b'ls', b'-f', + u'caf\xe9'.encode(ui._arg_encoding())) + self.assertEqual(l, u'caf\xe9\n') + def test_root_format_option(self): l = self.run_with_output(u'--format-item', u'$artist', u'--format-album', u'foo', u'ls') From 4c98edc58829d77e110f388cc8887df767a318a6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 21 Jun 2016 23:44:24 -0400 Subject: [PATCH 1013/2280] check for encoding attr before set in test_helper This makes it work equivalently in py2 and py3 --- test/helper.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/helper.py b/test/helper.py index 9335a7d6b..067509221 100644 --- a/test/helper.py +++ b/test/helper.py @@ -89,7 +89,8 @@ def control_stdin(input=None): """ org = sys.stdin sys.stdin = StringIO(input) - sys.stdin.encoding = 'utf8' + if hasattr(sys.stdin, 'encoding'): + sys.stdin.encoding = 'utf8' try: yield sys.stdin finally: @@ -108,7 +109,8 @@ def capture_stdout(): """ org = sys.stdout sys.stdout = capture = StringIO() - sys.stdout.encoding = 'utf8' + if not hasattr(sys.stdout, 'encoding'): + sys.stdout.encoding = 'utf8' try: yield sys.stdout finally: From 5b590f75f0580ac08a17ef0d00535242a3e7a362 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 22 Jun 2016 00:11:48 -0400 Subject: [PATCH 1014/2280] use as_string to get str results from unidecode --- beets/autotag/hooks.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 0d9030b2c..0b8a6f6bf 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -23,6 +23,7 @@ import re from beets import logging from beets import plugins from beets import config +from beets.util import as_string from beets.autotag import mb from jellyfish import levenshtein_distance from unidecode import unidecode @@ -206,8 +207,8 @@ def _string_dist_basic(str1, str2): """ assert isinstance(str1, unicode) assert isinstance(str2, unicode) - str1 = unidecode(str1).decode('ascii') - str2 = unidecode(str2).decode('ascii') + str1 = as_string(unidecode(str1)) + str2 = as_string(unidecode(str2)) str1 = re.sub(r'[^a-z0-9]', '', str1.lower()) str2 = re.sub(r'[^a-z0-9]', '', str2.lower()) if not str1 and not str2: From ab1e3ce87cb136e0e9fcb483458926ba6b1a524f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 22 Jun 2016 00:12:15 -0400 Subject: [PATCH 1015/2280] use as_string to get str result from root_parser name --- beets/ui/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 80a2abfea..a5fb10ba0 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -38,7 +38,7 @@ from beets import plugins from beets import util from beets.util.functemplate import Template from beets import config -from beets.util import confit +from beets.util import confit, as_string from beets.autotag import mb from beets.dbcore import query as db_query @@ -923,7 +923,7 @@ class Subcommand(object): def root_parser(self, root_parser): self._root_parser = root_parser self.parser.prog = '{0} {1}'.format( - root_parser.get_prog_name().decode('utf8'), self.name) + as_string(root_parser.get_prog_name()), self.name) class SubcommandsOptionParser(CommonOptionsParser): From 0b17666b55f498e5f5b74bb5021da7c93b577690 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 22 Jun 2016 00:51:10 -0400 Subject: [PATCH 1016/2280] Revert "check for encoding attr before set in test_helper" This doesn't actually help us, since the property is there, but not writeable This reverts commit 4c98edc58829d77e110f388cc8887df767a318a6. --- test/helper.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/test/helper.py b/test/helper.py index 067509221..9335a7d6b 100644 --- a/test/helper.py +++ b/test/helper.py @@ -89,8 +89,7 @@ def control_stdin(input=None): """ org = sys.stdin sys.stdin = StringIO(input) - if hasattr(sys.stdin, 'encoding'): - sys.stdin.encoding = 'utf8' + sys.stdin.encoding = 'utf8' try: yield sys.stdin finally: @@ -109,8 +108,7 @@ def capture_stdout(): """ org = sys.stdout sys.stdout = capture = StringIO() - if not hasattr(sys.stdout, 'encoding'): - sys.stdout.encoding = 'utf8' + sys.stdout.encoding = 'utf8' try: yield sys.stdout finally: From f07e6265ee59b5410da2678f46974a57d20edcf3 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 22 Jun 2016 13:02:15 +0200 Subject: [PATCH 1017/2280] Changelog for the Content-Type based image extension detection --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 6f0333582..567927a1d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -34,6 +34,10 @@ Fixes: installations. Thanks to :user:`bismark`. :bug:`2038` * Fix a crash introduced in the previous version when the standard input was connected to a Unix pipe. :bug:`2041` +* :doc:`/plugins/fetchart`: Determine the file extension for downloaded images + based on the ``Content-Type`` header instead of hardcoding it to .jpg. + Reported in :bug:`2053`, which for now it does not fix due to + server-side issues, though. 1.3.18 (May 31, 2016) --------------------- From 2836877c35295b711a6e2e55ecf2abecb19b0287 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 01:06:15 -0400 Subject: [PATCH 1018/2280] use as_string to get mediafile properties as str --- beets/mediafile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index e80cd65d9..556b41bb8 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -58,7 +58,7 @@ import traceback import enum from beets import logging -from beets.util import displayable_path, syspath +from beets.util import displayable_path, syspath, as_string __all__ = ['UnreadableFileError', 'FileTypeError', 'MediaFile'] @@ -1470,7 +1470,7 @@ class MediaFile(object): """ for property, descriptor in cls.__dict__.items(): if isinstance(descriptor, MediaField): - yield property.decode('utf8') + yield as_string(property) @classmethod def _field_sort_name(cls, name): From c7a4d261e213ec2dbe93e3cdfd5ce1dc30c18189 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 01:29:46 -0400 Subject: [PATCH 1019/2280] fix a comment typo in ui/__init__.py --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index a5fb10ba0..af7fe9aff 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -199,7 +199,7 @@ def input_(prompt=None): input cursor. """ # raw_input incorrectly sends prompts to stderr, not stdout, so we - # use print() explicitly to display prompts. + # use print_() explicitly to display prompts. # http://bugs.python.org/issue1927 if prompt: print_(prompt, end=' ') From ea02269dee6309f15f017bb721a2c7a05abeee0e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 02:29:49 -0400 Subject: [PATCH 1020/2280] remove ext encode from fetchart (py3 fix for #2068) --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index e10a35270..a2ce1661d 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -611,7 +611,7 @@ class FileSystem(LocalArtSource): for fn in os.listdir(syspath(path)): fn = bytestring_path(fn) for ext in IMAGE_EXTENSIONS: - if fn.lower().endswith(b'.' + ext.encode('utf8')) and \ + if fn.lower().endswith(b'.' + ext) and \ os.path.isfile(syspath(os.path.join(path, fn))): images.append(fn) From ed2580d5b1e83269a507428f4f3dd0a4e006488e Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Thu, 23 Jun 2016 08:51:26 +0200 Subject: [PATCH 1021/2280] Fix bugs in beatport plugin (#2076) * Fix naming bug * Fix another minor bug * Remove debugger statement * Another fix for developer clumsiness in beatport plugin * Fix typo in error description --- beetsplug/beatport.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index f2c731469..c1425ad9e 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -187,7 +187,7 @@ class BeatportClient(object): try: response = self.api.get(self._make_url(endpoint), params=kwargs) except Exception as e: - raise BeatportAPIError("Error connection to Beatport API: {}" + raise BeatportAPIError("Error connecting to Beatport API: {}" .format(e.message)) if not response: raise BeatportAPIError( @@ -262,7 +262,7 @@ class BeatportPlugin(BeetsPlugin): }) self.config['apikey'].redact = True self.config['apisecret'].redact = True - self.discogs_client = None + self.client = None self.register_listener('import_begin', self.setup) def setup(self, session=None): @@ -280,7 +280,7 @@ class BeatportPlugin(BeetsPlugin): token = tokendata['token'] secret = tokendata['secret'] - self.beatport_api = BeatportClient(c_key, c_secret, token, secret) + self.client = BeatportClient(c_key, c_secret, token, secret) def authenticate(self, c_key, c_secret): # Get the link for the OAuth page. @@ -393,7 +393,7 @@ class BeatportPlugin(BeetsPlugin): # can also negate an otherwise positive result. query = re.sub(r'\b(CD|disc)\s*\d+', '', query, re.I) albums = [self._get_album_info(x) - for x in self.client.search(query).results] + for x in self.client.search(query)] return albums def _get_album_info(self, release): @@ -451,6 +451,6 @@ class BeatportPlugin(BeetsPlugin): def _get_tracks(self, query): """Returns a list of TrackInfo objects for a Beatport query. """ - bp_tracks = self.client.search(query, release_type='track').results + bp_tracks = self.client.search(query, release_type='track') tracks = [self._get_track_info(x) for x in bp_tracks] return tracks From cc6465d31ef1c098c71e70c7ab1a7874ceb8c029 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 04:35:26 -0400 Subject: [PATCH 1022/2280] convert Item.destination() fragment to a string --- beets/library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index b9d9d4ffc..3450a35a8 100644 --- a/beets/library.py +++ b/beets/library.py @@ -839,7 +839,7 @@ class Item(LibModel): ) if fragment: - return subpath + return util.as_string(subpath) else: return normpath(os.path.join(basedir, subpath)) From 695ac781c2a83752bdbb5b48babe998acf7daa93 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:19:35 -0400 Subject: [PATCH 1023/2280] add six as a new dependency for beets --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 03d7c5833..12c6e06ad 100755 --- a/setup.py +++ b/setup.py @@ -86,6 +86,7 @@ setup( }, install_requires=[ + 'six', 'enum34>=1.0.4', 'mutagen>=1.27', 'munkres', From a5d39d3f5c2accb90d5e7535a0f2f2ef9527d2b6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:23:28 -0400 Subject: [PATCH 1024/2280] use six.integer_types in isinstance checks --- beets/library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 3450a35a8..f268694cb 100644 --- a/beets/library.py +++ b/beets/library.py @@ -22,6 +22,7 @@ import sys import unicodedata import time import re +import six from unidecode import unidecode from beets import logging @@ -565,7 +566,7 @@ class Item(LibModel): for key in self._media_fields: value = getattr(mediafile, key) - if isinstance(value, (int, long)): + if isinstance(value, six.integer_types): if value.bit_length() > 63: value = 0 self[key] = value From c188a4c5062c94ef415e1bb8242d2941d99ade80 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:27:54 -0400 Subject: [PATCH 1025/2280] use queue from six.moves --- beets/util/pipeline.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index b5f777336..648d11b70 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -34,7 +34,7 @@ in place of any single coroutine. from __future__ import division, absolute_import, print_function -import Queue +from six.moves import queue from threading import Thread, Lock import sys @@ -75,13 +75,13 @@ def _invalidate_queue(q, val=None, sync=True): q.mutex.release() -class CountedQueue(Queue.Queue): +class CountedQueue(queue.Queue): """A queue that keeps track of the number of threads that are still feeding into it. The queue is poisoned when all threads are finished with the queue. """ def __init__(self, maxsize=0): - Queue.Queue.__init__(self, maxsize) + queue.Queue.__init__(self, maxsize) self.nthreads = 0 self.poisoned = False From 7713be4c0f09b1af0aa8a757d4d26fc21fbb0ccf Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:33:10 -0400 Subject: [PATCH 1026/2280] use http_client (really http.client) from six.moves --- beetsplug/discogs.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 85010d3a2..4252900e0 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -27,12 +27,12 @@ from beets.util import confit from discogs_client import Release, Client from discogs_client.exceptions import DiscogsAPIError from requests.exceptions import ConnectionError +from six.moves import http_client import beets import re import time import json import socket -import httplib import os @@ -43,7 +43,7 @@ urllib3_logger.setLevel(logging.CRITICAL) USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) # Exceptions that discogs_client should really handle but does not. -CONNECTION_ERRORS = (ConnectionError, socket.error, httplib.HTTPException, +CONNECTION_ERRORS = (ConnectionError, socket.error, http_client.HTTPException, ValueError, # JSON decoding raises a ValueError. DiscogsAPIError) From 129e140015baace43771af82a7a08fdf501f75d0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:34:22 -0400 Subject: [PATCH 1027/2280] use html_parser (really html.parser) from six.moves --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 1bce066c9..cb455ab36 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -26,7 +26,7 @@ import requests import unicodedata import urllib import warnings -from HTMLParser import HTMLParseError +from six.moves.html_parser import HTMLParseError try: from bs4 import SoupStrainer, BeautifulSoup From 1f8fe0f9a6e3569050e1ea1fe971de281ed05d87 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 00:34:44 -0400 Subject: [PATCH 1028/2280] use _thread from six.moves --- beetsplug/bpd/gstplayer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 326739a7a..7d29764cb 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -21,7 +21,7 @@ from __future__ import division, absolute_import, print_function import sys import time -import thread +from six.moves import _thread import os import copy import urllib @@ -164,7 +164,7 @@ class GstPlayer(object): loop = GLib.MainLoop() loop.run() - thread.start_new_thread(start, ()) + _thread.start_new_thread(start, ()) def time(self): """Returns a tuple containing (position, length) where both From 4649226b9bca3718d38974784b24fe4567b70b1a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 01:17:36 -0400 Subject: [PATCH 1029/2280] use urllib from six.moves --- beets/autotag/mb.py | 2 +- beets/util/artresizer.py | 5 ++--- beetsplug/bpd/gstplayer.py | 4 ++-- beetsplug/embyupdate.py | 4 ++-- beetsplug/lyrics.py | 12 ++++++------ beetsplug/metasync/itunes.py | 6 +++--- beetsplug/plexupdate.py | 3 +-- test/test_spotify.py | 4 ++-- 8 files changed, 19 insertions(+), 21 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 2e8109fb9..4df0187e4 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -20,7 +20,7 @@ from __future__ import division, absolute_import, print_function import musicbrainzngs import re import traceback -from urlparse import urljoin +from six.moves.urllib.parse import urljoin from beets import logging import beets.autotag.hooks diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 8f7ae7514..8468a6ccc 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -18,12 +18,11 @@ public resizing proxy if neither is available. """ from __future__ import division, absolute_import, print_function -import urllib import subprocess import os import re from tempfile import NamedTemporaryFile - +from six.moves.urllib.parse import urlencode from beets import logging from beets import util @@ -41,7 +40,7 @@ def resize_url(url, maxwidth): """Return a proxied image URL that resizes the original image to maxwidth (preserving aspect ratio). """ - return '{0}?{1}'.format(PROXY_URL, urllib.urlencode({ + return '{0}?{1}'.format(PROXY_URL, urlencode({ 'url': url.replace('http://', ''), 'w': bytes(maxwidth), })) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 7d29764cb..e90a5a44e 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -24,7 +24,7 @@ import time from six.moves import _thread import os import copy -import urllib +from six.moves import urllib from beets import ui import gi @@ -130,7 +130,7 @@ class GstPlayer(object): self.player.set_state(Gst.State.NULL) if isinstance(path, unicode): path = path.encode('utf8') - uri = 'file://' + urllib.quote(path) + uri = 'file://' + urllib.parse.quote(path) self.player.set_property("uri", uri) self.player.set_state(Gst.State.PLAYING) self.playing = True diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 1237762fe..73fa3dcc3 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -12,8 +12,8 @@ from __future__ import division, absolute_import, print_function from beets import config from beets.plugins import BeetsPlugin -from urllib import urlencode -from urlparse import urljoin, parse_qs, urlsplit, urlunsplit +from six.moves.urllib.parse import urlencode +from six.moves.urllib.parse import urljoin, parse_qs, urlsplit, urlunsplit import hashlib import requests diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index cb455ab36..f7bc674fb 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -24,9 +24,9 @@ import json import re import requests import unicodedata -import urllib import warnings from six.moves.html_parser import HTMLParseError +from six.moves import urllib try: from bs4 import SoupStrainer, BeautifulSoup @@ -181,7 +181,7 @@ class Backend(object): for char, repl in URL_CHARACTERS.items(): s = s.replace(char, repl) s = s.encode('utf8', 'ignore') - return urllib.quote(s) + return urllib.parse.quote(s) def build_url(self, artist, title): return self.URL_PATTERN % (self._encode(artist.title()), @@ -256,7 +256,7 @@ class Genius(Backend): def search_genius(self, artist, title): query = u"%s %s" % (artist, title) url = u'https://api.genius.com/search?q=%s' \ - % (urllib.quote(query.encode('utf8'))) + % (urllib.parse.quote(query.encode('utf8'))) self._log.debug(u'genius: requesting search {}', url) try: @@ -542,9 +542,9 @@ class Google(Backend): query = u"%s %s" % (artist, title) url = u'https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s' \ % (self.api_key, self.engine_id, - urllib.quote(query.encode('utf8'))) + urllib.parse.quote(query.encode('utf8'))) - data = urllib.urlopen(url) + data = urllib.request.urlopen(url) data = json.load(data) if 'error' in data: reason = data['error']['errors'][0]['reason'] @@ -643,7 +643,7 @@ class LyricsPlugin(plugins.BeetsPlugin): oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13' oauth_token = json.loads(requests.post( oauth_url, - data=urllib.urlencode(params)).content) + data=urllib.parse.urlencode(params)).content) if 'access_token' in oauth_token: return "Bearer " + oauth_token['access_token'] else: diff --git a/beetsplug/metasync/itunes.py b/beetsplug/metasync/itunes.py index a62746848..17ab1637f 100644 --- a/beetsplug/metasync/itunes.py +++ b/beetsplug/metasync/itunes.py @@ -23,8 +23,8 @@ import os import shutil import tempfile import plistlib -import urllib -from urlparse import urlparse + +from six.moves.urllib.parse import urlparse, unquote from time import mktime from beets import util @@ -57,7 +57,7 @@ def _norm_itunes_path(path): # E.g., '\\G:\\Music\\bar' needs to be stripped to 'G:\\Music\\bar' return util.bytestring_path(os.path.normpath( - urllib.unquote(urlparse(path).path)).lstrip('\\')).lower() + unquote(urlparse(path).path)).lstrip('\\')).lower() class Itunes(MetaSource): diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index ef50fde73..7dbc8b018 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -12,9 +12,8 @@ Put something like the following in your config.yaml to configure: from __future__ import division, absolute_import, print_function import requests -from urlparse import urljoin -from urllib import urlencode import xml.etree.ElementTree as ET +from six.moves.urllib.parse import urljoin, urlencode from beets import config from beets.plugins import BeetsPlugin diff --git a/test/test_spotify.py b/test/test_spotify.py index 721d4f953..20101d76c 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -13,7 +13,7 @@ from beets import config from beets.library import Item from beetsplug import spotify from test.helper import TestHelper -import urlparse +from six.moves.urllib.parse import parse_qs, urlparse class ArgumentsMock(object): @@ -25,7 +25,7 @@ class ArgumentsMock(object): def _params(url): """Get the query parameters from a URL.""" - return urlparse.parse_qs(urlparse.urlparse(url).query) + return parse_qs(urlparse(url).query) class SpotifyPluginTest(_common.TestCase, TestHelper): From 1f8e08d168c5abfd08090f8bf77574de14e6c4d7 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 01:37:17 -0400 Subject: [PATCH 1030/2280] replace raw_input with input from six.moves --- beets/ui/__init__.py | 5 +++-- beetsplug/bpm.py | 3 ++- docs/faq.rst | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index af7fe9aff..9cebf7a28 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -31,6 +31,7 @@ import re import struct import traceback import os.path +from six.moves import input from beets import logging from beets import library @@ -193,7 +194,7 @@ def should_move(move_opt=None): # Input prompts. def input_(prompt=None): - """Like `raw_input`, but decodes the result to a Unicode string. + """Like `input`, but decodes the result to a Unicode string. Raises a UserError if stdin is not available. The prompt is sent to stdout rather than stderr. A printed between the prompt and the input cursor. @@ -205,7 +206,7 @@ def input_(prompt=None): print_(prompt, end=' ') try: - resp = raw_input() + resp = input() except EOFError: raise UserError(u'stdin stream ended while input required') diff --git a/beetsplug/bpm.py b/beetsplug/bpm.py index ba284c042..89424f30e 100644 --- a/beetsplug/bpm.py +++ b/beetsplug/bpm.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import time +from six.moves import input from beets import ui from beets.plugins import BeetsPlugin @@ -31,7 +32,7 @@ def bpm(max_strokes): dt = [] for i in range(max_strokes): # Press enter to the rhythm... - s = raw_input() + s = input() if s == '': t1 = time.time() # Only start measuring at the second stroke diff --git a/docs/faq.rst b/docs/faq.rst index 974b0dce6..ff74a5350 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -289,7 +289,7 @@ Also note that beets may take some time to quit after ^C is typed; it tries to clean up after itself briefly even when canceled. (For developers: this is because the UI thread is blocking on -``raw_input`` and cannot be interrupted by the main thread, which is +``input`` and cannot be interrupted by the main thread, which is trying to close all pipeline stages in the exception handler by setting a flag. There is no simple way to remedy this.) From 31cca684f2dff365b5dbc5b6b4af0ff16831a635 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 02:46:18 -0400 Subject: [PATCH 1031/2280] replace itertools.izip with zip from six.moves --- beetsplug/bucket.py | 5 +++-- beetsplug/replaygain.py | 5 ++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/bucket.py b/beetsplug/bucket.py index 7ce0d0d43..c4be2a3df 100644 --- a/beetsplug/bucket.py +++ b/beetsplug/bucket.py @@ -21,7 +21,8 @@ from __future__ import division, absolute_import, print_function from datetime import datetime import re import string -from itertools import tee, izip +from six.moves import zip +from itertools import tee from beets import plugins, ui @@ -37,7 +38,7 @@ def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) - return izip(a, b) + return zip(a, b) def span_from_str(span_str): diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index a1e573361..e06407037 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -18,10 +18,10 @@ from __future__ import division, absolute_import, print_function import subprocess import os import collections -import itertools import sys import warnings import re +from six.moves import zip from beets import logging from beets import ui @@ -883,8 +883,7 @@ class ReplayGainPlugin(BeetsPlugin): ) self.store_album_gain(album, album_gain.album_gain) - for item, track_gain in itertools.izip(album.items(), - album_gain.track_gains): + for item, track_gain in zip(album.items(), album_gain.track_gains): self.store_track_gain(item, track_gain) if write: item.try_write() From 8e682f14a13f0bb277ac2c929d4bc44fa5df7ef1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 02:48:48 -0400 Subject: [PATCH 1032/2280] replace xrange with range from six.moves --- beetsplug/lastimport.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 2d8cc7008..e31863da7 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -15,6 +15,7 @@ from __future__ import division, absolute_import, print_function +from six.moves import range import pylast from pylast import TopItem, _extract, _number from beets import ui @@ -192,7 +193,7 @@ def process_tracks(lib, tracks, log): total_fails = 0 log.info(u'Received {0} tracks in this page, processing...', total) - for num in xrange(0, total): + for num in range(0, total): song = None trackid = tracks[num]['mbid'].strip() artist = tracks[num]['artist'].get('name', '').strip() From 5f4678e3e8e8bce7287476c70ceaf779e02c398c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 21 Jun 2016 01:17:25 -0400 Subject: [PATCH 1033/2280] use StringIO from six --- test/helper.py | 2 +- test/test_importer.py | 6 +++--- test/test_logging.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/helper.py b/test/helper.py index 9335a7d6b..d2fe5cc81 100644 --- a/test/helper.py +++ b/test/helper.py @@ -40,7 +40,7 @@ import shutil import subprocess from tempfile import mkdtemp, mkstemp from contextlib import contextmanager -from StringIO import StringIO +from six import StringIO from enum import Enum import beets diff --git a/test/test_importer.py b/test/test_importer.py index a1b0cd895..cd5756b1d 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -20,9 +20,9 @@ from __future__ import division, absolute_import, print_function import os import re import shutil -import StringIO import unicodedata import sys +from six import StringIO from tempfile import mkstemp from zipfile import ZipFile from tarfile import TarFile @@ -1250,14 +1250,14 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, class TagLogTest(_common.TestCase): def test_tag_log_line(self): - sio = StringIO.StringIO() + sio = StringIO() handler = logging.StreamHandler(sio) session = _common.import_session(loghandler=handler) session.tag_log('status', 'path') self.assertIn('status path', sio.getvalue()) def test_tag_log_unicode(self): - sio = StringIO.StringIO() + sio = StringIO() handler = logging.StreamHandler(sio) session = _common.import_session(loghandler=handler) session.tag_log('status', u'caf\xe9') # send unicode diff --git a/test/test_logging.py b/test/test_logging.py index 19d9b0e1e..2de8a3ceb 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -6,7 +6,7 @@ from __future__ import division, absolute_import, print_function import sys import threading import logging as log -from StringIO import StringIO +from six import StringIO import beets.logging as blog from beets import plugins, ui From 7b66dfec4bcc47c8c27d1e34ce26385c56a78e3c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 03:15:30 -0400 Subject: [PATCH 1034/2280] use renamed test assertions from six --- test/test_dbcore.py | 9 +++++---- test/test_mediafile.py | 9 +++++---- test/test_web.py | 8 +++++--- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index bd51aea32..67a96e4f2 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function import os import shutil import sqlite3 +from six import assertRaisesRegex from test import _common from test._common import unittest @@ -298,9 +299,9 @@ class ModelTest(unittest.TestCase): self.assertNotIn('flex_field', model2) def test_check_db_fails(self): - with self.assertRaisesRegexp(ValueError, 'no database'): + with assertRaisesRegex(self, ValueError, 'no database'): dbcore.Model()._check_db() - with self.assertRaisesRegexp(ValueError, 'no id'): + with assertRaisesRegex(self, ValueError, 'no id'): TestModel1(self.db)._check_db() dbcore.Model(self.db)._check_db(need_id=False) @@ -312,7 +313,7 @@ class ModelTest(unittest.TestCase): def test_computed_field(self): model = TestModelWithGetters() self.assertEqual(model.aComputedField, 'thing') - with self.assertRaisesRegexp(KeyError, u'computed field .+ deleted'): + with assertRaisesRegex(self, KeyError, u'computed field .+ deleted'): del model.aComputedField def test_items(self): @@ -328,7 +329,7 @@ class ModelTest(unittest.TestCase): model._db def test_parse_nonstring(self): - with self.assertRaisesRegexp(TypeError, u"must be a string"): + with assertRaisesRegex(self, TypeError, u"must be a string"): dbcore.Model._parse(None, 42) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index e2fdd9fce..2405e7fd3 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -23,6 +23,7 @@ import shutil import tempfile import datetime import time +from six import assertCountEqual from test import _common from test._common import unittest @@ -268,7 +269,7 @@ class GenreListTestMixin(object): def test_read_genre_list(self): mediafile = self._mediafile_fixture('full') - self.assertItemsEqual(mediafile.genres, ['the genre']) + assertCountEqual(self, mediafile.genres, ['the genre']) def test_write_genre_list(self): mediafile = self._mediafile_fixture('empty') @@ -276,7 +277,7 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertItemsEqual(mediafile.genres, [u'one', u'two']) + assertCountEqual(self, mediafile.genres, [u'one', u'two']) def test_write_genre_list_get_first(self): mediafile = self._mediafile_fixture('empty') @@ -293,7 +294,7 @@ class GenreListTestMixin(object): mediafile.save() mediafile = MediaFile(mediafile.path) - self.assertItemsEqual(mediafile.genres, [u'the genre', u'another']) + assertCountEqual(self, mediafile.genres, [u'the genre', u'another']) field_extension = MediaField( @@ -949,7 +950,7 @@ class MediaFieldTest(unittest.TestCase): def test_known_fields(self): fields = list(ReadWriteTestBase.tag_fields) fields.extend(('encoder', 'images', 'genres', 'albumtype')) - self.assertItemsEqual(MediaFile.fields(), fields) + assertCountEqual(self, MediaFile.fields(), fields) def test_fields_in_readable_fields(self): readable = MediaFile.readable_fields() diff --git a/test/test_web.py b/test/test_web.py index 51a55f33d..ac4e03e97 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -4,6 +4,8 @@ from __future__ import division, absolute_import, print_function +from six import assertCountEqual + from test._common import unittest from test import _common import json @@ -52,7 +54,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json['items']), 2) response_titles = [item['title'] for item in response.json['items']] - self.assertItemsEqual(response_titles, [u'title', u'another title']) + assertCountEqual(self, response_titles, [u'title', u'another title']) def test_get_single_item_not_found(self): response = self.client.get('/item/3') @@ -80,7 +82,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, [u'album', u'another album']) + assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_single_album_by_id(self): response = self.client.get('/album/2') @@ -96,7 +98,7 @@ class WebPluginTest(_common.LibTestCase): self.assertEqual(response.status_code, 200) response_albums = [album['album'] for album in response.json['albums']] - self.assertItemsEqual(response_albums, [u'album', u'another album']) + assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_album_empty_query(self): response = self.client.get('/album/query/') From d47182a3e5f758aaee5adca7398fed1b3d9145c8 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 23 Jun 2016 16:48:17 +0200 Subject: [PATCH 1035/2280] fetchart: do not rely on the server-provided Content-Type, but determine the image format from the file magic --- beetsplug/fetchart.py | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a2ce1661d..c629aeca6 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -29,6 +29,7 @@ from beets import importer from beets import ui from beets import util from beets import config +from beets.mediafile import _image_mime_type from beets.util.artresizer import ArtResizer from beets.util import confit from beets.util import syspath, bytestring_path @@ -231,21 +232,39 @@ class RemoteArtSource(ArtSource): message=u'downloading image')) as resp: ct = resp.headers.get('Content-Type', None) if ct not in CONTENT_TYPES: - self._log.debug( - u'not a supported image: {}', - resp.headers.get('Content-Type') or u'no content type', - ) + self._log.debug(u'not a supported image: {}', + ct or u'no content type') candidate.path = None return - # Generate a temporary file with the correct extension. - with NamedTemporaryFile(suffix=b'.' + CONTENT_TYPES[ct][0], - delete=False) as fh: - for chunk in resp.iter_content(chunk_size=1024): + # Generate a temporary file and guess the extension based on + # the Content-Type header. This may be wrong for badly + # configured servers. E.g. fanart.tv only allows .jpg uploads + # and ALWAYS returns a image/jpeg Content-Type, but other + # formats with a erroneous .jp(e)g extension apparently can + # sneak through the upload filter. Therefore validate the type + # using the file magic. + data = resp.iter_content(chunk_size=1024) + try: + chunk = next(data) + except StopIteration: + pass + else: + real_ct = _image_mime_type(chunk) + ext = b'.' + CONTENT_TYPES[real_ct][0] + if real_ct != ct: + self._log.warn(u'Server specified {}, but returned a ' + u'{} image. Correcting the extension ' + u'to {}', + ct, real_ct, ext) + with NamedTemporaryFile(suffix=ext, delete=False) as fh: fh.write(chunk) - self._log.debug(u'downloaded art to: {0}', - util.displayable_path(fh.name)) - candidate.path = util.bytestring_path(fh.name) + for chunk in data: + fh.write(chunk) + self._log.debug(u'downloaded art to: {0}', + util.displayable_path(fh.name)) + candidate.path = util.bytestring_path(fh.name) + return except (IOError, requests.RequestException, TypeError) as exc: From 34cdf0f3f382acc855e87c680bb231fad27777dc Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 23 Jun 2016 16:58:57 +0200 Subject: [PATCH 1036/2280] fetchart: complain about unsupported images only after validating the Content-Type --- beetsplug/fetchart.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index c629aeca6..9614b17f2 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -231,11 +231,6 @@ class RemoteArtSource(ArtSource): with closing(self.request(candidate.url, stream=True, message=u'downloading image')) as resp: ct = resp.headers.get('Content-Type', None) - if ct not in CONTENT_TYPES: - self._log.debug(u'not a supported image: {}', - ct or u'no content type') - candidate.path = None - return # Generate a temporary file and guess the extension based on # the Content-Type header. This may be wrong for badly @@ -251,12 +246,19 @@ class RemoteArtSource(ArtSource): pass else: real_ct = _image_mime_type(chunk) + if real_ct not in CONTENT_TYPES: + self._log.debug(u'not a supported image: {}', + real_ct or u'unknown content type') + candidate.path = None + return + ext = b'.' + CONTENT_TYPES[real_ct][0] if real_ct != ct: self._log.warn(u'Server specified {}, but returned a ' u'{} image. Correcting the extension ' u'to {}', ct, real_ct, ext) + with NamedTemporaryFile(suffix=ext, delete=False) as fh: fh.write(chunk) for chunk in data: From c789d31614a94009f68778bb1fa6bc4edf26a7eb Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 23 Jun 2016 17:30:10 +0200 Subject: [PATCH 1037/2280] fetchart: fix and add tests for the new behaviour --- test/test_art.py | 45 +++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 58b15d8e5..e2867a7ec 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -45,16 +45,26 @@ class UseThePlugin(_common.TestCase): self.plugin = fetchart.FetchArtPlugin() -class FetchImageTest(UseThePlugin): - URL = 'http://example.com/test.jpg' - +class FetchImageHelper(_common.TestCase): + """Helper mixin for mocking requests when fetching images + with remote art sources. + """ @responses.activate def run(self, *args, **kwargs): - super(FetchImageTest, self).run(*args, **kwargs) + super(FetchImageHelper, self).run(*args, **kwargs) - def mock_response(self, content_type): - responses.add(responses.GET, self.URL, - content_type=content_type) + def mock_response(self, url, content_type='image/jpeg', file_type=None): + IMAGEHEADER = {'image/jpeg': b'\x00' * 6 + b'JFIF', + 'image/png': b'\211PNG\r\n\032\n', } + if file_type is None: + file_type = content_type + responses.add(responses.GET, url, + content_type=content_type, + body=IMAGEHEADER.get(file_type, b'\x00' * 32)) + + +class FetchImageTest(FetchImageHelper, UseThePlugin): + URL = 'http://example.com/test.jpg' def setUp(self): super(FetchImageTest, self).setUp() @@ -64,17 +74,23 @@ class FetchImageTest(UseThePlugin): self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): - self.mock_response('image/watercolour') + self.mock_response(self.URL, 'image/watercolour') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): - self.mock_response('image/jpeg') + self.mock_response(self.URL, 'image/jpeg') self.source.fetch_image(self.candidate, self.extra) self.assertNotEqual(self.candidate.path, None) def test_extension_set_by_content_type(self): - self.mock_response('image/png') + self.mock_response(self.URL, 'image/png') + self.source.fetch_image(self.candidate, self.extra) + self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') + self.assertExists(self.candidate.path) + + def test_does_not_rely_on_server_content_type(self): + self.mock_response(self.URL, 'image/jpeg', 'image/png') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -128,7 +144,7 @@ class FSArtTest(UseThePlugin): self.assertEqual(candidates, paths) -class CombinedTest(UseThePlugin): +class CombinedTest(FetchImageHelper, UseThePlugin): ASIN = 'xxxx' MBID = 'releaseid' AMAZON_URL = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ @@ -143,13 +159,6 @@ class CombinedTest(UseThePlugin): self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) - @responses.activate - def run(self, *args, **kwargs): - super(CombinedTest, self).run(*args, **kwargs) - - def mock_response(self, url, content_type='image/jpeg'): - responses.add(responses.GET, url, content_type=content_type) - def test_main_interface_returns_amazon_art(self): self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) From e8afcbe7ec4bc37bb080f6f466b98807d020753b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 04:34:24 -0400 Subject: [PATCH 1038/2280] replace unicode with six.text_type --- beets/autotag/hooks.py | 5 +-- beets/autotag/mb.py | 8 +++-- beets/dbcore/db.py | 3 +- beets/dbcore/query.py | 7 ++-- beets/dbcore/types.py | 9 ++--- beets/importer.py | 3 +- beets/library.py | 23 ++++++------ beets/logging.py | 5 +-- beets/mediafile.py | 48 +++++++++++++------------ beets/ui/__init__.py | 20 ++++++----- beets/ui/commands.py | 7 ++-- beets/util/__init__.py | 17 ++++----- beets/util/confit.py | 3 +- beets/util/functemplate.py | 9 ++--- beets/util/hidden.py | 3 +- beetsplug/badfiles.py | 3 +- beetsplug/beatport.py | 19 +++++----- beetsplug/bpd/__init__.py | 64 +++++++++++++++++---------------- beetsplug/bpd/gstplayer.py | 3 +- beetsplug/chroma.py | 3 +- beetsplug/convert.py | 13 +++---- beetsplug/discogs.py | 7 ++-- beetsplug/duplicates.py | 3 +- beetsplug/edit.py | 5 +-- beetsplug/fetchart.py | 3 +- beetsplug/fromfilename.py | 3 +- beetsplug/ftintitle.py | 3 +- beetsplug/hook.py | 5 +-- beetsplug/importfeeds.py | 3 +- beetsplug/inline.py | 7 ++-- beetsplug/keyfinder.py | 3 +- beetsplug/lastgenre/__init__.py | 10 +++--- beetsplug/lastimport.py | 3 +- beetsplug/lyrics.py | 11 +++--- beetsplug/mbcollection.py | 5 +-- beetsplug/mpdstats.py | 9 ++--- beetsplug/mpdupdate.py | 7 ++-- beetsplug/replaygain.py | 7 ++-- beetsplug/rewrite.py | 3 +- beetsplug/spotify.py | 3 +- beetsplug/the.py | 3 +- beetsplug/thumbnails.py | 4 ++- beetsplug/web/__init__.py | 3 +- beetsplug/zero.py | 3 +- test/helper.py | 5 +-- test/test_config_command.py | 5 +-- test/test_dbcore.py | 3 +- test/test_library.py | 8 +++-- test/test_lyrics.py | 3 +- test/test_mediafile.py | 5 +-- test/test_mediafile_edge.py | 9 ++--- test/test_query.py | 8 +++-- test/test_template.py | 3 +- test/test_ui.py | 27 +++++++------- test/test_ui_importer.py | 3 +- test/test_util.py | 5 +-- 56 files changed, 269 insertions(+), 203 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 0b8a6f6bf..154896da7 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -27,6 +27,7 @@ from beets.util import as_string from beets.autotag import mb from jellyfish import levenshtein_distance from unidecode import unidecode +import six log = logging.getLogger('beets') @@ -205,8 +206,8 @@ def _string_dist_basic(str1, str2): transliteration/lowering to ASCII characters. Normalized by string length. """ - assert isinstance(str1, unicode) - assert isinstance(str2, unicode) + assert isinstance(str1, six.text_type) + assert isinstance(str2, six.text_type) str1 = as_string(unidecode(str1)) str2 = as_string(unidecode(str2)) str1 = re.sub(r'[^a-z0-9]', '', str1.lower()) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 4df0187e4..8aafe36e2 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -27,6 +27,7 @@ import beets.autotag.hooks import beets from beets import util from beets import config +import six VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' BASE_URL = 'http://musicbrainz.org/' @@ -69,7 +70,8 @@ def configure(): """Set up the python-musicbrainz-ngs module according to settings from the beets configuration. This should be called at startup. """ - musicbrainzngs.set_hostname(config['musicbrainz']['host'].get(unicode)) + hostname = config['musicbrainz']['host'].get(six.text_type) + musicbrainzngs.set_hostname(hostname) musicbrainzngs.set_rate_limit( config['musicbrainz']['ratelimit_interval'].as_number(), config['musicbrainz']['ratelimit'].get(int), @@ -260,7 +262,7 @@ def album_info(release): ) info.va = info.artist_id == VARIOUS_ARTISTS_ID if info.va: - info.artist = config['va_name'].get(unicode) + info.artist = config['va_name'].get(six.text_type) info.asin = release.get('asin') info.releasegroup_id = release['release-group']['id'] info.country = release.get('country') @@ -329,7 +331,7 @@ def match_album(artist, album, tracks=None): # Various Artists search. criteria['arid'] = VARIOUS_ARTISTS_ID if tracks is not None: - criteria['tracks'] = unicode(tracks) + criteria['tracks'] = six.text_type(tracks) # Abort if we have no search terms. if not any(criteria.itervalues()): diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index a07a19997..19d5c51e6 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -29,6 +29,7 @@ import beets from beets.util.functemplate import Template from beets.dbcore import types from .query import MatchQuery, NullSort, TrueQuery +import six class FormattedMapping(collections.Mapping): @@ -69,7 +70,7 @@ class FormattedMapping(collections.Mapping): value = value.decode('utf8', 'ignore') if self.for_path: - sep_repl = beets.config['path_sep_replace'].get(unicode) + sep_repl = beets.config['path_sep_replace'].get(six.text_type) for sep in (os.path.sep, os.path.altsep): if sep: value = value.replace(sep, sep_repl) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 8e2075f37..f95e4ac60 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -23,6 +23,7 @@ from beets import util from datetime import datetime, timedelta import unicodedata from functools import reduce +import six class ParsingError(ValueError): @@ -246,8 +247,8 @@ class BytesQuery(MatchQuery): # Use a buffer representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. - if isinstance(self.pattern, (unicode, bytes)): - if isinstance(self.pattern, unicode): + if isinstance(self.pattern, (six.text_type, bytes)): + if isinstance(self.pattern, six.text_type): self.pattern = self.pattern.encode('utf8') self.buf_pattern = buffer(self.pattern) elif isinstance(self.pattern, buffer): @@ -793,7 +794,7 @@ class FieldSort(Sort): def key(item): field_val = item.get(self.field, '') - if self.case_insensitive and isinstance(field_val, unicode): + if self.case_insensitive and isinstance(field_val, six.text_type): field_val = field_val.lower() return field_val diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 2726969dd..2270d7c13 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -19,6 +19,7 @@ from __future__ import division, absolute_import, print_function from . import query from beets.util import str2bool +import six # Abstract base. @@ -37,7 +38,7 @@ class Type(object): """The `Query` subclass to be used when querying the field. """ - model_type = unicode + model_type = six.text_type """The Python type that is used to represent the value in the model. The model is guaranteed to return a value of this type if the field @@ -63,7 +64,7 @@ class Type(object): if isinstance(value, bytes): value = value.decode('utf8', 'ignore') - return unicode(value) + return six.text_type(value) def parse(self, string): """Parse a (possibly human-written) string and return the @@ -102,7 +103,7 @@ class Type(object): """ if isinstance(sql_value, buffer): sql_value = bytes(sql_value).decode('utf8', 'ignore') - if isinstance(sql_value, unicode): + if isinstance(sql_value, six.text_type): return self.parse(sql_value) else: return self.normalize(sql_value) @@ -194,7 +195,7 @@ class Boolean(Type): model_type = bool def format(self, value): - return unicode(bool(value)) + return six.text_type(bool(value)) def parse(self, string): return str2bool(string) diff --git a/beets/importer.py b/beets/importer.py index 072c2ad5b..598dd36d7 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -14,6 +14,7 @@ # 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. @@ -640,7 +641,7 @@ class ImportTask(BaseImportTask): changes['comp'] = False else: # VA. - changes['albumartist'] = config['va_name'].get(unicode) + changes['albumartist'] = config['va_name'].get(six.text_type) changes['comp'] = True elif self.choice_flag in (action.APPLY, action.RETAG): diff --git a/beets/library.py b/beets/library.py index f268694cb..e672187a8 100644 --- a/beets/library.py +++ b/beets/library.py @@ -124,14 +124,15 @@ class DateType(types.Float): query = dbcore.query.DateQuery def format(self, value): - return time.strftime(beets.config['time_format'].get(unicode), + return time.strftime(beets.config['time_format'].get(six.text_type), time.localtime(value or 0)) def parse(self, string): try: # Try a formatted date string. return time.mktime( - time.strptime(string, beets.config['time_format'].get(unicode)) + time.strptime(string, + beets.config['time_format'].get(six.text_type)) ) except ValueError: # Fall back to a plain timestamp number. @@ -153,7 +154,7 @@ class PathType(types.Type): return normpath(bytestring_path(string)) def normalize(self, value): - if isinstance(value, unicode): + if isinstance(value, six.text_type): # Paths stored internally as encoded bytes. return bytestring_path(value) @@ -281,11 +282,11 @@ class FileOperationError(Exception): """ return u'{0}: {1}'.format( util.displayable_path(self.path), - unicode(self.reason) + six.text_type(self.reason) ) def __str__(self): - return unicode(self).encode('utf8') + return six.text_type(self).encode('utf8') class ReadError(FileOperationError): @@ -331,7 +332,7 @@ class LibModel(dbcore.Model): def __format__(self, spec): if not spec: - spec = beets.config[self._format_config_key].get(unicode) + spec = beets.config[self._format_config_key].get(six.text_type) result = self.evaluate_template(spec) if isinstance(spec, bytes): # if spec is a byte string then we must return a one as well @@ -517,7 +518,7 @@ class Item(LibModel): """ # Encode unicode paths and read buffers. if key == 'path': - if isinstance(value, unicode): + if isinstance(value, six.text_type): value = bytestring_path(value) elif isinstance(value, buffer): value = bytes(value) @@ -1061,7 +1062,8 @@ class Album(LibModel): image = bytestring_path(image) item_dir = item_dir or self.item_dir() - filename_tmpl = Template(beets.config['art_filename'].get(unicode)) + filename_tmpl = Template( + beets.config['art_filename'].get(six.text_type)) subpath = self.evaluate_template(filename_tmpl, True) if beets.config['asciify_paths']: subpath = unidecode(subpath) @@ -1179,7 +1181,8 @@ def parse_query_string(s, model_cls): The string is split into components using shell-like syntax. """ - assert isinstance(s, unicode), u"Query is not unicode: {0!r}".format(s) + message = u"Query is not unicode: {0!r}".format(s) + assert isinstance(s, six.text_type), message try: parts = util.shlex_split(s) except ValueError as exc: @@ -1405,7 +1408,7 @@ class DefaultTemplateFunctions(object): def tmpl_time(s, fmt): """Format a time value using `strftime`. """ - cur_fmt = beets.config['time_format'].get(unicode) + cur_fmt = beets.config['time_format'].get(six.text_type) return time.strftime(fmt, time.strptime(s, cur_fmt)) def tmpl_aunique(self, keys=None, disam=None): diff --git a/beets/logging.py b/beets/logging.py index a94da1c62..f7b46bd60 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -27,6 +27,7 @@ from copy import copy from logging import * # noqa import subprocess import threading +import six def logsafe(val): @@ -42,7 +43,7 @@ def logsafe(val): example. """ # Already Unicode. - if isinstance(val, unicode): + if isinstance(val, six.text_type): return val # Bytestring: needs decoding. @@ -56,7 +57,7 @@ def logsafe(val): # A "problem" object: needs a workaround. elif isinstance(val, subprocess.CalledProcessError): try: - return unicode(val) + return six.text_type(val) except UnicodeDecodeError: # An object with a broken __unicode__ formatter. Use __str__ # instead. diff --git a/beets/mediafile.py b/beets/mediafile.py index 556b41bb8..278e848b8 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -59,6 +59,7 @@ import enum from beets import logging from beets.util import displayable_path, syspath, as_string +import six __all__ = ['UnreadableFileError', 'FileTypeError', 'MediaFile'] @@ -131,7 +132,7 @@ def _safe_cast(out_type, val): else: # Process any other type as a string. if not isinstance(val, basestring): - val = unicode(val) + val = six.text_type(val) # Get a number from the front of the string. val = re.match(r'[0-9]*', val.strip()).group(0) if not val: @@ -146,13 +147,13 @@ def _safe_cast(out_type, val): except ValueError: return False - elif out_type == unicode: + elif out_type == six.text_type: if isinstance(val, bytes): return val.decode('utf8', 'ignore') - elif isinstance(val, unicode): + elif isinstance(val, six.text_type): return val else: - return unicode(val) + return six.text_type(val) elif out_type == float: if isinstance(val, int) or isinstance(val, float): @@ -161,7 +162,7 @@ def _safe_cast(out_type, val): if isinstance(val, bytes): val = val.decode('utf8', 'ignore') else: - val = unicode(val) + val = six.text_type(val) match = re.match(r'[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)', val.strip()) if match: @@ -220,7 +221,7 @@ def _sc_decode(soundcheck): """ # We decode binary data. If one of the formats gives us a text # string, interpret it as UTF-8. - if isinstance(soundcheck, unicode): + if isinstance(soundcheck, six.text_type): soundcheck = soundcheck.encode('utf8') # SoundCheck tags consist of 10 numbers, each represented by 8 @@ -407,7 +408,8 @@ class StorageStyle(object): """List of mutagen classes the StorageStyle can handle. """ - def __init__(self, key, as_type=unicode, suffix=None, float_places=2): + def __init__(self, key, as_type=six.text_type, suffix=None, + float_places=2): """Create a basic storage strategy. Parameters: - `key`: The key on the Mutagen file object used to access the @@ -426,8 +428,8 @@ class StorageStyle(object): self.float_places = float_places # Convert suffix to correct string type. - if self.suffix and self.as_type is unicode \ - and not isinstance(self.suffix, unicode): + if self.suffix and self.as_type is six.text_type \ + and not isinstance(self.suffix, six.text_type): self.suffix = self.suffix.decode('utf8') # Getter. @@ -450,7 +452,7 @@ class StorageStyle(object): """Given a raw value stored on a Mutagen object, decode and return the represented value. """ - if self.suffix and isinstance(mutagen_value, unicode) \ + if self.suffix and isinstance(mutagen_value, six.text_type) \ and mutagen_value.endswith(self.suffix): return mutagen_value[:-len(self.suffix)] else: @@ -472,17 +474,17 @@ class StorageStyle(object): """Convert the external Python value to a type that is suitable for storing in a Mutagen file object. """ - if isinstance(value, float) and self.as_type is unicode: + if isinstance(value, float) and self.as_type is six.text_type: value = u'{0:.{1}f}'.format(value, self.float_places) value = self.as_type(value) - elif self.as_type is unicode: + elif self.as_type is six.text_type: if isinstance(value, bool): # Store bools as 1/0 instead of True/False. - value = unicode(int(bool(value))) + value = six.text_type(int(bool(value))) elif isinstance(value, bytes): value = value.decode('utf8', 'ignore') else: - value = unicode(value) + value = six.text_type(value) else: value = self.as_type(value) @@ -592,7 +594,7 @@ class MP4StorageStyle(StorageStyle): def serialize(self, value): value = super(MP4StorageStyle, self).serialize(value) - if self.key.startswith('----:') and isinstance(value, unicode): + if self.key.startswith('----:') and isinstance(value, six.text_type): value = value.encode('utf8') return value @@ -807,7 +809,7 @@ class MP3SlashPackStorageStyle(MP3StorageStyle): def _fetch_unpacked(self, mutagen_file): data = self.fetch(mutagen_file) if data: - items = unicode(data).split('/') + items = six.text_type(data).split('/') else: items = [] packing_length = 2 @@ -823,7 +825,7 @@ class MP3SlashPackStorageStyle(MP3StorageStyle): items[0] = '' if items[1] is None: items.pop() # Do not store last value - self.store(mutagen_file, '/'.join(map(unicode, items))) + self.store(mutagen_file, '/'.join(map(six.text_type, items))) def delete(self, mutagen_file): if self.pack_pos == 0: @@ -1074,7 +1076,7 @@ class MediaField(object): getting this property. """ - self.out_type = kwargs.get('out_type', unicode) + self.out_type = kwargs.get('out_type', six.text_type) self._styles = styles def styles(self, mutagen_file): @@ -1113,7 +1115,7 @@ class MediaField(object): return 0.0 elif self.out_type == bool: return False - elif self.out_type == unicode: + elif self.out_type == six.text_type: return u'' @@ -1195,8 +1197,8 @@ class DateField(MediaField): # Get the underlying data and split on hyphens and slashes. datestring = super(DateField, self).__get__(mediafile, None) if isinstance(datestring, basestring): - datestring = re.sub(r'[Tt ].*$', '', unicode(datestring)) - items = re.split('[-/]', unicode(datestring)) + datestring = re.sub(r'[Tt ].*$', '', six.text_type(datestring)) + items = re.split('[-/]', six.text_type(datestring)) else: items = [] @@ -1233,7 +1235,7 @@ class DateField(MediaField): date.append(u'{0:02d}'.format(int(month))) if month and day: date.append(u'{0:02d}'.format(int(day))) - date = map(unicode, date) + date = map(six.text_type, date) super(DateField, self).__set__(mediafile, u'-'.join(date)) if hasattr(self, '_year_field'): @@ -1360,7 +1362,7 @@ class MediaFile(object): try: self.mgfile = mutagen.File(path) except unreadable_exc as exc: - log.debug(u'header parsing failed: {0}', unicode(exc)) + log.debug(u'header parsing failed: {0}', six.text_type(exc)) raise UnreadableFileError(path) except IOError as exc: if type(exc) == IOError: diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 9cebf7a28..61176307f 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -42,6 +42,7 @@ from beets import config from beets.util import confit, as_string from beets.autotag import mb from beets.dbcore import query as db_query +import six # On Windows platforms, use colorama to support "ANSI" terminal colors. if sys.platform == 'win32': @@ -140,7 +141,7 @@ def print_(*strings, **kwargs): """ end = kwargs.get('end') - if not strings or isinstance(strings[0], unicode): + if not strings or isinstance(strings[0], six.text_type): txt = u' '.join(strings) txt += u'\n' if end is None else end else: @@ -148,7 +149,7 @@ def print_(*strings, **kwargs): txt += b'\n' if end is None else end # Always send bytes to the stdout stream. - if isinstance(txt, unicode): + if isinstance(txt, six.text_type): txt = txt.encode(_out_encoding(), 'replace') sys.stdout.write(txt) @@ -298,11 +299,11 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, prompt_part_lengths = [] if numrange: if isinstance(default, int): - default_name = unicode(default) + default_name = six.text_type(default) default_name = colorize('action_default', default_name) tmpl = '# selection (default %s)' prompt_parts.append(tmpl % default_name) - prompt_part_lengths.append(len(tmpl % unicode(default))) + prompt_part_lengths.append(len(tmpl % six.text_type(default))) else: prompt_parts.append('# selection') prompt_part_lengths.append(len(prompt_parts[-1])) @@ -522,7 +523,8 @@ def colorize(color_name, text): if config['ui']['color']: global COLORS if not COLORS: - COLORS = dict((name, config['ui']['colors'][name].get(unicode)) + COLORS = dict((name, + config['ui']['colors'][name].get(six.text_type)) 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') @@ -544,8 +546,8 @@ def _colordiff(a, b, highlight='text_highlight', """ if not isinstance(a, basestring) or not isinstance(b, basestring): # Non-strings: use ordinary equality. - a = unicode(a) - b = unicode(b) + a = six.text_type(a) + b = six.text_type(b) if a == b: return a, b else: @@ -593,7 +595,7 @@ def colordiff(a, b, highlight='text_highlight'): if config['ui']['color']: return _colordiff(a, b, highlight) else: - return unicode(a), unicode(b) + return six.text_type(a), six.text_type(b) def get_path_formats(subview=None): @@ -604,7 +606,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(unicode)))) + path_formats.append((query, Template(view.get(six.text_type)))) return path_formats diff --git a/beets/ui/commands.py b/beets/ui/commands.py index d2270c662..9b23eafd4 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -38,6 +38,7 @@ from beets import library from beets import config from beets import logging from beets.util.confit import _package_path +import six VARIOUS_ARTISTS = u'Various Artists' PromptChoice = namedtuple('ExtraChoice', ['short', 'long', 'callback']) @@ -163,7 +164,7 @@ def disambig_string(info): else: disambig.append(info.media) if info.year: - disambig.append(unicode(info.year)) + disambig.append(six.text_type(info.year)) if info.country: disambig.append(info.country) if info.label: @@ -236,9 +237,9 @@ def show_change(cur_artist, cur_album, match): if mediums > 1: return u'{0}-{1}'.format(medium, medium_index) else: - return unicode(medium_index) + return six.text_type(medium_index) else: - return unicode(index) + return six.text_type(index) # Identify the album in question. if cur_artist != match.info.artist or \ diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 0628f324b..5fe52d7b8 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -27,6 +27,7 @@ import subprocess import platform import shlex from beets.util import hidden +import six MAX_FILENAME_LENGTH = 200 @@ -65,14 +66,14 @@ class HumanReadableException(Exception): def _reasonstr(self): """Get the reason as a string.""" - if isinstance(self.reason, unicode): + if isinstance(self.reason, six.text_type): return self.reason elif isinstance(self.reason, bytes): return self.reason.decode('utf8', 'ignore') elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError return self.reason.strerror else: - return u'"{0}"'.format(unicode(self.reason)) + return u'"{0}"'.format(six.text_type(self.reason)) def get_message(self): """Create the human-readable description of the error, sans @@ -346,11 +347,11 @@ def displayable_path(path, separator=u'; '): """ if isinstance(path, (list, tuple)): return separator.join(displayable_path(p) for p in path) - elif isinstance(path, unicode): + elif isinstance(path, six.text_type): return path elif not isinstance(path, bytes): # A non-string object: just get its unicode representation. - return unicode(path) + return six.text_type(path) try: return path.decode(_fsencoding(), 'ignore') @@ -369,7 +370,7 @@ def syspath(path, prefix=True): if os.path.__name__ != 'ntpath': return path - if not isinstance(path, unicode): + if not isinstance(path, six.text_type): # Beets currently represents Windows paths internally with UTF-8 # arbitrarily. But earlier versions used MBCS because it is # reported as the FS encoding by Windows. Try both. @@ -639,7 +640,7 @@ def as_string(value): elif isinstance(value, bytes): return value.decode('utf8', 'ignore') else: - return unicode(value) + return six.text_type(value) def plurality(objs): @@ -765,7 +766,7 @@ def shlex_split(s): # Shlex works fine. return shlex.split(s) - elif isinstance(s, unicode): + elif isinstance(s, six.text_type): # Work around a Python bug. # http://bugs.python.org/issue6988 bs = s.encode('utf8') @@ -801,7 +802,7 @@ def _windows_long_path_name(short_path): """Use Windows' `GetLongPathNameW` via ctypes to get the canonical, long path given a short filename. """ - if not isinstance(short_path, unicode): + if not isinstance(short_path, six.text_type): short_path = short_path.decode(_fsencoding()) import ctypes diff --git a/beets/util/confit.py b/beets/util/confit.py index 057f85a1f..7994a0b3e 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -25,6 +25,7 @@ import yaml import collections import re from collections import OrderedDict +import six UNIX_DIR_VAR = 'XDG_CONFIG_HOME' UNIX_DIR_FALLBACK = '~/.config' @@ -44,7 +45,7 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else unicode # noqa +STRING = str if PY3 else six.text_type # noqa BASESTRING = str if PY3 else basestring # noqa NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 05f0892c2..3a07df5bd 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -35,6 +35,7 @@ import dis import types from .confit import NUMERIC_TYPES +import six SYMBOL_DELIM = u'$' FUNC_DELIM = u'%' @@ -190,8 +191,8 @@ class Call(object): except Exception as exc: # Function raised exception! Maybe inlining the name of # the exception will help debug. - return u'<%s>' % unicode(exc) - return unicode(out) + return u'<%s>' % six.text_type(exc) + return six.text_type(out) else: return self.original @@ -246,7 +247,7 @@ class Expression(object): out.append(part) else: out.append(part.evaluate(env)) - return u''.join(map(unicode, out)) + return u''.join(map(six.text_type, out)) def translate(self): """Compile the expression to a list of Python AST expressions, a @@ -563,7 +564,7 @@ if __name__ == '__main__': import timeit _tmpl = Template(u'foo $bar %baz{foozle $bar barzle} $bar') _vars = {'bar': 'qux'} - _funcs = {'baz': unicode.upper} + _funcs = {'baz': six.text_type.upper} interp_time = timeit.timeit('_tmpl.interpret(_vars, _funcs)', 'from __main__ import _tmpl, _vars, _funcs', number=10000) diff --git a/beets/util/hidden.py b/beets/util/hidden.py index 262d371ea..11e3691d6 100644 --- a/beets/util/hidden.py +++ b/beets/util/hidden.py @@ -20,6 +20,7 @@ import os import stat import ctypes import sys +import six def _is_hidden_osx(path): @@ -74,7 +75,7 @@ def is_hidden(path): work out if a file is hidden. """ # Convert the path to unicode if it is not already. - if not isinstance(path, unicode): + if not isinstance(path, six.text_type): path = path.decode('utf-8') # Run platform specific functions depending on the platform diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index f9704d484..bb14c7762 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -27,6 +27,7 @@ import shlex import os import errno import sys +import six class BadFiles(BeetsPlugin): @@ -97,7 +98,7 @@ class BadFiles(BeetsPlugin): if not checker: continue path = item.path - if not isinstance(path, unicode): + if not isinstance(path, six.text_type): path = item.path.decode(sys.getfilesystemencoding()) status, errors, output = checker(path) if status > 0: diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index c1425ad9e..530bf5184 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import json import re +import six from datetime import datetime, timedelta from requests_oauthlib import OAuth1Session @@ -42,15 +43,15 @@ class BeatportAPIError(Exception): class BeatportObject(object): def __init__(self, data): self.beatport_id = data['id'] - self.name = unicode(data['name']) + self.name = six.text_type(data['name']) if 'releaseDate' in data: self.release_date = datetime.strptime(data['releaseDate'], '%Y-%m-%d') if 'artists' in data: - self.artists = [(x['id'], unicode(x['name'])) + self.artists = [(x['id'], six.text_type(x['name'])) for x in data['artists']] if 'genres' in data: - self.genres = [unicode(x['name']) + self.genres = [six.text_type(x['name']) for x in data['genres']] @@ -209,7 +210,7 @@ class BeatportRelease(BeatportObject): ) def __repr__(self): - return unicode(self).encode('utf8') + return six.text_type(self).encode('utf8') def __init__(self, data): BeatportObject.__init__(self, data) @@ -231,14 +232,14 @@ class BeatportTrack(BeatportObject): .format(artist_str, self.name, self.mix_name)) def __repr__(self): - return unicode(self).encode('utf8') + return six.text_type(self).encode('utf8') def __init__(self, data): BeatportObject.__init__(self, data) if 'title' in data: - self.title = unicode(data['title']) + self.title = six.text_type(data['title']) if 'mixName' in data: - self.mix_name = unicode(data['mixName']) + self.mix_name = six.text_type(data['mixName']) self.length = timedelta(milliseconds=data.get('lengthMs', 0) or 0) if not self.length: try: @@ -266,8 +267,8 @@ class BeatportPlugin(BeetsPlugin): self.register_listener('import_begin', self.setup) def setup(self, session=None): - c_key = self.config['apikey'].get(unicode) - c_secret = self.config['apisecret'].get(unicode) + c_key = self.config['apikey'].get(six.text_type) + c_secret = self.config['apisecret'].get(six.text_type) # Get the OAuth token from a file or log in. try: diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index ea1b0082e..ee41ad164 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -35,6 +35,7 @@ from beets.util import bluelet from beets.library import Item from beets import dbcore from beets.mediafile import MediaFile +import six PROTOCOL_VERSION = '0.13.0' BUFSIZE = 1024 @@ -305,12 +306,12 @@ class BaseServer(object): playlist, playlistlength, and xfade. """ yield ( - u'volume: ' + unicode(self.volume), - u'repeat: ' + unicode(int(self.repeat)), - u'random: ' + unicode(int(self.random)), - u'playlist: ' + unicode(self.playlist_version), - u'playlistlength: ' + unicode(len(self.playlist)), - u'xfade: ' + unicode(self.crossfade), + u'volume: ' + six.text_type(self.volume), + u'repeat: ' + six.text_type(int(self.repeat)), + u'random: ' + six.text_type(int(self.random)), + u'playlist: ' + six.text_type(self.playlist_version), + u'playlistlength: ' + six.text_type(len(self.playlist)), + u'xfade: ' + six.text_type(self.crossfade), ) if self.current_index == -1: @@ -323,8 +324,8 @@ class BaseServer(object): if self.current_index != -1: # i.e., paused or playing current_id = self._item_id(self.playlist[self.current_index]) - yield u'song: ' + unicode(self.current_index) - yield u'songid: ' + unicode(current_id) + yield u'song: ' + six.text_type(self.current_index) + yield u'songid: ' + six.text_type(current_id) if self.error: yield u'error: ' + self.error @@ -468,8 +469,8 @@ class BaseServer(object): Also a dummy implementation. """ for idx, track in enumerate(self.playlist): - yield u'cpos: ' + unicode(idx) - yield u'Id: ' + unicode(track.id) + yield u'cpos: ' + six.text_type(idx) + yield u'Id: ' + six.text_type(track.id) def cmd_currentsong(self, conn): """Sends information about the currently-playing song. @@ -573,7 +574,7 @@ class Connection(object): lines = [lines] out = NEWLINE.join(lines) + NEWLINE log.debug('{}', out[:-1]) # Don't log trailing newline. - if isinstance(out, unicode): + if isinstance(out, six.text_type): out = out.encode('utf8') return self.sock.sendall(out) @@ -771,28 +772,28 @@ class Server(BaseServer): def _item_info(self, item): info_lines = [ u'file: ' + item.destination(fragment=True), - u'Time: ' + unicode(int(item.length)), + u'Time: ' + six.text_type(int(item.length)), u'Title: ' + item.title, u'Artist: ' + item.artist, u'Album: ' + item.album, u'Genre: ' + item.genre, ] - track = unicode(item.track) + track = six.text_type(item.track) if item.tracktotal: - track += u'/' + unicode(item.tracktotal) + track += u'/' + six.text_type(item.tracktotal) info_lines.append(u'Track: ' + track) - info_lines.append(u'Date: ' + unicode(item.year)) + info_lines.append(u'Date: ' + six.text_type(item.year)) try: pos = self._id_to_index(item.id) - info_lines.append(u'Pos: ' + unicode(pos)) + info_lines.append(u'Pos: ' + six.text_type(pos)) except ArgumentNotFoundError: # Don't include position if not in playlist. pass - info_lines.append(u'Id: ' + unicode(item.id)) + info_lines.append(u'Id: ' + six.text_type(item.id)) return info_lines @@ -917,7 +918,7 @@ class Server(BaseServer): for item in self._all_items(self._resolve_path(path)): self.playlist.append(item) if send_id: - yield u'Id: ' + unicode(item.id) + yield u'Id: ' + six.text_type(item.id) self.playlist_version += 1 def cmd_add(self, conn, path): @@ -938,11 +939,11 @@ class Server(BaseServer): if self.current_index > -1: item = self.playlist[self.current_index] - yield u'bitrate: ' + unicode(item.bitrate / 1000) + yield u'bitrate: ' + six.text_type(item.bitrate / 1000) # Missing 'audio'. (pos, total) = self.player.time() - yield u'time: ' + unicode(pos) + u':' + unicode(total) + yield u'time: ' + six.text_type(pos) + u':' + six.text_type(total) # Also missing 'updating_db'. @@ -957,13 +958,13 @@ class Server(BaseServer): artists, albums, songs, totaltime = tx.query(statement)[0] yield ( - u'artists: ' + unicode(artists), - u'albums: ' + unicode(albums), - u'songs: ' + unicode(songs), - u'uptime: ' + unicode(int(time.time() - self.startup_time)), + u'artists: ' + six.text_type(artists), + u'albums: ' + six.text_type(albums), + u'songs: ' + six.text_type(songs), + u'uptime: ' + six.text_type(int(time.time() - self.startup_time)), u'playtime: ' + u'0', # Missing. - u'db_playtime: ' + unicode(int(totaltime)), - u'db_update: ' + unicode(int(self.updated_time)), + u'db_playtime: ' + six.text_type(int(totaltime)), + u'db_update: ' + six.text_type(int(self.updated_time)), ) # Searching. @@ -1059,7 +1060,7 @@ class Server(BaseServer): rows = tx.query(statement, subvals) for row in rows: - yield show_tag_canon + u': ' + unicode(row[0]) + yield show_tag_canon + u': ' + six.text_type(row[0]) def cmd_count(self, conn, tag, value): """Returns the number and total time of songs matching the @@ -1071,8 +1072,8 @@ class Server(BaseServer): for item in self.lib.items(dbcore.query.MatchQuery(key, value)): songs += 1 playtime += item.length - yield u'songs: ' + unicode(songs) - yield u'playtime: ' + unicode(int(playtime)) + yield u'songs: ' + six.text_type(songs) + yield u'playtime: ' + six.text_type(int(playtime)) # "Outputs." Just a dummy implementation because we don't control # any outputs. @@ -1180,11 +1181,12 @@ class BPDPlugin(BeetsPlugin): ) def func(lib, opts, args): - host = args.pop(0) if args else self.config['host'].get(unicode) + host = self.config['host'].get(six.text_type) + 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(unicode) + password = self.config['password'].get(six.text_type) volume = self.config['volume'].get(int) debug = opts.debug or False self.start_bpd(lib, host, int(port), password, volume, debug) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index e90a5a44e..8fa0f7a81 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -19,6 +19,7 @@ music player. from __future__ import division, absolute_import, print_function +import six import sys import time from six.moves import _thread @@ -128,7 +129,7 @@ class GstPlayer(object): path. """ self.player.set_state(Gst.State.NULL) - if isinstance(path, unicode): + if isinstance(path, six.text_type): path = path.encode('utf8') uri = 'file://' + urllib.parse.quote(path) self.player.set_property("uri", uri) diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 148e9c20c..4881113a4 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -26,6 +26,7 @@ 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 @@ -181,7 +182,7 @@ class AcoustidPlugin(plugins.BeetsPlugin): def submit_cmd_func(lib, opts, args): try: - apikey = config['acoustid']['apikey'].get(unicode) + apikey = config['acoustid']['apikey'].get(six.text_type) except confit.NotFoundError: raise ui.UserError(u'no Acoustid user API key provided') submit_items(self._log, apikey, lib.items(ui.decargs(args))) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 21a348bab..63057b46f 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -29,6 +29,7 @@ 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. @@ -55,7 +56,7 @@ def get_format(fmt=None): """Return the command template and the extension from the config. """ if not fmt: - fmt = config['convert']['format'].get(unicode).lower() + fmt = config['convert']['format'].get(six.text_type).lower() fmt = ALIASES.get(fmt, fmt) try: @@ -74,14 +75,14 @@ def get_format(fmt=None): # Convenience and backwards-compatibility shortcuts. keys = config['convert'].keys() if 'command' in keys: - command = config['convert']['command'].get(unicode) + command = config['convert']['command'].get(six.text_type) 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(unicode) + config['convert']['opts'].get(six.text_type) ) if 'extension' in keys: - extension = config['convert']['extension'].get(unicode) + extension = config['convert']['extension'].get(six.text_type) return (command.encode('utf8'), extension.encode('utf8')) @@ -389,7 +390,7 @@ class ConvertPlugin(BeetsPlugin): path_formats = ui.get_path_formats() if not opts.format: - opts.format = self.config['format'].get(unicode).lower() + opts.format = self.config['format'].get(six.text_type).lower() pretend = opts.pretend if opts.pretend is not None else \ self.config['pretend'].get(bool) @@ -422,7 +423,7 @@ class ConvertPlugin(BeetsPlugin): """Transcode a file automatically after it is imported into the library. """ - fmt = self.config['format'].get(unicode).lower() + fmt = self.config['format'].get(six.text_type).lower() if should_transcode(item, fmt): command, ext = get_format() diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 4252900e0..b33dec7ed 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -34,6 +34,7 @@ import time import json import socket import os +import six # Silence spurious INFO log lines generated by urllib3. @@ -66,8 +67,8 @@ class DiscogsPlugin(BeetsPlugin): def setup(self, session=None): """Create the `discogs_client` field. Authenticate if necessary. """ - c_key = self.config['apikey'].get(unicode) - c_secret = self.config['apisecret'].get(unicode) + c_key = self.config['apikey'].get(six.text_type) + c_secret = self.config['apisecret'].get(six.text_type) # Get the OAuth token from a file or log in. try: @@ -225,7 +226,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(unicode) + artist = config['va_name'].get(six.text_type) year = result.data['year'] label = result.data['labels'][0]['name'] mediums = len(set(t.medium for t in tracks)) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 4f0397171..f9b089e0f 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -23,6 +23,7 @@ from beets.plugins import BeetsPlugin from beets.ui import decargs, print_, vararg_callback, Subcommand, UserError from beets.util import command_output, displayable_path, subprocess from beets.library import Item, Album +import six PLUGIN = 'duplicates' @@ -264,7 +265,7 @@ class DuplicatesPlugin(BeetsPlugin): # between a bytes object and the empty Unicode # string ''. return v is not None and \ - (v != '' if isinstance(v, unicode) else True) + (v != '' if isinstance(v, six.text_type) else True) fields = kind.all_keys() key = lambda x: sum(1 for f in fields if truthy(getattr(x, f))) else: diff --git a/beetsplug/edit.py b/beetsplug/edit.py index c8522849d..4a55e59ed 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -27,6 +27,7 @@ import subprocess import yaml from tempfile import NamedTemporaryFile import os +import six # These "safe" types can avoid the format/parse cycle that most fields go @@ -82,7 +83,7 @@ def load(s): # Convert all keys to strings. They started out as strings, # but the user may have inadvertently messed this up. - out.append({unicode(k): v for k, v in d.items()}) + out.append({six.text_type(k): v for k, v in d.items()}) except yaml.YAMLError as e: raise ParseError(u'invalid YAML: {}'.format(e)) @@ -141,7 +142,7 @@ def apply_(obj, data): else: # Either the field was stringified originally or the user changed # it from a safe type to an unsafe one. Parse it as a string. - obj.set_parse(key, unicode(value)) + obj.set_parse(key, six.text_type(value)) class EditPlugin(plugins.BeetsPlugin): diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a2ce1661d..3109bce65 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -32,6 +32,7 @@ from beets import config from beets.util.artresizer import ArtResizer from beets.util import confit from beets.util import syspath, bytestring_path +import six try: import itunes @@ -696,7 +697,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): confit.String(pattern=self.PAT_PERCENT)])) self.margin_px = None self.margin_percent = None - if type(self.enforce_ratio) is unicode: + if type(self.enforce_ratio) is six.text_type: if self.enforce_ratio[-1] == u'%': self.margin_percent = float(self.enforce_ratio[:-1]) / 100 elif self.enforce_ratio[-2:] == u'px': diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index e9c49bee3..648df6258 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -22,6 +22,7 @@ from beets import plugins from beets.util import displayable_path import os import re +import six # Filename field extraction patterns. @@ -132,7 +133,7 @@ def apply_matches(d): # Apply the title and track. for item in d: if bad_title(item.title): - item.title = unicode(d[item][title_field]) + item.title = six.text_type(d[item][title_field]) if 'track' in d[item] and item.track == 0: item.track = int(d[item]['track']) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index eefdfcf15..4e415b48d 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -22,6 +22,7 @@ import re from beets import plugins from beets import ui from beets.util import displayable_path +import six def split_on_feat(artist): @@ -137,7 +138,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(unicode) + feat_format = self.config['format'].get(six.text_type) 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) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 4f2b8f0e2..80daad68c 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -21,6 +21,7 @@ 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): @@ -79,8 +80,8 @@ class HookPlugin(BeetsPlugin): for hook_index in range(len(hooks)): hook = self.config['hooks'][hook_index] - hook_event = hook['event'].get(unicode) - hook_command = hook['command'].get(unicode) + hook_event = hook['event'].get(six.text_type) + hook_command = hook['command'].get(six.text_type) self.create_and_register_hook(hook_event, hook_command) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 0d9e50616..e02c5793f 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -14,6 +14,7 @@ # 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 @@ -119,7 +120,7 @@ class ImportFeedsPlugin(BeetsPlugin): if 'm3u' in formats: m3u_basename = bytestring_path( - self.config['m3u_name'].get(unicode)) + self.config['m3u_name'].get(six.text_type)) m3u_path = os.path.join(feedsdir, m3u_basename) _write_m3u(m3u_path, paths) diff --git a/beetsplug/inline.py b/beetsplug/inline.py index 6e3771f2a..5787b739e 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -22,6 +22,7 @@ import itertools from beets.plugins import BeetsPlugin from beets import config +import six FUNC_NAME = u'__INLINE_FUNC__' @@ -32,7 +33,7 @@ class InlineError(Exception): def __init__(self, code, exc): super(InlineError, self).__init__( (u"error in inline path field code:\n" - u"%s\n%s: %s") % (code, type(exc).__name__, unicode(exc)) + u"%s\n%s: %s") % (code, type(exc).__name__, six.text_type(exc)) ) @@ -64,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(unicode), False) + func = self.compile_inline(view.get(six.text_type), 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(unicode), True) + func = self.compile_inline(view.get(six.text_type), True) if func is not None: self.album_template_fields[key] = func diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index b6131a4b0..dad62487f 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -23,6 +23,7 @@ import subprocess from beets import ui from beets import util from beets.plugins import BeetsPlugin +import six class KeyFinderPlugin(BeetsPlugin): @@ -52,7 +53,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(unicode)) + bin = util.bytestring_path(self.config['bin'].get(six.text_type)) for item in items: if item['initial_key'] and not overwrite: diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 97daafb6b..abda7ed6b 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -14,6 +14,7 @@ # included in all copies or substantial portions of the Software. from __future__ import division, absolute_import, print_function +import six """Gets genres for imported music based on Last.fm tags. @@ -71,7 +72,7 @@ def flatten_tree(elem, path, branches): for sub in elem: flatten_tree(sub, path, branches) else: - branches.append(path + [unicode(elem)]) + branches.append(path + [six.text_type(elem)]) def find_parents(candidate, branches): @@ -186,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(unicode).join( + return self.config['separator'].get(six.text_type).join( tags[:self.config['count'].get(int)] ) @@ -221,7 +222,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): if any(not s for s in args): return None - key = u'{0}.{1}'.format(entity, u'-'.join(unicode(a) for a in args)) + key = u'{0}.{1}'.format(entity, + u'-'.join(six.text_type(a) for a in args)) if key in self._genre_cache: return self._genre_cache[key] else: @@ -297,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(unicode): + elif obj.albumartist != config['va_name'].get(six.text_type): result = self.fetch_album_artist_genre(obj) else: # For "Various Artists", pick the most popular track genre. diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index e31863da7..4d0557331 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -23,6 +23,7 @@ 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 +112,7 @@ class CustomUser(pylast.User): def import_lastfm(lib, log): - user = config['lastfm']['user'].get(unicode) + user = config['lastfm']['user'].get(six.text_type) per_page = config['lastimport']['per_page'].get(int) if not user: diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f7bc674fb..5d19b1dca 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -27,6 +27,7 @@ import unicodedata import warnings from six.moves.html_parser import HTMLParseError from six.moves import urllib +import six try: from bs4 import SoupStrainer, BeautifulSoup @@ -177,7 +178,7 @@ class Backend(object): @staticmethod def _encode(s): """Encode the string for inclusion in a URL""" - if isinstance(s, unicode): + if isinstance(s, six.text_type): for char, repl in URL_CHARACTERS.items(): s = s.replace(char, repl) s = s.encode('utf8', 'ignore') @@ -250,7 +251,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(unicode) + self.api_key = config['genius_api_key'].get(six.text_type) self.headers = {'Authorization': "Bearer %s" % self.api_key} def search_genius(self, artist, title): @@ -461,8 +462,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(unicode) - self.engine_id = config['google_engine_ID'].get(unicode) + self.api_key = config['google_API_key'].get(six.text_type) + self.engine_id = config['google_engine_ID'].get(six.text_type) def is_lyrics(self, text, artist=None): """Determine whether the text seems to be valid lyrics. @@ -503,7 +504,7 @@ class Google(Backend): try: text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') - text = unicode(re.sub('[-\s]+', ' ', text.decode('utf-8'))) + text = six.text_type(re.sub('[-\s]+', ' ', text.decode('utf-8'))) except UnicodeDecodeError: self._log.exception(u"Failing to normalize '{0}'", text) return text diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index b95ba6fed..0760be0e5 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -22,6 +22,7 @@ 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}$' @@ -57,8 +58,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): super(MusicBrainzCollectionPlugin, self).__init__() config['musicbrainz']['pass'].redact = True musicbrainzngs.auth( - config['musicbrainz']['user'].get(unicode), - config['musicbrainz']['pass'].get(unicode), + config['musicbrainz']['user'].get(six.text_type), + config['musicbrainz']['pass'].get(six.text_type), ) self.config.add({'auto': False}) if self.config['auto']: diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index fedf3276c..ca8dc9c7b 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -27,6 +27,7 @@ from beets import plugins from beets import library from beets.util import displayable_path from beets.dbcore import types +import six # If we lose the connection, how many times do we want to retry and how # much time should we wait between retries? @@ -49,7 +50,7 @@ def is_url(path): # see http://www.tarmack.eu/code/mpdunicode.py for the general idea class MPDClient(mpd.MPDClient): def _write_command(self, command, args=[]): - args = [unicode(arg).encode('utf-8') for arg in args] + args = [six.text_type(arg).encode('utf-8') for arg in args] super(MPDClient, self)._write_command(command, args) def _read_line(self): @@ -64,14 +65,14 @@ class MPDClientWrapper(object): self._log = log self.music_directory = ( - mpd_config['music_directory'].get(unicode)) + mpd_config['music_directory'].get(six.text_type)) self.client = MPDClient() def connect(self): """Connect to the MPD. """ - host = mpd_config['host'].get(unicode) + host = mpd_config['host'].get(six.text_type) port = mpd_config['port'].get(int) if host[0] in ['/', '~']: @@ -83,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(unicode) + password = mpd_config['password'].get(six.text_type) if password: try: self.client.password(password) diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index f828ba5d7..36449a5ac 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -27,6 +27,7 @@ from beets.plugins import BeetsPlugin import os import socket from beets import config +import six # No need to introduce a dependency on an MPD library for such a @@ -86,9 +87,9 @@ class MPDUpdatePlugin(BeetsPlugin): def update(self, lib): self.update_mpd( - config['mpd']['host'].get(unicode), + config['mpd']['host'].get(six.text_type), config['mpd']['port'].get(int), - config['mpd']['password'].get(unicode), + config['mpd']['password'].get(six.text_type), ) def update_mpd(self, host='localhost', port=6600, password=None): @@ -101,7 +102,7 @@ class MPDUpdatePlugin(BeetsPlugin): s = BufferedSocket(host, port) except socket.error as e: self._log.warning(u'MPD connection failed: {0}', - unicode(e.strerror)) + six.text_type(e.strerror)) return resp = s.readline() diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index e06407037..27659ca27 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -27,6 +27,7 @@ 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. @@ -102,7 +103,7 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = b'--' + bytes(config['method'].get(unicode)) + self.method = b'--' + bytes(config['method'].get(six.text_type)) cmd = b'bs1770gain' try: @@ -256,7 +257,7 @@ class CommandBackend(Backend): 'noclip': True, }) - self.command = config["command"].get(unicode) + self.command = config["command"].get(six.text_type) if self.command: # Explicit executable path. @@ -809,7 +810,7 @@ class ReplayGainPlugin(BeetsPlugin): }) self.overwrite = self.config['overwrite'].get(bool) - backend_name = self.config['backend'].get(unicode) + backend_name = self.config['backend'].get(six.text_type) if backend_name not in self.backends: raise ui.UserError( u"Selected ReplayGain backend {0} is not supported. " diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index b0104a118..ef9aa0c9a 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -24,6 +24,7 @@ from collections import defaultdict from beets.plugins import BeetsPlugin from beets import ui from beets import library +import six def rewriter(field, rules): @@ -51,7 +52,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(unicode) + value = view.get(six.text_type) try: fieldname, pattern = key.split(None, 1) except ValueError: diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 77df15790..33570b5e4 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -9,6 +9,7 @@ from beets.plugins import BeetsPlugin from beets.ui import decargs from beets import ui from requests.exceptions import HTTPError +import six class SpotifyPlugin(BeetsPlugin): @@ -170,6 +171,6 @@ class SpotifyPlugin(BeetsPlugin): else: for item in ids: - print(unicode.encode(self.open_url + item)) + print(six.text_type.encode(self.open_url + item)) else: self._log.warn(u'No Spotify tracks found from beets query') diff --git a/beetsplug/the.py b/beetsplug/the.py index 6bed4c6ed..149233c45 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -19,6 +19,7 @@ from __future__ import division, absolute_import, print_function import re from beets.plugins import BeetsPlugin +import six __author__ = 'baobab@heresiarch.info' __version__ = '1.1' @@ -81,7 +82,7 @@ class ThePlugin(BeetsPlugin): if self.config['strip']: return r else: - fmt = self.config['format'].get(unicode) + fmt = self.config['format'].get(six.text_type) return fmt.format(r, t.strip()).strip() else: return u'' diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index ce0a9490e..1ea90f01e 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -35,6 +35,7 @@ from beets.plugins import BeetsPlugin from beets.ui import Subcommand, decargs from beets import util from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version +import six BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") @@ -169,8 +170,9 @@ class ThumbnailsPlugin(BeetsPlugin): """Write required metadata to the thumbnail See http://standards.freedesktop.org/thumbnail-spec/latest/x142.html """ + mtime = os.stat(album.artpath).st_mtime metadata = {"Thumb::URI": self.get_uri(album.artpath), - "Thumb::MTime": unicode(os.stat(album.artpath).st_mtime)} + "Thumb::MTime": six.text_type(mtime)} try: self.write_metadata(image_path, metadata) except Exception: diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 67d99db67..6f480fb36 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -25,6 +25,7 @@ from flask import g from werkzeug.routing import BaseConverter, PathConverter import os import json +import six # Utilities. @@ -321,7 +322,7 @@ class WebPlugin(BeetsPlugin): } CORS(app) # Start the web application. - app.run(host=self.config['host'].get(unicode), + app.run(host=self.config['host'].get(six.text_type), port=self.config['port'].get(int), debug=opts.debug, threaded=True) cmd.func = func diff --git a/beetsplug/zero.py b/beetsplug/zero.py index d20f76166..80925741b 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -22,6 +22,7 @@ from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action from beets.util import confit +import six __author__ = 'baobab@heresiarch.info' __version__ = '0.10' @@ -113,7 +114,7 @@ class ZeroPlugin(BeetsPlugin): if patterns is True: return True for p in patterns: - if re.search(p, unicode(field), flags=re.IGNORECASE): + if re.search(p, six.text_type(field), flags=re.IGNORECASE): return True return False diff --git a/test/helper.py b/test/helper.py index d2fe5cc81..0d37e90eb 100644 --- a/test/helper.py +++ b/test/helper.py @@ -56,6 +56,7 @@ from beets import util # TODO Move AutotagMock here from test import _common +import six class LogCapture(logging.Handler): @@ -65,7 +66,7 @@ class LogCapture(logging.Handler): self.messages = [] def emit(self, record): - self.messages.append(unicode(record.msg)) + self.messages.append(six.text_type(record.msg)) @contextmanager @@ -121,7 +122,7 @@ def has_program(cmd, args=['--version']): """ full_cmd = [cmd] + args for i, elem in enumerate(full_cmd): - if isinstance(elem, unicode): + if isinstance(elem, six.text_type): full_cmd[i] = elem.encode(_arg_encoding()) try: with open(os.devnull, 'wb') as devnull: diff --git a/test/test_config_command.py b/test/test_config_command.py index 77a370ce3..d59181373 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -14,6 +14,7 @@ from beets import config from test._common import unittest from test.helper import TestHelper, capture_stdout from beets.library import Library +import six class ConfigCommandTest(unittest.TestCase, TestHelper): @@ -114,8 +115,8 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): execlp.side_effect = OSError('here is problem') self.run_command('config', '-e') self.assertIn('Could not edit configuration', - unicode(user_error.exception)) - self.assertIn('here is problem', unicode(user_error.exception)) + six.text_type(user_error.exception)) + self.assertIn('here is problem', six.text_type(user_error.exception)) def test_edit_invalid_config_file(self): self.lib = Library(':memory:') diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 67a96e4f2..8fc8532c6 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -26,6 +26,7 @@ from test import _common from test._common import unittest from beets import dbcore from tempfile import mkstemp +import six # Fixture: concrete database and model classes. For migration tests, we @@ -350,7 +351,7 @@ class FormatTest(unittest.TestCase): model = TestModel1() model.other_field = u'caf\xe9'.encode('utf8') value = model.formatted().get('other_field') - self.assertTrue(isinstance(value, unicode)) + self.assertTrue(isinstance(value, six.text_type)) self.assertEqual(value, u'caf\xe9') def test_format_unset_field(self): diff --git a/test/test_library.py b/test/test_library.py index 4cd922910..b1ac76c25 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -38,6 +38,7 @@ from beets import config from beets.mediafile import MediaFile from beets.util import syspath, bytestring_path from test.helper import TestHelper +import six # Shortcut to path normalization. np = util.normpath @@ -964,7 +965,7 @@ class PathStringTest(_common.TestCase): def test_sanitize_path_returns_unicode(self): path = u'b\xe1r?' new_path = util.sanitize_path(path) - self.assertTrue(isinstance(new_path, unicode)) + self.assertTrue(isinstance(new_path, six.text_type)) def test_unicode_artpath_becomes_bytestring(self): alb = self.lib.add_album([self.i]) @@ -1051,7 +1052,7 @@ class TemplateTest(_common.LibTestCase): album.tagada = u'togodo' self.assertEqual(u"{0}".format(album), u"foö bar") self.assertEqual(u"{0:$tagada}".format(album), u"togodo") - self.assertEqual(unicode(album), u"foö bar") + self.assertEqual(six.text_type(album), u"foö bar") self.assertEqual(bytes(album), b"fo\xc3\xb6 bar") config['format_item'] = 'bar $foo' @@ -1174,7 +1175,8 @@ class LibraryFieldTypesTest(unittest.TestCase): t = beets.library.DateType() # format - time_local = time.strftime(beets.config['time_format'].get(unicode), + time_format = beets.config['time_format'].get(six.text_type) + time_local = time.strftime(time_format, time.localtime(123456789)) self.assertEqual(time_local, t.format(123456789)) # parse diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 9136131c1..d49c4d980 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -29,6 +29,7 @@ from beetsplug import lyrics from beets.library import Item from beets.util import confit, bytestring_path from beets import logging +import six log = logging.getLogger('beets.test_lyrics') raw_backend = lyrics.Backend({}, log) @@ -354,7 +355,7 @@ class LyricsGooglePluginTest(unittest.TestCase): present in the title.""" from bs4 import SoupStrainer, BeautifulSoup s = self.source - url = unicode(s['url'] + s['path']) + url = six.text_type(s['url'] + s['path']) html = raw_backend.fetch_url(url) soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 2405e7fd3..258e03896 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -33,6 +33,7 @@ from beets.mediafile import MediaFile, MediaField, Image, \ from beets.library import Item from beets.plugins import BeetsPlugin from beets.util import bytestring_path +import six class ArtTestMixin(object): @@ -353,13 +354,13 @@ class ExtendedFieldTestMixin(object): with self.assertRaises(ValueError) as cm: MediaFile.add_field('somekey', True) self.assertIn(u'must be an instance of MediaField', - unicode(cm.exception)) + six.text_type(cm.exception)) def test_overwrite_property(self): with self.assertRaises(ValueError) as cm: MediaFile.add_field('artist', MediaField()) self.assertIn(u'property "artist" already exists', - unicode(cm.exception)) + six.text_type(cm.exception)) class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 26d88ae74..9fbf4e2bb 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -26,6 +26,7 @@ from test.helper import TestHelper from beets.util import bytestring_path import beets.mediafile +import six _sc = beets.mediafile._safe_cast @@ -127,8 +128,8 @@ class InvalidValueToleranceTest(unittest.TestCase): self.assertAlmostEqual(_sc(float, u'-1.234'), -1.234) def test_safe_cast_special_chars_to_unicode(self): - us = _sc(unicode, 'caf\xc3\xa9') - self.assertTrue(isinstance(us, unicode)) + us = _sc(six.text_type, 'caf\xc3\xa9') + self.assertTrue(isinstance(us, six.text_type)) self.assertTrue(us.startswith(u'caf')) def test_safe_cast_float_with_no_numbers(self): @@ -350,7 +351,7 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf.year = 2013 mf.save() frame = mf.mgfile['TDRC'] - self.assertTrue('2013' in unicode(frame)) + self.assertTrue('2013' in six.text_type(frame)) self.assertTrue('TYER' not in mf.mgfile) finally: self._delete_test() @@ -361,7 +362,7 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf.year = 2013 mf.save() frame = mf.mgfile['TYER'] - self.assertTrue('2013' in unicode(frame)) + self.assertTrue('2013' in six.text_type(frame)) self.assertTrue('TDRC' not in mf.mgfile) finally: self._delete_test() diff --git a/test/test_query.py b/test/test_query.py index 707d9d182..d9b181930 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -33,6 +33,7 @@ from beets.dbcore.query import (NoneQuery, ParsingError, from beets.library import Library, Item from beets import util import platform +import six class TestHelper(helper.TestHelper): @@ -301,12 +302,13 @@ class GetTest(DummyDataTestCase): def test_invalid_query(self): with self.assertRaises(InvalidQueryArgumentTypeError) as raised: dbcore.query.NumericQuery('year', u'199a') - self.assertIn(u'not an int', unicode(raised.exception)) + self.assertIn(u'not an int', six.text_type(raised.exception)) with self.assertRaises(InvalidQueryArgumentTypeError) as raised: dbcore.query.RegexpQuery('year', u'199(') - self.assertIn(u'not a regular expression', unicode(raised.exception)) - self.assertIn(u'unbalanced parenthesis', unicode(raised.exception)) + exception = six.text_type(raised.exception) + self.assertIn(u'not a regular expression', exception) + self.assertIn(u'unbalanced parenthesis', exception) self.assertIsInstance(raised.exception, ParsingError) diff --git a/test/test_template.py b/test/test_template.py index 3ec97bea4..868696a67 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -21,6 +21,7 @@ import warnings from test._common import unittest from beets.util import functemplate +import six def _normexpr(expr): @@ -227,7 +228,7 @@ class EvalTest(unittest.TestCase): u'baz': u'BaR', } functions = { - u'lower': unicode.lower, + u'lower': six.text_type.lower, u'len': len, } return functemplate.Template(template).substitute(values, functions) diff --git a/test/test_ui.py b/test/test_ui.py index d14febbff..78d777f9e 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -39,6 +39,7 @@ from beets import config from beets import plugins from beets.util.confit import ConfigError from beets import util +import six class ListTest(unittest.TestCase): @@ -1257,15 +1258,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$foo') self.assertEqual(parser.parse_args([]), ({'path': None}, [])) - self.assertEqual(config['format_item'].get(unicode), u'$foo') + self.assertEqual(config['format_item'].get(six.text_type), 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(unicode), u'$path') - self.assertEqual(config['format_album'].get(unicode), u'$path') + self.assertEqual(config['format_item'].get(six.text_type), u'$path') + self.assertEqual(config['format_album'].get(six.text_type), u'$path') def test_format_option(self): parser = ui.CommonOptionsParser() @@ -1274,15 +1275,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_item'].set('$foo') self.assertEqual(parser.parse_args([]), ({'format': None}, [])) - self.assertEqual(config['format_item'].get(unicode), u'$foo') + self.assertEqual(config['format_item'].get(six.text_type), 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(unicode), u'$baz') - self.assertEqual(config['format_album'].get(unicode), u'$baz') + self.assertEqual(config['format_item'].get(six.text_type), u'$baz') + self.assertEqual(config['format_album'].get(six.text_type), u'$baz') def test_format_option_with_target(self): with self.assertRaises(KeyError): @@ -1297,8 +1298,8 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): self.assertEqual(parser.parse_args([u'-f', u'$bar']), ({'format': u'$bar'}, [])) - self.assertEqual(config['format_item'].get(unicode), u'$bar') - self.assertEqual(config['format_album'].get(unicode), u'$album') + self.assertEqual(config['format_item'].get(six.text_type), u'$bar') + self.assertEqual(config['format_album'].get(six.text_type), u'$album') def test_format_option_with_album(self): parser = ui.CommonOptionsParser() @@ -1309,15 +1310,15 @@ class CommonOptionsParserTest(unittest.TestCase, TestHelper): config['format_album'].set('$album') parser.parse_args([u'-f', u'$bar']) - self.assertEqual(config['format_item'].get(unicode), u'$bar') - self.assertEqual(config['format_album'].get(unicode), u'$album') + self.assertEqual(config['format_item'].get(six.text_type), u'$bar') + self.assertEqual(config['format_album'].get(six.text_type), u'$album') parser.parse_args([u'-a', u'-f', u'$foo']) - self.assertEqual(config['format_item'].get(unicode), u'$bar') - self.assertEqual(config['format_album'].get(unicode), u'$foo') + self.assertEqual(config['format_item'].get(six.text_type), u'$bar') + self.assertEqual(config['format_album'].get(six.text_type), u'$foo') parser.parse_args([u'-f', u'$foo2', u'-a']) - self.assertEqual(config['format_album'].get(unicode), u'$foo2') + self.assertEqual(config['format_album'].get(six.text_type), u'$foo2') def test_add_all_common_options(self): parser = ui.CommonOptionsParser() diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index 4596e781a..cc2938ad3 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -26,6 +26,7 @@ from test import test_importer from beets.ui.commands import TerminalImportSession from beets import importer from beets import config +import six class TestTerminalImportSession(TerminalImportSession): @@ -69,7 +70,7 @@ class TestTerminalImportSession(TerminalImportSession): self.io.addinput(u'S') elif isinstance(choice, int): self.io.addinput(u'M') - self.io.addinput(unicode(choice)) + self.io.addinput(six.text_type(choice)) self._add_choice_input() else: raise Exception(u'Unknown choice %s' % choice) diff --git a/test/test_util.py b/test/test_util.py index 32028c9fb..f4c2eca80 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -26,6 +26,7 @@ from mock import patch, Mock from test._common import unittest from test import _common from beets import util +import six class UtilTest(unittest.TestCase): @@ -122,7 +123,7 @@ class PathConversionTest(_common.TestCase): with _common.platform_windows(): path = os.path.join(u'a', u'b', u'c') outpath = util.syspath(path) - self.assertTrue(isinstance(outpath, unicode)) + self.assertTrue(isinstance(outpath, six.text_type)) self.assertTrue(outpath.startswith(u'\\\\?\\')) def test_syspath_windows_format_unc_path(self): @@ -131,7 +132,7 @@ class PathConversionTest(_common.TestCase): path = '\\\\server\\share\\file.mp3' with _common.platform_windows(): outpath = util.syspath(path) - self.assertTrue(isinstance(outpath, unicode)) + self.assertTrue(isinstance(outpath, six.text_type)) self.assertEqual(outpath, u'\\\\?\\UNC\\server\\share\\file.mp3') def test_syspath_posix_unchanged(self): From e57b7faf69df216bca63a841c97ae1805719c208 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 04:47:38 -0400 Subject: [PATCH 1039/2280] replace basestring with six.text_types --- beets/autotag/mb.py | 2 +- beets/dbcore/db.py | 4 ++-- beets/dbcore/query.py | 4 ++-- beets/library.py | 2 +- beets/mediafile.py | 4 ++-- beets/plugins.py | 5 +++-- beets/ui/__init__.py | 9 +++++---- beets/util/functemplate.py | 8 ++++---- beetsplug/bpd/__init__.py | 2 +- beetsplug/fuzzy.py | 3 ++- beetsplug/smartplaylist.py | 3 ++- test/test_lastgenre.py | 5 +++-- test/test_template.py | 4 ++-- 13 files changed, 30 insertions(+), 25 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 8aafe36e2..d2700773a 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -110,7 +110,7 @@ def _flatten_artist_credit(credit): artist_sort_parts = [] artist_credit_parts = [] for el in credit: - if isinstance(el, basestring): + if isinstance(el, six.string_types): # Join phrase. artist_parts.append(el) artist_credit_parts.append(el) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 19d5c51e6..229fd0f66 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -453,7 +453,7 @@ class Model(object): separators will be added to the template. """ # Perform substitution. - if isinstance(template, basestring): + if isinstance(template, six.string_types): template = Template(template) return template.substitute(self.formatted(for_path), self._template_funcs()) @@ -464,7 +464,7 @@ class Model(object): def _parse(cls, key, string): """Parse a string as a value for the given key. """ - if not isinstance(string, basestring): + if not isinstance(string, six.string_types): raise TypeError(u"_parse() argument must be a string") return cls._type(key).parse(string) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f95e4ac60..001e84616 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -230,7 +230,7 @@ class BooleanQuery(MatchQuery): """ def __init__(self, field, pattern, fast=True): super(BooleanQuery, self).__init__(field, pattern, fast) - if isinstance(pattern, basestring): + if isinstance(pattern, six.string_types): self.pattern = util.str2bool(pattern) self.pattern = int(self.pattern) @@ -303,7 +303,7 @@ class NumericQuery(FieldQuery): if self.field not in item: return False value = item[self.field] - if isinstance(value, basestring): + if isinstance(value, six.string_types): value = self._convert(value) if self.point is not None: diff --git a/beets/library.py b/beets/library.py index e672187a8..f46092fe2 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1258,7 +1258,7 @@ class Library(dbcore.Database): # Parse the query, if necessary. try: parsed_sort = None - if isinstance(query, basestring): + if isinstance(query, six.string_types): query, parsed_sort = parse_query_string(query, model_cls) elif isinstance(query, (list, tuple)): query, parsed_sort = parse_query_parts(query, model_cls) diff --git a/beets/mediafile.py b/beets/mediafile.py index 278e848b8..dbe035d5a 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -131,7 +131,7 @@ def _safe_cast(out_type, val): return int(val) else: # Process any other type as a string. - if not isinstance(val, basestring): + if not isinstance(val, six.string_types): val = six.text_type(val) # Get a number from the front of the string. val = re.match(r'[0-9]*', val.strip()).group(0) @@ -1196,7 +1196,7 @@ class DateField(MediaField): """ # Get the underlying data and split on hyphens and slashes. datestring = super(DateField, self).__get__(mediafile, None) - if isinstance(datestring, basestring): + if isinstance(datestring, six.string_types): datestring = re.sub(r'[Tt ].*$', '', six.text_type(datestring)) items = re.split('[-/]', six.text_type(datestring)) else: diff --git a/beets/plugins.py b/beets/plugins.py index 239f64fbb..8fe4c6d0c 100755 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -27,6 +27,7 @@ from functools import wraps import beets from beets import logging from beets import mediafile +import six PLUGIN_NAMESPACE = 'beetsplug' @@ -54,10 +55,10 @@ class PluginLogFilter(logging.Filter): def filter(self, record): if hasattr(record.msg, 'msg') and isinstance(record.msg.msg, - basestring): + six.string_types): # A _LogMessage from our hacked-up Logging replacement. record.msg.msg = self.prefix + record.msg.msg - elif isinstance(record.msg, basestring): + elif isinstance(record.msg, six.string_types): record.msg = self.prefix + record.msg return True diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 61176307f..ce3c46f31 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -263,7 +263,7 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None, # Mark the option's shortcut letter for display. if not require and ( (default is None and not numrange and first) or - (isinstance(default, basestring) and + (isinstance(default, six.string_types) and found_letter.lower() == default.lower())): # The first option is the default; mark it. show_letter = '[%s]' % found_letter.upper() @@ -544,7 +544,8 @@ def _colordiff(a, b, highlight='text_highlight', highlighted intelligently to show differences; other values are stringified and highlighted in their entirety. """ - if not isinstance(a, basestring) or not isinstance(b, basestring): + if not isinstance(a, six.string_types) \ + or not isinstance(b, six.string_types): # Non-strings: use ordinary equality. a = six.text_type(a) b = six.text_type(b) @@ -674,7 +675,7 @@ def _field_diff(field, old, new): # For strings, highlight changes. For others, colorize the whole # thing. - if isinstance(oldval, basestring): + if isinstance(oldval, six.string_types): oldstr, newstr = colordiff(oldval, newstr) else: oldstr = colorize('text_error', oldstr) @@ -867,7 +868,7 @@ class CommonOptionsParser(optparse.OptionParser, object): """ kwargs = {} if target: - if isinstance(target, basestring): + if isinstance(target, six.string_types): target = {'item': library.Item, 'album': library.Album}[target] kwargs['target'] = target diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 3a07df5bd..ad3d22c92 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -79,7 +79,7 @@ def ex_literal(val): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) - elif isinstance(val, basestring): + elif isinstance(val, six.string_types): return ast.Str(val) raise TypeError(u'no literal for {0}'.format(type(val))) @@ -98,7 +98,7 @@ def ex_call(func, args): function may be an expression or the name of a function. Each argument may be an expression or a value to be used as a literal. """ - if isinstance(func, basestring): + if isinstance(func, six.string_types): func = ex_rvalue(func) args = list(args) @@ -243,7 +243,7 @@ class Expression(object): """ out = [] for part in self.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): out.append(part) else: out.append(part.evaluate(env)) @@ -257,7 +257,7 @@ class Expression(object): varnames = set() funcnames = set() for part in self.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): expressions.append(ex_literal(part)) else: e, v, f = part.translate() diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index ee41ad164..296c5ffdd 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -570,7 +570,7 @@ class Connection(object): added after every string. Returns a Bluelet event that sends the data. """ - if isinstance(lines, basestring): + if isinstance(lines, six.string_types): lines = [lines] out = NEWLINE.join(lines) + NEWLINE log.debug('{}', out[:-1]) # Don't log trailing newline. diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index 3decdc602..1624ee1c1 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -22,6 +22,7 @@ from beets.plugins import BeetsPlugin from beets.dbcore.query import StringFieldQuery from beets import config import difflib +import six class FuzzyQuery(StringFieldQuery): @@ -44,5 +45,5 @@ class FuzzyPlugin(BeetsPlugin): }) def queries(self): - prefix = self.config['prefix'].get(basestring) + prefix = self.config['prefix'].get(six.string_types) return {prefix: FuzzyQuery} diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 1ccb37030..11c5530b2 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -25,6 +25,7 @@ from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import MultipleSort, ParsingError import os +import six class SmartPlaylistPlugin(BeetsPlugin): @@ -106,7 +107,7 @@ class SmartPlaylistPlugin(BeetsPlugin): qs = playlist.get(key) if qs is None: query_and_sort = None, None - elif isinstance(qs, basestring): + elif isinstance(qs, six.string_types): query_and_sort = parse_query_string(qs, Model) elif len(qs) == 1: query_and_sort = parse_query_string(qs[0], Model) diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 19adab98a..c060e95a9 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -25,6 +25,7 @@ from beetsplug import lastgenre from beets import config from test.helper import TestHelper +import six class LastGenrePluginTest(unittest.TestCase, TestHelper): @@ -38,11 +39,11 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): def _setup_config(self, whitelist=False, canonical=False, count=1): config['lastgenre']['canonical'] = canonical config['lastgenre']['count'] = count - if isinstance(whitelist, (bool, basestring)): + if isinstance(whitelist, (bool, six.string_types)): # Filename, default, or disabled. config['lastgenre']['whitelist'] = whitelist self.plugin.setup() - if not isinstance(whitelist, (bool, basestring)): + if not isinstance(whitelist, (bool, six.string_types)): # Explicit list of genres. self.plugin.whitelist = whitelist diff --git a/test/test_template.py b/test/test_template.py index 868696a67..0605675c6 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -31,7 +31,7 @@ def _normexpr(expr): """ textbuf = [] for part in expr.parts: - if isinstance(part, basestring): + if isinstance(part, six.string_types): textbuf.append(part) else: if textbuf: @@ -259,7 +259,7 @@ class EvalTest(unittest.TestCase): def test_function_call_exception(self): res = self._eval(u"%lower{a,b,c,d,e}") - self.assertTrue(isinstance(res, basestring)) + self.assertTrue(isinstance(res, six.string_types)) def test_function_returning_integer(self): self.assertEqual(self._eval(u"%len{foo}"), u"3") From 83f6ba3ce4cd0ce8de796e3a2b36fcd4f58b348c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 04:53:44 -0400 Subject: [PATCH 1040/2280] handle metaclasses with six --- beets/util/artresizer.py | 4 ++-- beetsplug/metasync/__init__.py | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 8468a6ccc..820bc4ed1 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -25,6 +25,7 @@ from tempfile import NamedTemporaryFile from six.moves.urllib.parse import urlencode from beets import logging from beets import util +import six # Resizing methods PIL = 1 @@ -159,10 +160,9 @@ class Shareable(type): return self._instance -class ArtResizer(object): +class ArtResizer(six.with_metaclass(Shareable, object)): """A singleton class that performs image resizes. """ - __metaclass__ = Shareable def __init__(self): """Create a resizer object with an inferred method. diff --git a/beetsplug/metasync/__init__.py b/beetsplug/metasync/__init__.py index 3fc0be4cc..02f0b0f9b 100644 --- a/beetsplug/metasync/__init__.py +++ b/beetsplug/metasync/__init__.py @@ -24,6 +24,7 @@ from importlib import import_module from beets.util.confit import ConfigValueError from beets import ui from beets.plugins import BeetsPlugin +import six METASYNC_MODULE = 'beetsplug.metasync' @@ -35,9 +36,7 @@ SOURCES = { } -class MetaSource(object): - __metaclass__ = ABCMeta - +class MetaSource(six.with_metaclass(ABCMeta, object)): def __init__(self, config, log): self.item_types = {} self.config = config From edb1cbc5fccac3269bc8202002ad31985661df94 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 05:34:15 -0400 Subject: [PATCH 1041/2280] replace iter{items|values} with six.iter{items|values} --- beets/autotag/__init__.py | 3 ++- beets/autotag/hooks.py | 6 +++--- beets/autotag/match.py | 17 +++++++++-------- beets/autotag/mb.py | 4 ++-- beets/dbcore/db.py | 4 ++-- beets/ui/commands.py | 2 +- beetsplug/bpd/__init__.py | 10 +++++----- beetsplug/chroma.py | 2 +- beetsplug/duplicates.py | 2 +- beetsplug/fetchart.py | 2 +- beetsplug/importadded.py | 3 ++- beetsplug/info.py | 7 ++++--- beetsplug/lyrics.py | 2 +- beetsplug/rewrite.py | 2 +- test/test_autotag.py | 3 ++- test/test_edit.py | 3 ++- test/test_importadded.py | 5 +++-- 17 files changed, 42 insertions(+), 35 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index f8233be61..040a5144a 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -25,6 +25,7 @@ from beets import config from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa from .match import tag_item, tag_album # noqa from .match import Recommendation # noqa +import six # Global logger. log = logging.getLogger('beets') @@ -52,7 +53,7 @@ def apply_metadata(album_info, mapping): """Set the items' metadata to match an AlbumInfo object using a mapping from Items to TrackInfo objects. """ - for item, track_info in mapping.iteritems(): + for item, track_info in six.iteritems(mapping): # Album, artist, track count. if track_info.artist: item.artist = track_info.artist diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 154896da7..f9388ad83 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -327,7 +327,7 @@ class Distance(object): """Return the maximum distance penalty (normalization factor). """ dist_max = 0.0 - for key, penalty in self._penalties.iteritems(): + for key, penalty in six.iteritems(self._penalties): dist_max += len(penalty) * self._weights[key] return dist_max @@ -336,7 +336,7 @@ class Distance(object): """Return the raw (denormalized) distance. """ dist_raw = 0.0 - for key, penalty in self._penalties.iteritems(): + for key, penalty in six.iteritems(self._penalties): dist_raw += sum(penalty) * self._weights[key] return dist_raw @@ -408,7 +408,7 @@ class Distance(object): raise ValueError( u'`dist` must be a Distance object, not {0}'.format(type(dist)) ) - for key, penalties in dist._penalties.iteritems(): + for key, penalties in six.iteritems(dist._penalties): self._penalties.setdefault(key, []).extend(penalties) # Adding components. diff --git a/beets/autotag/match.py b/beets/autotag/match.py index ba657cedb..136c7f527 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -30,6 +30,7 @@ from beets.util import plurality from beets.autotag import hooks from beets.util.enumeration import OrderedEnum from functools import reduce +import six # Artist signals that indicate "various artists". These are used at the # album level to determine whether a given release is likely a VA @@ -238,7 +239,7 @@ def distance(items, album_info, mapping): # Tracks. dist.tracks = {} - for item, track in mapping.iteritems(): + for item, track in six.iteritems(mapping): dist.tracks[track] = track_distance(item, track, album_info.va) dist.add('tracks', dist.tracks[track].distance) @@ -312,10 +313,10 @@ def _recommendation(results): keys = set(min_dist.keys()) if isinstance(results[0], hooks.AlbumMatch): for track_dist in min_dist.tracks.values(): - keys.update(track_dist.keys()) + keys.update(list(track_dist.keys())) max_rec_view = config['match']['max_rec'] for key in keys: - if key in max_rec_view.keys(): + if key in list(max_rec_view.keys()): max_rec = max_rec_view[key].as_choice({ 'strong': Recommendation.strong, 'medium': Recommendation.medium, @@ -443,7 +444,7 @@ def tag_album(items, search_artist=None, search_album=None, _add_candidate(items, candidates, info) # Sort and get the recommendation. - candidates = sorted(candidates.itervalues()) + candidates = sorted(six.itervalues(candidates)) rec = _recommendation(candidates) return cur_artist, cur_album, candidates, rec @@ -471,16 +472,16 @@ def tag_item(item, search_artist=None, search_title=None, candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) # If this is a good match, then don't keep searching. - rec = _recommendation(sorted(candidates.itervalues())) + rec = _recommendation(sorted(six.itervalues(candidates))) if rec == Recommendation.strong and \ not config['import']['timid']: log.debug(u'Track ID match.') - return sorted(candidates.itervalues()), rec + return sorted(six.itervalues(candidates)), rec # If we're searching by ID, don't proceed. if search_ids: if candidates: - return sorted(candidates.itervalues()), rec + return sorted(six.itervalues(candidates)), rec else: return [], Recommendation.none @@ -496,6 +497,6 @@ def tag_item(item, search_artist=None, search_title=None, # Sort by distance and return with recommendation. log.debug(u'Found {0} candidates.', len(candidates)) - candidates = sorted(candidates.itervalues()) + candidates = sorted(six.itervalues(candidates)) rec = _recommendation(candidates) return candidates, rec diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index d2700773a..fdbb8e9e7 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -334,7 +334,7 @@ def match_album(artist, album, tracks=None): criteria['tracks'] = six.text_type(tracks) # Abort if we have no search terms. - if not any(criteria.itervalues()): + if not any(six.itervalues(criteria)): return try: @@ -360,7 +360,7 @@ def match_track(artist, title): 'recording': title.lower().strip(), } - if not any(criteria.itervalues()): + if not any(six.itervalues(criteria)): return try: diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 229fd0f66..24bf6bfe8 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -177,9 +177,9 @@ class Model(object): ordinary construction are bypassed. """ obj = cls(db) - for key, value in fixed_values.iteritems(): + for key, value in six.iteritems(fixed_values): obj._values_fixed[key] = cls._type(key).from_sql(value) - for key, value in flex_values.iteritems(): + for key, value in six.iteritems(flex_values): obj._values_flex[key] = cls._type(key).from_sql(value) return obj diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 9b23eafd4..c352fe53d 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -807,7 +807,7 @@ class TerminalImportSession(importer.ImportSession): if search_id: candidates, rec = autotag.tag_item( task.item, search_ids=search_id.split()) - elif choice in extra_ops.keys(): + elif choice in list(extra_ops.keys()): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) if isinstance(post_choice, importer.action): diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 296c5ffdd..5d06028df 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -853,7 +853,7 @@ class Server(BaseServer): for name, itemid in iter(sorted(node.files.items())): item = self.lib.get_item(itemid) yield self._item_info(item) - for name, _ in iter(sorted(node.dirs.iteritems())): + for name, _ in iter(sorted(six.iteritems(node.dirs))): dirpath = self._path_join(path, name) if dirpath.startswith(u"/"): # Strip leading slash (libmpc rejects this). @@ -873,12 +873,12 @@ class Server(BaseServer): yield u'file: ' + basepath else: # List a directory. Recurse into both directories and files. - for name, itemid in sorted(node.files.iteritems()): + for name, itemid in sorted(six.iteritems(node.files)): newpath = self._path_join(basepath, name) # "yield from" for v in self._listall(newpath, itemid, info): yield v - for name, subdir in sorted(node.dirs.iteritems()): + for name, subdir in sorted(six.iteritems(node.dirs)): newpath = self._path_join(basepath, name) yield u'directory: ' + newpath for v in self._listall(newpath, subdir, info): @@ -903,11 +903,11 @@ class Server(BaseServer): yield self.lib.get_item(node) else: # Recurse into a directory. - for name, itemid in sorted(node.files.iteritems()): + for name, itemid in sorted(six.iteritems(node.files)): # "yield from" for v in self._all_items(itemid): yield v - for name, subdir in sorted(node.dirs.iteritems()): + for name, subdir in sorted(six.iteritems(node.dirs)): for v in self._all_items(subdir): yield v diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 4881113a4..54ea54f4c 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -122,7 +122,7 @@ def _all_releases(items): for release_id in release_ids: relcounts[release_id] += 1 - for release_id, count in relcounts.iteritems(): + for release_id, count in six.iteritems(relcounts): if float(count) / len(items) > COMMON_REL_THRESH: yield release_id diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index f9b089e0f..141e36927 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -330,7 +330,7 @@ class DuplicatesPlugin(BeetsPlugin): """Generate triples of keys, duplicate counts, and constituent objects. """ offset = 0 if full else 1 - for k, objs in self._group_by(objs, keys, strict).iteritems(): + for k, objs in six.iteritems(self._group_by(objs, keys, strict)): if len(objs) > 1: objs = self._order(objs, tiebreak) if merge: diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 3109bce65..8700d9de0 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -570,7 +570,7 @@ class Wikipedia(RemoteArtSource): try: data = wikipedia_response.json() results = data['query']['pages'] - for _, result in results.iteritems(): + for _, result in six.iteritems(results): image_url = result['imageinfo'][0]['url'] yield self._candidate(url=image_url, match=Candidate.MATCH_EXACT) diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 77c7e7ab8..707f04abd 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -12,6 +12,7 @@ import os from beets import util from beets import importer from beets.plugins import BeetsPlugin +import six class ImportAddedPlugin(BeetsPlugin): @@ -62,7 +63,7 @@ class ImportAddedPlugin(BeetsPlugin): def record_reimported(self, task, session): self.reimported_item_ids = set(item.id for item, replaced_items - in task.replaced_items.iteritems() + in six.iteritems(task.replaced_items) if replaced_items) self.replaced_album_paths = set(task.replaced_albums.keys()) diff --git a/beetsplug/info.py b/beetsplug/info.py index d29d9b45f..026c8d8e6 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -26,6 +26,7 @@ from beets import ui from beets import mediafile from beets.library import Item from beets.util import displayable_path, normpath, syspath +import six def tag_data(lib, args): @@ -73,7 +74,7 @@ def library_data_emitter(item): def update_summary(summary, tags): - for key, value in tags.iteritems(): + for key, value in six.iteritems(tags): if key not in summary: summary[key] = value elif summary[key] != value: @@ -96,7 +97,7 @@ def print_data(data, item=None, fmt=None): path = displayable_path(item.path) if item else None formatted = {} - for key, value in data.iteritems(): + for key, value in six.iteritems(data): if isinstance(value, list): formatted[key] = u'; '.join(value) if value is not None: @@ -123,7 +124,7 @@ def print_data_keys(data, item=None): """ path = displayable_path(item.path) if item else None formatted = [] - for key, value in data.iteritems(): + for key, value in six.iteritems(data): formatted.append(key) if len(formatted) == 0: diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 5d19b1dca..346abc01a 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -224,7 +224,7 @@ class SymbolsReplaced(Backend): @classmethod def _encode(cls, s): - for old, new in cls.REPLACEMENTS.iteritems(): + for old, new in six.iteritems(cls.REPLACEMENTS): s = re.sub(old, new, s) return super(SymbolsReplaced, cls)._encode(s) diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index ef9aa0c9a..b04973101 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -69,7 +69,7 @@ class RewritePlugin(BeetsPlugin): rules['albumartist'].append((pattern, value)) # Replace each template field with the new rewriter function. - for fieldname, fieldrules in rules.iteritems(): + for fieldname, fieldrules in six.iteritems(rules): getter = rewriter(fieldname, fieldrules) self.template_fields[fieldname] = getter if fieldname in library.Album._fields: diff --git a/test/test_autotag.py b/test/test_autotag.py index 61a4d5d6f..5e6f76ffb 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -29,6 +29,7 @@ from beets.library import Item from beets.util import plurality from beets.autotag import AlbumInfo, TrackInfo from beets import config +import six class PluralityTest(_common.TestCase): @@ -611,7 +612,7 @@ class AssignmentTest(unittest.TestCase): match.assign_items(items, trackinfo) self.assertEqual(extra_items, []) self.assertEqual(extra_tracks, []) - for item, info in mapping.iteritems(): + for item, info in six.iteritems(mapping): self.assertEqual(items.index(item), trackinfo.index(info)) diff --git a/test/test_edit.py b/test/test_edit.py index 669f6a2fa..9205166fd 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -23,6 +23,7 @@ from test.test_ui_importer import TerminalImportSessionSetup from test.test_importer import ImportHelper, AutotagStub from beets.library import Item from beetsplug.edit import EditPlugin +import six class ModifyFileMocker(object): @@ -63,7 +64,7 @@ class ModifyFileMocker(object): """ with codecs.open(filename, 'r', encoding='utf8') as f: contents = f.read() - for old, new_ in self.replacements.iteritems(): + for old, new_ in six.iteritems(self.replacements): contents = contents.replace(old, new_) with codecs.open(filename, 'w', encoding='utf8') as f: f.write(contents) diff --git a/test/test_importadded.py b/test/test_importadded.py index 474f56384..01c7d0ed9 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -14,6 +14,7 @@ # included in all copies or substantial portions of the Software. from __future__ import division, absolute_import, print_function +import six """Tests for the `importadded` plugin.""" @@ -124,7 +125,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.assertEqualTimes(album.added, album_added_before) items_added_after = dict((item.path, item.added) for item in album.items()) - for item_path, added_after in items_added_after.iteritems(): + for item_path, added_after in six.iteritems(items_added_after): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + util.displayable_path(item_path)) @@ -162,7 +163,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): # Verify the reimported items items_added_after = dict((item.path, item.added) for item in self.lib.items()) - for item_path, added_after in items_added_after.iteritems(): + for item_path, added_after in six.iteritems(items_added_after): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + util.displayable_path(item_path)) From 36ed75cd01e396edd764c9884de0b27d09cfd92e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 05:41:17 -0400 Subject: [PATCH 1042/2280] use reraise from six --- beets/util/pipeline.py | 3 ++- test/test_logging.py | 3 ++- test/test_replaygain.py | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 648d11b70..1a0cd4b5c 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -37,6 +37,7 @@ from __future__ import division, absolute_import, print_function from six.moves import queue from threading import Thread, Lock import sys +import six BUBBLE = '__PIPELINE_BUBBLE__' POISON = '__PIPELINE_POISON__' @@ -431,7 +432,7 @@ class Pipeline(object): exc_info = thread.exc_info if exc_info: # Make the exception appear as it was raised originally. - raise exc_info[0], exc_info[1], exc_info[2] + six.reraise(exc_info[0], exc_info[1], exc_info[2]) def pull(self): """Yield elements from the end of the pipeline. Runs the stages diff --git a/test/test_logging.py b/test/test_logging.py index 2de8a3ceb..6e5e6c8b6 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -14,6 +14,7 @@ import beetsplug from test import _common from test._common import unittest, TestCase from test import helper +import six class LoggingTest(TestCase): @@ -218,7 +219,7 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): def check_dp_exc(): if dp.exc_info: - raise dp.exc_info[1], None, dp.exc_info[2] + six.reraise(dp.exc_info[1], None, dp.exc_info[2]) try: dp.lock1.acquire() diff --git a/test/test_replaygain.py b/test/test_replaygain.py index e3fdf18a6..d2a8aa9ba 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -23,6 +23,7 @@ from beets import config from beets.mediafile import MediaFile from beetsplug.replaygain import (FatalGstreamerPluginReplayGainError, GStreamerBackend) +import six try: import gi @@ -62,7 +63,7 @@ class ReplayGainCliTestBase(TestHelper): # teardown operations may fail. In particular # {Item,Album} # may not have the _original_types attribute in unload_plugins pass - raise exc_info[1], None, exc_info[2] + six.reraise(exc_info[1], None, exc_info[2]) album = self.add_album_fixture(2) for item in album.items(): From faea61a76eb04910ca2ce9765361db22ca075248 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 05:53:24 -0400 Subject: [PATCH 1043/2280] use the real six.reraise in bluelet --- beets/util/bluelet.py | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index d81c2919a..48dd7bd94 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -9,6 +9,7 @@ Bluelet: easy concurrency without all the messy parallelism. """ from __future__ import division, absolute_import, print_function +import six import socket import select import sys @@ -19,20 +20,6 @@ import time import collections -# A little bit of "six" (Python 2/3 compatibility): cope with PEP 3109 syntax -# changes. - -PY3 = sys.version_info[0] == 3 -if PY3: - def _reraise(typ, exc, tb): - raise exc.with_traceback(tb) -else: - exec(""" -def _reraise(typ, exc, tb): - raise typ, exc, tb -""") - - # Basic events used for thread scheduling. class Event(object): @@ -214,7 +201,7 @@ class ThreadException(Exception): self.exc_info = exc_info def reraise(self): - _reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) + six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2]) SUSPENDED = Event() # Special sentinel placeholder for suspended threads. From 9f6b07fe1f582df3c488f503cf8efa650e22328c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 06:10:57 -0400 Subject: [PATCH 1044/2280] replace NUMERIC_TYPES with integer_types in functemplate --- beets/util/functemplate.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index ad3d22c92..1dc704020 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -34,7 +34,6 @@ import ast import dis import types -from .confit import NUMERIC_TYPES import six SYMBOL_DELIM = u'$' @@ -75,7 +74,7 @@ def ex_literal(val): """ if val is None: return ast.Name('None', ast.Load()) - elif isinstance(val, NUMERIC_TYPES): + elif isinstance(val, six.integer_types): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) From fd3f0b51590a3f2f530859eff7cef629b3adcb83 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 06:17:20 -0400 Subject: [PATCH 1045/2280] disable compiled functemplates if not using PY2 The AST code needs rewritten for PY3. This is tracked in https://github.com/beetbox/beets/issues/2058 --- beets/util/functemplate.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 1dc704020..2b32971e2 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -508,7 +508,8 @@ class Template(object): def __init__(self, template): self.expr = _parse(template) self.original = template - self.compiled = self.translate() + if six.PY2: + self.compiled = self.translate() def __eq__(self, other): return self.original == other.original @@ -524,9 +525,12 @@ class Template(object): def substitute(self, values={}, functions={}): """Evaluate the template given the values and functions. """ - try: - res = self.compiled(values, functions) - except: # Handle any exceptions thrown by compiled version. + if six.PY2: + try: + res = self.compiled(values, functions) + except: # Handle any exceptions thrown by compiled version. + res = self.interpret(values, functions) + else: res = self.interpret(values, functions) return res From 6849ab874e8383c0f4fd62382e66c0b407b814e9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 20 Jun 2016 06:21:05 -0400 Subject: [PATCH 1046/2280] skip pipeline test_constrainted_exception on PY3 This one would make every test run last until the timeout is reached, so it's necessary skip it until the root cause is found. --- test/test_pipeline.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_pipeline.py b/test/test_pipeline.py index e48a62f53..6f95a2208 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -17,6 +17,8 @@ """ from __future__ import division, absolute_import, print_function +import six + from test._common import unittest from beets.util import pipeline @@ -157,6 +159,7 @@ class ConstrainedThreadedPipelineTest(unittest.TestCase): pl.run_parallel(1) self.assertEqual(l, [i * 2 for i in range(1000)]) + @unittest.skipIf(six.PY3, u'freezes the test suite in py3') def test_constrained_exception(self): # Raise an exception in a constrained pipeline. l = [] From 78334876c37b6e8831f539660c7213c44cc3a2e1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 22 Jun 2016 16:11:29 -0400 Subject: [PATCH 1047/2280] treat HTMLParseError as a noop when missing Strict mode no longer exists in html.parser on python >= 3.5, and no longer means anything on python >= 3.3 --- beetsplug/lyrics.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 346abc01a..8aaebc672 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -25,7 +25,6 @@ import re import requests import unicodedata import warnings -from six.moves.html_parser import HTMLParseError from six.moves import urllib import six @@ -41,6 +40,15 @@ try: except ImportError: HAS_LANGDETECT = False +try: + # PY3: HTMLParseError was removed in 3.5 as strict mode + # was deprecated in 3.3. + # https://docs.python.org/3.3/library/html.parser.html + from six.moves.html_parser import HTMLParseError +except ImportError: + class HTMLParseError(Exception): + pass + from beets import plugins from beets import ui From 8c2809f75c5b63f0dc105fd8ec9ad60a6cff6377 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 01:23:30 -0400 Subject: [PATCH 1048/2280] only write StringIO encoding attr on py2 --- test/helper.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/helper.py b/test/helper.py index 0d37e90eb..8df7c8e3c 100644 --- a/test/helper.py +++ b/test/helper.py @@ -90,7 +90,8 @@ def control_stdin(input=None): """ org = sys.stdin sys.stdin = StringIO(input) - sys.stdin.encoding = 'utf8' + if six.PY2: # StringIO encoding attr isn't writable in python >= 3 + sys.stdin.encoding = 'utf8' try: yield sys.stdin finally: @@ -109,7 +110,8 @@ def capture_stdout(): """ org = sys.stdout sys.stdout = capture = StringIO() - sys.stdout.encoding = 'utf8' + if six.PY2: # StringIO encoding attr isn't writable in python >= 3 + sys.stdout.encoding = 'utf8' try: yield sys.stdout finally: From 433ac368dfb4d6606646078c1bb9a829dfdbeb34 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 23 Jun 2016 02:55:59 -0400 Subject: [PATCH 1049/2280] check pull.__next__ on py3 in pipeline tests --- test/test_pipeline.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 6f95a2208..a40cccdbd 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -136,7 +136,10 @@ class ExceptionTest(unittest.TestCase): pull = pl.pull() for i in range(3): next(pull) - self.assertRaises(TestException, pull.next) + if six.PY2: + self.assertRaises(TestException, pull.next) + else: + self.assertRaises(TestException, pull.__next__) class ParallelExceptionTest(unittest.TestCase): From 364d32953e8ff7f7c6b7aa728e6162ecf5e92473 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 24 Jun 2016 01:24:57 -0400 Subject: [PATCH 1050/2280] use buffer on py2, memoryview on py3 This wouldn't be necessary if the sqlite module accepted memoryview instances on py2, but it doesn't. --- beets/dbcore/query.py | 5 ++++- beets/dbcore/types.py | 7 +++++-- beets/library.py | 6 ++++-- beets/util/__init__.py | 6 +++++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 001e84616..f6dadd686 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -25,6 +25,9 @@ import unicodedata from functools import reduce import six +if not six.PY2: + buffer = memoryview # sqlite won't accept memoryview in python 2 + class ParsingError(ValueError): """Abstract class for any unparseable user-requested album/query @@ -244,7 +247,7 @@ class BytesQuery(MatchQuery): def __init__(self, field, pattern): super(BytesQuery, self).__init__(field, pattern) - # Use a buffer representation of the pattern for SQLite + # Use a buffer/memoryview representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. if isinstance(self.pattern, (six.text_type, bytes)): diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 2270d7c13..ef583672e 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -21,6 +21,9 @@ from . import query from beets.util import str2bool import six +if not six.PY2: + buffer = memoryview # sqlite won't accept memoryview in python 2 + # Abstract base. @@ -98,8 +101,8 @@ class Type(object): https://docs.python.org/2/library/sqlite3.html#sqlite-and-python-types Flexible fields have the type affinity `TEXT`. This means the - `sql_value` is either a `buffer` or a `unicode` object` and the - method must handle these in addition. + `sql_value` is either a `buffer`/`memoryview` or a `unicode` object` + and the method must handle these in addition. """ if isinstance(sql_value, buffer): sql_value = bytes(sql_value).decode('utf8', 'ignore') diff --git a/beets/library.py b/beets/library.py index f46092fe2..7821f93f4 100644 --- a/beets/library.py +++ b/beets/library.py @@ -35,6 +35,8 @@ from beets import dbcore from beets.dbcore import types import beets +if not six.PY2: + buffer = memoryview # sqlite won't accept memoryview in python 2 log = logging.getLogger('beets') @@ -159,8 +161,8 @@ class PathType(types.Type): return bytestring_path(value) elif isinstance(value, buffer): - # SQLite must store bytestings as buffers to avoid decoding. - # We unwrap buffers to bytes. + # SQLite must store bytestings as buffers/memoryview + # to avoid decoding. We unwrap buffers to bytes. return bytes(value) else: diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5fe52d7b8..56504ec3f 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -633,9 +633,13 @@ def as_string(value): """Convert a value to a Unicode object for matching with a query. None becomes the empty string. Bytestrings are silently decoded. """ + buffer_types = memoryview + if six.PY2: + buffer_types = (buffer, memoryview) + if value is None: return u'' - elif isinstance(value, buffer): + elif isinstance(value, buffer_types): return bytes(value).decode('utf8', 'ignore') elif isinstance(value, bytes): return value.decode('utf8', 'ignore') From b6678019ea31dcd25ef67d6017080bbe1ab4d3ea Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 24 Jun 2016 05:50:14 -0400 Subject: [PATCH 1051/2280] use @six.python_2_unicode_compatible --- beets/autotag/hooks.py | 5 ++++- beets/library.py | 23 ++++++++++++----------- beetsplug/beatport.py | 6 ++++-- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index f9388ad83..e0f543870 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -292,6 +292,7 @@ class LazyClassProperty(object): @total_ordering +@six.python_2_unicode_compatible class Distance(object): """Keeps track of multiple distance penalties. Provides a single weighted distance for all penalties as well as a weighted distance @@ -378,7 +379,9 @@ class Distance(object): def __rsub__(self, other): return other - self.distance - def __unicode__(self): + # Behave like a string + + def __str__(self): return "{0:.2f}".format(self.distance) # Behave like a dict. diff --git a/beets/library.py b/beets/library.py index 7821f93f4..2c5ff47b5 100644 --- a/beets/library.py +++ b/beets/library.py @@ -264,7 +264,7 @@ PF_KEY_DEFAULT = 'default' # Exceptions. - +@six.python_2_unicode_compatible class FileOperationError(Exception): """Indicates an error when interacting with a file on disk. Possibilities include an unsupported media type, a permissions @@ -278,7 +278,7 @@ class FileOperationError(Exception): self.path = path self.reason = reason - def __unicode__(self): + def text(self): """Get a string representing the error. Describes both the underlying reason and the file path in question. """ @@ -287,26 +287,30 @@ class FileOperationError(Exception): six.text_type(self.reason) ) - def __str__(self): - return six.text_type(self).encode('utf8') + # define __str__ as text to avoid infinite loop on super() calls + # with @six.python_2_unicode_compatible + __str__ = text +@six.python_2_unicode_compatible class ReadError(FileOperationError): """An error while reading a file (i.e. in `Item.read`). """ - def __unicode__(self): - return u'error reading ' + super(ReadError, self).__unicode__() + def __str__(self): + return u'error reading ' + super(ReadError, self).text() +@six.python_2_unicode_compatible class WriteError(FileOperationError): """An error while writing a file (i.e. in `Item.write`). """ - def __unicode__(self): - return u'error writing ' + super(WriteError, self).__unicode__() + def __str__(self): + return u'error writing ' + super(WriteError, self).text() # Item and Album model classes. +@six.python_2_unicode_compatible class LibModel(dbcore.Model): """Shared concrete functionality for Items and Albums. """ @@ -343,9 +347,6 @@ class LibModel(dbcore.Model): return result def __str__(self): - return format(self).encode('utf8') - - def __unicode__(self): return format(self) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 530bf5184..5949589c3 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -197,8 +197,9 @@ class BeatportClient(object): return response.json()['results'] +@six.python_2_unicode_compatible class BeatportRelease(BeatportObject): - def __unicode__(self): + def __str__(self): if len(self.artists) < 4: artist_str = ", ".join(x[1] for x in self.artists) else: @@ -225,8 +226,9 @@ class BeatportRelease(BeatportObject): data['slug'], data['id']) +@six.python_2_unicode_compatible class BeatportTrack(BeatportObject): - def __unicode__(self): + def __str__(self): artist_str = ", ".join(x[1] for x in self.artists) return (u"" .format(artist_str, self.name, self.mix_name)) From 34074b530b120bc11659e1407305d3c99590d25f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 24 Jun 2016 19:09:29 -0400 Subject: [PATCH 1052/2280] check changed text on py >3.5 in RegexpQuery test See https://bugs.python.org/issue22364 for details --- test/test_query.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index 707d9d182..fc4ee04a6 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function from functools import partial from mock import patch import os +import sys from test import _common from test._common import unittest @@ -305,8 +306,12 @@ class GetTest(DummyDataTestCase): with self.assertRaises(InvalidQueryArgumentTypeError) as raised: dbcore.query.RegexpQuery('year', u'199(') - self.assertIn(u'not a regular expression', unicode(raised.exception)) - self.assertIn(u'unbalanced parenthesis', unicode(raised.exception)) + exception_text = unicode(raised.exception) + self.assertIn(u'not a regular expression', exception_text) + if sys.version_info >= (3, 5): + self.assertIn(u'unterminated subpattern', exception_text) + else: + self.assertIn(u'unbalanced parenthesis', exception_text) self.assertIsInstance(raised.exception, ParsingError) From a1ed78135c4fdccd708ea0a1ee0dca581665b1a0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 25 Jun 2016 04:52:11 -0400 Subject: [PATCH 1053/2280] mark confit as_*() methods as shortcuts, not deprecated Fixes #2026 --- beets/util/confit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 057f85a1f..e4a3d8f8e 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -383,7 +383,7 @@ class ConfigView(object): """ return as_template(template).value(self, template) - # Old validation methods (deprecated). + # Shortcuts def as_filename(self): return self.get(Filename()) From 9968288358784bb8a6d051cb9acc93eadeea8215 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 25 Jun 2016 13:25:29 +0200 Subject: [PATCH 1054/2280] fetchart: update comments --- beetsplug/fetchart.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 9614b17f2..2ac7fb8ab 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -232,20 +232,25 @@ class RemoteArtSource(ArtSource): message=u'downloading image')) as resp: ct = resp.headers.get('Content-Type', None) - # Generate a temporary file and guess the extension based on - # the Content-Type header. This may be wrong for badly - # configured servers. E.g. fanart.tv only allows .jpg uploads - # and ALWAYS returns a image/jpeg Content-Type, but other - # formats with a erroneous .jp(e)g extension apparently can - # sneak through the upload filter. Therefore validate the type - # using the file magic. + # Download the image to a temporary file. As some servers + # (notably fanart.tv) have proven to return wrong Content-Types + # when images were uploaded with a bad file extension, do not + # rely on it. Instead validate the type using the file magic + # and only then determine the extension. data = resp.iter_content(chunk_size=1024) try: + # stream only a small part of the image to get its header chunk = next(data) except StopIteration: pass else: real_ct = _image_mime_type(chunk) + if real_ct is None: + # detection by file magic failed, fall back to the + # server-supplied Content-Type + # Is our type detection failsafe enough to drop this? + real_ct = ct + if real_ct not in CONTENT_TYPES: self._log.debug(u'not a supported image: {}', real_ct or u'unknown content type') @@ -260,7 +265,9 @@ class RemoteArtSource(ArtSource): ct, real_ct, ext) with NamedTemporaryFile(suffix=ext, delete=False) as fh: + # write the first already loaded part of the image fh.write(chunk) + # download the remaining part of the image for chunk in data: fh.write(chunk) self._log.debug(u'downloaded art to: {0}', From 697291b04e34dcbb2e8297ed10191381e5d9b077 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 25 Jun 2016 13:43:20 +0200 Subject: [PATCH 1055/2280] fetchart: improve error resilience of the Content-Type detection by file magic --- beetsplug/fetchart.py | 67 +++++++++++++++++++++++-------------------- test/test_art.py | 3 +- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 2ac7fb8ab..af44a7660 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -238,42 +238,47 @@ class RemoteArtSource(ArtSource): # rely on it. Instead validate the type using the file magic # and only then determine the extension. data = resp.iter_content(chunk_size=1024) - try: - # stream only a small part of the image to get its header - chunk = next(data) - except StopIteration: - pass + header = b'' + for chunk in data: + header += chunk + if len(header) >= 32: + # The imghdr module will only read 32 bytes, and our + # own additions in mediafile even less. + break else: - real_ct = _image_mime_type(chunk) - if real_ct is None: - # detection by file magic failed, fall back to the - # server-supplied Content-Type - # Is our type detection failsafe enough to drop this? - real_ct = ct + # server didn't return enough data, i.e. corrupt image + return - if real_ct not in CONTENT_TYPES: - self._log.debug(u'not a supported image: {}', - real_ct or u'unknown content type') - candidate.path = None - return + real_ct = _image_mime_type(header) + if real_ct is None: + # detection by file magic failed, fall back to the + # server-supplied Content-Type + # Is our type detection failsafe enough to drop this? + real_ct = ct - ext = b'.' + CONTENT_TYPES[real_ct][0] - if real_ct != ct: - self._log.warn(u'Server specified {}, but returned a ' - u'{} image. Correcting the extension ' - u'to {}', - ct, real_ct, ext) + if real_ct not in CONTENT_TYPES: + self._log.debug(u'not a supported image: {}', + real_ct or u'unknown content type') + candidate.path = None + return - with NamedTemporaryFile(suffix=ext, delete=False) as fh: - # write the first already loaded part of the image + ext = b'.' + CONTENT_TYPES[real_ct][0] + + if real_ct != ct: + self._log.warn(u'Server specified {}, but returned a ' + u'{} image. Correcting the extension ' + u'to {}', + ct, real_ct, ext) + + with NamedTemporaryFile(suffix=ext, delete=False) as fh: + # write the first already loaded part of the image + fh.write(header) + # download the remaining part of the image + for chunk in data: fh.write(chunk) - # download the remaining part of the image - for chunk in data: - fh.write(chunk) - self._log.debug(u'downloaded art to: {0}', - util.displayable_path(fh.name)) - candidate.path = util.bytestring_path(fh.name) - + self._log.debug(u'downloaded art to: {0}', + util.displayable_path(fh.name)) + candidate.path = util.bytestring_path(fh.name) return except (IOError, requests.RequestException, TypeError) as exc: diff --git a/test/test_art.py b/test/test_art.py index e2867a7ec..1388282f8 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -60,7 +60,8 @@ class FetchImageHelper(_common.TestCase): file_type = content_type responses.add(responses.GET, url, content_type=content_type, - body=IMAGEHEADER.get(file_type, b'\x00' * 32)) + # imghdr reads 32 bytes + body=IMAGEHEADER.get(file_type, b'').ljust(32, b'\x00')) class FetchImageTest(FetchImageHelper, UseThePlugin): From 5d00ca8bdaa97ab35e895bcef627eba67b30d587 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 25 Jun 2016 13:46:26 +0200 Subject: [PATCH 1056/2280] fetchart: do not unnecessarily reset Candidate.path on download failure --- beetsplug/fetchart.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index af44a7660..4d4158ec1 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -259,7 +259,6 @@ class RemoteArtSource(ArtSource): if real_ct not in CONTENT_TYPES: self._log.debug(u'not a supported image: {}', real_ct or u'unknown content type') - candidate.path = None return ext = b'.' + CONTENT_TYPES[real_ct][0] @@ -285,7 +284,6 @@ class RemoteArtSource(ArtSource): # Handling TypeError works around a urllib3 bug: # https://github.com/shazow/urllib3/issues/556 self._log.debug(u'error fetching art: {}', exc) - candidate.path = None return From 2db1530ef8d3a09b3436ceab296dbbedec1ecf17 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 25 Jun 2016 21:55:44 +0200 Subject: [PATCH 1057/2280] fetchart: flake8 fixes --- test/test_art.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 1388282f8..8659cf12a 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -46,22 +46,24 @@ class UseThePlugin(_common.TestCase): class FetchImageHelper(_common.TestCase): - """Helper mixin for mocking requests when fetching images + """Helper mixin for mocking requests when fetching images with remote art sources. """ @responses.activate def run(self, *args, **kwargs): super(FetchImageHelper, self).run(*args, **kwargs) + IMAGEHEADER = {'image/jpeg': b'\x00' * 6 + b'JFIF', + 'image/png': b'\211PNG\r\n\032\n', } + def mock_response(self, url, content_type='image/jpeg', file_type=None): - IMAGEHEADER = {'image/jpeg': b'\x00' * 6 + b'JFIF', - 'image/png': b'\211PNG\r\n\032\n', } if file_type is None: file_type = content_type responses.add(responses.GET, url, content_type=content_type, # imghdr reads 32 bytes - body=IMAGEHEADER.get(file_type, b'').ljust(32, b'\x00')) + body=self.IMAGEHEADER.get( + file_type, b'').ljust(32, b'\x00')) class FetchImageTest(FetchImageHelper, UseThePlugin): From 7bf6554cdc8031662795132dbedcf35dbe97debe Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sat, 25 Jun 2016 21:57:10 +0200 Subject: [PATCH 1058/2280] fetchart: update changelog --- docs/changelog.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4cd44372d..b01af1495 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -40,9 +40,9 @@ Fixes: * Fix a crash when specifying non-ASCII format strings on the command line with the ``-f`` option to many commands. :bug:`2063` * :doc:`/plugins/fetchart`: Determine the file extension for downloaded images - based on the ``Content-Type`` header instead of hardcoding it to .jpg. - Reported in :bug:`2053`, which for now it does not fix due to - server-side issues, though. + based on the image's magic bytes and warn if result is not consistent with + the server-supplied ``Content-Type`` header instead of + hardcoding it to .jpg. :bug:`2053` 1.3.18 (May 31, 2016) --------------------- From a7e91593a61ad850b1449cc7928b2537ea112e3c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 17:44:13 -0700 Subject: [PATCH 1059/2280] Meantion Beatport in README again --- README.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 5e953c302..5224a6f71 100644 --- a/README.rst +++ b/README.rst @@ -35,7 +35,7 @@ imagine for your music collection. Via `plugins`_, beets becomes a panacea: - Fetch or calculate all the metadata you could possibly need: `album art`_, `lyrics`_, `genres`_, `tempos`_, `ReplayGain`_ levels, or `acoustic fingerprints`_. -- Get metadata from `MusicBrainz`_ or `Discogs`_. Or guess +- Get metadata from `MusicBrainz`_, `Discogs`_, and `Beatport`_. Or guess metadata using songs' filenames or their acoustic fingerprints. - `Transcode audio`_ to any format you like. - Check your library for `duplicate tracks and albums`_ or for `albums that @@ -73,6 +73,7 @@ shockingly simple if you know a little Python. .. _album art: http://beets.readthedocs.org/page/plugins/fetchart.html .. _lyrics: http://beets.readthedocs.org/page/plugins/lyrics.html .. _MusicBrainz: http://musicbrainz.org/ +.. _Beatport: https://www.beatport.com Read More --------- From 6d619b67ab8181f7155815e46985044e9a1a6dfc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 17:50:12 -0700 Subject: [PATCH 1060/2280] Clean up the changelog for release --- docs/changelog.rst | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b01af1495..3a205c506 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,17 +4,24 @@ Changelog 1.3.19 (in development) ----------------------- +This is primarily a bug fix release: it cleans up a couple of regressions that +appeared in the last version. But it also features the triumphant return of the +:doc:`/plugins/beatport` and a modernized :doc:`/plugins/bpd`. + +It's also the first version where beets passes all its tests on Windows! May +this herald a new age of cross-platform reliability for beets. + New features: -* A new ``--force`` option for :ref:`remove-cmd` allows removal of items - without prompting beforehand. :bug:`2042` -* A new importer configuration :ref:`duplicate_action` controls how - duplicate albums or tracks treated in import task. :bug:`185` -* :doc:`/plugins/bpd`: The plugin now uses the modern GStreamer 1.0 instead of - the old 0.10. Thanks to :user:`philippbeckmann`. :bug:`2057` :bug:`2062` * :doc:`/plugins/beatport`: This metadata source plugin has arisen from the dead! It now works with Beatport's new OAuth-based API. Thanks to :user:`jbaiter`. :bug:`1989` :bug:`2067` +* :doc:`/plugins/bpd`: The plugin now uses the modern GStreamer 1.0 instead of + the old 0.10. Thanks to :user:`philippbeckmann`. :bug:`2057` :bug:`2062` +* A new ``--force`` option for the :ref:`remove-cmd` command allows removal of + items without prompting beforehand. :bug:`2042` +* A new :ref:`duplicate_action` importer config option controls how duplicate + albums or tracks treated in import task. :bug:`185` Some fixes for Windows: @@ -25,24 +32,26 @@ Some fixes for Windows: * :doc:`/plugins/fetchart`: The plugin should work more reliably with non-ASCII paths. -Fixes: +And other fixes: * :doc:`/plugins/replaygain`: The ``bs1770gain`` backend now correctly calculates sample peak instead of true peak. This comes with a major speed increase. :bug:`2031` * :doc:`/plugins/lyrics`: Avoid a crash and a spurious warning introduced in the last version about a Google API key, which appeared even when you hadn't - tried to enable the Google lyrics source. + enabled the Google lyrics source. * Fix a hard-coded path to ``bash-completion`` to work better with Homebrew installations. Thanks to :user:`bismark`. :bug:`2038` * Fix a crash introduced in the previous version when the standard input was connected to a Unix pipe. :bug:`2041` * Fix a crash when specifying non-ASCII format strings on the command line - with the ``-f`` option to many commands. :bug:`2063` + with the ``-f`` option for many commands. :bug:`2063` * :doc:`/plugins/fetchart`: Determine the file extension for downloaded images - based on the image's magic bytes and warn if result is not consistent with - the server-supplied ``Content-Type`` header instead of - hardcoding it to .jpg. :bug:`2053` + based on the image's magic bytes. The plugin prints a warning if result is + not consistent with the server-supplied ``Content-Type`` header. In previous + versions, the plugin would use a ``.jpg`` extension for all images. + :bug:`2053` + 1.3.18 (May 31, 2016) --------------------- From 9d66e2c30695da9b754e6e74a1d5a7e9f7b89cfb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 17:52:32 -0700 Subject: [PATCH 1061/2280] Add release date for 1.3.19 --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3a205c506..ed392fac2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.19 (in development) ------------------------ +1.3.19 (June 25, 2016) +---------------------- This is primarily a bug fix release: it cleans up a couple of regressions that appeared in the last version. But it also features the triumphant return of the From 035bf96558f205d62256ecd19bd557291fda6db5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 17:53:20 -0700 Subject: [PATCH 1062/2280] Version bump: 1.3.20 --- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ed392fac2..85ac0dfcc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.3.20 (in development) +----------------------- + +Changelog goes here! + + 1.3.19 (June 25, 2016) ---------------------- diff --git a/docs/conf.py b/docs/conf.py index 33ef95398..2b181a580 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.3' -release = '1.3.19' +release = '1.3.20' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 03d7c5833..f5102aef6 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.19', + version='1.3.20', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 2b289cd74cb05372bcf3749a2bb9d75ea999a919 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:04:03 -0700 Subject: [PATCH 1063/2280] Fix setup.py comment about bpd dependencies --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f5102aef6..6877d794b 100755 --- a/setup.py +++ b/setup.py @@ -122,7 +122,7 @@ setup( }, # Non-Python/non-PyPI plugin dependencies: # convert: ffmpeg - # bpd: pygst + # bpd: python-gi and GStreamer classifiers=[ 'Topic :: Multimedia :: Sound/Audio', From 349a6e6c1dd652e291331f431cf492b5d09f5a9c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:11:15 -0700 Subject: [PATCH 1064/2280] Fix an erroneous six usage in fuzzy --- beetsplug/fuzzy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index 1624ee1c1..ad61dc76b 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -45,5 +45,5 @@ class FuzzyPlugin(BeetsPlugin): }) def queries(self): - prefix = self.config['prefix'].get(six.string_types) + prefix = self.config['prefix'].get(six.text_type) return {prefix: FuzzyQuery} From e16cc58cb9dd9b3cb97842c21e8a109da2581781 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:29:55 -0700 Subject: [PATCH 1065/2280] Walk back some six.iter* uses In places where it doesn't much matter whether we use an iterator or the old Python 2 list way, using the six name just hurts legibility. --- beets/autotag/__init__.py | 3 +-- beets/autotag/hooks.py | 8 +++----- beets/autotag/match.py | 13 ++++++------- beets/autotag/mb.py | 4 ++-- beets/dbcore/db.py | 4 ++-- beetsplug/bpd/__init__.py | 10 +++++----- beetsplug/chroma.py | 2 +- beetsplug/duplicates.py | 2 +- beetsplug/fetchart.py | 2 +- beetsplug/importadded.py | 3 +-- beetsplug/info.py | 7 +++---- beetsplug/lyrics.py | 2 +- beetsplug/rewrite.py | 2 +- test/test_autotag.py | 3 +-- test/test_edit.py | 3 +-- test/test_importadded.py | 5 ++--- 16 files changed, 32 insertions(+), 41 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 040a5144a..ef775f6ec 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -25,7 +25,6 @@ from beets import config from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa from .match import tag_item, tag_album # noqa from .match import Recommendation # noqa -import six # Global logger. log = logging.getLogger('beets') @@ -53,7 +52,7 @@ def apply_metadata(album_info, mapping): """Set the items' metadata to match an AlbumInfo object using a mapping from Items to TrackInfo objects. """ - for item, track_info in six.iteritems(mapping): + for item, track_info in mapping.items(): # Album, artist, track count. if track_info.artist: item.artist = track_info.artist diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index e0f543870..c7b5edd73 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -328,7 +328,7 @@ class Distance(object): """Return the maximum distance penalty (normalization factor). """ dist_max = 0.0 - for key, penalty in six.iteritems(self._penalties): + for key, penalty in self._penalties.items(): dist_max += len(penalty) * self._weights[key] return dist_max @@ -337,7 +337,7 @@ class Distance(object): """Return the raw (denormalized) distance. """ dist_raw = 0.0 - for key, penalty in six.iteritems(self._penalties): + for key, penalty in self._penalties.items(): dist_raw += sum(penalty) * self._weights[key] return dist_raw @@ -379,8 +379,6 @@ class Distance(object): def __rsub__(self, other): return other - self.distance - # Behave like a string - def __str__(self): return "{0:.2f}".format(self.distance) @@ -411,7 +409,7 @@ class Distance(object): raise ValueError( u'`dist` must be a Distance object, not {0}'.format(type(dist)) ) - for key, penalties in six.iteritems(dist._penalties): + for key, penalties in dist._penalties.items(): self._penalties.setdefault(key, []).extend(penalties) # Adding components. diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 136c7f527..96057fe9a 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -30,7 +30,6 @@ from beets.util import plurality from beets.autotag import hooks from beets.util.enumeration import OrderedEnum from functools import reduce -import six # Artist signals that indicate "various artists". These are used at the # album level to determine whether a given release is likely a VA @@ -239,7 +238,7 @@ def distance(items, album_info, mapping): # Tracks. dist.tracks = {} - for item, track in six.iteritems(mapping): + for item, track in mapping.items(): dist.tracks[track] = track_distance(item, track, album_info.va) dist.add('tracks', dist.tracks[track].distance) @@ -444,7 +443,7 @@ def tag_album(items, search_artist=None, search_album=None, _add_candidate(items, candidates, info) # Sort and get the recommendation. - candidates = sorted(six.itervalues(candidates)) + candidates = sorted(candidates.values()) rec = _recommendation(candidates) return cur_artist, cur_album, candidates, rec @@ -472,16 +471,16 @@ def tag_item(item, search_artist=None, search_title=None, candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) # If this is a good match, then don't keep searching. - rec = _recommendation(sorted(six.itervalues(candidates))) + rec = _recommendation(sorted(candidates.values())) if rec == Recommendation.strong and \ not config['import']['timid']: log.debug(u'Track ID match.') - return sorted(six.itervalues(candidates)), rec + return sorted(candidates.values()), rec # If we're searching by ID, don't proceed. if search_ids: if candidates: - return sorted(six.itervalues(candidates)), rec + return sorted(candidates.values()), rec else: return [], Recommendation.none @@ -497,6 +496,6 @@ def tag_item(item, search_artist=None, search_title=None, # Sort by distance and return with recommendation. log.debug(u'Found {0} candidates.', len(candidates)) - candidates = sorted(six.itervalues(candidates)) + candidates = sorted(candidates.values()) rec = _recommendation(candidates) return candidates, rec diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index fdbb8e9e7..7fab3d41c 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -334,7 +334,7 @@ def match_album(artist, album, tracks=None): criteria['tracks'] = six.text_type(tracks) # Abort if we have no search terms. - if not any(six.itervalues(criteria)): + if not any(criteria.values()): return try: @@ -360,7 +360,7 @@ def match_track(artist, title): 'recording': title.lower().strip(), } - if not any(six.itervalues(criteria)): + if not any(criteria.values()): return try: diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 24bf6bfe8..780596fc9 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -177,9 +177,9 @@ class Model(object): ordinary construction are bypassed. """ obj = cls(db) - for key, value in six.iteritems(fixed_values): + for key, value in fixed_values.items(): obj._values_fixed[key] = cls._type(key).from_sql(value) - for key, value in six.iteritems(flex_values): + for key, value in flex_values.items(): obj._values_flex[key] = cls._type(key).from_sql(value) return obj diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 5d06028df..a28b1ff0d 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -853,7 +853,7 @@ class Server(BaseServer): for name, itemid in iter(sorted(node.files.items())): item = self.lib.get_item(itemid) yield self._item_info(item) - for name, _ in iter(sorted(six.iteritems(node.dirs))): + for name, _ in iter(sorted(node.dirs.items())): dirpath = self._path_join(path, name) if dirpath.startswith(u"/"): # Strip leading slash (libmpc rejects this). @@ -873,12 +873,12 @@ class Server(BaseServer): yield u'file: ' + basepath else: # List a directory. Recurse into both directories and files. - for name, itemid in sorted(six.iteritems(node.files)): + for name, itemid in sorted(node.files.items()): newpath = self._path_join(basepath, name) # "yield from" for v in self._listall(newpath, itemid, info): yield v - for name, subdir in sorted(six.iteritems(node.dirs)): + for name, subdir in sorted(node.dirs.items()): newpath = self._path_join(basepath, name) yield u'directory: ' + newpath for v in self._listall(newpath, subdir, info): @@ -903,11 +903,11 @@ class Server(BaseServer): yield self.lib.get_item(node) else: # Recurse into a directory. - for name, itemid in sorted(six.iteritems(node.files)): + for name, itemid in sorted(node.files.items()): # "yield from" for v in self._all_items(itemid): yield v - for name, subdir in sorted(six.iteritems(node.dirs)): + for name, subdir in sorted(node.dirs.items()): for v in self._all_items(subdir): yield v diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 54ea54f4c..38b90b2a9 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -122,7 +122,7 @@ def _all_releases(items): for release_id in release_ids: relcounts[release_id] += 1 - for release_id, count in six.iteritems(relcounts): + for release_id, count in relcounts.items(): if float(count) / len(items) > COMMON_REL_THRESH: yield release_id diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 141e36927..89bf78a2a 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -330,7 +330,7 @@ class DuplicatesPlugin(BeetsPlugin): """Generate triples of keys, duplicate counts, and constituent objects. """ offset = 0 if full else 1 - for k, objs in six.iteritems(self._group_by(objs, keys, strict)): + for k, objs in self._group_by(objs, keys, strict).items(): if len(objs) > 1: objs = self._order(objs, tiebreak) if merge: diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 2488144f1..22e2be56c 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -601,7 +601,7 @@ class Wikipedia(RemoteArtSource): try: data = wikipedia_response.json() results = data['query']['pages'] - for _, result in six.iteritems(results): + for _, result in results.items(): image_url = result['imageinfo'][0]['url'] yield self._candidate(url=image_url, match=Candidate.MATCH_EXACT) diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 707f04abd..07434ee72 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -12,7 +12,6 @@ import os from beets import util from beets import importer from beets.plugins import BeetsPlugin -import six class ImportAddedPlugin(BeetsPlugin): @@ -63,7 +62,7 @@ class ImportAddedPlugin(BeetsPlugin): def record_reimported(self, task, session): self.reimported_item_ids = set(item.id for item, replaced_items - in six.iteritems(task.replaced_items) + in task.replaced_items.items() if replaced_items) self.replaced_album_paths = set(task.replaced_albums.keys()) diff --git a/beetsplug/info.py b/beetsplug/info.py index 026c8d8e6..8e6f25953 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -26,7 +26,6 @@ from beets import ui from beets import mediafile from beets.library import Item from beets.util import displayable_path, normpath, syspath -import six def tag_data(lib, args): @@ -74,7 +73,7 @@ def library_data_emitter(item): def update_summary(summary, tags): - for key, value in six.iteritems(tags): + for key, value in tags.items(): if key not in summary: summary[key] = value elif summary[key] != value: @@ -97,7 +96,7 @@ def print_data(data, item=None, fmt=None): path = displayable_path(item.path) if item else None formatted = {} - for key, value in six.iteritems(data): + for key, value in data.items(): if isinstance(value, list): formatted[key] = u'; '.join(value) if value is not None: @@ -124,7 +123,7 @@ def print_data_keys(data, item=None): """ path = displayable_path(item.path) if item else None formatted = [] - for key, value in six.iteritems(data): + for key, value in data.items(): formatted.append(key) if len(formatted) == 0: diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 8aaebc672..347d3b91a 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -232,7 +232,7 @@ class SymbolsReplaced(Backend): @classmethod def _encode(cls, s): - for old, new in six.iteritems(cls.REPLACEMENTS): + for old, new in cls.REPLACEMENTS.items(): s = re.sub(old, new, s) return super(SymbolsReplaced, cls)._encode(s) diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index b04973101..e99df81fc 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -69,7 +69,7 @@ class RewritePlugin(BeetsPlugin): rules['albumartist'].append((pattern, value)) # Replace each template field with the new rewriter function. - for fieldname, fieldrules in six.iteritems(rules): + for fieldname, fieldrules in rules.items(): getter = rewriter(fieldname, fieldrules) self.template_fields[fieldname] = getter if fieldname in library.Album._fields: diff --git a/test/test_autotag.py b/test/test_autotag.py index 5e6f76ffb..b2f3fd61d 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -29,7 +29,6 @@ from beets.library import Item from beets.util import plurality from beets.autotag import AlbumInfo, TrackInfo from beets import config -import six class PluralityTest(_common.TestCase): @@ -612,7 +611,7 @@ class AssignmentTest(unittest.TestCase): match.assign_items(items, trackinfo) self.assertEqual(extra_items, []) self.assertEqual(extra_tracks, []) - for item, info in six.iteritems(mapping): + for item, info in mapping.items(): self.assertEqual(items.index(item), trackinfo.index(info)) diff --git a/test/test_edit.py b/test/test_edit.py index 9205166fd..5a46ece90 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -23,7 +23,6 @@ from test.test_ui_importer import TerminalImportSessionSetup from test.test_importer import ImportHelper, AutotagStub from beets.library import Item from beetsplug.edit import EditPlugin -import six class ModifyFileMocker(object): @@ -64,7 +63,7 @@ class ModifyFileMocker(object): """ with codecs.open(filename, 'r', encoding='utf8') as f: contents = f.read() - for old, new_ in six.iteritems(self.replacements): + for old, new_ in self.replacements.items(): contents = contents.replace(old, new_) with codecs.open(filename, 'w', encoding='utf8') as f: f.write(contents) diff --git a/test/test_importadded.py b/test/test_importadded.py index 01c7d0ed9..bd8d8b506 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -14,7 +14,6 @@ # included in all copies or substantial portions of the Software. from __future__ import division, absolute_import, print_function -import six """Tests for the `importadded` plugin.""" @@ -125,7 +124,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.assertEqualTimes(album.added, album_added_before) items_added_after = dict((item.path, item.added) for item in album.items()) - for item_path, added_after in six.iteritems(items_added_after): + for item_path, added_after in items_added_after.items(): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + util.displayable_path(item_path)) @@ -163,7 +162,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): # Verify the reimported items items_added_after = dict((item.path, item.added) for item in self.lib.items()) - for item_path, added_after in six.iteritems(items_added_after): + for item_path, added_after in items_added_after.items(): self.assertEqualTimes(items_added_before[item_path], added_after, u"reimport modified Item.added for " + util.displayable_path(item_path)) From 2e39c7944075d06aa2f45f17c414f4299bc297aa Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:32:15 -0700 Subject: [PATCH 1066/2280] Fix redundant six string reference in Confit --- beets/util/confit.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 238f806ca..e4a3d8f8e 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -25,7 +25,6 @@ import yaml import collections import re from collections import OrderedDict -import six UNIX_DIR_VAR = 'XDG_CONFIG_HOME' UNIX_DIR_FALLBACK = '~/.config' @@ -45,7 +44,7 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else six.text_type # noqa +STRING = str if PY3 else unicode # noqa BASESTRING = str if PY3 else basestring # noqa NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa From de62a59d35c83ff79bf58bf570259997f3f5969c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:39:29 -0700 Subject: [PATCH 1067/2280] Remove an unnecessary `six.range` use Ordinary `range` works fine here. --- beetsplug/lastimport.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 4d0557331..e222e8b97 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -15,7 +15,6 @@ from __future__ import division, absolute_import, print_function -from six.moves import range import pylast from pylast import TopItem, _extract, _number from beets import ui From c9aeac8cca429805f6a9200f8bdf3b56bbee6c5b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:46:46 -0700 Subject: [PATCH 1068/2280] Sync up Confit/Confuse with external repo --- beets/util/confit.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index e4a3d8f8e..30b5fe178 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# This file is part of Confit. +# This file is part of Confuse. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining @@ -44,9 +44,9 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else unicode # noqa -BASESTRING = str if PY3 else basestring # noqa -NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa +STRING = str if PY3 else unicode # noqa ignore=F821 +BASESTRING = str if PY3 else basestring # noqa ignore=F821 +NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa ignore=F821 def iter_first(sequence): @@ -383,7 +383,7 @@ class ConfigView(object): """ return as_template(template).value(self, template) - # Shortcuts + # Shortcuts for common templates. def as_filename(self): return self.get(Filename()) @@ -950,7 +950,7 @@ should be raised when the value is missing. class Template(object): """A value template for configuration fields. - The template works like a type and instructs Confit about how to + The template works like a type and instructs Confuse about how to interpret a deserialized YAML value. This includes type conversions, providing a default value, and validating for errors. For example, a filepath type might expand tildes and check that the file exists. From f63513c0e015eb6343464a6607afa504b06da547 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:49:17 -0700 Subject: [PATCH 1069/2280] Simpler string type handling --- beets/util/confit.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 30b5fe178..965bd3254 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -481,11 +481,10 @@ class Subview(ConfigView): self.name += '.' if isinstance(self.key, int): self.name += u'#{0}'.format(self.key) - elif isinstance(self.key, (bytes, BASESTRING)): - if isinstance(self.key, STRING): - self.name += self.key - else: - self.name += self.key.decode('utf8') + elif isinstance(self.key, bytes): + self.name += self.key.decode('utf8') + elif isinstance(self.key, STRING): + self.name += self.key else: self.name += repr(self.key) From c8816df9fd6709736a73c7c1f4fad9dd8d580b7c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 18:54:21 -0700 Subject: [PATCH 1070/2280] Walk back small change to Confit path types --- beets/util/confit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 965bd3254..61062839b 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1340,7 +1340,7 @@ class Filename(Template): def value(self, view, template=None): path, source = view.first() - if not isinstance(path, (bytes, BASESTRING)): + if not isinstance(path, BASESTRING): self.fail( u'must be a filename, not {0}'.format(type(path).__name__), view, From fa7b9999e75e81a47ee27376b2f6b8e5b8a86dff Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 19:06:01 -0700 Subject: [PATCH 1071/2280] Add `as_str` shortcut to Confuse --- beets/util/confit.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/beets/util/confit.py b/beets/util/confit.py index 61062839b..f2a919cd4 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -386,17 +386,34 @@ class ConfigView(object): # Shortcuts for common templates. def as_filename(self): + """Get the value as a path. Equivalent to `get(Filename())`. + """ return self.get(Filename()) def as_choice(self, choices): + """Get the value from a list of choices. Equivalent to + `get(Choice(choices))`. + """ return self.get(Choice(choices)) def as_number(self): + """Get the value as any number type: int or float. Equivalent to + `get(Number())`. + """ return self.get(Number()) def as_str_seq(self): + """Get the value as a sequence of strings. Equivalent to + `get(StrSeq())`. + """ return self.get(StrSeq()) + def as_str(self): + """Get the value as a (Unicode) string. Equivalent to + `get(unicode)` on Python 2 and `get(str)` on Python 3. + """ + return self.get(String()) + # Redaction. @property From 5efd5b21c5bade84a42833140d9365c4e8e505b3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 19:16:14 -0700 Subject: [PATCH 1072/2280] Use new `as_str` method Instead of `get(six.text_type)`, which was a surprisingly large portion of our uses of six. --- beets/autotag/mb.py | 4 ++-- beets/dbcore/db.py | 2 +- beets/importer.py | 3 +-- beets/library.py | 10 +++++----- beets/ui/__init__.py | 4 ++-- beetsplug/beatport.py | 4 ++-- beetsplug/bpd/__init__.py | 4 ++-- beetsplug/chroma.py | 3 +-- beetsplug/convert.py | 13 ++++++------- beetsplug/discogs.py | 7 +++---- beetsplug/ftintitle.py | 3 +-- beetsplug/fuzzy.py | 3 +-- beetsplug/hook.py | 5 ++--- beetsplug/importfeeds.py | 3 +-- beetsplug/inline.py | 4 ++-- beetsplug/keyfinder.py | 3 +-- beetsplug/lastgenre/__init__.py | 4 ++-- beetsplug/lastimport.py | 3 +-- beetsplug/lyrics.py | 6 +++--- beetsplug/mbcollection.py | 5 ++--- beetsplug/mpdstats.py | 6 +++--- beetsplug/mpdupdate.py | 4 ++-- beetsplug/replaygain.py | 7 +++---- beetsplug/rewrite.py | 3 +-- beetsplug/the.py | 3 +-- beetsplug/web/__init__.py | 3 +-- test/test_library.py | 2 +- test/test_ui.py | 27 +++++++++++++-------------- 28 files changed, 66 insertions(+), 82 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 7fab3d41c..78d382d87 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -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') diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 780596fc9..c0f329468 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -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) diff --git a/beets/importer.py b/beets/importer.py index 598dd36d7..f3272311f 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -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): diff --git a/beets/library.py b/beets/library.py index 2c5ff47b5..1c9a8f8b1 100644 --- a/beets/library.py +++ b/beets/library.py @@ -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): diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ce3c46f31..807219b43 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -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 diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 5949589c3..f7c52bd38 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -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: diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index a28b1ff0d..3aabeb869 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -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) diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index 38b90b2a9..b45bcfe3e 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -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))) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 63057b46f..14f3f3452 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -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() diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index b33dec7ed..9eca1eae9 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -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)) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 4e415b48d..db450d9c8 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -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) diff --git a/beetsplug/fuzzy.py b/beetsplug/fuzzy.py index ad61dc76b..a7308a525 100644 --- a/beetsplug/fuzzy.py +++ b/beetsplug/fuzzy.py @@ -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} diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 80daad68c..e48c5f374 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -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) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index e02c5793f..5e4333f73 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -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) diff --git a/beetsplug/inline.py b/beetsplug/inline.py index 5787b739e..fd0e9fc30 100644 --- a/beetsplug/inline.py +++ b/beetsplug/inline.py @@ -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 diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index dad62487f..0ef5ac155 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -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: diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index abda7ed6b..bc3155b94 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -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. diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index e222e8b97..0ed9daf3c 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -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: diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 347d3b91a..fe833e6c1 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -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. diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 0760be0e5..a590a7605 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -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']: diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index ca8dc9c7b..8ae3eb783 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -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) diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 36449a5ac..8ea1b5204 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -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): diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 27659ca27..e25f1a045 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -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. " diff --git a/beetsplug/rewrite.py b/beetsplug/rewrite.py index e99df81fc..eadb14252 100644 --- a/beetsplug/rewrite.py +++ b/beetsplug/rewrite.py @@ -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: diff --git a/beetsplug/the.py b/beetsplug/the.py index 149233c45..c746f88b0 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -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'' diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 6f480fb36..91b1b3a28 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -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 diff --git a/test/test_library.py b/test/test_library.py index b1ac76c25..d4c781986 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -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)) diff --git a/test/test_ui.py b/test/test_ui.py index 78d777f9e..5ea875e42 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -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() From a8b039da78683180805f682965b11c3272fd866c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Jun 2016 19:24:59 -0700 Subject: [PATCH 1073/2280] Remove a spurious `six` use I'm not sure what that `encode` was doing anyway. --- beetsplug/spotify.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 33570b5e4..619faebbc 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -9,7 +9,6 @@ from beets.plugins import BeetsPlugin from beets.ui import decargs from beets import ui from requests.exceptions import HTTPError -import six class SpotifyPlugin(BeetsPlugin): @@ -171,6 +170,6 @@ class SpotifyPlugin(BeetsPlugin): else: for item in ids: - print(six.text_type.encode(self.open_url + item)) + print(self.open_url + item) else: self._log.warn(u'No Spotify tracks found from beets query') From ce88a78de74a8ef3c9d7db7247a644e2b7fcf893 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 26 Jun 2016 04:06:29 -0400 Subject: [PATCH 1074/2280] add a __bytes__ method to LibModel this allows `test_album_and_item_format` in test_library to pass in py3 --- beets/library.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beets/library.py b/beets/library.py index 1c9a8f8b1..5859451d5 100644 --- a/beets/library.py +++ b/beets/library.py @@ -349,6 +349,9 @@ class LibModel(dbcore.Model): def __str__(self): return format(self) + def __bytes__(self): + return self.__str__().encode('utf-8') + class FormattedItemMapping(dbcore.db.FormattedMapping): """Add lookup for album-level fields. From 5831b99b9f1635580e8fc2d45c15ef04a64bccbd Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Mon, 13 Jun 2016 14:05:30 +0200 Subject: [PATCH 1075/2280] Adding 'expand' flag for json requests This allows you to query the individual items of an album --- beetsplug/web/__init__.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 91b1b3a28..fefa4ce5f 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -55,7 +55,7 @@ def _rep(obj, expand=False): return out -def json_generator(items, root): +def json_generator(items, root, expand=False): """Generator that dumps list of beets Items or Albums as JSON :param root: root key for JSON @@ -69,10 +69,14 @@ def json_generator(items, root): first = False else: yield ',' - yield json.dumps(_rep(item)) + yield json.dumps(_rep(item, expand=expand)) yield ']}' +def is_expand(args): + return "expand" in args + + def resource(name): """Decorates a function to handle RESTful HTTP requests for a resource. """ @@ -82,7 +86,7 @@ def resource(name): entities = [entity for entity in entities if entity] if len(entities) == 1: - return flask.jsonify(_rep(entities[0])) + return flask.jsonify(_rep(entities[0], expand=is_expand(flask.request.args))) elif entities: return app.response_class( json_generator(entities, root=name), @@ -101,7 +105,7 @@ def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class( - json_generator(query_func(queries), root='results'), + json_generator(query_func(queries), root='results', expand=is_expand(flask.request.args)), mimetype='application/json' ) responder.__name__ = 'query_{0}'.format(name) @@ -116,7 +120,7 @@ def resource_list(name): def make_responder(list_all): def responder(): return app.response_class( - json_generator(list_all(), root=name), + json_generator(list_all(), root=name, expand=is_expand(flask.request.args)), mimetype='application/json' ) responder.__name__ = 'all_{0}'.format(name) @@ -310,6 +314,9 @@ class WebPlugin(BeetsPlugin): self.config['port'] = int(args.pop(0)) app.config['lib'] = lib + # Normalizes json output + app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False + # Enable CORS if required. if self.config['cors']: self._log.info(u'Enabling CORS with origin: {0}', From 4be45eacc6867ee7f3184ada2d06f2f6da5485df Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Mon, 13 Jun 2016 14:08:01 +0200 Subject: [PATCH 1076/2280] Added documentation for the new 'expand' flag --- docs/plugins/web.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 7b2bfedef..b267af9d2 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -197,6 +197,7 @@ The interface and response format is similar to the item API, except replacing the encapsulation key ``"items"`` with ``"albums"`` when requesting ``/album/`` or ``/album/5,7``. In addition we can request the cover art of an album with ``GET /album/5/art``. +You can also add the '?expand' flag to get the individual items of an album. ``GET /stats`` From 041adf47acc21eb36a3507dc2eb19f77cfc08b56 Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Mon, 13 Jun 2016 14:35:24 +0200 Subject: [PATCH 1077/2280] Fixed lines which are mor than 79 characters --- beetsplug/web/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index fefa4ce5f..e485bc84d 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -86,7 +86,9 @@ def resource(name): entities = [entity for entity in entities if entity] if len(entities) == 1: - return flask.jsonify(_rep(entities[0], expand=is_expand(flask.request.args))) + return flask.jsonify( + _rep(entities[0], expand=is_expand(flask.request.args)) + ) elif entities: return app.response_class( json_generator(entities, root=name), @@ -105,7 +107,10 @@ def resource_query(name): def make_responder(query_func): def responder(queries): return app.response_class( - json_generator(query_func(queries), root='results', expand=is_expand(flask.request.args)), + json_generator( + query_func(queries), + root='results', expand=is_expand(flask.request.args) + ), mimetype='application/json' ) responder.__name__ = 'query_{0}'.format(name) @@ -120,7 +125,8 @@ def resource_list(name): def make_responder(list_all): def responder(): return app.response_class( - json_generator(list_all(), root=name, expand=is_expand(flask.request.args)), + json_generator(list_all(), root=name, + expand=is_expand(flask.request.args)), mimetype='application/json' ) responder.__name__ = 'all_{0}'.format(name) From 619344c8134f553e00563d9bb19f736cc6e92457 Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Mon, 13 Jun 2016 14:38:51 +0200 Subject: [PATCH 1078/2280] Added documentation for the expand parameter --- beetsplug/web/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index e485bc84d..65c1dcad8 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -60,6 +60,8 @@ def json_generator(items, root, expand=False): :param root: root key for JSON :param items: list of :class:`Item` or :class:`Album` to dump + :param expand: If true every :class:`Album` contains its items in the json + representation :returns: generator that yields strings """ yield '{"%s":[' % root From 2ae26548fcc5ed66cd5a4d99bdff32610b5979ad Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Mon, 13 Jun 2016 15:08:47 +0200 Subject: [PATCH 1079/2280] Modified and simplified is_expand(...) method --- beetsplug/web/__init__.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 65c1dcad8..59fa6b42a 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -75,8 +75,10 @@ def json_generator(items, root, expand=False): yield ']}' -def is_expand(args): - return "expand" in args +def is_expand(): + """Returns whether the current request is for an expanded response.""" + + return flask.request.args.get('expand') is not None def resource(name): @@ -88,9 +90,7 @@ def resource(name): entities = [entity for entity in entities if entity] if len(entities) == 1: - return flask.jsonify( - _rep(entities[0], expand=is_expand(flask.request.args)) - ) + return flask.jsonify(_rep(entities[0], expand=is_expand())) elif entities: return app.response_class( json_generator(entities, root=name), @@ -111,7 +111,7 @@ def resource_query(name): return app.response_class( json_generator( query_func(queries), - root='results', expand=is_expand(flask.request.args) + root='results', expand=is_expand() ), mimetype='application/json' ) @@ -127,8 +127,7 @@ def resource_list(name): def make_responder(list_all): def responder(): return app.response_class( - json_generator(list_all(), root=name, - expand=is_expand(flask.request.args)), + json_generator(list_all(), root=name, expand=is_expand()), mimetype='application/json' ) responder.__name__ = 'all_{0}'.format(name) From 5e8ac9e4a5d06de791fe051a419ba070bbdd5bec Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Tue, 14 Jun 2016 21:14:21 +0200 Subject: [PATCH 1080/2280] Expose the relative path to the library instead of omitting the 'path' variable --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 59fa6b42a..baf83f7ca 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -37,7 +37,7 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - del out['path'] + out['path'] = obj.destination(fragment=True) # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. From cfd70c2685d0da3c06b93043522f585fb58b87bd Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Sun, 26 Jun 2016 20:01:48 +0200 Subject: [PATCH 1081/2280] Added changelog for beetbox/beets#2050 --- docs/changelog.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 85ac0dfcc..f7ea2c0b3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,8 +4,15 @@ Changelog 1.3.20 (in development) ----------------------- -Changelog goes here! +New features: +* :doc:`/plugins/web`: Added an option to show the items of an album and a + 'path' tag to the json outpu of a file which shows the relative path to the + file. :bug:`2050` + +Other fixes: + +* :doc:`/plugins/web`: Normalized the json output 1.3.19 (June 25, 2016) ---------------------- From 890102e114530ce84fec095c65974533d7ee4b2d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 26 Jun 2016 16:37:38 -0400 Subject: [PATCH 1082/2280] explicitly cast g1, g2, and peak to int in _sc_encode They seem to have been implicitly forced to int via `%X` format, but with python 3.5 we must make it explicit. --- beets/mediafile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index dbe035d5a..4e92419bb 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -269,14 +269,14 @@ def _sc_encode(gain, peak): # from the gain ratio using a reference value of 1000 units. We also # enforce the maximum value here, which is equivalent to about # -18.2dB. - g1 = min(round((10 ** (gain / -10)) * 1000), 65534) + g1 = int(min(round((10 ** (gain / -10)) * 1000), 65534)) # Same as above, except our reference level is 2500 units. - g2 = min(round((10 ** (gain / -10)) * 2500), 65534) + g2 = int(min(round((10 ** (gain / -10)) * 2500), 65534)) # The purpose of these values are unknown, but they also seem to be # unused so we just use zero. uk = 0 - values = (g1, g1, g2, g2, uk, uk, peak, peak, uk, uk) + values = (g1, g1, g2, g2, uk, uk, int(peak), int(peak), uk, uk) return (u' %08X' * 10) % values From 33faa48516f691063eed5da907dd6ad284aa446d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 26 Jun 2016 16:56:09 -0400 Subject: [PATCH 1083/2280] fallthrough to shlex.split on py3 in shlex_split --- beets/util/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 56504ec3f..294074d10 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -766,8 +766,7 @@ def shlex_split(s): Raise `ValueError` if the string is not a well-formed shell string. This is a workaround for a bug in some versions of Python. """ - if isinstance(s, bytes): - # Shlex works fine. + if not six.PY2 or isinstance(s, bytes): # Shlex works fine. return shlex.split(s) elif isinstance(s, six.text_type): From 74aeb0edbcf863156c1364705d387da0c635cc06 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 26 Jun 2016 21:47:15 -0400 Subject: [PATCH 1084/2280] call is_alive() instead of isAlive() in pipeline --- beets/util/pipeline.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 1a0cd4b5c..995d6e3d0 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -412,7 +412,7 @@ class Pipeline(object): try: # Using a timeout allows us to receive KeyboardInterrupt # exceptions during the join(). - while threads[-1].isAlive(): + while threads[-1].is_alive(): threads[-1].join(1) except: From 06072c5d7d2bc33a9a7cf041b8fc5bd362758a69 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Mon, 27 Jun 2016 10:23:34 +0200 Subject: [PATCH 1085/2280] tests: Fix setup.py test test_hidden was missing suite() which made testall.suite() fail --- test/test_hidden.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_hidden.py b/test/test_hidden.py index f808af99f..316779f4d 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -72,3 +72,10 @@ class HiddenFileTest(unittest.TestCase): with tempfile.NamedTemporaryFile(prefix='.tmp') as f: self.assertTrue(hidden.is_hidden(f.name)) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') From 3984febf6cc1beba0c48a175c394b393eadab721 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Mon, 27 Jun 2016 08:37:20 +0200 Subject: [PATCH 1086/2280] mediafile: Add note to ASF.delete that it's fixed in newer mutagen --- beets/mediafile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/mediafile.py b/beets/mediafile.py index 4e92419bb..b9fcae091 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1457,6 +1457,7 @@ class MediaFile(object): try: self.mgfile.delete() except NotImplementedError: + # FIXME: This is fixed in mutagen >=1.31 # For Mutagen types that don't support deletion (notably, # ASF), just delete each tag individually. for tag in self.mgfile.keys(): From 9f16cfd0786e0878fda93256eed8a729a7e3d2e0 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Mon, 27 Jun 2016 08:39:27 +0200 Subject: [PATCH 1087/2280] mediafile: Remove alac detection workaround No longer needed since we depend on mutagen 1.27 --- beets/mediafile.py | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index b9fcae091..1874b7d10 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1384,20 +1384,10 @@ class MediaFile(object): elif (type(self.mgfile).__name__ == 'M4A' or type(self.mgfile).__name__ == 'MP4'): info = self.mgfile.info - if hasattr(info, 'codec'): - if info.codec and info.codec.startswith('alac'): - self.type = 'alac' - else: - self.type = 'aac' + if info.codec and info.codec.startswith('alac'): + self.type = 'alac' else: - # This hack differentiates AAC and ALAC on versions of - # Mutagen < 1.26. Once Mutagen > 1.26 is out and - # required by beets, we can remove this. - if hasattr(self.mgfile.info, 'bitrate') and \ - self.mgfile.info.bitrate > 0: - self.type = 'aac' - else: - self.type = 'alac' + self.type = 'aac' elif (type(self.mgfile).__name__ == 'ID3' or type(self.mgfile).__name__ == 'MP3'): self.type = 'mp3' From 45404bce850487f185ad4c1c56981bb4a41f35b3 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Mon, 27 Jun 2016 08:41:34 +0200 Subject: [PATCH 1088/2280] mediafile: Add note about MPEGInfo.channels being available in newer mutagen versions --- beets/mediafile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/mediafile.py b/beets/mediafile.py index 1874b7d10..0f51e5017 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1960,6 +1960,7 @@ class MediaFile(object): def channels(self): """The number of channels in the audio (an int).""" if isinstance(self.mgfile.info, mutagen.mp3.MPEGInfo): + # FIXME: MPEGInfo.channels was added in mutagen 1.30 return { mutagen.mp3.STEREO: 2, mutagen.mp3.JOINTSTEREO: 2, From 629241efd389bea7b4075f2591a06f2ef462dc82 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Mon, 27 Jun 2016 09:43:48 +0200 Subject: [PATCH 1089/2280] mediafile: Cleanup mutagen error handling Instead of the individial mutagen format exceptions use the mutagen.MutagenError exception introduced in 1.25. Since 1.33 mutagen will only raise MutagenError for load/save/delete and no longer raise IOError. Translate both errors to UnreadableFileError to support older and newer mutagen versions. Unify error handling in __init__(), save() and delete(). Since it's no longer possible to get an IOError from MediaFile, adjust all callers and tests accordingly. This was tested with mutagen 1.27 and current mutagen master. --- beets/library.py | 8 ++--- beets/mediafile.py | 66 +++++++++++++++++-------------------- beetsplug/scrub.py | 13 +++++--- test/test_mediafile.py | 23 ++++++++++++- test/test_mediafile_edge.py | 2 +- 5 files changed, 65 insertions(+), 47 deletions(-) diff --git a/beets/library.py b/beets/library.py index 5859451d5..5ef809122 100644 --- a/beets/library.py +++ b/beets/library.py @@ -26,7 +26,7 @@ import six from unidecode import unidecode from beets import logging -from beets.mediafile import MediaFile, MutagenError, UnreadableFileError +from beets.mediafile import MediaFile, UnreadableFileError from beets import plugins from beets import util from beets.util import bytestring_path, syspath, normpath, samefile @@ -568,7 +568,7 @@ class Item(LibModel): read_path = normpath(read_path) try: mediafile = MediaFile(syspath(read_path)) - except (OSError, IOError, UnreadableFileError) as exc: + except UnreadableFileError as exc: raise ReadError(read_path, exc) for key in self._media_fields: @@ -615,14 +615,14 @@ class Item(LibModel): try: mediafile = MediaFile(syspath(path), id3v23=beets.config['id3v23'].get(bool)) - except (OSError, IOError, UnreadableFileError) as exc: + except UnreadableFileError as exc: raise ReadError(self.path, exc) # Write the tags to the file. mediafile.update(item_tags) try: mediafile.save() - except (OSError, IOError, MutagenError) as exc: + except UnreadableFileError as exc: raise WriteError(self.path, exc) # The file has a new mtime. diff --git a/beets/mediafile.py b/beets/mediafile.py index 0f51e5017..6cdea47b4 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1346,32 +1346,12 @@ class MediaFile(object): path = syspath(path) self.path = path - unreadable_exc = ( - mutagen.mp3.error, - mutagen.id3.error, - mutagen.flac.error, - mutagen.monkeysaudio.MonkeysAudioHeaderError, - mutagen.mp4.error, - mutagen.oggopus.error, - mutagen.oggvorbis.error, - mutagen.ogg.error, - mutagen.asf.error, - mutagen.apev2.error, - mutagen.aiff.error, - ) try: self.mgfile = mutagen.File(path) - except unreadable_exc as exc: - log.debug(u'header parsing failed: {0}', six.text_type(exc)) + except (mutagen.MutagenError, IOError) as exc: + # Mutagen <1.33 could raise IOError + log.debug(u'parsing failed: {0}', six.text_type(exc)) raise UnreadableFileError(path) - except IOError as exc: - if type(exc) == IOError: - # This is a base IOError, not a subclass from Mutagen or - # anywhere else. - raise - else: - log.debug(u'{}', traceback.format_exc()) - raise MutagenError(path, exc) except Exception as exc: # Isolate bugs in Mutagen. log.debug(u'{}', traceback.format_exc()) @@ -1418,7 +1398,8 @@ class MediaFile(object): self.id3v23 = id3v23 and self.type == 'mp3' def save(self): - """Write the object's tags back to the file. + """Write the object's tags back to the file. May + throw `UnreadableFileError`. """ # Possibly save the tags to ID3v2.3. kwargs = {} @@ -1430,28 +1411,41 @@ class MediaFile(object): id3.update_to_v23() kwargs['v2_version'] = 3 - # Isolate bugs in Mutagen. try: self.mgfile.save(**kwargs) - except (IOError, OSError): - # Propagate these through: they don't represent Mutagen bugs. - raise + except (mutagen.MutagenError, IOError) as exc: + # Mutagen <1.33 could raise IOError + log.debug(u'saving failed: {0}', six.text_type(exc)) + raise UnreadableFileError(self.path) except Exception as exc: + # Isolate bugs in Mutagen. log.debug(u'{}', traceback.format_exc()) log.error(u'uncaught Mutagen exception in save: {0}', exc) raise MutagenError(self.path, exc) def delete(self): - """Remove the current metadata tag from the file. + """Remove the current metadata tag from the file. May + throw `UnreadableFileError`. """ + try: - self.mgfile.delete() - except NotImplementedError: - # FIXME: This is fixed in mutagen >=1.31 - # For Mutagen types that don't support deletion (notably, - # ASF), just delete each tag individually. - for tag in self.mgfile.keys(): - del self.mgfile[tag] + try: + self.mgfile.delete() + except NotImplementedError: + # FIXME: This is fixed in mutagen >=1.31 + # For Mutagen types that don't support deletion (notably, + # ASF), just delete each tag individually. + for tag in self.mgfile.keys(): + del self.mgfile[tag] + except (mutagen.MutagenError, IOError) as exc: + # Mutagen <1.33 could raise IOError + log.debug(u'deleting failed: {0}', six.text_type(exc)) + raise UnreadableFileError(self.path) + except Exception as exc: + # Isolate bugs in Mutagen. + log.debug(u'{}', traceback.format_exc()) + log.error(u'uncaught Mutagen exception in save: {0}', exc) + raise MutagenError(self.path, exc) # Convenient access to the set of available fields. diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index ed4040d5b..4dcefe572 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -119,7 +119,7 @@ class ScrubPlugin(BeetsPlugin): try: mf = mediafile.MediaFile(util.syspath(item.path), config['id3v23'].get(bool)) - except IOError as exc: + except mediafile.UnreadableFileError as exc: self._log.error(u'could not open file to scrub: {0}', exc) art = mf.art @@ -133,10 +133,13 @@ class ScrubPlugin(BeetsPlugin): item.try_write() if art: self._log.debug(u'restoring art') - mf = mediafile.MediaFile(util.syspath(item.path), - config['id3v23'].get(bool)) - mf.art = art - mf.save() + try: + mf = mediafile.MediaFile(util.syspath(item.path), + config['id3v23'].get(bool)) + mf.art = art + mf.save() + except mediafile.UnreadableFileError as exc: + self._log.error(u'could not write tags: {0}', exc) def import_task_files(self, session, task): """Automatically scrub imported files.""" diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 258e03896..7a299a1d0 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -29,7 +29,7 @@ from test import _common from test._common import unittest from beets.mediafile import MediaFile, MediaField, Image, \ MP3DescStorageStyle, StorageStyle, MP4StorageStyle, \ - ASFStorageStyle, ImageType, CoverArtField + ASFStorageStyle, ImageType, CoverArtField, UnreadableFileError from beets.library import Item from beets.plugins import BeetsPlugin from beets.util import bytestring_path @@ -455,6 +455,27 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, if os.path.isdir(self.temp_dir): shutil.rmtree(self.temp_dir) + def test_read_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + self.assertRaises(UnreadableFileError, MediaFile, mediafile.path) + + def test_save_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + try: + mediafile.save() + except UnreadableFileError: + pass + + def test_delete_nonexisting(self): + mediafile = self._mediafile_fixture('full') + os.remove(mediafile.path) + try: + mediafile.delete() + except UnreadableFileError: + pass + def test_read_audio_properties(self): mediafile = self._mediafile_fixture('full') for key, value in self.audio_properties.items(): diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 9fbf4e2bb..c95556820 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -193,7 +193,7 @@ class SafetyTest(unittest.TestCase, TestHelper): fn = os.path.join(_common.RSRC, b'brokenlink') os.symlink('does_not_exist', fn) try: - self.assertRaises(IOError, + self.assertRaises(beets.mediafile.UnreadableFileError, beets.mediafile.MediaFile, fn) finally: os.unlink(fn) From e39b6bd3febb20c5c1c13131dbb30d209be9f161 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:10:03 -0700 Subject: [PATCH 1090/2280] Fix in-package version number (fix #2086) --- beets/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/__init__.py b/beets/__init__.py index 830477a9a..d5d2eca4d 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.3.18' +__version__ = u'1.3.20' __author__ = u'Adrian Sampson ' From 7827d8691770d61c9ee6d75ef66cfb3bd1c765f4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:12:18 -0700 Subject: [PATCH 1091/2280] Note about six in changelog --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f7ea2c0b3..8e780b9a6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,9 @@ Changelog 1.3.20 (in development) ----------------------- +This version of beets now depends on the `six`_ library. This is our first +step toward supporting Python 3. + New features: * :doc:`/plugins/web`: Added an option to show the items of an album and a @@ -14,6 +17,9 @@ Other fixes: * :doc:`/plugins/web`: Normalized the json output +.. _six: https://pythonhosted.org/six/ + + 1.3.19 (June 25, 2016) ---------------------- From e33c19a3e93525aae3077e5a29a951b1cd5acb8f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:29:26 -0700 Subject: [PATCH 1092/2280] permissions: Use proper logging (#2089) Refactored so we can use the proper logging infrastructure instead of `print`. --- beetsplug/permissions.py | 85 ++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index b2c5e7fb0..129431e92 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -48,54 +48,55 @@ class Permissions(BeetsPlugin): u'dir': '755' }) - self.register_listener('item_imported', permissions) - self.register_listener('album_imported', permissions) + self.register_listener('item_imported', self.fix) + self.register_listener('album_imported', self.fix) + def fix(self, lib, item=None, album=None): + """Fix the permissions for an imported Item or Album. + """ + # Getting the config. + file_perm = config['permissions']['file'].get() + dir_perm = config['permissions']['dir'].get() -def permissions(lib, item=None, album=None): - """Running the permission fixer. - """ - # Getting the config. - file_perm = config['permissions']['file'].get() - dir_perm = config['permissions']['dir'].get() + # Converts permissions to oct. + file_perm = convert_perm(file_perm) + dir_perm = convert_perm(dir_perm) - # Converts permissions to oct. - file_perm = convert_perm(file_perm) - dir_perm = convert_perm(dir_perm) + # Create chmod_queue. + file_chmod_queue = [] + if item: + file_chmod_queue.append(item.path) + elif album: + for album_item in album.items(): + file_chmod_queue.append(album_item.path) - # Create chmod_queue. - file_chmod_queue = [] - if item: - file_chmod_queue.append(item.path) - elif album: - for album_item in album.items(): - file_chmod_queue.append(album_item.path) + # A set of directories to change permissions for. + dir_chmod_queue = set() - # A set of directories to change permissions for. - dir_chmod_queue = set() + for path in file_chmod_queue: + # Changing permissions on the destination file. + os.chmod(util.bytestring_path(path), file_perm) - for path in file_chmod_queue: - # Changing permissions on the destination file. - os.chmod(util.bytestring_path(path), file_perm) + # Checks if the destination path has the permissions configured. + if not check_permissions(util.bytestring_path(path), file_perm): + self._log.warn( + u'There was a problem setting permissions on file {}', + path, + ) - # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), file_perm): - message = u'There was a problem setting permission on {}'.format( - path) - print(message) + # Adding directories to the directory chmod queue. + dir_chmod_queue.update( + dirs_in_library(lib.directory, + path)) - # Adding directories to the directory chmod queue. - dir_chmod_queue.update( - dirs_in_library(lib.directory, - path)) + # Change permissions for the directories. + for path in dir_chmod_queue: + # Chaning permissions on the destination directory. + os.chmod(util.bytestring_path(path), dir_perm) - # Change permissions for the directories. - for path in dir_chmod_queue: - # Chaning permissions on the destination directory. - os.chmod(util.bytestring_path(path), dir_perm) - - # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), dir_perm): - message = u'There was a problem setting permission on {}'.format( - path) - print(message) + # Checks if the destination path has the permissions configured. + if not check_permissions(util.bytestring_path(path), dir_perm): + self._log.warn( + u'There was a problem setting permissions on directory {}', + path, + ) From b099503a6cafd30edc7413b297e5f99b2582a5fe Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:31:57 -0700 Subject: [PATCH 1093/2280] permissions: Use correct path conversions It looks like the original author mistook `bytestring_path` for `syspath`. --- beetsplug/permissions.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 129431e92..0e8422d9d 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -75,10 +75,10 @@ class Permissions(BeetsPlugin): for path in file_chmod_queue: # Changing permissions on the destination file. - os.chmod(util.bytestring_path(path), file_perm) + os.chmod(util.syspath(path), file_perm) # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), file_perm): + if not check_permissions(util.syspath(path), file_perm): self._log.warn( u'There was a problem setting permissions on file {}', path, @@ -92,10 +92,10 @@ class Permissions(BeetsPlugin): # Change permissions for the directories. for path in dir_chmod_queue: # Chaning permissions on the destination directory. - os.chmod(util.bytestring_path(path), dir_perm) + os.chmod(util.syspath(path), dir_perm) # Checks if the destination path has the permissions configured. - if not check_permissions(util.bytestring_path(path), dir_perm): + if not check_permissions(util.syspath(path), dir_perm): self._log.warn( u'There was a problem setting permissions on directory {}', path, From 84bfbe95b9a45293314869a2cd9dd5d9b317c6c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:39:35 -0700 Subject: [PATCH 1094/2280] permissions: More helpful logging (#2089) --- beetsplug/permissions.py | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 0e8422d9d..1d2c45f0f 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -25,11 +25,29 @@ def convert_perm(perm): def check_permissions(path, permission): - """Checks the permissions of a path. + """Check whether the file's permissions equal the given vector. + Return a boolean. """ return oct(os.stat(path).st_mode & 0o777) == oct(permission) +def assert_permissions(path, permission, log): + """Check whether the file's permissions are as expected, otherwise, + log a warning message. Return a boolean indicating the match, like + `check_permissions`. + """ + if not check_permissions(util.syspath(path), permission): + log.warn( + u'could not set permissions on {}', + util.displayable_path(path), + ) + log.debug( + u'set permissions to {}, but permissions are now {}', + permission, + os.stat(util.syspath(path)).st_mode & 0o777, + ) + + def dirs_in_library(library, item): """Creates a list of ancestor directories in the beets library path. """ @@ -78,11 +96,7 @@ class Permissions(BeetsPlugin): os.chmod(util.syspath(path), file_perm) # Checks if the destination path has the permissions configured. - if not check_permissions(util.syspath(path), file_perm): - self._log.warn( - u'There was a problem setting permissions on file {}', - path, - ) + assert_permissions(path, file_perm, self._log) # Adding directories to the directory chmod queue. dir_chmod_queue.update( @@ -95,8 +109,4 @@ class Permissions(BeetsPlugin): os.chmod(util.syspath(path), dir_perm) # Checks if the destination path has the permissions configured. - if not check_permissions(util.syspath(path), dir_perm): - self._log.warn( - u'There was a problem setting permissions on directory {}', - path, - ) + assert_permissions(path, dir_perm, self._log) From 890b9e81e3dec898e365a4f3478df749dc27a1c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:51:13 -0700 Subject: [PATCH 1095/2280] Fix #2089: correct permissions configuration This reverts the change in 44380db6e8dc6ed5e656b00444b6171accd90562, where we lost the ability to "reinterpret" decimals in the YAML configuration file as octal permissions values. --- beetsplug/permissions.py | 21 ++++++++++++--------- docs/changelog.rst | 8 +++++++- test/test_permissions.py | 3 +++ 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 1d2c45f0f..aaf923fe8 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -13,15 +13,17 @@ import os from beets import config, util from beets.plugins import BeetsPlugin from beets.util import ancestry +import six def convert_perm(perm): - """If the perm is a int then just return it, otherwise convert it to oct. + """Convert a string to an integer, interpreting the text as octal. + Or, if `perm` is an integer, reinterpret it as an octal number that + has been "misinterpreted" as decimal. """ - if isinstance(perm, int): - return perm - else: - return int(perm, 8) + if isinstance(perm, six.integer_types): + perm = six.text_type(perm) + return int(perm, 8) def check_permissions(path, permission): @@ -63,7 +65,7 @@ class Permissions(BeetsPlugin): # Adding defaults. self.config.add({ u'file': '644', - u'dir': '755' + u'dir': '755', }) self.register_listener('item_imported', self.fix) @@ -72,11 +74,12 @@ class Permissions(BeetsPlugin): def fix(self, lib, item=None, album=None): """Fix the permissions for an imported Item or Album. """ - # Getting the config. + # Get the configured permissions. The user can specify this either a + # string (in YAML quotes) or, for convenience, as an integer so the + # quotes can be omitted. In the latter case, we need to reinterpret the + # integer as octal, not decimal. file_perm = config['permissions']['file'].get() dir_perm = config['permissions']['dir'].get() - - # Converts permissions to oct. file_perm = convert_perm(file_perm) dir_perm = convert_perm(dir_perm) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8e780b9a6..ef91a11da 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,9 +13,15 @@ New features: 'path' tag to the json outpu of a file which shows the relative path to the file. :bug:`2050` -Other fixes: +Fixes: * :doc:`/plugins/web`: Normalized the json output +* :doc:`/plugins/permissions`: Fix a regression in the previous release where + the plugin would always fail to set permissions (and log a warning). + :bug:`2089` + +The last release, 1.3.19, also erroneously reported its version as "1.3.18" +when you typed ``beet version``. This has been corrected. .. _six: https://pythonhosted.org/six/ diff --git a/test/test_permissions.py b/test/test_permissions.py index c6b1837b4..7234ec30d 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -74,6 +74,9 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): def test_convert_perm_from_string(self): self.assertEqual(convert_perm('10'), 8) + def test_convert_perm_from_int(self): + self.assertEqual(convert_perm(10), 8) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 192dd321f12ddc8c29b1a9037bd5e0a9d3a14dfc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:53:23 -0700 Subject: [PATCH 1096/2280] permissions: Add debug logging --- beetsplug/permissions.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index aaf923fe8..9bced8396 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -96,6 +96,10 @@ class Permissions(BeetsPlugin): for path in file_chmod_queue: # Changing permissions on the destination file. + self._log.debug( + u'setting file permissions on {}', + util.displayable_path(path), + ) os.chmod(util.syspath(path), file_perm) # Checks if the destination path has the permissions configured. @@ -109,6 +113,10 @@ class Permissions(BeetsPlugin): # Change permissions for the directories. for path in dir_chmod_queue: # Chaning permissions on the destination directory. + self._log.debug( + u'setting directory permissions on {}', + util.displayable_path(path), + ) os.chmod(util.syspath(path), dir_perm) # Checks if the destination path has the permissions configured. From 4955933670a48f892e27bf41756bd378a8c7440c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 10:58:08 -0700 Subject: [PATCH 1097/2280] Update Mutagen dependency (#2088) This lets us remove a few more workarounds that Mutagen itself has addressed already. --- beets/mediafile.py | 21 +++------------------ docs/changelog.rst | 8 ++++++-- setup.py | 2 +- 3 files changed, 10 insertions(+), 21 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 6cdea47b4..754fb2349 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1429,22 +1429,15 @@ class MediaFile(object): """ try: - try: - self.mgfile.delete() - except NotImplementedError: - # FIXME: This is fixed in mutagen >=1.31 - # For Mutagen types that don't support deletion (notably, - # ASF), just delete each tag individually. - for tag in self.mgfile.keys(): - del self.mgfile[tag] + self.mgfile.delete() except (mutagen.MutagenError, IOError) as exc: - # Mutagen <1.33 could raise IOError + # Mutagen <1.33 could raise IOError. log.debug(u'deleting failed: {0}', six.text_type(exc)) raise UnreadableFileError(self.path) except Exception as exc: # Isolate bugs in Mutagen. log.debug(u'{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in save: {0}', exc) + log.error(u'uncaught Mutagen exception in delete: {0}', exc) raise MutagenError(self.path, exc) # Convenient access to the set of available fields. @@ -1953,14 +1946,6 @@ class MediaFile(object): @property def channels(self): """The number of channels in the audio (an int).""" - if isinstance(self.mgfile.info, mutagen.mp3.MPEGInfo): - # FIXME: MPEGInfo.channels was added in mutagen 1.30 - return { - mutagen.mp3.STEREO: 2, - mutagen.mp3.JOINTSTEREO: 2, - mutagen.mp3.DUALCHANNEL: 2, - mutagen.mp3.MONO: 1, - }[self.mgfile.info.mode] if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0 diff --git a/docs/changelog.rst b/docs/changelog.rst index ef91a11da..7e51aabbc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,8 +4,12 @@ Changelog 1.3.20 (in development) ----------------------- -This version of beets now depends on the `six`_ library. This is our first -step toward supporting Python 3. +Some dependency notes for packagers: + +* This version of beets now depends on the `six`_ library. This is our first + step toward supporting Python 3. +* We also bumped our minimum required version of `Mutagen`_ to 1.31 (from + 1.27). New features: diff --git a/setup.py b/setup.py index e736b3b09..2cca0498d 100755 --- a/setup.py +++ b/setup.py @@ -88,7 +88,7 @@ setup( install_requires=[ 'six', 'enum34>=1.0.4', - 'mutagen>=1.27', + 'mutagen>=1.31', 'munkres', 'unidecode', 'musicbrainzngs>=0.4', From 0da1ba9299b13f99e25c6344e5fa2e92e45f9024 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 20:19:20 -0700 Subject: [PATCH 1098/2280] Enforce string types for mutagen.Image --- beets/mediafile.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 754fb2349..f13287a86 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -351,6 +351,9 @@ class Image(object): the binary data """ def __init__(self, data, desc=None, type=None): + assert isinstance(data, bytes) + if desc is not None: + assert isinstance(desc, six.text_type) self.data = data self.desc = desc if isinstance(type, int): @@ -1026,8 +1029,11 @@ class APEv2ImageStorageStyle(ListStorageStyle): try: frame = mutagen_file[cover_tag] text_delimiter_index = frame.value.find(b'\x00') - comment = frame.value[0:text_delimiter_index] \ - if text_delimiter_index > 0 else None + if text_delimiter_index > 0: + comment = frame.value[0:text_delimiter_index] + comment = comment.decode('utf8', 'replace') + else: + comment = None image_data = frame.value[text_delimiter_index + 1:] images.append(Image(data=image_data, type=cover_type, desc=comment)) From 44e0e441080da8057260cea7a9225e03e93ffca0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 20:22:58 -0700 Subject: [PATCH 1099/2280] Enforce type of ID3 `desc` fields --- beets/mediafile.py | 3 ++- test/test_mediafile.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index f13287a86..32d2abc90 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -754,6 +754,7 @@ class MP3DescStorageStyle(MP3StorageStyle): selected based its ``desc`` field. """ def __init__(self, desc=u'', key='TXXX', **kwargs): + assert isinstance(desc, six.text_type) self.description = desc super(MP3DescStorageStyle, self).__init__(key=key, **kwargs) @@ -1702,7 +1703,7 @@ class MediaFile(object): ASFStorageStyle('WM/Language'), ) country = MediaField( - MP3DescStorageStyle('MusicBrainz Album Release Country'), + MP3DescStorageStyle(u'MusicBrainz Album Release Country'), MP4StorageStyle('----:com.apple.iTunes:MusicBrainz ' 'Album Release Country'), StorageStyle('RELEASECOUNTRY'), diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 7a299a1d0..5a6100c54 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -299,7 +299,7 @@ class GenreListTestMixin(object): field_extension = MediaField( - MP3DescStorageStyle('customtag'), + MP3DescStorageStyle(u'customtag'), MP4StorageStyle('----:com.apple.iTunes:customtag'), StorageStyle('customtag'), ASFStorageStyle('customtag'), From 5d4e3396d203110d27486380bd85b33283ac9d01 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 28 Jun 2016 23:28:58 -0400 Subject: [PATCH 1100/2280] wrap a path in displayable_path in commands --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c352fe53d..523de31c8 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -772,7 +772,7 @@ class TerminalImportSession(importer.ImportSession): either an action constant or a TrackMatch object. """ print_() - print_(task.item.path) + print_(displayable_path(task.item.path)) candidates, rec = task.candidates, task.rec # Take immediate action if appropriate. From 159e24a14be709de789d65257f8b50124e535c30 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 28 Jun 2016 23:32:46 -0400 Subject: [PATCH 1101/2280] only decode decarg results on python 2 --- beets/ui/__init__.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 807219b43..e9175fb7f 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -122,9 +122,12 @@ def _arg_encoding(): def decargs(arglist): """Given a list of command-line argument bytestrings, attempts to - decode them to Unicode strings. + decode them to Unicode strings when running under Python 2. """ - return [s.decode(_arg_encoding()) for s in arglist] + if six.PY2: + return [s.decode(_arg_encoding()) for s in arglist] + else: + return arglist def print_(*strings, **kwargs): From bdbed1f6d9d3d2dfa92e6e061c967398baa1eb6a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 28 Jun 2016 23:33:39 -0400 Subject: [PATCH 1102/2280] only decode input_ results on python 2 --- beets/ui/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index e9175fb7f..032143928 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -214,7 +214,10 @@ def input_(prompt=None): except EOFError: raise UserError(u'stdin stream ended while input required') - return resp.decode(_in_encoding(), 'ignore') + if six.PY2: + return resp.decode(_in_encoding(), 'ignore') + else: + return resp def input_options(options, require=False, prompt=None, fallback_prompt=None, From f46bfdf219475d78f82d56098ada319bca87be80 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 20:34:04 -0700 Subject: [PATCH 1103/2280] Fix index display with per_disc_numbering If `medium_index` is missing, as it is from the Beatport source, the display would show "None" instead of the global index (a fallback). This is half of the problem in #2085. --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c352fe53d..d518ed017 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -237,7 +237,7 @@ def show_change(cur_artist, cur_album, match): if mediums > 1: return u'{0}-{1}'.format(medium, medium_index) else: - return six.text_type(medium_index) + return six.text_type(medium_index or index) else: return six.text_type(index) From aea692a112eab58d5a468d4d90c620d8227489da Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Jun 2016 20:38:41 -0700 Subject: [PATCH 1104/2280] Fix applying track index in per_disc_numbering Fixes #2085. This is the second half, which deals with actually applying the track number. The previous condition didn't acknowledge that `Item` coerced `None` to 0 to enforce its field types. --- beets/autotag/__init__.py | 5 +++-- docs/changelog.rst | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index ef775f6ec..b3cfa9541 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -97,8 +97,9 @@ def apply_metadata(album_info, mapping): if config['per_disc_numbering']: # We want to let the track number be zero, but if the medium index # is not provided we need to fall back to the overall index. - item.track = track_info.medium_index - if item.track is None: + if track_info.medium_index is not None: + item.track = track_info.medium_index + else: item.track = track_info.index item.tracktotal = track_info.medium_total or len(album_info.tracks) else: diff --git a/docs/changelog.rst b/docs/changelog.rst index 7e51aabbc..6bf4a9681 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,9 @@ Fixes: * :doc:`/plugins/permissions`: Fix a regression in the previous release where the plugin would always fail to set permissions (and log a warning). :bug:`2089` +* With :ref:`per_disc_numbering` enabled, some metadata sources (notably, the + :doc:`/plugins/beatport`) would not set the track number at all. This is + fixed. :bug:`2085` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 2f1cd59e1be4de669abf2d94e3c42ed8a91a4224 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 29 Jun 2016 03:16:42 -0400 Subject: [PATCH 1105/2280] make sure ui.print_() only accepts unicode strings --- beets/ui/__init__.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 032143928..4fd79974f 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -135,25 +135,25 @@ def print_(*strings, **kwargs): is not in the terminal's encoding's character set, just silently replaces it. - If the arguments are strings then they're expected to share the same - type: either bytes or unicode. + The arguments must be unicode strings The `end` keyword argument behaves similarly to the built-in `print` (it defaults to a newline). The value should have the same string type as the arguments. """ + if not strings: + strings = [u''] + end = kwargs.get('end') + assert isinstance(strings[0], six.text_type) - if not strings or isinstance(strings[0], six.text_type): - txt = u' '.join(strings) - txt += u'\n' if end is None else end - else: - txt = b' '.join(strings) - txt += b'\n' if end is None else end + txt = u' '.join(strings) + txt += u'\n' if end is None else end - # Always send bytes to the stdout stream. - if isinstance(txt, six.text_type): - txt = txt.encode(_out_encoding(), 'replace') + # Always send bytes to the stdout stream on python 2. + if six.PY2: + if isinstance(txt, six.text_type): + txt = txt.encode(_out_encoding(), 'replace') sys.stdout.write(txt) @@ -207,7 +207,7 @@ def input_(prompt=None): # use print_() explicitly to display prompts. # http://bugs.python.org/issue1927 if prompt: - print_(prompt, end=' ') + print_(prompt, end=u' ') try: resp = input() From 6b3cc6ff379419a939dc8fdb4a97591571cbe73b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 29 Jun 2016 03:17:02 -0400 Subject: [PATCH 1106/2280] adapt print_() callers to send unicode strings --- beets/ui/commands.py | 17 +++++++++-------- beetsplug/info.py | 3 ++- beetsplug/play.py | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0db17b88e..325b549d3 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -86,13 +86,13 @@ def _print_keys(query): returned row, with identation of 2 spaces. """ for row in query: - print_(' ' * 2 + row['key']) + print_(u' ' * 2 + six.text_type(row['key'])) def fields_func(lib, opts, args): def _print_rows(names): names.sort() - print_(" " + "\n ".join(names)) + print_(six.text_type(' ' + '\n '.join(names))) print_(u"Item fields:") _print_rows(library.Item.all_keys()) @@ -1060,10 +1060,10 @@ def list_items(lib, query, album, fmt=''): """ if album: for album in lib.albums(query): - ui.print_(format(album, fmt)) + ui.print_(six.text_type(format(album, fmt))) else: for item in lib.items(query): - ui.print_(format(item, fmt)) + ui.print_(six.text_type(format(item, fmt))) def list_func(lib, opts, args): @@ -1211,7 +1211,7 @@ def remove_items(lib, query, album, delete, force): prompt = u'Really DELETE %i file%s (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') else: - fmt = '' + fmt = u'' prompt = u'Really remove %i item%s from the library (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') @@ -1608,7 +1608,7 @@ def config_func(lib, opts, args): filenames.insert(0, user_path) for filename in filenames: - print_(filename) + print_(displayable_path(filename)) # Open in editor. elif opts.edit: @@ -1616,7 +1616,8 @@ def config_func(lib, opts, args): # Dump configuration. else: - print_(config.dump(full=opts.defaults, redact=opts.redact)) + config_out = config.dump(full=opts.defaults, redact=opts.redact) + print_(six.text_type(config_out)) def config_edit(): @@ -1662,7 +1663,7 @@ default_commands.append(config_cmd) def print_completion(*args): for line in completion_script(default_commands + plugins.commands()): - print_(line, end='') + print_(six.text_type(line), end=u'') if not any(map(os.path.isfile, BASH_COMPLETION_PATHS)): log.warn(u'Warning: Unable to find the bash-completion package. ' u'Command line completion might not work.') diff --git a/beetsplug/info.py b/beetsplug/info.py index 8e6f25953..3865865d4 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function import os import re +import six from beets.plugins import BeetsPlugin from beets import ui @@ -91,7 +92,7 @@ def print_data(data, item=None, fmt=None): """ if fmt: # use fmt specified by the user - ui.print_(format(item, fmt)) + ui.print_(six.text_type(format(item, fmt))) return path = displayable_path(item.path) if item else None diff --git a/beetsplug/play.py b/beetsplug/play.py index 465d8e6d5..409ac46f9 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -128,7 +128,7 @@ class PlayPlugin(BeetsPlugin): u'You are about to queue {0} {1}.'.format( len(selection), item_type))) - if ui.input_options(('Continue', 'Abort')) == 'a': + if ui.input_options((u'Continue', u'Abort')) == 'a': return ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) From ebf44fd6cd09d6bc4d6da60a6a0dadf781064723 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 29 Jun 2016 18:22:44 +0200 Subject: [PATCH 1107/2280] Workaround for a race condition on queue invalidation, Issue #2078 --- beets/util/pipeline.py | 12 +++++++++++- test/test_pipeline.py | 1 - 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 995d6e3d0..367e5d980 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -64,7 +64,17 @@ def _invalidate_queue(q, val=None, sync=True): q.mutex.acquire() try: - q.maxsize = 0 + # Originally, we set `maxsize` to 0 here, which is supposed to mean + # an unlimited queue size. However, there is a race condition since + # Python 3.2 when this attribute is changed while another thread is + # waiting in put()/get() due to a full/empty queue. + # Setting it to 2 is still hacky because Python does not give any + # guarantee what happens if Queue methods/attributes are overwritten + # when it is already in use. However, because of our dummy _put() + # and _get() methods, it provides a workaround to let the queue appear + # to be never empty or full. + # See issue https://github.com/beetbox/beets/issues/2078 + q.maxsize = 2 q._qsize = _qsize q._put = _put q._get = _get diff --git a/test/test_pipeline.py b/test/test_pipeline.py index a40cccdbd..4d3bde4d0 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -162,7 +162,6 @@ class ConstrainedThreadedPipelineTest(unittest.TestCase): pl.run_parallel(1) self.assertEqual(l, [i * 2 for i in range(1000)]) - @unittest.skipIf(six.PY3, u'freezes the test suite in py3') def test_constrained_exception(self): # Raise an exception in a constrained pipeline. l = [] From 4ae7448c25dfd888ff5c5b810772b0866eace6fb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 10:12:38 -0700 Subject: [PATCH 1108/2280] Simplify print_ changes (#2094) --- beets/ui/__init__.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 4fd79974f..21966b2c6 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -135,7 +135,8 @@ def print_(*strings, **kwargs): is not in the terminal's encoding's character set, just silently replaces it. - The arguments must be unicode strings + The arguments must be Unicode strings: `unicode` on Python 2; `str` on + Python 3. The `end` keyword argument behaves similarly to the built-in `print` (it defaults to a newline). The value should have the same string @@ -143,17 +144,14 @@ def print_(*strings, **kwargs): """ if not strings: strings = [u''] - - end = kwargs.get('end') assert isinstance(strings[0], six.text_type) txt = u' '.join(strings) - txt += u'\n' if end is None else end + txt += kwargs.get('end', u'\n') - # Always send bytes to the stdout stream on python 2. + # Send bytes to the stdout stream on Python 2. if six.PY2: - if isinstance(txt, six.text_type): - txt = txt.encode(_out_encoding(), 'replace') + txt = txt.encode(_out_encoding(), 'replace') sys.stdout.write(txt) From e2c6547635bb12d6baae48281116ced38aa55ea3 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 29 Jun 2016 19:16:44 +0200 Subject: [PATCH 1109/2280] fetchart: Clarify the deprecation of `remote_priority` in docs and warning, closes #2092 --- beetsplug/fetchart.py | 3 ++- docs/plugins/fetchart.rst | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 22e2be56c..6c7984845 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -762,7 +762,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if 'remote_priority' in self.config: self._log.warning( u'The `fetch_art.remote_priority` configuration option has ' - u'been deprecated, see the documentation.') + u'been deprecated. Instead, place `filesystem` at the end of ' + u'your `sources` list.') if self.config['remote_priority'].get(bool): try: sources_name.remove(u'filesystem') diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 2812c7745..7856521a9 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -69,6 +69,14 @@ file. The available options are: Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ or `Pillow`_. +.. note:: + + Previously, there was a `remote_priority` option to specify when to + look for art on the filesystem. This is + still respected, but a deprecation message will be shown until you + replace this configuration with the new `filesystem` value in the + `sources` array. + .. _beets custom search engine: https://cse.google.com.au:443/cse/publicurl?cx=001442825323518660753:hrh5ch1gjzm .. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ From d5205915ccb49495ab4c245a7908aadbbd628772 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 10:30:26 -0700 Subject: [PATCH 1110/2280] Avoid dangerous string conversions (#2094) This rolls back the places in #2094 where `six.text_type(s)` was used where `s` might be a bytestring. We almost never want that conversion, because it uses the default encoding (almost always ASCII). The need for it indicates a problem somewhere else, where bytes were produced when we were expecting unicode strings. --- beets/ui/commands.py | 32 ++++++++++++++++---------------- test/test_ui.py | 12 ++++++------ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 325b549d3..eb7807dc8 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -86,13 +86,13 @@ def _print_keys(query): returned row, with identation of 2 spaces. """ for row in query: - print_(u' ' * 2 + six.text_type(row['key'])) + print_(u' ' * 2 + row['key'].decode('utf8')) def fields_func(lib, opts, args): def _print_rows(names): names.sort() - print_(six.text_type(' ' + '\n '.join(names))) + print_(u' ' + u'\n '.join(names)) print_(u"Item fields:") _print_rows(library.Item.all_keys()) @@ -1054,16 +1054,16 @@ default_commands.append(import_cmd) # list: Query and show library contents. -def list_items(lib, query, album, fmt=''): +def list_items(lib, query, album, fmt=u''): """Print out items in lib matching query. If album, then search for albums instead of single items. """ if album: for album in lib.albums(query): - ui.print_(six.text_type(format(album, fmt))) + ui.print_(format(album, fmt)) else: for item in lib.items(query): - ui.print_(six.text_type(format(item, fmt))) + ui.print_(format(item, fmt)) def list_func(lib, opts, args): @@ -1617,7 +1617,7 @@ def config_func(lib, opts, args): # Dump configuration. else: config_out = config.dump(full=opts.defaults, redact=opts.redact) - print_(six.text_type(config_out)) + print_(config_out.decode('utf8')) def config_edit(): @@ -1663,7 +1663,7 @@ default_commands.append(config_cmd) def print_completion(*args): for line in completion_script(default_commands + plugins.commands()): - print_(six.text_type(line), end=u'') + print_(line, end=u'') if not any(map(os.path.isfile, BASH_COMPLETION_PATHS)): log.warn(u'Warning: Unable to find the bash-completion package. ' u'Command line completion might not work.') @@ -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 base_script.read() + yield base_script.read().decode('utf8') options = {} aliases = {} @@ -1702,12 +1702,12 @@ def completion_script(commands): if re.match(r'^\w+$', alias): aliases[alias] = name - options[name] = {'flags': [], 'opts': []} + options[name] = {u'flags': [], u'opts': []} for opts in cmd.parser._get_all_options()[1:]: if opts.action in ('store_true', 'store_false'): - option_type = 'flags' + option_type = u'flags' else: - option_type = 'opts' + option_type = u'opts' options[name][option_type].extend( opts._short_opts + opts._long_opts @@ -1715,14 +1715,14 @@ def completion_script(commands): # Add global options options['_global'] = { - 'flags': [u'-v', u'--verbose'], - 'opts': u'-l --library -c --config -d --directory -h --help'.split( - u' ') + u'flags': [u'-v', u'--verbose'], + u'opts': + u'-l --library -c --config -d --directory -h --help'.split(u' ') } # Add flags common to all commands options['_common'] = { - 'flags': [u'-h', u'--help'] + u'flags': [u'-h', u'--help'] } # Start generating the script @@ -1750,7 +1750,7 @@ def completion_script(commands): for cmd, opts in options.items(): for option_type, option_list in opts.items(): if option_list: - option_list = ' '.join(option_list) + option_list = u' '.join(option_list) yield u" local %s__%s='%s'\n" % ( option_type, cmd, option_list) diff --git a/test/test_ui.py b/test/test_ui.py index 5ea875e42..63af553bf 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -49,7 +49,7 @@ class ListTest(unittest.TestCase): self.lib.add(self.item) self.lib.add_album([self.item]) - def _run_list(self, query=u'', album=False, path=False, fmt=''): + def _run_list(self, query=u'', album=False, path=False, fmt=u''): commands.list_items(self.lib, query, album, fmt) def test_list_outputs_item(self): @@ -69,7 +69,7 @@ class ListTest(unittest.TestCase): def test_list_item_path(self): with capture_stdout() as stdout: - self._run_list(fmt='$path') + self._run_list(fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx/yyy') def test_list_album_outputs_something(self): @@ -79,7 +79,7 @@ class ListTest(unittest.TestCase): def test_list_album_path(self): with capture_stdout() as stdout: - self._run_list(album=True, fmt='$path') + self._run_list(album=True, fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx') def test_list_album_omits_title(self): @@ -101,18 +101,18 @@ class ListTest(unittest.TestCase): def test_list_item_format_artist(self): with capture_stdout() as stdout: - self._run_list(fmt='$artist') + self._run_list(fmt=u'$artist') self.assertIn(u'the artist', stdout.getvalue()) def test_list_item_format_multiple(self): with capture_stdout() as stdout: - self._run_list(fmt='$artist - $album - $year') + self._run_list(fmt=u'$artist - $album - $year') self.assertEqual(u'the artist - the album - 0001', stdout.getvalue().strip()) def test_list_album_format(self): with capture_stdout() as stdout: - self._run_list(album=True, fmt='$genre') + self._run_list(album=True, fmt=u'$genre') self.assertIn(u'the genre', stdout.getvalue()) self.assertNotIn(u'the album', stdout.getvalue()) From 89c7b78994c304bf443b14580948eb9e30948009 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 10:43:51 -0700 Subject: [PATCH 1111/2280] Disable PyPy on Travis for now Travis has a very old version of PyPy which seems to be running into a Unicode-related bug in our tests. --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index d5611deb5..54ec2b817 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,8 +16,8 @@ matrix: env: {TOX_ENV: py34-test} - python: 3.5 env: {TOX_ENV: py35-test} - - python: pypy - env: {TOX_ENV: pypy-test} + # - python: pypy + # - env: {TOX_ENV: pypy-test} - python: 2.7 env: {TOX_ENV: py27-flake8} - python: 3.3 From 44ca6938ffd450847810f5c426e9afdbab1fc424 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 10:51:56 -0700 Subject: [PATCH 1112/2280] Add FIXMEs to functemplate about py3 --- beets/util/functemplate.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 2b32971e2..cdccc49a5 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -508,7 +508,7 @@ class Template(object): def __init__(self, template): self.expr = _parse(template) self.original = template - if six.PY2: + if six.PY2: # FIXME Compiler is broken on Python 3. self.compiled = self.translate() def __eq__(self, other): @@ -525,7 +525,7 @@ class Template(object): def substitute(self, values={}, functions={}): """Evaluate the template given the values and functions. """ - if six.PY2: + if six.PY2: # FIXME As above. try: res = self.compiled(values, functions) except: # Handle any exceptions thrown by compiled version. From 4c324fae2ab21eef860dea4dc7d6d49b736cfab3 Mon Sep 17 00:00:00 2001 From: Johannes Baiter Date: Wed, 29 Jun 2016 20:34:05 +0200 Subject: [PATCH 1113/2280] beatport: Use track numbers from API (#2091) * beatport: Use trackNumber from API instead of enumerating the tracks * beatport: Set medium_index to track number * Update changelog with fixes to beatport plugin --- beetsplug/beatport.py | 10 +++++----- docs/changelog.rst | 3 +++ 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index f7c52bd38..1ea1aea4e 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -252,6 +252,7 @@ class BeatportTrack(BeatportObject): if 'slug' in data: self.url = "http://beatport.com/track/{0}/{1}".format(data['slug'], data['id']) + self.track_number = data.get('trackNumber') class BeatportPlugin(BeetsPlugin): @@ -406,8 +407,7 @@ class BeatportPlugin(BeetsPlugin): artist, artist_id = self._get_artist(release.artists) if va: artist = u"Various Artists" - tracks = [self._get_track_info(x, index=idx) - for idx, x in enumerate(release.tracks, 1)] + tracks = [self._get_track_info(x) for x in release.tracks] return AlbumInfo(album=release.name, album_id=release.beatport_id, artist=artist, artist_id=artist_id, tracks=tracks, @@ -419,7 +419,7 @@ class BeatportPlugin(BeetsPlugin): catalognum=release.catalog_number, media=u'Digital', data_source=u'Beatport', data_url=release.url) - def _get_track_info(self, track, index=None): + def _get_track_info(self, track): """Returns a TrackInfo object for a Beatport Track object. """ title = track.name @@ -427,10 +427,10 @@ class BeatportPlugin(BeetsPlugin): title += u" ({0})".format(track.mix_name) artist, artist_id = self._get_artist(track.artists) length = track.length.total_seconds() - return TrackInfo(title=title, track_id=track.beatport_id, artist=artist, artist_id=artist_id, - length=length, index=index, + length=length, index=track.track_number, + medium_index=track.track_number, data_source=u'Beatport', data_url=track.url) def _get_artist(self, artists): diff --git a/docs/changelog.rst b/docs/changelog.rst index 6bf4a9681..8ac73257b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,9 @@ Fixes: * :doc:`/plugins/permissions`: Fix a regression in the previous release where the plugin would always fail to set permissions (and log a warning). :bug:`2089` +* :doc:`/plugins/beatport`: Use track numbers from Beatport (instead of + determining them from the order of tracks) and set the `medium_index` + value. * With :ref:`per_disc_numbering` enabled, some metadata sources (notably, the :doc:`/plugins/beatport`) would not set the track number at all. This is fixed. :bug:`2085` From 3d9b43fd06bf23a52cadbc65478a1cc2b7b693c4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 11:38:58 -0700 Subject: [PATCH 1114/2280] Update codecov.yml for new configuration format? Their web interface confusingly just says that the file is missing, but perhaps that means the formatting is invalid? I *really* wish this stuff were more transparent. :cry: --- codecov.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/codecov.yml b/codecov.yml index d01e442e5..cbbe408ba 100644 --- a/codecov.yml +++ b/codecov.yml @@ -4,9 +4,6 @@ comment: off # I think this disables commit statuses? coverage: status: - project: - enabled: no - patch: - enabled: no - changes: - enabled: no + project: no + patch: no + changes: no From a2a4926598ce95ce5621362ba2c019c505b46a90 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 29 Jun 2016 23:42:14 -0400 Subject: [PATCH 1115/2280] replace .decode('utf-8') with as_string() from #2094 They are strings in py3, so they need to stay that way --- beets/ui/commands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index eb7807dc8..89ceef692 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_(config_out.decode('utf8')) + print_(util.as_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 base_script.read().decode('utf8') + yield util.as_string(base_script.read()) options = {} aliases = {} From ecfda77f5a71e7881e4e97d63952f3869b4d50c2 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 00:07:52 -0400 Subject: [PATCH 1116/2280] bytestringify a few more paths in tests --- test/helper.py | 3 ++- test/test_art.py | 2 +- test/test_mediafile.py | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/test/helper.py b/test/helper.py index 8df7c8e3c..d0b8472b4 100644 --- a/test/helper.py +++ b/test/helper.py @@ -437,7 +437,8 @@ class TestHelper(object): """Create a temporary directory and assign it into `self.temp_dir`. Call `remove_temp_dir` later to delete it. """ - self.temp_dir = mkdtemp() + temp_dir = mkdtemp() + self.temp_dir = util.bytestring_path(temp_dir) def remove_temp_dir(self): """Delete the temporary directory created by `create_temp_dir`. diff --git a/test/test_art.py b/test/test_art.py index 8659cf12a..a36719ac5 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -416,7 +416,7 @@ class ArtImporterTest(UseThePlugin): # Test library. self.libpath = os.path.join(self.temp_dir, 'tmplib.blb') - self.libdir = os.path.join(self.temp_dir, 'tmplib') + self.libdir = os.path.join(self.temp_dir, b'tmplib') os.mkdir(self.libdir) os.mkdir(os.path.join(self.libdir, b'album')) itempath = os.path.join(self.libdir, b'album', b'test.mp3') diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 5a6100c54..a2cc04d8c 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -449,7 +449,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, ] def setUp(self): - self.temp_dir = tempfile.mkdtemp() + self.temp_dir = bytestring_path(tempfile.mkdtemp()) def tearDown(self): if os.path.isdir(self.temp_dir): From 386f58236440e1bae49bcf6e2a047fb808796155 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 22:25:03 -0700 Subject: [PATCH 1117/2280] 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 From cec632f359ca78e357606fc0938d8c8a7d3fe663 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 29 Jun 2016 22:53:51 -0700 Subject: [PATCH 1118/2280] Python 3 compatible formatting in `unique_path` --- beets/util/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index ba9445f8f..832d17942 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -496,7 +496,8 @@ def unique_path(path): num = 0 while True: num += 1 - new_path = b'%s.%i%s' % (base, num, ext) + suffix = u'.{}'.format(num).encode() + ext + new_path = base + suffix if not os.path.exists(new_path): return new_path From 75c226bd37733ff4e2d958cd05c9826adbebdf60 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 02:09:52 -0400 Subject: [PATCH 1119/2280] remove pathlib tests that just test pathlib itself --- test/test_thumbnails.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index 0454ae0d7..fe1c80f4a 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -273,20 +273,15 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): def test_uri(self): gio = GioURI() - plib = PathlibURI() if not gio.available: self.skipTest(u"GIO library not found") self.assertEqual(gio.uri(u"/foo"), b"file:///") # silent fail self.assertEqual(gio.uri(b"/foo"), b"file:///foo") self.assertEqual(gio.uri(b"/foo!"), b"file:///foo!") - self.assertEqual(plib.uri(b"/foo!"), b"file:///foo%21") self.assertEqual( gio.uri(b'/music/\xec\x8b\xb8\xec\x9d\xb4'), b'file:///music/%EC%8B%B8%EC%9D%B4') - self.assertEqual( - plib.uri(b'/music/\xec\x8b\xb8\xec\x9d\xb4'), - b'file:///music/%EC%8B%B8%EC%9D%B4') def suite(): From 2617536294261a8766f3a34ff6fe4c5f058152e7 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 07:11:52 -0400 Subject: [PATCH 1120/2280] Remove support for Python 3.3 It doesn't seem like Python 3.3 is worth supporting anymore. I'm not sure if any popular(ish) distro supports Python 3.3, only 3.2 or >=3.4 --- .travis.yml | 7 ++----- appveyor.yml | 3 --- tox.ini | 6 +++--- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 54ec2b817..dfc3719b5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,8 +10,6 @@ matrix: include: - python: 2.7 env: {TOX_ENV: py27-cov, COVERAGE: 1} - - python: 3.3 - env: {TOX_ENV: py33-test} - python: 3.4 env: {TOX_ENV: py34-test} - python: 3.5 @@ -20,12 +18,11 @@ matrix: # - env: {TOX_ENV: pypy-test} - python: 2.7 env: {TOX_ENV: py27-flake8} - - python: 3.3 - env: {TOX_ENV: py33-flake8} + - python: 3.4 + env: {TOX_ENV: py34-flake8} - python: 2.7 env: {TOX_ENV: docs} allow_failures: - - python: 3.3 - python: 3.4 - python: 3.5 diff --git a/appveyor.yml b/appveyor.yml index ef3ba8bcc..fef39faf2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,8 +9,6 @@ environment: matrix: - PYTHON: C:\Python27 TOX_ENV: py27-test - - PYTHON: C:\Python33 - TOX_ENV: py33-test - PYTHON: C:\Python34 TOX_ENV: py34-test - PYTHON: C:\Python35 @@ -27,6 +25,5 @@ test_script: # Allow all failures for now: the tests don't yet pass! matrix: allow_failures: - - TOX_ENV: py33-test - TOX_ENV: py34-test - TOX_ENV: py35-test diff --git a/tox.ini b/tox.ini index 22d4aba2a..f0cc77b04 100644 --- a/tox.ini +++ b/tox.ini @@ -7,7 +7,7 @@ envlist = py27-test, py27-flake8, docs # The exhaustive list of environments is: -# envlist = py{27,33,34,35}-{test,cov}, py{27,33}-flake8, docs +# envlist = py{27,34,35}-{test,cov}, py{27,34}-flake8, docs [_test] deps = @@ -37,12 +37,12 @@ passenv = NOSE_SHOW_SKIPPED # Undocumented feature of nose-show-skipped. deps = {test,cov}: {[_test]deps} - py{27,33}-flake8: {[_flake8]deps} + py{27,34}-flake8: {[_flake8]deps} commands = cov: nosetests --with-coverage {posargs} test: nosetests {posargs} py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} - py33-flake8: flake8 --min-version 3.3 {posargs} {[_flake8]files} + py34-flake8: flake8 --min-version 3.4 {posargs} {[_flake8]files} [testenv:docs] basepython = python2.7 From c532860613d610d28c28d76046f1c70c7507754b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 14:22:16 -0700 Subject: [PATCH 1121/2280] Apply simple type consistency changes from #2096 These are the changes from that PR that just enforce the path type invariants we already want---they're a good idea regardless of Python 3. --- test/_common.py | 7 ++++--- test/helper.py | 2 +- test/test_art.py | 2 +- test/test_ui.py | 34 +++++++++++++++++----------------- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/test/_common.py b/test/_common.py index a3388b88e..d467a75aa 100644 --- a/test/_common.py +++ b/test/_common.py @@ -162,9 +162,10 @@ class TestCase(unittest.TestCase, Assertions): # Direct paths to a temporary directory. Tests can also use this # temporary directory. self.temp_dir = tempfile.mkdtemp() - beets.config['statefile'] = os.path.join(self.temp_dir, 'state.pickle') - beets.config['library'] = os.path.join(self.temp_dir, 'library.db') - beets.config['directory'] = os.path.join(self.temp_dir, 'libdir') + beets.config['statefile'] = os.path.join(self.temp_dir, + b'state.pickle') + beets.config['library'] = os.path.join(self.temp_dir, b'library.db') + beets.config['directory'] = os.path.join(self.temp_dir, b'libdir') # Set $HOME, which is used by confit's `config_dir()` to create # directories. diff --git a/test/helper.py b/test/helper.py index d0b8472b4..24171920f 100644 --- a/test/helper.py +++ b/test/helper.py @@ -185,7 +185,7 @@ class TestHelper(object): self.config['directory'] = self.libdir if disk: - dbpath = self.config['library'].as_filename() + dbpath = util.bytestring_path(self.config['library'].as_filename()) else: dbpath = ':memory:' self.lib = Library(dbpath, self.libdir) diff --git a/test/test_art.py b/test/test_art.py index a36719ac5..5c3a4d7e9 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -415,7 +415,7 @@ class ArtImporterTest(UseThePlugin): self.plugin.art_for_album = art_for_album # Test library. - self.libpath = os.path.join(self.temp_dir, 'tmplib.blb') + self.libpath = os.path.join(self.temp_dir, b'tmplib.blb') self.libdir = os.path.join(self.temp_dir, b'tmplib') os.mkdir(self.libdir) os.mkdir(os.path.join(self.libdir, b'album')) diff --git a/test/test_ui.py b/test/test_ui.py index 63af553bf..7177f4ce3 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -671,11 +671,11 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # Default user configuration if platform.system() == 'Windows': self.user_config_dir = os.path.join( - self.temp_dir, 'AppData', 'Roaming', 'beets' + self.temp_dir, b'AppData', b'Roaming', b'beets' ) else: self.user_config_dir = os.path.join( - self.temp_dir, '.config', 'beets' + self.temp_dir, b'.config', b'beets' ) os.makedirs(self.user_config_dir) self.user_config_path = os.path.join(self.user_config_dir, @@ -846,11 +846,11 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['--config', cli_config_path, 'test']) self.assert_equal_path( config['library'].as_filename(), - os.path.join(self.user_config_dir, 'beets.db') + os.path.join(self.user_config_dir, b'beets.db') ) self.assert_equal_path( config['statefile'].as_filename(), - os.path.join(self.user_config_dir, 'state') + os.path.join(self.user_config_dir, b'state') ) def test_cli_config_paths_resolve_relative_to_beetsdir(self): @@ -863,9 +863,9 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['--config', cli_config_path, 'test']) self.assert_equal_path(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) + os.path.join(self.beetsdir, b'beets.db')) self.assert_equal_path(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + os.path.join(self.beetsdir, b'state')) def test_command_line_option_relative_to_working_dir(self): os.chdir(self.temp_dir) @@ -885,7 +885,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def test_beetsdir_config(self): os.environ['BEETSDIR'] = self.beetsdir - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('anoption: overwrite') @@ -893,7 +893,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.assertEqual(config['anoption'].get(), 'overwrite') def test_beetsdir_points_to_file_error(self): - beetsdir = os.path.join(self.temp_dir, 'beetsfile') + beetsdir = os.path.join(self.temp_dir, b'beetsfile') open(beetsdir, 'a').close() os.environ['BEETSDIR'] = beetsdir self.assertRaises(ConfigError, ui._raw_main, ['test']) @@ -911,24 +911,24 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.environ['BEETSDIR'] = self.beetsdir config.read() - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'library.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state.pickle')) + self.assert_equal_path(config['library'].as_filename(), + os.path.join(self.beetsdir, b'library.db')) + self.assert_equal_path(config['statefile'].as_filename(), + os.path.join(self.beetsdir, b'state.pickle')) def test_beetsdir_config_paths_resolve_relative_to_beetsdir(self): os.environ['BEETSDIR'] = self.beetsdir - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') config.read() - self.assertEqual(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) - self.assertEqual(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + self.assert_equal_path(config['library'].as_filename(), + os.path.join(self.beetsdir, 'beets.db')) + self.assert_equal_path(config['statefile'].as_filename(), + os.path.join(self.beetsdir, 'state')) class ShowModelChangeTest(_common.TestCase): From a6830ae7d11b7864cbd2a8203b4b72522c9d1971 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 14:29:50 -0700 Subject: [PATCH 1122/2280] Remove dead path normalization The `self.path` field was immediately overwritten in the __init__ from dbcore, so this was doing nothing. --- beets/library.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 5ef809122..a6e0b7a13 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1208,8 +1208,6 @@ class Library(dbcore.Database): path_formats=((PF_KEY_DEFAULT, '$artist/$album/$track $title'),), replacements=None): - if path != ':memory:': - self.path = bytestring_path(normpath(path)) super(Library, self).__init__(path) self.directory = bytestring_path(normpath(directory)) From 61805b99941dea06fba5bc5f4104c6a56191ca06 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 14:48:07 -0700 Subject: [PATCH 1123/2280] Marginally more readable bytes/memoryview switch --- beets/library.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/beets/library.py b/beets/library.py index a6e0b7a13..1d63da2c7 100644 --- a/beets/library.py +++ b/beets/library.py @@ -35,8 +35,14 @@ from beets import dbcore from beets.dbcore import types import beets -if not six.PY2: - buffer = memoryview # sqlite won't accept memoryview in python 2 +# To use the SQLite "blob" type, it doesn't suffice to provide a byte +# string; SQLite treats that as encoded text. Wrapping it in a `buffer` or a +# `memoryview`, depending on the Python version, tells it that we +# actually mean non-text data. +if six.PY2: + BLOB_TYPE = buffer +else: + BLOB_TYPE = memoryview log = logging.getLogger('beets') @@ -103,16 +109,16 @@ class PathQuery(dbcore.FieldQuery): def col_clause(self): if self.case_sensitive: - file_blob = buffer(self.file_path) - dir_blob = buffer(self.dir_path) + file_blob = BLOB_TYPE(self.file_path) + dir_blob = BLOB_TYPE(self.dir_path) return '({0} = ?) || (substr({0}, 1, ?) = ?)'.format(self.field), \ (file_blob, len(dir_blob), dir_blob) escape = lambda m: self.escape_char + m.group(0) dir_pattern = self.escape_re.sub(escape, self.dir_path) - dir_blob = buffer(dir_pattern + b'%') + dir_blob = BLOB_TYPE(dir_pattern + b'%') file_pattern = self.escape_re.sub(escape, self.file_path) - file_blob = buffer(file_pattern) + file_blob = BLOB_TYPE(file_pattern) return '({0} LIKE ? ESCAPE ?) || ({0} LIKE ? ESCAPE ?)'.format( self.field), (file_blob, self.escape_char, dir_blob, self.escape_char) @@ -160,9 +166,8 @@ class PathType(types.Type): # Paths stored internally as encoded bytes. return bytestring_path(value) - elif isinstance(value, buffer): - # SQLite must store bytestings as buffers/memoryview - # to avoid decoding. We unwrap buffers to bytes. + elif isinstance(value, BLOB_TYPE): + # We unwrap buffers to bytes. return bytes(value) else: @@ -173,7 +178,7 @@ class PathType(types.Type): def to_sql(self, value): if isinstance(value, bytes): - value = buffer(value) + value = BLOB_TYPE(value) return value @@ -526,7 +531,7 @@ class Item(LibModel): if key == 'path': if isinstance(value, six.text_type): value = bytestring_path(value) - elif isinstance(value, buffer): + elif isinstance(value, BLOB_TYPE): value = bytes(value) if key in MediaFile.fields(): From e25a95b2d3dc19a79f88f530faf622c5e0a0a63a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 04:06:26 -0400 Subject: [PATCH 1124/2280] add py3_path() for methods the only accept strings on py3 It returns bytes on py2, and native strings on py3. This function was created by @sampsyo. --- beets/util/__init__.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 832d17942..83d1f18f3 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -625,6 +625,22 @@ def legalize_path(path, replacements, length, extension, fragment): return second_stage_path, retruncated +def py3_path(path): + """Convert a bytestring path to Unicode on Python 3 only. On Python + 2, return the bytestring path unchanged. + + This helps deal with APIs on Python 3 that *only* accept Unicode + (i.e., `str` objects). I philosophically disagree with this + decision, because paths are sadly bytes on Unix, but that's the way + it is. So this function helps us "smuggle" the true bytes data + through APIs that took Python 3's Unicode mandate too seriously. + """ + assert isinstance(path, bytes) + if six.PY2: + return path + return os.fsdecode(path) + + def str2bool(value): """Returns a boolean reflecting a human-entered string.""" return value.lower() in (u'yes', u'1', u'true', u't', u'y') From d04fe42cee9be8b0cdb10813a4af100e5f573688 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 14:54:38 -0700 Subject: [PATCH 1125/2280] Use py3_path for sqlite3.connect (part of #2096) --- beets/dbcore/db.py | 7 +++++-- beets/util/__init__.py | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index c0f329468..539658578 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -27,6 +27,7 @@ import collections import beets from beets.util.functemplate import Template +from beets.util import py3_path from beets.dbcore import types from .query import MatchQuery, NullSort, TrueQuery import six @@ -727,9 +728,11 @@ class Database(object): if thread_id in self._connections: return self._connections[thread_id] else: - # Make a new connection. + # Make a new connection. The `sqlite3` module can't use + # bytestring paths here on Python 3, so we need to + # provide a `str` using `py3_path`. conn = sqlite3.connect( - self.path, + py3_path(self.path), timeout=beets.config['timeout'].as_number(), ) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 83d1f18f3..0715459af 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -635,6 +635,8 @@ def py3_path(path): it is. So this function helps us "smuggle" the true bytes data through APIs that took Python 3's Unicode mandate too seriously. """ + if isinstance(path, six.text_type): + return path assert isinstance(path, bytes) if six.PY2: return path From ec08272a06ef663d1d9ad8448e8f8b9e02a31fa5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 15:47:39 -0700 Subject: [PATCH 1126/2280] Replace `map` with list comprehension --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 21966b2c6..ba6d4b148 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1106,7 +1106,7 @@ def _load_plugins(config): """Load the plugins specified in the configuration. """ paths = config['pluginpath'].get(confit.StrSeq(split=False)) - paths = list(map(util.normpath, paths)) + paths = [util.normpath(p) for p in paths] log.debug(u'plugin paths: {0}', util.displayable_path(paths)) import beetsplug From f65cf62c80bed7017f63836909d3252b2a46e300 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 30 Jun 2016 15:49:42 -0700 Subject: [PATCH 1127/2280] Use py3_path for plugin search paths (from #2096) --- beets/ui/__init__.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ba6d4b148..ba342f12c 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1109,9 +1109,15 @@ def _load_plugins(config): paths = [util.normpath(p) for p in paths] log.debug(u'plugin paths: {0}', util.displayable_path(paths)) + # On Python 3, the search paths need to be unicode. + paths = [util.py3_path(p) for p in paths] + + # Extend the `beetsplug` package to include the plugin paths. import beetsplug beetsplug.__path__ = paths + beetsplug.__path__ - # For backwards compatibility. + + # For backwards compatibility, also support plugin paths that + # *contain* a `beetsplug` package. sys.path += paths plugins.load_plugins(config['plugins'].as_str_seq()) From dd729f0ce8321fbfce573f2c6dad61e129aa4150 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 22:19:45 -0400 Subject: [PATCH 1128/2280] mark more paths as bytestrings in tests --- test/_common.py | 2 +- test/test_ui.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/_common.py b/test/_common.py index d467a75aa..791bbb22b 100644 --- a/test/_common.py +++ b/test/_common.py @@ -161,7 +161,7 @@ class TestCase(unittest.TestCase, Assertions): # Direct paths to a temporary directory. Tests can also use this # temporary directory. - self.temp_dir = tempfile.mkdtemp() + self.temp_dir = util.bytestring_path(tempfile.mkdtemp()) beets.config['statefile'] = os.path.join(self.temp_dir, b'state.pickle') beets.config['library'] = os.path.join(self.temp_dir, b'library.db') diff --git a/test/test_ui.py b/test/test_ui.py index 7177f4ce3..5643291c5 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -662,7 +662,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # Also set APPDATA, the Windows equivalent of setting $HOME. self._old_appdata = os.environ.get('APPDATA') os.environ['APPDATA'] = \ - os.path.join(self.temp_dir, 'AppData', 'Roaming') + util.py3_path(os.path.join(self.temp_dir, b'AppData', b'Roaming')) self._orig_cwd = os.getcwd() self.test_cmd = self._make_test_cmd() @@ -679,10 +679,10 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ) os.makedirs(self.user_config_dir) self.user_config_path = os.path.join(self.user_config_dir, - 'config.yaml') + b'config.yaml') # Custom BEETSDIR - self.beetsdir = os.path.join(self.temp_dir, 'beetsdir') + self.beetsdir = os.path.join(self.temp_dir, b'beetsdir') os.makedirs(self.beetsdir) self._reset_config() @@ -926,9 +926,9 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): config.read() self.assert_equal_path(config['library'].as_filename(), - os.path.join(self.beetsdir, 'beets.db')) + os.path.join(self.beetsdir, b'beets.db')) self.assert_equal_path(config['statefile'].as_filename(), - os.path.join(self.beetsdir, 'state')) + os.path.join(self.beetsdir, b'state')) class ShowModelChangeTest(_common.TestCase): From aa0a0a0f22c8ada25d354e0c5bf78adf44ef3825 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 30 Jun 2016 22:12:31 -0400 Subject: [PATCH 1129/2280] use util.py3_path for confit and env paths in tests --- test/_common.py | 13 ++++++++----- test/helper.py | 8 +++++--- test/test_metasync.py | 5 +++-- test/test_smartplaylist.py | 6 +++--- test/test_ui.py | 18 +++++++++--------- 5 files changed, 28 insertions(+), 22 deletions(-) diff --git a/test/_common.py b/test/_common.py index 791bbb22b..98a8a1e5b 100644 --- a/test/_common.py +++ b/test/_common.py @@ -162,15 +162,18 @@ class TestCase(unittest.TestCase, Assertions): # Direct paths to a temporary directory. Tests can also use this # temporary directory. self.temp_dir = util.bytestring_path(tempfile.mkdtemp()) - beets.config['statefile'] = os.path.join(self.temp_dir, - b'state.pickle') - beets.config['library'] = os.path.join(self.temp_dir, b'library.db') - beets.config['directory'] = os.path.join(self.temp_dir, b'libdir') + + beets.config['statefile'] = \ + util.py3_path(os.path.join(self.temp_dir, b'state.pickle')) + beets.config['library'] = \ + util.py3_path(os.path.join(self.temp_dir, b'library.db')) + beets.config['directory'] = \ + util.py3_path(os.path.join(self.temp_dir, b'libdir')) # Set $HOME, which is used by confit's `config_dir()` to create # directories. self._old_home = os.environ.get('HOME') - os.environ['HOME'] = self.temp_dir + os.environ['HOME'] = util.py3_path(self.temp_dir) # Initialize, but don't install, a DummyIO. self.io = DummyIO() diff --git a/test/helper.py b/test/helper.py index 24171920f..b91d5553c 100644 --- a/test/helper.py +++ b/test/helper.py @@ -169,7 +169,7 @@ class TestHelper(object): Make sure you call ``teardown_beets()`` afterwards. """ self.create_temp_dir() - os.environ['BEETSDIR'] = self.temp_dir + os.environ['BEETSDIR'] = util.py3_path(self.temp_dir) self.config = beets.config self.config.clear() @@ -182,10 +182,12 @@ class TestHelper(object): self.libdir = os.path.join(self.temp_dir, b'libdir') os.mkdir(self.libdir) - self.config['directory'] = self.libdir + self.config['directory'] = util.py3_path(self.libdir) if disk: - dbpath = util.bytestring_path(self.config['library'].as_filename()) + dbpath = util.bytestring_path( + self.config['library'].as_filename() + ) else: dbpath = ':memory:' self.lib = Library(dbpath, self.libdir) diff --git a/test/test_metasync.py b/test/test_metasync.py index 785a3381a..60f63c413 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -20,6 +20,7 @@ import platform import time from datetime import datetime from beets.library import Item +from beets.util import py3_path from test import _common from test._common import unittest @@ -48,10 +49,10 @@ class MetaSyncTest(_common.TestCase, TestHelper): if _is_windows(): self.config['metasync']['itunes']['library'] = \ - self.itunes_library_windows + py3_path(self.itunes_library_windows) else: self.config['metasync']['itunes']['library'] = \ - self.itunes_library_unix + py3_path(self.itunes_library_unix) self._set_up_data() diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 2f0f261d7..071ff390b 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -25,7 +25,7 @@ from beetsplug.smartplaylist import SmartPlaylistPlugin from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import NullSort, MultipleSort, FixedFieldSort -from beets.util import syspath, bytestring_path +from beets.util import syspath, bytestring_path, py3_path from beets.ui import UserError from beets import config @@ -161,7 +161,7 @@ class SmartPlaylistTest(unittest.TestCase): dir = bytestring_path(mkdtemp()) config['smartplaylist']['relative_to'] = False - config['smartplaylist']['playlist_dir'] = dir + config['smartplaylist']['playlist_dir'] = py3_path(dir) try: spl.update_playlists(lib) except Exception: @@ -191,7 +191,7 @@ class SmartPlaylistCLITest(unittest.TestCase, TestHelper): {'name': 'all.m3u', 'query': u''} ]) - config['smartplaylist']['playlist_dir'].set(self.temp_dir) + config['smartplaylist']['playlist_dir'].set(py3_path(self.temp_dir)) self.load_plugins('smartplaylist') def tearDown(self): diff --git a/test/test_ui.py b/test/test_ui.py index 5643291c5..1257b0876 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -657,7 +657,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # directory there. Some tests will set `BEETSDIR` themselves. del os.environ['BEETSDIR'] self._old_home = os.environ.get('HOME') - os.environ['HOME'] = self.temp_dir + os.environ['HOME'] = util.py3_path(self.temp_dir) # Also set APPDATA, the Windows equivalent of setting $HOME. self._old_appdata = os.environ.get('APPDATA') @@ -793,8 +793,8 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_file_overwrites_beetsdir_defaults(self): - os.environ['BEETSDIR'] = self.beetsdir - env_config_path = os.path.join(self.beetsdir, 'config.yaml') + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) + env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: file.write('anoption: value') @@ -854,7 +854,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ) def test_cli_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) cli_config_path = os.path.join(self.temp_dir, 'config.yaml') with open(cli_config_path, 'w') as file: @@ -883,7 +883,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.assertTrue(plugins.find_plugins()[0].is_test_plugin) def test_beetsdir_config(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: @@ -895,11 +895,11 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def test_beetsdir_points_to_file_error(self): beetsdir = os.path.join(self.temp_dir, b'beetsfile') open(beetsdir, 'a').close() - os.environ['BEETSDIR'] = beetsdir + os.environ['BEETSDIR'] = util.py3_path(beetsdir) self.assertRaises(ConfigError, ui._raw_main, ['test']) def test_beetsdir_config_does_not_load_default_user_config(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) with open(self.user_config_path, 'w') as file: file.write('anoption: value') @@ -908,7 +908,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.assertFalse(config['anoption'].exists()) def test_default_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) config.read() self.assert_equal_path(config['library'].as_filename(), @@ -917,7 +917,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.path.join(self.beetsdir, b'state.pickle')) def test_beetsdir_config_paths_resolve_relative_to_beetsdir(self): - os.environ['BEETSDIR'] = self.beetsdir + os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) env_config_path = os.path.join(self.beetsdir, b'config.yaml') with open(env_config_path, 'w') as file: From eea4c02d54f1d30e5699df2f489e2eb02ec5edb2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 20:57:35 -0700 Subject: [PATCH 1130/2280] Fix a bytes(s) call in MediaFile --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 32d2abc90..13d9b9920 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -774,7 +774,7 @@ class MP3DescStorageStyle(MP3StorageStyle): # Try creating a new frame. if not found: frame = mutagen.id3.Frames[self.key]( - desc=bytes(self.description), + desc=self.description.encode('utf8'), text=value, encoding=mutagen.id3.Encoding.UTF8, ) From b1fb17c29c1b88eccd35f2b3bac5b040467b17d4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:03:00 -0700 Subject: [PATCH 1131/2280] UFID tags store strings as encoded bytes --- beets/mediafile.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 13d9b9920..3deeee31d 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -725,7 +725,7 @@ class MP3ListStorageStyle(ListStorageStyle, MP3StorageStyle): class MP3UFIDStorageStyle(MP3StorageStyle): - """Store data in a UFID ID3 frame with a particular owner. + """Store string data in a UFID ID3 frame with a particular owner. """ def __init__(self, owner, **kwargs): self.owner = owner @@ -738,6 +738,10 @@ class MP3UFIDStorageStyle(MP3StorageStyle): return None def store(self, mutagen_file, value): + # This field type stores text data as encoded data. + assert isinstance(value, six.text_type) + value = value.encode('utf8') + frames = mutagen_file.tags.getall(self.key) for frame in frames: # Replace existing frame data. From 45727c56e28a4cda63852d9423a2a3400388717a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 1 Jul 2016 23:56:37 -0400 Subject: [PATCH 1132/2280] treat DummyIO as text on py3 --- test/_common.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/_common.py b/test/_common.py index 98a8a1e5b..2c4fe1f24 100644 --- a/test/_common.py +++ b/test/_common.py @@ -21,6 +21,7 @@ import sys import os import tempfile import shutil +import six import unittest from contextlib import contextmanager @@ -256,7 +257,10 @@ class DummyOut(object): self.buf.append(s) def get(self): - return b''.join(self.buf) + if six.PY2: + return b''.join(self.buf) + else: + return ''.join(self.buf) def clear(self): self.buf = [] @@ -271,7 +275,10 @@ class DummyIn(object): self.out = out def add(self, s): - self.buf.append(s + b'\n') + if six.PY2: + self.buf.append(s + b'\n') + else: + self.buf.append(s + '\n') def readline(self): if not self.buf: From 9020dc1f45433c4bbe10665ab1213914c7640cf1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 1 Jul 2016 22:48:18 -0400 Subject: [PATCH 1133/2280] use text_string() in a few places for io output --- beetsplug/keyfinder.py | 2 +- test/helper.py | 2 +- test/test_ui.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index 0ef5ac155..77312e25b 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -73,7 +73,7 @@ class KeyFinderPlugin(BeetsPlugin): key_raw = output.rsplit(None, 1)[-1] try: - key = key_raw.decode('utf8') + key = util.text_string(key_raw) except UnicodeDecodeError: self._log.error(u'output is invalid UTF-8') continue diff --git a/test/helper.py b/test/helper.py index b91d5553c..3f187d76e 100644 --- a/test/helper.py +++ b/test/helper.py @@ -431,7 +431,7 @@ class TestHelper(object): def run_with_output(self, *args): with capture_stdout() as out: self.run_command(*args) - return out.getvalue().decode('utf-8') + return util.text_string(out.getvalue()) # Safe file operations diff --git a/test/test_ui.py b/test/test_ui.py index 1257b0876..3e29c180a 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1013,7 +1013,7 @@ class ShowChangeTest(_common.TestCase): autotag.AlbumMatch(album_dist, info, mapping, set(), set()), ) # FIXME decoding shouldn't be done here - return self.io.getoutput().lower().decode('utf8') + return util.text_string(self.io.getoutput().lower()) def test_null_change(self): msg = self._show_change() From a3236cbee060ef52bd971d059b4c4039260f5c51 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:15:33 -0700 Subject: [PATCH 1134/2280] Set APIC frame desc to unicode Weirdly, using binary data here resulted in Mutagen storing a string containing "b'foo'", i.e., the `repr` of a bytes object. --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 3deeee31d..7d7661bb2 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -874,7 +874,7 @@ class MP3ImageStorageStyle(ListStorageStyle, MP3StorageStyle): frame = mutagen.id3.Frames[self.key]() frame.data = image.data frame.mime = image.mime_type - frame.desc = (image.desc or u'').encode('utf8') + frame.desc = image.desc or u'' frame.encoding = 3 # UTF-8 encoding of desc frame.type = image.type_index return frame From 17927303ed9ebd4fa4127347d90e9c44b29f0c7a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:21:31 -0700 Subject: [PATCH 1135/2280] Store Vorbis image blocks using text strings --- beets/mediafile.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 7d7661bb2..d8529ecb8 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -955,7 +955,11 @@ class VorbisImageStorageStyle(ListStorageStyle): pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' - return base64.b64encode(pic.write()) + + # Encoding with base64 returns bytes on both Python 2 and 3. + # Mutagen requires the data to be a Unicode string, so we decode + # it before passing it along. + return base64.b64encode(pic.write()).decode('ascii') class FlacImageStorageStyle(ListStorageStyle): From 30a172fff31afd757c3eca56710a48ea9f6075c1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:29:50 -0700 Subject: [PATCH 1136/2280] Properly handle exceptions in custom tag tests --- test/test_mediafile.py | 51 ++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index a2cc04d8c..32d93f815 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -312,43 +312,50 @@ class ExtendedFieldTestMixin(object): plugin = BeetsPlugin() plugin.add_media_field('customtag', field_extension) - mediafile = self._mediafile_fixture('empty') - mediafile.customtag = u'F#' - mediafile.save() + try: + mediafile = self._mediafile_fixture('empty') + mediafile.customtag = u'F#' + mediafile.save() - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, u'F#') - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') + mediafile = MediaFile(mediafile.path) + self.assertEqual(mediafile.customtag, u'F#') + + finally: + delattr(MediaFile, 'customtag') + Item._media_fields.remove('customtag') def test_write_extended_tag_from_item(self): plugin = BeetsPlugin() plugin.add_media_field('customtag', field_extension) - mediafile = self._mediafile_fixture('empty') - self.assertIsNone(mediafile.customtag) + try: + mediafile = self._mediafile_fixture('empty') + self.assertIsNone(mediafile.customtag) - item = Item(path=mediafile.path, customtag=u'Gb') - item.write() - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, u'Gb') + item = Item(path=mediafile.path, customtag=u'Gb') + item.write() + mediafile = MediaFile(mediafile.path) + self.assertEqual(mediafile.customtag, u'Gb') - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') + finally: + delattr(MediaFile, 'customtag') + Item._media_fields.remove('customtag') def test_read_flexible_attribute_from_file(self): plugin = BeetsPlugin() plugin.add_media_field('customtag', field_extension) - mediafile = self._mediafile_fixture('empty') - mediafile.update({'customtag': u'F#'}) - mediafile.save() + try: + mediafile = self._mediafile_fixture('empty') + mediafile.update({'customtag': u'F#'}) + mediafile.save() - item = Item.from_path(mediafile.path) - self.assertEqual(item['customtag'], u'F#') + item = Item.from_path(mediafile.path) + self.assertEqual(item['customtag'], u'F#') - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') + finally: + delattr(MediaFile, 'customtag') + Item._media_fields.remove('customtag') def test_invalid_descriptor(self): with self.assertRaises(ValueError) as cm: From 4ddb7cfe9e5fa671a34ce56cb7929730da0ce15e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:47:18 -0700 Subject: [PATCH 1137/2280] ID3 `desc` fields also use unicode strings The old version *also* silently led to the string "b'foo'" being stored in the frame on Python 3. --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index d8529ecb8..2a678f304 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -778,7 +778,7 @@ class MP3DescStorageStyle(MP3StorageStyle): # Try creating a new frame. if not found: frame = mutagen.id3.Frames[self.key]( - desc=self.description.encode('utf8'), + desc=self.description, text=value, encoding=mutagen.id3.Encoding.UTF8, ) From 6919d6980fe6bf2b674ace913c86a191b5c059cb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 1 Jul 2016 21:54:37 -0700 Subject: [PATCH 1138/2280] Fix path types in test_unicode_path This is lifted directly from 658e814ad718610004cbe6d865c8f2f62e676ffb. --- test/test_library.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index d4c781986..4265f6d1a 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1065,7 +1065,8 @@ class TemplateTest(_common.LibTestCase): class UnicodePathTest(_common.LibTestCase): def test_unicode_path(self): - self.i.path = os.path.join(_common.RSRC, u'unicode\u2019d.mp3') + self.i.path = os.path.join(_common.RSRC, + u'unicode\u2019d.mp3'.encode('utf-8')) # If there are any problems with unicode paths, we will raise # here and fail. self.i.read() From 24ae4bb0569dfbf06d06c20893e98a8c5e1e6b86 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 01:23:56 -0400 Subject: [PATCH 1139/2280] encode path as utf-8 for is_path_query tests is_path_query is not supposed to accept bytestrings --- test/test_query.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_query.py b/test/test_query.py index 4650df868..e0bbebfe1 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -601,6 +601,7 @@ class PathQueryTest(_common.LibTestCase, TestHelper, AssertsMixin): try: path = self.touch(os.path.join(b'foo', b'bar')) + path = path.decode('utf-8') # The file itself. self.assertTrue(is_path(path)) From 02680eba59536c554fc7fcda91fb61461059f593 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 01:50:57 -0400 Subject: [PATCH 1140/2280] bytestringify a few more paths in test_importer --- test/test_importer.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index cd5756b1d..b879290ad 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -355,9 +355,10 @@ def create_archive(session): (handle, path) = mkstemp(dir=session.temp_dir) os.close(handle) archive = ZipFile(path, mode='w') - archive.write(os.path.join(_common.RSRC, 'full.mp3'), + archive.write(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() + path = bytestring_path(path) return path @@ -411,7 +412,7 @@ class ImportTarTest(ImportZipTest): (handle, path) = mkstemp(dir=self.temp_dir) os.close(handle) archive = TarFile(path, mode='w') - archive.add(os.path.join(_common.RSRC, 'full.mp3'), + archive.add(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() return path @@ -421,14 +422,14 @@ class ImportTarTest(ImportZipTest): class ImportRarTest(ImportZipTest): def create_archive(self): - return os.path.join(_common.RSRC, 'archive.rar') + return os.path.join(_common.RSRC, b'archive.rar') @unittest.skip('Implement me!') class ImportPasswordRarTest(ImportZipTest): def create_archive(self): - return os.path.join(_common.RSRC, 'password.rar') + return os.path.join(_common.RSRC, b'password.rar') class ImportSingletonTest(_common.TestCase, ImportHelper): From e83b9ce14acd2b3161780084c05099fd784fa286 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 02:24:26 -0400 Subject: [PATCH 1141/2280] add unrar to .travis.yml --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index dfc3719b5..d8d176dec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,6 +32,7 @@ addons: packages: - bash-completion - mp3gain + - unrar # To install dependencies, tell tox to do everything but actually running the # test. From be08d4b1291566a330c357771ec9ccd96d819af8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 02:35:58 -0400 Subject: [PATCH 1142/2280] replace unichr with six.unichr in lyrics plugin --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index fe833e6c1..4cc8cb441 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -84,7 +84,7 @@ def unescape(text): def replchar(m): num = m.group(1) - return unichr(int(num)) + return six.unichr(int(num)) out = re.sub(u"&#(\d+);", replchar, out) return out From ce8d1c0c2849bba6dd24bb3d4eaa9eaf547a08d0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 02:42:29 -0400 Subject: [PATCH 1143/2280] ignore undefined name (F821) warning for buffer --- beets/library.py | 2 +- beets/util/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 1d63da2c7..18764b6f0 100644 --- a/beets/library.py +++ b/beets/library.py @@ -40,7 +40,7 @@ import beets # `memoryview`, depending on the Python version, tells it that we # actually mean non-text data. if six.PY2: - BLOB_TYPE = buffer + BLOB_TYPE = buffer # noqa ignore=F821 else: BLOB_TYPE = memoryview diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 0715459af..fec6d56db 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -654,7 +654,7 @@ def as_string(value): """ buffer_types = memoryview if six.PY2: - buffer_types = (buffer, memoryview) + buffer_types = (buffer, memoryview) # noqa ignore=F821 if value is None: return u'' From 915ec595009f5c0c89902770b1b4cde9fa74a6e1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 04:53:14 -0400 Subject: [PATCH 1144/2280] bytestringify path from tempfile name in fetchart --- beets/util/artresizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 820bc4ed1..3366ec4e4 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -53,7 +53,7 @@ def temp_file_for(path): """ ext = os.path.splitext(path)[1] with NamedTemporaryFile(suffix=ext, delete=False) as f: - return f.name + return util.bytestring_path(f.name) def pil_resize(maxwidth, path_in, path_out=None): From 527b51147e368c1df043c57697826e255a9fa45a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 04:53:57 -0400 Subject: [PATCH 1145/2280] add py3_path to NamedTemporaryFile suffixes --- beets/util/artresizer.py | 2 +- beetsplug/fetchart.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 3366ec4e4..e15ada3af 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -52,7 +52,7 @@ def temp_file_for(path): specified path. """ ext = os.path.splitext(path)[1] - with NamedTemporaryFile(suffix=ext, delete=False) as f: + with NamedTemporaryFile(suffix=util.py3_path(ext), delete=False) as f: return util.bytestring_path(f.name) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 6c7984845..aaa18dd02 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -32,7 +32,7 @@ from beets import config from beets.mediafile import _image_mime_type from beets.util.artresizer import ArtResizer from beets.util import confit -from beets.util import syspath, bytestring_path +from beets.util import syspath, bytestring_path, py3_path import six try: @@ -270,7 +270,8 @@ class RemoteArtSource(ArtSource): u'to {}', ct, real_ct, ext) - with NamedTemporaryFile(suffix=ext, delete=False) as fh: + suffix = py3_path(ext) + with NamedTemporaryFile(suffix=suffix, delete=False) as fh: # write the first already loaded part of the image fh.write(header) # download the remaining part of the image From 093d6ecea21c947ec4631243a9613f59bc848262 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 2 Jul 2016 10:07:36 -0700 Subject: [PATCH 1146/2280] Clean up changelog errors --- docs/changelog.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8ac73257b..f36c2f5fb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,13 +13,14 @@ Some dependency notes for packagers: New features: -* :doc:`/plugins/web`: Added an option to show the items of an album and a - 'path' tag to the json outpu of a file which shows the relative path to the - file. :bug:`2050` +* :doc:`/plugins/web`: Added an ``expand`` option to show the items of an + album and a ``path`` field to the JSON output of a file which shows the + filled-out path template for each file. :bug:`2050` Fixes: -* :doc:`/plugins/web`: Normalized the json output +* :doc:`/plugins/web`: The JSON output is no longer pretty-printed (for a + space savings). :bug:`2050` * :doc:`/plugins/permissions`: Fix a regression in the previous release where the plugin would always fail to set permissions (and log a warning). :bug:`2089` From 40ab3f2992ce6afb6499d918d8b900603cdb6b3f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 2 Jul 2016 10:09:50 -0700 Subject: [PATCH 1147/2280] Disable PyPI download badge PyPI has disabled its download statistics tracking: https://github.com/pypa/pypi-legacy/issues/396 So this badge was just saying "0 downloads." :cry: --- README.rst | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.rst b/README.rst index 5224a6f71..8172a1b9b 100644 --- a/README.rst +++ b/README.rst @@ -1,9 +1,6 @@ .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets -.. image:: https://img.shields.io/pypi/dw/beets.svg - :target: https://pypi.python.org/pypi/beets#downloads - .. image:: http://img.shields.io/codecov/c/github/beetbox/beets.svg :target: https://codecov.io/github/beetbox/beets From b49d3344d4f4dbe94eb758f7b598358a0f536ec1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 2 Jul 2016 10:11:31 -0700 Subject: [PATCH 1148/2280] Next release version is 1.4.0, not 1.3.20 It's time for a minor version bump with our six dependency and "experimental" Python 3 support. --- beets/__init__.py | 2 +- docs/changelog.rst | 4 ++-- docs/conf.py | 4 ++-- setup.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index d5d2eca4d..4b86c8419 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.3.20' +__version__ = u'1.4.0' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index f36c2f5fb..6b8ef0f3c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.3.20 (in development) ------------------------ +1.4.0 (in development) +---------------------- Some dependency notes for packagers: diff --git a/docs/conf.py b/docs/conf.py index 2b181a580..6cddd74c0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,8 +15,8 @@ master_doc = 'index' project = u'beets' copyright = u'2016, Adrian Sampson' -version = '1.3' -release = '1.3.20' +version = '1.4' +release = '1.4.0' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 2cca0498d..41b2fe8cc 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.3.20', + version='1.4.0', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From d6c62d08c4d65501c1542ac1d29def9f099b5d60 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 2 Jul 2016 10:17:53 -0700 Subject: [PATCH 1149/2280] Fill out changelog with prose summary --- docs/changelog.rst | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 6b8ef0f3c..efb6cc260 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,20 +4,27 @@ Changelog 1.4.0 (in development) ---------------------- -Some dependency notes for packagers: +Version 1.4 is our first step toward supporting Python 3 in addition to Python +2. We're not quite there yet, but thanks mainly to the heroic efforts of +:user:`jrobeson`, we're on our way. A few basic commands work now, and we're +working to bring full support over the next few releases. -* This version of beets now depends on the `six`_ library. This is our first - step toward supporting Python 3. +Specifically, if you package beets for distribution, here's what you'll want +to know: + +* This version of beets now depends on the `six`_ library. * We also bumped our minimum required version of `Mutagen`_ to 1.31 (from 1.27). +* Please don't package beets as a Python 3 application *yet*, even though some + things may appear to work under Python 3.4 and later. -New features: +There's a small new feature: * :doc:`/plugins/web`: Added an ``expand`` option to show the items of an album and a ``path`` field to the JSON output of a file which shows the filled-out path template for each file. :bug:`2050` -Fixes: +And there are a few bug fixes too: * :doc:`/plugins/web`: The JSON output is no longer pretty-printed (for a space savings). :bug:`2050` From 81887ed81706ef6ea936f58975d5c43806b07a94 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 22:53:23 -0400 Subject: [PATCH 1150/2280] don't require enum34 on python < 3.4 --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 41b2fe8cc..90224f949 100755 --- a/setup.py +++ b/setup.py @@ -94,7 +94,8 @@ setup( 'musicbrainzngs>=0.4', 'pyyaml', 'jellyfish', - ] + (['colorama'] if (sys.platform == 'win32') else []), + ] + (['colorama'] if (sys.platform == 'win32') else []) + + (['enum34>=1.0.4'] if sys.version_info < (3, 4, 0) else []), tests_require=[ 'beautifulsoup4', From f149bc39b09ee607313bea5f922593b407f1a9a9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 18:27:29 -0400 Subject: [PATCH 1151/2280] Add appveyor skip as an alias for skip appveyor Strangely while both "ci skip" and "skip ci" are supported (with brackets) only "skip appveyor" is supported by default --- appveyor.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index fef39faf2..cd40e6e82 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,6 +1,9 @@ version: "{build}" build: off deploy: off +skip_commits: + # add [appveyor skip] as an alias for [skip appveyor] (like [ci skip]) + message: /\[appveyor skip\]/ environment: # Undocumented feature of nose-show-skipped. From 6f5e08a0bb16d94f76d8ca3d508a2ad3d047456c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 17:24:10 -0400 Subject: [PATCH 1152/2280] switch travis env to trusty tahir (14.04) [skip appveyor] --- .travis.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d8d176dec..5d48e88d5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ +dist: trusty +sudo: required language: python -sudo: false env: global: @@ -29,6 +30,9 @@ matrix: # Non-Python dependencies. addons: apt: + sources: + - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty multiverse" + - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty-updates multiverse" packages: - bash-completion - mp3gain From d2045d7ce531eff5be9a261e59a2a96697276e66 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 18:45:08 -0400 Subject: [PATCH 1153/2280] add imagemagick package [skip appveyor] --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 5d48e88d5..89097b937 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,6 +35,7 @@ addons: - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty-updates multiverse" packages: - bash-completion + - imagemagick - mp3gain - unrar From 35d0e81949255fc6372d3e4c89370b6bd475eae8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 22:24:21 -0400 Subject: [PATCH 1154/2280] add missing bytestring_paths for python -bb --- beets/ui/__init__.py | 2 +- test/test_ui.py | 40 ++++++++++++++++++++++++++-------------- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ba342f12c..e338e46df 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1208,7 +1208,7 @@ def _configure(options): def _open_library(config): """Create a new library instance from the configuration. """ - dbpath = config['library'].as_filename() + dbpath = util.bytestring_path(config['library'].as_filename()) try: lib = library.Library( dbpath, diff --git a/test/test_ui.py b/test/test_ui.py index 3e29c180a..365b40923 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -845,11 +845,11 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ui._raw_main(['--config', cli_config_path, 'test']) self.assert_equal_path( - config['library'].as_filename(), + util.bytestring_path(config['library'].as_filename()), os.path.join(self.user_config_dir, b'beets.db') ) self.assert_equal_path( - config['statefile'].as_filename(), + util.bytestring_path(config['statefile'].as_filename()), os.path.join(self.user_config_dir, b'state') ) @@ -862,10 +862,14 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): file.write('statefile: state') ui._raw_main(['--config', cli_config_path, 'test']) - self.assert_equal_path(config['library'].as_filename(), - os.path.join(self.beetsdir, b'beets.db')) - self.assert_equal_path(config['statefile'].as_filename(), - os.path.join(self.beetsdir, b'state')) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'beets.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state') + ) def test_command_line_option_relative_to_working_dir(self): os.chdir(self.temp_dir) @@ -911,10 +915,14 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) config.read() - self.assert_equal_path(config['library'].as_filename(), - os.path.join(self.beetsdir, b'library.db')) - self.assert_equal_path(config['statefile'].as_filename(), - os.path.join(self.beetsdir, b'state.pickle')) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'library.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state.pickle') + ) def test_beetsdir_config_paths_resolve_relative_to_beetsdir(self): os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) @@ -925,10 +933,14 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): file.write('statefile: state') config.read() - self.assert_equal_path(config['library'].as_filename(), - os.path.join(self.beetsdir, b'beets.db')) - self.assert_equal_path(config['statefile'].as_filename(), - os.path.join(self.beetsdir, b'state')) + self.assert_equal_path( + util.bytestring_path(config['library'].as_filename()), + os.path.join(self.beetsdir, b'beets.db') + ) + self.assert_equal_path( + util.bytestring_path(config['statefile'].as_filename()), + os.path.join(self.beetsdir, b'state') + ) class ShowModelChangeTest(_common.TestCase): From 8c1e9e0dd48137e5a13006f87e178abc1f489aa7 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 23:47:34 -0400 Subject: [PATCH 1155/2280] add missing displayable_paths to satisify python -bb --- test/test_convert.py | 19 ++++++++++++++----- test/test_embedart.py | 6 +++--- test/test_permissions.py | 11 ++++++++--- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/test/test_convert.py b/test/test_convert.py index d3a1206be..1f1b1a7fb 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -44,26 +44,35 @@ class TestHelper(helper.TestHelper): def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. """ + display_tag = tag tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), - u'{0} is not a file'.format(path)) + u'{0} is not a file'.format( + util.displayable_path(path))) with open(path, 'rb') as f: - f.seek(-len(tag), os.SEEK_END) + f.seek(-len(display_tag), os.SEEK_END) self.assertEqual(f.read(), tag, - u'{0} is not tagged with {1}'.format(path, tag)) + u'{0} is not tagged with {1}' + .format( + util.displayable_path(path), + display_tag)) def assertNoFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content does not end with `tag`. """ + display_tag = tag tag = tag.encode('utf-8') self.assertTrue(os.path.isfile(path), - u'{0} is not a file'.format(path)) + u'{0} is not a file'.format( + util.displayable_path(path))) with open(path, 'rb') as f: f.seek(-len(tag), os.SEEK_END) self.assertNotEqual(f.read(), tag, u'{0} is unexpectedly tagged with {1}' - .format(path, tag)) + .format( + util.displayable_path(path), + display_tag)) @_common.slow_test() diff --git a/test/test_embedart.py b/test/test_embedart.py index 2f47e8f25..4ba5c3424 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -26,7 +26,7 @@ from test.helper import TestHelper from beets.mediafile import MediaFile from beets import config, logging, ui -from beets.util import syspath +from beets.util import syspath, displayable_path from beets.util.artresizer import ArtResizer from beets import art @@ -136,7 +136,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.assertEqual(mediafile.images[0].data, self.image_data, u'Image written is not {0}'.format( - self.abbey_artpath)) + displayable_path(self.abbey_artpath))) @require_artresizer_compare def test_accept_similar_art(self): @@ -150,7 +150,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.assertEqual(mediafile.images[0].data, self.image_data, u'Image written is not {0}'.format( - self.abbey_similarpath)) + displayable_path(self.abbey_similarpath))) def test_non_ascii_album_path(self): resource_path = os.path.join(_common.RSRC, b'image.mp3') diff --git a/test/test_permissions.py b/test/test_permissions.py index 7234ec30d..040839110 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -10,6 +10,7 @@ from mock import patch, Mock from test._common import unittest from test.helper import TestHelper +from beets.util import displayable_path from beetsplug.permissions import (check_permissions, convert_perm, dirs_in_library) @@ -67,9 +68,13 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper): def assertPerms(self, path, typ, expect_success): # noqa for x in [(True, self.exp_perms[expect_success][typ], '!='), (False, self.exp_perms[not expect_success][typ], '==')]: - self.assertEqual(x[0], check_permissions(path, x[1]), - msg=u'{} : {} {} {}'.format( - path, oct(os.stat(path).st_mode), x[2], oct(x[1]))) + msg = u'{} : {} {} {}'.format( + displayable_path(path), + oct(os.stat(path).st_mode), + x[2], + oct(x[1]) + ) + self.assertEqual(x[0], check_permissions(path, x[1]), msg=msg) def test_convert_perm_from_string(self): self.assertEqual(convert_perm('10'), 8) From b9cd889ef47f6f7311ebd5a3a1a93a20dcc106b1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 3 Jul 2016 23:48:19 -0400 Subject: [PATCH 1156/2280] decode ipfs item paths to satisy python -bb --- beetsplug/ipfs.py | 6 ++++-- test/test_ipfs.py | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/beetsplug/ipfs.py b/beetsplug/ipfs.py index 87a100b14..9a9d6aa50 100644 --- a/beetsplug/ipfs.py +++ b/beetsplug/ipfs.py @@ -272,9 +272,11 @@ class IPFSPlugin(BeetsPlugin): break except AttributeError: pass + item_path = os.path.basename(item.path).decode( + util._fsencoding(), 'ignore' + ) # Clear current path from item - item.path = '/ipfs/{0}/{1}'.format(album.ipfs, - os.path.basename(item.path)) + item.path = '/ipfs/{0}/{1}'.format(album.ipfs, item_path) item.id = None items.append(item) diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 61f10dc92..228575fd8 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -17,7 +17,7 @@ from __future__ import division, absolute_import, print_function from mock import patch from beets import library -from beets.util import bytestring_path +from beets.util import bytestring_path, _fsencoding from beetsplug.ipfs import IPFSPlugin from test import _common @@ -51,9 +51,11 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): for check_item in added_album.items(): try: if check_item.ipfs: + ipfs_item = os.path.basename(want_item.path).decode( + _fsencoding(), + ) want_path = '/ipfs/{0}/{1}'.format(test_album.ipfs, - os.path.basename( - want_item.path)) + ipfs_item) want_path = bytestring_path(want_path) self.assertEqual(check_item.path, want_path) self.assertEqual(check_item.ipfs, want_item.ipfs) From 00bff817564da7d0561101ffa1c39b593a305228 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 02:24:32 -0400 Subject: [PATCH 1157/2280] add a flush() method to test DummyOut The method just runs `self.clear()` --- test/_common.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/_common.py b/test/_common.py index 2c4fe1f24..12a3d479e 100644 --- a/test/_common.py +++ b/test/_common.py @@ -262,6 +262,9 @@ class DummyOut(object): else: return ''.join(self.buf) + def flush(self): + self.clear() + def clear(self): self.buf = [] From a15ae96616e11edb17f5c7cd47d529dfd0b2f298 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 02:48:54 -0400 Subject: [PATCH 1158/2280] add a missing text_string in play plugin I don't think wanna send the cli args as bytes to the logger --- beetsplug/play.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 409ac46f9..7d5b4c227 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -138,7 +138,7 @@ class PlayPlugin(BeetsPlugin): open_args = [self._create_tmp_playlist(paths)] self._log.debug(u'executing command: {} {}', command_str, - b' '.join(open_args)) + util.text_string(b' '.join(open_args))) try: util.interactive_open(open_args, command_str) except OSError as exc: From e434074bf078e8bde63ad640831172c62e63d546 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 02:57:00 -0400 Subject: [PATCH 1159/2280] reorganize tox.ini so we can pass -bb to our 3.x tests It's done this way so the tests don't run twice on py 3.x tests Thanks to @jackwilsdon for the tip! --- tox.ini | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index f0cc77b04..88fc6e409 100644 --- a/tox.ini +++ b/tox.ini @@ -39,8 +39,10 @@ deps = {test,cov}: {[_test]deps} py{27,34}-flake8: {[_flake8]deps} commands = - cov: nosetests --with-coverage {posargs} - test: nosetests {posargs} + py27-cov: nosetests --with-coverage {posargs} + py27-test: nosetests {posargs} + py{34,35}-cov: python -bb -m nose --with-coverage {posargs} + py{34,35}-test: python -bb -m nose {posargs} py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} py34-flake8: flake8 --min-version 3.4 {posargs} {[_flake8]files} From b564683d59b2fc93b0213cb70cbd401a46cc79ad Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 03:00:28 -0400 Subject: [PATCH 1160/2280] use -m nose for tests on python 2.x too --- tox.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 88fc6e409..f17abd9ae 100644 --- a/tox.ini +++ b/tox.ini @@ -39,8 +39,8 @@ deps = {test,cov}: {[_test]deps} py{27,34}-flake8: {[_flake8]deps} commands = - py27-cov: nosetests --with-coverage {posargs} - py27-test: nosetests {posargs} + py27-cov: python -m nose --with-coverage {posargs} + py27-test: python -m nose {posargs} py{34,35}-cov: python -bb -m nose --with-coverage {posargs} py{34,35}-test: python -bb -m nose {posargs} py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} From 0290c9eadb2719ea60de863418958bfe627eba55 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 16:15:56 -0400 Subject: [PATCH 1161/2280] actually remove unconditional enum34 from setup.py --- setup.py | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.py b/setup.py index 90224f949..149da2ffe 100755 --- a/setup.py +++ b/setup.py @@ -87,7 +87,6 @@ setup( install_requires=[ 'six', - 'enum34>=1.0.4', 'mutagen>=1.31', 'munkres', 'unidecode', From cae6e128e4376546cae2d53d2751565b4262cda8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 5 Jul 2016 01:28:39 -0400 Subject: [PATCH 1162/2280] use same symlink test in mediafile_edge as elsewhere --- test/test_mediafile_edge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index c95556820..173a0d063 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -188,7 +188,7 @@ class SafetyTest(unittest.TestCase, TestHelper): self._exccheck(b'nothing.xml', beets.mediafile.UnreadableFileError, "ftyp") - @unittest.skipIf(not hasattr(os, 'symlink'), u'platform lacks symlink') + @unittest.skipUnless(_common.HAVE_SYMLINK, u'platform lacks symlink') def test_broken_symlink(self): fn = os.path.join(_common.RSRC, b'brokenlink') os.symlink('does_not_exist', fn) From 53d1dc905f35f2bea5f4aaf4af9491e1726e442a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 4 Jul 2016 21:53:34 -0400 Subject: [PATCH 1163/2280] add a missing bytestring_path in importer test --- test/test_importer.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test_importer.py b/test/test_importer.py index b879290ad..29487ec26 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -348,7 +348,10 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): ) self.assertExists(filename) self.assertTrue(os.path.islink(filename)) - self.assert_equal_path(os.readlink(filename), mediafile.path) + self.assert_equal_path( + util.bytestring_path(os.readlink(filename)), + mediafile.path + ) def create_archive(session): From fa3fe86ac1e07506cfb51de937c1c18070baa634 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 5 Jul 2016 02:06:13 -0400 Subject: [PATCH 1164/2280] remove bytes() wrap from test helper fixture It was already bytes, so this was redundant. It also broke the tests on windows with py3. --- test/helper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helper.py b/test/helper.py index 3f187d76e..ae6dc4fbd 100644 --- a/test/helper.py +++ b/test/helper.py @@ -366,7 +366,7 @@ class TestHelper(object): items = [] path = os.path.join(_common.RSRC, util.bytestring_path('full.' + ext)) for i in range(track_count): - item = Item.from_path(bytes(path)) + item = Item.from_path(path) item.album = u'\u00e4lbum' # Check unicode paths item.title = u't\u00eftle {0}'.format(i) item.add(self.lib) From 3aa5682a77a7e1530c60f6d5bdf836d6c85b24ca Mon Sep 17 00:00:00 2001 From: Wieland Hoffmann Date: Tue, 5 Jul 2016 20:25:00 +0200 Subject: [PATCH 1165/2280] chmod -x plugins.py --- beets/plugins.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 beets/plugins.py diff --git a/beets/plugins.py b/beets/plugins.py old mode 100755 new mode 100644 From 49f59115cb824e65665a1d582796a1454012cd07 Mon Sep 17 00:00:00 2001 From: Wieland Hoffmann Date: Tue, 5 Jul 2016 20:29:35 +0200 Subject: [PATCH 1166/2280] chmod -x image_unknown_type.mp3 --- test/rsrc/image_unknown_type.mp3 | Bin 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 test/rsrc/image_unknown_type.mp3 diff --git a/test/rsrc/image_unknown_type.mp3 b/test/rsrc/image_unknown_type.mp3 old mode 100755 new mode 100644 From b5d22ec7b8404611d868e9a149c1b9bd46f2fc1a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 5 Jul 2016 22:28:48 -0400 Subject: [PATCH 1167/2280] don't install pathlib on py 2.7 Fixes #2105 --- setup.py | 3 ++- tox.ini | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 149da2ffe..9ab145e5d 100755 --- a/setup.py +++ b/setup.py @@ -118,7 +118,8 @@ setup( 'mpdstats': ['python-mpd2'], 'web': ['flask', 'flask-cors'], 'import': ['rarfile'], - 'thumbnails': ['pathlib', 'pyxdg'], + 'thumbnails': ['pyxdg'] + + (['pathlib'] if (sys.version_info < (3, 4, 0)) else []), 'metasync': ['dbus-python'], }, # Non-Python/non-PyPI plugin dependencies: diff --git a/tox.ini b/tox.ini index f17abd9ae..81eacf16a 100644 --- a/tox.ini +++ b/tox.ini @@ -19,7 +19,6 @@ deps = pylast rarfile responses>=0.3.0 - pathlib pyxdg jellyfish python-mpd2 @@ -37,6 +36,7 @@ passenv = NOSE_SHOW_SKIPPED # Undocumented feature of nose-show-skipped. deps = {test,cov}: {[_test]deps} + py27: pathlib py{27,34}-flake8: {[_flake8]deps} commands = py27-cov: python -m nose --with-coverage {posargs} From 3710c139fb4cafe2db93c60ba05b134be90fe807 Mon Sep 17 00:00:00 2001 From: Rob McGhee Date: Wed, 6 Jul 2016 19:42:57 +0100 Subject: [PATCH 1168/2280] Emby API Key Add the option to read an API Key from the config file and submit that instead of needing a password. Doesn't remove the use of password so is backwards compatible with users current config file --- beetsplug/embyupdate.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 73fa3dcc3..b9adde36a 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -104,24 +104,26 @@ class EmbyUpdate(BeetsPlugin): port = config['emby']['port'].get() username = config['emby']['username'].get() password = config['emby']['password'].get() + token = config['emby']['apikey'].get() # Get user information from the Emby API. user = get_user(host, port, username) if not user: self._log.warning(u'User {0} could not be found.'.format(username)) return + + if not token: + # Create Authentication data and headers. + auth_data = password_data(username, password) + headers = create_headers(user[0]['Id']) - # Create Authentication data and headers. - auth_data = password_data(username, password) - headers = create_headers(user[0]['Id']) - - # Get authentication token. - token = get_token(host, port, headers, auth_data) - if not token: - self._log.warning( - u'Could not get token for user {0}', username - ) - return + # Get authentication token. + token = get_token(host, port, headers, auth_data) + if not token: + self._log.warning( + u'Could not get token for user {0}', username + ) + return # Recreate headers with a token. headers = create_headers(user[0]['Id'], token=token) From 1119e219b3644acca9cc241425dbbc5bd7f62e38 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 03:39:53 -0400 Subject: [PATCH 1169/2280] adjust bytestring treatment of ext in convert plugin --- beetsplug/convert.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 14f3f3452..4eb8a1be3 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -47,7 +47,7 @@ def replace_ext(path, ext): The new extension must not contain a leading dot. """ - ext_dot = util.bytestring_path('.' + ext) + ext_dot = b'.' + ext return os.path.splitext(path)[0] + ext_dot @@ -68,7 +68,7 @@ def get_format(fmt=None): .format(fmt) ) except ConfigTypeError: - command = config['convert']['formats'][fmt].get(bytes) + command = config['convert']['formats'][fmt].get(str) extension = fmt # Convenience and backwards-compatibility shortcuts. @@ -428,7 +428,7 @@ class ConvertPlugin(BeetsPlugin): # Create a temporary file for the conversion. tmpdir = self.config['tmpdir'].get() - fd, dest = tempfile.mkstemp('.' + ext, dir=tmpdir) + fd, dest = tempfile.mkstemp(b'.' + ext, dir=tmpdir) os.close(fd) dest = util.bytestring_path(dest) _temp_files.append(dest) # Delete the transcode later. From c9c37a8f79509eae63411f1a6fe47e458f3198bc Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 03:40:26 -0400 Subject: [PATCH 1170/2280] adding missing b' to command name checks in replaygain --- beetsplug/replaygain.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index e25f1a045..cae55f5b5 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -308,9 +308,9 @@ class CommandBackend(Backend): def format_supported(self, item): """Checks whether the given item is supported by the selected tool. """ - if 'mp3gain' in self.command and item.format != 'MP3': + if b'mp3gain' in self.command and item.format != 'MP3': return False - elif 'aacgain' in self.command and item.format not in ('MP3', 'AAC'): + elif b'aacgain' in self.command and item.format not in ('MP3', 'AAC'): return False return True From a221a120c4ede3051ee00eb95ac8f9d704773647 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 03:41:53 -0400 Subject: [PATCH 1171/2280] fix keyfinder command name comparison in test --- test/test_keyfinder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 00952fe14..a9b1ae085 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -46,7 +46,7 @@ class KeyFinderTest(unittest.TestCase, TestHelper): item.load() self.assertEqual(item['initial_key'], 'C#m') self.command_output.assert_called_with( - ['KeyFinder', '-f', util.syspath(item.path)]) + [b'KeyFinder', b'-f', util.syspath(item.path)]) def test_add_key_on_import(self): self.command_output.return_value = 'dbm' From bb15829b17a57bf8be2f8cb68db765eff9185d34 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 03:42:43 -0400 Subject: [PATCH 1172/2280] add missing b' to config.yaml files in ui tests I'd not gotten around to doing this because of other py3 test issues, but here we go now! --- test/test_ui.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 365b40923..94594d9f7 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -774,7 +774,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): ]) def test_cli_config_option(self): - config_path = os.path.join(self.temp_dir, 'config.yaml') + config_path = os.path.join(self.temp_dir, b'config.yaml') with open(config_path, 'w') as file: file.write('anoption: value') @@ -785,7 +785,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): with open(self.user_config_path, 'w') as file: file.write('anoption: value') - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') @@ -798,7 +798,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): with open(env_config_path, 'w') as file: file.write('anoption: value') - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') @@ -807,8 +807,8 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # @unittest.skip('Difficult to implement with optparse') # def test_multiple_cli_config_files(self): -# cli_config_path_1 = os.path.join(self.temp_dir, 'config.yaml') -# cli_config_path_2 = os.path.join(self.temp_dir, 'config_2.yaml') +# cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') +# cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') # # with open(cli_config_path_1, 'w') as file: # file.write('first: value') @@ -823,9 +823,9 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # # @unittest.skip('Difficult to implement with optparse') # def test_multiple_cli_config_overwrite(self): -# cli_config_path = os.path.join(self.temp_dir, 'config.yaml') +# cli_config_path = os.path.join(self.temp_dir, b'config.yaml') # cli_overwrite_config_path = os.path.join(self.temp_dir, -# 'overwrite_config.yaml') +# b'overwrite_config.yaml') # # with open(cli_config_path, 'w') as file: # file.write('anoption: value') @@ -838,7 +838,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_paths_resolve_relative_to_user_dir(self): - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') @@ -856,7 +856,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def test_cli_config_paths_resolve_relative_to_beetsdir(self): os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('library: beets.db\n') file.write('statefile: state') @@ -878,7 +878,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): os.path.join(os.getcwd(), 'foo.db')) def test_cli_config_file_loads_plugin_commands(self): - cli_config_path = os.path.join(self.temp_dir, 'config.yaml') + cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('pluginpath: %s\n' % _common.PLUGINPATH) file.write('plugins: test') From 2dad86291e35c05e3739c867187d6c9b2026727e Mon Sep 17 00:00:00 2001 From: Rob McGhee Date: Thu, 7 Jul 2016 22:46:33 +0100 Subject: [PATCH 1173/2280] Emby API Key Corrected the use of spaces rather than tabs. Add the option to use an Emby API key to authenticate rather than a password --- beetsplug/embyupdate.py | 26 +++++++++++++------------- docs/changelog.rst | 5 +++++ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index b9adde36a..2a2f792f5 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -104,26 +104,26 @@ class EmbyUpdate(BeetsPlugin): port = config['emby']['port'].get() username = config['emby']['username'].get() password = config['emby']['password'].get() - token = config['emby']['apikey'].get() + token = config['emby']['apikey'].get() # Get user information from the Emby API. user = get_user(host, port, username) if not user: self._log.warning(u'User {0} could not be found.'.format(username)) return - - if not token: - # Create Authentication data and headers. - auth_data = password_data(username, password) - headers = create_headers(user[0]['Id']) - # Get authentication token. - token = get_token(host, port, headers, auth_data) - if not token: - self._log.warning( - u'Could not get token for user {0}', username - ) - return + if not token: + # Create Authentication data and headers. + auth_data = password_data(username, password) + headers = create_headers(user[0]['Id']) + + # Get authentication token. + token = get_token(host, port, headers, auth_data) + if not token: + self._log.warning( + u'Could not get token for user {0}', username + ) + return # Recreate headers with a token. headers = create_headers(user[0]['Id'], token=token) diff --git a/docs/changelog.rst b/docs/changelog.rst index efb6cc260..82172f545 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,11 @@ Changelog ========= +* :doc:`/plugins/embyupdate`: Use the option of Emby's API Key's rather than + a password. Add an apikey to your config file for this to work. Does not + break the use of password as an authentication method + + 1.4.0 (in development) ---------------------- From cb6efc4c225416a9951c09237b1fbb547147bb34 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 8 Jul 2016 05:48:26 -0400 Subject: [PATCH 1174/2280] Reorganize Gst import and version req in bpd This avoids ```sh PyGIWarning: Gst was imported without specifying a version first. Use gi.require_version('Gst', '1.0') before import to ensure that the right version gets loaded. ``` by silencing E401 import ordering warning --- beetsplug/bpd/gstplayer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 8fa0f7a81..6972a2722 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -29,9 +29,9 @@ from six.moves import urllib from beets import ui import gi -from gi.repository import GLib, Gst - gi.require_version('Gst', '1.0') +from gi.repository import GLib, Gst # noqa ignore=E402 + Gst.init(None) From 3db81a3345913dc32d34f038d0f8fee35b64fbcf Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 9 Jul 2016 03:50:16 -0400 Subject: [PATCH 1175/2280] bytestringify tmpdir in convert plugin This works fine in py 3.5, but not 3.4 --- beetsplug/convert.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 4eb8a1be3..4c64b8a2e 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -428,6 +428,7 @@ class ConvertPlugin(BeetsPlugin): # Create a temporary file for the conversion. tmpdir = self.config['tmpdir'].get() + tmpdir = util.bytestring_path(tmpdir) if tmpdir else None fd, dest = tempfile.mkstemp(b'.' + ext, dir=tmpdir) os.close(fd) dest = util.bytestring_path(dest) From 17883bc501beb7731780063abb934d0f2d60ce2f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 9 Jul 2016 22:44:26 -0400 Subject: [PATCH 1176/2280] replace os.symlink() with util.link() in importfeeds --- beetsplug/importfeeds.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 5e4333f73..18f63a2bd 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -24,7 +24,7 @@ import os import re from beets.plugins import BeetsPlugin -from beets.util import mkdirall, normpath, syspath, bytestring_path +from beets.util import mkdirall, normpath, syspath, bytestring_path, link from beets import config M3U_DEFAULT_NAME = 'imported.m3u' @@ -131,7 +131,7 @@ class ImportFeedsPlugin(BeetsPlugin): for path in paths: dest = os.path.join(feedsdir, os.path.basename(path)) if not os.path.exists(syspath(dest)): - os.symlink(syspath(path), syspath(dest)) + link(path, dest) if 'echo' in formats: self._log.info(u"Location of imported music:") From f9dfd3460219f17e6757872c511e4d1dd9e34007 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 2 Jul 2016 02:02:21 -0400 Subject: [PATCH 1177/2280] use py3_path for archive (ZipFile, etc) filenames ZipFile and RarFile both only accept string filenames on py3, not bytestrings. --- beets/importer.py | 4 ++-- test/test_importer.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index f3272311f..6a1be6ddc 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -944,7 +944,7 @@ class ArchiveImportTask(SentinelImportTask): return False for path_test, _ in cls.handlers(): - if path_test(path): + if path_test(util.py3_path(path)): return True return False @@ -990,7 +990,7 @@ class ArchiveImportTask(SentinelImportTask): try: extract_to = mkdtemp() - archive = handler_class(self.toppath, mode='r') + archive = handler_class(util.py3_path(self.toppath), mode='r') archive.extractall(extract_to) finally: archive.close() diff --git a/test/test_importer.py b/test/test_importer.py index 29487ec26..07b6680ea 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -30,7 +30,7 @@ from mock import patch from test import _common from test._common import unittest -from beets.util import displayable_path, bytestring_path +from beets.util import displayable_path, bytestring_path, py3_path from test.helper import TestImportSession, TestHelper, has_program, capture_log from beets import importer from beets.importer import albums_in_dir @@ -355,9 +355,9 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): def create_archive(session): - (handle, path) = mkstemp(dir=session.temp_dir) + (handle, path) = mkstemp(dir=py3_path(session.temp_dir)) os.close(handle) - archive = ZipFile(path, mode='w') + archive = ZipFile(py3_path(path), mode='w') archive.write(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() @@ -414,7 +414,7 @@ class ImportTarTest(ImportZipTest): def create_archive(self): (handle, path) = mkstemp(dir=self.temp_dir) os.close(handle) - archive = TarFile(path, mode='w') + archive = TarFile(py3_path(path), mode='w') archive.add(os.path.join(_common.RSRC, b'full.mp3'), 'full.mp3') archive.close() From 5107f2e6d2d11cac5fb485ac856a032a54069342 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 10 Jul 2016 04:58:40 -0400 Subject: [PATCH 1178/2280] add missing py3_path to tempdir in convert plugin --- beetsplug/convert.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 4c64b8a2e..4e3556684 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -428,8 +428,9 @@ class ConvertPlugin(BeetsPlugin): # Create a temporary file for the conversion. tmpdir = self.config['tmpdir'].get() - tmpdir = util.bytestring_path(tmpdir) if tmpdir else None - fd, dest = tempfile.mkstemp(b'.' + ext, dir=tmpdir) + if tmpdir: + tmpdir = util.py3_path(util.bytestring_path(tmpdir)) + fd, dest = tempfile.mkstemp(util.py3_path(b'.' + ext), dir=tmpdir) os.close(fd) dest = util.bytestring_path(dest) _temp_files.append(dest) # Delete the transcode later. From f82f5f51a4a5f86d67bd86c9222395f9c377d003 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 10 Jul 2016 06:00:53 -0400 Subject: [PATCH 1179/2280] use !r for command exec logging in play plugin This is a bit simpler and is compatible with py2 and 3. --- beetsplug/play.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 7d5b4c227..27da15b37 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -137,8 +137,7 @@ class PlayPlugin(BeetsPlugin): else: open_args = [self._create_tmp_playlist(paths)] - self._log.debug(u'executing command: {} {}', command_str, - util.text_string(b' '.join(open_args))) + self._log.debug(u'executing command: {} {!r}', command_str, open_args) try: util.interactive_open(open_args, command_str) except OSError as exc: From a1edf1928d334f657415534fa19879d2bfe3a88e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 03:16:09 -0400 Subject: [PATCH 1180/2280] treat bpd command and args as strings, not bytes --- beetsplug/bpd/__init__.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 3aabeb869..5b6a8a9a7 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -640,8 +640,8 @@ class Command(object): """A command issued by the client for processing by the server. """ - command_re = re.compile(br'^([^ \t]+)[ \t]*') - arg_re = re.compile(br'"((?:\\"|[^"])+)"|([^ \t"]+)') + command_re = re.compile(r'^([^ \t]+)[ \t]*') + arg_re = re.compile(r'"((?:\\"|[^"])+)"|([^ \t"]+)') def __init__(self, s): """Creates a new `Command` from the given string, `s`, parsing @@ -656,11 +656,10 @@ class Command(object): if match[0]: # Quoted argument. arg = match[0] - arg = arg.replace(b'\\"', b'"').replace(b'\\\\', b'\\') + arg = arg.replace('\\"', '"').replace('\\\\', '\\') else: # Unquoted argument. arg = match[1] - arg = arg.decode('utf8') self.args.append(arg) def run(self, conn): From 910a1b93f5a2d8e80f84f1a753a5201cef36970b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 5 Jul 2016 02:10:52 -0400 Subject: [PATCH 1181/2280] don't test symlink related functions on Windows They do work, but only with admin privs. Related discussion in #2114 --- test/_common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/_common.py b/test/_common.py index 12a3d479e..cfec6afb1 100644 --- a/test/_common.py +++ b/test/_common.py @@ -53,7 +53,7 @@ log.setLevel(logging.DEBUG) _item_ident = 0 # OS feature test. -HAVE_SYMLINK = hasattr(os, 'symlink') +HAVE_SYMLINK = sys.platform != 'win32' def item(lib=None): From 7e150481b6a56271a4f808034658d6be63eb4d83 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 11 Jul 2016 02:24:07 -0400 Subject: [PATCH 1182/2280] compare test_types plugin test output as strings Since we're using StringIO (and equivalent in DummyIO), we can just use strings here. --- test/test_types_plugin.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 6a3df8051..67e682844 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -48,7 +48,7 @@ class TypesPluginTest(unittest.TestCase, TestHelper): # Match in range out = self.list(u'myint:1..3') - self.assertIn(b'aaa', out) + self.assertIn('aaa', out) def test_album_integer_modify_and_query(self): self.config['types'] = {'myint': u'int'} @@ -64,7 +64,7 @@ class TypesPluginTest(unittest.TestCase, TestHelper): # Match in range out = self.list_album(u'myint:1..3') - self.assertIn(b'aaa', out) + self.assertIn('aaa', out) def test_float_modify_and_query(self): self.config['types'] = {'myfloat': u'float'} @@ -76,7 +76,7 @@ class TypesPluginTest(unittest.TestCase, TestHelper): # Match in range out = self.list(u'myfloat:-10..0') - self.assertIn(b'aaa', out) + self.assertIn('aaa', out) def test_bool_modify_and_query(self): self.config['types'] = {'mybool': u'bool'} From 41fb0d92876eb0ffcf5ce4306678ee60d40ba4e9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 14 Jul 2016 03:23:39 -0400 Subject: [PATCH 1183/2280] Explicitly sort match candidates by distance Python 3 is stricter when sorted values compare equally, so we explictly sort by distance. This fixes #2125 --- beets/autotag/match.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 96057fe9a..1b21f725a 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -327,6 +327,11 @@ def _recommendation(results): return rec +def _sort_candidates(candidates): + """Sort candidates by distance.""" + return sorted(candidates, key=lambda match: match.distance) + + def _add_candidate(items, results, info): """Given a candidate AlbumInfo object, attempt to add the candidate to the output dictionary of AlbumMatch objects. This involves @@ -443,7 +448,7 @@ def tag_album(items, search_artist=None, search_album=None, _add_candidate(items, candidates, info) # Sort and get the recommendation. - candidates = sorted(candidates.values()) + candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) return cur_artist, cur_album, candidates, rec @@ -471,16 +476,16 @@ def tag_item(item, search_artist=None, search_title=None, candidates[track_info.track_id] = \ hooks.TrackMatch(dist, track_info) # If this is a good match, then don't keep searching. - rec = _recommendation(sorted(candidates.values())) + rec = _recommendation(_sort_candidates(candidates.values())) if rec == Recommendation.strong and \ not config['import']['timid']: log.debug(u'Track ID match.') - return sorted(candidates.values()), rec + return _sort_candidates(candidates.values()), rec # If we're searching by ID, don't proceed. if search_ids: if candidates: - return sorted(candidates.values()), rec + return _sort_candidates(candidates.values()), rec else: return [], Recommendation.none @@ -496,6 +501,6 @@ def tag_item(item, search_artist=None, search_title=None, # Sort by distance and return with recommendation. log.debug(u'Found {0} candidates.', len(candidates)) - candidates = sorted(candidates.values()) + candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) return candidates, rec From 18b57ea02260039e76493b2baa4b1a3cefb17f15 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 14 Jul 2016 03:33:29 -0400 Subject: [PATCH 1184/2280] clear argv before running commands in the test suite Fixes #2123 --- test/helper.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/helper.py b/test/helper.py index ae6dc4fbd..93813004b 100644 --- a/test/helper.py +++ b/test/helper.py @@ -422,6 +422,7 @@ class TestHelper(object): # Running beets commands def run_command(self, *args): + sys.argv = ['beet'] # avoid leakage from test suite args if hasattr(self, 'lib'): lib = self.lib else: From 80bb550f45999589cf830c6564951d762627f44d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 15 Jul 2016 03:05:53 -0400 Subject: [PATCH 1185/2280] remove useless format_exc in util.move There isn't a traceback for us to format here, so it errors out on certain versions of python 3 --- beets/util/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index fec6d56db..f6e10463d 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -443,8 +443,7 @@ def move(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if os.path.exists(dest) and not replace: - raise FilesystemError(u'file exists', 'rename', (path, dest), - traceback.format_exc()) + raise FilesystemError(u'file exists', 'rename', (path, dest)) # First, try renaming the file. try: From 22c6d85535c098d2c25ad2fdc3a812767d377b50 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 15 Jul 2016 17:40:48 -0400 Subject: [PATCH 1186/2280] remove tb.format_exc() from util.link replace --- beets/util/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index f6e10463d..44fbdbda7 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -468,8 +468,7 @@ def link(path, dest, replace=False): path = syspath(path) dest = syspath(dest) if os.path.exists(dest) and not replace: - raise FilesystemError(u'file exists', 'rename', (path, dest), - traceback.format_exc()) + raise FilesystemError(u'file exists', 'rename', (path, dest)) try: os.symlink(path, dest) except OSError: From 65e38896ad89e20cababf9a84ebaf365ffaa3071 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 16 Jul 2016 00:22:01 -0400 Subject: [PATCH 1187/2280] except on NotImplementedError in util.link NotImplementedError is raised on python >= 3.2 and Windows versions before Vista. This is one part of the fix for #2114 --- beets/util/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 44fbdbda7..f75c1ac41 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -471,6 +471,10 @@ def link(path, dest, replace=False): raise FilesystemError(u'file exists', 'rename', (path, dest)) try: os.symlink(path, dest) + except NotImplementedError: + # raised on python >= 3.2 and Windows versions before Vista + raise FilesystemError(u'Windows XP does not support symbolic links.' + 'link', (path, dest), traceback.format_exc()) except OSError: raise FilesystemError(u'Operating system does not support symbolic ' u'links.', 'link', (path, dest), From 21dbc9cbab7759e0b82f84164b017c9eee52fe7a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 16 Jul 2016 01:49:11 -0400 Subject: [PATCH 1188/2280] use windows specific language for symlink exceptions This now shows our original OS symlink error when Windows version < 6 (Vista) and also shows any other OS error that might be raised. This fixes #2114 --- beets/util/__init__.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index f75c1ac41..01bd452bc 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -473,11 +473,14 @@ def link(path, dest, replace=False): os.symlink(path, dest) except NotImplementedError: # raised on python >= 3.2 and Windows versions before Vista - raise FilesystemError(u'Windows XP does not support symbolic links.' + raise FilesystemError(u'OS does not support symbolic links.' 'link', (path, dest), traceback.format_exc()) - except OSError: - raise FilesystemError(u'Operating system does not support symbolic ' - u'links.', 'link', (path, dest), + except OSError as exc: + # TODO: Windows version checks can be removed for python 3 + if hasattr('sys', 'getwindowsversion'): + if sys.getwindowsversion()[0] < 6: # is before Vista + exc = u'OS does not support symbolic links.' + raise FilesystemError(exc, 'link', (path, dest), traceback.format_exc()) From 9aeaff0e9aec08b942e6f3fb8d18301e0f022081 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 16 Jul 2016 22:16:04 -0400 Subject: [PATCH 1189/2280] replace py27-flake8 with py34-flake8 We definitely want py34-flake8 to succeed, so we don't end up with `unicode` and other py27 specific. With that in mind, we don't need py27-flake8 anymore either. --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 89097b937..39796cbdc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,14 +17,13 @@ matrix: env: {TOX_ENV: py35-test} # - python: pypy # - env: {TOX_ENV: pypy-test} - - python: 2.7 - env: {TOX_ENV: py27-flake8} - python: 3.4 env: {TOX_ENV: py34-flake8} - python: 2.7 env: {TOX_ENV: docs} allow_failures: - python: 3.4 + env: {TOX_ENV: py34-test} - python: 3.5 # Non-Python dependencies. From 1da919bc40aa430e4f85b71975c1d4a0d021d059 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 17 Jul 2016 05:57:52 -0400 Subject: [PATCH 1190/2280] open lastgenre genres file with codecs.open() This should fix an error when decoding the file on Windows. It defaults to using the code page there and not utf-8 as intended for yaml. --- beetsplug/lastgenre/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index bc3155b94..f901bdaac 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -25,6 +25,7 @@ The scraper script used is available here: https://gist.github.com/1241307 """ import pylast +import codecs import os import yaml import traceback @@ -140,7 +141,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): c14n_filename = C14N_TREE if c14n_filename: c14n_filename = normpath(c14n_filename) - genres_tree = yaml.load(open(c14n_filename, 'r')) + genres_file = codecs.open(c14n_filename, 'r', encoding='utf-8') + genres_tree = yaml.load(genres_file) flatten_tree(genres_tree, [], self.c14n_branches) @property From 2885a189f8a76b61b5817694d475a4d8c6a75d88 Mon Sep 17 00:00:00 2001 From: Jim DeLaHunt Date: Sat, 16 Jul 2016 23:30:31 -0700 Subject: [PATCH 1191/2280] Ignore PyDev and Eclipse project settings. --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 50a0f290c..b93d93305 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,8 @@ ENV/ # Rope project settings .ropeproject + +# PyDev and Eclipse project settings +/.project +/.pydevproject +/.settings From af24277ad39fcf2bfa9dc238ad0e891b30571cb3 Mon Sep 17 00:00:00 2001 From: Rob McGhee Date: Wed, 20 Jul 2016 21:17:45 +0100 Subject: [PATCH 1192/2280] Emby API Key Update Added note to the Emby Plugin Documentation --- docs/plugins/embyupdate.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index 3e4c9687f..f2826040c 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -9,6 +9,7 @@ To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-p host: localhost port: 8096 username: user + apikey: apikey password: password To use the ``embyupdate`` plugin you need to install the `requests`_ library with:: @@ -30,4 +31,5 @@ The available options under the ``emby:`` section are: - **port**: The Emby server port. Default: 8096 - **username**: A username of a Emby user that is allowed to refresh the library. -- **password**: That user's password. +- **apikey**: An Emby API key +- **password**: If no API key is present then enter the user aboves password. From f87486c1fae3ab9d78fd4b39297a421df7ad5543 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 20 Jul 2016 23:32:24 -0400 Subject: [PATCH 1193/2280] pass bytestringed names to fnmatch_all() Due to `syspath`, fnmatch ends up comparing strings to bytes, so we must make sure they are bytes. Fixes #2124 --- beets/util/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 01bd452bc..472f693b6 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -267,7 +267,8 @@ def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')): # Directory gone already. continue clutter = [bytestring_path(c) for c in clutter] - if fnmatch_all(os.listdir(directory), clutter): + match_paths = [bytestring_path(d) for d in os.listdir(directory)] + if fnmatch_all(match_paths, clutter): # Directory contains only clutter (or nothing). try: shutil.rmtree(directory) From efe654269582a5473c1d78ea74dbbaa0d05bab74 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 20 Jul 2016 23:46:36 -0400 Subject: [PATCH 1194/2280] Docs rewording for #2117 (fix #2045) --- docs/changelog.rst | 9 +++------ docs/plugins/embyupdate.rst | 9 ++++++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 82172f545..5b35ba9a3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,11 +1,6 @@ Changelog ========= -* :doc:`/plugins/embyupdate`: Use the option of Emby's API Key's rather than - a password. Add an apikey to your config file for this to work. Does not - break the use of password as an authentication method - - 1.4.0 (in development) ---------------------- @@ -23,11 +18,13 @@ to know: * Please don't package beets as a Python 3 application *yet*, even though some things may appear to work under Python 3.4 and later. -There's a small new feature: +The are a couple of small new features: * :doc:`/plugins/web`: Added an ``expand`` option to show the items of an album and a ``path`` field to the JSON output of a file which shows the filled-out path template for each file. :bug:`2050` +* :doc:`/plugins/embyupdate`: The plugin can now use an API key instead of a + password to authenticate with Emby. :bug:`2045` :bug:`2117` And there are a few bug fixes too: diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index f2826040c..a902e6076 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -10,7 +10,6 @@ To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-p port: 8096 username: user apikey: apikey - password: password To use the ``embyupdate`` plugin you need to install the `requests`_ library with:: @@ -31,5 +30,9 @@ The available options under the ``emby:`` section are: - **port**: The Emby server port. Default: 8096 - **username**: A username of a Emby user that is allowed to refresh the library. -- **apikey**: An Emby API key -- **password**: If no API key is present then enter the user aboves password. +- **apikey**: An Emby API key for the user. +- **password**: The password for the user. (This is only necessary if no API + key is provided.) + +You can choose to authenticate either with `apikey` or `password`, but only +one of those two is required. From e1d1d7b02628d3bf6ed9a5cf15fa11fd7cfbd36b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 21 Jul 2016 01:58:08 -0400 Subject: [PATCH 1195/2280] remove eval-attr for slow tests in setup.cfg The code that relied on this in the tests was removed in https://github.com/beetbox/beets/commit/84c82cc44ba95c57a5cd3da03f07493344c1aaa4 I don't think this was a good global option anyways, so I don't see us returning to it. This was discovered by @JesseWeinstein --- setup.cfg | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 79e453fbc..8050dd345 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,6 @@ [nosetests] verbosity=1 logging-clear-handlers=1 -eval-attr="!=slow" [flake8] min-version=2.7 From 8474ae3f66d6428933148f9e30369dc89b6e1696 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Thu, 21 Jul 2016 23:55:07 -0700 Subject: [PATCH 1196/2280] Fix patcher to always be correctly cleaned up --- test/test_ui.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 94594d9f7..500901ef1 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -24,7 +24,7 @@ import subprocess import platform from copy import deepcopy -from mock import patch +from mock import patch, Mock from test import _common from test._common import unittest from test.helper import capture_stdout, has_program, TestHelper, control_stdin @@ -1065,6 +1065,7 @@ class ShowChangeTest(_common.TestCase): u'caf.mp3 ->' in msg) +@patch('beets.library.Item.try_filesize', Mock(return_value=987)) class SummarizeItemsTest(_common.TestCase): def setUp(self): super(SummarizeItemsTest, self).setUp() @@ -1073,8 +1074,6 @@ class SummarizeItemsTest(_common.TestCase): item.length = 10 * 60 + 54 item.format = "F" self.item = item - fsize_mock = patch('beets.library.Item.try_filesize').start() - fsize_mock.return_value = 987 def test_summarize_item(self): summary = commands.summarize_items([], True) From dca27572aa1dd22462e07edb86d1069d311b3562 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Fri, 22 Jul 2016 23:10:35 -0700 Subject: [PATCH 1197/2280] Convert mock.patch.start() into annotation in test_edit --- test/test_edit.py | 50 ++++++++++++++++++++++------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 5a46ece90..d45bc0a13 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -106,6 +106,7 @@ class EditMixin(object): @_common.slow_test() +@patch('beets.library.Item.write') class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): """Black box tests for `beetsplug.edit`. Command line interaction is simulated using `test.helper.control_stdin()`, and yaml editing via an @@ -123,26 +124,21 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.items_orig = [{f: item[f] for f in item._fields} for item in self.album.items()] - # Keep track of write()s. - self.write_patcher = patch('beets.library.Item.write') - self.mock_write = self.write_patcher.start() - def tearDown(self): EditPlugin.listeners = None - self.write_patcher.stop() self.teardown_beets() self.unload_plugins() - def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa + def assertCounts(self, mock_write, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa write_call_count=TRACK_COUNT, title_starts_with=''): """Several common assertions on Album, Track and call counts.""" self.assertEqual(len(self.lib.albums()), album_count) self.assertEqual(len(self.lib.items()), track_count) - self.assertEqual(self.mock_write.call_count, write_call_count) + self.assertEqual(mock_write.call_count, write_call_count) self.assertTrue(all(i.title.startswith(title_starts_with) for i in self.lib.items())) - def test_title_edit_discard(self): + def test_title_edit_discard(self, m): """Edit title for all items in the library, then discard changes.""" # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': @@ -150,11 +146,11 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Cancel. ['c']) - self.assertCounts(write_call_count=0, + self.assertCounts(m, write_call_count=0, title_starts_with=u't\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, []) - def test_title_edit_apply(self): + def test_title_edit_apply(self, m): """Edit title for all items in the library, then apply changes.""" # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': @@ -162,12 +158,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(write_call_count=self.TRACK_COUNT, + self.assertCounts(m, write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['title']) - def test_single_title_edit_apply(self): + def test_single_title_edit_apply(self, m): """Edit title for one item in the library, then apply changes.""" # Edit one track title. self.run_mocked_command({'replacements': {u't\u00eftle 9': @@ -175,25 +171,25 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(write_call_count=1,) + self.assertCounts(m, write_call_count=1,) # No changes except on last item. self.assertItemFieldsModified(list(self.album.items())[:-1], self.items_orig[:-1], []) self.assertEqual(list(self.album.items())[-1].title, u'modified t\u00eftle 9') - def test_noedit(self): + def test_noedit(self, m): """Do not edit anything.""" # Do not edit anything. self.run_mocked_command({'contents': None}, # No stdin. []) - self.assertCounts(write_call_count=0, + self.assertCounts(m, write_call_count=0, title_starts_with=u't\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, []) - def test_album_edit_apply(self): + def test_album_edit_apply(self, m): """Edit the album field for all items in the library, apply changes. By design, the album should not be updated."" """ @@ -203,14 +199,14 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertCounts(m, write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) # Ensure album is *not* modified. self.album.load() self.assertEqual(self.album.album, u'\u00e4lbum') - def test_single_edit_add_field(self): + def test_single_edit_add_field(self, m): """Edit the yaml file appending an extra field to the first item, then apply changes.""" # Append "foo: bar" to item with id == 1. @@ -220,10 +216,10 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): ['a']) self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar') - self.assertCounts(write_call_count=1, + self.assertCounts(m, write_call_count=1, title_starts_with=u't\u00eftle') - def test_a_album_edit_apply(self): + def test_a_album_edit_apply(self, m): """Album query (-a), edit album field, apply changes.""" self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, @@ -232,12 +228,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): args=['-a']) self.album.load() - self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertCounts(m, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.album, u'modified \u00e4lbum') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) - def test_a_albumartist_edit_apply(self): + def test_a_albumartist_edit_apply(self, m): """Album query (-a), edit albumartist field, apply changes.""" self.run_mocked_command({'replacements': {u'album artist': u'modified album artist'}}, @@ -246,12 +242,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): args=['-a']) self.album.load() - self.assertCounts(write_call_count=self.TRACK_COUNT) + self.assertCounts(m, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.albumartist, u'the modified album artist') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['albumartist']) - def test_malformed_yaml(self): + def test_malformed_yaml(self, m): """Edit the yaml file incorrectly (resulting in a malformed yaml document).""" # Edit the yaml file to an invalid file. @@ -259,10 +255,10 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Edit again to fix? No. ['n']) - self.assertCounts(write_call_count=0, + self.assertCounts(m, write_call_count=0, title_starts_with=u't\u00eftle') - def test_invalid_yaml(self): + def test_invalid_yaml(self, m): """Edit the yaml file incorrectly (resulting in a well-formed but invalid yaml document).""" # Edit the yaml file to an invalid but parseable file. @@ -270,7 +266,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # No stdin. []) - self.assertCounts(write_call_count=0, + self.assertCounts(m, write_call_count=0, title_starts_with=u't\u00eftle') From e5a723b89911301c61f0486075665679aeb0260c Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Fri, 22 Jul 2016 23:35:33 -0700 Subject: [PATCH 1198/2280] Switch test_importer over to use @patch --- test/test_importer.py | 210 +++++++++++++++++++----------------------- 1 file changed, 95 insertions(+), 115 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 07b6680ea..21f3c2601 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -26,7 +26,7 @@ from six import StringIO from tempfile import mkstemp from zipfile import ZipFile from tarfile import TarFile -from mock import patch +from mock import patch, Mock from test import _common from test._common import unittest @@ -1072,7 +1072,7 @@ class InferAlbumDataTest(_common.TestCase): self.assertFalse(self.items[0].comp) -def test_album_info(): +def test_album_info(*args, **kwargs): """Create an AlbumInfo object for testing. """ track_info = TrackInfo( @@ -1087,9 +1087,10 @@ def test_album_info(): album_id=u'albumid', artist_id=u'artistid', ) - return album_info + return iter([album_info]) +@patch('beets.autotag.mb.match_album', Mock(side_effect=test_album_info)) class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, _common.Assertions): @@ -1099,17 +1100,11 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, # Original album self.add_album_fixture(albumartist=u'artist', album=u'album') - # Create duplicate through autotagger - self.match_album_patcher = patch('beets.autotag.mb.match_album') - self.match_album = self.match_album_patcher.start() - self.match_album.return_value = iter([test_album_info()]) - # Create import session self.importer = self.create_importer() config['import']['autotag'] = True def tearDown(self): - self.match_album_patcher.stop() self.teardown_beets() def test_remove_duplicate_album(self): @@ -1179,6 +1174,13 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, return album +def test_track_info(*args, **kwargs): + return iter([TrackInfo( + artist=u'artist', title=u'title', + track_id=u'new trackid', index=0,)]) + + +@patch('beets.autotag.mb.match_track', Mock(side_effect=test_track_info)) class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, _common.Assertions): @@ -1189,24 +1191,12 @@ class ImportDuplicateSingletonTest(unittest.TestCase, TestHelper, self.add_item_fixture(artist=u'artist', title=u'title', mb_trackid='old trackid') - # Create duplicate through autotagger - self.match_track_patcher = patch('beets.autotag.mb.match_track') - self.match_track = self.match_track_patcher.start() - track_info = TrackInfo( - artist=u'artist', - title=u'title', - track_id=u'new trackid', - index=0, - ) - self.match_track.return_value = iter([track_info]) - # Import session self.importer = self.create_importer() config['import']['autotag'] = True config['import']['singletons'] = True def tearDown(self): - self.match_track_patcher.stop() self.teardown_beets() def test_remove_duplicate(self): @@ -1706,100 +1696,6 @@ class ImportPretendTest(_common.TestCase, ImportHelper): self.assertEqual(logs, [u'No files imported from {0}' .format(displayable_path(self.empty_path))]) - -class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): - """Test the --musicbrainzid argument.""" - - MB_RELEASE_PREFIX = 'https://musicbrainz.org/release/' - MB_RECORDING_PREFIX = 'https://musicbrainz.org/recording/' - ID_RELEASE_0 = '00000000-0000-0000-0000-000000000000' - ID_RELEASE_1 = '11111111-1111-1111-1111-111111111111' - ID_RECORDING_0 = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' - ID_RECORDING_1 = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' - - def setUp(self): - self.setup_beets() - self._create_import_dir(1) - - # Patch calls to musicbrainzngs. - self.release_patcher = patch('musicbrainzngs.get_release_by_id', - side_effect=mocked_get_release_by_id) - self.recording_patcher = patch('musicbrainzngs.get_recording_by_id', - side_effect=mocked_get_recording_by_id) - self.release_patcher.start() - self.recording_patcher.start() - - def tearDown(self): - self.recording_patcher.stop() - self.release_patcher.stop() - self.teardown_beets() - - def test_one_mbid_one_album(self): - self.config['import']['search_ids'] = \ - [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0] - self._setup_import_session() - - self.importer.add_choice(importer.action.APPLY) - self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_0') - - def test_several_mbid_one_album(self): - self.config['import']['search_ids'] = \ - [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, - self.MB_RELEASE_PREFIX + self.ID_RELEASE_1] - self._setup_import_session() - - self.importer.add_choice(2) # Pick the 2nd best match (release 1). - self.importer.add_choice(importer.action.APPLY) - self.importer.run() - self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_1') - - def test_one_mbid_one_singleton(self): - self.config['import']['search_ids'] = \ - [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0] - self._setup_import_session(singletons=True) - - self.importer.add_choice(importer.action.APPLY) - self.importer.run() - self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_0') - - def test_several_mbid_one_singleton(self): - self.config['import']['search_ids'] = \ - [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, - self.MB_RECORDING_PREFIX + self.ID_RECORDING_1] - self._setup_import_session(singletons=True) - - self.importer.add_choice(2) # Pick the 2nd best match (recording 1). - self.importer.add_choice(importer.action.APPLY) - self.importer.run() - self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_1') - - def test_candidates_album(self): - """Test directly ImportTask.lookup_candidates().""" - task = importer.ImportTask(paths=self.import_dir, - toppath='top path', - items=[_common.item()]) - task.search_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, - self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, - 'an invalid and discarded id'] - - task.lookup_candidates() - self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), - set([c.info.album for c in task.candidates])) - - def test_candidates_singleton(self): - """Test directly SingletonImportTask.lookup_candidates().""" - task = importer.SingletonImportTask(toppath='top path', - item=_common.item()) - task.search_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, - self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, - 'an invalid and discarded id'] - - task.lookup_candidates() - self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), - set([c.info.title for c in task.candidates])) - - # Helpers for ImportMusicBrainzIdTest. @@ -1870,6 +1766,90 @@ def mocked_get_recording_by_id(id_, includes=[], release_status=[], } +@patch('musicbrainzngs.get_recording_by_id', Mock(side_effect=mocked_get_recording_by_id)) +@patch('musicbrainzngs.get_release_by_id', Mock(side_effect=mocked_get_release_by_id)) +class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): + """Test the --musicbrainzid argument.""" + + MB_RELEASE_PREFIX = 'https://musicbrainz.org/release/' + MB_RECORDING_PREFIX = 'https://musicbrainz.org/recording/' + ID_RELEASE_0 = '00000000-0000-0000-0000-000000000000' + ID_RELEASE_1 = '11111111-1111-1111-1111-111111111111' + ID_RECORDING_0 = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' + ID_RECORDING_1 = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' + + def setUp(self): + self.setup_beets() + self._create_import_dir(1) + + def tearDown(self): + self.teardown_beets() + + def test_one_mbid_one_album(self): + self.config['import']['search_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0] + self._setup_import_session() + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_0') + + def test_several_mbid_one_album(self): + self.config['import']['search_ids'] = \ + [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1] + self._setup_import_session() + + self.importer.add_choice(2) # Pick the 2nd best match (release 1). + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.albums().get().album, 'VALID_RELEASE_1') + + def test_one_mbid_one_singleton(self): + self.config['import']['search_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0] + self._setup_import_session(singletons=True) + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_0') + + def test_several_mbid_one_singleton(self): + self.config['import']['search_ids'] = \ + [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1] + self._setup_import_session(singletons=True) + + self.importer.add_choice(2) # Pick the 2nd best match (recording 1). + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().title, 'VALID_RECORDING_1') + + def test_candidates_album(self): + """Test directly ImportTask.lookup_candidates().""" + task = importer.ImportTask(paths=self.import_dir, + toppath='top path', + items=[_common.item()]) + task.search_ids = [self.MB_RELEASE_PREFIX + self.ID_RELEASE_0, + self.MB_RELEASE_PREFIX + self.ID_RELEASE_1, + 'an invalid and discarded id'] + + task.lookup_candidates() + self.assertEqual(set(['VALID_RELEASE_0', 'VALID_RELEASE_1']), + set([c.info.album for c in task.candidates])) + + def test_candidates_singleton(self): + """Test directly SingletonImportTask.lookup_candidates().""" + task = importer.SingletonImportTask(toppath='top path', + item=_common.item()) + task.search_ids = [self.MB_RECORDING_PREFIX + self.ID_RECORDING_0, + self.MB_RECORDING_PREFIX + self.ID_RECORDING_1, + 'an invalid and discarded id'] + + task.lookup_candidates() + self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), + set([c.info.title for c in task.candidates])) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From d808316b2379590c33d1f3660f810c88188f1a0e Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Fri, 22 Jul 2016 23:51:06 -0700 Subject: [PATCH 1199/2280] Switch over 3 more files --- test/test_ipfs.py | 6 ++--- test/test_keyfinder.py | 22 ++++++++--------- test/test_play.py | 56 ++++++++++++++++++++---------------------- 3 files changed, 39 insertions(+), 45 deletions(-) diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 228575fd8..66d895f2e 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -14,7 +14,7 @@ from __future__ import division, absolute_import, print_function -from mock import patch +from mock import patch, Mock from beets import library from beets.util import bytestring_path, _fsencoding @@ -26,19 +26,17 @@ from test.helper import TestHelper import os +@patch('beets.util.command_output', Mock()) class IPFSPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('ipfs') - self.patcher = patch('beets.util.command_output') - self.command_output = self.patcher.start() self.lib = library.Library(":memory:") def tearDown(self): self.unload_plugins() self.teardown_beets() - self.patcher.stop() def test_stored_hashes(self): test_album = self.mk_test_album() diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index a9b1ae085..8befd750c 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -23,56 +23,54 @@ from beets.library import Item from beets import util +@patch('beets.util.command_output') class KeyFinderTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('keyfinder') - self.patcher = patch('beets.util.command_output') - self.command_output = self.patcher.start() def tearDown(self): self.teardown_beets() self.unload_plugins() - self.patcher.stop() - def test_add_key(self): + def test_add_key(self, command_output): item = Item(path='/file') item.add(self.lib) - self.command_output.return_value = 'dbm' + command_output.return_value = 'dbm' self.run_command('keyfinder') item.load() self.assertEqual(item['initial_key'], 'C#m') - self.command_output.assert_called_with( + command_output.assert_called_with( [b'KeyFinder', b'-f', util.syspath(item.path)]) - def test_add_key_on_import(self): - self.command_output.return_value = 'dbm' + def test_add_key_on_import(self, command_output): + command_output.return_value = 'dbm' importer = self.create_importer() importer.run() item = self.lib.items().get() self.assertEqual(item['initial_key'], 'C#m') - def test_force_overwrite(self): + def test_force_overwrite(self, command_output): self.config['keyfinder']['overwrite'] = True item = Item(path='/file', initial_key='F') item.add(self.lib) - self.command_output.return_value = 'C#m' + command_output.return_value = 'C#m' self.run_command('keyfinder') item.load() self.assertEqual(item['initial_key'], 'C#m') - def test_do_not_overwrite(self): + def test_do_not_overwrite(self, command_output): item = Item(path='/file', initial_key='F') item.add(self.lib) - self.command_output.return_value = 'dbm' + command_output.return_value = 'dbm' self.run_command('keyfinder') item.load() diff --git a/test/test_play.py b/test/test_play.py index 469377c75..1fbcb6ae4 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -28,96 +28,94 @@ from beets.ui import UserError from beets.util import open_anything +@patch('beetsplug.play.util.interactive_open') class PlayPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() self.load_plugins('play') self.item = self.add_item(album=u'a nice älbum', title=u'aNiceTitle') self.lib.add_album([self.item]) - self.open_patcher = patch('beetsplug.play.util.interactive_open') - self.open_mock = self.open_patcher.start() self.config['play']['command'] = 'echo' def tearDown(self): - self.open_patcher.stop() self.teardown_beets() self.unload_plugins() - def do_test(self, args=('title:aNiceTitle',), expected_cmd='echo', + def do_test(self, open_mock, args=('title:aNiceTitle',), expected_cmd='echo', expected_playlist=None): self.run_command('play', *args) - self.open_mock.assert_called_once_with(ANY, expected_cmd) + open_mock.assert_called_once_with(ANY, expected_cmd) expected_playlist = expected_playlist or self.item.path.decode('utf-8') exp_playlist = expected_playlist + u'\n' - with open(self.open_mock.call_args[0][0][0], 'rb') as playlist: + with open(open_mock.call_args[0][0][0], 'rb') as playlist: self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) - def test_basic(self): - self.do_test() + def test_basic(self, open_mock): + self.do_test(open_mock) - def test_album_option(self): - self.do_test([u'-a', u'nice']) + def test_album_option(self, open_mock): + self.do_test(open_mock, [u'-a', u'nice']) - def test_args_option(self): - self.do_test([u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') + def test_args_option(self, open_mock): + self.do_test(open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') - def test_args_option_in_middle(self): + def test_args_option_in_middle(self, open_mock): self.config['play']['command'] = 'echo $args other' - self.do_test([u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') + self.do_test(open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') - def test_relative_to(self): + def test_relative_to(self, open_mock): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' path = os.path.relpath(self.item.path, b'/something') playlist = path.decode('utf8') - self.do_test(expected_cmd='echo', expected_playlist=playlist) + self.do_test(open_mock, expected_cmd='echo', expected_playlist=playlist) - def test_use_folders(self): + def test_use_folders(self, open_mock): self.config['play']['command'] = None self.config['play']['use_folders'] = True self.run_command('play', '-a', 'nice') - self.open_mock.assert_called_once_with(ANY, open_anything()) - playlist = open(self.open_mock.call_args[0][0][0], 'rb') + open_mock.assert_called_once_with(ANY, open_anything()) + playlist = open(open_mock.call_args[0][0][0], 'rb') self.assertEqual(u'{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), playlist.read().decode('utf-8')) - def test_raw(self): + def test_raw(self, open_mock): self.config['play']['raw'] = True self.run_command(u'play', u'nice') - self.open_mock.assert_called_once_with([self.item.path], 'echo') + open_mock.assert_called_once_with([self.item.path], 'echo') - def test_not_found(self): + def test_not_found(self, open_mock): self.run_command(u'play', u'not found') - self.open_mock.assert_not_called() + open_mock.assert_not_called() - def test_warning_threshold(self): + def test_warning_threshold(self, open_mock): self.config['play']['warning_threshold'] = 1 self.add_item(title='another NiceTitle') with control_stdin("a"): self.run_command(u'play', u'nice') - self.open_mock.assert_not_called() + open_mock.assert_not_called() - def test_warning_threshold_backwards_compat(self): + def test_warning_threshold_backwards_compat(self, open_mock): self.config['play']['warning_treshold'] = 1 self.add_item(title=u'another NiceTitle') with control_stdin("a"): self.run_command(u'play', u'nice') - self.open_mock.assert_not_called() + open_mock.assert_not_called() - def test_command_failed(self): - self.open_mock.side_effect = OSError(u"some reason") + def test_command_failed(self, open_mock): + open_mock.side_effect = OSError(u"some reason") with self.assertRaises(UserError): self.run_command(u'play', u'title:aNiceTitle') From 0377a4e26bc6f0156f4649ce70e4417e3e96e78e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 23 Jul 2016 04:23:54 -0400 Subject: [PATCH 1200/2280] open completion files in test_ui in binary mode --- test/test_ui.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 500901ef1..f55d4b48d 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1143,7 +1143,7 @@ class CompletionTest(_common.TestCase): else: self.skipTest(u'bash-completion script not found') try: - with open(util.syspath(bash_completion), 'r') as f: + with open(util.syspath(bash_completion), 'rb') as f: tester.stdin.writelines(f) except IOError: self.skipTest(u'could not read bash-completion script') @@ -1157,7 +1157,7 @@ class CompletionTest(_common.TestCase): # Load test suite. test_script = os.path.join(_common.RSRC, b'test_completion.sh') - with open(test_script, 'r') as test_script: + with open(test_script, 'rb') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() if tester.returncode != 0 or out != u"completion tests passed\n": From 20321feda7604c578895805770b0b084390234d2 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 23 Jul 2016 04:28:18 -0400 Subject: [PATCH 1201/2280] read and write pipes as bytes in completion tests The stdin/stdout for subprocess are bytes, so treat them that way --- test/test_ui.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index f55d4b48d..733754bf0 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1151,17 +1151,17 @@ class CompletionTest(_common.TestCase): # Load completion script. self.io.install() ui._raw_main(['completion']) - completion_script = self.io.getoutput() + completion_script = self.io.getoutput().encode('utf-8') self.io.restore() - tester.stdin.writelines(completion_script) + tester.stdin.writelines(completion_script.splitlines(True)) # Load test suite. test_script = os.path.join(_common.RSRC, b'test_completion.sh') with open(test_script, 'rb') as test_script: tester.stdin.writelines(test_script) (out, err) = tester.communicate() - if tester.returncode != 0 or out != u"completion tests passed\n": - print(out) + if tester.returncode != 0 or out != b'completion tests passed\n': + print(out.decode('utf-8')) self.fail(u'test/test_completion.sh did not execute properly') From 3d351548cf8c8fd570a661d82f379791950aee55 Mon Sep 17 00:00:00 2001 From: davidak Date: Sat, 23 Jul 2016 13:31:33 +0200 Subject: [PATCH 1202/2280] docs: add instructions to install plugin dependencies, fixes #2136 --- docs/plugins/index.rst | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 58464060b..ac5b76ef1 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -28,6 +28,23 @@ Each plugin has its own set of options that can be defined in a section bearing convert: auto: true +Install dependencies +-------------------- + +The needed dependencies can be found on the plugin page. + +You can also use `pip`'s "extras" feature to install all dependencies for a beets plugin. + +:: + + pip install beets[fetchart] + +It's also possible to install the dependencies for multiple plugins at once:: + + pip install beets[fetchart,lyrics,lastgenre] + +Remember to use `pip` for Python 2.7 as Python 3 is not yet supported. You might have to use `sudo`. + .. toctree:: :hidden: From d9a55dac4c90a039a752acedcafaea14db406f54 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 23 Jul 2016 12:25:13 -0700 Subject: [PATCH 1203/2280] Trim the docs on dependency installation (#2139) --- docs/plugins/index.rst | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index ac5b76ef1..f5895ab21 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -28,23 +28,13 @@ Each plugin has its own set of options that can be defined in a section bearing convert: auto: true -Install dependencies --------------------- - -The needed dependencies can be found on the plugin page. - -You can also use `pip`'s "extras" feature to install all dependencies for a beets plugin. - -:: - - pip install beets[fetchart] - -It's also possible to install the dependencies for multiple plugins at once:: +Some plugins have special dependencies that you'll need to install. The +documentation page for each plugin will list them in the setup instructions. +For some, you can use `pip`'s "extras" feature to install the dependencies, +like this:: pip install beets[fetchart,lyrics,lastgenre] -Remember to use `pip` for Python 2.7 as Python 3 is not yet supported. You might have to use `sudo`. - .. toctree:: :hidden: From 92d008b1550f07be5aff091409b924f6928bf737 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 24 Jul 2016 12:11:35 -0700 Subject: [PATCH 1204/2280] Fix overlength lines --- test/test_importer.py | 7 +++++-- test/test_play.py | 13 ++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/test/test_importer.py b/test/test_importer.py index 21f3c2601..37550263b 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1766,8 +1766,10 @@ def mocked_get_recording_by_id(id_, includes=[], release_status=[], } -@patch('musicbrainzngs.get_recording_by_id', Mock(side_effect=mocked_get_recording_by_id)) -@patch('musicbrainzngs.get_release_by_id', Mock(side_effect=mocked_get_release_by_id)) +@patch('musicbrainzngs.get_recording_by_id', + Mock(side_effect=mocked_get_recording_by_id)) +@patch('musicbrainzngs.get_release_by_id', + Mock(side_effect=mocked_get_release_by_id)) class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): """Test the --musicbrainzid argument.""" @@ -1850,6 +1852,7 @@ class ImportMusicBrainzIdTest(_common.TestCase, ImportHelper): self.assertEqual(set(['VALID_RECORDING_0', 'VALID_RECORDING_1']), set([c.info.title for c in task.candidates])) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) diff --git a/test/test_play.py b/test/test_play.py index 1fbcb6ae4..d250d08bb 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -41,8 +41,8 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def do_test(self, open_mock, args=('title:aNiceTitle',), expected_cmd='echo', - expected_playlist=None): + def do_test(self, open_mock, args=('title:aNiceTitle',), + expected_cmd='echo', expected_playlist=None): self.run_command('play', *args) open_mock.assert_called_once_with(ANY, expected_cmd) @@ -58,12 +58,14 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.do_test(open_mock, [u'-a', u'nice']) def test_args_option(self, open_mock): - self.do_test(open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') + self.do_test(open_mock, + [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') def test_args_option_in_middle(self, open_mock): self.config['play']['command'] = 'echo $args other' - self.do_test(open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') + self.do_test(open_mock, + [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') def test_relative_to(self, open_mock): self.config['play']['command'] = 'echo' @@ -71,7 +73,8 @@ class PlayPluginTest(unittest.TestCase, TestHelper): path = os.path.relpath(self.item.path, b'/something') playlist = path.decode('utf8') - self.do_test(open_mock, expected_cmd='echo', expected_playlist=playlist) + self.do_test(open_mock, + expected_cmd='echo', expected_playlist=playlist) def test_use_folders(self, open_mock): self.config['play']['command'] = None From c67fbefc4c164f89024ea4182792b46e48887abb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 24 Jul 2016 14:59:31 -0700 Subject: [PATCH 1205/2280] A little more spcificity in `CodingFormatter` --- beetsplug/hook.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index e48c5f374..673f7be71 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -24,8 +24,13 @@ from beets.util import shlex_split class CodingFormatter(string.Formatter): - """A custom string formatter that decodes the format string and it's - fields. + """A variant of `string.Formatter` that converts everything to `unicode` + strings. + + This is necessary on Python 2, where formatting otherwise occurs on + bytestrings. It intercepts two points in the formatting process to decode + the format string and all fields using the specified encoding. If decoding + fails, the values are used as-is. """ def __init__(self, coding): @@ -57,6 +62,7 @@ class CodingFormatter(string.Formatter): """ converted = super(CodingFormatter, self).convert_field(value, conversion) + try: converted = converted.decode(self._coding) except UnicodeEncodeError: From 039825e0e0eaf02404fd0ea2eb3272128c33cebe Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 24 Jul 2016 15:01:06 -0700 Subject: [PATCH 1206/2280] Only use CodingFormatter on Python 2 --- beetsplug/hook.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 673f7be71..596c969d0 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -17,6 +17,7 @@ from __future__ import division, absolute_import, print_function import string import subprocess +import six from beets.plugins import BeetsPlugin from beets.ui import _arg_encoding @@ -96,7 +97,12 @@ class HookPlugin(BeetsPlugin): self._log.error('invalid command "{0}"', command) return - formatter = CodingFormatter(_arg_encoding()) + # Use a string formatter that works on Unicode strings. + if six.PY2: + formatter = CodingFormatter(_arg_encoding()) + else: + formatter = string.Formatter() + command_pieces = shlex_split(command) for i, piece in enumerate(command_pieces): From 3275a511c2cd8322c006fc8bb511ca65d3ce1107 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 24 Jul 2016 23:40:29 -0400 Subject: [PATCH 1207/2280] remove a template test that doesn't test anything @samspyo discovered that this test wasn't testing anything of value, so we're dropping it. --- test/test_template.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/test/test_template.py b/test/test_template.py index 0605675c6..331de0458 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -17,8 +17,6 @@ """ from __future__ import division, absolute_import, print_function -import warnings - from test._common import unittest from beets.util import functemplate import six @@ -213,13 +211,6 @@ class ParseTest(unittest.TestCase): self._assert_call(arg_parts[0], u"bar", 1) self.assertEqual(list(_normexpr(arg_parts[0].args[0])), [u'baz']) - def test_fail_on_utf8(self): - parts = u'é'.encode('utf8') - warnings.simplefilter("ignore") - with self.assertRaises(UnicodeDecodeError): - functemplate._parse(parts) - warnings.simplefilter("default") - class EvalTest(unittest.TestCase): def _eval(self, template): From 2b349c785146e6e2900c726622a3345f39b7a7b0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 00:14:53 -0400 Subject: [PATCH 1208/2280] use :memory: Library in all test_config_command tests --- test/test_config_command.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_config_command.py b/test/test_config_command.py index d59181373..b0240574c 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -20,6 +20,7 @@ import six class ConfigCommandTest(unittest.TestCase, TestHelper): def setUp(self): + self.lib = Library(':memory:') self.temp_dir = mkdtemp() if 'EDITOR' in os.environ: del os.environ['EDITOR'] @@ -119,7 +120,6 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): self.assertIn('here is problem', six.text_type(user_error.exception)) def test_edit_invalid_config_file(self): - self.lib = Library(':memory:') with open(self.config_path, 'w') as file: file.write('invalid: [') config.clear() From 7bb649c3b2143155b1e1393fa75f22469f75ae20 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 00:16:09 -0400 Subject: [PATCH 1209/2280] remove :memory: library fallback from test run_command --- test/helper.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/helper.py b/test/helper.py index 93813004b..a0f126b0f 100644 --- a/test/helper.py +++ b/test/helper.py @@ -425,8 +425,6 @@ class TestHelper(object): sys.argv = ['beet'] # avoid leakage from test suite args if hasattr(self, 'lib'): lib = self.lib - else: - lib = Library(':memory:') beets.ui._raw_main(list(args), lib) def run_with_output(self, *args): From 9ab9166c8d5859fad53fd8a3ff422c6ff317b8b3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 00:43:33 -0400 Subject: [PATCH 1210/2280] add a lib keyword arg to the run_command test helper Now a `Library` instance can be passed to run_command as a keyword argument. --- test/helper.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/helper.py b/test/helper.py index a0f126b0f..69b2627db 100644 --- a/test/helper.py +++ b/test/helper.py @@ -421,10 +421,16 @@ class TestHelper(object): # Running beets commands - def run_command(self, *args): + def run_command(self, *args, **kwargs): + """Run a beets command with an arbitrary amount of arguments. The + Library` defaults to `self.lib`, but can be overridden with + the keyword argument `lib`. + """ sys.argv = ['beet'] # avoid leakage from test suite args + lib = None if hasattr(self, 'lib'): lib = self.lib + lib = kwargs.get('lib', lib) beets.ui._raw_main(list(args), lib) def run_with_output(self, *args): From ba26b7d26f25ee662c09161d7c44c232cff2cdd9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 01:04:06 -0400 Subject: [PATCH 1211/2280] replace calls to _raw_main in test_ui with run_command --- test/test_ui.py | 53 ++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 733754bf0..c41c4ab2c 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -172,7 +172,7 @@ class ModifyTest(unittest.TestCase, TestHelper): def modify_inp(self, inp, *args): with control_stdin(inp): - ui._raw_main(['modify'] + list(args), self.lib) + self.run_command('modify', *args) def modify(self, *args): self.modify_inp('y', *args) @@ -360,7 +360,7 @@ class WriteTest(unittest.TestCase, TestHelper): self.teardown_beets() def write_cmd(self, *args): - ui._raw_main(['write'] + list(args), self.lib) + self.run_command('write', *args) def test_update_mtime(self): item = self.add_item_fixture() @@ -721,7 +721,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): with self.write_config_file() as config: config.write('paths: {x: y}') - ui._raw_main(['test']) + self.run_command('test', lib=None) key, template = self.test_cmd.lib.path_formats[0] self.assertEqual(key, 'x') self.assertEqual(template.original, 'y') @@ -732,8 +732,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self._reset_config() with self.write_config_file() as config: config.write('paths: {x: y}') - - ui._raw_main(['test']) + self.run_command('test', lib=None) key, template = self.test_cmd.lib.path_formats[0] self.assertEqual(key, 'x') self.assertEqual(template.original, 'y') @@ -745,28 +744,27 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): config.write('library: /xxx/yyy/not/a/real/path') with self.assertRaises(ui.UserError): - ui._raw_main(['test']) + self.run_command('test', lib=None) def test_user_config_file(self): with self.write_config_file() as file: file.write('anoption: value') - ui._raw_main(['test']) + self.run_command('test', lib=None) self.assertEqual(config['anoption'].get(), 'value') def test_replacements_parsed(self): with self.write_config_file() as config: config.write("replace: {'[xy]': z}") - ui._raw_main(['test']) + self.run_command('test', lib=None) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [(re.compile(u'[xy]'), 'z')]) def test_multiple_replacements_parsed(self): with self.write_config_file() as config: config.write("replace: {'[xy]': z, foo: bar}") - - ui._raw_main(['test']) + self.run_command('test', lib=None) replacements = self.test_cmd.lib.replacements self.assertEqual(replacements, [ (re.compile(u'[xy]'), u'z'), @@ -777,8 +775,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): config_path = os.path.join(self.temp_dir, b'config.yaml') with open(config_path, 'w') as file: file.write('anoption: value') - - ui._raw_main(['--config', config_path, 'test']) + self.run_command('--config', config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'value') def test_cli_config_file_overwrites_user_defaults(self): @@ -788,8 +785,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') - - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_file_overwrites_beetsdir_defaults(self): @@ -801,8 +797,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): cli_config_path = os.path.join(self.temp_dir, b'config.yaml') with open(cli_config_path, 'w') as file: file.write('anoption: cli overwrite') - - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') # @unittest.skip('Difficult to implement with optparse') @@ -816,8 +811,8 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # with open(cli_config_path_2, 'w') as file: # file.write('second: value') # -# ui._raw_main(['--config', cli_config_path_1, -# '--config', cli_config_path_2, 'test']) +# self.run_command('--config', cli_config_path_1, +# '--config', cli_config_path_2, 'test', lib=None) # self.assertEqual(config['first'].get(), 'value') # self.assertEqual(config['second'].get(), 'value') # @@ -833,8 +828,8 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): # with open(cli_overwrite_config_path, 'w') as file: # file.write('anoption: overwrite') # -# ui._raw_main(['--config', cli_config_path, -# '--config', cli_overwrite_config_path, 'test']) +# self.run_command('--config', cli_config_path, +# '--config', cli_overwrite_config_path, 'test') # self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_paths_resolve_relative_to_user_dir(self): @@ -843,7 +838,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): file.write('library: beets.db\n') file.write('statefile: state') - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assert_equal_path( util.bytestring_path(config['library'].as_filename()), os.path.join(self.user_config_dir, b'beets.db') @@ -861,7 +856,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): file.write('library: beets.db\n') file.write('statefile: state') - ui._raw_main(['--config', cli_config_path, 'test']) + self.run_command('--config', cli_config_path, 'test', lib=None) self.assert_equal_path( util.bytestring_path(config['library'].as_filename()), os.path.join(self.beetsdir, b'beets.db') @@ -873,7 +868,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def test_command_line_option_relative_to_working_dir(self): os.chdir(self.temp_dir) - ui._raw_main(['--library', 'foo.db', 'test']) + self.run_command('--library', 'foo.db', 'test', lib=None) self.assert_equal_path(config['library'].as_filename(), os.path.join(os.getcwd(), 'foo.db')) @@ -883,7 +878,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): file.write('pluginpath: %s\n' % _common.PLUGINPATH) file.write('plugins: test') - ui._raw_main(['--config', cli_config_path, 'plugin']) + self.run_command('--config', cli_config_path, 'plugin', lib=None) self.assertTrue(plugins.find_plugins()[0].is_test_plugin) def test_beetsdir_config(self): @@ -900,7 +895,7 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): beetsdir = os.path.join(self.temp_dir, b'beetsfile') open(beetsdir, 'a').close() os.environ['BEETSDIR'] = util.py3_path(beetsdir) - self.assertRaises(ConfigError, ui._raw_main, ['test']) + self.assertRaises(ConfigError, self.run_command, 'test') def test_beetsdir_config_does_not_load_default_user_config(self): os.environ['BEETSDIR'] = util.py3_path(self.beetsdir) @@ -1114,15 +1109,15 @@ class PathFormatTest(_common.TestCase): @_common.slow_test() -class PluginTest(_common.TestCase): +class PluginTest(_common.TestCase, TestHelper): def test_plugin_command_from_pluginpath(self): config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] - ui._raw_main(['test']) + self.run_command('test', lib=None) @_common.slow_test() -class CompletionTest(_common.TestCase): +class CompletionTest(_common.TestCase, TestHelper): def test_completion(self): # Load plugin commands config['pluginpath'] = [_common.PLUGINPATH] @@ -1150,7 +1145,7 @@ class CompletionTest(_common.TestCase): # Load completion script. self.io.install() - ui._raw_main(['completion']) + self.run_command('completion', lib=None) completion_script = self.io.getoutput().encode('utf-8') self.io.restore() tester.stdin.writelines(completion_script.splitlines(True)) From 9df4b6dc1528882e941c2b4918f9c642b3fcf269 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Sun, 24 Jul 2016 22:45:31 -0700 Subject: [PATCH 1212/2280] do_test is not actually a test --- test/test_play.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index d250d08bb..7357cf3c6 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -41,8 +41,8 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def do_test(self, open_mock, args=('title:aNiceTitle',), - expected_cmd='echo', expected_playlist=None): + def run_and_assert(self, open_mock, args=('title:aNiceTitle',), + expected_cmd='echo', expected_playlist=None): self.run_command('play', *args) open_mock.assert_called_once_with(ANY, expected_cmd) @@ -52,20 +52,20 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.assertEqual(exp_playlist, playlist.read().decode('utf-8')) def test_basic(self, open_mock): - self.do_test(open_mock) + self.run_and_assert(open_mock) def test_album_option(self, open_mock): - self.do_test(open_mock, [u'-a', u'nice']) + self.run_and_assert(open_mock, [u'-a', u'nice']) def test_args_option(self, open_mock): - self.do_test(open_mock, - [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') + self.run_and_assert( + open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo') def test_args_option_in_middle(self, open_mock): self.config['play']['command'] = 'echo $args other' - self.do_test(open_mock, - [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') + self.run_and_assert( + open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') def test_relative_to(self, open_mock): self.config['play']['command'] = 'echo' @@ -73,8 +73,8 @@ class PlayPluginTest(unittest.TestCase, TestHelper): path = os.path.relpath(self.item.path, b'/something') playlist = path.decode('utf8') - self.do_test(open_mock, - expected_cmd='echo', expected_playlist=playlist) + self.run_and_assert( + open_mock, expected_cmd='echo', expected_playlist=playlist) def test_use_folders(self, open_mock): self.config['play']['command'] = None From f8049e67b483483ec4eb0346844472ff1dcd56e1 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 02:59:12 -0400 Subject: [PATCH 1213/2280] add test helper method to convert cmd args on py2/3 This helper method converts args to bytes on python 2, and args to strings on python 3 --- test/helper.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/test/helper.py b/test/helper.py index 69b2627db..49216f697 100644 --- a/test/helper.py +++ b/test/helper.py @@ -119,13 +119,25 @@ def capture_stdout(): print(capture.getvalue()) +def _convert_args(args): + """Convert args to bytestrings for Python 2 and convert them to strings + on Python 3. + """ + for i, elem in enumerate(args): + if six.PY2: + if isinstance(elem, six.text_type): + args[i] = elem.encode(_arg_encoding()) + else: + if isinstance(elem, bytes): + args[i] = elem.decode(_arg_encoding()) + + return args + + def has_program(cmd, args=['--version']): """Returns `True` if `cmd` can be executed. """ - full_cmd = [cmd] + args - for i, elem in enumerate(full_cmd): - if isinstance(elem, six.text_type): - full_cmd[i] = elem.encode(_arg_encoding()) + full_cmd = _convert_args([cmd] + args) try: with open(os.devnull, 'wb') as devnull: subprocess.check_call(full_cmd, stderr=devnull, @@ -431,7 +443,7 @@ class TestHelper(object): if hasattr(self, 'lib'): lib = self.lib lib = kwargs.get('lib', lib) - beets.ui._raw_main(list(args), lib) + beets.ui._raw_main(_convert_args(list(args)), lib) def run_with_output(self, *args): with capture_stdout() as out: From 417d78eb7895ec1d0f680c31505025e235ccb7a0 Mon Sep 17 00:00:00 2001 From: Jesse Weinstein Date: Mon, 25 Jul 2016 00:19:49 -0700 Subject: [PATCH 1214/2280] Use longer param name Per request by jrobeson on IRC --- test/test_edit.py | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index d45bc0a13..08a1c3d1f 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -138,7 +138,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.assertTrue(all(i.title.startswith(title_starts_with) for i in self.lib.items())) - def test_title_edit_discard(self, m): + def test_title_edit_discard(self, mock_write): """Edit title for all items in the library, then discard changes.""" # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': @@ -146,11 +146,11 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Cancel. ['c']) - self.assertCounts(m, write_call_count=0, + self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, []) - def test_title_edit_apply(self, m): + def test_title_edit_apply(self, mock_write): """Edit title for all items in the library, then apply changes.""" # Edit track titles. self.run_mocked_command({'replacements': {u't\u00eftle': @@ -158,12 +158,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(m, write_call_count=self.TRACK_COUNT, + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['title']) - def test_single_title_edit_apply(self, m): + def test_single_title_edit_apply(self, mock_write): """Edit title for one item in the library, then apply changes.""" # Edit one track title. self.run_mocked_command({'replacements': {u't\u00eftle 9': @@ -171,25 +171,25 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(m, write_call_count=1,) + self.assertCounts(mock_write, write_call_count=1,) # No changes except on last item. self.assertItemFieldsModified(list(self.album.items())[:-1], self.items_orig[:-1], []) self.assertEqual(list(self.album.items())[-1].title, u'modified t\u00eftle 9') - def test_noedit(self, m): + def test_noedit(self, mock_write): """Do not edit anything.""" # Do not edit anything. self.run_mocked_command({'contents': None}, # No stdin. []) - self.assertCounts(m, write_call_count=0, + self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, []) - def test_album_edit_apply(self, m): + def test_album_edit_apply(self, mock_write): """Edit the album field for all items in the library, apply changes. By design, the album should not be updated."" """ @@ -199,14 +199,14 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Apply changes. ['a']) - self.assertCounts(m, write_call_count=self.TRACK_COUNT) + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) # Ensure album is *not* modified. self.album.load() self.assertEqual(self.album.album, u'\u00e4lbum') - def test_single_edit_add_field(self, m): + def test_single_edit_add_field(self, mock_write): """Edit the yaml file appending an extra field to the first item, then apply changes.""" # Append "foo: bar" to item with id == 1. @@ -216,10 +216,10 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): ['a']) self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar') - self.assertCounts(m, write_call_count=1, + self.assertCounts(mock_write, write_call_count=1, title_starts_with=u't\u00eftle') - def test_a_album_edit_apply(self, m): + def test_a_album_edit_apply(self, mock_write): """Album query (-a), edit album field, apply changes.""" self.run_mocked_command({'replacements': {u'\u00e4lbum': u'modified \u00e4lbum'}}, @@ -228,12 +228,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): args=['-a']) self.album.load() - self.assertCounts(m, write_call_count=self.TRACK_COUNT) + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.album, u'modified \u00e4lbum') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album']) - def test_a_albumartist_edit_apply(self, m): + def test_a_albumartist_edit_apply(self, mock_write): """Album query (-a), edit albumartist field, apply changes.""" self.run_mocked_command({'replacements': {u'album artist': u'modified album artist'}}, @@ -242,12 +242,12 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): args=['-a']) self.album.load() - self.assertCounts(m, write_call_count=self.TRACK_COUNT) + self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.albumartist, u'the modified album artist') self.assertItemFieldsModified(self.album.items(), self.items_orig, ['albumartist']) - def test_malformed_yaml(self, m): + def test_malformed_yaml(self, mock_write): """Edit the yaml file incorrectly (resulting in a malformed yaml document).""" # Edit the yaml file to an invalid file. @@ -255,10 +255,10 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # Edit again to fix? No. ['n']) - self.assertCounts(m, write_call_count=0, + self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\u00eftle') - def test_invalid_yaml(self, m): + def test_invalid_yaml(self, mock_write): """Edit the yaml file incorrectly (resulting in a well-formed but invalid yaml document).""" # Edit the yaml file to an invalid but parseable file. @@ -266,7 +266,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): # No stdin. []) - self.assertCounts(m, write_call_count=0, + self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\u00eftle') From e5497c749459fd1bad37df456297d0eff10a279e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 03:26:29 -0400 Subject: [PATCH 1215/2280] use stringed template vars on PY3 in convert plugin We decode them with `surrogateescape`, so we avoid decoding errors --- beetsplug/convert.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 4e3556684..e48b455f5 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -22,6 +22,7 @@ import threading import subprocess import tempfile import shlex +import six from string import Template from beets import ui, util, plugins, config @@ -183,6 +184,11 @@ class ConvertPlugin(BeetsPlugin): self._log.info(u'Encoding {0}', util.displayable_path(source)) # Substitute $source and $dest in the argument list. + if not six.PY2: + command = command.decode(ui._arg_encoding(), 'surrogateescape') + source = source.decode(ui._arg_encoding(), 'surrogateescape') + dest = dest.decode(ui._arg_encoding(), 'surrogateescape') + args = shlex.split(command) for i, arg in enumerate(args): args[i] = Template(arg).safe_substitute({ From 1b103b087b39ecf0589ffe6dd0f4582747498edf Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 04:46:38 -0400 Subject: [PATCH 1216/2280] reencode convert args on py3 for util.command_output command_output requires bytestrings, so we put em back that way. --- beetsplug/convert.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index e48b455f5..10d5d9a18 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -190,18 +190,23 @@ class ConvertPlugin(BeetsPlugin): dest = dest.decode(ui._arg_encoding(), 'surrogateescape') args = shlex.split(command) + encode_cmd = [] for i, arg in enumerate(args): args[i] = Template(arg).safe_substitute({ 'source': source, 'dest': dest, }) + if six.PY2: + encode_cmd.append(args[i]) + else: + encode_cmd.append(args[i].encode(ui._arg_encoding())) if pretend: self._log.info(u' '.join(ui.decargs(args))) return try: - util.command_output(args) + util.command_output(encode_cmd) except subprocess.CalledProcessError as exc: # Something went wrong (probably Ctrl+C), remove temporary files self._log.info(u'Encoding {0} failed. Cleaning up...', From e65e7a6716194a1f1f7aeb81a636bb330c9a382a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 12:45:32 -0400 Subject: [PATCH 1217/2280] Fix minor style in completion test --- test/test_ui.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index c41c4ab2c..61e3ff33e 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1151,10 +1151,10 @@ class CompletionTest(_common.TestCase, TestHelper): tester.stdin.writelines(completion_script.splitlines(True)) # Load test suite. - test_script = os.path.join(_common.RSRC, b'test_completion.sh') - with open(test_script, 'rb') as test_script: - tester.stdin.writelines(test_script) - (out, err) = tester.communicate() + test_script_name = os.path.join(_common.RSRC, b'test_completion.sh') + with open(test_script_name, 'rb') as test_script_file: + tester.stdin.writelines(test_script_file) + out, err = tester.communicate() if tester.returncode != 0 or out != b'completion tests passed\n': print(out.decode('utf-8')) self.fail(u'test/test_completion.sh did not execute properly') From b73bbf0b3ec4b64054c4f14a995eef4a770727e2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 12:57:44 -0400 Subject: [PATCH 1218/2280] In completion tests, don't load system scripts On my machine, the "leak" of other bash_completion scripts here recently started doing a *lot* of work for other packages. Most damningly, it started compiling a bunch of stuff with rustc! Now we only load beets' own completion stuff. --- test/test_ui.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 61e3ff33e..ab8cc289d 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1123,12 +1123,18 @@ class CompletionTest(_common.TestCase, TestHelper): config['pluginpath'] = [_common.PLUGINPATH] config['plugins'] = ['test'] - # Tests run in bash + # Do not load any other bash completion scripts on the system. + env = dict(os.environ) + env['BASH_COMPLETION_DIR'] = os.devnull + env['BASH_COMPLETION_COMPAT_DIR'] = os.devnull + + # Open a `bash` process to run the tests in. We'll pipe in bash + # commands via stdin. cmd = os.environ.get('BEETS_TEST_SHELL', '/bin/bash --norc').split() if not has_program(cmd[0]): self.skipTest(u'bash not available') tester = subprocess.Popen(cmd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE) + stdout=subprocess.PIPE, env=env) # Load bash_completion library. for path in commands.BASH_COMPLETION_PATHS: From 0e2b8a5b60abbd7930c60627f536bf9f11cc1883 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 13:21:50 -0400 Subject: [PATCH 1219/2280] Use native strings for IO in a test --- test/test_ui.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index ab8cc289d..411901898 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -641,11 +641,13 @@ class InputTest(_common.TestCase): self.io.install() def test_manual_search_gets_unicode(self): - self.io.addinput(b'\xc3\x82me') - self.io.addinput(b'\xc3\x82me') + # The input here uses "native strings": bytes on Python 2, Unicode on + # Python 3. + self.io.addinput('foö') + self.io.addinput('bár') artist, album = commands.manual_search(False) - self.assertEqual(artist, u'\xc2me') - self.assertEqual(album, u'\xc2me') + self.assertEqual(artist, u'foö') + self.assertEqual(album, u'bár') @_common.slow_test() From 6772b4d1fd979d27c5d02fd2ef146dbccb8b0a9e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 13:24:51 -0400 Subject: [PATCH 1220/2280] Leave captured stdout as Unicode on Python 3 --- test/test_ui.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index 411901898..558c00932 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -23,6 +23,7 @@ import re import subprocess import platform from copy import deepcopy +import six from mock import patch, Mock from test import _common @@ -65,7 +66,9 @@ class ListTest(unittest.TestCase): with capture_stdout() as stdout: self._run_list([u'na\xefve']) out = stdout.getvalue() - self.assertTrue(u'na\xefve' in out.decode(stdout.encoding)) + if six.PY2: + out = out.decode(stdout.encoding) + self.assertTrue(u'na\xefve' in out) def test_list_item_path(self): with capture_stdout() as stdout: From 6a71e4bad486daf061f8d1ea55f7b4a11533d8a0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 14:58:49 -0400 Subject: [PATCH 1221/2280] tox: Add a py35-flake8 environment This is not on by default, but it's still useful to have around. --- tox.ini | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 81eacf16a..598368daa 100644 --- a/tox.ini +++ b/tox.ini @@ -7,7 +7,7 @@ envlist = py27-test, py27-flake8, docs # The exhaustive list of environments is: -# envlist = py{27,34,35}-{test,cov}, py{27,34}-flake8, docs +# envlist = py{27,34,35}-{test,cov}, py{27,34,35}-flake8, docs [_test] deps = @@ -37,7 +37,7 @@ passenv = deps = {test,cov}: {[_test]deps} py27: pathlib - py{27,34}-flake8: {[_flake8]deps} + py{27,34,35}-flake8: {[_flake8]deps} commands = py27-cov: python -m nose --with-coverage {posargs} py27-test: python -m nose {posargs} @@ -45,6 +45,7 @@ commands = py{34,35}-test: python -bb -m nose {posargs} py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} py34-flake8: flake8 --min-version 3.4 {posargs} {[_flake8]files} + py35-flake8: flake8 --min-version 3.5 {posargs} {[_flake8]files} [testenv:docs] basepython = python2.7 From 58afaf07a52df2b53bb2f8990cd06005cd063d9e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 15:02:10 -0400 Subject: [PATCH 1222/2280] Switch to new `noqa` syntax for flake8 3.0 Apparently, `# noqa ignore=X` worked before, but now the syntax is more terse, like this: `# noqa: X`. See the changelog here: http://flake8.pycqa.org/en/latest/release-notes/3.0.0.html --- beets/library.py | 2 +- beets/util/__init__.py | 5 +++-- beets/util/confit.py | 6 +++--- beetsplug/bpd/gstplayer.py | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/beets/library.py b/beets/library.py index 18764b6f0..3d18a1be0 100644 --- a/beets/library.py +++ b/beets/library.py @@ -40,7 +40,7 @@ import beets # `memoryview`, depending on the Python version, tells it that we # actually mean non-text data. if six.PY2: - BLOB_TYPE = buffer # noqa ignore=F821 + BLOB_TYPE = buffer # noqa: F821 else: BLOB_TYPE = memoryview diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 472f693b6..17cfc4f0e 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -658,9 +658,10 @@ def as_string(value): """Convert a value to a Unicode object for matching with a query. None becomes the empty string. Bytestrings are silently decoded. """ - buffer_types = memoryview if six.PY2: - buffer_types = (buffer, memoryview) # noqa ignore=F821 + buffer_types = buffer, memoryview # noqa: F821 + else: + buffer_types = memoryview if value is None: return u'' diff --git a/beets/util/confit.py b/beets/util/confit.py index f2a919cd4..18f7c1e16 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -44,9 +44,9 @@ REDACTED_TOMBSTONE = 'REDACTED' # Utilities. PY3 = sys.version_info[0] == 3 -STRING = str if PY3 else unicode # noqa ignore=F821 -BASESTRING = str if PY3 else basestring # noqa ignore=F821 -NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa ignore=F821 +STRING = str if PY3 else unicode # noqa: F821 +BASESTRING = str if PY3 else basestring # noqa: F821 +NUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa: F821 def iter_first(sequence): diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 6972a2722..471f204fb 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -30,7 +30,7 @@ from beets import ui import gi gi.require_version('Gst', '1.0') -from gi.repository import GLib, Gst # noqa ignore=E402 +from gi.repository import GLib, Gst # noqa: E402 Gst.init(None) From 5665696b872225e9df6fac204f15c5d002785463 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 15:08:36 -0400 Subject: [PATCH 1223/2280] Remove unnecessary path fiddling I don't know why this was here in the first place -- imports from `beetsplug` should work fine without this mess. --- test/test_web.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/test_web.py b/test/test_web.py index ac4e03e97..7d477227c 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -9,9 +9,7 @@ from six import assertCountEqual from test._common import unittest from test import _common import json -import beetsplug from beets.library import Item, Album -beetsplug.__path__ = ['./beetsplug', '../beetsplug'] # noqa from beetsplug import web From 8a234ebc557539b04c175e76ed3c9a19031f89ac Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 25 Jul 2016 15:11:10 -0400 Subject: [PATCH 1224/2280] Use flake8 3.0 style for import errors It worked in previous versions to put `noqa` on the non-import line that preceded the imports. As of flake8 3.0.0, we apparently need to ignore the import-after-non-import error on every `import` line. --- test/_common.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/_common.py b/test/_common.py index cfec6afb1..dac6c982a 100644 --- a/test/_common.py +++ b/test/_common.py @@ -27,15 +27,15 @@ from contextlib import contextmanager # Mangle the search path to include the beets sources. -sys.path.insert(0, '..') # noqa -import beets.library -from beets import importer, logging -from beets.ui import commands -from beets import util -import beets +sys.path.insert(0, '..') +import beets.library # noqa: E402 +from beets import importer, logging # noqa: E402 +from beets.ui import commands # noqa: E402 +from beets import util # noqa: E402 +import beets # noqa: E402 # Make sure the development versions of the plugins are used -import beetsplug +import beetsplug # noqa: E402 beetsplug.__path__ = [os.path.abspath( os.path.join(__file__, '..', '..', 'beetsplug') )] From f2998d279a99a12552634a7338b665414c34a5f0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 25 Jul 2016 15:58:52 -0400 Subject: [PATCH 1225/2280] remove py 3.4 and 3.5 from travis allowed_failures --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 39796cbdc..d919676fc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,10 +21,6 @@ matrix: env: {TOX_ENV: py34-flake8} - python: 2.7 env: {TOX_ENV: docs} - allow_failures: - - python: 3.4 - env: {TOX_ENV: py34-test} - - python: 3.5 # Non-Python dependencies. addons: From b4caa0e475f41ab0ece93153007a3747131ec3c8 Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Tue, 26 Jul 2016 15:42:35 +0200 Subject: [PATCH 1226/2280] Add BPM data with acousticbrainz The bpm plugin is a very slow way to add bpm data to songs, using the acousticbrainz plugin is much faster and can doesn't need a new plugin. --- beetsplug/acousticbrainz.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index df790b26f..d1dee855b 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -133,6 +133,9 @@ def fetch_info(log, items, write): item.average_loudness = get_value( "lowlevel", "average_loudness" ) + item.bpm = get_value( + "rhythm", "bpm" + ) item.chords_changes_rate = get_value( "tonal", "chords_changes_rate" ) From 9fb763e151ccbf039a84085d6fd3cd956d742533 Mon Sep 17 00:00:00 2001 From: xarph Date: Tue, 26 Jul 2016 15:41:45 -0700 Subject: [PATCH 1227/2280] fix bug where $args would be included in the command output if $args was set in config but -A or --args was left off the beet play command. --- beetsplug/play.py | 3 +++ test/test_play.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/beetsplug/play.py b/beetsplug/play.py index 27da15b37..c846a755e 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -90,6 +90,9 @@ class PlayPlugin(BeetsPlugin): command_str = command_str.replace(ARGS_MARKER, opts.args) else: command_str = u"{} {}".format(command_str, opts.args) + else: + if ARGS_MARKER in command_str: + command_str = command_str.replace(" "+ARGS_MARKER, "") # Perform search by album and add folders rather than tracks to # playlist. diff --git a/test/test_play.py b/test/test_play.py index 7357cf3c6..38524aa7d 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -67,6 +67,12 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_and_assert( open_mock, [u'-A', u'foo', u'title:aNiceTitle'], u'echo foo other') + def test_unset_args_option_in_middle(self, open_mock): + self.config['play']['command'] = 'echo $args other' + + self.run_and_assert( + open_mock, [u'title:aNiceTitle'], u'echo other') + def test_relative_to(self, open_mock): self.config['play']['command'] = 'echo' self.config['play']['relative_to'] = '/something' From 349a3260f88fde6966fa3a3cc3fa381173859614 Mon Sep 17 00:00:00 2001 From: xarph Date: Tue, 26 Jul 2016 16:08:52 -0700 Subject: [PATCH 1228/2280] Apparently py34-flake8 wants whitespace around operators. --- beetsplug/play.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index c846a755e..9c5f752ff 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -92,7 +92,7 @@ class PlayPlugin(BeetsPlugin): command_str = u"{} {}".format(command_str, opts.args) else: if ARGS_MARKER in command_str: - command_str = command_str.replace(" "+ARGS_MARKER, "") + command_str = command_str.replace(" " + ARGS_MARKER, "") # Perform search by album and add folders rather than tracks to # playlist. From 01483f9600918b094f6c2424c3d5090c5d592719 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 27 Jul 2016 02:53:55 -0400 Subject: [PATCH 1229/2280] change most googlecode refs to their new locations --- beetsplug/lastgenre/__init__.py | 2 +- docs/changelog.rst | 4 ++-- docs/faq.rst | 2 +- docs/plugins/chroma.rst | 3 +-- docs/plugins/fetchart.rst | 2 +- docs/plugins/lastgenre.rst | 2 +- docs/plugins/lastimport.rst | 2 +- docs/plugins/lyrics.rst | 2 +- 8 files changed, 9 insertions(+), 10 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index f901bdaac..d6f4c08a3 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -404,7 +404,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): """ # Work around an inconsistency in pylast where # Album.get_top_tags() does not return TopItem instances. - # https://code.google.com/p/pylast/issues/detail?id=85 + # https://github.com/pylast/pylast/issues/86 if isinstance(obj, pylast.Album): obj = super(pylast.Album, obj) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b35ba9a3..85304ede3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -2994,7 +2994,7 @@ issue involves correct ordering of autotagged albums. * Added `` beet version`` command that just shows the current release version. -.. _upstream bug: http://code.google.com/p/mutagen/issues/detail?id=7 +.. _upstream bug: https://github.com/quodlibet/mutagen/issues/7 .. _Bluelet: https://github.com/sampsyo/bluelet 1.0b5 (September 28, 2010) @@ -3207,7 +3207,7 @@ BPD). To "upgrade" an old database, you can use the included ``albumify`` plugin .. _for the future: http://code.google.com/p/beets/issues/detail?id=69 .. _the beetsplug directory: - http://code.google.com/p/beets/source/browse/#hg/beetsplug + https://github.com/beetbox/beets/tree/master/beetsplug Beets also now has its first third-party plugin: `beetfs`_, by Martin Eve! It exposes your music in a FUSE filesystem using a custom directory structure. Even diff --git a/docs/faq.rst b/docs/faq.rst index ff74a5350..e36b589bb 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -327,7 +327,7 @@ FLAC files. If beets still complains about a file that seems to be valid, `file a bug `__ and we'll look into it. There's always a possibility that there's a bug "upstream" in the -`Mutagen `__ library used by beets, +`Mutagen `__ library used by beets, in which case we'll forward the bug to that project's tracker. diff --git a/docs/plugins/chroma.rst b/docs/plugins/chroma.rst index b2a9f90c6..3cf983de2 100644 --- a/docs/plugins/chroma.rst +++ b/docs/plugins/chroma.rst @@ -75,7 +75,7 @@ You will also need a mechanism for decoding audio files supported by the Note that if you install beets in a virtualenv, you'll need it to have ``--system-site-packages`` enabled for Python to see the GStreamer bindings. -* On Windows, try the Gstreamer "WinBuilds" from the `OSSBuild`_ project. +* On Windows, builds are provided by `GStreamer`_ .. _audioread: https://github.com/beetbox/audioread .. _pyacoustid: http://github.com/beetbox/pyacoustid @@ -83,7 +83,6 @@ You will also need a mechanism for decoding audio files supported by the .. _MAD: http://spacepants.org/src/pymad/ .. _pymad: http://www.underbit.com/products/mad/ .. _Core Audio: http://developer.apple.com/technologies/mac/audio-and-video.html -.. _OSSBuild: http://code.google.com/p/ossbuild/ .. _Gstreamer: http://gstreamer.freedesktop.org/ .. _PyGObject: https://wiki.gnome.org/Projects/PyGObject diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 7856521a9..16478d2b1 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -167,7 +167,7 @@ To use the google image search backend you need to option to your key, then add ``google`` to the list of sources in your configuration. -.. _register for a Google API key: https://code.google.com/apis/console. +.. _register for a Google API key: https://console.developers.google.com. Optionally, you can `define a custom search engine`_. Get your search engine's token and use it for your ``google_engine`` configuration option. The diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 8db198151..c708219a9 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -35,7 +35,7 @@ For the curious, the default genre list is generated by a `script that scrapes Wikipedia`_. .. _pip: http://www.pip-installer.org/ -.. _pylast: http://code.google.com/p/pylast/ +.. _pylast: https://github.com/pylast/pylast .. _script that scrapes Wikipedia: https://gist.github.com/1241307 .. _internal whitelist: https://raw.githubusercontent.com/beetbox/beets/master/beetsplug/lastgenre/genres.txt diff --git a/docs/plugins/lastimport.rst b/docs/plugins/lastimport.rst index d047f8a3b..8006d6bbb 100644 --- a/docs/plugins/lastimport.rst +++ b/docs/plugins/lastimport.rst @@ -24,7 +24,7 @@ Next, add your Last.fm username to your beets configuration file:: user: beetsfanatic .. _pip: http://www.pip-installer.org/ -.. _pylast: http://code.google.com/p/pylast/ +.. _pylast: https://github.com/pylast/pylast Importing Play Counts --------------------- diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 992eb88c5..37444e87c 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -108,7 +108,7 @@ If you use default ``google_engine_ID``, we recommend limiting the sources to ``musixmatch google`` as the other sources are already included in the Google results. -.. _register for a Google API key: https://code.google.com/apis/console +.. _register for a Google API key: https://console.developers.google.com/ Optionally, you can `define a custom search engine`_. Get your search engine's token and use it for your ``google_engine_ID`` configuration option. By From 47c2ed001a4c77402fc5d90919118bf476ad5115 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 27 Jul 2016 02:54:35 -0400 Subject: [PATCH 1230/2280] update gstreamer package names to their 1.0 versions We no longer support 0.10 versions, so these were wrong --- docs/plugins/chroma.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/chroma.rst b/docs/plugins/chroma.rst index 3cf983de2..d26a6a92f 100644 --- a/docs/plugins/chroma.rst +++ b/docs/plugins/chroma.rst @@ -88,8 +88,8 @@ You will also need a mechanism for decoding audio files supported by the To decode audio formats (MP3, FLAC, etc.) with GStreamer, you'll need the standard set of Gstreamer plugins. For example, on Ubuntu, install the packages -``gstreamer0.10-plugins-good``, ``gstreamer0.10-plugins-bad``, and -``gstreamer0.10-plugins-ugly``. +``gstreamer1.0-plugins-good``, ``gstreamer1.0-plugins-bad``, and +``gstreamer1.0-plugins-ugly``. Usage ----- From 21cfe980ecf92e70fc8824f5f7fc5152ece42262 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 27 Jul 2016 02:55:11 -0400 Subject: [PATCH 1231/2280] remove some trailing whitespace --- docs/plugins/fetchart.rst | 4 ++-- docs/plugins/lastgenre.rst | 2 +- docs/plugins/lyrics.rst | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 16478d2b1..c839b90ba 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -51,9 +51,9 @@ file. The available options are: to all available sources. Default: ``filesystem coverart itunes amazon albumart``, i.e., everything but ``wikipedia``, ``google`` and ``fanarttv``. Enable those sources for more - matches at the cost of some speed. They are searched in the given order, + matches at the cost of some speed. They are searched in the given order, thus in the default config, no remote (Web) art source are queried if - local art is found in the filesystem. To use a local image as fallback, + local art is found in the filesystem. To use a local image as fallback, move it to the end of the list. - **google_key**: Your Google API key (to enable the Google Custom Search backend). diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index c708219a9..125b1073d 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -53,7 +53,7 @@ a desired subset of genres. Consider for a example this minimal whitelist:: rock heavy metal pop - + together with the default genre tree. Then an item that has its genre specified as *viking metal* would actually be tagged as *heavy metal* because neither *viking metal* nor its parent *black metal* are in the whitelist. It always diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 37444e87c..7263304f2 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -133,9 +133,9 @@ using `pip`_ by typing:: pip install langdetect You also need to register for a Microsoft Azure Marketplace free account and -to the `Microsoft Translator API`_. Follow the four steps process, specifically -at step 3 enter ``beets`` as *Client ID* and copy/paste the generated -*Client secret* into your ``bing_client_secret`` configuration, alongside +to the `Microsoft Translator API`_. Follow the four steps process, specifically +at step 3 enter ``beets`` as *Client ID* and copy/paste the generated +*Client secret* into your ``bing_client_secret`` configuration, alongside ``bing_lang_to`` target `language code`_. .. _langdetect: https://pypi.python.org/pypi/langdetect From 5e3bbf2aebf27937f08402e59fa0b4f4958f480d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 27 Jul 2016 13:32:41 -0400 Subject: [PATCH 1232/2280] Remove remaining links to Google Code (fix #2145) --- beetsplug/replaygain.py | 2 +- docs/changelog.rst | 4 ++-- docs/plugins/index.rst | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index cae55f5b5..fe108aec9 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -60,7 +60,7 @@ def call(args): except UnicodeEncodeError: # Due to a bug in Python 2's subprocess on Windows, Unicode # filenames can fail to encode on that platform. See: - # http://code.google.com/p/beets/issues/detail?id=499 + # https://github.com/google-code-export/beets/issues/499 raise ReplayGainError(u"argument encoding failed") diff --git a/docs/changelog.rst b/docs/changelog.rst index 85304ede3..0545467d8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -3205,7 +3205,7 @@ BPD). To "upgrade" an old database, you can use the included ``albumify`` plugin your library path format strings like ``$artist - $album ($format)`` to get directories with names like ``Paul Simon - Graceland (FLAC)``. -.. _for the future: http://code.google.com/p/beets/issues/detail?id=69 +.. _for the future: https://github.com/google-code-export/beets/issues/69 .. _the beetsplug directory: https://github.com/beetbox/beets/tree/master/beetsplug @@ -3214,7 +3214,7 @@ exposes your music in a FUSE filesystem using a custom directory structure. Even cooler: it lets you keep your files intact on-disk while correcting their tags when accessed through FUSE. Check it out! -.. _beetfs: http://code.google.com/p/beetfs/ +.. _beetfs: https://github.com/jbaiter/beetfs 1.0b2 (July 7, 2010) -------------------- diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index f5895ab21..e0f9521e2 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -237,7 +237,7 @@ Here are a few of the plugins written by the beets community: .. _copyartifacts: https://github.com/sbarakat/beets-copyartifacts .. _dsedivec: https://github.com/dsedivec/beets-plugins .. _beets-artistcountry: https://github.com/agrausem/beets-artistcountry -.. _beetFs: https://code.google.com/p/beetfs/ +.. _beetFs: https://github.com/jbaiter/beetfs .. _Beet-MusicBrainz-Collection: https://github.com/jeffayle/Beet-MusicBrainz-Collection/ .. _A cmus plugin: From 6b193342b5cb3755de353108502a0ab12e49e78a Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Wed, 27 Jul 2016 20:15:35 +0200 Subject: [PATCH 1233/2280] Update changelog for PR #2143 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b35ba9a3..12ea28850 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -25,6 +25,9 @@ The are a couple of small new features: filled-out path template for each file. :bug:`2050` * :doc:`/plugins/embyupdate`: The plugin can now use an API key instead of a password to authenticate with Emby. :bug:`2045` :bug:`2117` +* :doc:`/plugins/acousticbrainz`: The plugin now also adds a ``bpm``, when a + song can be found on AcousticBrainz, this is faster than using the bpm + plugin. And there are a few bug fixes too: From f1deb0c545452d4a4efc99ed6cd83328ebf4f998 Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Wed, 27 Jul 2016 20:16:06 +0200 Subject: [PATCH 1234/2280] Update AcousticBrainz docs for PR #2143 --- docs/plugins/acousticbrainz.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 1e1b076f0..b66bf17de 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -14,6 +14,7 @@ For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: * ``average_loudness`` +* ``bpm`` * ``chords_changes_rate`` * ``chords_key`` * ``chords_number_rate`` From be7c9d3b67594622557fdb7983a8130f5d2e5183 Mon Sep 17 00:00:00 2001 From: xarph Date: Wed, 27 Jul 2016 11:23:37 -0700 Subject: [PATCH 1235/2280] Remove unneeded if clause since .format will silently pass if the needle is not found. Add changelog note. --- beetsplug/play.py | 3 +-- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 9c5f752ff..7d29f040c 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -91,8 +91,7 @@ class PlayPlugin(BeetsPlugin): else: command_str = u"{} {}".format(command_str, opts.args) else: - if ARGS_MARKER in command_str: - command_str = command_str.replace(" " + ARGS_MARKER, "") + command_str = command_str.replace(" " + ARGS_MARKER, "") # Perform search by album and add folders rather than tracks to # playlist. diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b35ba9a3..9dca9a9a7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -39,6 +39,8 @@ And there are a few bug fixes too: * With :ref:`per_disc_numbering` enabled, some metadata sources (notably, the :doc:`/plugins/beatport`) would not set the track number at all. This is fixed. :bug:`2085` +* :doc:`/plugins/play`: Fix $args getting passed verbatim to the play command + if it was set in the configuration but -A or --args was ommitted. The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From c241f09bce7b408c15b70759f96d698537892a2e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 27 Jul 2016 14:56:55 -0400 Subject: [PATCH 1236/2280] Tiny text tweaks for #2144 --- beetsplug/play.py | 1 + docs/changelog.rst | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 7d29f040c..4a2174909 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -91,6 +91,7 @@ class PlayPlugin(BeetsPlugin): else: command_str = u"{} {}".format(command_str, opts.args) else: + # Don't include the marker in the command. command_str = command_str.replace(" " + ARGS_MARKER, "") # Perform search by album and add folders rather than tracks to diff --git a/docs/changelog.rst b/docs/changelog.rst index cba4f6a3c..f2dec37fe 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -39,8 +39,9 @@ And there are a few bug fixes too: * With :ref:`per_disc_numbering` enabled, some metadata sources (notably, the :doc:`/plugins/beatport`) would not set the track number at all. This is fixed. :bug:`2085` -* :doc:`/plugins/play`: Fix $args getting passed verbatim to the play command - if it was set in the configuration but -A or --args was ommitted. +* :doc:`/plugins/play`: Fix ``$args`` getting passed verbatim to the play + command if it was set in the configuration but ``-A`` or ``--args`` was + omitted. The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 8a78de44b01f50642337f8950f23bfbf6d0c2a1e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 27 Jul 2016 14:59:05 -0400 Subject: [PATCH 1237/2280] Changelog wording tweak for #2143 --- docs/changelog.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index da4a24143..f3500b1d2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -25,9 +25,9 @@ The are a couple of small new features: filled-out path template for each file. :bug:`2050` * :doc:`/plugins/embyupdate`: The plugin can now use an API key instead of a password to authenticate with Emby. :bug:`2045` :bug:`2117` -* :doc:`/plugins/acousticbrainz`: The plugin now also adds a ``bpm``, when a - song can be found on AcousticBrainz, this is faster than using the bpm - plugin. +* :doc:`/plugins/acousticbrainz`: The plugin now also adds a ``bpm`` field + when a song can be found on AcousticBrainz, this is faster and more + automatic than using the :doc:`/plugins/bpm`. And there are a few bug fixes too: From ae21d3dcf55d7f3dcb4436eddb31bac0ae055461 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 30 Jul 2016 22:57:56 -0400 Subject: [PATCH 1238/2280] install imagemagick on appveyor (via cholatey) --- appveyor.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/appveyor.yml b/appveyor.yml index cd40e6e82..9ee087a2f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -19,6 +19,7 @@ environment: # Install Tox for running tests. install: + - cinst imagemagick - "%PYTHON%/Scripts/pip.exe install tox" - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" From 15a840953511f93bd7d10e437ffdb871ce96d646 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 31 Jul 2016 02:48:07 -0400 Subject: [PATCH 1239/2280] add python version to beet --version --- beets/ui/commands.py | 2 ++ test/test_ui.py | 1 + 2 files changed, 3 insertions(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index af18a5c0d..fce977b14 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -21,6 +21,7 @@ from __future__ import division, absolute_import, print_function import os import re +from platform import python_version from collections import namedtuple, Counter from itertools import chain @@ -1317,6 +1318,7 @@ default_commands.append(stats_cmd) def show_version(lib, opts, args): print_(u'beets version %s' % beets.__version__) + print_(u'python version {}'.format(python_version())) # Show plugins. names = sorted(p.name for p in plugins.find_plugins()) if names: diff --git a/test/test_ui.py b/test/test_ui.py index 558c00932..160d1dfbc 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1242,6 +1242,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): def test_version(self): l = self.run_with_output(u'version') + self.assertIn(u'python version', l) self.assertIn(u'no plugins loaded', l) # # Need to have plugin loaded From 8b21346fdd4d6b2356afd52b377b33cd70c00486 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 31 Jul 2016 02:56:26 -0400 Subject: [PATCH 1240/2280] add changelog entry for python ver in beet --version --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f3500b1d2..0c2554968 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,6 +28,7 @@ The are a couple of small new features: * :doc:`/plugins/acousticbrainz`: The plugin now also adds a ``bpm`` field when a song can be found on AcousticBrainz, this is faster and more automatic than using the :doc:`/plugins/bpm`. +* ``beet --version`` now includes the python version used to run beets. And there are a few bug fixes too: From 86cfe24d7913245da9850b5a58a56f679bba2314 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 31 Jul 2016 03:59:44 -0400 Subject: [PATCH 1241/2280] depend on six>=1.9 as it adds functions we need 1.9.0 is the release that added the `@py2_unicode_compatible` and the 3.x compatible unittest aliases we rely on --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 9ab145e5d..07545998d 100755 --- a/setup.py +++ b/setup.py @@ -86,7 +86,7 @@ setup( }, install_requires=[ - 'six', + 'six>=1.9', 'mutagen>=1.31', 'munkres', 'unidecode', From 39430764f3e8413bbe9663889df5eb4bf60a854b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 31 Jul 2016 12:36:23 -0400 Subject: [PATCH 1242/2280] Install command for NixOS (fix #2150) --- docs/guides/main.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 2d80eb2fd..4586da8da 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -42,6 +42,8 @@ dropped, and Python 3.x is not yet supported.) $ sudo dnf install beets beets-plugins beets-doc +* On **NixOS**, run ``nix-env -i beets``. + .. _copr: https://copr.fedoraproject.org/coprs/afreof/beets/ .. _dnf package: https://apps.fedoraproject.org/packages/beets .. _SlackBuild: http://slackbuilds.org/repository/14.1/multimedia/beets/ From 70b58c19059bec91c2806202125bd7e6e5a8a7db Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 1 Aug 2016 18:33:59 -0400 Subject: [PATCH 1243/2280] use normpath() in all cases for assert_equal_path This fixes issues with comparing string (via syspath) and bytestring paths on Windows. --- test/_common.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test/_common.py b/test/_common.py index dac6c982a..f2e0ddcf8 100644 --- a/test/_common.py +++ b/test/_common.py @@ -138,10 +138,6 @@ class Assertions(object): def assert_equal_path(self, a, b): """Check that two paths are equal.""" - # The common case. - if a == b: - return - self.assertEqual(util.normpath(a), util.normpath(b), u'paths are not equal: {!r} and {!r}'.format(a, b)) From 3d7c8810e70c618e445f0bd95ae0041d6c4898a6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 2 Aug 2016 08:24:37 -0400 Subject: [PATCH 1244/2280] Deduplicate Mutagen error handling code --- beets/mediafile.py | 55 ++++++++++++++++++---------------------------- 1 file changed, 21 insertions(+), 34 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 2a678f304..42c6cdcb5 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -114,6 +114,24 @@ class MutagenError(UnreadableFileError): Exception.__init__(self, msg) +# Interacting with Mutagen. + +def mutagen_call(action, path, func, *args, **kwargs): + """Call a Mutagen function with appropriate error handling. + """ + try: + return func(*args, **kwargs) + except (mutagen.MutagenError, IOError) as exc: + # Mutagen <1.33 could raise IOError + log.debug(u'{} failed: {}', action, six.text_type(exc)) + raise UnreadableFileError(path) + except Exception as exc: + # Isolate bugs in Mutagen. + log.debug(u'{}', traceback.format_exc()) + log.error(u'uncaught Mutagen exception in {}: {}', action, exc) + raise MutagenError(path, exc) + + # Utility. def _safe_cast(out_type, val): @@ -1361,17 +1379,7 @@ class MediaFile(object): path = syspath(path) self.path = path - try: - self.mgfile = mutagen.File(path) - except (mutagen.MutagenError, IOError) as exc: - # Mutagen <1.33 could raise IOError - log.debug(u'parsing failed: {0}', six.text_type(exc)) - raise UnreadableFileError(path) - except Exception as exc: - # Isolate bugs in Mutagen. - log.debug(u'{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in open: {0}', exc) - raise MutagenError(path, exc) + self.mgfile = mutagen_call('open', path, mutagen.File, path) if self.mgfile is None: # Mutagen couldn't guess the type @@ -1426,34 +1434,13 @@ class MediaFile(object): id3.update_to_v23() kwargs['v2_version'] = 3 - try: - self.mgfile.save(**kwargs) - except (mutagen.MutagenError, IOError) as exc: - # Mutagen <1.33 could raise IOError - log.debug(u'saving failed: {0}', six.text_type(exc)) - raise UnreadableFileError(self.path) - except Exception as exc: - # Isolate bugs in Mutagen. - log.debug(u'{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in save: {0}', exc) - raise MutagenError(self.path, exc) + mutagen_call('save', self.path, self.mgfile.save, **kwargs) def delete(self): """Remove the current metadata tag from the file. May throw `UnreadableFileError`. """ - - try: - self.mgfile.delete() - except (mutagen.MutagenError, IOError) as exc: - # Mutagen <1.33 could raise IOError. - log.debug(u'deleting failed: {0}', six.text_type(exc)) - raise UnreadableFileError(self.path) - except Exception as exc: - # Isolate bugs in Mutagen. - log.debug(u'{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in delete: {0}', exc) - raise MutagenError(self.path, exc) + mutagen_call('delete', self.path, self.mgfile.delete) # Convenient access to the set of available fields. From f001c0c53210f3ae0dc2bff668256b949be27c64 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 2 Aug 2016 08:39:14 -0400 Subject: [PATCH 1245/2280] Require Mutagen 1.33 This simplifies the exception-handling story. It also clarifies exactly what's going on, which I didn't fully realize before: Mutagen *never* raises IOError anymore, even for IO-related errors, so MediaFile doesn't either. --- beets/mediafile.py | 13 +++++++++++-- docs/changelog.rst | 2 +- setup.py | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 42c6cdcb5..6f78914c7 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -118,11 +118,20 @@ class MutagenError(UnreadableFileError): def mutagen_call(action, path, func, *args, **kwargs): """Call a Mutagen function with appropriate error handling. + + `action` is a string describing what the function is trying to do, + and `path` is the relevant filename. The rest of the arguments + describe the callable to invoke. + + We require at least Mutagen 1.33, where `IOError` is *never* used, + neither for internal parsing errors *nor* for ordinary IO error + conditions such as a bad filename. Mutagen-specific parsing errors and IO + errors are reraised as `UnreadableFileError`. Other exceptions + raised inside Mutagen---i.e., bugs---are reraised as `MutagenError`. """ try: return func(*args, **kwargs) - except (mutagen.MutagenError, IOError) as exc: - # Mutagen <1.33 could raise IOError + except mutagen.MutagenError as exc: log.debug(u'{} failed: {}', action, six.text_type(exc)) raise UnreadableFileError(path) except Exception as exc: diff --git a/docs/changelog.rst b/docs/changelog.rst index 0c2554968..56a759a41 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,7 +13,7 @@ Specifically, if you package beets for distribution, here's what you'll want to know: * This version of beets now depends on the `six`_ library. -* We also bumped our minimum required version of `Mutagen`_ to 1.31 (from +* We also bumped our minimum required version of `Mutagen`_ to 1.33 (from 1.27). * Please don't package beets as a Python 3 application *yet*, even though some things may appear to work under Python 3.4 and later. diff --git a/setup.py b/setup.py index 07545998d..0610d2226 100755 --- a/setup.py +++ b/setup.py @@ -87,7 +87,7 @@ setup( install_requires=[ 'six>=1.9', - 'mutagen>=1.31', + 'mutagen>=1.33', 'munkres', 'unidecode', 'musicbrainzngs>=0.4', From 304df823613533706a3ab6e92cc2d66de56aa9ed Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 4 Aug 2016 17:10:27 -0400 Subject: [PATCH 1246/2280] rename/move ui._arg_encoding to util.arg_encoding We use this for more than ui concerns, so it should be in util. It is also no longer marked as a "private" method. --- beets/ui/__init__.py | 15 +-------------- beets/util/__init__.py | 13 +++++++++++++ beetsplug/convert.py | 8 ++++---- beetsplug/hook.py | 5 ++--- test/helper.py | 5 ++--- test/test_convert.py | 3 +-- test/test_ui.py | 2 +- 7 files changed, 24 insertions(+), 27 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index e338e46df..71896ab3b 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -20,7 +20,6 @@ CLI commands are implemented in the ui.commands module. from __future__ import division, absolute_import, print_function -import locale import optparse import textwrap import sys @@ -108,24 +107,12 @@ def _stream_encoding(stream, default='utf8'): return stream.encoding or default -def _arg_encoding(): - """Get the encoding for command-line arguments (and other OS - locale-sensitive strings). - """ - try: - return locale.getdefaultlocale()[1] or 'utf8' - except ValueError: - # Invalid locale environment variable setting. To avoid - # failing entirely for no good reason, assume UTF-8. - return 'utf8' - - def decargs(arglist): """Given a list of command-line argument bytestrings, attempts to decode them to Unicode strings when running under Python 2. """ if six.PY2: - return [s.decode(_arg_encoding()) for s in arglist] + return [s.decode(util.arg_encoding()) for s in arglist] else: return arglist diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 17cfc4f0e..ba3070e82 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import os import sys +import locale import re import shutil import fnmatch @@ -302,6 +303,18 @@ def components(path): return comps +def arg_encoding(): + """Get the encoding for command-line arguments (and other OS + locale-sensitive strings). + """ + try: + return locale.getdefaultlocale()[1] or 'utf8' + except ValueError: + # Invalid locale environment variable setting. To avoid + # failing entirely for no good reason, assume UTF-8. + return 'utf8' + + def _fsencoding(): """Get the system's filesystem encoding. On Windows, this is always UTF-8 (not MBCS). diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 10d5d9a18..fc1c0588d 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -185,9 +185,9 @@ class ConvertPlugin(BeetsPlugin): # Substitute $source and $dest in the argument list. if not six.PY2: - command = command.decode(ui._arg_encoding(), 'surrogateescape') - source = source.decode(ui._arg_encoding(), 'surrogateescape') - dest = dest.decode(ui._arg_encoding(), 'surrogateescape') + command = command.decode(util.arg_encoding(), 'surrogateescape') + source = source.decode(util.arg_encoding(), 'surrogateescape') + dest = dest.decode(util.arg_encoding(), 'surrogateescape') args = shlex.split(command) encode_cmd = [] @@ -199,7 +199,7 @@ class ConvertPlugin(BeetsPlugin): if six.PY2: encode_cmd.append(args[i]) else: - encode_cmd.append(args[i].encode(ui._arg_encoding())) + encode_cmd.append(args[i].encode(util.arg_encoding())) if pretend: self._log.info(u' '.join(ui.decargs(args))) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 596c969d0..ff33f0ae4 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -20,8 +20,7 @@ import subprocess import six from beets.plugins import BeetsPlugin -from beets.ui import _arg_encoding -from beets.util import shlex_split +from beets.util import shlex_split, arg_encoding class CodingFormatter(string.Formatter): @@ -99,7 +98,7 @@ class HookPlugin(BeetsPlugin): # Use a string formatter that works on Unicode strings. if six.PY2: - formatter = CodingFormatter(_arg_encoding()) + formatter = CodingFormatter(arg_encoding()) else: formatter = string.Formatter() diff --git a/test/helper.py b/test/helper.py index 49216f697..f6b0d5ecc 100644 --- a/test/helper.py +++ b/test/helper.py @@ -51,7 +51,6 @@ from beets.library import Library, Item, Album from beets import importer from beets.autotag.hooks import AlbumInfo, TrackInfo from beets.mediafile import MediaFile, Image -from beets.ui import _arg_encoding from beets import util # TODO Move AutotagMock here @@ -126,10 +125,10 @@ def _convert_args(args): for i, elem in enumerate(args): if six.PY2: if isinstance(elem, six.text_type): - args[i] = elem.encode(_arg_encoding()) + args[i] = elem.encode(util.arg_encoding()) else: if isinstance(elem, bytes): - args[i] = elem.decode(_arg_encoding()) + args[i] = elem.decode(util.arg_encoding()) return args diff --git a/test/test_convert.py b/test/test_convert.py index 1f1b1a7fb..8d75fbb57 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -24,7 +24,6 @@ from test.helper import control_stdin from beets.mediafile import MediaFile from beets import util -from beets import ui class TestHelper(helper.TestHelper): @@ -119,7 +118,7 @@ class ConvertCommand(object): """Run the `convert` command on a given path.""" # The path is currently a filesystem bytestring. Convert it to # an argument bytestring. - path = path.decode(util._fsencoding()).encode(ui._arg_encoding()) + path = path.decode(util._fsencoding()).encode(util.arg_encoding()) args = args + (b'path:' + path,) return self.run_command('convert', *args) diff --git a/test/test_ui.py b/test/test_ui.py index 160d1dfbc..c7de8caab 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1209,7 +1209,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): def test_format_option_unicode(self): l = self.run_with_output(b'ls', b'-f', - u'caf\xe9'.encode(ui._arg_encoding())) + u'caf\xe9'.encode(util.arg_encoding())) self.assertEqual(l, u'caf\xe9\n') def test_root_format_option(self): From 5b3cd4460821e02c72954103816452768aa372b6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 7 Aug 2016 04:04:34 -0400 Subject: [PATCH 1247/2280] add coding: utf-8 magic comment to every .py file --- beetsplug/beatport.py | 1 + beetsplug/edit.py | 1 + beetsplug/hook.py | 1 + docs/serve.py | 1 + test/rsrc/convert_stub.py | 1 + test/test_edit.py | 1 + test/test_hook.py | 1 + 7 files changed, 7 insertions(+) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 1ea1aea4e..463858c8c 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 4a55e59ed..c97e8cd32 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016 # diff --git a/beetsplug/hook.py b/beetsplug/hook.py index ff33f0ae4..833f0feaa 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Adrian Sampson. # diff --git a/docs/serve.py b/docs/serve.py index d54c8b64d..2bbf6b623 100644 --- a/docs/serve.py +++ b/docs/serve.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 9fb044b4f..1c4b7200c 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- """A tiny tool used to test the `convert` plugin. It copies a file and appends a specified text tag. diff --git a/test/test_edit.py b/test/test_edit.py index 08a1c3d1f..2c76997a1 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson and Diego Moreda. # diff --git a/test/test_hook.py b/test/test_hook.py index 9985fbbae..cd6b2734f 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # From 08cd22834ba3b4f01f425787dc1419ea656e3f6d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 7 Aug 2016 04:09:58 -0400 Subject: [PATCH 1248/2280] add flake8-coding to our tox config Now we can enforce that all py files have the coding magic comment with utf-8. --- setup.cfg | 1 + tox.ini | 1 + 2 files changed, 2 insertions(+) diff --git a/setup.cfg b/setup.cfg index 8050dd345..d11c57507 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,6 +4,7 @@ logging-clear-handlers=1 [flake8] min-version=2.7 +accept-encodings=utf-8 # Default pyflakes errors we ignore: # - E241: missing whitespace after ',' (used to align visually) # - E221: multiple spaces before operator (used to align visually) diff --git a/tox.ini b/tox.ini index 598368daa..648054b89 100644 --- a/tox.ini +++ b/tox.ini @@ -27,6 +27,7 @@ deps = [_flake8] deps = flake8 + flake8-coding flake8-future-import pep8-naming files = beets beetsplug beet test setup.py docs From 303627e44f32d5ebec5c3f84059618bc102eaa5d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 7 Aug 2016 05:17:15 -0400 Subject: [PATCH 1249/2280] Read and write edit plugin yaml as utf-8 --- beetsplug/edit.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index c97e8cd32..5c403adde 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -24,6 +24,7 @@ from beets.dbcore import types from beets.importer import action from beets.ui.commands import _do_query, PromptChoice from copy import deepcopy +import codecs import subprocess import yaml from tempfile import NamedTemporaryFile @@ -244,7 +245,11 @@ class EditPlugin(plugins.BeetsPlugin): old_data = [flatten(o, fields) for o in objs] # Set up a temporary file with the initial data for editing. - new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) + if six.PY2: + new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) + else: + new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False, + encoding='utf-8') old_str = dump(old_data) new.write(old_str) new.close() @@ -257,7 +262,7 @@ class EditPlugin(plugins.BeetsPlugin): # Read the data back after editing and check whether anything # changed. - with open(new.name) as f: + with codecs.open(new.name, encoding='utf-8') as f: new_str = f.read() if new_str == old_str: ui.print_(u"No changes; aborting.") From 47bddb394c610beb6f582fee72706ef27e4eaf87 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 8 Aug 2016 23:59:54 -0400 Subject: [PATCH 1250/2280] decode yaml dumped data as utf-8 in edit plugin for PY2 Yaml doesn't return a true unicode string even with `allow_unicode` passed to `safe_dump_all`. --- beetsplug/edit.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 5c403adde..7f35e49bc 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -252,6 +252,8 @@ class EditPlugin(plugins.BeetsPlugin): encoding='utf-8') old_str = dump(old_data) new.write(old_str) + if six.PY2: + old_str = old_str.decode('utf-8') new.close() # Loop until we have parseable data and the user confirms. From fcbfce39841e9c7e29dfd7a18f4edfbcf8035db5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 9 Aug 2016 00:33:38 -0400 Subject: [PATCH 1251/2280] replace deprecated log.warn() with log.warning() --- beets/importer.py | 14 +++++++------- beets/plugins.py | 4 ++-- beets/ui/commands.py | 14 +++++++------- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 8 ++++---- beetsplug/chroma.py | 2 +- beetsplug/edit.py | 6 +++--- beetsplug/fetchart.py | 8 ++++---- beetsplug/lyrics.py | 12 ++++++------ beetsplug/permissions.py | 2 +- beetsplug/smartplaylist.py | 6 +++--- beetsplug/spotify.py | 12 ++++++------ beetsplug/the.py | 6 +++--- beetsplug/zero.py | 12 +++++++----- 14 files changed, 55 insertions(+), 53 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 6a1be6ddc..2c1d07c5c 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -362,8 +362,8 @@ class ImportSession(object): # Either accept immediately or prompt for input to decide. if self.want_resume is True or \ self.should_resume(toppath): - log.warn(u'Resuming interrupted import of {0}', - util.displayable_path(toppath)) + log.warning(u'Resuming interrupted import of {0}', + util.displayable_path(toppath)) self._is_resuming[toppath] = True else: # Clear progress; we're starting from the top. @@ -1148,8 +1148,8 @@ class ImportTaskFactory(object): if not (self.session.config['move'] or self.session.config['copy']): - log.warn(u"Archive importing requires either " - u"'copy' or 'move' to be enabled.") + log.warning(u"Archive importing requires either " + u"'copy' or 'move' to be enabled.") return log.debug(u'Extracting archive: {0}', @@ -1179,7 +1179,7 @@ class ImportTaskFactory(object): # Silently ignore non-music files. pass elif isinstance(exc.reason, mediafile.UnreadableFileError): - log.warn(u'unreadable file: {0}', displayable_path(path)) + log.warning(u'unreadable file: {0}', displayable_path(path)) else: log.error(u'error reading {0}: {1}', displayable_path(path), exc) @@ -1204,8 +1204,8 @@ def read_tasks(session): skipped += task_factory.skipped if not task_factory.imported: - log.warn(u'No files imported from {0}', - displayable_path(toppath)) + log.warning(u'No files imported from {0}', + displayable_path(toppath)) # Show skipped directories (due to incremental/resume). if skipped: diff --git a/beets/plugins.py b/beets/plugins.py index 8fe4c6d0c..6c48d47d2 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -255,7 +255,7 @@ def load_plugins(names=()): except ImportError as exc: # Again, this is hacky: if exc.args[0].endswith(' ' + name): - log.warn(u'** plugin {0} not found', name) + log.warning(u'** plugin {0} not found', name) else: raise else: @@ -265,7 +265,7 @@ def load_plugins(names=()): _classes.add(obj) except: - log.warn( + log.warning( u'** error loading plugin {}:\n{}', name, traceback.format_exc(), diff --git a/beets/ui/commands.py b/beets/ui/commands.py index fce977b14..6ea9872d3 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -823,8 +823,8 @@ class TerminalImportSession(importer.ImportSession): """Decide what to do when a new album or item seems similar to one that's already in the library. """ - log.warn(u"This {0} is already in the library!", - (u"album" if task.is_album else u"item")) + log.warning(u"This {0} is already in the library!", + (u"album" if task.is_album else u"item")) if config['import']['quiet']: # In quiet mode, don't prompt -- just skip. @@ -902,9 +902,9 @@ class TerminalImportSession(importer.ImportSession): # Keep the first of the choices, removing the rest. dup_choices = [c for c in all_choices if c.short == short] for c in dup_choices[1:]: - log.warn(u"Prompt choice '{0}' removed due to conflict " - u"with '{1}' (short letter: '{2}')", - c.long, dup_choices[0].long, c.short) + log.warning(u"Prompt choice '{0}' removed due to conflict " + u"with '{1}' (short letter: '{2}')", + c.long, dup_choices[0].long, c.short) extra_choices.remove(c) return extra_choices @@ -1667,8 +1667,8 @@ def print_completion(*args): for line in completion_script(default_commands + plugins.commands()): print_(line, end=u'') if not any(map(os.path.isfile, BASH_COMPLETION_PATHS)): - log.warn(u'Warning: Unable to find the bash-completion package. ' - u'Command line completion might not work.') + log.warning(u'Warning: Unable to find the bash-completion package. ' + u'Command line completion might not work.') BASH_COMPLETION_PATHS = map(syspath, [ u'/etc/bash_completion', diff --git a/beets/util/__init__.py b/beets/util/__init__.py index ba3070e82..5732c81b5 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -169,7 +169,7 @@ def sorted_walk(path, ignore=(), ignore_hidden=False, logger=None): contents = os.listdir(syspath(path)) except OSError as exc: if logger: - logger.warn(u'could not list directory {0}: {1}'.format( + logger.warning(u'could not list directory {0}: {1}'.format( displayable_path(path), exc.strerror )) return diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index e15ada3af..c1382b5bf 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -96,8 +96,8 @@ def im_resize(maxwidth, path_in, path_out=None): util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: - log.warn(u'artresizer: IM convert failed for {0}', - util.displayable_path(path_in)) + log.warning(u'artresizer: IM convert failed for {0}', + util.displayable_path(path_in)) return path_in return path_out @@ -124,7 +124,7 @@ def im_getsize(path_in): try: out = util.command_output(cmd) except subprocess.CalledProcessError as exc: - log.warn(u'ImageMagick size query failed') + log.warning(u'ImageMagick size query failed') log.debug( u'`convert` exited with (status {}) when ' u'getting size with command {}:\n{}', @@ -134,7 +134,7 @@ def im_getsize(path_in): try: return tuple(map(int, out.split(b' '))) except IndexError: - log.warn(u'Could not understand IM output: {0!r}', out) + log.warning(u'Could not understand IM output: {0!r}', out) BACKEND_GET_SIZE = { diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index b45bcfe3e..cd0a77593 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -236,7 +236,7 @@ def submit_items(log, userkey, items, chunksize=64): try: acoustid.submit(API_KEY, userkey, data) except acoustid.AcoustidError as exc: - log.warn(u'acoustid submission error: {0}', exc) + log.warning(u'acoustid submission error: {0}', exc) del data[:] for item in items: diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 7f35e49bc..1411c0401 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -319,8 +319,8 @@ class EditPlugin(plugins.BeetsPlugin): are temporary. """ if len(old_data) != len(new_data): - self._log.warn(u'number of objects changed from {} to {}', - len(old_data), len(new_data)) + self._log.warning(u'number of objects changed from {} to {}', + len(old_data), len(new_data)) obj_by_id = {o.id: o for o in objs} ignore_fields = self.config['ignore_fields'].as_str_seq() @@ -330,7 +330,7 @@ class EditPlugin(plugins.BeetsPlugin): forbidden = False for key in ignore_fields: if old_dict.get(key) != new_dict.get(key): - self._log.warn(u'ignoring object whose {} changed', key) + self._log.warning(u'ignoring object whose {} changed', key) forbidden = True break if forbidden: diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index aaa18dd02..4db22397e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -265,10 +265,10 @@ class RemoteArtSource(ArtSource): ext = b'.' + CONTENT_TYPES[real_ct][0] if real_ct != ct: - self._log.warn(u'Server specified {}, but returned a ' - u'{} image. Correcting the extension ' - u'to {}', - ct, real_ct, ext) + self._log.warning(u'Server specified {}, but returned a ' + u'{} image. Correcting the extension ' + u'to {}', + ct, real_ct, ext) suffix = py3_path(ext) with NamedTemporaryFile(suffix=suffix, delete=False) as fh: diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 4cc8cb441..32473dd10 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -624,9 +624,9 @@ class LyricsPlugin(plugins.BeetsPlugin): u'no API key configured.') sources.remove('google') elif not HAS_BEAUTIFUL_SOUP: - self._log.warn(u'To use the google lyrics source, you must ' - u'install the beautifulsoup4 module. See the ' - u'documentation for further details.') + self._log.warning(u'To use the google lyrics source, you must ' + u'install the beautifulsoup4 module. See ' + u'the documentation for further details.') sources.remove('google') self.config['bing_lang_from'] = [ @@ -634,9 +634,9 @@ class LyricsPlugin(plugins.BeetsPlugin): self.bing_auth_token = None if not HAS_LANGDETECT and self.config['bing_client_secret'].get(): - self._log.warn(u'To use bing translations, you need to ' - u'install the langdetect module. See the ' - u'documentation for further details.') + self._log.warning(u'To use bing translations, you need to ' + u'install the langdetect module. See the ' + u'documentation for further details.') self.backends = [self.SOURCE_BACKENDS[source](self.config, self._log) for source in sources] diff --git a/beetsplug/permissions.py b/beetsplug/permissions.py index 9bced8396..dd9e09843 100644 --- a/beetsplug/permissions.py +++ b/beetsplug/permissions.py @@ -39,7 +39,7 @@ def assert_permissions(path, permission, log): `check_permissions`. """ if not check_permissions(util.syspath(path), permission): - log.warn( + log.warning( u'could not set permissions on {}', util.displayable_path(path), ) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 11c5530b2..416dc37f5 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -98,7 +98,7 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self.config['playlists'].get(list): if 'name' not in playlist: - self._log.warn(u"playlist configuration is missing name") + self._log.warning(u"playlist configuration is missing name") continue playlist_data = (playlist['name'],) @@ -134,8 +134,8 @@ class SmartPlaylistPlugin(BeetsPlugin): playlist_data += (query_and_sort,) except ParsingError as exc: - self._log.warn(u"invalid query in playlist {}: {}", - playlist['name'], exc) + self._log.warning(u"invalid query in playlist {}: {}", + playlist['name'], exc) continue self._unmatched_playlists.add(playlist_data) diff --git a/beetsplug/spotify.py b/beetsplug/spotify.py index 619faebbc..36231f297 100644 --- a/beetsplug/spotify.py +++ b/beetsplug/spotify.py @@ -63,8 +63,8 @@ class SpotifyPlugin(BeetsPlugin): self.config['show_failures'].set(True) if self.config['mode'].get() not in ['list', 'open']: - self._log.warn(u'{0} is not a valid mode', - self.config['mode'].get()) + self._log.warning(u'{0} is not a valid mode', + self.config['mode'].get()) return False self.opts = opts @@ -154,9 +154,9 @@ class SpotifyPlugin(BeetsPlugin): self._log.info(u'track: {0}', track) self._log.info(u'') else: - self._log.warn(u'{0} track(s) did not match a Spotify ID;\n' - u'use --show-failures to display', - failure_count) + self._log.warning(u'{0} track(s) did not match a Spotify ID;\n' + u'use --show-failures to display', + failure_count) return results @@ -172,4 +172,4 @@ class SpotifyPlugin(BeetsPlugin): for item in ids: print(self.open_url + item) else: - self._log.warn(u'No Spotify tracks found from beets query') + self._log.warning(u'No Spotify tracks found from beets query') diff --git a/beetsplug/the.py b/beetsplug/the.py index c746f88b0..cfb583ced 100644 --- a/beetsplug/the.py +++ b/beetsplug/the.py @@ -54,14 +54,14 @@ class ThePlugin(BeetsPlugin): self._log.error(u'invalid pattern: {0}', p) else: if not (p.startswith('^') or p.endswith('$')): - self._log.warn(u'warning: \"{0}\" will not ' - u'match string start/end', p) + self._log.warning(u'warning: \"{0}\" will not ' + u'match string start/end', p) if self.config['a']: self.patterns = [PATTERN_A] + self.patterns if self.config['the']: self.patterns = [PATTERN_THE] + self.patterns if not self.patterns: - self._log.warn(u'no patterns defined!') + self._log.warning(u'no patterns defined!') def unthe(self, text, pattern): """Moves pattern in the path format string or strips it diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 80925741b..1401b11de 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -51,7 +51,9 @@ class ZeroPlugin(BeetsPlugin): # We'll only handle `fields` or `keep_fields`, but not both. if self.config['fields'] and self.config['keep_fields']: - self._log.warn(u'cannot blacklist and whitelist at the same time') + self._log.warning( + u'cannot blacklist and whitelist at the same time' + ) # Blacklist mode. if self.config['fields']: @@ -84,8 +86,8 @@ class ZeroPlugin(BeetsPlugin): self._log.error(u'invalid field: {0}', field) continue if mode == 'fields' and field in ('id', 'path', 'album_id'): - self._log.warn(u'field \'{0}\' ignored, zeroing ' - u'it would be dangerous', field) + self._log.warning(u'field \'{0}\' ignored, zeroing ' + u'it would be dangerous', field) continue def set_pattern(self, field): @@ -102,7 +104,7 @@ class ZeroPlugin(BeetsPlugin): def import_task_choice_event(self, session, task): """Listen for import_task_choice event.""" if task.choice_flag == action.ASIS and not self.warned: - self._log.warn(u'cannot zero in \"as-is\" mode') + self._log.warning(u'cannot zero in \"as-is\" mode') self.warned = True # TODO request write in as-is mode @@ -123,7 +125,7 @@ class ZeroPlugin(BeetsPlugin): by `self.patterns`. """ if not self.patterns: - self._log.warn(u'no fields, nothing to do') + self._log.warning(u'no fields, nothing to do') return for field, patterns in self.patterns.items(): From d41949d326d321a67ff0ad8620ee21a34bd1f2ff Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 9 Aug 2016 01:15:28 -0400 Subject: [PATCH 1252/2280] close files we open, but forgot to close This fixes all the obvious `ResourceWarning`s seen in the tests --- beetsplug/lastgenre/__init__.py | 4 ++-- test/test_mediafile_edge.py | 5 +++-- test/test_play.py | 5 +++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index d6f4c08a3..cbaa972ca 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -141,8 +141,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): c14n_filename = C14N_TREE if c14n_filename: c14n_filename = normpath(c14n_filename) - genres_file = codecs.open(c14n_filename, 'r', encoding='utf-8') - genres_tree = yaml.load(genres_file) + with codecs.open(c14n_filename, 'r', encoding='utf-8') as f: + genres_tree = yaml.load(f) flatten_tree(genres_tree, [], self.c14n_branches) @property diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 173a0d063..fea7aebad 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -87,8 +87,9 @@ class EdgeTest(unittest.TestCase): # such aren't recognized by imghdr. Ensure that this still works thanks # to our own follow up mimetype detection based on # https://github.com/file/file/blob/master/magic/Magdir/jpeg#L12 - f = open(os.path.join(_common.RSRC, b'only-magic-bytes.jpg'), 'rb') - jpg_data = f.read() + magic_bytes_file = os.path.join(_common.RSRC, b'only-magic-bytes.jpg') + with open(magic_bytes_file, 'rb') as f: + jpg_data = f.read() self.assertEqual( beets.mediafile._image_mime_type(jpg_data), 'image/jpeg') diff --git a/test/test_play.py b/test/test_play.py index 38524aa7d..259e59383 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -88,10 +88,11 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.run_command('play', '-a', 'nice') open_mock.assert_called_once_with(ANY, open_anything()) - playlist = open(open_mock.call_args[0][0][0], 'rb') + with open(open_mock.call_args[0][0][0], 'rb') as f: + playlist = f.read().decode('utf-8') self.assertEqual(u'{}\n'.format( os.path.dirname(self.item.path.decode('utf-8'))), - playlist.read().decode('utf-8')) + playlist) def test_raw(self, open_mock): self.config['play']['raw'] = True From d32aa0015425a97657bf7ac8b660e1bcf83c7041 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 9 Aug 2016 04:34:40 -0400 Subject: [PATCH 1253/2280] remove bytes() on maxwidth in artresizer This would definitely break on py3. --- beets/util/artresizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index c1382b5bf..bc9f4409b 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -43,7 +43,7 @@ def resize_url(url, maxwidth): """ return '{0}?{1}'.format(PROXY_URL, urlencode({ 'url': url.replace('http://', ''), - 'w': bytes(maxwidth), + 'w': maxwidth, })) From fb78830788421a57fba6daa4b4c468c53288e7ff Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 9 Aug 2016 05:17:53 -0400 Subject: [PATCH 1254/2280] fix incorrect bytes() usages in replaygain We encode the method and gain offset values to ascii. --- beetsplug/replaygain.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index fe108aec9..884339387 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -102,7 +102,7 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = b'--' + bytes(config['method'].as_str()) + self.method = b'--' + config['method'].as_str().encode('ascii') cmd = b'bs1770gain' try: @@ -341,7 +341,7 @@ class CommandBackend(Backend): else: # Disable clipping warning. cmd = cmd + [b'-c'] - cmd = cmd + [b'-d', bytes(self.gain_offset)] + cmd = cmd + [b'-d', str(self.gain_offset).encode('ascii')] cmd = cmd + [syspath(i.path) for i in items] self._log.debug(u'analyzing {0} files', len(items)) From bcc77f747b39209c665683ee1d6bf30066fd4ac6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 8 Aug 2016 07:07:44 -0400 Subject: [PATCH 1255/2280] encode args before decode in convert_stub.py for py 3 We encode the args from `sys.argv` with `util.arg_encoding` to make sure we have paths that cleanly open when running `convert_stub.py` on Windows --- test/rsrc/convert_stub.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 1c4b7200c..0f4a20f30 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -6,9 +6,16 @@ a specified text tag. """ from __future__ import division, absolute_import, print_function +from os.path import dirname, abspath +import six import sys import platform +beets_src = dirname(dirname(dirname(abspath(__file__)))) +sys.path.insert(0, beets_src) + +from beets.util import arg_encoding # noqa: E402 + def convert(in_file, out_file, tag): """Copy `in_file` to `out_file` and append the string `tag`. @@ -20,8 +27,11 @@ def convert(in_file, out_file, tag): # On Windows, use Unicode paths. (The test harness gives them to us # as UTF-8 bytes.) if platform.system() == 'Windows': - in_file = in_file.decode('utf8') - out_file = out_file.decode('utf8') + if not six.PY2: + in_file = in_file.encode(arg_encoding()) + out_file = out_file.encode(arg_encoding()) + in_file = in_file.decode('utf-8') + out_file = out_file.decode('utf-8') with open(out_file, 'wb') as out_f: with open(in_file, 'rb') as in_f: From 10d7a6f46ac58d40bc12661d943d2e3ae24761cd Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 10 Aug 2016 21:28:06 -0400 Subject: [PATCH 1256/2280] add -y to cinst command in appveyor.yml [ci skip] --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 9ee087a2f..855561e69 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -19,7 +19,7 @@ environment: # Install Tox for running tests. install: - - cinst imagemagick + - cinst imagemagick -y - "%PYTHON%/Scripts/pip.exe install tox" - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" From c26266cab060b0f7cfc8966f2a67c407604ad8f4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 4 Aug 2016 23:38:21 -0400 Subject: [PATCH 1257/2280] convert byte args to string on PY3 in command_output The strings are surrogateescaped to make sure we can get the bytes representation back --- beets/util/__init__.py | 24 ++++++++++++++++++++++-- test/test_util.py | 13 +++++++++++-- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5732c81b5..c2d5c9334 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -737,10 +737,28 @@ def cpu_count(): return 1 +def convert_command_args(args): + """Convert command arguments to bytestrings on Python 2 and + surrogate-escaped strings on Python 3.""" + assert isinstance(args, list) + + def convert(arg): + if six.PY2: + if isinstance(arg, six.text_type): + arg = arg.encode(arg_encoding()) + else: + if isinstance(arg, bytes): + arg = arg.decode(arg_encoding(), 'surrogateescape') + return arg + + return [convert(a) for a in args] + + def command_output(cmd, shell=False): """Runs the command and returns its output after it has exited. - ``cmd`` is a list of byte string arguments starting with the command names. + ``cmd`` is a list of arguments starting with the command names. The + arguments are bytes on Unix and strings on Windows. If ``shell`` is true, ``cmd`` is assumed to be a string and passed to a shell to execute. @@ -751,6 +769,8 @@ def command_output(cmd, shell=False): This replaces `subprocess.check_output` which can have problems if lots of output is sent to stderr. """ + cmd = convert_command_args(cmd) + proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, @@ -762,7 +782,7 @@ def command_output(cmd, shell=False): if proc.returncode: raise subprocess.CalledProcessError( returncode=proc.returncode, - cmd=b' '.join(cmd), + cmd=' '.join(cmd), output=stdout + stderr, ) return stdout diff --git a/test/test_util.py b/test/test_util.py index f4c2eca80..490992039 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -104,6 +104,15 @@ class UtilTest(unittest.TestCase): ]) self.assertEqual(p, u'foo/_/bar') + @unittest.skipIf(six.PY2, 'surrogateescape error handler not available' + 'on Python 2') + def test_convert_command_args_keeps_undecodeable_bytes(self): + arg = b'\x82' # non-ascii bytes + cmd_args = util.convert_command_args([arg]) + + self.assertEqual(cmd_args[0], + arg.decode(util.arg_encoding(), 'surrogateescape')) + @patch('beets.util.subprocess.Popen') def test_command_output(self, mock_popen): def popen_fail(*args, **kwargs): @@ -113,9 +122,9 @@ class UtilTest(unittest.TestCase): mock_popen.side_effect = popen_fail with self.assertRaises(subprocess.CalledProcessError) as exc_context: - util.command_output([b"taga", b"\xc3\xa9"]) + util.command_output(['taga', '\xc3\xa9']) self.assertEqual(exc_context.exception.returncode, 1) - self.assertEqual(exc_context.exception.cmd, b"taga \xc3\xa9") + self.assertEqual(exc_context.exception.cmd, 'taga \xc3\xa9') class PathConversionTest(_common.TestCase): From 72a55957a9467d4f84cd2fe9564ad4c424c64b1f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 8 Aug 2016 22:22:36 -0400 Subject: [PATCH 1258/2280] remove allow_failures for python 3.x from appveyor --- appveyor.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 855561e69..d28146402 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -25,9 +25,3 @@ install: test_script: - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV%" - -# Allow all failures for now: the tests don't yet pass! -matrix: - allow_failures: - - TOX_ENV: py34-test - - TOX_ENV: py35-test From 86d2129c5261da4f74e0ef35eb2679d59f9f48ec Mon Sep 17 00:00:00 2001 From: arogl Date: Fri, 12 Aug 2016 14:48:55 +1000 Subject: [PATCH 1259/2280] Spelling update --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 9eca1eae9..a31c575d3 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -84,7 +84,7 @@ class DiscogsPlugin(BeetsPlugin): token, secret) def reset_auth(self): - """Delete toke file & redo the auth steps. + """Delete token file & redo the auth steps. """ os.remove(self._tokenfile()) self.setup() From 0833c820757aa748567eb19251bdebc1303eb74b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 12 Aug 2016 19:59:07 +0000 Subject: [PATCH 1260/2280] web: Fix a crash related to byte paths on Python 3 --- beetsplug/web/__init__.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index baf83f7ca..07e68638b 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -203,8 +203,11 @@ def all_items(): @app.route('/item//file') def item_file(item_id): item = g.lib.get_item(item_id) - response = flask.send_file(item.path, as_attachment=True, - attachment_filename=os.path.basename(item.path)) + response = flask.send_file( + util.py3_path(item.path), + as_attachment=True, + attachment_filename=os.path.basename(item.path), + ) response.headers['Content-Length'] = os.path.getsize(item.path) return response From 162bf6a594a2804da7edca36f5e727abe0032946 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 13 Aug 2016 09:54:25 -0400 Subject: [PATCH 1261/2280] Fix path handling in hidden module Probably fixes #2168. --- beets/util/hidden.py | 15 ++++++--------- docs/changelog.rst | 2 ++ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/beets/util/hidden.py b/beets/util/hidden.py index 11e3691d6..ed97f2bfc 100644 --- a/beets/util/hidden.py +++ b/beets/util/hidden.py @@ -20,7 +20,7 @@ import os import stat import ctypes import sys -import six +import beets.util def _is_hidden_osx(path): @@ -28,7 +28,7 @@ def _is_hidden_osx(path): This uses os.lstat to work out if a file has the "hidden" flag. """ - file_stat = os.lstat(path) + file_stat = os.lstat(beets.util.syspath(path)) if hasattr(file_stat, 'st_flags') and hasattr(stat, 'UF_HIDDEN'): return bool(file_stat.st_flags & stat.UF_HIDDEN) @@ -46,7 +46,7 @@ def _is_hidden_win(path): hidden_mask = 2 # Retrieve the attributes for the file. - attrs = ctypes.windll.kernel32.GetFileAttributesW(path) + attrs = ctypes.windll.kernel32.GetFileAttributesW(beets.util.syspath(path)) # Ensure we have valid attribues and compare them against the mask. return attrs >= 0 and attrs & hidden_mask @@ -57,11 +57,12 @@ def _is_hidden_dot(path): Files starting with a dot are seen as "hidden" files on Unix-based OSes. """ - return os.path.basename(path).startswith('.') + return os.path.basename(path).startswith(b'.') def is_hidden(path): - """Return whether or not a file is hidden. + """Return whether or not a file is hidden. `path` should be a + bytestring filename. This method works differently depending on the platform it is called on. @@ -74,10 +75,6 @@ def is_hidden(path): On any other operating systems (i.e. Linux), it uses `is_hidden_dot` to work out if a file is hidden. """ - # Convert the path to unicode if it is not already. - if not isinstance(path, six.text_type): - path = path.decode('utf-8') - # Run platform specific functions depending on the platform if sys.platform == 'darwin': return _is_hidden_osx(path) or _is_hidden_dot(path) diff --git a/docs/changelog.rst b/docs/changelog.rst index 56a759a41..c3f5ba1bb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -46,6 +46,8 @@ And there are a few bug fixes too: * :doc:`/plugins/play`: Fix ``$args`` getting passed verbatim to the play command if it was set in the configuration but ``-A`` or ``--args`` was omitted. +* With :ref:`ignore_hidden` enabled, non-UTF-8 filenames would cause a crash. + This is fixed. :bug:`2168` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 7061f7ff47f7ba1052bef3a382d70bcae0b3dadc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 13 Aug 2016 10:11:52 -0400 Subject: [PATCH 1262/2280] Use byte path consistently in hidden test (#2168) --- test/test_hidden.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_hidden.py b/test/test_hidden.py index 316779f4d..cb673a64a 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -21,6 +21,7 @@ from test._common import unittest import sys import tempfile from beets.util import hidden +from beets import util import subprocess import errno import ctypes @@ -71,7 +72,8 @@ class HiddenFileTest(unittest.TestCase): return with tempfile.NamedTemporaryFile(prefix='.tmp') as f: - self.assertTrue(hidden.is_hidden(f.name)) + fn = util.bytestring_path(f.name) + self.assertTrue(hidden.is_hidden(fn)) def suite(): From e1d598aced0385c224f513c53eb3b897c0f18146 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 16 Aug 2016 20:48:46 -0400 Subject: [PATCH 1263/2280] Less verbose metavariable in --search-id help --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 6ea9872d3..af05084fa 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1046,7 +1046,7 @@ import_cmd.parser.add_option( ) import_cmd.parser.add_option( u'-S', u'--search-id', dest='search_ids', action='append', - metavar='BACKEND_ID', + metavar='ID', help=u'restrict matching to a specific metadata backend ID' ) import_cmd.func = import_func From 4c4d8cff60b574296194075bce54a05d017f053b Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 17 Aug 2016 02:15:20 -0400 Subject: [PATCH 1264/2280] s/get(list)/as_str_seq() for keys in duplicates plugin stolen from @sampsyo in the click branch --- beetsplug/duplicates.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 89bf78a2a..3c3a8de43 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -118,7 +118,7 @@ class DuplicatesPlugin(BeetsPlugin): delete = self.config['delete'].get(bool) fmt = self.config['format'].get(str) full = self.config['full'].get(bool) - keys = self.config['keys'].get(list) + keys = self.config['keys'].as_str_seq() merge = self.config['merge'].get(bool) move = self.config['move'].get(str) path = self.config['path'].get(bool) From 972ee4c5c56f806f467b4881a2aa6840a8e2dd4e Mon Sep 17 00:00:00 2001 From: Stefano Rivera Date: Mon, 22 Aug 2016 23:54:36 -0700 Subject: [PATCH 1265/2280] Include extra bits in the source distribution --- MANIFEST.in | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MANIFEST.in b/MANIFEST.in index 3e64d2781..f5459a443 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -31,3 +31,6 @@ include beets/config_default.yaml # Shell completion template include beets/ui/completion_base.sh + +# Include extra bits +recursive-include extra * From 6bedbd84df6629b69cda4e86dbf15b50602fad44 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 25 Aug 2016 03:34:11 -0400 Subject: [PATCH 1266/2280] removebyte conversion/literals for command args Paths are obviously untouched. We definitely don't need these as they are entirely ascii. --- beets/util/__init__.py | 2 +- beets/util/artresizer.py | 8 ++++---- beetsplug/keyfinder.py | 4 ++-- beetsplug/replaygain.py | 22 +++++++++++----------- test/test_keyfinder.py | 2 +- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index c2d5c9334..642298c25 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -723,7 +723,7 @@ def cpu_count(): num = 0 elif sys.platform == 'darwin': try: - num = int(command_output([b'/usr/sbin/sysctl', b'-n', b'hw.ncpu'])) + num = int(command_output(['/usr/sbin/sysctl', '-n', 'hw.ncpu'])) except (ValueError, OSError, subprocess.CalledProcessError): num = 0 else: diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index bc9f4409b..4c2e92532 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -91,8 +91,8 @@ def im_resize(maxwidth, path_in, path_out=None): # compatibility. try: util.command_output([ - b'convert', util.syspath(path_in, prefix=False), - b'-resize', b'{0}x^>'.format(maxwidth), + 'convert', util.syspath(path_in, prefix=False), + '-resize', '{0}x^>'.format(maxwidth), util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: @@ -119,7 +119,7 @@ def pil_getsize(path_in): def im_getsize(path_in): - cmd = [b'identify', b'-format', b'%w %h', + cmd = ['identify', '-format', '%w %h', util.syspath(path_in, prefix=False)] try: out = util.command_output(cmd) @@ -233,7 +233,7 @@ def get_im_version(): Try invoking ImageMagick's "convert". """ try: - out = util.command_output([b'convert', b'--version']) + out = util.command_output(['convert', '--version']) if b'imagemagick' in out.lower(): pattern = br".+ (\d+)\.(\d+)\.(\d+).*" diff --git a/beetsplug/keyfinder.py b/beetsplug/keyfinder.py index 77312e25b..34a4abca4 100644 --- a/beetsplug/keyfinder.py +++ b/beetsplug/keyfinder.py @@ -52,14 +52,14 @@ class KeyFinderPlugin(BeetsPlugin): def find_key(self, items, write=False): overwrite = self.config['overwrite'].get(bool) - bin = util.bytestring_path(self.config['bin'].as_str()) + bin = self.config['bin'].as_str() for item in items: if item['initial_key'] and not overwrite: continue try: - output = util.command_output([bin, b'-f', + output = util.command_output([bin, '-f', util.syspath(item.path)]) except (subprocess.CalledProcessError, OSError) as exc: self._log.error(u'execution failed: {0}', exc) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 884339387..a3f94bd2e 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -102,9 +102,9 @@ class Bs1770gainBackend(Backend): 'method': 'replaygain', }) self.chunk_at = config['chunk_at'].as_number() - self.method = b'--' + config['method'].as_str().encode('ascii') + self.method = '--' + config['method'].as_str() - cmd = b'bs1770gain' + cmd = 'bs1770gain' try: call([cmd, self.method]) self.command = cmd @@ -195,7 +195,7 @@ class Bs1770gainBackend(Backend): # Construct shell command. cmd = [self.command] cmd = cmd + [self.method] - cmd = cmd + [b'-p'] + cmd = cmd + ['-p'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This @@ -267,9 +267,9 @@ class CommandBackend(Backend): ) else: # Check whether the program is in $PATH. - for cmd in (b'mp3gain', b'aacgain'): + for cmd in ('mp3gain', 'aacgain'): try: - call([cmd, b'-v']) + call([cmd, '-v']) self.command = cmd except OSError: pass @@ -308,9 +308,9 @@ class CommandBackend(Backend): def format_supported(self, item): """Checks whether the given item is supported by the selected tool. """ - if b'mp3gain' in self.command and item.format != 'MP3': + if 'mp3gain' in self.command and item.format != 'MP3': return False - elif b'aacgain' in self.command and item.format not in ('MP3', 'AAC'): + elif 'aacgain' in self.command and item.format not in ('MP3', 'AAC'): return False return True @@ -334,14 +334,14 @@ class CommandBackend(Backend): # tag-writing; this turns the mp3gain/aacgain tool into a gain # calculator rather than a tag manipulator because we take care # of changing tags ourselves. - cmd = [self.command, b'-o', b'-s', b's'] + cmd = [self.command, '-o', '-s', 's'] if self.noclip: # Adjust to avoid clipping. - cmd = cmd + [b'-k'] + cmd = cmd + ['-k'] else: # Disable clipping warning. - cmd = cmd + [b'-c'] - cmd = cmd + [b'-d', str(self.gain_offset).encode('ascii')] + cmd = cmd + ['-c'] + cmd = cmd + ['-d', str(self.gain_offset)] cmd = cmd + [syspath(i.path) for i in items] self._log.debug(u'analyzing {0} files', len(items)) diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 8befd750c..57e2bcd9c 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -44,7 +44,7 @@ class KeyFinderTest(unittest.TestCase, TestHelper): item.load() self.assertEqual(item['initial_key'], 'C#m') command_output.assert_called_with( - [b'KeyFinder', b'-f', util.syspath(item.path)]) + ['KeyFinder', '-f', util.syspath(item.path)]) def test_add_key_on_import(self, command_output): command_output.return_value = 'dbm' From 78171ee560536cee88ae583ef59819c1de294499 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 25 Aug 2016 04:08:05 -0400 Subject: [PATCH 1267/2280] remove byte literals from art.py commands args I'm not sure how i forgot these! --- beets/art.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/art.py b/beets/art.py index bf1d03a0a..a47fe02cb 100644 --- a/beets/art.py +++ b/beets/art.py @@ -128,10 +128,10 @@ def check_art_similarity(log, item, imagepath, compare_threshold): # to grayscale and then pipe them into the `compare` command. # On Windows, ImageMagick doesn't support the magic \\?\ prefix # on paths, so we pass `prefix=False` to `syspath`. - convert_cmd = [b'convert', syspath(imagepath, prefix=False), + convert_cmd = ['convert', syspath(imagepath, prefix=False), syspath(art, prefix=False), - b'-colorspace', b'gray', b'MIFF:-'] - compare_cmd = [b'compare', b'-metric', b'PHASH', b'-', b'null:'] + '-colorspace', 'gray', 'MIFF:-'] + compare_cmd = ['compare', '-metric', 'PHASH', '-', 'null:'] log.debug(u'comparing images with pipeline {} | {}', convert_cmd, compare_cmd) convert_proc = subprocess.Popen( From a282d4abc5ac988653327a9f2f6edfe0286eaf64 Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Fri, 26 Aug 2016 10:21:46 +0200 Subject: [PATCH 1268/2280] embyupdate: Fix authentication header problem There was a problem with the authentication header in the latest versions. The header creation function changed to fix that. Username and passwort authentication should work again. The `host` config variable takes now a full hostname. For example `http://localhost` instead of just `localhost`. This makes it easier to use https hosts. --- beetsplug/embyupdate.py | 82 +++++++++++++++++++++++++++++-------- docs/changelog.rst | 2 + docs/plugins/embyupdate.rst | 6 +-- test/test_embyupdate.py | 50 ++++++++++++---------- 4 files changed, 99 insertions(+), 41 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 2a2f792f5..4da124dbb 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -3,25 +3,38 @@ """Updates the Emby Library whenever the beets library is changed. emby: - host: localhost + host: http://localhost port: 8096 username: user password: password """ from __future__ import division, absolute_import, print_function -from beets import config -from beets.plugins import BeetsPlugin -from six.moves.urllib.parse import urlencode -from six.moves.urllib.parse import urljoin, parse_qs, urlsplit, urlunsplit import hashlib import requests +from six.moves.urllib.parse import urlencode +from six.moves.urllib.parse import urljoin, parse_qs, urlsplit, urlunsplit + +from beets import config +from beets.plugins import BeetsPlugin + def api_url(host, port, endpoint): """Returns a joined url. + + Takes host, port and endpoint and generates a valid emby API url. + + :param host: Hostname of the emby server + :param port: Portnumber of the emby server + :param endpoint: API endpoint + :type host: str + :type port: int + :type endpoint: str + :returns: Full API url + :rtype: str """ - joined = urljoin('http://{0}:{1}'.format(host, port), endpoint) + joined = urljoin('{0}:{1}'.format(host, port), endpoint) scheme, netloc, path, query_string, fragment = urlsplit(joined) query_params = parse_qs(query_string) @@ -33,6 +46,13 @@ def api_url(host, port, endpoint): def password_data(username, password): """Returns a dict with username and its encoded password. + + :param username: Emby username + :param password: Emby password + :type username: str + :type password: str + :returns: Dictionary with username and encoded password + :rtype: dict """ return { 'username': username, @@ -43,24 +63,45 @@ def password_data(username, password): def create_headers(user_id, token=None): """Return header dict that is needed to talk to the Emby API. + + :param user_id: Emby user ID + :param token: Authentication token for Emby + :type user_id: str + :type token: str + :returns: Headers for requests + :rtype: dict """ - headers = { - 'Authorization': 'MediaBrowser', - 'UserId': user_id, - 'Client': 'other', - 'Device': 'empy', - 'DeviceId': 'beets', - 'Version': '0.0.0' - } + headers = {} + + authorization = ( + 'MediaBrowser UserId="{user_id}", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ).format(user_id=user_id) + + headers['x-emby-authorization'] = authorization if token: - headers['X-MediaBrowser-Token'] = token + headers['x-mediabrowser-token'] = token return headers def get_token(host, port, headers, auth_data): """Return token for a user. + + :param host: Emby host + :param port: Emby port + :param headers: Headers for requests + :param auth_data: Username and encoded password for authentication + :type host: str + :type port: int + :type headers: dict + :type auth_data: dict + :returns: Access Token + :rtype: str """ url = api_url(host, port, '/Users/AuthenticateByName') r = requests.post(url, headers=headers, data=auth_data) @@ -70,6 +111,15 @@ def get_token(host, port, headers, auth_data): def get_user(host, port, username): """Return user dict from server or None if there is no user. + + :param host: Emby host + :param port: Emby port + :username: Username + :type host: str + :type port: int + :type username: str + :returns: Matched Users + :rtype: list """ url = api_url(host, port, '/Users/Public') r = requests.get(url) @@ -84,7 +134,7 @@ class EmbyUpdate(BeetsPlugin): # Adding defaults. config['emby'].add({ - u'host': u'localhost', + u'host': u'http://localhost', u'port': 8096 }) diff --git a/docs/changelog.rst b/docs/changelog.rst index c3f5ba1bb..a3a392d53 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -48,6 +48,8 @@ And there are a few bug fixes too: omitted. * With :ref:`ignore_hidden` enabled, non-UTF-8 filenames would cause a crash. This is fixed. :bug:`2168` +* :doc:`/plugins/embyupdate`: Fixes authentication header problem that caused + a problem that it was not possible to get tokens from the Emby API. The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index a902e6076..339f0c818 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -6,7 +6,7 @@ EmbyUpdate Plugin To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll probably want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: emby: - host: localhost + host: http://localhost port: 8096 username: user apikey: apikey @@ -25,8 +25,8 @@ Configuration The available options under the ``emby:`` section are: -- **host**: The Emby server name. - Default: ``localhost`` +- **host**: The Emby server host. You have to include ``http://`` or ``https://``. + Default: ``http://localhost`` - **port**: The Emby server port. Default: 8096 - **username**: A username of a Emby user that is allowed to refresh the library. diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index dc4cad23c..905766f7a 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -14,7 +14,7 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): self.load_plugins('embyupdate') self.config['emby'] = { - u'host': u'localhost', + u'host': u'http://localhost', u'port': 8096, u'username': u'username', u'password': u'password' @@ -47,12 +47,14 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): self.assertEqual( embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721'), { - 'Authorization': 'MediaBrowser', - 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', - 'Client': 'other', - 'Device': 'empy', - 'DeviceId': 'beets', - 'Version': '0.0.0' + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ) } ) @@ -61,13 +63,15 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): embyupdate.create_headers('e8837bc1-ad67-520e-8cd2-f629e3155721', token='abc123'), { - 'Authorization': 'MediaBrowser', - 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', - 'Client': 'other', - 'Device': 'empy', - 'DeviceId': 'beets', - 'Version': '0.0.0', - 'X-MediaBrowser-Token': 'abc123' + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ), + 'x-mediabrowser-token': 'abc123' } ) @@ -132,12 +136,14 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): content_type='application/json') headers = { - 'Authorization': 'MediaBrowser', - 'UserId': 'e8837bc1-ad67-520e-8cd2-f629e3155721', - 'Client': 'other', - 'Device': 'empy', - 'DeviceId': 'beets', - 'Version': '0.0.0' + 'x-emby-authorization': ( + 'MediaBrowser ' + 'UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", ' + 'Client="other", ' + 'Device="beets", ' + 'DeviceId="beets", ' + 'Version="0.0.0"' + ) } auth_data = { @@ -147,7 +153,7 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): } self.assertEqual( - embyupdate.get_token('localhost', 8096, headers, auth_data), + embyupdate.get_token('http://localhost', 8096, headers, auth_data), '4b19180cf02748f7b95c7e8e76562fc8') @responses.activate @@ -196,7 +202,7 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): status=200, content_type='application/json') - response = embyupdate.get_user('localhost', 8096, 'username') + response = embyupdate.get_user('http://localhost', 8096, 'username') self.assertEqual(response[0]['Id'], '2ec276a2642e54a19b612b9418a8bd3b') From 5592499b3167f8f24818ec3571ae9ef9efcf920e Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Fri, 26 Aug 2016 12:28:48 +0200 Subject: [PATCH 1269/2280] embyupdate: backwards compatible hostname `host` takes `localhost`, `http://localhost` and `https://`. --- beetsplug/embyupdate.py | 19 +++++++++++++++++-- docs/plugins/embyupdate.rst | 6 +++--- test/test_embyupdate.py | 20 ++++++++++++++++++-- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 4da124dbb..3af285973 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -3,7 +3,7 @@ """Updates the Emby Library whenever the beets library is changed. emby: - host: http://localhost + host: localhost port: 8096 username: user password: password @@ -34,7 +34,22 @@ def api_url(host, port, endpoint): :returns: Full API url :rtype: str """ - joined = urljoin('{0}:{1}'.format(host, port), endpoint) + # check if http or https is defined as host and create hostname + hostname_list = [host] + if host.startswith('http://') or host.startswith('https://'): + hostname = ''.join(hostname_list) + else: + hostname_list.insert(0, 'http://') + hostname = ''.join(hostname_list) + + joined = urljoin( + '{hostname}:{port}'.format( + hostname=hostname, + port=port + ), + endpoint + ) + scheme, netloc, path, query_string, fragment = urlsplit(joined) query_params = parse_qs(query_string) diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index 339f0c818..8dbb7c1db 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -6,7 +6,7 @@ EmbyUpdate Plugin To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll probably want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: emby: - host: http://localhost + host: localhost port: 8096 username: user apikey: apikey @@ -25,8 +25,8 @@ Configuration The available options under the ``emby:`` section are: -- **host**: The Emby server host. You have to include ``http://`` or ``https://``. - Default: ``http://localhost`` +- **host**: The Emby server host. You also can include ``http://`` or ``https://``. + Default: ``localhost`` - **port**: The Emby server port. Default: 8096 - **username**: A username of a Emby user that is allowed to refresh the library. diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index 905766f7a..17e82c73e 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -14,7 +14,7 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): self.load_plugins('embyupdate') self.config['emby'] = { - u'host': u'http://localhost', + u'host': u'localhost', u'port': 8096, u'username': u'username', u'password': u'password' @@ -24,7 +24,7 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): self.teardown_beets() self.unload_plugins() - def test_api_url(self): + def test_api_url_only_name(self): self.assertEqual( embyupdate.api_url(self.config['emby']['host'].get(), self.config['emby']['port'].get(), @@ -32,6 +32,22 @@ class EmbyUpdateTest(unittest.TestCase, TestHelper): 'http://localhost:8096/Library/Refresh?format=json' ) + def test_api_url_http(self): + self.assertEqual( + embyupdate.api_url(u'http://localhost', + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'http://localhost:8096/Library/Refresh?format=json' + ) + + def test_api_url_https(self): + self.assertEqual( + embyupdate.api_url(u'https://localhost', + self.config['emby']['port'].get(), + '/Library/Refresh'), + 'https://localhost:8096/Library/Refresh?format=json' + ) + def test_password_data(self): self.assertEqual( embyupdate.password_data(self.config['emby']['username'].get(), From 9963fd0432e379f163dcde2efa39a13689cff0e9 Mon Sep 17 00:00:00 2001 From: Thiago de Arruda Date: Fri, 26 Aug 2016 10:58:32 -0300 Subject: [PATCH 1270/2280] mpdupdate: Support `$MPD_HOST` environment variable. This environment variable is also used by mpc. See http://linux.die.net/man/1/mpc for details. --- beetsplug/mpdupdate.py | 2 +- docs/plugins/mpdupdate.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 8ea1b5204..6c39375be 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -68,7 +68,7 @@ class MPDUpdatePlugin(BeetsPlugin): def __init__(self): super(MPDUpdatePlugin, self).__init__() config['mpd'].add({ - 'host': u'localhost', + 'host': os.environ.get('MPD_HOST', u'localhost'), 'port': 6600, 'password': u'', }) diff --git a/docs/plugins/mpdupdate.rst b/docs/plugins/mpdupdate.rst index 954a87b33..c846b917f 100644 --- a/docs/plugins/mpdupdate.rst +++ b/docs/plugins/mpdupdate.rst @@ -31,7 +31,7 @@ Configuration The available options under the ``mpd:`` section are: - **host**: The MPD server name. - Default: ``localhost``. + Default: The ``$MPD_HOST`` environment variable if set, falling back to ``localhost`` otherwise. - **port**: The MPD server port. Default: 6600. - **password**: The MPD server password. From 3acd44260ac3f8ee73e19eb9c1ab88d05b760158 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Fri, 26 Aug 2016 18:17:37 +0200 Subject: [PATCH 1271/2280] Apply #2175 to mpdstats to keep consistency --- beetsplug/mpdstats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 8ae3eb783..0f78ee561 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -331,7 +331,7 @@ class MPDStatsPlugin(plugins.BeetsPlugin): 'music_directory': config['directory'].as_filename(), 'rating': True, 'rating_mix': 0.75, - 'host': u'localhost', + 'host': os.environ.get('MPD_HOST', u'localhost'), 'port': 6600, 'password': u'', }) From ed0adc2b6343358274c8b4ab28889f4db245e796 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Fri, 26 Aug 2016 18:18:35 +0200 Subject: [PATCH 1272/2280] Add more doc and changelog for #2175 --- docs/changelog.rst | 4 ++++ docs/plugins/mpdstats.rst | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index a3a392d53..950dd991d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,10 @@ to know: The are a couple of small new features: +* :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option + is not set, these plugins will now look for the ``$MPD_HOST`` environment + variable before falling back to ``localhost``. Thanks to :user:`tarruda`. + :bug:`2175` * :doc:`/plugins/web`: Added an ``expand`` option to show the items of an album and a ``path`` field to the JSON output of a file which shows the filled-out path template for each file. :bug:`2050` diff --git a/docs/plugins/mpdstats.rst b/docs/plugins/mpdstats.rst index 4389fa27e..5472e7294 100644 --- a/docs/plugins/mpdstats.rst +++ b/docs/plugins/mpdstats.rst @@ -39,7 +39,8 @@ To configure the plugin, make an ``mpd:`` section in your configuration file. The available options are: - **host**: The MPD server hostname. - Default: ``localhost``. + Default: The ``$MPD_HOST`` environment variable if set, + falling back to ``localhost`` otherwise. - **port**: The MPD server port. Default: 6600. - **password**: The MPD server password. From 15be20c70150e89881623c22bab5cf8507853ced Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 28 Aug 2016 21:06:14 -0400 Subject: [PATCH 1273/2280] Compare case insensitive paths with SUBSTR and BYTELOWER Create a custom `bytelower` sqlite function so we can compare bytestrings in a semi case insensitive fashion. This is to work around sqlite builds are that compiled with `-DSQLITE_LIKE_DOESNT_MATCH_BLOBS`. See https://github.com/beetbox/beets/issues/2172 for details. --- beets/library.py | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/beets/library.py b/beets/library.py index 3d18a1be0..91e4a076f 100644 --- a/beets/library.py +++ b/beets/library.py @@ -57,9 +57,6 @@ class PathQuery(dbcore.FieldQuery): and case-sensitive otherwise. """ - escape_re = re.compile(br'[\\_%]') - escape_char = b'\\' - def __init__(self, field, pattern, fast=True, case_sensitive=None): """Create a path query. `pattern` must be a path, either to a file or a directory. @@ -108,20 +105,17 @@ class PathQuery(dbcore.FieldQuery): return (path == self.file_path) or path.startswith(self.dir_path) def col_clause(self): - if self.case_sensitive: - file_blob = BLOB_TYPE(self.file_path) - dir_blob = BLOB_TYPE(self.dir_path) - return '({0} = ?) || (substr({0}, 1, ?) = ?)'.format(self.field), \ - (file_blob, len(dir_blob), dir_blob) + file_blob = BLOB_TYPE(self.file_path) + dir_blob = BLOB_TYPE(self.dir_path) - escape = lambda m: self.escape_char + m.group(0) - dir_pattern = self.escape_re.sub(escape, self.dir_path) - dir_blob = BLOB_TYPE(dir_pattern + b'%') - file_pattern = self.escape_re.sub(escape, self.file_path) - file_blob = BLOB_TYPE(file_pattern) - return '({0} LIKE ? ESCAPE ?) || ({0} LIKE ? ESCAPE ?)'.format( - self.field), (file_blob, self.escape_char, dir_blob, - self.escape_char) + if self.case_sensitive: + query_part = '({0} = ?) || (substr({0}, 1, ?) = ?)' + else: + query_part = '(BYTELOWER({0}) = BYTELOWER(?)) || \ + (substr(BYTELOWER({0}), 1, ?) = BYTELOWER(?))' + + return query_part.format(self.field), \ + (file_blob, len(dir_blob), dir_blob) # Library-specific field types. @@ -1201,6 +1195,19 @@ def parse_query_string(s, model_cls): return parse_query_parts(parts, model_cls) +def _sqlite_bytelower(bytestring): + """ A custom ``bytelower`` sqlite function so we can compare + bytestrings in a semi case insensitive fashion. This is to work + around sqlite builds are that compiled with + ``-DSQLITE_LIKE_DOESNT_MATCH_BLOBS``. See + ``https://github.com/beetbox/beets/issues/2172`` for details. + """ + if not six.PY2: + return bytestring.lower() + + return buffer(bytes(bytestring).lower()) # noqa: F821 + + # The Library: interface to the database. class Library(dbcore.Database): @@ -1215,6 +1222,8 @@ class Library(dbcore.Database): replacements=None): super(Library, self).__init__(path) + self._connection().create_function('bytelower', 1, _sqlite_bytelower) + self.directory = bytestring_path(normpath(directory)) self.path_formats = path_formats self.replacements = replacements From cda239a06d79b1109ea0744a5a7450edba6cbd45 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 29 Aug 2016 18:31:43 -0400 Subject: [PATCH 1274/2280] pass arguments to FunctionDef as keyword args This makes it a lot easier to read. --- beets/util/functemplate.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index cdccc49a5..6147a2185 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -114,14 +114,15 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): bytecode of the compiled function. """ func_def = ast.FunctionDef( - name.encode('utf8'), - ast.arguments( - [ast.Name(n, ast.Param()) for n in arg_names], - None, None, - [ex_literal(None) for _ in arg_names], + name=name.encode('utf8'), + args=ast.arguments( + args=[ast.Name(n, ast.Param()) for n in arg_names], + vararg=None, + kwarg=None, + defaults=[ex_literal(None) for _ in arg_names], ), - statements, - [], + body=statements, + decorator_list=[], ) mod = ast.Module([func_def]) ast.fix_missing_locations(mod) From bcb1f8036ac8692469b119a5603164e9876cb532 Mon Sep 17 00:00:00 2001 From: Stefano Rivera Date: Mon, 29 Aug 2016 16:29:28 -0700 Subject: [PATCH 1275/2280] Correct a typo Spotted by lintian which runs spellchecks on man pages. --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 0892aaa30..264cd6413 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -557,7 +557,7 @@ duplicate_action Either ``skip``, ``keep``, ``remove``, or ``ask``. Controls how duplicates are treated in import task. "skip" means that new item(album or track) will be -skiped; "keep" means keep both old and new items; "remove" means remove old +skipped; "keep" means keep both old and new items; "remove" means remove old item; "ask" means the user should be prompted for the action each time. The default is ``ask``. From 4b7a44a9b51e210413ae6d219ecb4ac63b1e11e5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 29 Aug 2016 18:40:31 -0400 Subject: [PATCH 1276/2280] functemplate AST: use py2/3 compatible string type It was previously forced to `unicode`, but now uses the appropriate string type for the executing Python version. --- beets/util/functemplate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 6147a2185..4cb93430d 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -214,7 +214,7 @@ class Call(object): [ex_call( 'map', [ - ex_rvalue('unicode'), + ex_rvalue(six.text_type.__name__), ast.List(subexprs, ast.Load()), ] )], From 38ec80b35ed316ebc1e539785dd27c0db6d8d86e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 29 Aug 2016 23:15:03 -0400 Subject: [PATCH 1277/2280] functemplate AST: only encode ident names on py2 They are passed as `unicode` types, but the AST only accepts py2 strings. --- beets/util/functemplate.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 4cb93430d..b5f6a2f3a 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -113,8 +113,10 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): the resulting Python function. If `debug`, then print out the bytecode of the compiled function. """ + if six.PY2: + name = name.encode('utf-8') func_def = ast.FunctionDef( - name=name.encode('utf8'), + name=name, args=ast.arguments( args=[ast.Name(n, ast.Param()) for n in arg_names], vararg=None, @@ -165,8 +167,12 @@ class Symbol(object): def translate(self): """Compile the variable lookup.""" - expr = ex_rvalue(VARIABLE_PREFIX + self.ident.encode('utf8')) - return [expr], set([self.ident.encode('utf8')]), set() + if six.PY2: + ident = self.ident.encode('utf-8') + else: + ident = self.ident + expr = ex_rvalue(VARIABLE_PREFIX + ident) + return [expr], set([ident]), set() class Call(object): @@ -199,7 +205,11 @@ class Call(object): def translate(self): """Compile the function call.""" varnames = set() - funcnames = set([self.ident.encode('utf8')]) + if six.PY2: + ident = self.ident.encode('utf-8') + else: + ident = self.ident + funcnames = set([ident]) arg_exprs = [] for arg in self.args: @@ -221,7 +231,7 @@ class Call(object): )) subexpr_call = ex_call( - FUNCTION_PREFIX + self.ident.encode('utf8'), + FUNCTION_PREFIX + ident, arg_exprs ) return [subexpr_call], varnames, funcnames From 6234da31a8336fc004561eece3def352834ed3ac Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 30 Aug 2016 03:49:17 -0400 Subject: [PATCH 1278/2280] functemplate AST: py3 versions of FunctionDef/Call Note that `ast.Call` only changed signatures on py 3.5. --- beets/util/functemplate.py | 43 +++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index b5f6a2f3a..f8fabf4a8 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -33,7 +33,7 @@ import re import ast import dis import types - +import sys import six SYMBOL_DELIM = u'$' @@ -105,7 +105,10 @@ def ex_call(func, args): if not isinstance(args[i], ast.expr): args[i] = ex_literal(args[i]) - return ast.Call(func, args, [], None, None) + if sys.version_info[:2] < (3, 5): + return ast.Call(func, args, [], None, None) + else: + return ast.Call(func, args, []) def compile_func(arg_names, statements, name='_the_func', debug=False): @@ -114,18 +117,30 @@ def compile_func(arg_names, statements, name='_the_func', debug=False): bytecode of the compiled function. """ if six.PY2: - name = name.encode('utf-8') - func_def = ast.FunctionDef( - name=name, - args=ast.arguments( - args=[ast.Name(n, ast.Param()) for n in arg_names], - vararg=None, - kwarg=None, - defaults=[ex_literal(None) for _ in arg_names], - ), - body=statements, - decorator_list=[], - ) + func_def = ast.FunctionDef( + name=name.encode('utf-8'), + args=ast.arguments( + args=[ast.Name(n, ast.Param()) for n in arg_names], + vararg=None, + kwarg=None, + defaults=[ex_literal(None) for _ in arg_names], + ), + body=statements, + decorator_list=[], + ) + else: + func_def = ast.FunctionDef( + name=name, + args=ast.arguments( + args=[ast.arg(arg=n, annotation=None) for n in arg_names], + kwonlyargs=[], + kw_defaults=[], + defaults=[ex_literal(None) for _ in arg_names], + ), + body=statements, + decorator_list=[], + ) + mod = ast.Module([func_def]) ast.fix_missing_locations(mod) From 2cc7225805d735f3cfdf06a312a5b791022cd08d Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 30 Aug 2016 03:49:58 -0400 Subject: [PATCH 1279/2280] functemplate AST: enable the compiler on py3 --- beets/util/functemplate.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index f8fabf4a8..7a309e793 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -534,8 +534,7 @@ class Template(object): def __init__(self, template): self.expr = _parse(template) self.original = template - if six.PY2: # FIXME Compiler is broken on Python 3. - self.compiled = self.translate() + self.compiled = self.translate() def __eq__(self, other): return self.original == other.original @@ -551,13 +550,11 @@ class Template(object): def substitute(self, values={}, functions={}): """Evaluate the template given the values and functions. """ - if six.PY2: # FIXME As above. - try: - res = self.compiled(values, functions) - except: # Handle any exceptions thrown by compiled version. - res = self.interpret(values, functions) - else: + try: + res = self.compiled(values, functions) + except: # Handle any exceptions thrown by compiled version. res = self.interpret(values, functions) + return res def translate(self): From 25fb0304a6e3683d6595b8392c9add7a4a6189a0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Thu, 7 Jul 2016 19:02:40 -0400 Subject: [PATCH 1280/2280] Add gstreamer deps to travis config [appveyor skip] --- .travis.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.travis.yml b/.travis.yml index d919676fc..d3633fdb4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,8 +30,16 @@ addons: - sourceline: "deb http://archive.ubuntu.com/ubuntu/ trusty-updates multiverse" packages: - bash-completion + - gir1.2-gst-plugins-base-1.0 + - gir1.2-gstreamer-1.0 + - gstreamer1.0-plugins-good + - gstreamer1.0-plugins-bad - imagemagick - mp3gain + - python-gi + - python-gst-1.0 + - python3-gi + - python3-gst-1.0 - unrar # To install dependencies, tell tox to do everything but actually running the From 632240c01ce5ee9f670453eef8b647d69271580c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 5 Sep 2016 22:57:38 -0400 Subject: [PATCH 1281/2280] s/linux2/linux/ as platform name in test_library This causes no issues for us now, and is more forward compatible. --- test/test_library.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 4265f6d1a..395a811aa 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -392,7 +392,7 @@ class DestinationTest(_common.TestCase): def test_unicode_normalized_nfc_on_linux(self): instr = unicodedata.normalize('NFD', u'caf\xe9') self.lib.path_formats = [(u'default', instr)] - dest = self.i.destination(platform='linux2', fragment=True) + dest = self.i.destination(platform='linux', fragment=True) self.assertEqual(dest, unicodedata.normalize('NFC', instr)) def test_non_mbcs_characters_on_windows(self): @@ -411,7 +411,7 @@ class DestinationTest(_common.TestCase): def test_unicode_extension_in_fragment(self): self.lib.path_formats = [(u'default', u'foo')] self.i.path = util.bytestring_path(u'bar.caf\xe9') - dest = self.i.destination(platform='linux2', fragment=True) + dest = self.i.destination(platform='linux', fragment=True) self.assertEqual(dest, u'foo.caf\xe9') def test_asciify_and_replace(self): From 7a2bdf502f88a278da6be55f93770dad738a14e6 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 6 Sep 2016 23:08:16 -0400 Subject: [PATCH 1282/2280] s/utf8/utf-8/ in all encoding/decoding contexts This matches up with the python documentation. --- beets/autotag/hooks.py | 4 ++-- beets/dbcore/db.py | 2 +- beets/dbcore/query.py | 2 +- beets/dbcore/types.py | 4 ++-- beets/library.py | 2 +- beets/logging.py | 4 ++-- beets/mediafile.py | 18 +++++++++--------- beets/ui/__init__.py | 2 +- beets/ui/commands.py | 2 +- beets/util/__init__.py | 28 ++++++++++++++-------------- beets/util/confit.py | 6 +++--- beetsplug/beatport.py | 4 ++-- beetsplug/bpd/__init__.py | 2 +- beetsplug/bpd/gstplayer.py | 2 +- beetsplug/convert.py | 2 +- beetsplug/lastgenre/__init__.py | 2 +- beetsplug/lyrics.py | 10 +++++----- beetsplug/mpdstats.py | 4 ++-- beetsplug/replaygain.py | 2 +- extra/release.py | 4 ++-- test/_common.py | 4 ++-- test/helper.py | 4 ++-- test/lyrics_download_samples.py | 2 +- test/rsrc/convert_stub.py | 2 +- test/test_dbcore.py | 2 +- test/test_edit.py | 6 +++--- test/test_importer.py | 4 ++-- test/test_library.py | 6 +++--- test/test_mediafile_edge.py | 2 +- test/test_play.py | 2 +- test/test_ui.py | 6 +++--- test/test_util.py | 4 ++-- 32 files changed, 75 insertions(+), 75 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index c7b5edd73..b5dfb5d39 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -107,7 +107,7 @@ class AlbumInfo(object): # Work around a bug in python-musicbrainz-ngs that causes some # strings to be bytes rather than Unicode. # https://github.com/alastair/python-musicbrainz-ngs/issues/85 - def decode(self, codec='utf8'): + def decode(self, codec='utf-8'): """Ensure that all string attributes on this object, and the constituent `TrackInfo` objects, are decoded to Unicode. """ @@ -169,7 +169,7 @@ class TrackInfo(object): self.data_url = data_url # As above, work around a bug in python-musicbrainz-ngs. - def decode(self, codec='utf8'): + def decode(self, codec='utf-8'): """Ensure that all string attributes on this object are decoded to Unicode. """ diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 539658578..73233b52c 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -68,7 +68,7 @@ class FormattedMapping(collections.Mapping): def _get_formatted(self, model, key): value = model._type(key).format(model.get(key)) if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') if self.for_path: sep_repl = beets.config['path_sep_replace'].as_str() diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f6dadd686..3710d55c2 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -252,7 +252,7 @@ class BytesQuery(MatchQuery): # rather than encoded Unicode. if isinstance(self.pattern, (six.text_type, bytes)): if isinstance(self.pattern, six.text_type): - self.pattern = self.pattern.encode('utf8') + self.pattern = self.pattern.encode('utf-8') self.buf_pattern = buffer(self.pattern) elif isinstance(self.pattern, buffer): self.buf_pattern = self.pattern diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index ef583672e..b909904bd 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -65,7 +65,7 @@ class Type(object): if value is None: value = u'' if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') return six.text_type(value) @@ -105,7 +105,7 @@ class Type(object): and the method must handle these in addition. """ if isinstance(sql_value, buffer): - sql_value = bytes(sql_value).decode('utf8', 'ignore') + sql_value = bytes(sql_value).decode('utf-8', 'ignore') if isinstance(sql_value, six.text_type): return self.parse(sql_value) else: diff --git a/beets/library.py b/beets/library.py index 91e4a076f..99df2d87b 100644 --- a/beets/library.py +++ b/beets/library.py @@ -341,7 +341,7 @@ class LibModel(dbcore.Model): result = self.evaluate_template(spec) if isinstance(spec, bytes): # if spec is a byte string then we must return a one as well - return result.encode('utf8') + return result.encode('utf-8') else: return result diff --git a/beets/logging.py b/beets/logging.py index f7b46bd60..d5ec7b73f 100644 --- a/beets/logging.py +++ b/beets/logging.py @@ -52,7 +52,7 @@ def logsafe(val): # (a) only do this for paths, if they can be given a distinct # type, and (b) warn the developer if they do this for other # bytestrings. - return val.decode('utf8', 'replace') + return val.decode('utf-8', 'replace') # A "problem" object: needs a workaround. elif isinstance(val, subprocess.CalledProcessError): @@ -61,7 +61,7 @@ def logsafe(val): except UnicodeDecodeError: # An object with a broken __unicode__ formatter. Use __str__ # instead. - return str(val).decode('utf8', 'replace') + return str(val).decode('utf-8', 'replace') # Other objects are used as-is so field access, etc., still works in # the format string. diff --git a/beets/mediafile.py b/beets/mediafile.py index 6f78914c7..6dd7bc816 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -176,7 +176,7 @@ def _safe_cast(out_type, val): elif out_type == six.text_type: if isinstance(val, bytes): - return val.decode('utf8', 'ignore') + return val.decode('utf-8', 'ignore') elif isinstance(val, six.text_type): return val else: @@ -187,7 +187,7 @@ def _safe_cast(out_type, val): return float(val) else: if isinstance(val, bytes): - val = val.decode('utf8', 'ignore') + val = val.decode('utf-8', 'ignore') else: val = six.text_type(val) match = re.match(r'[\+-]?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)', @@ -249,7 +249,7 @@ def _sc_decode(soundcheck): # We decode binary data. If one of the formats gives us a text # string, interpret it as UTF-8. if isinstance(soundcheck, six.text_type): - soundcheck = soundcheck.encode('utf8') + soundcheck = soundcheck.encode('utf-8') # SoundCheck tags consist of 10 numbers, each represented by 8 # characters of ASCII hex preceded by a space. @@ -460,7 +460,7 @@ class StorageStyle(object): # Convert suffix to correct string type. if self.suffix and self.as_type is six.text_type \ and not isinstance(self.suffix, six.text_type): - self.suffix = self.suffix.decode('utf8') + self.suffix = self.suffix.decode('utf-8') # Getter. @@ -512,7 +512,7 @@ class StorageStyle(object): # Store bools as 1/0 instead of True/False. value = six.text_type(int(bool(value))) elif isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') else: value = six.text_type(value) else: @@ -625,7 +625,7 @@ class MP4StorageStyle(StorageStyle): def serialize(self, value): value = super(MP4StorageStyle, self).serialize(value) if self.key.startswith('----:') and isinstance(value, six.text_type): - value = value.encode('utf8') + value = value.encode('utf-8') return value @@ -767,7 +767,7 @@ class MP3UFIDStorageStyle(MP3StorageStyle): def store(self, mutagen_file, value): # This field type stores text data as encoded data. assert isinstance(value, six.text_type) - value = value.encode('utf8') + value = value.encode('utf-8') frames = mutagen_file.tags.getall(self.key) for frame in frames: @@ -1067,7 +1067,7 @@ class APEv2ImageStorageStyle(ListStorageStyle): text_delimiter_index = frame.value.find(b'\x00') if text_delimiter_index > 0: comment = frame.value[0:text_delimiter_index] - comment = comment.decode('utf8', 'replace') + comment = comment.decode('utf-8', 'replace') else: comment = None image_data = frame.value[text_delimiter_index + 1:] @@ -1084,7 +1084,7 @@ class APEv2ImageStorageStyle(ListStorageStyle): for image in values: image_type = image.type or ImageType.other comment = image.desc or '' - image_data = comment.encode('utf8') + b'\x00' + image.data + image_data = comment.encode('utf-8') + b'\x00' + image.data cover_tag = self.TAG_NAMES[image_type] mutagen_file[cover_tag] = image_data diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 71896ab3b..1c208a429 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -86,7 +86,7 @@ def _out_encoding(): return _stream_encoding(sys.stdout) -def _stream_encoding(stream, default='utf8'): +def _stream_encoding(stream, default='utf-8'): """A helper for `_in_encoding` and `_out_encoding`: get the stream's preferred encoding, using a configured override or a default fallback if neither is not specified. diff --git a/beets/ui/commands.py b/beets/ui/commands.py index af05084fa..2f323b604 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -87,7 +87,7 @@ def _print_keys(query): returned row, with identation of 2 spaces. """ for row in query: - print_(u' ' * 2 + row['key'].decode('utf8')) + print_(u' ' * 2 + row['key'].decode('utf-8')) def fields_func(lib, opts, args): diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 642298c25..5e1c30df1 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -70,7 +70,7 @@ class HumanReadableException(Exception): if isinstance(self.reason, six.text_type): return self.reason elif isinstance(self.reason, bytes): - return self.reason.decode('utf8', 'ignore') + return self.reason.decode('utf-8', 'ignore') elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError return self.reason.strerror else: @@ -308,11 +308,11 @@ def arg_encoding(): locale-sensitive strings). """ try: - return locale.getdefaultlocale()[1] or 'utf8' + return locale.getdefaultlocale()[1] or 'utf-8' except ValueError: # Invalid locale environment variable setting. To avoid # failing entirely for no good reason, assume UTF-8. - return 'utf8' + return 'utf-8' def _fsencoding(): @@ -326,7 +326,7 @@ def _fsencoding(): # for Windows paths, so the encoding is actually immaterial so # we can avoid dealing with this nastiness. We arbitrarily # choose UTF-8. - encoding = 'utf8' + encoding = 'utf-8' return encoding @@ -344,11 +344,11 @@ def bytestring_path(path): if os.path.__name__ == 'ntpath' and path.startswith(WINDOWS_MAGIC_PREFIX): path = path[len(WINDOWS_MAGIC_PREFIX):] - # Try to encode with default encodings, but fall back to UTF8. + # Try to encode with default encodings, but fall back to utf-8. try: return path.encode(_fsencoding()) except (UnicodeError, LookupError): - return path.encode('utf8') + return path.encode('utf-8') PATH_SEP = bytestring_path(os.sep) @@ -370,7 +370,7 @@ def displayable_path(path, separator=u'; '): try: return path.decode(_fsencoding(), 'ignore') except (UnicodeError, LookupError): - return path.decode('utf8', 'ignore') + return path.decode('utf-8', 'ignore') def syspath(path, prefix=True): @@ -389,7 +389,7 @@ def syspath(path, prefix=True): # arbitrarily. But earlier versions used MBCS because it is # reported as the FS encoding by Windows. Try both. try: - path = path.decode('utf8') + path = path.decode('utf-8') except UnicodeError: # The encoding should always be MBCS, Windows' broken # Unicode representation. @@ -620,7 +620,7 @@ def legalize_path(path, replacements, length, extension, fragment): if fragment: # Outputting Unicode. - extension = extension.decode('utf8', 'ignore') + extension = extension.decode('utf-8', 'ignore') first_stage_path, _ = _legalize_stage( path, replacements, length, extension, fragment @@ -679,14 +679,14 @@ def as_string(value): if value is None: return u'' elif isinstance(value, buffer_types): - return bytes(value).decode('utf8', 'ignore') + return bytes(value).decode('utf-8', 'ignore') elif isinstance(value, bytes): - return value.decode('utf8', 'ignore') + return value.decode('utf-8', 'ignore') else: return six.text_type(value) -def text_string(value, encoding='utf8'): +def text_string(value, encoding='utf-8'): """Convert a string, which can either be bytes or unicode, to unicode. @@ -844,8 +844,8 @@ def shlex_split(s): elif isinstance(s, six.text_type): # Work around a Python bug. # http://bugs.python.org/issue6988 - bs = s.encode('utf8') - return [c.decode('utf8') for c in shlex.split(bs)] + bs = s.encode('utf-8') + return [c.decode('utf-8') for c in shlex.split(bs)] else: raise TypeError(u'shlex_split called with non-string') diff --git a/beets/util/confit.py b/beets/util/confit.py index 18f7c1e16..9474062b3 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -499,7 +499,7 @@ class Subview(ConfigView): if isinstance(self.key, int): self.name += u'#{0}'.format(self.key) elif isinstance(self.key, bytes): - self.name += self.key.decode('utf8') + self.name += self.key.decode('utf-8') elif isinstance(self.key, STRING): self.name += self.key else: @@ -1238,7 +1238,7 @@ class StrSeq(Template): def convert(self, value, view): if isinstance(value, bytes): - value = value.decode('utf8', 'ignore') + value = value.decode('utf-8', 'ignore') if isinstance(value, STRING): if self.split: @@ -1256,7 +1256,7 @@ class StrSeq(Template): if isinstance(x, STRING): return x elif isinstance(x, bytes): - return x.decode('utf8', 'ignore') + return x.decode('utf-8', 'ignore') else: self.fail(u'must be a list of strings', view, True) return list(map(convert, value)) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 463858c8c..c62abf7ab 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -212,7 +212,7 @@ class BeatportRelease(BeatportObject): ) def __repr__(self): - return six.text_type(self).encode('utf8') + return six.text_type(self).encode('utf-8') def __init__(self, data): BeatportObject.__init__(self, data) @@ -235,7 +235,7 @@ class BeatportTrack(BeatportObject): .format(artist_str, self.name, self.mix_name)) def __repr__(self): - return six.text_type(self).encode('utf8') + return six.text_type(self).encode('utf-8') def __init__(self, data): BeatportObject.__init__(self, data) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index 5b6a8a9a7..c789d32b5 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -575,7 +575,7 @@ class Connection(object): out = NEWLINE.join(lines) + NEWLINE log.debug('{}', out[:-1]) # Don't log trailing newline. if isinstance(out, six.text_type): - out = out.encode('utf8') + out = out.encode('utf-8') return self.sock.sendall(out) def do_command(self, command): diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index 471f204fb..fffa8a6ed 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -130,7 +130,7 @@ class GstPlayer(object): """ self.player.set_state(Gst.State.NULL) if isinstance(path, six.text_type): - path = path.encode('utf8') + path = path.encode('utf-8') uri = 'file://' + urllib.parse.quote(path) self.player.set_property("uri", uri) self.player.set_state(Gst.State.PLAYING) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index fc1c0588d..9b7f49e36 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -84,7 +84,7 @@ def get_format(fmt=None): if 'extension' in keys: extension = config['convert']['extension'].as_str() - return (command.encode('utf8'), extension.encode('utf8')) + return (command.encode('utf-8'), extension.encode('utf-8')) def should_transcode(item, fmt): diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index cbaa972ca..9523f57f5 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -130,7 +130,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): wl_filename = normpath(wl_filename) with open(wl_filename, 'rb') as f: for line in f: - line = line.decode('utf8').strip().lower() + line = line.decode('utf-8').strip().lower() if line and not line.startswith(u'#'): self.whitelist.add(line) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 32473dd10..f6092f625 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -79,7 +79,7 @@ URL_CHARACTERS = { def unescape(text): """Resolve &#xxx; HTML entities (and some others).""" if isinstance(text, bytes): - text = text.decode('utf8', 'ignore') + text = text.decode('utf-8', 'ignore') out = text.replace(u' ', u' ') def replchar(m): @@ -189,7 +189,7 @@ class Backend(object): if isinstance(s, six.text_type): for char, repl in URL_CHARACTERS.items(): s = s.replace(char, repl) - s = s.encode('utf8', 'ignore') + s = s.encode('utf-8', 'ignore') return urllib.parse.quote(s) def build_url(self, artist, title): @@ -265,7 +265,7 @@ class Genius(Backend): def search_genius(self, artist, title): query = u"%s %s" % (artist, title) url = u'https://api.genius.com/search?q=%s' \ - % (urllib.parse.quote(query.encode('utf8'))) + % (urllib.parse.quote(query.encode('utf-8'))) self._log.debug(u'genius: requesting search {}', url) try: @@ -551,7 +551,7 @@ class Google(Backend): query = u"%s %s" % (artist, title) url = u'https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s' \ % (self.api_key, self.engine_id, - urllib.parse.quote(query.encode('utf8'))) + urllib.parse.quote(query.encode('utf-8'))) data = urllib.request.urlopen(url) data = json.load(data) @@ -763,7 +763,7 @@ class LyricsPlugin(plugins.BeetsPlugin): self.bing_auth_token = None return self.append_translation(text, to_lang) return text - lines_translated = ET.fromstring(r.text.encode('utf8')).text + lines_translated = ET.fromstring(r.text.encode('utf-8')).text # Use a translation mapping dict to build resulting lyrics translations = dict(zip(text_lines, lines_translated.split('|'))) result = '' diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 0f78ee561..89b99a9df 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -356,11 +356,11 @@ class MPDStatsPlugin(plugins.BeetsPlugin): # Overrides for MPD settings. if opts.host: - mpd_config['host'] = opts.host.decode('utf8') + mpd_config['host'] = opts.host.decode('utf-8') if opts.port: mpd_config['host'] = int(opts.port) if opts.password: - mpd_config['password'] = opts.password.decode('utf8') + mpd_config['password'] = opts.password.decode('utf-8') try: MPDStats(lib, self._log).run() diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index a3f94bd2e..841db2cb5 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -220,7 +220,7 @@ class Bs1770gainBackend(Backend): containing information about each analyzed file. """ out = [] - data = text.decode('utf8', errors='ignore') + data = text.decode('utf-8', errors='ignore') regex = re.compile( u'(\\s{2,2}\\[\\d+\\/\\d+\\].*?|\\[ALBUM\\].*?)' '(?=\\s{2,2}\\[\\d+\\/\\d+\\]|\\s{2,2}\\[ALBUM\\]' diff --git a/extra/release.py b/extra/release.py index 7bbc080c4..1d3b7eed5 100755 --- a/extra/release.py +++ b/extra/release.py @@ -169,8 +169,8 @@ def rst2md(text): ['pandoc', '--from=rst', '--to=markdown', '--no-wrap'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) - stdout, _ = pandoc.communicate(text.encode('utf8')) - md = stdout.decode('utf8').strip() + stdout, _ = pandoc.communicate(text.encode('utf-8')) + md = stdout.decode('utf-8').strip() # Fix up odd spacing in lists. return re.sub(r'^- ', '- ', md, flags=re.M) diff --git a/test/_common.py b/test/_common.py index f2e0ddcf8..11f71a631 100644 --- a/test/_common.py +++ b/test/_common.py @@ -244,7 +244,7 @@ class InputException(Exception): class DummyOut(object): - encoding = 'utf8' + encoding = 'utf-8' def __init__(self): self.buf = [] @@ -266,7 +266,7 @@ class DummyOut(object): class DummyIn(object): - encoding = 'utf8' + encoding = 'utf-8' def __init__(self, out=None): self.buf = [] diff --git a/test/helper.py b/test/helper.py index f6b0d5ecc..795fd2ac0 100644 --- a/test/helper.py +++ b/test/helper.py @@ -90,7 +90,7 @@ def control_stdin(input=None): org = sys.stdin sys.stdin = StringIO(input) if six.PY2: # StringIO encoding attr isn't writable in python >= 3 - sys.stdin.encoding = 'utf8' + sys.stdin.encoding = 'utf-8' try: yield sys.stdin finally: @@ -110,7 +110,7 @@ def capture_stdout(): org = sys.stdout sys.stdout = capture = StringIO() if six.PY2: # StringIO encoding attr isn't writable in python >= 3 - sys.stdout.encoding = 'utf8' + sys.stdout.encoding = 'utf-8' try: yield sys.stdout finally: diff --git a/test/lyrics_download_samples.py b/test/lyrics_download_samples.py index 21c260146..9e7b69731 100644 --- a/test/lyrics_download_samples.py +++ b/test/lyrics_download_samples.py @@ -52,7 +52,7 @@ def main(argv=None): if not os.path.isfile(fn): html = requests.get(url, verify=False).text with safe_open_w(fn) as f: - f.write(html.encode('utf8')) + f.write(html.encode('utf-8')) if __name__ == "__main__": sys.exit(main()) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 0f4a20f30..3ca71352a 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -22,7 +22,7 @@ def convert(in_file, out_file, tag): """ # On Python 3, encode the tag argument as bytes. if not isinstance(tag, bytes): - tag = tag.encode('utf8') + tag = tag.encode('utf-8') # On Windows, use Unicode paths. (The test harness gives them to us # as UTF-8 bytes.) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index 8fc8532c6..bb6a56fab 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -349,7 +349,7 @@ class FormatTest(unittest.TestCase): def test_format_flex_field_bytes(self): model = TestModel1() - model.other_field = u'caf\xe9'.encode('utf8') + model.other_field = u'caf\xe9'.encode('utf-8') value = model.formatted().get('other_field') self.assertTrue(isinstance(value, six.text_type)) self.assertEqual(value, u'caf\xe9') diff --git a/test/test_edit.py b/test/test_edit.py index 2c76997a1..a23860b07 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -55,18 +55,18 @@ class ModifyFileMocker(object): `self.contents` is empty, the file remains unchanged. """ if self.contents: - with codecs.open(filename, 'w', encoding='utf8') as f: + with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(self.contents) def replace_contents(self, filename, log): """Modify `filename`, reading its contents and replacing the strings specified in `self.replacements`. """ - with codecs.open(filename, 'r', encoding='utf8') as f: + with codecs.open(filename, 'r', encoding='utf-8') as f: contents = f.read() for old, new_ in self.replacements.items(): contents = contents.replace(old, new_) - with codecs.open(filename, 'w', encoding='utf8') as f: + with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(contents) diff --git a/test/test_importer.py b/test/test_importer.py index 37550263b..55b03378c 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1465,10 +1465,10 @@ class MultiDiscAlbumsInDirTest(_common.TestCase): """Normalize a path's Unicode combining form according to the platform. """ - path = path.decode('utf8') + path = path.decode('utf-8') norm_form = 'NFD' if sys.platform == 'darwin' else 'NFC' path = unicodedata.normalize(norm_form, path) - return path.encode('utf8') + return path.encode('utf-8') def test_coalesce_nested_album_multiple_subdirs(self): self.create_music() diff --git a/test/test_library.py b/test/test_library.py index 395a811aa..742b98984 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -404,7 +404,7 @@ class DestinationTest(_common.TestCase): p = self.i.destination() self.assertFalse(b'?' in p) # We use UTF-8 to encode Windows paths now. - self.assertTrue(u'h\u0259d'.encode('utf8') in p) + self.assertTrue(u'h\u0259d'.encode('utf-8') in p) finally: sys.getfilesystemencoding = oldfunc @@ -923,7 +923,7 @@ class PathStringTest(_common.TestCase): self.assertTrue(isinstance(i.path, bytes)) def test_special_chars_preserved_in_database(self): - path = u'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf-8') self.i.path = path self.i.store() i = list(self.lib.items())[0] @@ -931,7 +931,7 @@ class PathStringTest(_common.TestCase): def test_special_char_path_added_to_database(self): self.i.remove() - path = u'b\xe1r'.encode('utf8') + path = u'b\xe1r'.encode('utf-8') i = item() i.path = path self.lib.add(i) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index fea7aebad..4e053192a 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -321,7 +321,7 @@ class SoundCheckTest(unittest.TestCase): self.assertEqual(peak, 0.0) def test_special_characters(self): - gain, peak = beets.mediafile._sc_decode(u'caf\xe9'.encode('utf8')) + gain, peak = beets.mediafile._sc_decode(u'caf\xe9'.encode('utf-8')) self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) diff --git a/test/test_play.py b/test/test_play.py index 259e59383..c05e24c51 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -78,7 +78,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): self.config['play']['relative_to'] = '/something' path = os.path.relpath(self.item.path, b'/something') - playlist = path.decode('utf8') + playlist = path.decode('utf-8') self.run_and_assert( open_mock, expected_cmd='echo', expected_playlist=playlist) diff --git a/test/test_ui.py b/test/test_ui.py index c7de8caab..38ea7cf6c 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1059,7 +1059,7 @@ class ShowChangeTest(_common.TestCase): def test_item_data_change_title_missing_with_unicode_filename(self): self.items[0].title = u'' - self.items[0].path = u'/path/to/caf\xe9.mp3'.encode('utf8') + self.items[0].path = u'/path/to/caf\xe9.mp3'.encode('utf-8') msg = re.sub(r' +', ' ', self._show_change()) self.assertTrue(u'caf\xe9.mp3 -> the title' in msg or u'caf.mp3 ->' in msg) @@ -1360,12 +1360,12 @@ class EncodingTest(_common.TestCase): def out_encoding_default_utf8(self): with patch('sys.stdout') as stdout: stdout.encoding = None - self.assertEqual(ui._out_encoding(), 'utf8') + self.assertEqual(ui._out_encoding(), 'utf-8') def in_encoding_default_utf8(self): with patch('sys.stdin') as stdin: stdin.encoding = None - self.assertEqual(ui._in_encoding(), 'utf8') + self.assertEqual(ui._in_encoding(), 'utf-8') def suite(): diff --git a/test/test_util.py b/test/test_util.py index 490992039..96d02f955 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -162,12 +162,12 @@ class PathConversionTest(_common.TestCase): def test_bytestring_path_windows_encodes_utf8(self): path = u'caf\xe9' outpath = self._windows_bytestring_path(path) - self.assertEqual(path, outpath.decode('utf8')) + self.assertEqual(path, outpath.decode('utf-8')) def test_bytesting_path_windows_removes_magic_prefix(self): path = u'\\\\?\\C:\\caf\xe9' outpath = self._windows_bytestring_path(path) - self.assertEqual(outpath, u'C:\\caf\xe9'.encode('utf8')) + self.assertEqual(outpath, u'C:\\caf\xe9'.encode('utf-8')) class PathTruncationTest(_common.TestCase): From 139d22fe9ffaa33efb771edb9558d0fb9911822c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Sep 2016 21:01:24 -0400 Subject: [PATCH 1283/2280] Template strings must always be unicode (#2188) This seems to be half the problem. --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 1c208a429..0627c8803 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -837,7 +837,7 @@ class CommonOptionsParser(optparse.OptionParser, object): """ path = optparse.Option(*flags, nargs=0, action='callback', callback=self._set_format, - callback_kwargs={'fmt': '$path', + callback_kwargs={'fmt': u'$path', 'store_true': True}, help=u'print paths for matched items or albums') self.add_option(path) From ed8d04f594f18beb30b7e367b7e4c1e7176550d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Sep 2016 21:04:05 -0400 Subject: [PATCH 1284/2280] Unicode templates in duplicates (fix #2188) --- beetsplug/duplicates.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 3c3a8de43..632b7d772 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -136,15 +136,15 @@ class DuplicatesPlugin(BeetsPlugin): items = lib.items(decargs(args)) if path: - fmt = '$path' + fmt = u'$path' # Default format string for count mode. if count and not fmt: if album: - fmt = '$albumartist - $album' + fmt = u'$albumartist - $album' else: - fmt = '$albumartist - $album - $title' - fmt += ': {0}' + fmt = u'$albumartist - $album - $title' + fmt += u': {0}' if checksum: for i in items: @@ -170,7 +170,7 @@ class DuplicatesPlugin(BeetsPlugin): return [self._command] def _process_item(self, item, copy=False, move=False, delete=False, - tag=False, fmt=''): + tag=False, fmt=u''): """Process Item `item`. """ print_(format(item, fmt)) From 15a5512ea54a5e4e1a4096869f3d4ad2e4f7555c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Sep 2016 21:42:59 -0400 Subject: [PATCH 1285/2280] Require Unicode format strings Fallout from #2188. Following @jrobeson's suggestion, I just turned the check in LibModel.__format__ into an assert. This turned up a few badly-behaved clients, which are also fixed. --- beets/library.py | 8 ++------ beetsplug/info.py | 6 +++--- beetsplug/mbsubmit.py | 4 ++-- test/test_library.py | 6 +++--- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/beets/library.py b/beets/library.py index 99df2d87b..d4b9b8189 100644 --- a/beets/library.py +++ b/beets/library.py @@ -338,12 +338,8 @@ class LibModel(dbcore.Model): def __format__(self, spec): if not spec: 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 - return result.encode('utf-8') - else: - return result + assert isinstance(spec, six.text_type) + return self.evaluate_template(spec) def __str__(self): return format(self) diff --git a/beetsplug/info.py b/beetsplug/info.py index 3865865d4..da9608d73 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -20,7 +20,6 @@ from __future__ import division, absolute_import, print_function import os import re -import six from beets.plugins import BeetsPlugin from beets import ui @@ -92,7 +91,7 @@ def print_data(data, item=None, fmt=None): """ if fmt: # use fmt specified by the user - ui.print_(six.text_type(format(item, fmt))) + ui.print_(format(item, fmt)) return path = displayable_path(item.path) if item else None @@ -205,7 +204,8 @@ class InfoPlugin(BeetsPlugin): if opts.keys_only: print_data_keys(data, item) else: - print_data(data, item, opts.format) + fmt = ui.decargs([opts.format])[0] + print_data(data, item, fmt) first = False if opts.summarize: diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 91de6128e..58b357dd3 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -36,7 +36,7 @@ class MBSubmitPlugin(BeetsPlugin): super(MBSubmitPlugin, self).__init__() self.config.add({ - 'format': '$track. $title - $artist ($length)', + 'format': u'$track. $title - $artist ($length)', 'threshold': 'medium', }) @@ -57,4 +57,4 @@ class MBSubmitPlugin(BeetsPlugin): def print_tracks(self, session, task): for i in task.items: - print_data(None, i, self.config['format'].get()) + print_data(None, i, self.config['format'].as_str()) diff --git a/test/test_library.py b/test/test_library.py index 742b98984..174e6d527 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1055,12 +1055,12 @@ class TemplateTest(_common.LibTestCase): self.assertEqual(six.text_type(album), u"foö bar") self.assertEqual(bytes(album), b"fo\xc3\xb6 bar") - config['format_item'] = 'bar $foo' + config['format_item'] = u'bar $foo' item = beets.library.Item() item.foo = u'bar' item.tagada = u'togodo' - self.assertEqual("{0}".format(item), u"bar bar") - self.assertEqual("{0:$tagada}".format(item), u"togodo") + self.assertEqual(u"{0}".format(item), u"bar bar") + self.assertEqual(u"{0:$tagada}".format(item), u"togodo") class UnicodePathTest(_common.LibTestCase): From eb58575024a68a99ea3e22284f63660aafbe83b7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Sep 2016 21:46:07 -0400 Subject: [PATCH 1286/2280] Unicode formats in a test --- test/test_mbsync.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_mbsync.py b/test/test_mbsync.py index 8e4825888..57213878c 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -100,8 +100,8 @@ class MbsyncCliTest(unittest.TestCase, TestHelper): self.assertEqual(e, logs[0]) # restore the config - config['format_item'] = '$artist - $album - $title' - config['format_album'] = '$albumartist - $album' + config['format_item'] = u'$artist - $album - $title' + config['format_album'] = u'$albumartist - $album' # Test singleton with no mb_trackid. # The default singleton format includes $artist and $album From f8a8388e0c8df3246f3977c56d1834b4bfc3d015 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 7 Sep 2016 21:47:31 -0400 Subject: [PATCH 1287/2280] Avoid using None when format is unspecified --- beetsplug/info.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/info.py b/beetsplug/info.py index da9608d73..0d40c597b 100644 --- a/beetsplug/info.py +++ b/beetsplug/info.py @@ -204,7 +204,7 @@ class InfoPlugin(BeetsPlugin): if opts.keys_only: print_data_keys(data, item) else: - fmt = ui.decargs([opts.format])[0] + fmt = ui.decargs([opts.format])[0] if opts.format else None print_data(data, item, fmt) first = False From da0e15b71e29a1fec3c7808a70b47b720612c324 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 9 Sep 2016 18:55:47 -0400 Subject: [PATCH 1288/2280] fold capture_stdout into _run_list() in test_ui --- test/test_ui.py | 37 ++++++++++++++----------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 38ea7cf6c..89e099f8a 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -51,11 +51,12 @@ class ListTest(unittest.TestCase): self.lib.add_album([self.item]) def _run_list(self, query=u'', album=False, path=False, fmt=u''): - commands.list_items(self.lib, query, album, fmt) + with capture_stdout() as stdout: + commands.list_items(self.lib, query, album, fmt) + return stdout def test_list_outputs_item(self): - with capture_stdout() as stdout: - self._run_list() + stdout = self._run_list() self.assertIn(u'the title', stdout.getvalue()) def test_list_unicode_query(self): @@ -63,59 +64,49 @@ class ListTest(unittest.TestCase): self.item.store() self.lib._connection().commit() - with capture_stdout() as stdout: - self._run_list([u'na\xefve']) + stdout = self._run_list([u'na\xefve']) out = stdout.getvalue() if six.PY2: out = out.decode(stdout.encoding) self.assertTrue(u'na\xefve' in out) def test_list_item_path(self): - with capture_stdout() as stdout: - self._run_list(fmt=u'$path') + stdout = self._run_list(fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx/yyy') def test_list_album_outputs_something(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertGreater(len(stdout.getvalue()), 0) def test_list_album_path(self): - with capture_stdout() as stdout: - self._run_list(album=True, fmt=u'$path') + stdout = self._run_list(album=True, fmt=u'$path') self.assertEqual(stdout.getvalue().strip(), u'xxx') def test_list_album_omits_title(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertNotIn(u'the title', stdout.getvalue()) def test_list_uses_track_artist(self): - with capture_stdout() as stdout: - self._run_list() + stdout = self._run_list() self.assertIn(u'the artist', stdout.getvalue()) self.assertNotIn(u'the album artist', stdout.getvalue()) def test_list_album_uses_album_artist(self): - with capture_stdout() as stdout: - self._run_list(album=True) + stdout = self._run_list(album=True) self.assertNotIn(u'the artist', stdout.getvalue()) self.assertIn(u'the album artist', stdout.getvalue()) def test_list_item_format_artist(self): - with capture_stdout() as stdout: - self._run_list(fmt=u'$artist') + stdout = self._run_list(fmt=u'$artist') self.assertIn(u'the artist', stdout.getvalue()) def test_list_item_format_multiple(self): - with capture_stdout() as stdout: - self._run_list(fmt=u'$artist - $album - $year') + stdout = self._run_list(fmt=u'$artist - $album - $year') self.assertEqual(u'the artist - the album - 0001', stdout.getvalue().strip()) def test_list_album_format(self): - with capture_stdout() as stdout: - self._run_list(album=True, fmt=u'$genre') + stdout = self._run_list(album=True, fmt=u'$genre') self.assertIn(u'the genre', stdout.getvalue()) self.assertNotIn(u'the album', stdout.getvalue()) From b63ac3aef7a586ff86fd5768a7d0bc0f0f3c7e10 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 9 Sep 2016 20:12:05 -0400 Subject: [PATCH 1289/2280] Fix a missing Python 3 dict view conversion --- beets/autotag/match.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 1b21f725a..ac213b5f9 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -425,7 +425,8 @@ def tag_album(items, search_artist=None, search_album=None, # matches. if rec == Recommendation.strong: log.debug(u'ID match.') - return cur_artist, cur_album, candidates.values(), rec + return cur_artist, cur_album, \ + list(candidates.values()), rec # Search terms. if not (search_artist and search_album): From b77991704393359712be13f1152369454d33cea9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 10 Sep 2016 02:42:17 -0400 Subject: [PATCH 1290/2280] ConfigView.set_args() can now accept dicts Credit goes to @duailibe for implementing this in the click branch --- beets/util/confit.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 9474062b3..276a8cbf9 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -245,10 +245,15 @@ class ConfigView(object): def set_args(self, namespace): """Overlay parsed command-line arguments, generated by a library - like argparse or optparse, onto this view's value. + like argparse or optparse, onto this view's value. ``namespace`` + can be a ``dict`` or namespace object. """ args = {} - for key, value in namespace.__dict__.items(): + if isinstance(namespace, dict): + items = namespace.items() + else: + items = namespace.__dict__.items() + for key, value in items: if value is not None: # Avoid unset options. args[key] = value self.set(args) From d00c0fb5cf6a2cb459041275611d317934e4f443 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 24 Jan 2016 23:14:39 -0800 Subject: [PATCH 1291/2280] Replace varargs_callback in duplicates Now you just use `-k KEY1 -k KEY2`, which seems more natural to me anyway. --- beetsplug/duplicates.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 632b7d772..5ca314d3f 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -20,7 +20,7 @@ from __future__ import division, absolute_import, print_function import shlex from beets.plugins import BeetsPlugin -from beets.ui import decargs, print_, vararg_callback, Subcommand, UserError +from beets.ui import decargs, print_, Subcommand, UserError from beets.util import command_output, displayable_path, subprocess from beets.library import Item, Album import six @@ -80,10 +80,9 @@ class DuplicatesPlugin(BeetsPlugin): help=u'report duplicates only if all attributes are set', ) self._command.parser.add_option( - u'-k', u'--keys', dest='keys', - action='callback', metavar='KEY1 KEY2', - callback=vararg_callback, - help=u'report duplicates based on keys', + u'-k', u'--key', + action='append', metavar='KEY', + help=u'report duplicates based on keys (use multiple times)', ) self._command.parser.add_option( u'-M', u'--merge', dest='merge', From 079d083a4b6fedc6ee033c3cbef15c2cd426df52 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 10 Sep 2016 04:59:41 -0400 Subject: [PATCH 1292/2280] add docs and changelog for --keys change --- docs/changelog.rst | 6 ++++++ docs/plugins/duplicates.rst | 10 +++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 950dd991d..4c94af42b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,12 @@ to know: * Please don't package beets as a Python 3 application *yet*, even though some things may appear to work under Python 3.4 and later. +UI Change: + +* :doc:`/plugins/duplicates` no longer accepts multiple arguments in the form + of ``-k title albumartist album``. Each argument must be prefixed with + ``-k``. Example: ``-k title -k albumartist -k album`` + The are a couple of small new features: * :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option diff --git a/docs/plugins/duplicates.rst b/docs/plugins/duplicates.rst index 4d8b35376..85835e2eb 100644 --- a/docs/plugins/duplicates.rst +++ b/docs/plugins/duplicates.rst @@ -28,7 +28,7 @@ duplicates themselves via command-line switches :: -d, --delete delete items from library and disk -F, --full show all versions of duplicate tracks or albums -s, --strict report duplicates only if all attributes are set - -k, --keys report duplicates based on keys + -k, --key report duplicates based on keys (can be used multiple times) -M, --merge merge duplicate items -m DEST, --move=DEST move items to dest -o DEST, --copy=DEST copy items to dest @@ -46,8 +46,8 @@ file. The available options mirror the command-line options: - **checksum**: Use an arbitrary command to compute a checksum of items. This overrides the ``keys`` option the first time it is run; however, because it caches the resulting checksum as ``flexattrs`` in the - database, you can use ``--keys=name_of_the_checksumming_program - any_other_keys`` (or set configuration ``keys`` option) the second time + database, you can use ``--key=name_of_the_checksumming_program + --key=any_other_keys`` (or set configuration ``keys`` option) the second time around. Default: ``ffmpeg -i {file} -f crc -``. - **copy**: A destination base directory into which to copy matched @@ -120,7 +120,7 @@ The same as the above but include the original album, and show the path:: Get tracks with the same title, artist, and album:: - beet duplicates -k title albumartist album + beet duplicates -k title -k albumartist -k album Compute Adler CRC32 or MD5 checksums, storing them as flexattrs, and report back duplicates based on those values:: @@ -138,7 +138,7 @@ Move likely duplicates to ``trash`` directory:: Delete items (careful!), if they're Nickelback:: - beet duplicates --delete --keys albumartist albumartist:nickelback + beet duplicates --delete -k albumartist -k albumartist:nickelback Tag duplicate items with some flag:: From cc5012fda23e3f4962de08483f7792ecffea296e Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 10 Sep 2016 16:53:53 -0400 Subject: [PATCH 1293/2280] slight language tweak in duplicates plugin docs Suggested by @sampsyo in https://github.com/beetbox/beets/pull/2193 --- docs/plugins/duplicates.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/duplicates.rst b/docs/plugins/duplicates.rst index 85835e2eb..8b11b6661 100644 --- a/docs/plugins/duplicates.rst +++ b/docs/plugins/duplicates.rst @@ -47,8 +47,8 @@ file. The available options mirror the command-line options: of items. This overrides the ``keys`` option the first time it is run; however, because it caches the resulting checksum as ``flexattrs`` in the database, you can use ``--key=name_of_the_checksumming_program - --key=any_other_keys`` (or set configuration ``keys`` option) the second time - around. + --key=any_other_keys`` (or set the ``keys`` configuration option) the second + time around. Default: ``ffmpeg -i {file} -f crc -``. - **copy**: A destination base directory into which to copy matched items. From 925d7bebf9e8408d5bf56a6eb34211d38dd43425 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 10 Sep 2016 16:59:04 -0400 Subject: [PATCH 1294/2280] drop vararg_callback as the only caller is gone. It was used only in the duplicates plugin --- beets/ui/__init__.py | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 0627c8803..7062d8078 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1051,42 +1051,6 @@ class SubcommandsOptionParser(CommonOptionsParser): optparse.Option.ALWAYS_TYPED_ACTIONS += ('callback',) -def vararg_callback(option, opt_str, value, parser): - """Callback for an option with variable arguments. - Manually collect arguments right of a callback-action - option (ie. with action="callback"), and add the resulting - list to the destination var. - - Usage: - parser.add_option("-c", "--callback", dest="vararg_attr", - action="callback", callback=vararg_callback) - - Details: - http://docs.python.org/2/library/optparse.html#callback-example-6-variable - -arguments - """ - value = [value] - - def floatable(str): - try: - float(str) - return True - except ValueError: - return False - - for arg in parser.rargs: - # stop on --foo like options - if arg[:2] == "--" and len(arg) > 2: - break - # stop on -a, but not on -3 or -3.0 - if arg[:1] == "-" and len(arg) > 1 and not floatable(arg): - break - value.append(arg) - - del parser.rargs[:len(value) - 1] - setattr(parser.values, option.dest, value) - - # The main entry point and bootstrapping. def _load_plugins(config): From d384b07914457ad960f633a12776a2c7ba9e086a Mon Sep 17 00:00:00 2001 From: "Cody W. Opel" Date: Mon, 12 Sep 2016 09:29:32 -0400 Subject: [PATCH 1295/2280] fromfilename: fix dict view conversion for python3 (fix #2195) dict.values() returns a view rather than a list in python3 --- beetsplug/fromfilename.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index 648df6258..5e1b822c2 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -101,7 +101,7 @@ def apply_matches(d): """Given a mapping from items to field dicts, apply the fields to the objects. """ - some_map = d.values()[0] + some_map = list(d.values())[0] keys = some_map.keys() # Only proceed if the "tag" field is equal across all filenames. From db782a2404fa8a6827c10a6536b4a960d19af135 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Wed, 14 Sep 2016 00:40:53 -0400 Subject: [PATCH 1296/2280] wrap 2 results in a list in cue and random plugin --- beetsplug/cue.py | 2 +- beetsplug/random.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/cue.py b/beetsplug/cue.py index 63051bfc1..fd564b55c 100644 --- a/beetsplug/cue.py +++ b/beetsplug/cue.py @@ -35,7 +35,7 @@ class CuePlugin(BeetsPlugin): return if len(cues) > 1: self._log.info(u"Found multiple cue files doing nothing: {0}", - map(displayable_path, cues)) + list(map(displayable_path, cues))) cue_file = cues[0] self._log.info("Found {} for {}", displayable_path(cue_file), item) diff --git a/beetsplug/random.py b/beetsplug/random.py index e1c6fea4a..a0719dcad 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -48,7 +48,7 @@ def random_item(lib, opts, args): # Choose an artist and an object for that artist, removing # this choice from the pool. - artist = random.choice(objs_by_artists.keys()) + artist = random.choice(list(objs_by_artists.keys())) objs_from_artist = objs_by_artists[artist] i = random.randint(0, len(objs_from_artist) - 1) objs.append(objs_from_artist.pop(i)) From bdb2de69bbf3780c18b701683c518828689734e3 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 16 Sep 2016 23:29:29 -0400 Subject: [PATCH 1297/2280] add python 3.6 to tox.ini --- tox.ini | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 648054b89..c22fb1c6f 100644 --- a/tox.ini +++ b/tox.ini @@ -38,15 +38,16 @@ passenv = deps = {test,cov}: {[_test]deps} py27: pathlib - py{27,34,35}-flake8: {[_flake8]deps} + py{27,34,35,36}-flake8: {[_flake8]deps} commands = py27-cov: python -m nose --with-coverage {posargs} py27-test: python -m nose {posargs} py{34,35}-cov: python -bb -m nose --with-coverage {posargs} - py{34,35}-test: python -bb -m nose {posargs} + py{34,35,36}-test: python -bb -m nose {posargs} py27-flake8: flake8 --min-version 2.7 {posargs} {[_flake8]files} py34-flake8: flake8 --min-version 3.4 {posargs} {[_flake8]files} py35-flake8: flake8 --min-version 3.5 {posargs} {[_flake8]files} + py36-flake8: flake8 --min-version 3.6 {posargs} {[_flake8]files} [testenv:docs] basepython = python2.7 From d585019ab32f55884360e6662b21a037ed4846f4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 17 Sep 2016 21:59:56 -0400 Subject: [PATCH 1298/2280] Remove indirect run_command() in test_info.py This was breaking the `info` command in the click branch. I assume that was because `run_command` was aliased to `run_with_output`. It was also confusing in its own right, so I consider it a win either way. --- test/test_info.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/test/test_info.py b/test/test_info.py index 0ac1f95dd..f7973796e 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -32,9 +32,6 @@ class InfoTest(unittest.TestCase, TestHelper): self.unload_plugins() self.teardown_beets() - def run_command(self, *args): - super(InfoTest, self).run_command('info', *args) - def test_path(self): path = self.create_mediafile_fixture() @@ -45,7 +42,7 @@ class InfoTest(unittest.TestCase, TestHelper): mediafile.composer = None mediafile.save() - out = self.run_with_output(path) + out = self.run_with_output('info', path) self.assertIn(path, out) self.assertIn('albumartist: AAA', out) self.assertIn('disctitle: DDD', out) @@ -60,7 +57,7 @@ class InfoTest(unittest.TestCase, TestHelper): item1.album = 'yyyy' item1.store() - out = self.run_with_output('album:yyyy') + out = self.run_with_output('info', 'album:yyyy') self.assertIn(displayable_path(item1.path), out) self.assertIn(u'album: xxxx', out) @@ -71,7 +68,7 @@ class InfoTest(unittest.TestCase, TestHelper): item.album = 'xxxx' item.store() - out = self.run_with_output('--library', 'album:xxxx') + out = self.run_with_output('info', '--library', 'album:xxxx') self.assertIn(displayable_path(item.path), out) self.assertIn(u'album: xxxx', out) @@ -89,7 +86,7 @@ class InfoTest(unittest.TestCase, TestHelper): item.store() mediafile.save() - out = self.run_with_output('--summarize', 'album:AAA', path) + out = self.run_with_output('info', '--summarize', 'album:AAA', path) self.assertIn(u'album: AAA', out) self.assertIn(u'tracktotal: 5', out) self.assertIn(u'title: [various]', out) @@ -100,7 +97,7 @@ class InfoTest(unittest.TestCase, TestHelper): item.album = 'xxxx' item.store() - out = self.run_with_output('--library', 'album:xxxx', + out = self.run_with_output('info', '--library', 'album:xxxx', '--include-keys', '*lbu*') self.assertIn(displayable_path(item.path), out) self.assertNotIn(u'title:', out) @@ -108,7 +105,7 @@ class InfoTest(unittest.TestCase, TestHelper): def test_custom_format(self): self.add_item_fixtures() - out = self.run_with_output('--library', '--format', + out = self.run_with_output('info', '--library', '--format', '$track. $title - $artist ($length)') self.assertEqual(u'02. tïtle 0 - the artist (0:01)\n', out) From ddaa94003bca853819855014b7d99c165c890de8 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 18 Sep 2016 03:17:44 -0400 Subject: [PATCH 1299/2280] add yaml output command func to config_command tests --- test/test_config_command.py | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/test/test_config_command.py b/test/test_config_command.py index b0240574c..3f0da5f18 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -43,40 +43,41 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): def tearDown(self): rmtree(self.temp_dir) - def test_show_user_config(self): + def _run_with_yaml_output(self, *args): with capture_stdout() as output: - self.run_command('config', '-c') - output = yaml.load(output.getvalue()) + self.run_command(*args) + return yaml.load(output.getvalue()) + + def test_show_user_config(self): + output = self._run_with_yaml_output('config', '-c') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'password_value') def test_show_user_config_with_defaults(self): - with capture_stdout() as output: - self.run_command('config', '-dc') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config', '-dc') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'password_value') self.assertEqual(output['library'], 'lib') self.assertEqual(output['import']['timid'], False) def test_show_user_config_with_cli(self): - with capture_stdout() as output: - self.run_command('--config', self.cli_config_path, 'config') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('--config', self.cli_config_path, + 'config') + self.assertEqual(output['library'], 'lib') self.assertEqual(output['option'], 'cli overwrite') def test_show_redacted_user_config(self): - with capture_stdout() as output: - self.run_command('config') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'REDACTED') def test_show_redacted_user_config_with_defaults(self): - with capture_stdout() as output: - self.run_command('config', '-d') - output = yaml.load(output.getvalue()) + output = self._run_with_yaml_output('config', '-d') + self.assertEqual(output['option'], 'value') self.assertEqual(output['password'], 'REDACTED') self.assertEqual(output['import']['timid'], False) From ec4eb8368eedab395732fb94e80f44477102014a Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 18 Sep 2016 03:29:04 -0400 Subject: [PATCH 1300/2280] Replace capture_stdout in test_config_command I didn't see a good reason not to use `run_with_command` here --- test/test_config_command.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/test/test_config_command.py b/test/test_config_command.py index 3f0da5f18..26242132d 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -12,7 +12,7 @@ from beets import ui from beets import config from test._common import unittest -from test.helper import TestHelper, capture_stdout +from test.helper import TestHelper from beets.library import Library import six @@ -44,9 +44,8 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): rmtree(self.temp_dir) def _run_with_yaml_output(self, *args): - with capture_stdout() as output: - self.run_command(*args) - return yaml.load(output.getvalue()) + output = self.run_with_output(*args) + return yaml.load(output) def test_show_user_config(self): output = self._run_with_yaml_output('config', '-c') @@ -83,16 +82,16 @@ class ConfigCommandTest(unittest.TestCase, TestHelper): self.assertEqual(output['import']['timid'], False) def test_config_paths(self): - with capture_stdout() as output: - self.run_command('config', '-p') - paths = output.getvalue().split('\n') + output = self.run_with_output('config', '-p') + + paths = output.split('\n') self.assertEqual(len(paths), 2) self.assertEqual(paths[0], self.config_path) def test_config_paths_with_cli(self): - with capture_stdout() as output: - self.run_command('--config', self.cli_config_path, 'config', '-p') - paths = output.getvalue().split('\n') + output = self.run_with_output('--config', self.cli_config_path, + 'config', '-p') + paths = output.split('\n') self.assertEqual(len(paths), 3) self.assertEqual(paths[0], self.cli_config_path) From 49fc2ac5e9b137bd84639c550773546bb0962759 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 18 Sep 2016 03:31:00 -0400 Subject: [PATCH 1301/2280] Use run_with_command in write_cmd in test_ui.py --- test/test_ui.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 89e099f8a..31f3f37da 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -354,7 +354,7 @@ class WriteTest(unittest.TestCase, TestHelper): self.teardown_beets() def write_cmd(self, *args): - self.run_command('write', *args) + return self.run_with_output('write', *args) def test_update_mtime(self): item = self.add_item_fixture() @@ -380,10 +380,9 @@ class WriteTest(unittest.TestCase, TestHelper): item.bitrate = 123 item.store() - with capture_stdout() as stdout: - self.write_cmd() + output = self.write_cmd() - self.assertEqual(stdout.getvalue(), '') + self.assertEqual(output, '') def test_write_metadata_field(self): item = self.add_item_fixture() @@ -393,11 +392,10 @@ class WriteTest(unittest.TestCase, TestHelper): item.title = u'new title' item.store() - with capture_stdout() as stdout: - self.write_cmd() + output = self.write_cmd() self.assertTrue(u'{0} -> new title'.format(old_title) - in stdout.getvalue()) + in output) class MoveTest(_common.TestCase): From 009108627d72c7e530733c20fc0f0413726e8c4c Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 18 Sep 2016 17:57:43 -0400 Subject: [PATCH 1302/2280] Add python 3.6-dev to Travis (#2198) [appveyor skip] --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d3633fdb4..d5191e30c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,13 +15,16 @@ matrix: env: {TOX_ENV: py34-test} - python: 3.5 env: {TOX_ENV: py35-test} + - python: 3.6-dev + env: {TOX_ENV: py36-test} # - python: pypy # - env: {TOX_ENV: pypy-test} - python: 3.4 env: {TOX_ENV: py34-flake8} - python: 2.7 env: {TOX_ENV: docs} - + allow_failures: + - python: 3.6-dev # Non-Python dependencies. addons: apt: From 6b73aa25d2bffdb9e0bdcbe925af0e78af9c1cce Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 20 Sep 2016 17:38:39 -0400 Subject: [PATCH 1303/2280] Use b'' in discogs medium query regex Since the first arg to `re.sub()` is bytes, thus must be the replacement string. --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index a31c575d3..0e12d0acb 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -200,7 +200,7 @@ class DiscogsPlugin(BeetsPlugin): query = re.sub(r'(?u)\W+', ' ', query).encode('ascii', "replace") # Strip medium information from query, Things like "CD1" and "disk 1" # can also negate an otherwise positive result. - query = re.sub(br'(?i)\b(CD|disc)\s*\d+', '', query) + query = re.sub(br'(?i)\b(CD|disc)\s*\d+', b'', query) try: releases = self.discogs_client.search(query, type='release').page(1) From 4b702b338e0dcc83a1abe85eb311fb2fe8ae0fa3 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Fri, 23 Sep 2016 22:21:00 +0200 Subject: [PATCH 1304/2280] lyrics: reduce code duplication in search_pairs() --- beetsplug/lyrics.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f6092f625..b2e5b5f0d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -144,29 +144,29 @@ def search_pairs(item): The method also tries to split multiple titles separated with `/`. """ + def strip_part(string, pattern): + """Return first matching group if string matches pattern, the full + string otherwise.""" + match = re.search(pattern, string, re.IGNORECASE) + if match: + return match.group(1) + return string + title, artist = item.title, item.artist - titles = [title] - artists = [artist] + titles = set([title]) + artists = set([artist]) # Remove any featuring artists from the artists name - pattern = r"(.*?) {0}".format(plugins.feat_tokens()) - match = re.search(pattern, artist, re.IGNORECASE) - if match: - artists.append(match.group(1)) + artists.add(strip_part(artist, r"(.*?) {0}".format(plugins.feat_tokens()))) # Remove a parenthesized suffix from a title string. Common # examples include (live), (remix), and (acoustic). - pattern = r"(.+?)\s+[(].*[)]$" - match = re.search(pattern, title, re.IGNORECASE) - if match: - titles.append(match.group(1)) + titles.add(strip_part(title, r"(.+?)\s+[(].*[)]$")) # Remove any featuring artists from the title pattern = r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)) - for title in titles[:]: - match = re.search(pattern, title, re.IGNORECASE) - if match: - titles.append(match.group(1)) + for title in list(titles): + titles.add(strip_part(title, pattern)) # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe) # and each of them. From 8b4f39da422de4b3a90e07fcd00bc76b7dcbd6c2 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Fri, 23 Sep 2016 22:23:32 +0200 Subject: [PATCH 1305/2280] lyrics: search for song title part preceding colon. fix #2205 --- beetsplug/lyrics.py | 3 +++ test/test_lyrics.py | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b2e5b5f0d..dc069e430 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -168,6 +168,9 @@ def search_pairs(item): for title in list(titles): titles.add(strip_part(title, pattern)) + # Remove part of the title string after colon ':' + titles.add(strip_part(title, r"(.+?)\s*:.*")) + # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe) # and each of them. multi_titles = [] diff --git a/test/test_lyrics.py b/test/test_lyrics.py index d49c4d980..797a227be 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -84,6 +84,7 @@ class LyricsPluginTest(unittest.TestCase): self.assertIn(('Alice', ['song']), lyrics.search_pairs(item)) + def test_search_pairs_multi_titles(self): item = Item(title='1 / 2', artist='A') self.assertIn(('A', ['1 / 2']), lyrics.search_pairs(item)) @@ -118,6 +119,10 @@ class LyricsPluginTest(unittest.TestCase): self.assertNotIn(('A', ['Song']), lyrics.search_pairs(item)) self.assertIn(('A', ['Song and B']), lyrics.search_pairs(item)) + item = Item(title='Song: B', artist='A') + self.assertIn(('A', ['Song']), lyrics.search_pairs(item)) + self.assertIn(('A', ['Song: B']), lyrics.search_pairs(item)) + def test_remove_credits(self): self.assertEqual( lyrics.remove_credits("""It's close to midnight From 059be3b94ca0fb3df462873f0500855c117088ab Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Fri, 23 Sep 2016 22:41:44 +0200 Subject: [PATCH 1306/2280] test_lyrics: fix too many blank lines --- test/test_lyrics.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 797a227be..0e9f13043 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -84,7 +84,6 @@ class LyricsPluginTest(unittest.TestCase): self.assertIn(('Alice', ['song']), lyrics.search_pairs(item)) - def test_search_pairs_multi_titles(self): item = Item(title='1 / 2', artist='A') self.assertIn(('A', ['1 / 2']), lyrics.search_pairs(item)) From 7e15ac069577eed6aa751a5e66bd3c50c7ddd537 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Fri, 23 Sep 2016 23:11:27 +0200 Subject: [PATCH 1307/2280] add changelog --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4c94af42b..2f09c0599 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -60,6 +60,8 @@ And there are a few bug fixes too: This is fixed. :bug:`2168` * :doc:`/plugins/embyupdate`: Fixes authentication header problem that caused a problem that it was not possible to get tokens from the Emby API. +* :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the + colon character. :bug:`2206` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 3db656a6853d78b671c50a811a7821b25a06c8bb Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 24 Sep 2016 01:16:56 -0400 Subject: [PATCH 1308/2280] use py3_path on gstreamer location prop setters Location properties require strings, so we give them to them! --- beetsplug/replaygain.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 841db2cb5..2d3af58a6 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -26,7 +26,7 @@ from six.moves import zip from beets import logging from beets import ui from beets.plugins import BeetsPlugin -from beets.util import syspath, command_output, displayable_path +from beets.util import syspath, command_output, displayable_path, py3_path # Utilities. @@ -574,7 +574,7 @@ class GStreamerBackend(Backend): self._file = self._files.pop(0) self._pipe.set_state(self.Gst.State.NULL) - self._src.set_property("location", syspath(self._file.path)) + self._src.set_property("location", py3_path(syspath(self._file.path))) self._pipe.set_state(self.Gst.State.PLAYING) return True @@ -595,7 +595,7 @@ class GStreamerBackend(Backend): # Set a new file on the filesrc element, can only be done in the # READY state self._src.set_state(self.Gst.State.READY) - self._src.set_property("location", syspath(self._file.path)) + self._src.set_property("location", py3_path(syspath(self._file.path))) # Ensure the filesrc element received the paused state of the # pipeline in a blocking manner From 1a8b20f3541992d4e5c575bfa2b166be5f5868df Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 25 Sep 2016 03:14:24 -0400 Subject: [PATCH 1309/2280] Expose split arg from StrSeq in as_str_seq --- beets/util/confit.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 276a8cbf9..373e05ffc 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -407,11 +407,11 @@ class ConfigView(object): """ return self.get(Number()) - def as_str_seq(self): + def as_str_seq(self, split=True): """Get the value as a sequence of strings. Equivalent to `get(StrSeq())`. """ - return self.get(StrSeq()) + return self.get(StrSeq(split=split)) def as_str(self): """Get the value as a (Unicode) string. Equivalent to From 623dee064ab8d7b9c6d3ceb389c2bf73d3a530ef Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 25 Sep 2016 03:17:43 -0400 Subject: [PATCH 1310/2280] Use as_str_seq in pluginpath --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 7062d8078..422055dbd 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1056,7 +1056,7 @@ optparse.Option.ALWAYS_TYPED_ACTIONS += ('callback',) def _load_plugins(config): """Load the plugins specified in the configuration. """ - paths = config['pluginpath'].get(confit.StrSeq(split=False)) + paths = config['pluginpath'].as_str_seq(split=False) paths = [util.normpath(p) for p in paths] log.debug(u'plugin paths: {0}', util.displayable_path(paths)) From e2703b9a7cf79b66027840b6869104e049a8418e Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 25 Sep 2016 15:46:22 +0200 Subject: [PATCH 1311/2280] always yield item artist and title first Rather than using an unordered set for storing pairs, append to a list and build an OrderedDict from it to filter duplicated strings while keeping order. --- beetsplug/lyrics.py | 22 ++++++++++++++-------- test/test_lyrics.py | 4 ++++ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index dc069e430..179f0c0b6 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -25,8 +25,9 @@ import re import requests import unicodedata import warnings -from six.moves import urllib import six +from six.moves import urllib +from collections import OrderedDict try: from bs4 import SoupStrainer, BeautifulSoup @@ -153,23 +154,28 @@ def search_pairs(item): return string title, artist = item.title, item.artist - titles = set([title]) - artists = set([artist]) + titles = [title] + artists = [artist] # Remove any featuring artists from the artists name - artists.add(strip_part(artist, r"(.*?) {0}".format(plugins.feat_tokens()))) + artists.append( + strip_part(artist, r"(.*?) {0}".format(plugins.feat_tokens()))) # Remove a parenthesized suffix from a title string. Common # examples include (live), (remix), and (acoustic). - titles.add(strip_part(title, r"(.+?)\s+[(].*[)]$")) + titles.append(strip_part(title, r"(.+?)\s+[(].*[)]$")) # Remove any featuring artists from the title pattern = r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)) for title in list(titles): - titles.add(strip_part(title, pattern)) + titles.append(strip_part(title, pattern)) - # Remove part of the title string after colon ':' - titles.add(strip_part(title, r"(.+?)\s*:.*")) + # Remove part of the title string after colon ':' for songs with subtitles + titles.append(strip_part(title, r"(.+?)\s*:.*")) + + # Yield artist and title obtained from item first + titles = list(OrderedDict.fromkeys([title] + titles)) + artists = list(OrderedDict.fromkeys([artist] + artists)) # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe) # and each of them. diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 0e9f13043..429dee4e8 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -84,6 +84,10 @@ class LyricsPluginTest(unittest.TestCase): self.assertIn(('Alice', ['song']), lyrics.search_pairs(item)) + item = Item(artist='Alice and Bob', title='song') + self.assertEqual(('Alice and Bob', ['song']), + list(lyrics.search_pairs(item))[0]) + def test_search_pairs_multi_titles(self): item = Item(title='1 / 2', artist='A') self.assertIn(('A', ['1 / 2']), lyrics.search_pairs(item)) From 722662440552bd28d6fb9bf6f2e06314ca5826da Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 25 Sep 2016 19:37:14 +0200 Subject: [PATCH 1312/2280] replace strip_part() by generate_alternatives() Delegate the update of titles and artists lists to the helper generate_alternatives() function. --- beetsplug/lyrics.py | 50 ++++++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 28 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 179f0c0b6..92757a40a 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -27,7 +27,6 @@ import unicodedata import warnings import six from six.moves import urllib -from collections import OrderedDict try: from bs4 import SoupStrainer, BeautifulSoup @@ -145,37 +144,32 @@ def search_pairs(item): The method also tries to split multiple titles separated with `/`. """ - def strip_part(string, pattern): - """Return first matching group if string matches pattern, the full - string otherwise.""" - match = re.search(pattern, string, re.IGNORECASE) - if match: - return match.group(1) - return string + def generate_alternatives(string, patterns): + """Generate string alternatives by extracting first matching group for + each given pattern.""" + alternatives = [string] + for pattern in patterns: + match = re.search(pattern, string, re.IGNORECASE) + if match: + alternatives.append(match.group(1)) + return alternatives title, artist = item.title, item.artist - titles = [title] - artists = [artist] - # Remove any featuring artists from the artists name - artists.append( - strip_part(artist, r"(.*?) {0}".format(plugins.feat_tokens()))) + patterns = [ + # Remove any featuring artists from the artists name + r"(.*?) {0}".format(plugins.feat_tokens())] + artists = generate_alternatives(artist, patterns) - # Remove a parenthesized suffix from a title string. Common - # examples include (live), (remix), and (acoustic). - titles.append(strip_part(title, r"(.+?)\s+[(].*[)]$")) - - # Remove any featuring artists from the title - pattern = r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)) - for title in list(titles): - titles.append(strip_part(title, pattern)) - - # Remove part of the title string after colon ':' for songs with subtitles - titles.append(strip_part(title, r"(.+?)\s*:.*")) - - # Yield artist and title obtained from item first - titles = list(OrderedDict.fromkeys([title] + titles)) - artists = list(OrderedDict.fromkeys([artist] + artists)) + patterns = [ + # Remove a parenthesized suffix from a title string. Common + # examples include (live), (remix), and (acoustic). + r"(.+?)\s+[(].*[)]$", + # Remove any featuring artists from the title + r"(.*?) {0}".format(plugins.feat_tokens(for_artist=False)), + # Remove part of title after colon ':' for songs with subtitles + r"(.+?)\s*:.*"] + titles = generate_alternatives(title, patterns) # Check for a dual song (e.g. Pink Floyd - Speak to Me / Breathe) # and each of them. From 2e0775c0fe042c8d94775dbe2e7518ddae147ba2 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 25 Sep 2016 15:34:01 -0400 Subject: [PATCH 1313/2280] add site-packages tests to the travis build matrix (#2183) Add `with_system_site_packages` variants of the two installed pythons (2.7, 3.4) so any plugin requiring pygobject/gstreamer can be tested with the CI system. [appveyor skip] --- .travis.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d5191e30c..bb67723f5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,8 +11,12 @@ matrix: include: - python: 2.7 env: {TOX_ENV: py27-cov, COVERAGE: 1} + - python: 2.7_with_system_site_packages + env: {TOX_ENV: py27-test} - python: 3.4 env: {TOX_ENV: py34-test} + - python: 3.4_with_system_site_packages + env: {TOX_ENV: py34-test} - python: 3.5 env: {TOX_ENV: py35-test} - python: 3.6-dev @@ -51,7 +55,13 @@ install: - travis_retry pip install tox sphinx - travis_retry tox -e $TOX_ENV --notest -script: tox -e $TOX_ENV +script: + # prevents "libdc1394 error: Failed to initialize libdc1394" errors + - sudo ln -s /dev/null /dev/raw1394 + - if [[ $TRAVIS_PYTHON_VERSION == *_site_packages ]]; then SITE_PACKAGES=--sitepackages; fi + # pip in trusty breaks on packages prefixed with "_". See https://github.com/pypa/pip/issues/3681 + - if [[ $TRAVIS_PYTHON_VERSION == 3.4_with_system_site_packages ]]; then sudo rm -rf /usr/lib/python3/dist-packages/_lxc-0.1.egg-info; fi + - tox -e $TOX_ENV $SITE_PACKAGES # Report coverage to codecov.io. before_install: From be8fe8753c5c06534fed7e21ca9d1fa7eb236f73 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 25 Sep 2016 22:56:29 -0400 Subject: [PATCH 1314/2280] Remove deprecated top level colors config option (#2209) It was deprecated in https://github.com/beetbox/beets/commit/d3fce35481f09f28561dc2438baa7ec5245b7870 on 2015-01-25. --- beets/ui/__init__.py | 8 -------- docs/changelog.rst | 4 ++++ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 422055dbd..19ab8b949 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1121,14 +1121,6 @@ def _configure(options): else: log.set_global_level(logging.INFO) - # Ensure compatibility with old (top-level) color configuration. - # Deprecation msg to motivate user to switch to config['ui']['color]. - if config['color'].exists(): - log.warning(u'Warning: top-level configuration of `color` ' - u'is deprecated. Configure color use under `ui`. ' - u'See documentation for more info.') - config['ui']['color'].set(config['color'].get(bool)) - # Compatibility from list_format_{item,album} to format_{item,album} for elem in ('item', 'album'): old_key = 'list_format_{0}'.format(elem) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2f09c0599..a15019e2e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,10 @@ UI Change: of ``-k title albumartist album``. Each argument must be prefixed with ``-k``. Example: ``-k title -k albumartist -k album`` +Deprecated configuration optional removals: + +* Remove top level ``colors`` configuration option. + The are a couple of small new features: * :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option From ffa4dfaac03a92362afa6a5f99ae4baae6cf4e72 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sun, 25 Sep 2016 23:28:44 -0400 Subject: [PATCH 1315/2280] Remove deprecated list_format_{album|item} config It was deprecated in https://github.com/beetbox/beets/commit/f14f47f059459118a5d3f9123c5f72a948ac3a4c on 2015-03-04. --- beets/ui/__init__.py | 14 -------------- docs/changelog.rst | 2 ++ 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 19ab8b949..ae30a9c60 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1121,20 +1121,6 @@ def _configure(options): else: log.set_global_level(logging.INFO) - # Compatibility from list_format_{item,album} to format_{item,album} - for elem in ('item', 'album'): - old_key = 'list_format_{0}'.format(elem) - if config[old_key].exists(): - new_key = 'format_{0}'.format(elem) - 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.', - old_key, - new_key, - ) - config[new_key].set(config[old_key]) - config_path = config.user_config_path() if os.path.isfile(config_path): log.debug(u'user configuration: {0}', diff --git a/docs/changelog.rst b/docs/changelog.rst index a15019e2e..699a3c500 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ UI Change: Deprecated configuration optional removals: * Remove top level ``colors`` configuration option. +* Remove deprecated ``list_format_album`` and ``list_format_item`` + configuration options. The are a couple of small new features: From 288ff6ba198e89ee74ab25e6db6a31b33c9a0134 Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Mon, 26 Sep 2016 16:12:38 -0400 Subject: [PATCH 1316/2280] Add specificity option to lastgenre in order to prefer the most specific genres --- beetsplug/lastgenre/__init__.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index cbaa972ca..373fea56c 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -109,6 +109,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): 'force': True, 'auto': True, 'separator': u', ', + 'specificity': False, }) self.setup() @@ -158,6 +159,27 @@ class LastGenrePlugin(plugins.BeetsPlugin): elif source == 'artist': return 'artist', + def _get_depth(self, tag): + """Find the depth of a tag in the genres tree. + """ + depth = None + for key, value in enumerate(self.c14n_branches): + if tag in value: + depth = value.index(tag) + break + return depth + + def _sort_by_depth(self, tags): + """Given a list of tags, sort the tags by their depths in the + genre tree. + """ + tags_by_depth = [] + for key, value in enumerate(tags): + depth = self._get_depth(value) + tags_by_depth.append({'tag': value, 'depth': depth}) + tags_by_depth = sorted(tags_by_depth, key=lambda k: k['depth'], reverse=True) + return [i['tag'] for i in tags_by_depth] + def _resolve_genres(self, tags): """Given a list of strings, return a genre by joining them into a single string and (optionally) canonicalizing each. @@ -179,12 +201,18 @@ class LastGenrePlugin(plugins.BeetsPlugin): parents = [find_parents(tag, self.c14n_branches)[-1]] tags_all += parents - if len(tags_all) >= count: + # Don't break here if we need to sort by specificity, which happens with + # the full tag list below + if not self.config['specificity'] and len(tags_all) >= count: break tags = tags_all tags = deduplicate(tags) + # sort the tags by specificity + if self.config['specificity']: + tags = self._sort_by_depth(tags) + # c14n only adds allowed genres but we may have had forbidden genres in # the original tags list tags = [x.title() for x in tags if self._is_allowed(x)] From fa70c48bf91a04043fd30cd7fa9423933007f35f Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 26 Sep 2016 16:49:43 -0400 Subject: [PATCH 1317/2280] Add unrar installation to appveyor.yml --- appveyor.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/appveyor.yml b/appveyor.yml index d28146402..974bff4db 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -20,6 +20,7 @@ environment: # Install Tox for running tests. install: - cinst imagemagick -y + - cinst unrar -y - "%PYTHON%/Scripts/pip.exe install tox" - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" From be5ce3194f4f3ad74e0b9e38d47f78a895de58b6 Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Mon, 26 Sep 2016 19:02:10 -0400 Subject: [PATCH 1318/2280] better syntax; better comments --- beetsplug/lastgenre/__init__.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 373fea56c..0faa587c2 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -173,12 +173,9 @@ class LastGenrePlugin(plugins.BeetsPlugin): """Given a list of tags, sort the tags by their depths in the genre tree. """ - tags_by_depth = [] - for key, value in enumerate(tags): - depth = self._get_depth(value) - tags_by_depth.append({'tag': value, 'depth': depth}) - tags_by_depth = sorted(tags_by_depth, key=lambda k: k['depth'], reverse=True) - return [i['tag'] for i in tags_by_depth] + depth_tag_pairs = [(self._get_depth(t), t) for t in tags] + depth_tag_pairs.sort(reverse=True) + return [p[1] for p in depth_tag_pairs] def _resolve_genres(self, tags): """Given a list of strings, return a genre by joining them into a @@ -201,15 +198,15 @@ class LastGenrePlugin(plugins.BeetsPlugin): parents = [find_parents(tag, self.c14n_branches)[-1]] tags_all += parents - # Don't break here if we need to sort by specificity, which happens with - # the full tag list below + # Stop if we have enough tags already, unless we need to find + # the most specific tag (instead of the most popular). if not self.config['specificity'] and len(tags_all) >= count: break tags = tags_all tags = deduplicate(tags) - # sort the tags by specificity + # Sort the tags by specificity. if self.config['specificity']: tags = self._sort_by_depth(tags) From c10fe1e126b628945da0d0e2aafd1536e1ebb62a Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Mon, 26 Sep 2016 19:06:34 -0400 Subject: [PATCH 1319/2280] change option name to prefer_specific --- beetsplug/lastgenre/__init__.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 0faa587c2..7c1cddf04 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -109,7 +109,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): 'force': True, 'auto': True, 'separator': u', ', - 'specificity': False, + 'prefer_specific': False, }) self.setup() @@ -200,14 +200,15 @@ class LastGenrePlugin(plugins.BeetsPlugin): tags_all += parents # Stop if we have enough tags already, unless we need to find # the most specific tag (instead of the most popular). - if not self.config['specificity'] and len(tags_all) >= count: + if (not self.config['prefer_specific'] and + len(tags_all) >= count): break tags = tags_all tags = deduplicate(tags) # Sort the tags by specificity. - if self.config['specificity']: + if self.config['prefer_specific']: tags = self._sort_by_depth(tags) # c14n only adds allowed genres but we may have had forbidden genres in From a9ac2fa9c8e5b212160b07855fc2f012a0cea0d0 Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Mon, 26 Sep 2016 19:21:58 -0400 Subject: [PATCH 1320/2280] add some docs --- docs/plugins/lastgenre.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/plugins/lastgenre.rst b/docs/plugins/lastgenre.rst index 125b1073d..5e3235bd7 100644 --- a/docs/plugins/lastgenre.rst +++ b/docs/plugins/lastgenre.rst @@ -103,6 +103,19 @@ The plugin uses this weight to discard unpopular tags. The default is to ignore tags with a weight less then 10. You can change this by setting the ``min_weight`` config option. +Specific vs. Popular Genres +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, the plugin sorts genres by popularity. However, you can use the +``prefer_specific`` option to override this behavior and instead sort genres +by specificity, as determined by your whitelist and canonicalization tree. + +For instance, say you have both ``folk`` and ``americana`` in your whitelist +and canonicalization tree and ``americana`` is a leaf within ``folk``. If +Last.fm returns both of those tags, lastgenre is going to use the most +popular, which is often the most generic (in this case ``folk``). By setting +``prefer_specific`` to true, lastgenre would use ``americana`` instead. + Configuration ------------- @@ -126,6 +139,8 @@ configuration file. The available options are: Default: ``yes``. - **min_weight**: Minimum popularity factor below which genres are discarded. Default: 10. +- **prefer_specific**: Sort genres by the most to least specific, rather than + most to least popular. Default: ``no``. - **source**: Which entity to look up in Last.fm. Can be either ``artist``, ``album`` or ``track``. Default: ``album``. From 1c9202cc8687c9bc23c580f9776c6aa9b85b19a4 Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Mon, 26 Sep 2016 21:21:15 -0400 Subject: [PATCH 1321/2280] moar indents! --- beetsplug/lastgenre/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 7c1cddf04..728e6069c 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -200,8 +200,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): tags_all += parents # Stop if we have enough tags already, unless we need to find # the most specific tag (instead of the most popular). - if (not self.config['prefer_specific'] and - len(tags_all) >= count): + if (not self.config['prefer_specific'] + and len(tags_all) >= count): break tags = tags_all From a7e3bf2d0b8cb4c2874a14471e2b8daaeb317970 Mon Sep 17 00:00:00 2001 From: Corinne Hoener Date: Tue, 27 Sep 2016 06:21:51 -0400 Subject: [PATCH 1322/2280] third time's a charm --- beetsplug/lastgenre/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 728e6069c..13f7a300d 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -200,8 +200,8 @@ class LastGenrePlugin(plugins.BeetsPlugin): tags_all += parents # Stop if we have enough tags already, unless we need to find # the most specific tag (instead of the most popular). - if (not self.config['prefer_specific'] - and len(tags_all) >= count): + if (not self.config['prefer_specific'] and + len(tags_all) >= count): break tags = tags_all From c1e04ac039b7a70db3177bfdb9ac076ff56e3e40 Mon Sep 17 00:00:00 2001 From: vapniks Date: Thu, 29 Sep 2016 15:05:50 +0100 Subject: [PATCH 1323/2280] Update _beet Some fixes to make it work with new plugins --- extra/_beet | 74 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 29 deletions(-) diff --git a/extra/_beet b/extra/_beet index 9e4a3437b..dd3f6570b 100644 --- a/extra/_beet +++ b/extra/_beet @@ -1,6 +1,13 @@ #compdef beet -# Completion for beets music library manager and MusicBrainz tagger: http://beets.io/ +# zsh completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ + +# NOTE: it will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins) +# You can make it faster in future by saving the generated completion function: which _beet > _beet2 +# to the top of the file add: #compdef beet +# to the bottom of the file add: _beet "$@" +# add this file to your zsh completions directory, and then in your .zshrc file add: compdef _beet2 beet +# You will need to repeat this proceedure each time you enable new plugins if you want them to complete properly. # useful: argument to _regex_arguments for matching any word local matchany=/$'[^\0]##\0'/ @@ -13,15 +20,23 @@ fields=(`beet fields | grep -G '^ ' | sort -u | colrm 1 2`) # regexps for matching query and modify terms on the command line matchquery=/"(${(j/|/)fields[@]})"$':[^\0]##\0'/ matchmodify=/"(${(j/|/)fields[@]})"$'(=[^\0]##|!)\0'/ + +# Function for joining grouped lines of output into single lines (taken from _completion_helpers) +function _join_lines() { + awk -v SEP="$1" -v ARG2="$2" -v START="$3" -v END2="$4" 'BEGIN {if(START==""){f=1}{f=0}; + if(ARG2 ~ "^[0-9]+"){LINE1 = "^[[:space:]]{,"ARG2"}[^[:space:]]"}else{LINE1 = ARG2}} + ($0 ~ END2 && f>0 && END2!="") {exit} + ($0 ~ START && f<1) {f=1; if(length(START)!=0){next}} + ($0 ~ LINE1 && f>0) {if(f<2){f=2; printf("%s",$0)}else{printf("\n%s",$0)}; next} + (f>1) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); printf("%s%s",SEP, $0); next} + END {print ""}' +} + # Function for getting unique values for field from database (you may need to change the path to the database). function _beet_field_values() { local -a output fieldvals local library="$(beet config|grep library|cut -f 2 -d ' ')" - if [ -z "$library" ]; then - # Use default library location if there is no user defined one - library="~/.config/beets/library.db" - fi output=$(sqlite3 ${~library} "select distinct $1 from items;") case $1 in @@ -54,7 +69,7 @@ query=( \( "$matchquery" ":query:query string:{_beet_query}" \) \( "$matchquery" modify=( \( "$matchmodify" ":modify:modify string:$modifyelem" \) \( "$matchmodify" ":modify:modify string:$modifyelem" \) \# ) # arguments to _regex_arguments for completing files and directories -local -a files dirs +local -a files dirs files=("$matchany" ':file:file:_files') dirs=("$matchany" ':dir:directory:_dirs') @@ -86,7 +101,7 @@ retagopt='-L:retag items matching a query:${query[@]}' skipopt='-i:skip already-imported directories' noskipopt='-I:do not skip already-imported directories' flatopt='--flat:import an entire tree as a single album' -groupopt='-g:group tracks in a folder into seperate albums' +groupopt='-g:group tracks in a folder into seperate albums' editopt='-e:edit user configuration with $EDITOR' defaultopt='-d:include the default configuration' copynomoveopt='-c:copy instead of moving' @@ -106,45 +121,45 @@ function _beet_subcmd_options() regex_words=() for i in ${${(f)"$(beet help $1 | awk '/^ +-/{if(x)print x;x=$0;next}/^ *$/{if(x) exit}{if(x) x=x$0}END{print x}')"}[@]} do - shortopt="${i[(w)1]/,/}" - optarg="${$(echo ${i[(w)2]}|grep -o '[A-Z]\+')[(w)1]}" - optdesc="${${${${${i[(w)2,-1]/[A-Z, ]#--[a-z]##[=A-Z]# #/}//:/-}//\[/(}//\]/)}//\'/}" + opt="${i[(w)1]/,/}" + optarg="${${${i## #[-a-zA-Z]# }##[- ]##*}%%[, ]*}" + optdesc="${${${${${i[(w)2,-1]/[A-Z, ]#--[-a-z]##[=A-Z]# #/}//:/-}//\[/(}//\]/)}//\'/}" case $optarg in ("") - if [[ "$1" == "import" && "$shortopt" == "-L" ]]; then - regex_words+=("$shortopt:$optdesc:\${query[@]}") + if [[ "$1" == "import" && "$opt" == "-L" ]]; then + regex_words+=("$opt:$optdesc:\${query[@]}") else - regex_words+=("$shortopt:$optdesc") + regex_words+=("$opt:$optdesc") fi ;; (LOG) - regex_words+=("$shortopt:$optdesc:\$files") + regex_words+=("$opt:$optdesc:\$files") ;; (CONFIG) local -a configfile configfile=("$matchany" ':file:config file:{_files -g *.yaml}') - regex_words+=("$shortopt:$optdesc:\$configfile") + regex_words+=("$opt:$optdesc:\$configfile") ;; (LIB|LIBRARY) local -a libfile libfile=("$matchany" ':file:database file:{_files -g *.db}') - regex_words+=("$shortopt:$optdesc:\$libfile") + regex_words+=("$opt:$optdesc:\$libfile") ;; (DIR|DIRECTORY) - regex_words+=("$shortopt:$optdesc:\$dirs") + regex_words+=("$opt:$optdesc:\$dirs") ;; (SOURCE) if [[ $1 -eq lastgenre ]]; then local -a lastgenresource lastgenresource=(/$'(artist|album|track)\0'/ ':source:genre source:(artist album track)') - regex_words+=("$shortopt:$optdesc:\$lastgenresource") + regex_words+=("$opt:$optdesc:\$lastgenresource") else - regex_words+=("$shortopt:$optdesc:\$matchany") + regex_words+=("$opt:$optdesc:\$matchany") fi ;; (*) - regex_words+=("$shortopt:$optdesc:\$matchany") + regex_words+=("$opt:$optdesc:\$matchany") ;; esac done @@ -154,20 +169,21 @@ function _beet_subcmd_options() # Now build the arguments to _regex_arguments for each subcommand. local -a options regex_words_subcmds regex_words_help local subcmd cmddesc -for i in ${${(f)"$(beet help | awk 'f;/Commands:/{f=1}' | grep '^ \w.*')"[@]}[@]} +for i in ${${(f)"$(beet help | _join_lines ' ' 3 'Commands:')"[@]}[@]} do subcmd="${i[(w)1]}" + # remove first word and parenthesised alias, replace : with -, [ with (, ] with ), and remove single quotes cmddesc="${${${${${i[(w)2,-1]##\(*\) #}//:/-}//\[/(}//\]/)}//\'/}" case $subcmd in (config) - _regex_words options "config options" "$helpopt" "$pathopt" "$editopt" "$defaultopt" + _regex_words options "config options" "$helpopt" "$pathopt" "$editopt" "$defaultopt" options=("${reply[@]}") ;; (import) - _regex_words options "import options" "$helpopt" "$writeopt" "$nowriteopt" "$copyopt" "$nocopyopt" "$inferopt" \ - "$noinferopt" "$resumeopt" "$noresumeopt" "$nopromptopt" "$logopt" "$individualopt" "$confirmopt" "$retagopt" \ - "$skipopt" "$noskipopt" "$flatopt" "$groupopt" + _regex_words options "import options" "$helpopt" "$writeopt" "$nowriteopt" "$copyopt" "$nocopyopt"\ + "$inferopt" "$noinferopt" "$resumeopt" "$noresumeopt" "$nopromptopt" "$logopt" "$individualopt" "$confirmopt"\ + "$retagopt" "$skipopt" "$noskipopt" "$flatopt" "$groupopt" options=( "${reply[@]}" \# "${files[@]}" \# ) ;; (list) @@ -188,7 +204,7 @@ do options=( "${reply[@]}" \# "${query[@]}" ) ;; (stats) - _regex_words options "stats options" "$helpopt" "$exactopt" + _regex_words options "stats options" "$helpopt" "$exactopt" options=( "${reply[@]}" \# "${query[@]}" ) ;; (update) @@ -204,9 +220,9 @@ do ;; (help) # The help subcommand is treated separately - continue + continue ;; - (*) # completions for plugin commands are generated using _beet_subcmd_options + (*) # completions for plugin commands are generated using _beet_subcmd_options _beet_subcmd_options "$subcmd" options=( \( "${reply[@]}" \# "${query[@]}" \) ) ;; @@ -241,6 +257,6 @@ zstyle ":completion:${curcontext}:" tag-order '! options' # Execute the completion function _beet "$@" -# Local Variables: +# Local Variables: # mode:shell-script # End: From 8d7a6260741abaabfbb2736d4566bfe2946406d9 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 1 Oct 2016 05:00:29 -0400 Subject: [PATCH 1324/2280] Move timeout config getter to library from dbcore I wanted to move it up even higher, but I wanted to hold off on that for a bit longer. --- beets/dbcore/db.py | 6 +++--- beets/library.py | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 73233b52c..daa636d24 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -692,8 +692,9 @@ class Database(object): """The Model subclasses representing tables in this database. """ - def __init__(self, path): + def __init__(self, path, timeout=5.0): self.path = path + self.timeout = timeout self._connections = {} self._tx_stacks = defaultdict(list) @@ -732,8 +733,7 @@ class Database(object): # bytestring paths here on Python 3, so we need to # provide a `str` using `py3_path`. conn = sqlite3.connect( - py3_path(self.path), - timeout=beets.config['timeout'].as_number(), + py3_path(self.path), timeout=self.timeout ) # Access SELECT results like dictionaries. diff --git a/beets/library.py b/beets/library.py index d4b9b8189..59784e808 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1216,7 +1216,8 @@ class Library(dbcore.Database): path_formats=((PF_KEY_DEFAULT, '$artist/$album/$track $title'),), replacements=None): - super(Library, self).__init__(path) + timeout = beets.config['timeout'].as_number() + super(Library, self).__init__(path, timeout=timeout) self._connection().create_function('bytelower', 1, _sqlite_bytelower) From 9dc79950d3d9ebdfe09224e27e3af258f7438ae6 Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 16:20:55 +0100 Subject: [PATCH 1325/2280] Update comments section of _beet More accurate instructions on how to create a cached completion file (previous instructions where incorrect) --- extra/_beet | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/extra/_beet b/extra/_beet index dd3f6570b..9f20151f7 100644 --- a/extra/_beet +++ b/extra/_beet @@ -3,10 +3,17 @@ # zsh completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ # NOTE: it will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins) -# You can make it faster in future by saving the generated completion function: which _beet > _beet2 -# to the top of the file add: #compdef beet -# to the bottom of the file add: _beet "$@" -# add this file to your zsh completions directory, and then in your .zshrc file add: compdef _beet2 beet +# You can make it faster in future by creating a cached version: +# 1) perform a query completion with this file (_beet), e.g. do: beet list artist:" +# to create the completion function (takes a few seconds) +# 2) save a copy of the completion function: which _beet > _beet_cached +# 3) save a copy of the query completion function: which _beet_query > _beet_query_cached +# 4) copy the contents of _beet_query_cached to the top of _beet_cached +# 5) copy and paste the _beet_field_values function from _beet to the top of _beet_cached +# 6) add the following line to the top of _beet_cached: #compdef beet +# 7) add the following line to the bottom of _beet_cached: _beet "$@" +# 8) save _beet_cached to your completions directory (e.g. /usr/share/zsh/functions/Completion) +# 9) add the following line to your .zshrc file: compdef _beet_cached beet # You will need to repeat this proceedure each time you enable new plugins if you want them to complete properly. # useful: argument to _regex_arguments for matching any word From df3a4317a6a6bfd8422870b457d726a22944023c Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 16:27:22 +0100 Subject: [PATCH 1326/2280] Cached completion file (faster) A cached completion file for faster initial completions. Completes the following plugins: fuzzy play info lyrics fromfilename check lastgenre badfiles chroma edit smartplaylist --- extra/_beet_cached | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 extra/_beet_cached diff --git a/extra/_beet_cached b/extra/_beet_cached new file mode 100644 index 000000000..afdae0e80 --- /dev/null +++ b/extra/_beet_cached @@ -0,0 +1,59 @@ +#compdef beet + +# cached completion file for beet (generated from _beet) + +_beet_field_values () { + local -a output fieldvals + local library="$(beet config|grep library|cut -f 2 -d ' ')" + output=$(sqlite3 ${~library} "select distinct $1 from items;") + case $1 in + (lyrics) fieldvals= ;; + (*) fieldvals=("${(f)output[@]}") ;; + esac + compadd -P \" -S \" -M 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' -Q -a fieldvals +} + +_beet_query () { + local _ra_p1 _ra_p2 _ra_left _ra_right _ra_com expl tmp nm="$compstate[nmatches]" + local _ra_actions _ra_line="${(pj:\0:)${(@)words[1,CURRENT - 1]:Q}}"$'\0'"$PREFIX" + _ra_actions=() + zregexparse -c _ra_p1 _ra_p2 "$_ra_line" $'/[^\0]##\0/' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:_values -S : \\\'query field (add an extra : to match by regexp)\\\' \\\'::\\\' \\\'acoustid_fingerprint:::{_beet_field_values acoustid_fingerprint}\\\' \\\'acoustid_id:::{_beet_field_values acoustid_id}\\\' \\\'added:::{_beet_field_values added}\\\' \\\'album:::{_beet_field_values album}\\\' \\\'albumartist:::{_beet_field_values albumartist}\\\' \\\'albumartist_credit:::{_beet_field_values albumartist_credit}\\\' \\\'albumartist_sort:::{_beet_field_values albumartist_sort}\\\' \\\'albumdisambig:::{_beet_field_values albumdisambig}\\\' \\\'album_id:::{_beet_field_values album_id}\\\' \\\'albumstatus:::{_beet_field_values albumstatus}\\\' \\\'albumtotal:::{_beet_field_values albumtotal}\\\' \\\'albumtype:::{_beet_field_values albumtype}\\\' \\\'artist:::{_beet_field_values artist}\\\' \\\'artist_credit:::{_beet_field_values artist_credit}\\\' \\\'artist_sort:::{_beet_field_values artist_sort}\\\' \\\'artpath:::{_beet_field_values artpath}\\\' \\\'asin:::{_beet_field_values asin}\\\' \\\'bitdepth:::{_beet_field_values bitdepth}\\\' \\\'bitrate:::{_beet_field_values bitrate}\\\' \\\'bpm:::{_beet_field_values bpm}\\\' \\\'catalognum:::{_beet_field_values catalognum}\\\' \\\'channels:::{_beet_field_values channels}\\\' \\\'checksum:::{_beet_field_values checksum}\\\' \\\'comments:::{_beet_field_values comments}\\\' \\\'comp:::{_beet_field_values comp}\\\' \\\'composer:::{_beet_field_values composer}\\\' \\\'country:::{_beet_field_values country}\\\' \\\'data_source:::{_beet_field_values data_source}\\\' \\\'day:::{_beet_field_values day}\\\' \\\'disc:::{_beet_field_values disc}\\\' \\\'disctitle:::{_beet_field_values disctitle}\\\' \\\'disctotal:::{_beet_field_values disctotal}\\\' \\\'encoder:::{_beet_field_values encoder}\\\' \\\'filesize:::{_beet_field_values filesize}\\\' \\\'format:::{_beet_field_values format}\\\' \\\'genre:::{_beet_field_values genre}\\\' \\\'grouping:::{_beet_field_values grouping}\\\' \\\'id:::{_beet_field_values id}\\\' \\\'initial_key:::{_beet_field_values initial_key}\\\' \\\'label:::{_beet_field_values label}\\\' \\\'language:::{_beet_field_values language}\\\' \\\'length:::{_beet_field_values length}\\\' \\\'lyrics:::{_beet_field_values lyrics}\\\' \\\'mb_albumartistid:::{_beet_field_values mb_albumartistid}\\\' \\\'mb_albumid:::{_beet_field_values mb_albumid}\\\' \\\'mb_artistid:::{_beet_field_values mb_artistid}\\\' \\\'mb_releasegroupid:::{_beet_field_values mb_releasegroupid}\\\' \\\'mb_trackid:::{_beet_field_values mb_trackid}\\\' \\\'media:::{_beet_field_values media}\\\' \\\'month:::{_beet_field_values month}\\\' \\\'mtime:::{_beet_field_values mtime}\\\' \\\'original_day:::{_beet_field_values original_day}\\\' \\\'original_month:::{_beet_field_values original_month}\\\' \\\'original_year:::{_beet_field_values original_year}\\\' \\\'path:::{_beet_field_values path}\\\' \\\'rg_album_gain:::{_beet_field_values rg_album_gain}\\\' \\\'rg_album_peak:::{_beet_field_values rg_album_peak}\\\' \\\'rg_track_gain:::{_beet_field_values rg_track_gain}\\\' \\\'rg_track_peak:::{_beet_field_values rg_track_peak}\\\' \\\'samplerate:::{_beet_field_values samplerate}\\\' \\\'script:::{_beet_field_values script}\\\' \\\'singleton:::{_beet_field_values singleton}\\\' \\\'title:::{_beet_field_values title}\\\' \\\'track:::{_beet_field_values track}\\\' \\\'tracktotal:::{_beet_field_values tracktotal}\\\' \\\'year:::{_beet_field_values year}\\\'\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:_values -S : \\\'query field (add an extra : to match by regexp)\\\' \\\'::\\\' \\\'acoustid_fingerprint:::{_beet_field_values acoustid_fingerprint}\\\' \\\'acoustid_id:::{_beet_field_values acoustid_id}\\\' \\\'added:::{_beet_field_values added}\\\' \\\'album:::{_beet_field_values album}\\\' \\\'albumartist:::{_beet_field_values albumartist}\\\' \\\'albumartist_credit:::{_beet_field_values albumartist_credit}\\\' \\\'albumartist_sort:::{_beet_field_values albumartist_sort}\\\' \\\'albumdisambig:::{_beet_field_values albumdisambig}\\\' \\\'album_id:::{_beet_field_values album_id}\\\' \\\'albumstatus:::{_beet_field_values albumstatus}\\\' \\\'albumtotal:::{_beet_field_values albumtotal}\\\' \\\'albumtype:::{_beet_field_values albumtype}\\\' \\\'artist:::{_beet_field_values artist}\\\' \\\'artist_credit:::{_beet_field_values artist_credit}\\\' \\\'artist_sort:::{_beet_field_values artist_sort}\\\' \\\'artpath:::{_beet_field_values artpath}\\\' \\\'asin:::{_beet_field_values asin}\\\' \\\'bitdepth:::{_beet_field_values bitdepth}\\\' \\\'bitrate:::{_beet_field_values bitrate}\\\' \\\'bpm:::{_beet_field_values bpm}\\\' \\\'catalognum:::{_beet_field_values catalognum}\\\' \\\'channels:::{_beet_field_values channels}\\\' \\\'checksum:::{_beet_field_values checksum}\\\' \\\'comments:::{_beet_field_values comments}\\\' \\\'comp:::{_beet_field_values comp}\\\' \\\'composer:::{_beet_field_values composer}\\\' \\\'country:::{_beet_field_values country}\\\' \\\'data_source:::{_beet_field_values data_source}\\\' \\\'day:::{_beet_field_values day}\\\' \\\'disc:::{_beet_field_values disc}\\\' \\\'disctitle:::{_beet_field_values disctitle}\\\' \\\'disctotal:::{_beet_field_values disctotal}\\\' \\\'encoder:::{_beet_field_values encoder}\\\' \\\'filesize:::{_beet_field_values filesize}\\\' \\\'format:::{_beet_field_values format}\\\' \\\'genre:::{_beet_field_values genre}\\\' \\\'grouping:::{_beet_field_values grouping}\\\' \\\'id:::{_beet_field_values id}\\\' \\\'initial_key:::{_beet_field_values initial_key}\\\' \\\'label:::{_beet_field_values label}\\\' \\\'language:::{_beet_field_values language}\\\' \\\'length:::{_beet_field_values length}\\\' \\\'lyrics:::{_beet_field_values lyrics}\\\' \\\'mb_albumartistid:::{_beet_field_values mb_albumartistid}\\\' \\\'mb_albumid:::{_beet_field_values mb_albumid}\\\' \\\'mb_artistid:::{_beet_field_values mb_artistid}\\\' \\\'mb_releasegroupid:::{_beet_field_values mb_releasegroupid}\\\' \\\'mb_trackid:::{_beet_field_values mb_trackid}\\\' \\\'media:::{_beet_field_values media}\\\' \\\'month:::{_beet_field_values month}\\\' \\\'mtime:::{_beet_field_values mtime}\\\' \\\'original_day:::{_beet_field_values original_day}\\\' \\\'original_month:::{_beet_field_values original_month}\\\' \\\'original_year:::{_beet_field_values original_year}\\\' \\\'path:::{_beet_field_values path}\\\' \\\'rg_album_gain:::{_beet_field_values rg_album_gain}\\\' \\\'rg_album_peak:::{_beet_field_values rg_album_peak}\\\' \\\'rg_track_gain:::{_beet_field_values rg_track_gain}\\\' \\\'rg_track_peak:::{_beet_field_values rg_track_peak}\\\' \\\'samplerate:::{_beet_field_values samplerate}\\\' \\\'script:::{_beet_field_values script}\\\' \\\'singleton:::{_beet_field_values singleton}\\\' \\\'title:::{_beet_field_values title}\\\' \\\'track:::{_beet_field_values track}\\\' \\\'tracktotal:::{_beet_field_values tracktotal}\\\' \\\'year:::{_beet_field_values year}\\\'\'' $')' $'#' + case "$?" in + (0|2) _message "no more arguments" ;; + (1) if [[ "$_ra_line[_ra_p1 + 1, -1]" = *$'\0'* ]] + then + _message "parse failed before current word" + else + _ra_left="$_ra_line[_ra_p1 + 1, _ra_p2]" + _ra_right="$_ra_line[_ra_p2 + 1, -1]" + compset -p $(( $#PREFIX - $#_ra_line + $_ra_p1 )) + (( $#_ra_actions )) && _alternative "$_ra_actions[@]" + fi ;; + (3) _message "invalid regex" ;; + esac + [[ nm -ne "$compstate[nmatches]" ]] +} + +_beet () { + local _ra_p1 _ra_p2 _ra_left _ra_right _ra_com expl tmp nm="$compstate[nmatches]" + local _ra_actions _ra_line="${(pj:\0:)${(@)words[1,CURRENT - 1]:Q}}"$'\0'"$PREFIX" + _ra_actions=() + zregexparse -c _ra_p1 _ra_p2 "$_ra_line" $'/[^\0]##\0/' $'(' $'(' $'/-c\0/' $':_ra_comp $\'options:global options:(( -c:path\\\\ to\\\\ configuration\\\\ file ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-v\0/' $':_ra_comp $\'options:global options:(( -v:print\\\\ debugging\\\\ information ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:global options:(( -l:library\\\\ database\\\\ file\\\\ to\\\\ use ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-h\0/' $':_ra_comp $\'options:global options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:global options:(( -d:destination\\\\ music\\\\ directory ))\'' $'/[^\0]##\0/' $':_ra_comp $\'dir:directory:_dirs\'' $')' $'#' $')' $'(' $'/bad\0/' $':_ra_comp $\'subcmds:subcommands:(( bad:check\\\\ for\\\\ corrupt\\\\ or\\\\ missing\\\\ files ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:bad options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/check\0/' $':_ra_comp $\'subcmds:subcommands:(( check:compute\\\\ and\\\\ verify\\\\ checksums ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:check options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:check options:(( -e:run\\\\ external\\\\ tools ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:check options:(( -a:add\\\\ checksum\\\\ for\\\\ all\\\\ files\\\\ that\\\\ do\\\\ not\\\\ already\\\\ have\\\\ one ))\'' $'|' $'/-u\0/' $':_ra_comp $\'options:check options:(( -u:compute\\\\ new\\\\ checksums\\\\ and\\\\ add\\\\ the\\\\ to\\\\ the\\\\ database ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:check options:(( -f:force\\\\ updating\\\\ the\\\\ whole\\\\ library\\\\ or\\\\ fixing\\\\ all\\\\ files ))\'' $'|' $'/--export\0/' $':_ra_comp $\'options:check options:(( --export:print\\\\ paths\\\\ and\\\\ corresponding\\\\ checksum ))\'' $'|' $'/-x\0/' $':_ra_comp $\'options:check options:(( -x:fix\\\\ errors\\\\ with\\\\ external\\\\ tools ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:check options:(( -l:list\\\\ available\\\\ third-party\\\\ used\\\\ to\\\\ check\\\\ integrity ))\'' $'|' $'/-q\0/' $':_ra_comp $\'options:check options:(( -q:only\\\\ show\\\\ errors ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/config\0/' $':_ra_comp $\'subcmds:subcommands:(( config:show\\\\ or\\\\ edit\\\\ the\\\\ user\\\\ configuration ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:config options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:config options:(( -p:print\\\\ paths\\\\ for\\\\ matched\\\\ items\\\\ or\\\\ albums ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:config options:(( -e:edit\\\\ user\\\\ configuration\\\\ with\\\\ $EDITOR ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:config options:(( -d:include\\\\ the\\\\ default\\\\ configuration ))\'' $')' $'|' $'/edit\0/' $':_ra_comp $\'subcmds:subcommands:(( edit:interactively\\\\ edit\\\\ metadata ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:edit options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:edit options:(( -f:edit\\\\ this\\\\ field\\\\ also ))\'' $'/[^\0]##\0/' $'|' $'/--all\0/' $':_ra_comp $\'options:edit options:(( --all:edit\\\\ all\\\\ fields ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:edit options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/fields\0/' $':_ra_comp $\'subcmds:subcommands:(( fields:show\\\\ fields\\\\ available\\\\ for\\\\ queries\\\\ and\\\\ format\\\\ strings ))\'' $'|' $'/fingerprint\0/' $':_ra_comp $\'subcmds:subcommands:(( fingerprint:generate\\\\ fingerprints\\\\ for\\\\ items\\\\ without\\\\ them ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:fingerprint options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/import\0/' $':_ra_comp $\'subcmds:subcommands:(( import:import\\\\ new\\\\ music ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:import options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-w\0/' $':_ra_comp $\'options:import options:(( -w:write\\\\ new\\\\ metadata\\\\ to\\\\ files\\\\ tags\\\\ \\\\(default\\\\) ))\'' $'|' $'/-W\0/' $':_ra_comp $\'options:import options:(( -W:dont\\\\ write\\\\ metadata\\\\ \\\\(opposite\\\\ of\\\\ -w\\\\) ))\'' $'|' $'/-c\0/' $':_ra_comp $\'options:import options:(( -c:copy\\\\ tracks\\\\ into\\\\ library\\\\ directory\\\\ \\\\(default\\\\) ))\'' $'|' $'/-C\0/' $':_ra_comp $\'options:import options:(( -C:dont\\\\ copy\\\\ tracks\\\\ \\\\(opposite\\\\ of\\\\ -c\\\\) ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:import options:(( -a:infer\\\\ tags\\\\ for\\\\ imported\\\\ files\\\\ \\\\(default\\\\) ))\'' $'|' $'/-A\0/' $':_ra_comp $\'options:import options:(( -A:dont\\\\ infer\\\\ tags\\\\ for\\\\ imported\\\\ files\\\\ \\\\(opposite\\\\ of\\\\ -a\\\\) ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:import options:(( -p:resume\\\\ importing\\\\ if\\\\ interrupted ))\'' $'|' $'/-P\0/' $':_ra_comp $\'options:import options:(( -P:do\\\\ not\\\\ try\\\\ to\\\\ resume\\\\ importing ))\'' $'|' $'/-q\0/' $':_ra_comp $\'options:import options:(( -q:never\\\\ prompt\\\\ for\\\\ input,\\\\ skip\\\\ albums\\\\ instead ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:import options:(( -l:file\\\\ to\\\\ log\\\\ untaggable\\\\ albums\\\\ for\\\\ later\\\\ review ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-s\0/' $':_ra_comp $\'options:import options:(( -s:import\\\\ individual\\\\ tracks\\\\ instead\\\\ of\\\\ full\\\\ albums ))\'' $'|' $'/-t\0/' $':_ra_comp $\'options:import options:(( -t:always\\\\ confirm\\\\ all\\\\ actions ))\'' $'|' $'/-L\0/' $':_ra_comp $\'options:import options:(( -L:retag\\\\ items\\\\ matching\\\\ a\\\\ query ))\'' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/-i\0/' $':_ra_comp $\'options:import options:(( -i:skip\\\\ already-imported\\\\ directories ))\'' $'|' $'/-I\0/' $':_ra_comp $\'options:import options:(( -I:do\\\\ not\\\\ skip\\\\ already-imported\\\\ directories ))\'' $'|' $'/--flat\0/' $':_ra_comp $\'options:import options:(( --flat:import\\\\ an\\\\ entire\\\\ tree\\\\ as\\\\ a\\\\ single\\\\ album ))\'' $'|' $'/-g\0/' $':_ra_comp $\'options:import options:(( -g:group\\\\ tracks\\\\ in\\\\ a\\\\ folder\\\\ into\\\\ seperate\\\\ albums ))\'' $')' $'#' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'#' $'|' $'/info\0/' $':_ra_comp $\'subcmds:subcommands:(( info:show\\\\ file\\\\ metadata ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:info options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:info options:(( -l:show\\\\ library\\\\ fields\\\\ instead\\\\ of\\\\ tags ))\'' $'|' $'/-s\0/' $':_ra_comp $\'options:info options:(( -s:summarize\\\\ the\\\\ tags\\\\ of\\\\ all\\\\ files ))\'' $'|' $'/-i\0/' $':_ra_comp $\'options:info options:(( -i:INCLUDED__KEYS\\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ comma\\\\ separated\\\\ list\\\\ of\\\\ keys\\\\ to\\\\ show ))\'' $'/[^\0]##\0/' $'|' $'/-k\0/' $':_ra_comp $\'options:info options:(( -k:show\\\\ only\\\\ the\\\\ keys ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:info options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/lastgenre\0/' $':_ra_comp $\'subcmds:subcommands:(( lastgenre:fetch\\\\ genres ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:lastgenre options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:lastgenre options:(( -f:re-download\\\\ genre\\\\ when\\\\ already\\\\ present ))\'' $'|' $'/-s\0/' $':_ra_comp $\'options:lastgenre options:(( -s:genre\\\\ source-\\\\ artist,\\\\ album,\\\\ or\\\\ track ))\'' $'/(artist|album|track)\0/' $':_ra_comp $\'source:genre source:(artist album track)\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/list\0/' $':_ra_comp $\'subcmds:subcommands:(( list:query\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:list options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:list options:(( -p:print\\\\ paths\\\\ for\\\\ matched\\\\ items\\\\ or\\\\ albums ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:list options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:list options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/lyrics\0/' $':_ra_comp $\'subcmds:subcommands:(( lyrics:fetch\\\\ song\\\\ lyrics ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:lyrics options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:lyrics options:(( -p:print\\\\ lyrics\\\\ to\\\\ console ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:lyrics options:(( -f:always\\\\ re-download\\\\ lyrics ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/modify\0/' $':_ra_comp $\'subcmds:subcommands:(( modify:change\\\\ metadata\\\\ fields ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:modify options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-M\0/' $':_ra_comp $\'options:modify options:(( -M:dont\\\\ move\\\\ files\\\\ in\\\\ library ))\'' $'|' $'/-w\0/' $':_ra_comp $\'options:modify options:(( -w:write\\\\ new\\\\ metadata\\\\ to\\\\ files\\\\ tags\\\\ \\\\(default\\\\) ))\'' $'|' $'/-W\0/' $':_ra_comp $\'options:modify options:(( -W:dont\\\\ write\\\\ metadata\\\\ \\\\(opposite\\\\ of\\\\ -w\\\\) ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:modify options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-y\0/' $':_ra_comp $\'options:modify options:(( -y:skip\\\\ confirmation ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:modify options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year)(=[^\0]##|\!)\0/' $':_ra_comp $\'modify:modify string:_values -S = \\\'modify field (replace = with \\\! to remove field)\\\' \\\'acoustid_fingerprint:: \\\' \\\'acoustid_id:: \\\' \\\'added:: \\\' \\\'album:: \\\' \\\'albumartist:: \\\' \\\'albumartist_credit:: \\\' \\\'albumartist_sort:: \\\' \\\'albumdisambig:: \\\' \\\'album_id:: \\\' \\\'albumstatus:: \\\' \\\'albumtotal:: \\\' \\\'albumtype:: \\\' \\\'artist:: \\\' \\\'artist_credit:: \\\' \\\'artist_sort:: \\\' \\\'artpath:: \\\' \\\'asin:: \\\' \\\'bitdepth:: \\\' \\\'bitrate:: \\\' \\\'bpm:: \\\' \\\'catalognum:: \\\' \\\'channels:: \\\' \\\'checksum:: \\\' \\\'comments:: \\\' \\\'comp:: \\\' \\\'composer:: \\\' \\\'country:: \\\' \\\'data_source:: \\\' \\\'day:: \\\' \\\'disc:: \\\' \\\'disctitle:: \\\' \\\'disctotal:: \\\' \\\'encoder:: \\\' \\\'filesize:: \\\' \\\'format:: \\\' \\\'genre:: \\\' \\\'grouping:: \\\' \\\'id:: \\\' \\\'initial_key:: \\\' \\\'label:: \\\' \\\'language:: \\\' \\\'length:: \\\' \\\'lyrics:: \\\' \\\'mb_albumartistid:: \\\' \\\'mb_albumid:: \\\' \\\'mb_artistid:: \\\' \\\'mb_releasegroupid:: \\\' \\\'mb_trackid:: \\\' \\\'media:: \\\' \\\'month:: \\\' \\\'mtime:: \\\' \\\'original_day:: \\\' \\\'original_month:: \\\' \\\'original_year:: \\\' \\\'path:: \\\' \\\'rg_album_gain:: \\\' \\\'rg_album_peak:: \\\' \\\'rg_track_gain:: \\\' \\\'rg_track_peak:: \\\' \\\'samplerate:: \\\' \\\'script:: \\\' \\\'singleton:: \\\' \\\'title:: \\\' \\\'track:: \\\' \\\'tracktotal:: \\\' \\\'year:: \\\'\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year)(=[^\0]##|\!)\0/' $':_ra_comp $\'modify:modify string:_values -S = \\\'modify field (replace = with \\\! to remove field)\\\' \\\'acoustid_fingerprint:: \\\' \\\'acoustid_id:: \\\' \\\'added:: \\\' \\\'album:: \\\' \\\'albumartist:: \\\' \\\'albumartist_credit:: \\\' \\\'albumartist_sort:: \\\' \\\'albumdisambig:: \\\' \\\'album_id:: \\\' \\\'albumstatus:: \\\' \\\'albumtotal:: \\\' \\\'albumtype:: \\\' \\\'artist:: \\\' \\\'artist_credit:: \\\' \\\'artist_sort:: \\\' \\\'artpath:: \\\' \\\'asin:: \\\' \\\'bitdepth:: \\\' \\\'bitrate:: \\\' \\\'bpm:: \\\' \\\'catalognum:: \\\' \\\'channels:: \\\' \\\'checksum:: \\\' \\\'comments:: \\\' \\\'comp:: \\\' \\\'composer:: \\\' \\\'country:: \\\' \\\'data_source:: \\\' \\\'day:: \\\' \\\'disc:: \\\' \\\'disctitle:: \\\' \\\'disctotal:: \\\' \\\'encoder:: \\\' \\\'filesize:: \\\' \\\'format:: \\\' \\\'genre:: \\\' \\\'grouping:: \\\' \\\'id:: \\\' \\\'initial_key:: \\\' \\\'label:: \\\' \\\'language:: \\\' \\\'length:: \\\' \\\'lyrics:: \\\' \\\'mb_albumartistid:: \\\' \\\'mb_albumid:: \\\' \\\'mb_artistid:: \\\' \\\'mb_releasegroupid:: \\\' \\\'mb_trackid:: \\\' \\\'media:: \\\' \\\'month:: \\\' \\\'mtime:: \\\' \\\'original_day:: \\\' \\\'original_month:: \\\' \\\'original_year:: \\\' \\\'path:: \\\' \\\'rg_album_gain:: \\\' \\\'rg_album_peak:: \\\' \\\'rg_track_gain:: \\\' \\\'rg_track_peak:: \\\' \\\'samplerate:: \\\' \\\'script:: \\\' \\\'singleton:: \\\' \\\'title:: \\\' \\\'track:: \\\' \\\'tracktotal:: \\\' \\\'year:: \\\'\'' $')' $'#' $'|' $'/move\0/' $':_ra_comp $\'subcmds:subcommands:(( move:move\\\\ or\\\\ copy\\\\ items ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:move options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:move options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:move options:(( -d:destination\\\\ music\\\\ directory ))\'' $'/[^\0]##\0/' $':_ra_comp $\'dir:directory:_dirs\'' $'|' $'/-c\0/' $':_ra_comp $\'options:move options:(( -c:copy\\\\ instead\\\\ of\\\\ moving ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/play\0/' $':_ra_comp $\'subcmds:subcommands:(( play:send\\\\ music\\\\ to\\\\ a\\\\ player\\\\ as\\\\ a\\\\ playlist ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:play options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:play options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-A\0/' $':_ra_comp $\'options:play options:(( -A:add\\\\ additional\\\\ arguments\\\\ to\\\\ the\\\\ command ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/remove\0/' $':_ra_comp $\'subcmds:subcommands:(( remove:remove\\\\ matching\\\\ items\\\\ from\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:remove options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:remove options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:remove options:(( -d:also\\\\ remove\\\\ files\\\\ from\\\\ disk ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/splupdate\0/' $':_ra_comp $\'subcmds:subcommands:(( splupdate:update\\\\ the\\\\ smart\\\\ playlists.\\\\ Playlist\\\\ names\\\\ may\\\\ be\\\\ passed\\\\ as\\\\ arguments. ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:splupdate options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/stats\0/' $':_ra_comp $\'subcmds:subcommands:(( stats:show\\\\ statistics\\\\ about\\\\ the\\\\ library\\\\ or\\\\ a\\\\ query ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:stats options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:stats options:(( -e:get\\\\ exact\\\\ file\\\\ sizes ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/submit\0/' $':_ra_comp $\'subcmds:subcommands:(( submit:submit\\\\ Acoustid\\\\ fingerprints ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:submit options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/update\0/' $':_ra_comp $\'subcmds:subcommands:(( update:update\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:update options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:update options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-M\0/' $':_ra_comp $\'options:update options:(( -M:dont\\\\ move\\\\ files\\\\ in\\\\ library ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:update options:(( -p:show\\\\ all\\\\ changes\\\\ but\\\\ do\\\\ nothing ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:update options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/version\0/' $':_ra_comp $\'subcmds:subcommands:(( version:output\\\\ version\\\\ information ))\'' $'|' $'/write\0/' $':_ra_comp $\'subcmds:subcommands:(( write:write\\\\ tag\\\\ information\\\\ to\\\\ files ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:write options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:write options:(( -p:show\\\\ all\\\\ changes\\\\ but\\\\ do\\\\ nothing ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/help\0/' $':_ra_comp $\'subcmds:subcommands:(( help:show\\\\ help ))\'' $'(' $'/bad\0/' $':_ra_comp $\'subcmds:subcommands:(( bad:check\\\\ for\\\\ corrupt\\\\ or\\\\ missing\\\\ files ))\'' $'|' $'/check\0/' $':_ra_comp $\'subcmds:subcommands:(( check:compute\\\\ and\\\\ verify\\\\ checksums ))\'' $'|' $'/config\0/' $':_ra_comp $\'subcmds:subcommands:(( config:show\\\\ or\\\\ edit\\\\ the\\\\ user\\\\ configuration ))\'' $'|' $'/edit\0/' $':_ra_comp $\'subcmds:subcommands:(( edit:interactively\\\\ edit\\\\ metadata ))\'' $'|' $'/fields\0/' $':_ra_comp $\'subcmds:subcommands:(( fields:show\\\\ fields\\\\ available\\\\ for\\\\ queries\\\\ and\\\\ format\\\\ strings ))\'' $'|' $'/fingerprint\0/' $':_ra_comp $\'subcmds:subcommands:(( fingerprint:generate\\\\ fingerprints\\\\ for\\\\ items\\\\ without\\\\ them ))\'' $'|' $'/import\0/' $':_ra_comp $\'subcmds:subcommands:(( import:import\\\\ new\\\\ music ))\'' $'|' $'/info\0/' $':_ra_comp $\'subcmds:subcommands:(( info:show\\\\ file\\\\ metadata ))\'' $'|' $'/lastgenre\0/' $':_ra_comp $\'subcmds:subcommands:(( lastgenre:fetch\\\\ genres ))\'' $'|' $'/list\0/' $':_ra_comp $\'subcmds:subcommands:(( list:query\\\\ the\\\\ library ))\'' $'|' $'/lyrics\0/' $':_ra_comp $\'subcmds:subcommands:(( lyrics:fetch\\\\ song\\\\ lyrics ))\'' $'|' $'/modify\0/' $':_ra_comp $\'subcmds:subcommands:(( modify:change\\\\ metadata\\\\ fields ))\'' $'|' $'/move\0/' $':_ra_comp $\'subcmds:subcommands:(( move:move\\\\ or\\\\ copy\\\\ items ))\'' $'|' $'/play\0/' $':_ra_comp $\'subcmds:subcommands:(( play:send\\\\ music\\\\ to\\\\ a\\\\ player\\\\ as\\\\ a\\\\ playlist ))\'' $'|' $'/remove\0/' $':_ra_comp $\'subcmds:subcommands:(( remove:remove\\\\ matching\\\\ items\\\\ from\\\\ the\\\\ library ))\'' $'|' $'/splupdate\0/' $':_ra_comp $\'subcmds:subcommands:(( splupdate:update\\\\ the\\\\ smart\\\\ playlists.\\\\ Playlist\\\\ names\\\\ may\\\\ be\\\\ passed\\\\ as\\\\ arguments. ))\'' $'|' $'/stats\0/' $':_ra_comp $\'subcmds:subcommands:(( stats:show\\\\ statistics\\\\ about\\\\ the\\\\ library\\\\ or\\\\ a\\\\ query ))\'' $'|' $'/submit\0/' $':_ra_comp $\'subcmds:subcommands:(( submit:submit\\\\ Acoustid\\\\ fingerprints ))\'' $'|' $'/update\0/' $':_ra_comp $\'subcmds:subcommands:(( update:update\\\\ the\\\\ library ))\'' $'|' $'/version\0/' $':_ra_comp $\'subcmds:subcommands:(( version:output\\\\ version\\\\ information ))\'' $'|' $'/write\0/' $':_ra_comp $\'subcmds:subcommands:(( write:write\\\\ tag\\\\ information\\\\ to\\\\ files ))\'' $')' $')' + case "$?" in + (0|2) _message "no more arguments" ;; + (1) if [[ "$_ra_line[_ra_p1 + 1, -1]" = *$'\0'* ]] + then + _message "parse failed before current word" + else + _ra_left="$_ra_line[_ra_p1 + 1, _ra_p2]" + _ra_right="$_ra_line[_ra_p2 + 1, -1]" + compset -p $(( $#PREFIX - $#_ra_line + $_ra_p1 )) + (( $#_ra_actions )) && _alternative "$_ra_actions[@]" + fi ;; + (3) _message "invalid regex" ;; + esac + [[ nm -ne "$compstate[nmatches]" ]] +} + + +_beet "$@" From 873a6251af0aeb6d30f31e0dc92bc90a1e9eca7d Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 16:29:36 +0100 Subject: [PATCH 1327/2280] Update comments in _beet_cached --- extra/_beet_cached | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/extra/_beet_cached b/extra/_beet_cached index afdae0e80..28e4c4b10 100644 --- a/extra/_beet_cached +++ b/extra/_beet_cached @@ -1,6 +1,11 @@ #compdef beet -# cached completion file for beet (generated from _beet) +# Cached completion file for beet (generated from _beet) +# To use this file add the following line to your .zshrc file: compdef _beet_cached beet +# Note: this was created from _beet, and should be regenerated when new fields or plugins are added. +# See comments at the start of _beet for instructions on how to do this. + +# Created with the following plugins active: fuzzy play info lyrics fromfilename check lastgenre badfiles chroma edit smartplaylist _beet_field_values () { local -a output fieldvals From be69f52b69f397e0265e7ca289a52a0cb1052e90 Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 16:31:02 +0100 Subject: [PATCH 1328/2280] Update _beet_cached --- extra/_beet_cached | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extra/_beet_cached b/extra/_beet_cached index 28e4c4b10..d5f565e29 100644 --- a/extra/_beet_cached +++ b/extra/_beet_cached @@ -1,6 +1,6 @@ #compdef beet -# Cached completion file for beet (generated from _beet) +# Cached zsh completion file for beet (generated from _beet) # To use this file add the following line to your .zshrc file: compdef _beet_cached beet # Note: this was created from _beet, and should be regenerated when new fields or plugins are added. # See comments at the start of _beet for instructions on how to do this. From 518c6b8801dc349a4b8fff6dd52c8a4a52a716f9 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 2 Oct 2016 19:17:56 +0200 Subject: [PATCH 1329/2280] Add tests for comma outside functions in templates Add unit tests for the use of the separator special character (comma) outside a function argument. --- test/test_template.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/test_template.py b/test/test_template.py index 331de0458..67d5d97fe 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -211,6 +211,22 @@ class ParseTest(unittest.TestCase): self._assert_call(arg_parts[0], u"bar", 1) self.assertEqual(list(_normexpr(arg_parts[0].args[0])), [u'baz']) + def test_sep_before_call_two_args(self): + parts = list(_normparse(u'hello, %foo{bar,baz}')) + self.assertEqual(len(parts), 2) + self.assertEqual(parts[0], u'hello, ') + self._assert_call(parts[1], u"foo", 2) + self.assertEqual(list(_normexpr(parts[1].args[0])), [u'bar']) + self.assertEqual(list(_normexpr(parts[1].args[1])), [u'baz']) + + def test_sep_with_symbols(self): + parts = list(_normparse(u'hello,$foo,$bar')) + self.assertEqual(len(parts), 4) + self.assertEqual(parts[0], u'hello,') + self._assert_symbol(parts[1], u"foo") + self.assertEqual(parts[2], u',') + self._assert_symbol(parts[3], u"bar") + class EvalTest(unittest.TestCase): def _eval(self, template): From 657a711f17b34c0ea2e980445912003ba1d61721 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 2 Oct 2016 19:36:32 +0200 Subject: [PATCH 1330/2280] Remove comma from special chars, class variables Remove ARG_SEP from Parser.special_chars, and promote some groups of characters used in parse_expression to class variables. ARG_SEP is still considered an "escapable" character, pending a decision on whether both escaped ('$,') and unescaped (',') syntax would be allowed. --- beets/util/functemplate.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 7a309e793..05d412508 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -318,9 +318,11 @@ class Parser(object): # Common parsing resources. special_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_OPEN, GROUP_CLOSE, - ARG_SEP, ESCAPE_CHAR) + ESCAPE_CHAR) special_char_re = re.compile(r'[%s]|$' % u''.join(re.escape(c) for c in special_chars)) + escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) + terminator_chars = (GROUP_CLOSE) def parse_expression(self): """Parse a template expression starting at ``pos``. Resulting @@ -348,14 +350,13 @@ class Parser(object): # The last character can never begin a structure, so we # just interpret it as a literal character (unless it # terminates the expression, as with , and }). - if char not in (GROUP_CLOSE, ARG_SEP): + if char not in self.terminator_chars: text_parts.append(char) self.pos += 1 break next_char = self.string[self.pos + 1] - if char == ESCAPE_CHAR and next_char in \ - (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP): + if char == ESCAPE_CHAR and next_char in self.escapable_chars: # An escaped special character ($$, $}, etc.). Note that # ${ is not an escape sequence: this is ambiguous with # the start of a symbol and it's not necessary (just @@ -375,7 +376,7 @@ class Parser(object): elif char == FUNC_DELIM: # Parse a function call. self.parse_call() - elif char in (GROUP_CLOSE, ARG_SEP): + elif char in self.terminator_chars: # Template terminated. break elif char == GROUP_OPEN: From 3e8200703674c2a518d4186a4c77287333fc0a14 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 2 Oct 2016 19:44:13 +0200 Subject: [PATCH 1331/2280] Add ArgumentParser, taking into account commas Add ArgumentParser as a subclass of Parser that considers ARG_SEP a special character (ie. always needs escaping, terminates a block); and use it for parsing the substring that contains the list of arguments at parse_argument_list(). --- beets/util/functemplate.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 05d412508..f6b5b3c25 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -484,7 +484,7 @@ class Parser(object): expressions = [] while self.pos < len(self.string): - subparser = Parser(self.string[self.pos:]) + subparser = ArgumentsParser(self.string[self.pos:]) subparser.parse_expression() # Extract and advance past the parsed expression. @@ -513,6 +513,18 @@ class Parser(object): return ident +class ArgumentsParser(Parser): + """``Parser`` that considers ``ARG_SEP`` to be a special character. + """ + # Common parsing resources. + special_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_OPEN, GROUP_CLOSE, + ARG_SEP, ESCAPE_CHAR) + special_char_re = re.compile(r'[%s]|$' % + u''.join(re.escape(c) for c in special_chars)) + escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) + terminator_chars = (GROUP_CLOSE, ARG_SEP) + + def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. From 5282d2882eb9cd4cb7e9d9370256c599575bcaee Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 19:54:10 +0100 Subject: [PATCH 1332/2280] Automatically generate cache file This makes updating cache files easier; you just delete the old one and try completing again. --- extra/_beet | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/extra/_beet b/extra/_beet index 9f20151f7..1c0d23841 100644 --- a/extra/_beet +++ b/extra/_beet @@ -2,19 +2,21 @@ # zsh completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ -# NOTE: it will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins) -# You can make it faster in future by creating a cached version: -# 1) perform a query completion with this file (_beet), e.g. do: beet list artist:" -# to create the completion function (takes a few seconds) -# 2) save a copy of the completion function: which _beet > _beet_cached -# 3) save a copy of the query completion function: which _beet_query > _beet_query_cached -# 4) copy the contents of _beet_query_cached to the top of _beet_cached -# 5) copy and paste the _beet_field_values function from _beet to the top of _beet_cached -# 6) add the following line to the top of _beet_cached: #compdef beet -# 7) add the following line to the bottom of _beet_cached: _beet "$@" -# 8) save _beet_cached to your completions directory (e.g. /usr/share/zsh/functions/Completion) -# 9) add the following line to your .zshrc file: compdef _beet_cached beet -# You will need to repeat this proceedure each time you enable new plugins if you want them to complete properly. +# IMPORTANT: You need to change the $completionsdir variable defined below to point to the directory where your completion files +# are stored. +# It will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins), +# but a cache file (_beet_cached) will be created after the first completion which will make subsequent calls much +# faster. If you enable new plugins or fields you should update the cache file by deleting it and then performing +# another completion in a new shell. + +# If cache file exists, use that +local completionsdir="$HOME/.oh-my-zsh/custom/completions" +local cachefile=$completionsdir/_beet_cached +if [[ -r "$cachefile" ]]; then + source "$cachefile" + _beet "$@" + return +fi # useful: argument to _regex_arguments for matching any word local matchany=/$'[^\0]##\0'/ @@ -68,8 +70,7 @@ queryelem="_values -S : 'query field (add an extra : to match by regexp)' '::' $ # store call to _values function for completing modify terms (no need to complete field values) modifyelem="_values -S = 'modify field (replace = with ! to remove field)' $(echo "'${^fields[@]}:: '")" # Create completion function for queries -_regex_arguments _beet_query "$matchany" \# \( "$matchquery" ":query:query string:$queryelem" \) \ - \( "$matchquery" ":query:query string:$queryelem" \) \# +_regex_arguments _beet_query "$matchany" \# \( "$matchquery" ":query:query string:$queryelem" \) \( "$matchquery" ":query:query string:$queryelem" \) \# # store regexps for completing lists of queries and modifications local -a query modify query=( \( "$matchquery" ":query:query string:{_beet_query}" \) \( "$matchquery" ":query:query string:{_beet_query}" \) \# ) @@ -261,6 +262,17 @@ _regex_arguments _beet "$matchany" \( "${globalopts[@]}" \# \) "${subcmds[@]}" # Set tag-order so that options are completed separately from arguments zstyle ":completion:${curcontext}:" tag-order '! options' +# Save completion functions to _beet_cached +echo "# Cached completion file for beet\n# Note: this was created from _beet, and should be regenerated when new fields or plugins are added.\n# To regenerate this file just delete it, open a new zshell and try completing beet.\n\n" > $cachefile +which _beet_field_values >> $cachefile +echo "\n\n" >> $cachefile +which _beet_query >> $cachefile +echo "\n\n" >> $cachefile +which _beet >> $cachefile +echo "\n\n" >> $cachefile +echo zstyle \":completion:\${curcontext}:\" tag-order \'! options\' >> $cachefile +echo "\n\n_beet \"\$@\"\n" >> $cachefile + # Execute the completion function _beet "$@" From 8671c8381708d54403e86292a0909d574386b1d9 Mon Sep 17 00:00:00 2001 From: vapniks Date: Sun, 2 Oct 2016 19:54:39 +0100 Subject: [PATCH 1333/2280] Delete _beet_cached --- extra/_beet_cached | 64 ---------------------------------------------- 1 file changed, 64 deletions(-) delete mode 100644 extra/_beet_cached diff --git a/extra/_beet_cached b/extra/_beet_cached deleted file mode 100644 index d5f565e29..000000000 --- a/extra/_beet_cached +++ /dev/null @@ -1,64 +0,0 @@ -#compdef beet - -# Cached zsh completion file for beet (generated from _beet) -# To use this file add the following line to your .zshrc file: compdef _beet_cached beet -# Note: this was created from _beet, and should be regenerated when new fields or plugins are added. -# See comments at the start of _beet for instructions on how to do this. - -# Created with the following plugins active: fuzzy play info lyrics fromfilename check lastgenre badfiles chroma edit smartplaylist - -_beet_field_values () { - local -a output fieldvals - local library="$(beet config|grep library|cut -f 2 -d ' ')" - output=$(sqlite3 ${~library} "select distinct $1 from items;") - case $1 in - (lyrics) fieldvals= ;; - (*) fieldvals=("${(f)output[@]}") ;; - esac - compadd -P \" -S \" -M 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' -Q -a fieldvals -} - -_beet_query () { - local _ra_p1 _ra_p2 _ra_left _ra_right _ra_com expl tmp nm="$compstate[nmatches]" - local _ra_actions _ra_line="${(pj:\0:)${(@)words[1,CURRENT - 1]:Q}}"$'\0'"$PREFIX" - _ra_actions=() - zregexparse -c _ra_p1 _ra_p2 "$_ra_line" $'/[^\0]##\0/' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:_values -S : \\\'query field (add an extra : to match by regexp)\\\' \\\'::\\\' \\\'acoustid_fingerprint:::{_beet_field_values acoustid_fingerprint}\\\' \\\'acoustid_id:::{_beet_field_values acoustid_id}\\\' \\\'added:::{_beet_field_values added}\\\' \\\'album:::{_beet_field_values album}\\\' \\\'albumartist:::{_beet_field_values albumartist}\\\' \\\'albumartist_credit:::{_beet_field_values albumartist_credit}\\\' \\\'albumartist_sort:::{_beet_field_values albumartist_sort}\\\' \\\'albumdisambig:::{_beet_field_values albumdisambig}\\\' \\\'album_id:::{_beet_field_values album_id}\\\' \\\'albumstatus:::{_beet_field_values albumstatus}\\\' \\\'albumtotal:::{_beet_field_values albumtotal}\\\' \\\'albumtype:::{_beet_field_values albumtype}\\\' \\\'artist:::{_beet_field_values artist}\\\' \\\'artist_credit:::{_beet_field_values artist_credit}\\\' \\\'artist_sort:::{_beet_field_values artist_sort}\\\' \\\'artpath:::{_beet_field_values artpath}\\\' \\\'asin:::{_beet_field_values asin}\\\' \\\'bitdepth:::{_beet_field_values bitdepth}\\\' \\\'bitrate:::{_beet_field_values bitrate}\\\' \\\'bpm:::{_beet_field_values bpm}\\\' \\\'catalognum:::{_beet_field_values catalognum}\\\' \\\'channels:::{_beet_field_values channels}\\\' \\\'checksum:::{_beet_field_values checksum}\\\' \\\'comments:::{_beet_field_values comments}\\\' \\\'comp:::{_beet_field_values comp}\\\' \\\'composer:::{_beet_field_values composer}\\\' \\\'country:::{_beet_field_values country}\\\' \\\'data_source:::{_beet_field_values data_source}\\\' \\\'day:::{_beet_field_values day}\\\' \\\'disc:::{_beet_field_values disc}\\\' \\\'disctitle:::{_beet_field_values disctitle}\\\' \\\'disctotal:::{_beet_field_values disctotal}\\\' \\\'encoder:::{_beet_field_values encoder}\\\' \\\'filesize:::{_beet_field_values filesize}\\\' \\\'format:::{_beet_field_values format}\\\' \\\'genre:::{_beet_field_values genre}\\\' \\\'grouping:::{_beet_field_values grouping}\\\' \\\'id:::{_beet_field_values id}\\\' \\\'initial_key:::{_beet_field_values initial_key}\\\' \\\'label:::{_beet_field_values label}\\\' \\\'language:::{_beet_field_values language}\\\' \\\'length:::{_beet_field_values length}\\\' \\\'lyrics:::{_beet_field_values lyrics}\\\' \\\'mb_albumartistid:::{_beet_field_values mb_albumartistid}\\\' \\\'mb_albumid:::{_beet_field_values mb_albumid}\\\' \\\'mb_artistid:::{_beet_field_values mb_artistid}\\\' \\\'mb_releasegroupid:::{_beet_field_values mb_releasegroupid}\\\' \\\'mb_trackid:::{_beet_field_values mb_trackid}\\\' \\\'media:::{_beet_field_values media}\\\' \\\'month:::{_beet_field_values month}\\\' \\\'mtime:::{_beet_field_values mtime}\\\' \\\'original_day:::{_beet_field_values original_day}\\\' \\\'original_month:::{_beet_field_values original_month}\\\' \\\'original_year:::{_beet_field_values original_year}\\\' \\\'path:::{_beet_field_values path}\\\' \\\'rg_album_gain:::{_beet_field_values rg_album_gain}\\\' \\\'rg_album_peak:::{_beet_field_values rg_album_peak}\\\' \\\'rg_track_gain:::{_beet_field_values rg_track_gain}\\\' \\\'rg_track_peak:::{_beet_field_values rg_track_peak}\\\' \\\'samplerate:::{_beet_field_values samplerate}\\\' \\\'script:::{_beet_field_values script}\\\' \\\'singleton:::{_beet_field_values singleton}\\\' \\\'title:::{_beet_field_values title}\\\' \\\'track:::{_beet_field_values track}\\\' \\\'tracktotal:::{_beet_field_values tracktotal}\\\' \\\'year:::{_beet_field_values year}\\\'\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:_values -S : \\\'query field (add an extra : to match by regexp)\\\' \\\'::\\\' \\\'acoustid_fingerprint:::{_beet_field_values acoustid_fingerprint}\\\' \\\'acoustid_id:::{_beet_field_values acoustid_id}\\\' \\\'added:::{_beet_field_values added}\\\' \\\'album:::{_beet_field_values album}\\\' \\\'albumartist:::{_beet_field_values albumartist}\\\' \\\'albumartist_credit:::{_beet_field_values albumartist_credit}\\\' \\\'albumartist_sort:::{_beet_field_values albumartist_sort}\\\' \\\'albumdisambig:::{_beet_field_values albumdisambig}\\\' \\\'album_id:::{_beet_field_values album_id}\\\' \\\'albumstatus:::{_beet_field_values albumstatus}\\\' \\\'albumtotal:::{_beet_field_values albumtotal}\\\' \\\'albumtype:::{_beet_field_values albumtype}\\\' \\\'artist:::{_beet_field_values artist}\\\' \\\'artist_credit:::{_beet_field_values artist_credit}\\\' \\\'artist_sort:::{_beet_field_values artist_sort}\\\' \\\'artpath:::{_beet_field_values artpath}\\\' \\\'asin:::{_beet_field_values asin}\\\' \\\'bitdepth:::{_beet_field_values bitdepth}\\\' \\\'bitrate:::{_beet_field_values bitrate}\\\' \\\'bpm:::{_beet_field_values bpm}\\\' \\\'catalognum:::{_beet_field_values catalognum}\\\' \\\'channels:::{_beet_field_values channels}\\\' \\\'checksum:::{_beet_field_values checksum}\\\' \\\'comments:::{_beet_field_values comments}\\\' \\\'comp:::{_beet_field_values comp}\\\' \\\'composer:::{_beet_field_values composer}\\\' \\\'country:::{_beet_field_values country}\\\' \\\'data_source:::{_beet_field_values data_source}\\\' \\\'day:::{_beet_field_values day}\\\' \\\'disc:::{_beet_field_values disc}\\\' \\\'disctitle:::{_beet_field_values disctitle}\\\' \\\'disctotal:::{_beet_field_values disctotal}\\\' \\\'encoder:::{_beet_field_values encoder}\\\' \\\'filesize:::{_beet_field_values filesize}\\\' \\\'format:::{_beet_field_values format}\\\' \\\'genre:::{_beet_field_values genre}\\\' \\\'grouping:::{_beet_field_values grouping}\\\' \\\'id:::{_beet_field_values id}\\\' \\\'initial_key:::{_beet_field_values initial_key}\\\' \\\'label:::{_beet_field_values label}\\\' \\\'language:::{_beet_field_values language}\\\' \\\'length:::{_beet_field_values length}\\\' \\\'lyrics:::{_beet_field_values lyrics}\\\' \\\'mb_albumartistid:::{_beet_field_values mb_albumartistid}\\\' \\\'mb_albumid:::{_beet_field_values mb_albumid}\\\' \\\'mb_artistid:::{_beet_field_values mb_artistid}\\\' \\\'mb_releasegroupid:::{_beet_field_values mb_releasegroupid}\\\' \\\'mb_trackid:::{_beet_field_values mb_trackid}\\\' \\\'media:::{_beet_field_values media}\\\' \\\'month:::{_beet_field_values month}\\\' \\\'mtime:::{_beet_field_values mtime}\\\' \\\'original_day:::{_beet_field_values original_day}\\\' \\\'original_month:::{_beet_field_values original_month}\\\' \\\'original_year:::{_beet_field_values original_year}\\\' \\\'path:::{_beet_field_values path}\\\' \\\'rg_album_gain:::{_beet_field_values rg_album_gain}\\\' \\\'rg_album_peak:::{_beet_field_values rg_album_peak}\\\' \\\'rg_track_gain:::{_beet_field_values rg_track_gain}\\\' \\\'rg_track_peak:::{_beet_field_values rg_track_peak}\\\' \\\'samplerate:::{_beet_field_values samplerate}\\\' \\\'script:::{_beet_field_values script}\\\' \\\'singleton:::{_beet_field_values singleton}\\\' \\\'title:::{_beet_field_values title}\\\' \\\'track:::{_beet_field_values track}\\\' \\\'tracktotal:::{_beet_field_values tracktotal}\\\' \\\'year:::{_beet_field_values year}\\\'\'' $')' $'#' - case "$?" in - (0|2) _message "no more arguments" ;; - (1) if [[ "$_ra_line[_ra_p1 + 1, -1]" = *$'\0'* ]] - then - _message "parse failed before current word" - else - _ra_left="$_ra_line[_ra_p1 + 1, _ra_p2]" - _ra_right="$_ra_line[_ra_p2 + 1, -1]" - compset -p $(( $#PREFIX - $#_ra_line + $_ra_p1 )) - (( $#_ra_actions )) && _alternative "$_ra_actions[@]" - fi ;; - (3) _message "invalid regex" ;; - esac - [[ nm -ne "$compstate[nmatches]" ]] -} - -_beet () { - local _ra_p1 _ra_p2 _ra_left _ra_right _ra_com expl tmp nm="$compstate[nmatches]" - local _ra_actions _ra_line="${(pj:\0:)${(@)words[1,CURRENT - 1]:Q}}"$'\0'"$PREFIX" - _ra_actions=() - zregexparse -c _ra_p1 _ra_p2 "$_ra_line" $'/[^\0]##\0/' $'(' $'(' $'/-c\0/' $':_ra_comp $\'options:global options:(( -c:path\\\\ to\\\\ configuration\\\\ file ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-v\0/' $':_ra_comp $\'options:global options:(( -v:print\\\\ debugging\\\\ information ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:global options:(( -l:library\\\\ database\\\\ file\\\\ to\\\\ use ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-h\0/' $':_ra_comp $\'options:global options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:global options:(( -d:destination\\\\ music\\\\ directory ))\'' $'/[^\0]##\0/' $':_ra_comp $\'dir:directory:_dirs\'' $')' $'#' $')' $'(' $'/bad\0/' $':_ra_comp $\'subcmds:subcommands:(( bad:check\\\\ for\\\\ corrupt\\\\ or\\\\ missing\\\\ files ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:bad options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/check\0/' $':_ra_comp $\'subcmds:subcommands:(( check:compute\\\\ and\\\\ verify\\\\ checksums ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:check options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:check options:(( -e:run\\\\ external\\\\ tools ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:check options:(( -a:add\\\\ checksum\\\\ for\\\\ all\\\\ files\\\\ that\\\\ do\\\\ not\\\\ already\\\\ have\\\\ one ))\'' $'|' $'/-u\0/' $':_ra_comp $\'options:check options:(( -u:compute\\\\ new\\\\ checksums\\\\ and\\\\ add\\\\ the\\\\ to\\\\ the\\\\ database ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:check options:(( -f:force\\\\ updating\\\\ the\\\\ whole\\\\ library\\\\ or\\\\ fixing\\\\ all\\\\ files ))\'' $'|' $'/--export\0/' $':_ra_comp $\'options:check options:(( --export:print\\\\ paths\\\\ and\\\\ corresponding\\\\ checksum ))\'' $'|' $'/-x\0/' $':_ra_comp $\'options:check options:(( -x:fix\\\\ errors\\\\ with\\\\ external\\\\ tools ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:check options:(( -l:list\\\\ available\\\\ third-party\\\\ used\\\\ to\\\\ check\\\\ integrity ))\'' $'|' $'/-q\0/' $':_ra_comp $\'options:check options:(( -q:only\\\\ show\\\\ errors ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/config\0/' $':_ra_comp $\'subcmds:subcommands:(( config:show\\\\ or\\\\ edit\\\\ the\\\\ user\\\\ configuration ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:config options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:config options:(( -p:print\\\\ paths\\\\ for\\\\ matched\\\\ items\\\\ or\\\\ albums ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:config options:(( -e:edit\\\\ user\\\\ configuration\\\\ with\\\\ $EDITOR ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:config options:(( -d:include\\\\ the\\\\ default\\\\ configuration ))\'' $')' $'|' $'/edit\0/' $':_ra_comp $\'subcmds:subcommands:(( edit:interactively\\\\ edit\\\\ metadata ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:edit options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:edit options:(( -f:edit\\\\ this\\\\ field\\\\ also ))\'' $'/[^\0]##\0/' $'|' $'/--all\0/' $':_ra_comp $\'options:edit options:(( --all:edit\\\\ all\\\\ fields ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:edit options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/fields\0/' $':_ra_comp $\'subcmds:subcommands:(( fields:show\\\\ fields\\\\ available\\\\ for\\\\ queries\\\\ and\\\\ format\\\\ strings ))\'' $'|' $'/fingerprint\0/' $':_ra_comp $\'subcmds:subcommands:(( fingerprint:generate\\\\ fingerprints\\\\ for\\\\ items\\\\ without\\\\ them ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:fingerprint options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/import\0/' $':_ra_comp $\'subcmds:subcommands:(( import:import\\\\ new\\\\ music ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:import options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-w\0/' $':_ra_comp $\'options:import options:(( -w:write\\\\ new\\\\ metadata\\\\ to\\\\ files\\\\ tags\\\\ \\\\(default\\\\) ))\'' $'|' $'/-W\0/' $':_ra_comp $\'options:import options:(( -W:dont\\\\ write\\\\ metadata\\\\ \\\\(opposite\\\\ of\\\\ -w\\\\) ))\'' $'|' $'/-c\0/' $':_ra_comp $\'options:import options:(( -c:copy\\\\ tracks\\\\ into\\\\ library\\\\ directory\\\\ \\\\(default\\\\) ))\'' $'|' $'/-C\0/' $':_ra_comp $\'options:import options:(( -C:dont\\\\ copy\\\\ tracks\\\\ \\\\(opposite\\\\ of\\\\ -c\\\\) ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:import options:(( -a:infer\\\\ tags\\\\ for\\\\ imported\\\\ files\\\\ \\\\(default\\\\) ))\'' $'|' $'/-A\0/' $':_ra_comp $\'options:import options:(( -A:dont\\\\ infer\\\\ tags\\\\ for\\\\ imported\\\\ files\\\\ \\\\(opposite\\\\ of\\\\ -a\\\\) ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:import options:(( -p:resume\\\\ importing\\\\ if\\\\ interrupted ))\'' $'|' $'/-P\0/' $':_ra_comp $\'options:import options:(( -P:do\\\\ not\\\\ try\\\\ to\\\\ resume\\\\ importing ))\'' $'|' $'/-q\0/' $':_ra_comp $\'options:import options:(( -q:never\\\\ prompt\\\\ for\\\\ input,\\\\ skip\\\\ albums\\\\ instead ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:import options:(( -l:file\\\\ to\\\\ log\\\\ untaggable\\\\ albums\\\\ for\\\\ later\\\\ review ))\'' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'|' $'/-s\0/' $':_ra_comp $\'options:import options:(( -s:import\\\\ individual\\\\ tracks\\\\ instead\\\\ of\\\\ full\\\\ albums ))\'' $'|' $'/-t\0/' $':_ra_comp $\'options:import options:(( -t:always\\\\ confirm\\\\ all\\\\ actions ))\'' $'|' $'/-L\0/' $':_ra_comp $\'options:import options:(( -L:retag\\\\ items\\\\ matching\\\\ a\\\\ query ))\'' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/-i\0/' $':_ra_comp $\'options:import options:(( -i:skip\\\\ already-imported\\\\ directories ))\'' $'|' $'/-I\0/' $':_ra_comp $\'options:import options:(( -I:do\\\\ not\\\\ skip\\\\ already-imported\\\\ directories ))\'' $'|' $'/--flat\0/' $':_ra_comp $\'options:import options:(( --flat:import\\\\ an\\\\ entire\\\\ tree\\\\ as\\\\ a\\\\ single\\\\ album ))\'' $'|' $'/-g\0/' $':_ra_comp $\'options:import options:(( -g:group\\\\ tracks\\\\ in\\\\ a\\\\ folder\\\\ into\\\\ seperate\\\\ albums ))\'' $')' $'#' $'/[^\0]##\0/' $':_ra_comp $\'file:file:_files\'' $'#' $'|' $'/info\0/' $':_ra_comp $\'subcmds:subcommands:(( info:show\\\\ file\\\\ metadata ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:info options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-l\0/' $':_ra_comp $\'options:info options:(( -l:show\\\\ library\\\\ fields\\\\ instead\\\\ of\\\\ tags ))\'' $'|' $'/-s\0/' $':_ra_comp $\'options:info options:(( -s:summarize\\\\ the\\\\ tags\\\\ of\\\\ all\\\\ files ))\'' $'|' $'/-i\0/' $':_ra_comp $\'options:info options:(( -i:INCLUDED__KEYS\\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ comma\\\\ separated\\\\ list\\\\ of\\\\ keys\\\\ to\\\\ show ))\'' $'/[^\0]##\0/' $'|' $'/-k\0/' $':_ra_comp $\'options:info options:(( -k:show\\\\ only\\\\ the\\\\ keys ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:info options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/lastgenre\0/' $':_ra_comp $\'subcmds:subcommands:(( lastgenre:fetch\\\\ genres ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:lastgenre options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:lastgenre options:(( -f:re-download\\\\ genre\\\\ when\\\\ already\\\\ present ))\'' $'|' $'/-s\0/' $':_ra_comp $\'options:lastgenre options:(( -s:genre\\\\ source-\\\\ artist,\\\\ album,\\\\ or\\\\ track ))\'' $'/(artist|album|track)\0/' $':_ra_comp $\'source:genre source:(artist album track)\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/list\0/' $':_ra_comp $\'subcmds:subcommands:(( list:query\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:list options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:list options:(( -p:print\\\\ paths\\\\ for\\\\ matched\\\\ items\\\\ or\\\\ albums ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:list options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:list options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/lyrics\0/' $':_ra_comp $\'subcmds:subcommands:(( lyrics:fetch\\\\ song\\\\ lyrics ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:lyrics options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:lyrics options:(( -p:print\\\\ lyrics\\\\ to\\\\ console ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:lyrics options:(( -f:always\\\\ re-download\\\\ lyrics ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/modify\0/' $':_ra_comp $\'subcmds:subcommands:(( modify:change\\\\ metadata\\\\ fields ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:modify options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-M\0/' $':_ra_comp $\'options:modify options:(( -M:dont\\\\ move\\\\ files\\\\ in\\\\ library ))\'' $'|' $'/-w\0/' $':_ra_comp $\'options:modify options:(( -w:write\\\\ new\\\\ metadata\\\\ to\\\\ files\\\\ tags\\\\ \\\\(default\\\\) ))\'' $'|' $'/-W\0/' $':_ra_comp $\'options:modify options:(( -W:dont\\\\ write\\\\ metadata\\\\ \\\\(opposite\\\\ of\\\\ -w\\\\) ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:modify options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-y\0/' $':_ra_comp $\'options:modify options:(( -y:skip\\\\ confirmation ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:modify options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year)(=[^\0]##|\!)\0/' $':_ra_comp $\'modify:modify string:_values -S = \\\'modify field (replace = with \\\! to remove field)\\\' \\\'acoustid_fingerprint:: \\\' \\\'acoustid_id:: \\\' \\\'added:: \\\' \\\'album:: \\\' \\\'albumartist:: \\\' \\\'albumartist_credit:: \\\' \\\'albumartist_sort:: \\\' \\\'albumdisambig:: \\\' \\\'album_id:: \\\' \\\'albumstatus:: \\\' \\\'albumtotal:: \\\' \\\'albumtype:: \\\' \\\'artist:: \\\' \\\'artist_credit:: \\\' \\\'artist_sort:: \\\' \\\'artpath:: \\\' \\\'asin:: \\\' \\\'bitdepth:: \\\' \\\'bitrate:: \\\' \\\'bpm:: \\\' \\\'catalognum:: \\\' \\\'channels:: \\\' \\\'checksum:: \\\' \\\'comments:: \\\' \\\'comp:: \\\' \\\'composer:: \\\' \\\'country:: \\\' \\\'data_source:: \\\' \\\'day:: \\\' \\\'disc:: \\\' \\\'disctitle:: \\\' \\\'disctotal:: \\\' \\\'encoder:: \\\' \\\'filesize:: \\\' \\\'format:: \\\' \\\'genre:: \\\' \\\'grouping:: \\\' \\\'id:: \\\' \\\'initial_key:: \\\' \\\'label:: \\\' \\\'language:: \\\' \\\'length:: \\\' \\\'lyrics:: \\\' \\\'mb_albumartistid:: \\\' \\\'mb_albumid:: \\\' \\\'mb_artistid:: \\\' \\\'mb_releasegroupid:: \\\' \\\'mb_trackid:: \\\' \\\'media:: \\\' \\\'month:: \\\' \\\'mtime:: \\\' \\\'original_day:: \\\' \\\'original_month:: \\\' \\\'original_year:: \\\' \\\'path:: \\\' \\\'rg_album_gain:: \\\' \\\'rg_album_peak:: \\\' \\\'rg_track_gain:: \\\' \\\'rg_track_peak:: \\\' \\\'samplerate:: \\\' \\\'script:: \\\' \\\'singleton:: \\\' \\\'title:: \\\' \\\'track:: \\\' \\\'tracktotal:: \\\' \\\'year:: \\\'\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year)(=[^\0]##|\!)\0/' $':_ra_comp $\'modify:modify string:_values -S = \\\'modify field (replace = with \\\! to remove field)\\\' \\\'acoustid_fingerprint:: \\\' \\\'acoustid_id:: \\\' \\\'added:: \\\' \\\'album:: \\\' \\\'albumartist:: \\\' \\\'albumartist_credit:: \\\' \\\'albumartist_sort:: \\\' \\\'albumdisambig:: \\\' \\\'album_id:: \\\' \\\'albumstatus:: \\\' \\\'albumtotal:: \\\' \\\'albumtype:: \\\' \\\'artist:: \\\' \\\'artist_credit:: \\\' \\\'artist_sort:: \\\' \\\'artpath:: \\\' \\\'asin:: \\\' \\\'bitdepth:: \\\' \\\'bitrate:: \\\' \\\'bpm:: \\\' \\\'catalognum:: \\\' \\\'channels:: \\\' \\\'checksum:: \\\' \\\'comments:: \\\' \\\'comp:: \\\' \\\'composer:: \\\' \\\'country:: \\\' \\\'data_source:: \\\' \\\'day:: \\\' \\\'disc:: \\\' \\\'disctitle:: \\\' \\\'disctotal:: \\\' \\\'encoder:: \\\' \\\'filesize:: \\\' \\\'format:: \\\' \\\'genre:: \\\' \\\'grouping:: \\\' \\\'id:: \\\' \\\'initial_key:: \\\' \\\'label:: \\\' \\\'language:: \\\' \\\'length:: \\\' \\\'lyrics:: \\\' \\\'mb_albumartistid:: \\\' \\\'mb_albumid:: \\\' \\\'mb_artistid:: \\\' \\\'mb_releasegroupid:: \\\' \\\'mb_trackid:: \\\' \\\'media:: \\\' \\\'month:: \\\' \\\'mtime:: \\\' \\\'original_day:: \\\' \\\'original_month:: \\\' \\\'original_year:: \\\' \\\'path:: \\\' \\\'rg_album_gain:: \\\' \\\'rg_album_peak:: \\\' \\\'rg_track_gain:: \\\' \\\'rg_track_peak:: \\\' \\\'samplerate:: \\\' \\\'script:: \\\' \\\'singleton:: \\\' \\\'title:: \\\' \\\'track:: \\\' \\\'tracktotal:: \\\' \\\'year:: \\\'\'' $')' $'#' $'|' $'/move\0/' $':_ra_comp $\'subcmds:subcommands:(( move:move\\\\ or\\\\ copy\\\\ items ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:move options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:move options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:move options:(( -d:destination\\\\ music\\\\ directory ))\'' $'/[^\0]##\0/' $':_ra_comp $\'dir:directory:_dirs\'' $'|' $'/-c\0/' $':_ra_comp $\'options:move options:(( -c:copy\\\\ instead\\\\ of\\\\ moving ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/play\0/' $':_ra_comp $\'subcmds:subcommands:(( play:send\\\\ music\\\\ to\\\\ a\\\\ player\\\\ as\\\\ a\\\\ playlist ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:play options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:play options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-A\0/' $':_ra_comp $\'options:play options:(( -A:add\\\\ additional\\\\ arguments\\\\ to\\\\ the\\\\ command ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/remove\0/' $':_ra_comp $\'subcmds:subcommands:(( remove:remove\\\\ matching\\\\ items\\\\ from\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:remove options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:remove options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-d\0/' $':_ra_comp $\'options:remove options:(( -d:also\\\\ remove\\\\ files\\\\ from\\\\ disk ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/splupdate\0/' $':_ra_comp $\'subcmds:subcommands:(( splupdate:update\\\\ the\\\\ smart\\\\ playlists.\\\\ Playlist\\\\ names\\\\ may\\\\ be\\\\ passed\\\\ as\\\\ arguments. ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:splupdate options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/stats\0/' $':_ra_comp $\'subcmds:subcommands:(( stats:show\\\\ statistics\\\\ about\\\\ the\\\\ library\\\\ or\\\\ a\\\\ query ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:stats options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-e\0/' $':_ra_comp $\'options:stats options:(( -e:get\\\\ exact\\\\ file\\\\ sizes ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/submit\0/' $':_ra_comp $\'subcmds:subcommands:(( submit:submit\\\\ Acoustid\\\\ fingerprints ))\'' $'(' $'(' $'/-h\0/' $':_ra_comp $\'options:submit options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $')' $'|' $'/update\0/' $':_ra_comp $\'subcmds:subcommands:(( update:update\\\\ the\\\\ library ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:update options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-a\0/' $':_ra_comp $\'options:update options:(( -a:match\\\\ albums\\\\ instead\\\\ of\\\\ tracks ))\'' $'|' $'/-M\0/' $':_ra_comp $\'options:update options:(( -M:dont\\\\ move\\\\ files\\\\ in\\\\ library ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:update options:(( -p:show\\\\ all\\\\ changes\\\\ but\\\\ do\\\\ nothing ))\'' $'|' $'/-f\0/' $':_ra_comp $\'options:update options:(( -f:print\\\\ with\\\\ custom\\\\ format ))\'' $'/[^\0]##\0/' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/version\0/' $':_ra_comp $\'subcmds:subcommands:(( version:output\\\\ version\\\\ information ))\'' $'|' $'/write\0/' $':_ra_comp $\'subcmds:subcommands:(( write:write\\\\ tag\\\\ information\\\\ to\\\\ files ))\'' $'(' $'/-h\0/' $':_ra_comp $\'options:write options:(( -h:show\\\\ this\\\\ help\\\\ message\\\\ and\\\\ exit ))\'' $'|' $'/-p\0/' $':_ra_comp $\'options:write options:(( -p:show\\\\ all\\\\ changes\\\\ but\\\\ do\\\\ nothing ))\'' $')' $'#' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'(' $'/(acoustid_fingerprint|acoustid_id|added|album|albumartist|albumartist_credit|albumartist_sort|albumdisambig|album_id|albumstatus|albumtotal|albumtype|artist|artist_credit|artist_sort|artpath|asin|bitdepth|bitrate|bpm|catalognum|channels|checksum|comments|comp|composer|country|data_source|day|disc|disctitle|disctotal|encoder|filesize|format|genre|grouping|id|initial_key|label|language|length|lyrics|mb_albumartistid|mb_albumid|mb_artistid|mb_releasegroupid|mb_trackid|media|month|mtime|original_day|original_month|original_year|path|rg_album_gain|rg_album_peak|rg_track_gain|rg_track_peak|samplerate|script|singleton|title|track|tracktotal|year):[^\0]##\0/' $':_ra_comp $\'query:query string:{_beet_query}\'' $')' $'#' $'|' $'/help\0/' $':_ra_comp $\'subcmds:subcommands:(( help:show\\\\ help ))\'' $'(' $'/bad\0/' $':_ra_comp $\'subcmds:subcommands:(( bad:check\\\\ for\\\\ corrupt\\\\ or\\\\ missing\\\\ files ))\'' $'|' $'/check\0/' $':_ra_comp $\'subcmds:subcommands:(( check:compute\\\\ and\\\\ verify\\\\ checksums ))\'' $'|' $'/config\0/' $':_ra_comp $\'subcmds:subcommands:(( config:show\\\\ or\\\\ edit\\\\ the\\\\ user\\\\ configuration ))\'' $'|' $'/edit\0/' $':_ra_comp $\'subcmds:subcommands:(( edit:interactively\\\\ edit\\\\ metadata ))\'' $'|' $'/fields\0/' $':_ra_comp $\'subcmds:subcommands:(( fields:show\\\\ fields\\\\ available\\\\ for\\\\ queries\\\\ and\\\\ format\\\\ strings ))\'' $'|' $'/fingerprint\0/' $':_ra_comp $\'subcmds:subcommands:(( fingerprint:generate\\\\ fingerprints\\\\ for\\\\ items\\\\ without\\\\ them ))\'' $'|' $'/import\0/' $':_ra_comp $\'subcmds:subcommands:(( import:import\\\\ new\\\\ music ))\'' $'|' $'/info\0/' $':_ra_comp $\'subcmds:subcommands:(( info:show\\\\ file\\\\ metadata ))\'' $'|' $'/lastgenre\0/' $':_ra_comp $\'subcmds:subcommands:(( lastgenre:fetch\\\\ genres ))\'' $'|' $'/list\0/' $':_ra_comp $\'subcmds:subcommands:(( list:query\\\\ the\\\\ library ))\'' $'|' $'/lyrics\0/' $':_ra_comp $\'subcmds:subcommands:(( lyrics:fetch\\\\ song\\\\ lyrics ))\'' $'|' $'/modify\0/' $':_ra_comp $\'subcmds:subcommands:(( modify:change\\\\ metadata\\\\ fields ))\'' $'|' $'/move\0/' $':_ra_comp $\'subcmds:subcommands:(( move:move\\\\ or\\\\ copy\\\\ items ))\'' $'|' $'/play\0/' $':_ra_comp $\'subcmds:subcommands:(( play:send\\\\ music\\\\ to\\\\ a\\\\ player\\\\ as\\\\ a\\\\ playlist ))\'' $'|' $'/remove\0/' $':_ra_comp $\'subcmds:subcommands:(( remove:remove\\\\ matching\\\\ items\\\\ from\\\\ the\\\\ library ))\'' $'|' $'/splupdate\0/' $':_ra_comp $\'subcmds:subcommands:(( splupdate:update\\\\ the\\\\ smart\\\\ playlists.\\\\ Playlist\\\\ names\\\\ may\\\\ be\\\\ passed\\\\ as\\\\ arguments. ))\'' $'|' $'/stats\0/' $':_ra_comp $\'subcmds:subcommands:(( stats:show\\\\ statistics\\\\ about\\\\ the\\\\ library\\\\ or\\\\ a\\\\ query ))\'' $'|' $'/submit\0/' $':_ra_comp $\'subcmds:subcommands:(( submit:submit\\\\ Acoustid\\\\ fingerprints ))\'' $'|' $'/update\0/' $':_ra_comp $\'subcmds:subcommands:(( update:update\\\\ the\\\\ library ))\'' $'|' $'/version\0/' $':_ra_comp $\'subcmds:subcommands:(( version:output\\\\ version\\\\ information ))\'' $'|' $'/write\0/' $':_ra_comp $\'subcmds:subcommands:(( write:write\\\\ tag\\\\ information\\\\ to\\\\ files ))\'' $')' $')' - case "$?" in - (0|2) _message "no more arguments" ;; - (1) if [[ "$_ra_line[_ra_p1 + 1, -1]" = *$'\0'* ]] - then - _message "parse failed before current word" - else - _ra_left="$_ra_line[_ra_p1 + 1, _ra_p2]" - _ra_right="$_ra_line[_ra_p2 + 1, -1]" - compset -p $(( $#PREFIX - $#_ra_line + $_ra_p1 )) - (( $#_ra_actions )) && _alternative "$_ra_actions[@]" - fi ;; - (3) _message "invalid regex" ;; - esac - [[ nm -ne "$compstate[nmatches]" ]] -} - - -_beet "$@" From bc8f422433adb8509f14e8a1539f4c146c44f56a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 3 Oct 2016 19:48:01 +0200 Subject: [PATCH 1334/2280] Do not attempt matching unset fields on DateQuery Add a comparison at DateQuery.match in order to avoid comparing if the field is not in the item. Revise the existing types_plugin unit tests for explicitely checking the behaviour when the values are unset. --- beets/dbcore/query.py | 2 ++ test/test_types_plugin.py | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 3710d55c2..d27897e69 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -628,6 +628,8 @@ class DateQuery(FieldQuery): self.interval = DateInterval.from_periods(start, end) def match(self, item): + if self.field not in item: + return False timestamp = float(item[self.field]) date = datetime.utcfromtimestamp(timestamp) return self.interval.contains(date) diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 67e682844..826dd5ea7 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -70,6 +70,10 @@ class TypesPluginTest(unittest.TestCase, TestHelper): self.config['types'] = {'myfloat': u'float'} item = self.add_item(artist=u'aaa') + # Do not match unset values + out = self.list(u'myfloat:10..0') + self.assertEqual(u'', out) + self.modify(u'myfloat=-9.1') item.load() self.assertEqual(item['myfloat'], -9.1) @@ -84,6 +88,10 @@ class TypesPluginTest(unittest.TestCase, TestHelper): false = self.add_item(artist=u'false') self.add_item(artist=u'unset') + # Do not match unset values + out = self.list(u'mybool:true, mybool:false') + self.assertEqual(u'', out) + # Set true self.modify(u'mybool=1', u'artist:true') true.load() @@ -112,6 +120,10 @@ class TypesPluginTest(unittest.TestCase, TestHelper): old = self.add_item(artist=u'prince') new = self.add_item(artist=u'britney') + # Do not match unset values + out = self.list(u'mydate:..2000') + self.assertEqual(u'', out) + self.modify(u'mydate=1999-01-01', u'artist:prince') old.load() self.assertEqual(old['mydate'], mktime(1999, 1, 1)) From b9b6dc47d1a1a72befdb3c0b0b10c40b80ef5dc6 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 3 Oct 2016 20:43:35 +0200 Subject: [PATCH 1335/2280] Add changelog for #1938 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 699a3c500..96c92aeb5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -68,6 +68,8 @@ And there are a few bug fixes too: a problem that it was not possible to get tokens from the Emby API. * :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the colon character. :bug:`2206` +* Fix a crash when a query contains a date field that is not set for all + the items. :bug:`1938` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From c5da6296c40146a4db9d158496353165127437f9 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 3 Oct 2016 23:01:50 +0200 Subject: [PATCH 1336/2280] Use flag instead of subclass for comma in Parser Use a `in_argument` flag on Parser constructor for specifying if the parser should treat commas as a special character, including the logic in parse_expression. --- beets/util/functemplate.py | 45 +++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index f6b5b3c25..51716552c 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -311,8 +311,14 @@ class Parser(object): replaced with a real, accepted parsing technique (PEG, parser generator, etc.). """ - def __init__(self, string): + def __init__(self, string, in_argument=False): + """ Create a new parser. + :param in_arguments: boolean that indicates the parser is to be + used for parsing function arguments, ie. considering commas + (`ARG_SEP`) a special character + """ self.string = string + self.in_argument = in_argument self.pos = 0 self.parts = [] @@ -322,7 +328,7 @@ class Parser(object): special_char_re = re.compile(r'[%s]|$' % u''.join(re.escape(c) for c in special_chars)) escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) - terminator_chars = (GROUP_CLOSE) + terminator_chars = (GROUP_CLOSE,) def parse_expression(self): """Parse a template expression starting at ``pos``. Resulting @@ -330,16 +336,26 @@ class Parser(object): the ``parts`` field, a list. The ``pos`` field is updated to be the next character after the expression. """ + # Append comma (ARG_SEP) to the list of special characters only when + # parsing function arguments. + extra_special_chars = () + special_char_re = self.special_char_re + if self.in_argument: + extra_special_chars = (ARG_SEP,) + special_char_re = re.compile( + r'[%s]|$' % u''.join(re.escape(c) for c in + self.special_chars + extra_special_chars)) + text_parts = [] while self.pos < len(self.string): char = self.string[self.pos] - if char not in self.special_chars: + if char not in self.special_chars + extra_special_chars: # A non-special character. Skip to the next special # character, treating the interstice as literal text. next_pos = ( - self.special_char_re.search( + special_char_re.search( self.string[self.pos:]).start() + self.pos ) text_parts.append(self.string[self.pos:next_pos]) @@ -350,13 +366,14 @@ class Parser(object): # The last character can never begin a structure, so we # just interpret it as a literal character (unless it # terminates the expression, as with , and }). - if char not in self.terminator_chars: + if char not in self.terminator_chars + extra_special_chars: text_parts.append(char) self.pos += 1 break next_char = self.string[self.pos + 1] - if char == ESCAPE_CHAR and next_char in self.escapable_chars: + if char == ESCAPE_CHAR and next_char in (self.escapable_chars + + extra_special_chars): # An escaped special character ($$, $}, etc.). Note that # ${ is not an escape sequence: this is ambiguous with # the start of a symbol and it's not necessary (just @@ -376,7 +393,7 @@ class Parser(object): elif char == FUNC_DELIM: # Parse a function call. self.parse_call() - elif char in self.terminator_chars: + elif char in self.terminator_chars + extra_special_chars: # Template terminated. break elif char == GROUP_OPEN: @@ -484,7 +501,7 @@ class Parser(object): expressions = [] while self.pos < len(self.string): - subparser = ArgumentsParser(self.string[self.pos:]) + subparser = Parser(self.string[self.pos:], in_argument=True) subparser.parse_expression() # Extract and advance past the parsed expression. @@ -513,18 +530,6 @@ class Parser(object): return ident -class ArgumentsParser(Parser): - """``Parser`` that considers ``ARG_SEP`` to be a special character. - """ - # Common parsing resources. - special_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_OPEN, GROUP_CLOSE, - ARG_SEP, ESCAPE_CHAR) - special_char_re = re.compile(r'[%s]|$' % - u''.join(re.escape(c) for c in special_chars)) - escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) - terminator_chars = (GROUP_CLOSE, ARG_SEP) - - def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. From 550206adb55bf312fc1863ac003b222caa5a4745 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 3 Oct 2016 23:31:47 +0200 Subject: [PATCH 1337/2280] Add changelog for unescaped commas in Parser --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 699a3c500..416568799 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -45,6 +45,8 @@ The are a couple of small new features: when a song can be found on AcousticBrainz, this is faster and more automatic than using the :doc:`/plugins/bpm`. * ``beet --version`` now includes the python version used to run beets. +* :doc:`/reference/pathformat` can now include unescaped commas (``,``) when + they are not part of a function call. :bug:`2166` :bug:`2213` And there are a few bug fixes too: From 0eb03534533143f5c6c6436a241317b891c7c209 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 4 Oct 2016 16:17:26 +0200 Subject: [PATCH 1338/2280] Revise documentation for commas in Parser --- docs/reference/pathformat.rst | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index b5d754bd4..240534a9a 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -142,11 +142,17 @@ Syntax Details The characters ``$``, ``%``, ``{``, ``}``, and ``,`` are "special" in the path template syntax. This means that, for example, if you want a ``%`` character to appear in your paths, you'll need to be careful that you don't accidentally -write a function call. To escape any of these characters (except ``{``), prefix -it with a ``$``. For example, ``$$`` becomes ``$``; ``$%`` becomes ``%``, etc. -The only exception is ``${``, which is ambiguous with the variable reference -syntax (like ``${title}``). To insert a ``{`` alone, it's always sufficient to -just type ``{``. +write a function call. To escape any of these characters (except ``{``, and +``,`` outside a function argument), prefix it with a ``$``. For example, +``$$`` becomes ``$``; ``$%`` becomes ``%``, etc. The only exceptions are: + +* ``${``, which is ambiguous with the variable reference syntax (like + ``${title}``). To insert a ``{`` alone, it's always sufficient to just type + ``{``. +* commas are used as argument separators in function calls. Inside of a + function's argument, use ``$,`` to get a literal ``,`` character. Outside of + any function argument, escaping is not necessary: ``,`` by itself will + produce ``,`` in the output. If a value or function is undefined, the syntax is simply left unreplaced. For example, if you write ``$foo`` in a path template, this will yield ``$foo`` in From f0a14bfdd530e1ddc8cc67316f458de6996c8a55 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Tue, 4 Oct 2016 16:20:52 +0200 Subject: [PATCH 1339/2280] Fix documentation issues for %first Fix a formatting problem related to sphinx not allowing spaces at the beginning or end of an inline literal, and removed an extra sentence at th end of the %first template function documentation. --- docs/reference/pathformat.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 240534a9a..72453a6e5 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -76,12 +76,12 @@ These functions are built in to beets: * ``%time{date_time,format}``: Return the date and time in any format accepted by `strftime`_. For example, to get the year some music was added to your library, use ``%time{$added,%Y}``. -* ``%first{text}``: Returns the first item, separated by ``; ``. +* ``%first{text}``: Returns the first item, separated by ``;`` (a semicolon + followed by a space). You can use ``%first{text,count,skip}``, where ``count`` is the number of items (default 1) and ``skip`` is number to skip (default 0). You can also use ``%first{text,count,skip,sep,join}`` where ``sep`` is the separator, like ``;`` or ``/`` and join is the text to concatenate the items. - For example, * ``%ifdef{field}``, ``%ifdef{field,truetext}`` or ``%ifdef{field,truetext,falsetext}``: If ``field`` exists, then return ``truetext`` or ``field`` (default). Otherwise, returns ``falsetext``. From 9c88998a5d40f623e1c98006492393d3b2ad718a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 6 Oct 2016 19:31:55 +0200 Subject: [PATCH 1340/2280] discogs: add initial unit test skeleton Add a first skeleton for providing unit tests for the discogs plugin, heavily inspired by test_mb, which adds a couple of method for creating very simple and not comprehensive Bags that mimic discogs_client.Release and discogs_client.Track. Add a test for checking the problem of setting media for the Tracks. --- test/test_discogs.py | 94 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 test/test_discogs.py diff --git a/test/test_discogs.py b/test/test_discogs.py new file mode 100644 index 000000000..2cf86bd0d --- /dev/null +++ b/test/test_discogs.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for discogs plugin. +""" +from __future__ import division, absolute_import, print_function + +from test import _common +from test._common import unittest, Bag + +from beetsplug.discogs import DiscogsPlugin + + +class DGAlbumInfoTest(_common.TestCase): + def _make_release(self, date_str='2009', tracks=None, track_length=None, + track_artist=False): + """Returns a Bag that mimics a discogs_client.Release. The list + of elements on the returned Bag is incomplete, including just + those required for the tests on this class.""" + data = { + 'id': 'ALBUM ID', + 'uri': 'ALBUM URI', + 'title': 'ALBUM TITLE', + 'year': '3001', + 'artists': [{ + 'name': 'ARTIST NAME', + 'id': 'ARTIST ID', + 'join': ',' + }], + 'formats': [{ + 'descriptions': ['FORMAT DESC 1', 'FORMAT DESC 2'], + 'name': 'FORMAT', + 'qty': 1 + }], + 'labels': [{ + 'name': 'LABEL NAME', + 'catno': 'CATALOG NUMBER', + }], + 'tracklist': [] + } + + if tracks: + for recording in tracks: + data['tracklist'].append(recording) + + return Bag(data=data, + # Make some fields available as properties, as they are + # accessed by DiscogsPlugin methods. + title=data['title'], + artists=[Bag(data=d) for d in data['artists']]) + + def _make_track(self, title, position='', duration='', type_=None): + track = { + 'title': title, + 'position': position, + 'duration': duration + } + if type_ is not None: + # Test samples on discogs_client do not have a 'type_' field, but + # the API seems to return it. Values: 'track' for regular tracks, + # 'heading' for descriptive texts (ie. not real tracks - 12.13.2). + track['type_'] = type_ + + return track + + def test_set_media_for_tracks(self): + tracks = [self._make_track('TITLE ONE', '1', '01:01'), + self._make_track('TITLE TWO', '2', '02:02')] + release = self._make_release(tracks=tracks) + + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + self.assertEqual(d.media, 'FORMAT') + self.assertEqual(t[0].media, d.media) + self.assertEqual(t[1].media, d.media) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') From 911117ef49e8a9d961615ecc6a43d04f5a57d6f5 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Thu, 6 Oct 2016 19:49:43 +0200 Subject: [PATCH 1341/2280] discogs: set media on tracks (#1921) Set the media for all the tracks when fetching a release using discogs, as autotag.apply_metadata requires it in order to work properly. --- beetsplug/discogs.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 0e12d0acb..5547e5d9a 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -234,6 +234,10 @@ class DiscogsPlugin(BeetsPlugin): catalogno = None country = result.data.get('country') media = result.data['formats'][0]['name'] + # Explicitely set the `media` for the tracks, since it is expected by + # `autotag.apply_metadata`. + for track in tracks: + track.media = media data_url = result.data['uri'] return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, From 1c63d0bbab8ee9db7e547627a75e9fde4140ac5a Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 7 Oct 2016 18:44:55 +0200 Subject: [PATCH 1342/2280] discogs: add more unit tests Add unit tests covering the discogs standard positions (12.2.9). Clean up a bit the helper methods (unused parameters, documentation). https://www.discogs.com/help/submission-guidelines-release-trk.html#Position --- test/test_discogs.py | 96 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 93 insertions(+), 3 deletions(-) diff --git a/test/test_discogs.py b/test/test_discogs.py index 2cf86bd0d..b5356ccf4 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -24,8 +24,7 @@ from beetsplug.discogs import DiscogsPlugin class DGAlbumInfoTest(_common.TestCase): - def _make_release(self, date_str='2009', tracks=None, track_length=None, - track_artist=False): + def _make_release(self, tracks=None): """Returns a Bag that mimics a discogs_client.Release. The list of elements on the returned Bag is incomplete, including just those required for the tests on this class.""" @@ -75,7 +74,14 @@ class DGAlbumInfoTest(_common.TestCase): return track - def test_set_media_for_tracks(self): + def _make_release_from_positions(self, positions): + """Return a Bag that mimics a discogs_client.Release with a + tracklist where tracks have the specified `positions`.""" + tracks = [self._make_track('TITLE%s' % i, position) for + (i, position) in enumerate(positions, start=1)] + return self._make_release(tracks) + + def test_parse_media_for_tracks(self): tracks = [self._make_track('TITLE ONE', '1', '01:01'), self._make_track('TITLE TWO', '2', '02:02')] release = self._make_release(tracks=tracks) @@ -86,6 +92,90 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[0].media, d.media) self.assertEqual(t[1].media, d.media) + def test_parse_tracklist_without_sides(self): + """Test standard Discogs position 12.2.9#1: "without sides".""" + release = self._make_release_from_positions(['1', '2', '3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_with_sides(self): + """Test standard Discogs position 12.2.9#2: "with sides".""" + release = self._make_release_from_positions(['A1', 'A2', 'B1', 'B2']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) # 2 sides = 1 LP + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_multiple_lp(self): + """Test standard Discogs position 12.2.9#3: "multiple LP".""" + release = self._make_release_from_positions(['A1', 'A2', 'B1', 'C1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 2) # 3 sides = 1 LP + 1 LP + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_multiple_cd(self): + """Test standard Discogs position 12.2.9#4: "multiple CDs".""" + release = self._make_release_from_positions(['1-1', '1-2', '2-1', + '3-1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 3) + self.assertEqual(len(d.tracks), 4) + + def test_parse_tracklist_subtracks_dot(self): + """Test standard Discogs position 12.2.9#5: "sub tracks, dots".""" + release = self._make_release_from_positions(['1', '2.1', '2.2', '3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + release = self._make_release_from_positions(['A1', 'A2.1', 'A2.2', + 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_letter(self): + """Test standard Discogs position 12.2.9#5: "sub tracks, letter".""" + release = self._make_release_from_positions(['A1', 'A2a', 'A2b', 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + release = self._make_release_from_positions(['A1', 'A2.a', 'A2.b', + 'A3']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_extra_material(self): + """Test standard Discogs position 12.2.9#6: "extra material".""" + release = self._make_release_from_positions(['1', '2', 'Video 1']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 2) + self.assertEqual(len(d.tracks), 3) + + def test_parse_tracklist_subtracks_indices(self): + """Test parsing of subtracks that include index tracks.""" + release = self._make_release_from_positions(['', '', '1.1', '1.2']) + # Track 1: Index track with medium title + release.data['tracklist'][0]['title'] = 'MEDIUM TITLE' + # Track 2: Index track with track group title + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 1) + self.assertEqual(d.tracks[0].title, 'TRACK GROUP TITLE') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From c55885c9e88e93079a977afa379fe6d99bab1386 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 7 Oct 2016 18:54:04 +0200 Subject: [PATCH 1343/2280] discogs: take into account two-sided media (#1762) Revise the discogs plugin so two-sided mediums are taking into account and each pair of consecutive *sides* is treated as single *medium*. --- beetsplug/discogs.py | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 5547e5d9a..80171fc4f 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -34,6 +34,7 @@ import time import json import socket import os +from string import ascii_lowercase # Silence spurious INFO log lines generated by urllib3. @@ -287,7 +288,19 @@ class DiscogsPlugin(BeetsPlugin): # Fix up medium and medium_index for each track. Discogs position is # unreliable, but tracks are in order. medium = None - medium_count, index_count = 0, 0 + medium_count, index_count, side_count = 0, 0, 0 + sides_per_medium = 1 + + # If a medium has two sides (ie. vinyl or cassette), each pair of + # consecutive sides should belong to the same medium. + if all([track.medium is not None for track in tracks]): + m = sorted(set([track.medium.lower() for track in tracks])) + # If all track.medium are single consecutive letters, assume it is + # a 2-sided medium. + if ''.join(m) in ascii_lowercase: + sides_per_medium = 2 + side_count = 1 # Force for first item, where medium == None + for track in tracks: # Handle special case where a different medium does not indicate a # new disc, when there is no medium_index and the ordinal of medium @@ -299,11 +312,17 @@ class DiscogsPlugin(BeetsPlugin): ) if not medium_is_index and medium != track.medium: - # Increment medium_count and reset index_count when medium - # changes. - medium = track.medium - medium_count += 1 - index_count = 0 + if side_count < (sides_per_medium - 1): + # Increment side count: side changed, but not medium. + side_count += 1 + medium = track.medium + else: + # Increment medium_count and reset index_count and side + # count when medium changes. + medium = track.medium + medium_count += 1 + index_count = 0 + side_count = 0 index_count += 1 track.medium, track.medium_index = medium_count, index_count From be223d966ef3fd4c73f22e711af3214004c02dc2 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Fri, 7 Oct 2016 19:03:03 +0200 Subject: [PATCH 1344/2280] discogs: coalesce subtracks (#1543) Detect subtracks and merge them into a single track, taking into account the index tracks if present. This includes a revision of the regular expression used for converting a discogs "position" into medium, medium index and subtrack index pieces, following the standard discogs positions (12.2.9). --- beetsplug/discogs.py | 80 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 73 insertions(+), 7 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 80171fc4f..58d8ff33e 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -274,10 +274,11 @@ class DiscogsPlugin(BeetsPlugin): def get_tracks(self, tracklist): """Returns a list of TrackInfo objects for a discogs tracklist. """ + clean_tracklist = self.coalesce_tracks(tracklist) tracks = [] index_tracks = {} index = 0 - for track in tracklist: + for track in clean_tracklist: # Only real tracks have `position`. Otherwise, it's an index track. if track['position']: index += 1 @@ -338,12 +339,73 @@ class DiscogsPlugin(BeetsPlugin): return tracks + def coalesce_tracks(self, raw_tracklist): + """Pre-process a tracklist, merging subtracks into a single track. The + title for the merged track is the one from the previous index track, + if present; otherwise it is a combination of the subtracks titles. + """ + def add_merged_subtracks(tracklist, subtracks): + """Modify `tracklist` in place, merging a list of `subtracks` into + a single track into `tracklist`.""" + # Calculate position based on first subtrack, without subindex. + idx, medium_idx, _ = self.get_track_index(subtracks[0]['position']) + position = '%s%s' % (idx or '', medium_idx or '') + + if len(tracklist) > 1 and not tracklist[-1]['position']: + # Assume the previous index track contains the track title, and + # "convert" it to a real track. The only exception is if the + # index track is the only one on the tracklist, as it probably + # is a medium title. + tracklist[-1]['position'] = position + else: + # Merge the subtracks, pick a title, and append the new track. + track = subtracks[0].copy() + track['title'] = ' / '.join([t['title'] for t in subtracks]) + tracklist.append(track) + + # Pre-process the tracklist, trying to identify subtracks. + subtracks = [] + tracklist = [] + prev_subindex = '' + for track in raw_tracklist: + if track['position']: + _, _, subindex = self.get_track_index(track['position']) + if subindex: + if subindex.rjust(len(raw_tracklist)) > prev_subindex: + # Subtrack still part of the current main track. + subtracks.append(track) + else: + # Subtrack part of a new group (..., 1.3, *2.1*, ...). + add_merged_subtracks(tracklist, subtracks) + subtracks = [track] + prev_subindex = subindex.rjust(len(raw_tracklist)) + else: + # Regular track. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + subtracks = [] + prev_subindex = '' + tracklist.append(track) + else: + # Index track. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + subtracks = [] + prev_subindex = '' + tracklist.append(track) + + # Merge and add the remaining subtracks, if any. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + + return tracklist + def get_track_info(self, track, index): """Returns a TrackInfo object for a discogs track. """ title = track['title'] track_id = None - medium, medium_index = self.get_track_index(track['position']) + medium, medium_index, _ = self.get_track_index(track['position']) artist, artist_id = self.get_artist(track.get('artists', [])) length = self.get_track_length(track['duration']) return TrackInfo(title, track_id, artist, artist_id, length, index, @@ -351,17 +413,21 @@ class DiscogsPlugin(BeetsPlugin): disctitle=None, artist_credit=None) def get_track_index(self, position): - """Returns the medium and medium index for a discogs track position. + """Returns the medium, medium index and subtrack index for a discogs + track position. """ + # TODO: revise comment # medium_index is a number at the end of position. medium is everything # else. E.g. (A)(1), (Side A, Track )(1), (A)(), ()(1), etc. - match = re.match(r'^(.*?)(\d*)$', position.upper()) + match = re.match(r'^(.*?)(\d*?)(\.[\w]+|[A-Z]+)?$', position.upper()) if match: - medium, index = match.groups() + medium, index, subindex = match.groups() + if subindex and subindex.startswith('.'): + subindex = subindex[1:] else: self._log.debug(u'Invalid position: {0}', position) - medium = index = None - return medium or None, index or None + medium = index, subindex = None + return medium or None, index or None, subindex or None def get_track_length(self, duration): """Returns the track length in seconds for a discogs duration. From f30c5da2abd9817bfba3f7c9cc927e9f59a5baa6 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 8 Oct 2016 14:30:59 +0200 Subject: [PATCH 1345/2280] doc-play: Fix an error and clarity: {} is not used any more to determine the location of parameters passed with --args. Fix two sentences for clarity/fluidity. Display the plugin's abilities in the intro. --- docs/plugins/play.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 55733cbaa..3c9f9a0e2 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -2,7 +2,7 @@ Play Plugin =========== The ``play`` plugin allows you to pass the results of a query to a music -player in the form of an m3u playlist. +player in the form of an m3u playlist or raw filepaths. Usage ----- @@ -37,7 +37,7 @@ configuration file. The available options are: - **command**: The command used to open the playlist. Default: ``open`` on OS X, ``xdg-open`` on other Unixes and ``start`` on - Windows. Insert ``{}`` to make use of the ``--args``-feature. + Windows. Insert ``$args`` to make use of the ``--args``-feature. - **relative_to**: If set, emit paths relative to this directory. Default: None. - **use_folders**: When using the ``-a`` option, the m3u will contain the @@ -90,9 +90,9 @@ Because the command that will open the generated ``.m3u`` files can be arbitrarily configured by the user, beets won't try to delete those files. For this reason, using this plugin will leave one or several playlist(s) in the directory selected to create temporary files (Most likely ``/tmp/`` on Unix-like -systems. See `tempfile.tempdir`_.). Leaking those playlists until they are -externally wiped could be an issue for privacy or storage reasons. If this is -the case for you, you might want to use the ``raw`` config option described -above. +systems. See `tempfile.tempdir`_ in python docs.). Leaking those playlists until +they are externally wiped could be an issue for privacy or storage reasons. If +this is the case for you, you might want to use the ``raw`` config option +described above. .. _tempfile.tempdir: https://docs.python.org/2/library/tempfile.html#tempfile.tempdir From 8bd6181c6afcbf575499c665e0e130868528ab78 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 8 Oct 2016 14:47:38 +0200 Subject: [PATCH 1346/2280] doc-play: Fix a header level. --- docs/plugins/play.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 3c9f9a0e2..564e03775 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -84,7 +84,7 @@ indicates that you need to insert extra arguments before specifying the playlist. Note on the Leakage of the Generated Playlists -_______________________________________________ +---------------------------------------------- Because the command that will open the generated ``.m3u`` files can be arbitrarily configured by the user, beets won't try to delete those files. For From 13cf1bff8fb442e18f48593750ca5212c9599c51 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 8 Oct 2016 18:41:16 -0400 Subject: [PATCH 1347/2280] Tiny text simplifications (#2223) --- docs/plugins/play.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 564e03775..1ac51a1f3 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -2,7 +2,7 @@ Play Plugin =========== The ``play`` plugin allows you to pass the results of a query to a music -player in the form of an m3u playlist or raw filepaths. +player in the form of an m3u playlist or paths on the command line. Usage ----- @@ -37,7 +37,7 @@ configuration file. The available options are: - **command**: The command used to open the playlist. Default: ``open`` on OS X, ``xdg-open`` on other Unixes and ``start`` on - Windows. Insert ``$args`` to make use of the ``--args``-feature. + Windows. Insert ``$args`` to use the ``--args`` feature. - **relative_to**: If set, emit paths relative to this directory. Default: None. - **use_folders**: When using the ``-a`` option, the m3u will contain the @@ -90,7 +90,7 @@ Because the command that will open the generated ``.m3u`` files can be arbitrarily configured by the user, beets won't try to delete those files. For this reason, using this plugin will leave one or several playlist(s) in the directory selected to create temporary files (Most likely ``/tmp/`` on Unix-like -systems. See `tempfile.tempdir`_ in python docs.). Leaking those playlists until +systems. See `tempfile.tempdir`_ in the Python docs.). Leaking those playlists until they are externally wiped could be an issue for privacy or storage reasons. If this is the case for you, you might want to use the ``raw`` config option described above. From e7f2a111e48c03916cefb68f49bfa6441ec7a4d9 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Sun, 9 Oct 2016 17:57:36 +0200 Subject: [PATCH 1348/2280] discogs: add test dependencies, fix spelling --- beetsplug/discogs.py | 2 +- setup.py | 1 + tox.ini | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 58d8ff33e..65cebbb2f 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -235,7 +235,7 @@ class DiscogsPlugin(BeetsPlugin): catalogno = None country = result.data.get('country') media = result.data['formats'][0]['name'] - # Explicitely set the `media` for the tracks, since it is expected by + # Explicitly set the `media` for the tracks, since it is expected by # `autotag.apply_metadata`. for track in tracks: track.media = media diff --git a/setup.py b/setup.py index 0610d2226..a19a45b2e 100755 --- a/setup.py +++ b/setup.py @@ -106,6 +106,7 @@ setup( 'pyxdg', 'pathlib', 'python-mpd2', + 'discogs-client' ], # Plugin (optional) dependencies: diff --git a/tox.ini b/tox.ini index c22fb1c6f..cb1db2aa1 100644 --- a/tox.ini +++ b/tox.ini @@ -23,6 +23,7 @@ deps = jellyfish python-mpd2 coverage + discogs_client [_flake8] deps = From 1148acaaf15a1a2f91b88fefd5653a81b4ca7dcd Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 10 Oct 2016 17:42:27 +0200 Subject: [PATCH 1349/2280] discogs: revise position regexp, add tests, tox Revise the regular expression used for extracting information from a discogs position, making the subtrack_index only be matched if one of the other groups is matched as well. Split the definition into several lines in order to try to document it a bit more clearly. Add unit tests for position parsing and non standard positions. Fix the underscore on tox dependency. --- beetsplug/discogs.py | 23 ++++++++++++++++++----- test/test_discogs.py | 28 ++++++++++++++++++++++++++++ tox.ini | 2 +- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 65cebbb2f..216540f34 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -416,17 +416,30 @@ class DiscogsPlugin(BeetsPlugin): """Returns the medium, medium index and subtrack index for a discogs track position. """ - # TODO: revise comment - # medium_index is a number at the end of position. medium is everything - # else. E.g. (A)(1), (Side A, Track )(1), (A)(), ()(1), etc. - match = re.match(r'^(.*?)(\d*?)(\.[\w]+|[A-Z]+)?$', position.upper()) + # Match the standard Discogs positions (12.2.9), which can have several + # forms (1, 1-1, A1, A1.1, A1a, ...). + match = re.match( + r'^(.*?)' # medium: everything before medium_index. + r'(\d*?)' # medium_index: a number at the end of + # `position`, except if followed by a subtrack + # index. + # subtrack_index: can only be matched if medium + # or medium_index have been matched, and can be + r'((?<=\w)\.[\w]+' # - a dot followed by a string (A.1, 2.A) + r'|(?<=\d)[A-Z]+' # - a string that follows a number (1A, B2a) + r')?' + r'$', + position.upper() + ) + if match: medium, index, subindex = match.groups() + if subindex and subindex.startswith('.'): subindex = subindex[1:] else: self._log.debug(u'Invalid position: {0}', position) - medium = index, subindex = None + medium = index = subindex = None return medium or None, index or None, subindex or None def get_track_length(self, duration): diff --git a/test/test_discogs.py b/test/test_discogs.py index b5356ccf4..c0cde0c92 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -92,6 +92,26 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[0].media, d.media) self.assertEqual(t[1].media, d.media) + def test_parse_position(self): + """Test the conversion of discogs `position` to medium, medium_index + and subtrack_index.""" + # List of tuples (discogs_position, (medium, medium_index, subindex) + positions = [('1', (None, '1', None)), + ('A12', ('A', '12', None)), + ('12-34', ('12-', '34', None)), + ('CD1-1', ('CD1-', '1', None)), + ('1.12', (None, '1', '12')), + ('12.a', (None, '12', 'A')), + ('12.34', (None, '12', '34')), + ('1ab', (None, '1', 'AB')), + # Non-standard + ('IV', ('IV', None, None)), + ] + + d = DiscogsPlugin() + for position, expected in positions: + self.assertEqual(d.get_track_index(position), expected) + def test_parse_tracklist_without_sides(self): """Test standard Discogs position 12.2.9#1: "without sides".""" release = self._make_release_from_positions(['1', '2', '3']) @@ -125,6 +145,14 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(d.mediums, 3) self.assertEqual(len(d.tracks), 4) + def test_parse_tracklist_non_standard(self): + """Test non standard Discogs position.""" + release = self._make_release_from_positions(['I', 'II', 'III', 'IV']) + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 4) + def test_parse_tracklist_subtracks_dot(self): """Test standard Discogs position 12.2.9#5: "sub tracks, dots".""" release = self._make_release_from_positions(['1', '2.1', '2.2', '3']) diff --git a/tox.ini b/tox.ini index cb1db2aa1..28fd3636e 100644 --- a/tox.ini +++ b/tox.ini @@ -23,7 +23,7 @@ deps = jellyfish python-mpd2 coverage - discogs_client + discogs-client [_flake8] deps = From fb398c5f2c65c894a4c2887ec378919fd7952a52 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 10 Oct 2016 17:46:41 +0200 Subject: [PATCH 1350/2280] discogs: add medium_total to tracks (#415) --- beetsplug/discogs.py | 3 ++- test/test_discogs.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 216540f34..9c37578b6 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -236,9 +236,10 @@ class DiscogsPlugin(BeetsPlugin): country = result.data.get('country') media = result.data['formats'][0]['name'] # Explicitly set the `media` for the tracks, since it is expected by - # `autotag.apply_metadata`. + # `autotag.apply_metadata`, and set `medium_total`. for track in tracks: track.media = media + track.medium_total = mediums data_url = result.data['uri'] return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, diff --git a/test/test_discogs.py b/test/test_discogs.py index c0cde0c92..be81fc9af 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -92,6 +92,38 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[0].media, d.media) self.assertEqual(t[1].media, d.media) + def test_parse_track_indices(self): + release = self._make_release_from_positions(['1', '2']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[0].index, 1) + self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[1].index, 2) + self.assertEqual(t[1].medium_total, 1) + + def test_parse_track_indices_several_media(self): + release = self._make_release_from_positions(['1-1', '1-2', '2-1', + '3-1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 3) + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[0].index, 1) + self.assertEqual(t[0].medium_total, 3) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[1].index, 2) + self.assertEqual(t[1].medium_total, 3) + self.assertEqual(t[2].medium_index, 1) + self.assertEqual(t[2].index, 3) + self.assertEqual(t[2].medium_total, 3) + self.assertEqual(t[3].medium_index, 1) + self.assertEqual(t[3].index, 4) + self.assertEqual(t[3].medium_total, 3) + def test_parse_position(self): """Test the conversion of discogs `position` to medium, medium_index and subtrack_index.""" From f4907ca5d03e1e998b172d2c6e64f8bc3d467e86 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 10 Oct 2016 19:59:42 +0200 Subject: [PATCH 1351/2280] discogs: handle nested subtracks, add try block Modify coalesce_tracks() in order to handle the case where subtracks are defined inside an index track (as `sub_tracks` attribute), reorganizing the if logic to avoid duplicated code. Add a try..catch block enclosing the call to clean_tracklist, as a measure for avoiding side effects (and reverting to just parsing the raw_list if there are any problems). --- beetsplug/discogs.py | 39 +++++++++++++++++++++++++-------------- test/test_discogs.py | 15 +++++++++++++++ 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 9c37578b6..1e4003c97 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -34,6 +34,7 @@ import time import json import socket import os +import traceback from string import ascii_lowercase @@ -275,7 +276,15 @@ class DiscogsPlugin(BeetsPlugin): def get_tracks(self, tracklist): """Returns a list of TrackInfo objects for a discogs tracklist. """ - clean_tracklist = self.coalesce_tracks(tracklist) + try: + clean_tracklist = self.coalesce_tracks(tracklist) + except Exception as exc: + # FIXME: this is an extra precaution for making sure there are no + # side effects after #2222. It should be removed after further + # testing. + self._log.debug(u'{}', traceback.format_exc()) + self._log.error(u'uncaught exception in coalesce_tracks: {}', exc) + clean_tracklist = tracklist tracks = [] index_tracks = {} index = 0 @@ -369,6 +378,7 @@ class DiscogsPlugin(BeetsPlugin): tracklist = [] prev_subindex = '' for track in raw_tracklist: + # Regular subtrack (track with subindex). if track['position']: _, _, subindex = self.get_track_index(track['position']) if subindex: @@ -380,20 +390,21 @@ class DiscogsPlugin(BeetsPlugin): add_merged_subtracks(tracklist, subtracks) subtracks = [track] prev_subindex = subindex.rjust(len(raw_tracklist)) - else: - # Regular track. - if subtracks: - add_merged_subtracks(tracklist, subtracks) - subtracks = [] - prev_subindex = '' - tracklist.append(track) - else: - # Index track. - if subtracks: - add_merged_subtracks(tracklist, subtracks) - subtracks = [] - prev_subindex = '' + continue + + # Index track with nested sub_tracks. + if not track['position'] and 'sub_tracks' in track: + # Append the index track, assuming it contains the track title. tracklist.append(track) + add_merged_subtracks(tracklist, track['sub_tracks']) + continue + + # Regular track or index track without nested sub_tracks. + if subtracks: + add_merged_subtracks(tracklist, subtracks) + subtracks = [] + prev_subindex = '' + tracklist.append(track) # Merge and add the remaining subtracks, if any. if subtracks: diff --git a/test/test_discogs.py b/test/test_discogs.py index be81fc9af..0dff77072 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -236,6 +236,21 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(len(d.tracks), 1) self.assertEqual(d.tracks[0].title, 'TRACK GROUP TITLE') + def test_parse_tracklist_subtracks_nested(self): + """Test parsing of subtracks defined inside a index track.""" + release = self._make_release_from_positions(['1', '', '3']) + # Track 2: Index track with track group title, and sub_tracks + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + release.data['tracklist'][1]['sub_tracks'] = [ + self._make_track('TITLE ONE', '2.1', '01:01'), + self._make_track('TITLE TWO', '2.2', '02:02') + ] + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 3) + self.assertEqual(d.tracks[1].title, 'TRACK GROUP TITLE') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From c5ae9c5bee93a9a73f55f8997f941ad712b557fe Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 10 Oct 2016 20:27:42 +0200 Subject: [PATCH 1352/2280] discogs: update changelog --- docs/changelog.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index bbc6cfa5c..c24fc6606 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -71,7 +71,10 @@ And there are a few bug fixes too: * :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the colon character. :bug:`2206` * Fix a crash when a query contains a date field that is not set for all - the items. :bug:`1938` + the items. :bug:`1938` +* :doc:`/plugins/discogs`: Subtracks are now detected and combined into a + single track, two-sided mediums are treated as single discs, and tracks + have ``media`` and ``medium_total`` set correctly. :bug:`2222` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 1f4bef9e6195ee0e58738888988a5f8fe2bdf2f1 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 10 Oct 2016 20:30:21 +0200 Subject: [PATCH 1353/2280] discogs: docstring style fix --- beetsplug/discogs.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 1e4003c97..90aefba10 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -426,8 +426,7 @@ class DiscogsPlugin(BeetsPlugin): def get_track_index(self, position): """Returns the medium, medium index and subtrack index for a discogs - track position. - """ + track position.""" # Match the standard Discogs positions (12.2.9), which can have several # forms (1, 1-1, A1, A1.1, A1a, ...). match = re.match( From 44f33cabc7e2c5ea6fd79fac3b73ac54fa11d568 Mon Sep 17 00:00:00 2001 From: vapniks Date: Mon, 10 Oct 2016 19:45:03 +0100 Subject: [PATCH 1354/2280] Update _beet update documentation --- extra/_beet | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/extra/_beet b/extra/_beet index 1c0d23841..520c212fc 100644 --- a/extra/_beet +++ b/extra/_beet @@ -6,8 +6,11 @@ # are stored. # It will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins), # but a cache file (_beet_cached) will be created after the first completion which will make subsequent calls much -# faster. If you enable new plugins or fields you should update the cache file by deleting it and then performing -# another completion in a new shell. +# faster. +# If you enable new plugins or fields you should update the cache file by deleting it, entering the following commands: +# unfunction _beet +# autoload -z _beet +# and then performing another completion in a new shell. # If cache file exists, use that local completionsdir="$HOME/.oh-my-zsh/custom/completions" From fc9f0615745727f1958d4f4043cffee57d876150 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 17 Oct 2016 19:48:06 +0200 Subject: [PATCH 1355/2280] discogs: add tests for medium, medium_total Add three tests for the setting of tracks' medium and medium_total on the discogs plugin. test_parse_medium_numbers_single_medium is meant to fail due to #587. --- test/test_discogs.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/test_discogs.py b/test/test_discogs.py index 0dff77072..0f89ff923 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -92,6 +92,44 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[0].media, d.media) self.assertEqual(t[1].media, d.media) + def test_parse_medium_numbers_single_medium(self): + release = self._make_release_from_positions(['1', '2']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 1) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[1].medium, 1) + self.assertEqual(t[0].medium_total, 1) + + def test_parse_medium_numbers_two_mediums(self): + release = self._make_release_from_positions(['1-1', '2-1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 2) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[1].medium, 2) + self.assertEqual(t[1].medium_total, 2) + + def test_parse_medium_numbers_two_mediums_two_sided(self): + release = self._make_release_from_positions(['A1', 'B1', 'C1']) + d = DiscogsPlugin().get_album_info(release) + t = d.tracks + + self.assertEqual(d.mediums, 2) + self.assertEqual(t[0].medium, 1) + self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[0].medium_index, 1) + self.assertEqual(t[1].medium, 1) + self.assertEqual(t[1].medium_total, 2) + self.assertEqual(t[1].medium_index, 2) + self.assertEqual(t[2].medium, 2) + self.assertEqual(t[2].medium_total, 2) + self.assertEqual(t[2].medium_index, 1) + def test_parse_track_indices(self): release = self._make_release_from_positions(['1', '2']) d = DiscogsPlugin().get_album_info(release) From 373cf19f8bbe5b445edf0829c5a6ed23b0cf7ed2 Mon Sep 17 00:00:00 2001 From: kooimens Date: Tue, 3 Nov 2015 19:57:05 +0100 Subject: [PATCH 1356/2280] Fix discogs disc field is set to zero Fixes #587. The disc field is only zero when there is only one medium, so I think this will do the trick. I wasn't able to reproduce the real problem within the code. This is just a small workaround. --- beetsplug/discogs.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 90aefba10..97834c500 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -335,6 +335,7 @@ class DiscogsPlugin(BeetsPlugin): index_count = 0 side_count = 0 index_count += 1 + medium_count = 1 if medium_count == 0 else medium_count track.medium, track.medium_index = medium_count, index_count # Get `disctitle` from Discogs index tracks. Assume that an index track From 2604bc8e7363b4bb8284435712ef2422b3eec527 Mon Sep 17 00:00:00 2001 From: Diego Moreda Date: Mon, 17 Oct 2016 20:02:17 +0200 Subject: [PATCH 1357/2280] discogs: update changelog for medium --- docs/changelog.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index c24fc6606..8213b9741 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -74,7 +74,8 @@ And there are a few bug fixes too: the items. :bug:`1938` * :doc:`/plugins/discogs`: Subtracks are now detected and combined into a single track, two-sided mediums are treated as single discs, and tracks - have ``media`` and ``medium_total`` set correctly. :bug:`2222` + have ``media``, ``medium_total`` and ``medium`` set correctly. :bug:`2222` + :bug:`2228`. The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From acd2b0ef77ccde44d518a998a78a6dfc3d52b43a Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 00:04:07 -0400 Subject: [PATCH 1358/2280] First attempt for selective field updates --- beets/dbcore/db.py | 6 ++++-- beets/library.py | 19 ++++++++++--------- beets/ui/commands.py | 23 +++++++++++++++-------- 3 files changed, 29 insertions(+), 19 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index daa636d24..37ec1a347 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -342,7 +342,7 @@ class Model(object): # Database interaction (CRUD methods). - def store(self): + def store(self, fields_to_store=None): """Save the object's metadata into the library database. """ self._check_db() @@ -350,7 +350,9 @@ class Model(object): # Build assignments for query. assignments = [] subvars = [] - for key in self._fields: + if fields_to_store is None: + fields_to_store = self._fields + for key in fields_to_store: if key != 'id' and key in self._dirty: self._dirty.remove(key) assignments.append(key + '=?') diff --git a/beets/library.py b/beets/library.py index 59784e808..ef079b6b6 100644 --- a/beets/library.py +++ b/beets/library.py @@ -323,8 +323,8 @@ class LibModel(dbcore.Model): funcs.update(plugins.template_funcs()) return funcs - def store(self): - super(LibModel, self).store() + def store(self, fields_to_store=None): + super(LibModel, self).store(fields_to_store) plugins.send('database_change', lib=self._db, model=self) def remove(self): @@ -729,7 +729,8 @@ class Item(LibModel): self._db._memotable = {} - def move(self, copy=False, link=False, basedir=None, with_album=True): + def move(self, copy=False, link=False, basedir=None, with_album=True, + fields_to_store=None): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path @@ -759,7 +760,7 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path self.move_file(dest, copy, link) - self.store() + self.store(fields_to_store) # If this item is in an album, move its art. if with_album: @@ -1000,7 +1001,7 @@ class Album(LibModel): util.prune_dirs(os.path.dirname(old_art), self._db.directory) - def move(self, copy=False, link=False, basedir=None): + def move(self, copy=False, link=False, basedir=None, fields_to_store=None): """Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base directory for the destination. The album is stored to the @@ -1010,7 +1011,7 @@ class Album(LibModel): # Ensure new metadata is available to items for destination # computation. - self.store() + self.store(fields_to_store) # Move items. items = list(self.items()) @@ -1019,7 +1020,7 @@ class Album(LibModel): # Move art. self.move_art(copy, link) - self.store() + self.store(fields_to_store) def item_dir(self): """Returns the directory containing the album's first item, @@ -1108,7 +1109,7 @@ class Album(LibModel): plugins.send('art_set', album=self) - def store(self): + def store(self, fields_to_store=None): """Update the database with the album information. The album's tracks are also updated. """ @@ -1119,7 +1120,7 @@ class Album(LibModel): track_updates[key] = self[key] with self._db.transaction(): - super(Album, self).store() + super(Album, self).store(fields_to_store) if track_updates: for item in self.items(): for key, value in track_updates.items(): diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 2f323b604..88b5de728 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1081,11 +1081,14 @@ default_commands.append(list_cmd) # update: Update library contents according to on-disk tags. -def update_items(lib, query, album, move, pretend): +def update_items(lib, query, album, move, pretend, fields): """For all the items matched by the query, update the library to reflect the item's embedded tags. """ with lib.transaction(): + if fields is None: + fields = library.Item._media_fields + items, _ = _do_query(lib, query, album) # Walk through the items and pick up their changes. @@ -1125,23 +1128,23 @@ def update_items(lib, query, album, move, pretend): # Check for and display changes. changed = ui.show_model_changes(item, - fields=library.Item._media_fields) + fields=fields) # Save changes. if not pretend: if changed: # Move the item if it's in the library. if move and lib.directory in ancestry(item.path): - item.move() + item.move(fields_to_store=fields) - item.store() + item.store(fields_to_store=fields) affected_albums.add(item.album_id) else: # The file's mtime was different, but there were no # changes to the metadata. Store the new mtime, # which is set in the call to read(), so we don't # check this again in the future. - item.store() + item.store(fields_to_store=fields) # Skip album changes while pretending. if pretend: @@ -1160,17 +1163,17 @@ def update_items(lib, query, album, move, pretend): # Update album structure to reflect an item in it. for key in library.Album.item_keys: album[key] = first_item[key] - album.store() + album.store(fields_to_store=fields) # Move album art (and any inconsistent items). if move and lib.directory in ancestry(first_item.path): log.debug(u'moving album {0}', album_id) - album.move() + album.move(fields_to_store=fields) def update_func(lib, opts, args): update_items(lib, decargs(args), opts.album, ui.should_move(opts.move), - opts.pretend) + opts.pretend, opts.fields) update_cmd = ui.Subcommand( @@ -1190,6 +1193,10 @@ update_cmd.parser.add_option( u'-p', u'--pretend', action='store_true', help=u"show all changes but do nothing" ) +update_cmd.parser.add_option( + u'-F', u'--field', default=None, action='append', dest='fields', + help=u'list of fields to update' +) update_cmd.func = update_func default_commands.append(update_cmd) From 679918f191ae6b3255c918f212a4a0920f0b0076 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 00:28:28 -0400 Subject: [PATCH 1359/2280] Fix some test failures --- test/test_ui.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 31f3f37da..571f39cf8 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -499,12 +499,13 @@ class UpdateTest(_common.TestCase): self.album.store() os.remove(artfile) - def _update(self, query=(), album=False, move=False, reset_mtime=True): + def _update(self, query=(), album=False, move=False, reset_mtime=True, + fields=None): self.io.addinput('y') if reset_mtime: self.i.mtime = 0 self.i.store() - commands.update_items(self.lib, query, album, move, False) + commands.update_items(self.lib, query, album, move, False, fields=fields) def test_delete_removes_item(self): self.assertTrue(list(self.lib.items())) From f17601e4cd3c748e609a2bd76f310e31c4245395 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 20:25:38 -0400 Subject: [PATCH 1360/2280] Fix update test failures --- beets/library.py | 2 +- beets/ui/commands.py | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/beets/library.py b/beets/library.py index ef079b6b6..edd79d243 100644 --- a/beets/library.py +++ b/beets/library.py @@ -767,7 +767,7 @@ class Item(LibModel): album = self.get_album() if album: album.move_art(copy) - album.store() + album.store(fields_to_store) # Prune vacated directory. if not copy: diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 88b5de728..823e99cfa 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1086,9 +1086,6 @@ def update_items(lib, query, album, move, pretend, fields): reflect the item's embedded tags. """ with lib.transaction(): - if fields is None: - fields = library.Item._media_fields - items, _ = _do_query(lib, query, album) # Walk through the items and pick up their changes. @@ -1127,8 +1124,9 @@ def update_items(lib, query, album, move, pretend, fields): item._dirty.discard(u'albumartist') # Check for and display changes. - changed = ui.show_model_changes(item, - fields=fields) + changed = ui.show_model_changes( + item, + fields=fields or library.Item._media_fields) # Save changes. if not pretend: From 406f3ce8437ffda09ccf25774f9e3f7ff9aa8707 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 21:07:12 -0400 Subject: [PATCH 1361/2280] Add tests and make sure they pass --- beets/library.py | 3 ++- beets/ui/commands.py | 5 +++++ test/test_ui.py | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index edd79d243..36e5a5d22 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1016,7 +1016,8 @@ class Album(LibModel): # Move items. items = list(self.items()) for item in items: - item.move(copy, link, basedir=basedir, with_album=False) + item.move(copy, link, basedir=basedir, with_album=False, + fields_to_store=fields_to_store) # Move art. self.move_art(copy, link) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 823e99cfa..d44bbadc6 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1086,6 +1086,11 @@ def update_items(lib, query, album, move, pretend, fields): reflect the item's embedded tags. """ with lib.transaction(): + if move and fields is not None and 'path' not in fields: + # Special case: if an item needs to be moved, the path field has to + # updated; otherwise the new path will not be reflected in the + # database + fields.append('path') items, _ = _do_query(lib, query, album) # Walk through the items and pick up their changes. diff --git a/test/test_ui.py b/test/test_ui.py index 571f39cf8..380b29173 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -550,6 +550,26 @@ class UpdateTest(_common.TestCase): item = self.lib.items().get() self.assertTrue(b'differentTitle' not in item.path) + def test_selective_modified_metadata_moved(self): + mf = MediaFile(self.i.path) + mf.title = u'differentTitle' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['title']) + item = self.lib.items().get() + self.assertTrue(b'differentTitle' in item.path) + self.assertNotEqual(item.genre, u'differentGenre') + + def test_selective_modified_metadata_not_moved(self): + mf = MediaFile(self.i.path) + mf.title = u'differentTitle' + mf.genre = u'differentGenre' + mf.save() + self._update(move=False, fields=['title']) + item = self.lib.items().get() + self.assertTrue(b'differentTitle' not in item.path) + self.assertNotEqual(item.genre, u'differentGenre') + def test_modified_album_metadata_moved(self): mf = MediaFile(self.i.path) mf.album = u'differentAlbum' From f42f558db22b81e80ba416327d24f346df45b4b4 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 21:21:50 -0400 Subject: [PATCH 1362/2280] Fix long line for flake8 --- test/test_ui.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index 380b29173..2a07db24d 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -505,7 +505,8 @@ class UpdateTest(_common.TestCase): if reset_mtime: self.i.mtime = 0 self.i.store() - commands.update_items(self.lib, query, album, move, False, fields=fields) + commands.update_items(self.lib, query, album, move, False, + fields=fields) def test_delete_removes_item(self): self.assertTrue(list(self.lib.items())) From 8d07bfe693ffc8e9bc6400c87d44b3a86d648287 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Thu, 20 Oct 2016 23:33:20 -0400 Subject: [PATCH 1363/2280] Documentation for new flag --- docs/reference/cli.rst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 93b9b6253..b2683cd86 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -272,7 +272,7 @@ update `````` :: - beet update [-aM] QUERY + beet update [-F] FIELD [-aM] QUERY Update the library (and, optionally, move files) to reflect out-of-band metadata changes and file deletions. @@ -288,6 +288,11 @@ To perform a "dry run" of an update, just use the ``-p`` (for "pretend") flag. This will show you all the proposed changes but won't actually change anything on disk. +By default, all the changed metadata will be populated back to the database. +If you only want certain fields to be written, specify them with the ```-F``` +flags (which can be used multiple times). For the list of supported fields, +please see ```beet fields```. + When an updated track is part of an album, the album-level fields of *all* tracks from the album are also updated. (Specifically, the command copies album-level data from the first track on the album and applies it to the @@ -318,7 +323,7 @@ You can think of this command as the opposite of :ref:`update-cmd`. The ``-p`` option previews metadata changes without actually applying them. -The ``-f`` option forces a write to the file, even if the file tags match the database. This is useful for making sure that enabled plugins that run on write (e.g., the Scrub and Zero plugins) are run on the file. +The ``-f`` option forces a write to the file, even if the file tags match the database. This is useful for making sure that enabled plugins that run on write (e.g., the Scrub and Zero plugins) are run on the file. From f91362a069ab1ad3292b05f9fd29827578822205 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Fri, 21 Oct 2016 16:15:37 -0400 Subject: [PATCH 1364/2280] Cosmetic refactors based on feedback --- beets/dbcore/db.py | 10 ++++++---- beets/library.py | 24 +++++++++++++----------- beets/ui/commands.py | 14 ++++++++------ 3 files changed, 27 insertions(+), 21 deletions(-) mode change 100644 => 100755 beets/dbcore/db.py mode change 100644 => 100755 beets/library.py mode change 100644 => 100755 beets/ui/commands.py diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py old mode 100644 new mode 100755 index 37ec1a347..d01e8a5c3 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -342,17 +342,19 @@ class Model(object): # Database interaction (CRUD methods). - def store(self, fields_to_store=None): + def store(self, fields=None): """Save the object's metadata into the library database. + :param fields: the fields to be stored. If not specified, all fields + will be. """ + if fields is None: + fields = self._fields self._check_db() # Build assignments for query. assignments = [] subvars = [] - if fields_to_store is None: - fields_to_store = self._fields - for key in fields_to_store: + for key in fields: if key != 'id' and key in self._dirty: self._dirty.remove(key) assignments.append(key + '=?') diff --git a/beets/library.py b/beets/library.py old mode 100644 new mode 100755 index 36e5a5d22..e545bd314 --- a/beets/library.py +++ b/beets/library.py @@ -323,8 +323,8 @@ class LibModel(dbcore.Model): funcs.update(plugins.template_funcs()) return funcs - def store(self, fields_to_store=None): - super(LibModel, self).store(fields_to_store) + def store(self, fields=None): + super(LibModel, self).store(fields) plugins.send('database_change', lib=self._db, model=self) def remove(self): @@ -730,7 +730,7 @@ class Item(LibModel): self._db._memotable = {} def move(self, copy=False, link=False, basedir=None, with_album=True, - fields_to_store=None): + fields=None): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path @@ -760,14 +760,14 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path self.move_file(dest, copy, link) - self.store(fields_to_store) + self.store(fields) # If this item is in an album, move its art. if with_album: album = self.get_album() if album: album.move_art(copy) - album.store(fields_to_store) + album.store(fields) # Prune vacated directory. if not copy: @@ -1001,7 +1001,7 @@ class Album(LibModel): util.prune_dirs(os.path.dirname(old_art), self._db.directory) - def move(self, copy=False, link=False, basedir=None, fields_to_store=None): + def move(self, copy=False, link=False, basedir=None, fields=None): """Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base directory for the destination. The album is stored to the @@ -1011,17 +1011,17 @@ class Album(LibModel): # Ensure new metadata is available to items for destination # computation. - self.store(fields_to_store) + self.store(fields) # Move items. items = list(self.items()) for item in items: item.move(copy, link, basedir=basedir, with_album=False, - fields_to_store=fields_to_store) + fields=fields) # Move art. self.move_art(copy, link) - self.store(fields_to_store) + self.store(fields) def item_dir(self): """Returns the directory containing the album's first item, @@ -1110,9 +1110,11 @@ class Album(LibModel): plugins.send('art_set', album=self) - def store(self, fields_to_store=None): + def store(self, fields=None): """Update the database with the album information. The album's tracks are also updated. + :param fields: The fields to be stored. If not specified, all fields + will be. """ # Get modified track fields. track_updates = {} @@ -1121,7 +1123,7 @@ class Album(LibModel): track_updates[key] = self[key] with self._db.transaction(): - super(Album, self).store(fields_to_store) + super(Album, self).store(fields) if track_updates: for item in self.items(): for key, value in track_updates.items(): diff --git a/beets/ui/commands.py b/beets/ui/commands.py old mode 100644 new mode 100755 index d44bbadc6..0c1eb3ae9 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1084,12 +1084,14 @@ default_commands.append(list_cmd) def update_items(lib, query, album, move, pretend, fields): """For all the items matched by the query, update the library to reflect the item's embedded tags. + :param fields: The fields to be stored. If not specified, all fields will + be. """ with lib.transaction(): if move and fields is not None and 'path' not in fields: # Special case: if an item needs to be moved, the path field has to # updated; otherwise the new path will not be reflected in the - # database + # database. fields.append('path') items, _ = _do_query(lib, query, album) @@ -1138,16 +1140,16 @@ def update_items(lib, query, album, move, pretend, fields): if changed: # Move the item if it's in the library. if move and lib.directory in ancestry(item.path): - item.move(fields_to_store=fields) + item.move(fields=fields) - item.store(fields_to_store=fields) + item.store(fields=fields) affected_albums.add(item.album_id) else: # The file's mtime was different, but there were no # changes to the metadata. Store the new mtime, # which is set in the call to read(), so we don't # check this again in the future. - item.store(fields_to_store=fields) + item.store(fields=fields) # Skip album changes while pretending. if pretend: @@ -1166,12 +1168,12 @@ def update_items(lib, query, album, move, pretend, fields): # Update album structure to reflect an item in it. for key in library.Album.item_keys: album[key] = first_item[key] - album.store(fields_to_store=fields) + album.store(fields=fields) # Move album art (and any inconsistent items). if move and lib.directory in ancestry(first_item.path): log.debug(u'moving album {0}', album_id) - album.move(fields_to_store=fields) + album.move(fields=fields) def update_func(lib, opts, args): From e94676e322672f6d309ba7d0b0a43e52be15d42a Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 22 Oct 2016 10:37:53 +0200 Subject: [PATCH 1365/2280] Refactor match_by_id: * Drop reduce * Readability --- beets/autotag/match.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index ac213b5f9..bfb2e9d56 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -29,7 +29,6 @@ from beets import config from beets.util import plurality from beets.autotag import hooks from beets.util.enumeration import OrderedEnum -from functools import reduce # Artist signals that indicate "various artists". These are used at the # album level to determine whether a given release is likely a VA @@ -261,19 +260,21 @@ def match_by_id(items): AlbumInfo object for the corresponding album. Otherwise, returns None. """ - # Is there a consensus on the MB album ID? - albumids = [item.mb_albumid for item in items if item.mb_albumid] - if not albumids: - log.debug(u'No album IDs found.') + albumids = (item.mb_albumid for item in items if item.mb_albumid) + try: + # Did any of the items have an MB album ID? + first = albumids.next() + except StopIteration: + log.debug(u'No album ID found.') return None - - # If all album IDs are equal, look up the album. - if bool(reduce(lambda x, y: x if x == y else (), albumids)): - albumid = albumids[0] - log.debug(u'Searching for discovered album ID: {0}', albumid) - return hooks.album_for_mbid(albumid) else: - log.debug(u'No album ID consensus.') + # Is there a consensus on the MB album ID? + if all(first == other for other in albumids): + # If all album IDs are equal, look up the album. + log.debug(u'Searching for discovered album ID: {0}', first) + return hooks.album_for_mbid(first) + else: + log.debug(u'No album ID consensus.') def _recommendation(results): From cee6c5fe520d9a4910c492e1abf3236cf35a8729 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 22 Oct 2016 12:37:38 +0200 Subject: [PATCH 1366/2280] Rewrite match_by_id to fix next vs __next__ --- beets/autotag/match.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index bfb2e9d56..5585c7f5c 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -261,20 +261,22 @@ def match_by_id(items): None. """ albumids = (item.mb_albumid for item in items if item.mb_albumid) + + # Did any of the items have an MB album ID? try: - # Did any of the items have an MB album ID? - first = albumids.next() + first = next(albumids) except StopIteration: log.debug(u'No album ID found.') return None - else: - # Is there a consensus on the MB album ID? - if all(first == other for other in albumids): - # If all album IDs are equal, look up the album. - log.debug(u'Searching for discovered album ID: {0}', first) - return hooks.album_for_mbid(first) - else: + + # Is there a consensus on the MB album ID? + for other in albumids: + if other != first: log.debug(u'No album ID consensus.') + return None + # If all album IDs are equal, look up the album. + log.debug(u'Searching for discovered album ID: {0}', first) + return hooks.album_for_mbid(first) def _recommendation(results): From 04560bd88ed139aa21447186bdea0a1630a5e919 Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Sun, 23 Oct 2016 15:52:27 -0400 Subject: [PATCH 1367/2280] Stop passing in fields to be stored for Item.move and Album.move --- beets/library.py | 31 +++++++++++++++++++------------ beets/ui/commands.py | 11 +++++++++-- test/test_ui.py | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/beets/library.py b/beets/library.py index e545bd314..6ba81a0be 100755 --- a/beets/library.py +++ b/beets/library.py @@ -730,7 +730,7 @@ class Item(LibModel): self._db._memotable = {} def move(self, copy=False, link=False, basedir=None, with_album=True, - fields=None): + store=True): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path @@ -746,10 +746,11 @@ class Item(LibModel): move its art. (This can be disabled by passing with_album=False.) - The item is stored to the database if it is in the database, so - any dirty fields prior to the move() call will be written as a + By default, the item is stored to the database if it is in the database, + so any dirty fields prior to the move() call will be written as a side effect. You probably want to call save() to commit the DB - transaction. + transaction. If `store` is true however, the item won't be stored, and + you'll have to manually store it after invoking this method. """ self._check_db() dest = self.destination(basedir=basedir) @@ -760,14 +761,16 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path self.move_file(dest, copy, link) - self.store(fields) + if store: + self.store() # If this item is in an album, move its art. if with_album: album = self.get_album() if album: album.move_art(copy) - album.store(fields) + if store: + album.store() # Prune vacated directory. if not copy: @@ -1001,27 +1004,31 @@ class Album(LibModel): util.prune_dirs(os.path.dirname(old_art), self._db.directory) - def move(self, copy=False, link=False, basedir=None, fields=None): + def move(self, copy=False, link=False, basedir=None, store=True): """Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base - directory for the destination. The album is stored to the - database, persisting any modifications to its metadata. + directory for the destination. By default, the album is stored to the + database, persisting any modifications to its metadata. If `store` is + true however, the album is not stored automatically, and you'll have + to manually store it after invoking this method. """ basedir = basedir or self._db.directory # Ensure new metadata is available to items for destination # computation. - self.store(fields) + if store: + self.store() # Move items. items = list(self.items()) for item in items: item.move(copy, link, basedir=basedir, with_album=False, - fields=fields) + store=store) # Move art. self.move_art(copy, link) - self.store(fields) + if store: + self.store() def item_dir(self): """Returns the directory containing the album's first item, diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0c1eb3ae9..c02f6accf 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1140,7 +1140,7 @@ def update_items(lib, query, album, move, pretend, fields): if changed: # Move the item if it's in the library. if move and lib.directory in ancestry(item.path): - item.move(fields=fields) + item.move(store=False) item.store(fields=fields) affected_albums.add(item.album_id) @@ -1173,7 +1173,14 @@ def update_items(lib, query, album, move, pretend, fields): # Move album art (and any inconsistent items). if move and lib.directory in ancestry(first_item.path): log.debug(u'moving album {0}', album_id) - album.move(fields=fields) + + # Manually moving and storing the album. + items = list(album.items()) + for item in items: + item.move(store=False) + item.store(fields=fields) + album.move(store=False) + album.store(fields=fields) def update_func(lib, opts, args): diff --git a/test/test_ui.py b/test/test_ui.py index 2a07db24d..f1c4c0fc1 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -588,6 +588,26 @@ class UpdateTest(_common.TestCase): album = self.lib.albums()[0] self.assertNotEqual(artpath, album.artpath) + def test_selective_modified_album_metadata_moved(self): + mf = MediaFile(self.i.path) + mf.album = u'differentAlbum' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['album']) + item = self.lib.items().get() + self.assertTrue(b'differentAlbum' in item.path) + self.assertNotEqual(item.genre, u'differentGenre') + + def test_selective_modified_album_metadata_not_moved(self): + mf = MediaFile(self.i.path) + mf.album = u'differentAlbum' + mf.genre = u'differentGenre' + mf.save() + self._update(move=True, fields=['genre']) + item = self.lib.items().get() + self.assertTrue(b'differentAlbum' not in item.path) + self.assertEqual(item.genre, u'differentGenre') + def test_mtime_match_skips_update(self): mf = MediaFile(self.i.path) mf.title = u'differentTitle' From 05377ee7c4ff13153598989495b0cfc976e3444c Mon Sep 17 00:00:00 2001 From: Dang Mai Date: Sun, 23 Oct 2016 16:00:36 -0400 Subject: [PATCH 1368/2280] Fixing line too long --- beets/library.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/library.py b/beets/library.py index 6ba81a0be..e80c4da72 100755 --- a/beets/library.py +++ b/beets/library.py @@ -746,9 +746,9 @@ class Item(LibModel): move its art. (This can be disabled by passing with_album=False.) - By default, the item is stored to the database if it is in the database, - so any dirty fields prior to the move() call will be written as a - side effect. You probably want to call save() to commit the DB + By default, the item is stored to the database if it is in the + database, so any dirty fields prior to the move() call will be written + as a side effect. You probably want to call save() to commit the DB transaction. If `store` is true however, the item won't be stored, and you'll have to manually store it after invoking this method. """ From c426b76cce3b39f2cac1b9a13e7977fcf31f0461 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 23 Oct 2016 16:38:17 -0400 Subject: [PATCH 1369/2280] Changelog/thanks for #2231 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8213b9741..08be98a5c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -47,6 +47,8 @@ The are a couple of small new features: * ``beet --version`` now includes the python version used to run beets. * :doc:`/reference/pathformat` can now include unescaped commas (``,``) when they are not part of a function call. :bug:`2166` :bug:`2213` +* The :ref:`update-cmd` command takes a new ``-F`` flag to specify the fields + to update. Thanks to :user:`dangmai`. :bug:`2229` :bug:`2231` And there are a few bug fixes too: From ee22165876ce05d2d109e842ff6249da70356bb8 Mon Sep 17 00:00:00 2001 From: Alex Claman Date: Wed, 26 Oct 2016 11:52:45 -0500 Subject: [PATCH 1370/2280] Add workaround for SIP --- docs/guides/main.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 4586da8da..c0f85f1af 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -69,6 +69,14 @@ new versions. .. _@b33ts: http://twitter.com/b33ts +Installing on Mac OS X 10.11 and higher +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Starting with Mac OS X 10.11 (El Capitan), Apple has enabled `System Integrity Protection`_ (SIP), and because of SIP, some installation processes may fail, even with ``sudo``, because they intrude on protected areas of the system (if you've installed python via `Homebrew`_ this probably won't happen since the Python libraries are installed to an unrestricted folder). If this does happen, try installing beets only for the current user by running ``pip install --user beets``. It might also be a good idea to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. + +.. _System Integrity Protection: https://support.apple.com/en-us/HT204899 +.. _Homebrew: http://brew.sh + Installing on Windows ^^^^^^^^^^^^^^^^^^^^^ From c4a5dc243686d62862c19c2f7cc2fb3ef13998e7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 26 Oct 2016 13:36:51 -0400 Subject: [PATCH 1371/2280] "macOS" --- docs/guides/main.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index c0f85f1af..ee9e59df1 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -14,7 +14,7 @@ dropped, and Python 3.x is not yet supported.) .. _Python 2.7: http://www.python.org/download/ -* **Mac OS X** v10.7 (Lion) and later include Python 2.7 out of the box. +* **macOS** v10.7 (Lion) and later include Python 2.7 out of the box. * On **Debian or Ubuntu**, depending on the version, beets is available as an official package (`Debian details`_, `Ubuntu details`_), so try typing: @@ -69,10 +69,10 @@ new versions. .. _@b33ts: http://twitter.com/b33ts -Installing on Mac OS X 10.11 and higher -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Installing on macOS 10.11 and Higher +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Starting with Mac OS X 10.11 (El Capitan), Apple has enabled `System Integrity Protection`_ (SIP), and because of SIP, some installation processes may fail, even with ``sudo``, because they intrude on protected areas of the system (if you've installed python via `Homebrew`_ this probably won't happen since the Python libraries are installed to an unrestricted folder). If this does happen, try installing beets only for the current user by running ``pip install --user beets``. It might also be a good idea to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. +Starting with macOS 10.11 (El Capitan), Apple has enabled `System Integrity Protection`_ (SIP), and because of SIP, some installation processes may fail, even with ``sudo``, because they intrude on protected areas of the system (if you've installed python via `Homebrew`_ this probably won't happen since the Python libraries are installed to an unrestricted folder). If this does happen, try installing beets only for the current user by running ``pip install --user beets``. It might also be a good idea to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. .. _System Integrity Protection: https://support.apple.com/en-us/HT204899 .. _Homebrew: http://brew.sh From bb9a107c565df2a811a3c4fc8d4cecfb7eea4eae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 26 Oct 2016 13:40:45 -0400 Subject: [PATCH 1372/2280] Slight rewording in docs about SIP --- docs/guides/main.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index ee9e59df1..4e833fe3c 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -72,7 +72,15 @@ new versions. Installing on macOS 10.11 and Higher ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Starting with macOS 10.11 (El Capitan), Apple has enabled `System Integrity Protection`_ (SIP), and because of SIP, some installation processes may fail, even with ``sudo``, because they intrude on protected areas of the system (if you've installed python via `Homebrew`_ this probably won't happen since the Python libraries are installed to an unrestricted folder). If this does happen, try installing beets only for the current user by running ``pip install --user beets``. It might also be a good idea to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. +Starting with version 10.11 (El Capitan), macOS has a new security feature +called `System Integrity Protection`_ (SIP) that prevents you from modifying +some parts of the system. This means that some ``pip`` commands may fail with +a permissions error, even when you use ``sudo``. (You probably *won't* run +into this if you've installed Python yourself with `Homebrew`_ or otherwise.) + +If this happens, you can install beets for the current user only (sans +``sudo``) by typing ``pip install --user beets``. If you do that, you might want +to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. .. _System Integrity Protection: https://support.apple.com/en-us/HT204899 .. _Homebrew: http://brew.sh From 7242c5ed03bdf43935f1286de22870b41bf76910 Mon Sep 17 00:00:00 2001 From: Max Ammann Date: Wed, 26 Oct 2016 23:08:44 +0200 Subject: [PATCH 1373/2280] Revert "Expose the relative path to the library instead of omitting the 'path' variable" This reverts commit 5e8ac9e4a5d06de791fe051a419ba070bbdd5bec, because of a slowdown. Resolves #2182. --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 07e68638b..810de8718 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -37,7 +37,7 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - out['path'] = obj.destination(fragment=True) + del out['path'] # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. From 3b372c05d6b5e30fa0aed59b20c6b4aef1c2a433 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 7 Nov 2016 16:03:56 +0100 Subject: [PATCH 1374/2280] art: fix a docstring typo --- beets/art.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/art.py b/beets/art.py index a47fe02cb..4f873fc60 100644 --- a/beets/art.py +++ b/beets/art.py @@ -180,7 +180,7 @@ def check_art_similarity(log, item, imagepath, compare_threshold): log.debug(u'IM output is not a number: {0!r}', out_str) return - log.debug(u'ImageMagick copmare score: {0}', phash_diff) + log.debug(u'ImageMagick compare score: {0}', phash_diff) return phash_diff <= compare_threshold return True From a0877dc092d006490bff365d66bb73b48b17c7c1 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 7 Nov 2016 16:01:57 +0100 Subject: [PATCH 1375/2280] images: Make sure all jpegs work everywhere Apply #1545 to a public function used everywhere --- beets/art.py | 1 - beets/mediafile.py | 17 ++++++++++++++--- beetsplug/fetchart.py | 4 ++-- test/test_mediafile_edge.py | 2 +- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/beets/art.py b/beets/art.py index 4f873fc60..b371c2c95 100644 --- a/beets/art.py +++ b/beets/art.py @@ -22,7 +22,6 @@ from __future__ import division, absolute_import, print_function import subprocess import platform from tempfile import NamedTemporaryFile -import imghdr import os from beets.util import displayable_path, syspath, bytestring_path diff --git a/beets/mediafile.py b/beets/mediafile.py index 6dd7bc816..616587597 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -308,6 +308,17 @@ def _sc_encode(gain, peak): # Cover art and other images. +def _imghdr_what_wrapper(data): + """A wrapper around imghdr.what to account for jpeg files that can only be + identified as such using their magic bytes + See #1545 + See https://github.com/file/file/blob/master/magic/Magdir/jpeg#L12 + """ + # imghdr.what returns none for jpegs with only the magic bytes, so + # _wider_test_jpeg is run in that case. It still returns None if it didn't + # match such a jpeg file. + return imghdr.what(None, h=data) or _wider_test_jpeg(data) + def _wider_test_jpeg(data): """Test for a jpeg file following the UNIX file implementation which @@ -318,14 +329,14 @@ def _wider_test_jpeg(data): return 'jpeg' -def _image_mime_type(data): +def image_mime_type(data): """Return the MIME type of the image data (a bytestring). """ # This checks for a jpeg file with only the magic bytes (unrecognized by # imghdr.what). imghdr.what returns none for that type of file, so # _wider_test_jpeg is run in that case. It still returns None if it didn't # match such a jpeg file. - kind = imghdr.what(None, h=data) or _wider_test_jpeg(data) + kind = _imghdr_what_wrapper(data) if kind in ['gif', 'jpeg', 'png', 'tiff', 'bmp']: return 'image/{0}'.format(kind) elif kind == 'pgm': @@ -394,7 +405,7 @@ class Image(object): @property def mime_type(self): if self.data: - return _image_mime_type(self.data) + return image_mime_type(self.data) @property def type_index(self): diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 4db22397e..27ffa49cb 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -29,7 +29,7 @@ from beets import importer from beets import ui from beets import util from beets import config -from beets.mediafile import _image_mime_type +from beets.mediafile import image_mime_type from beets.util.artresizer import ArtResizer from beets.util import confit from beets.util import syspath, bytestring_path, py3_path @@ -250,7 +250,7 @@ class RemoteArtSource(ArtSource): # server didn't return enough data, i.e. corrupt image return - real_ct = _image_mime_type(header) + real_ct = image_mime_type(header) if real_ct is None: # detection by file magic failed, fall back to the # server-supplied Content-Type diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 4e053192a..d09b11fb8 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -91,7 +91,7 @@ class EdgeTest(unittest.TestCase): with open(magic_bytes_file, 'rb') as f: jpg_data = f.read() self.assertEqual( - beets.mediafile._image_mime_type(jpg_data), + beets.mediafile.image_mime_type(jpg_data), 'image/jpeg') def test_soundcheck_non_ascii(self): From 92ee141662d8948177fb724ce1da07da50cda2bb Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 7 Nov 2016 16:03:05 +0100 Subject: [PATCH 1376/2280] images: use jpg extensions for jpeg files everywhere fix #2254 --- beets/art.py | 2 +- beets/mediafile.py | 7 +++++++ beets/util/collections.py | 27 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 beets/util/collections.py diff --git a/beets/art.py b/beets/art.py index b371c2c95..979a6f722 100644 --- a/beets/art.py +++ b/beets/art.py @@ -193,7 +193,7 @@ def extract(log, outpath, item): return # Add an extension to the filename. - ext = imghdr.what(None, h=art) + ext = mediafile.image_extension(art) if not ext: log.warning(u'Unknown image type in {0}.', displayable_path(item.path)) diff --git a/beets/mediafile.py b/beets/mediafile.py index 616587597..3faf2f60e 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -59,6 +59,7 @@ import enum from beets import logging from beets.util import displayable_path, syspath, as_string +from beets.util.collections import IdentityUnlessDict import six @@ -81,6 +82,8 @@ TYPES = { 'aiff': 'AIFF', } +PREFERRED_IMAGE_EXTENSIONS = IdentityUnlessDict({'jpeg': 'jpg'}) + # Exceptions. @@ -351,6 +354,10 @@ def image_mime_type(data): return 'image/x-{0}'.format(kind) +def image_extension(data): + return PREFERRED_IMAGE_EXTENSIONS[_imghdr_what_wrapper(data)] + + class ImageType(enum.Enum): """Indicates the kind of an `Image` stored in a file's tag. """ diff --git a/beets/util/collections.py b/beets/util/collections.py new file mode 100644 index 000000000..dad49a4a4 --- /dev/null +++ b/beets/util/collections.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +"""Custom collections classes +""" + + +class IdentityUnlessDict(dict): + """A dictionary which is "transparent" (maps keys to themselves) for all + keys not in it. + """ + def __getitem__(self, key): + try: + return dict.__getitem__(self, key) + except KeyError: + return key From e782885e5050fa1f40cd93aade900650bf1c90fc Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Tue, 8 Nov 2016 18:42:19 +0100 Subject: [PATCH 1377/2280] embedart: Adapt tests for #2254 --- test/rsrc/image-jpeg.mp3 | Bin 0 -> 10452 bytes test/test_embedart.py | 11 +++++++++++ test/test_mediafile_edge.py | 3 +-- 3 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 test/rsrc/image-jpeg.mp3 diff --git a/test/rsrc/image-jpeg.mp3 b/test/rsrc/image-jpeg.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..3f2d22ffb1f44b9169a1d491f4315afa8d1d1632 GIT binary patch literal 10452 zcmeZtF=k<4U|`@24heGhW?*1oWnf@7&^KTR3Gfd_=DGwqGcYi)fn*H~3>X{(Je?UB zSeY0Ym@{(|(^K`c3R2SK@x`2T=Gz{}0kje(Jok->w(gMs1yZ3btC|CEB;49<*{ zn(_YtgCGY3GXoPdqaXv5AS1IN(iUwW$pkka< z)WpdpCN3cY31zV>gMj@=@lFj8WtWA8I_!pnwFlCnN?g;T2@|B zS=HRq+ScCD*)?hMl&RCE&zL!D(c&dbmn~nha@D5ITefc7zGLUELx+zXJ$C%W$y1ju zU%7hi`i+~n9zJ^f*tmhXC@~VC1&PT>E#!tGlT~Fgg`Y!L_|QsY?K@g zfzc2c4FS?a;Q#M{BN)0o^V0Ge7#R2&7#K7d7!=DH*w}b@goTAAB^4AD)YNozbc~HH zEiD}!+}zxJe1e06BO?KLZ1UrH`YptFfM?xdP)-kehV> zF))ZYsIb;JF)%oQ+!4R~YaB=d4+i^(nZt0^9|x8Yi5sR$J`CNR4Iv!IrN9-lQ-)u0 zd!_V*mRd;;2L|JL$E}|`3I8(M|7-qxMf+dE|7tm$7fQ9LI|(pO=;UBnaUkhb0~4Q) z?FNQT3g)vP{Y`e2Nbr@_lUT-V#4Rgewacq~E@xV8`SNH%dyw(#dM94$4Yv|mx2n}m zK%s|~;RpYAr%R?wPd(qYkndXDX1TRm+H65q*-qQ<@4vln{{Q>`pU(WVFIq-of||wj z&?E!(z=#CKhKz-&|Nqbbf77V)YUGpuzk`k_HnVGP=?o?DW__3m9~$+hDwnazfM%e61tB~1^{ zTR(f>_W%F?|M~wb>uz>gt*2J8aK;aAJX%T~-h zsm&4Su$}Mmt?jY1ZfbAq+m-wO+e^3q`}5vEdVVp>o}Zsu6KmCJ$S`hoA; z5<3{B7x*d9F?lnG*<)7tIECzTM|>XO)gWRS~AV*-7)Y@RrmNmTewf+&!$*L}vLp2r*vF zR$aN=-BV{~YG~}TszANpt97>Nu3xiivC_@2pSS=2x}@%B?R~HCPjhSUT??7vy2S1! z_X*!FC*^64OI(Cza@e2v|9)Cb%0qu!#o6bHW?sq3~wT zwOd&fcx@ROw<&TksxREzdQER;&HVr0cl~^vw>82~G+X}d-6WCwT#4ago@FQ67s;u6 zgovvPIWS3OrfuG=RCIHy*w!kmZ=2pOwt4lSD=I3Cr6Xr)nDerEXSSsHum8^Bu5IU5 zt?9dB+2(BB)e9#sSM=4(_*nRraq1=YV`)8A1`ce$>i_@$^?vTI$oIKn+uo*MxmLb4 zq-`QsMXRE_qPly@Rh~2HKd<#0z4X>w_2=5w)w%a3@9N5)6J!{=ESc%`q}OUE*iLaB z$++y+3i421b7$m6kcT+Mw<#Q9RA0z6iD3f2@{%o~DPfuSi)QrjO!teMWVpTN@|{3Q z=2uUnZ10_W?Qb5n?bxN>+Mkan{NB9!`myqd%u*kn_e7^TEn08KJE@H$NUNhuV=<5Y zxt_lN+15TQ`qQ-Xf)@r?o+(btyc^Q0WpuMkZQWyQ?Gsbq|6kU-m1qAu;ikyougOA@ zCT_Q87Oy?0;k&@3v2eqQH72eRr4M8pH7=wHd08wd%XrLjh*K=3D$iA^fUAmmv$4RM z%Zucy*#G}4s(B0cPzy8X!L4i#oaP6Ww!+tJmB~x<9>K&*!&!YS$zO z?l=)%6O z-{$wv>bjG5O2p}}=Y*cgH?<2DE-rW&$*_d^_r4boa;#0Z7o0ItoYDB?)#5a!9`Do6 zeKT4;m#p3$sVZl;PWj%x+dux<-&^0=UpalV&W@yo{4$P_?elmfWO{WbYWMQDvQJUq zW>MAZ0hKPNK_$$~x6dOct^~!jOuqjvW+dKXEqdxKeiSFO`|K-0{nHChyc{HV@e?6-*m&rzM??@(+>brdhylZX;<(6|8?Kx`@X%u z>Xe!?V-5Y{xXbmkPD(WUYpz=0>lUu@1=o$**CmcRn%6b zpIBME^1`YYCt6~@eA#O6Yk&9uq}vhqUpl918$>dS=X_gsF;mEdqfsX*;fJk*O9x~4 z|NsAWCG$gV&ldRs9Tx{jp`J&j=`);(#E&I#LE<7E}`+xki z|5x#RvgGTIGmT%?=$bNqkcW;id!60PqR?y0$ZG~J z6mBH`tN(8=FZA-;l!QZ`olR3>&wFR?mPq}aX8lq)Q#nXpnroZBwUCut@SIwoBNEq( zxi4QiA1=4;^Wtf?89OACIhUBkWc4WVy0X9H;d5MIp~uCWptewV?N9rc za@c?Q`v2pn_BH!;`<(XFKK=1D%rWG9;61yUQESWMS^tLz&khVX-WqWBxWa5}k(-}y z`qjyW*44lL|N3c#*K)SJi#j_MGjv`|yE2RWQc6~@Zl?Gqh5arbF;hSuy2{MCa6O9x z?_5cF(}x_4(hGZLoOW#B@#5?{#=-2saR2}R|E^(5i+7yK7Cn<1H1T`6=7lxKORCoE zJ#$rj<-IcR#j&!go#D}vyMF)swY7Bmw{5SFnNMjI^PB6X@nwdR>BiaDK06#tl=iVz z?mN1`f&c%X{eKn&wg3PB|4HZ62eKu5%QG(ttqye$%$ZQ`D#XFIsq@VmW%myO4<9FLl0&# zhPT+B-o3)xHl`zU^3jhu2R%!R?Zd6-e>|D``{{j)^y#6IADxAg4|%>iy-riacUo9P zLMNZBk8zT*>kWYxm5?xyhu$>%q;6$!=$&`4eA@yRhGi>yYz{H#gQDpF|9|DDeT%HJ zQlcgbPA_df$)9|K~C&RlM4~q(Px=*roTee!sDP-=;qcI)AmENHh)UY7JkOl9jb0QBe8h z$q*MGK8FiAQ(`V{JJKNk|NsBjAL{>uJoJj$yKpm;L$57o(>4Vb!Ob^6Pb}LPIdkQ< z!cO&nS-VwPm3M1joYx|d!ysbREO~SWhf0RzoVYDwycZ`1cpiDG|1vJvnoaC@e@|< z%u4aV3+0S49|Nno^ znB%zq_xGHdulq$qUggfx_&4)!$17dtBCZd)8?U5pdw*iNW#r7K%O1`C_b<8pe!ldY z@BZh{v?Z2@t)09=b23wkclW#v4?Y}wI$7=93>%jg6Wt0EwOP{xA2HZfF#iAl|L2sx zP5=MDet2u&Y2MyB{l8*&3UB(j@73BE%@+3A6AD{mcl$U!Jrp`U=)&i=RKI)mb^q$Z zXP&=5Z(k7W?v2*!)22loyM7>MYsE^Px!W0UN_rm>y)Wgvy$|f6*UVhCTUi`U@BeB=NBf6Mfz|Nnn{Mx$l1r_;-Y+^(lft(7CXPK7O+(A2u~oUFuj7mG$QzK~M) z61V8CiF#Mwf70G$59uIuw*q5cUOvJuU_!U3Nec@YxS*VHaG9>1P4%(d(+IV zx|Jn?*ZkllvjrT&#y2i9aGk#X|JPQtTc6}Ni9RvuR}xsI(XKi7Mc1NN&Q~R*H|$g~ zmX*C5@lIE##4_U8Zj+f33Wlwqlljh9Ur+q@ZVRBIk6*`t1}^Gm!At) z$BD3`uMRb^?hXI{|LfiNrju5_o1JaEJ=lY{ZqDno5t`PMqpr*koY+zQbFD6~muE%l zz2`r-hyVTa^RxD~>iru&ef4>guhzfWQ{1p?{*@y_o{LVraY-;0VL5ytL)c8AajK)C z!vvwJn?N3V-RwPcE6ai2xs0u53p|82-(WnY;?nqfRo(Ib|GRCzC(9(694(HCIq$Un z!pov4(Wmus?`P(BF8r6kcbr@&jQX14?!M!)y!Q9^3c44S!M}6jA}m_`2YX^7eC9vx@`adm1{*@ z7W{EG_)w}eS4S{?k8{g1E@iW}e{*WqPd;ke@-y%3CG-A{2|Lf9n}098XkOm^pL@2L zd^7)gJND@sac$OnP0vIVov)nmkG1mf?})f=z+jibn0i%Ir+;nzuQzwEYU~Y}mDg#y z>XAul^WK-!{?6YQWz#rA_}kUjo0)&JKi-fYCBImF$>Wd3((`xfz4QHCm6ldE|MOgt zKPB&z-foV*%4Zf*^&~6O>OZH;Bdx-#7HuF8y=CID-OA*^Y3i75mZ-t7D6xb?QpGy1 zDN1LW$E{tgYZch%{{R2~yNAX~!5uDDbJ~n0TraFkU2ZJ1%vw+_@X!;>{8H7Uc?!-` zno?}F}A-H)# zll}ky|IV%myL)i|{~z;n^2ALR^omUUWbrkm{^)NV*U0q?R-g1UHFutD8j^FeDX*IA za>JUXw&|t+=f6DhD)Q5w)PQMIo9b?ca%p5vE96pJSK#5G$uIBGGC@XUC1Y2C69e=A z|Ns9=U00oM{(tKqP3gbBb}MzQlR4I9i(3}yuRPNFq@9ubp-@t+b5omR$H~`SDh5w{ zA`5PR{r`W?^88hMQ^F=yTdXSiH8GIKP&qeWSlXjxOJr(Mkc*G72G~Q)yc0Jv9N?VX zXuEA;55u$ttXxMg&tQoCzhQw%Rnp=UtZAqJ)hsdKS<1PfqlrOsmGjgkb_YFJW_yP1 zt6p|}!&9T2$(p`~+(E{mia%s~>f()kFS@!oPlbx;7+z%To5rGYu#x8~1A|<`B^KVT zYp%wWD$S6t|NmwGOsQuJTkTipTD%Ss(bW0r9she@Txj5DGN zPI-O*kDveQtom-3XcSvqU$kUJ+iEG^k47wRoQ-#xHzs_!P@XN&xRdGFNsW#Mh=;tt zZf1Aroy%Bmme3=(Jd^$Z|9_dr6LNW6ee3`K-*X~9&&MS^+4HFJ?@uv)!yu5Z*$^Y$hGr~RwhHS_-pg%fYoZrz;cGqY1mT4SM-P?ChtRTU*+ z#tE^CS}Ui5(wrbD&HZQP4L-Cc_5V+|bp1)2P1Mqtf4#_a=Eao#UWRKFLJk|g_O@=x zdm3|OR4F1pV7l@Yai zvi{LMF_%Ah{_}}^bL!QqW8$}D>?BkhCwKA&Yq=EH&;Qf@`OoLlxxbT^9CdrrIcLd( zKgVJYX&h+}i%Oj0)Fr~BlTg;X$*XHB0|NsS?-qx~OWXgyyO~~G{r~6Gl{SLM)clHU z-&LMFwoiOd*&B=fGoMZRwpujewl#;OyT}v4-D_4o|9^S=+t;VoEe`a0({)OL=iHlQ zkt2pj13J{CFdH4D^FY)x8}hFVbKX%jdxjht(+@*{neX$-+$lUudi5i zB4l0dcXhqqMWN4{CoQ}5d{OR!*?}=(3AJerqVQ*qz5j6M z*1stqS8P=Mbt)!l+PBUi%@n2?{9FmUj6bFpt?g%EU=X_d#i4Pc^G4QR-j8iU@6O)N zSj8=&?U3({7bHDq){_AyL@1nh0`r&exXPz;w zmT}}c++li($I?mpHN(?F2GG>!@1P^knYjZuaxUQ6e6rZ|!5KmIh5z4mWlx>>FsS3H z|NsAqdp1?pGmGjzDPyeew zZBX@RkD+mt@wAAR!x=lTKk_^Hd-=0TI?l)M1VwIA5e|xY6&7R)N^Nn*E{*^H|KFYz zoxt5~JOBTuM|(}eelB5iJ?SNv(9v@sh^j#*Z)ts2R?!Uf8?wT}XeVaXx4*tu_%Dj+X89U+por%}09j%@3 z$%Ou0@pjd;_BZkK|JOhN`Tw*1e*QVCO15WWWq4GA6P%oKH5wKcDP+iAWnf?^@=o?- z{Qv*eF$*Iv?>S3%wS_9L-WODB|Nfkm@p(Vt$GZAkp4~bgyhC}>;zwfdp{kdQCQQ0rWGbe6yT<};L;Hcni zdo{RXO574#m)tL)KEao@-(5;eRhL)32=P2#n83x**Ve#LTl2sC|FVY(23r&U|9jaN z-5>0_?djL^Kkld8|E&LSU+=4k#$K+nvu$k|H7&(u{L{Dj&SO~ka$*17_m7XJdfR`$ z|E>DJy;N#oA6)_W}#ZLob_n zJlAtBv?%lM=DFXwuKy-E{L;b&Z)BpGNEKcQ3{I>sRYSn{DHo{R~jY3(^xf<&R zEGk&E$$I95%Z5`!J}uN*>v`%hUzwHZ)vL>~Nn?Akro=EO6NO(IW{v?touzcroFIsK;O!mR&)d$XKO zdm2lsx65|)dhJOP5mXX<^WoA_P8EIg$+y>@ivK?`?au3GZ%)sh+bK15cJ;n$W=qER zHMcD6WDSHQ__$y5@F%pUf|f;iXL~Z*cW;_kbmQ>m=ea$r?|j~WhOv1R8j#mFm_XOd)mXST_3YiU_YoVhNSdoeT`loIaFT=8wU)z*~6Z&Ul7IW=~6 zS#s=tr@&zU|0>8sUzz*_w=z7KIhV0{+k!8OYCq~1t6S}uZm~7F)p*;Nm+y-O952YN z{<=#2{_piB->Z!-dnaGDJJA{;G_yPPh>5Y2@!h=EpY`*nKmDKYwR~sroS8kzDgvD* zv)s;vhf1znsN`$B^zfm1T3H&-1w4z`Kw0SSY6Zss|8Jz&oZZN_tjEQ|XSd#e-bm)j z5^N1?YzfaoDc|k~@MN8VL)a+ixP;8}Zf$~J{9iklZMmSa4f?9w=A`SH(< z6Q?Y^;Ba4S%l=23=6nA)QT|#mC3<0YsAr1^qlmkTx#q(3YqwO+=3G0ykog?PX8ZsD zf0r*$-)$^gCd=p8vhvWKRSw1rC%ki05jX|%$@|R?jQ{`N+~n_)VtJ_9%UsFy{GX-& zuFnW}@-2QD?Z}rJ{nk0)!UP4)%coCoIbReUBr0mAMc=Ej=hNmrTqY6d%<(EyP^BtJVAJIUkcVD3alPCuyntup#mQz0D-@UCl<<1k zz-qR20;pKuD|w+y#IV1vW!e9qYVMvFo;-_EIHxUsefy=VsCA(#+lyN@Gs{`ErfxU4 zhD0k`}rVHQXJtfd)u0=O2l zaJ_2OvJ^{L#G57lfByXE|LZ^P|GT|<^YgVvsplNd9ru&WSOoD9kL*VF1-*7B{mc?y zFm_eRY-wY=x|yx1bD|0l%l6#l9)^;VCs&1;jqlxy`)t4eU-@!(eY;wruGRAon|-|{ z8ZPYXq0!Ls+)2hzc~!St=P~7L=lT{eI$&1+|F^wQQ<%dHIR*xXruUyc8lLRS>j-M) z5SS_TR5d#a(jCJtnb~?Rr?;yy4zuUO!Jq{k-Y+TsX5o*P3X>;{c7c`_49we z-uLVOKZ|+wUo-bR&hk8Sh+*^2W4vxQCsjUjPAF)5bf`s2RAYaUi6`^_e;^ONXX4de z&%Th?{ABaCgfEKAGcgeLvGVQ-Jl6oOLv_) zurYHl1H(R#iz-~HJKtTiNOQWUE67n+^8SD2MaKHHIjt^RH@EVBer@YC`9g7(=j^1! zNvmQyLncj*ohB(6Z*LD8{M`QCdS-Q9>8(x4mpwxRR2zDnwcD8to?C?L_B62n|9?ss zX|&3mlVBmYu7n(>AbqFqud_n>FSa%bDsvxT(C-V z_Nl|sq9NNh-)?MIW17;ReEU=0R8!r$lj%R>|F;|e%8c5x_PcaXQrClPCMQLY3Ua2e zDLEXe)aiheQ>O^1 zD@WF=Z91(uW#^hXo4$Fu|Jncl+r%~dl_%?Lx?-BG)91GN{HAB|KcyO3Sp-i{(@^m1 zb6eQBW=7MjuCy4Chdwg#L~iC>z{-EHeVby2;H+Ood8 Date: Tue, 8 Nov 2016 12:10:17 +0100 Subject: [PATCH 1378/2280] utils.collections: rename IdentityUnlessDict to IdentityFallbackDict --- beets/mediafile.py | 4 ++-- beets/util/collections.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 3faf2f60e..784695c1a 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -59,7 +59,7 @@ import enum from beets import logging from beets.util import displayable_path, syspath, as_string -from beets.util.collections import IdentityUnlessDict +from beets.util.collections import IdentityFallbackDict import six @@ -82,7 +82,7 @@ TYPES = { 'aiff': 'AIFF', } -PREFERRED_IMAGE_EXTENSIONS = IdentityUnlessDict({'jpeg': 'jpg'}) +PREFERRED_IMAGE_EXTENSIONS = IdentityFallbackDict({'jpeg': 'jpg'}) # Exceptions. diff --git a/beets/util/collections.py b/beets/util/collections.py index dad49a4a4..6813b95df 100644 --- a/beets/util/collections.py +++ b/beets/util/collections.py @@ -16,7 +16,7 @@ """ -class IdentityUnlessDict(dict): +class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all keys not in it. """ From f236816431a3fdf18ae79eeaf35499cad69cdcc3 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Tue, 8 Nov 2016 12:10:34 +0100 Subject: [PATCH 1379/2280] embedart: Changelog for #2255 --- docs/changelog.rst | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 08be98a5c..7c03e230d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,6 +52,12 @@ The are a couple of small new features: And there are a few bug fixes too: +* :doc:`/plugins/embedart`: The plugin now uses ``jpg`` as an extension rather + than ``jpeg``, to ensure consistency with :doc:`plugins/fetchart`. + Thanks to :user:`tweitzel`. :bug:`2254` :bug:`2255` +* :doc:`/plugins/embedart`: The plugin now works for all jpeg files, including + those that are only recognizable by their magic bytes. + :bug:`1545` :bug:`2255` * :doc:`/plugins/web`: The JSON output is no longer pretty-printed (for a space savings). :bug:`2050` * :doc:`/plugins/permissions`: Fix a regression in the previous release where @@ -70,7 +76,7 @@ And there are a few bug fixes too: This is fixed. :bug:`2168` * :doc:`/plugins/embyupdate`: Fixes authentication header problem that caused a problem that it was not possible to get tokens from the Emby API. -* :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the +* :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the colon character. :bug:`2206` * Fix a crash when a query contains a date field that is not set for all the items. :bug:`1938` From acd5c6404f8b0cc8a7a62bd6c97cfff9f5b48dc2 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 8 Nov 2016 16:23:57 -0800 Subject: [PATCH 1380/2280] missing plugin, modify "missing" attribute by modifying album_types, making it of type INTEGER. also changelog for above. --- beetsplug/missing.py | 7 ++++++- docs/changelog.rst | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index b99a70d9e..a09c855cb 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -22,7 +22,7 @@ from beets.library import Item from beets.plugins import BeetsPlugin from beets.ui import decargs, print_, Subcommand from beets import config - +from beets.dbcore import types def _missing_count(album): """Return number of missing items in `album`. @@ -81,6 +81,11 @@ def _item(track_info, album_info, album_id): class MissingPlugin(BeetsPlugin): """List missing tracks """ + + album_types = { + 'missing': types.INTEGER, + } + def __init__(self): super(MissingPlugin, self).__init__() diff --git a/docs/changelog.rst b/docs/changelog.rst index 7c03e230d..dd012285b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -84,6 +84,8 @@ And there are a few bug fixes too: single track, two-sided mediums are treated as single discs, and tracks have ``media``, ``medium_total`` and ``medium`` set correctly. :bug:`2222` :bug:`2228`. +* :doc:`/plugins/missing`: ``missing`` is now treated as an integer, allowing + the use of (for example) ranges in queries. The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From f37df2dbd43ce34707cb26a70d9ca832ade3c21e Mon Sep 17 00:00:00 2001 From: root Date: Tue, 8 Nov 2016 16:56:13 -0800 Subject: [PATCH 1381/2280] Whitespace for flake8. --- beetsplug/missing.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index a09c855cb..24c903cd6 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -24,6 +24,7 @@ from beets.ui import decargs, print_, Subcommand from beets import config from beets.dbcore import types + def _missing_count(album): """Return number of missing items in `album`. """ @@ -83,7 +84,7 @@ class MissingPlugin(BeetsPlugin): """ album_types = { - 'missing': types.INTEGER, + 'missing': types.INTEGER, } def __init__(self): From 3e53d4caff31d4f9229572b60c9f4b87086565fe Mon Sep 17 00:00:00 2001 From: michaelbub Date: Thu, 10 Nov 2016 13:05:18 +0100 Subject: [PATCH 1382/2280] sanitize playlist names Make e. g. - name: $albumartist/$year-$album.m3u' work when album data includes non fs-friendly characters --- beetsplug/smartplaylist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 416dc37f5..73c3f59eb 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -20,7 +20,7 @@ from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui -from beets.util import mkdirall, normpath, syspath, bytestring_path +from beets.util import mkdirall, normpath, sanitize_path, syspath, bytestring_path from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import MultipleSort, ParsingError @@ -186,7 +186,7 @@ class SmartPlaylistPlugin(BeetsPlugin): # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: - m3u_name = item.evaluate_template(name, True) + m3u_name = sanitize_path(item.evaluate_template(name, True), lib.replacements) if m3u_name not in m3us: m3us[m3u_name] = [] item_path = item.path From 5942adba0104e834a3760affb94e5bda2c3ac489 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 10:07:25 +0100 Subject: [PATCH 1383/2280] fixed/updated test to consider sanitized playlist names --- beetsplug/smartplaylist.py | 5 +++-- test/test_smartplaylist.py | 16 +++++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 73c3f59eb..bde64ca3d 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -173,7 +173,8 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self._matched_playlists: name, (query, q_sort), (album_query, a_q_sort) = playlist - self._log.debug(u"Creating playlist {0}", name) + sanitized_name = sanitize_path(name, lib.replacements) + self._log.debug(u"Creating playlist {0}", sanitized_name) items = [] if query: @@ -186,7 +187,7 @@ class SmartPlaylistPlugin(BeetsPlugin): # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: - m3u_name = sanitize_path(item.evaluate_template(name, True), lib.replacements) + m3u_name = item.evaluate_template(sanitized_name, True) if m3u_name not in m3us: m3us[m3u_name] = [] item_path = item.path diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 071ff390b..4425aa172 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -25,7 +25,7 @@ from beetsplug.smartplaylist import SmartPlaylistPlugin from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import NullSort, MultipleSort, FixedFieldSort -from beets.util import syspath, bytestring_path, py3_path +from beets.util import syspath, bytestring_path, py3_path, CHAR_REPLACE from beets.ui import UserError from beets import config @@ -151,12 +151,15 @@ class SmartPlaylistTest(unittest.TestCase): i = Mock(path=b'/tagada.mp3') i.evaluate_template.side_effect = lambda x, _: x - q = Mock() - a_q = Mock() + lib = Mock() + lib.replacements = CHAR_REPLACE lib.items.return_value = [i] lib.albums.return_value = [] - pl = b'my_playlist.m3u', (q, None), (a_q, None) + + q = Mock() + a_q = Mock() + pl = b'.my:.m3u', (q, None), (a_q, None) spl._matched_playlists = [pl] dir = bytestring_path(mkdtemp()) @@ -171,15 +174,14 @@ class SmartPlaylistTest(unittest.TestCase): lib.items.assert_called_once_with(q, None) lib.albums.assert_called_once_with(a_q, None) - m3u_filepath = path.join(dir, pl[0]) + m3u_filepath = path.join(dir, b'_my__playlist_.m3u') self.assertTrue(path.exists(m3u_filepath)) with open(syspath(m3u_filepath), 'rb') as f: content = f.read() rmtree(dir) self.assertEqual(content, b'/tagada.mp3\n') - - + class SmartPlaylistCLITest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() From 405a633b5a136a097d33ec54b6b08624855c1e77 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 10:51:18 +0100 Subject: [PATCH 1384/2280] updated changelog with info about sanitized playlist names --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index dd012285b..02054e87c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -32,6 +32,8 @@ Deprecated configuration optional removals: The are a couple of small new features: +* :doc:`/plugins/smartplaylist`: Playlist names will be sanitized to + ensure valid filenames. :bug:`2258` * :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option is not set, these plugins will now look for the ``$MPD_HOST`` environment variable before falling back to ``localhost``. Thanks to :user:`tarruda`. From 0bdc621d991c31186a835866701836258aa1a7e7 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 15:21:34 +0100 Subject: [PATCH 1385/2280] sanitizing playlist name AFTER values have been filled in and updated test accordingly --- beetsplug/smartplaylist.py | 5 ++--- test/test_smartplaylist.py | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index bde64ca3d..73c3f59eb 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -173,8 +173,7 @@ class SmartPlaylistPlugin(BeetsPlugin): for playlist in self._matched_playlists: name, (query, q_sort), (album_query, a_q_sort) = playlist - sanitized_name = sanitize_path(name, lib.replacements) - self._log.debug(u"Creating playlist {0}", sanitized_name) + self._log.debug(u"Creating playlist {0}", name) items = [] if query: @@ -187,7 +186,7 @@ class SmartPlaylistPlugin(BeetsPlugin): # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: - m3u_name = item.evaluate_template(sanitized_name, True) + m3u_name = sanitize_path(item.evaluate_template(name, True), lib.replacements) if m3u_name not in m3us: m3us[m3u_name] = [] item_path = item.path diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 4425aa172..34f5b71d1 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -150,7 +150,7 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() i = Mock(path=b'/tagada.mp3') - i.evaluate_template.side_effect = lambda x, _: x + i.evaluate_template.side_effect = lambda pl, _: pl.replace('$title', 'ta:ga:da') lib = Mock() lib.replacements = CHAR_REPLACE @@ -159,7 +159,7 @@ class SmartPlaylistTest(unittest.TestCase): q = Mock() a_q = Mock() - pl = b'.my:.m3u', (q, None), (a_q, None) + pl = b'$title-my.m3u', (q, None), (a_q, None) spl._matched_playlists = [pl] dir = bytestring_path(mkdtemp()) @@ -174,7 +174,7 @@ class SmartPlaylistTest(unittest.TestCase): lib.items.assert_called_once_with(q, None) lib.albums.assert_called_once_with(a_q, None) - m3u_filepath = path.join(dir, b'_my__playlist_.m3u') + m3u_filepath = path.join(dir, b'ta_ga_da-my_playlist_.m3u') self.assertTrue(path.exists(m3u_filepath)) with open(syspath(m3u_filepath), 'rb') as f: content = f.read() From 28d18b7c64a6c04f3e84a4f6e6f0d2a3dbee3939 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 15:53:14 +0100 Subject: [PATCH 1386/2280] update test to run with python 3.5.2 --- test/test_smartplaylist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 34f5b71d1..f6cc04aef 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -150,8 +150,8 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() i = Mock(path=b'/tagada.mp3') - i.evaluate_template.side_effect = lambda pl, _: pl.replace('$title', 'ta:ga:da') - + i.evaluate_template.side_effect = lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() + lib = Mock() lib.replacements = CHAR_REPLACE lib.items.return_value = [i] From 0a88338f8b2c21817b21537a0ec2162a95f6f5b8 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 16:19:33 +0100 Subject: [PATCH 1387/2280] obey style guide --- beetsplug/smartplaylist.py | 6 ++++-- test/test_smartplaylist.py | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 73c3f59eb..514e74acc 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -20,7 +20,8 @@ from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets import ui -from beets.util import mkdirall, normpath, sanitize_path, syspath, bytestring_path +from beets.util import (mkdirall, normpath, sanitize_path, syspath, + bytestring_path) from beets.library import Item, Album, parse_query_string from beets.dbcore import OrQuery from beets.dbcore.query import MultipleSort, ParsingError @@ -186,7 +187,8 @@ class SmartPlaylistPlugin(BeetsPlugin): # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: - m3u_name = sanitize_path(item.evaluate_template(name, True), lib.replacements) + m3u_name = item.evaluate_template(name, True) + m3u_name = sanitize_path(m3u_name, lib.replacements) if m3u_name not in m3us: m3us[m3u_name] = [] item_path = item.path diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index f6cc04aef..084e0694d 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -150,8 +150,9 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() i = Mock(path=b'/tagada.mp3') - i.evaluate_template.side_effect = lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() - + title_replacer = lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() + i.evaluate_template.side_effect = title_replacer + lib = Mock() lib.replacements = CHAR_REPLACE lib.items.return_value = [i] @@ -181,7 +182,8 @@ class SmartPlaylistTest(unittest.TestCase): rmtree(dir) self.assertEqual(content, b'/tagada.mp3\n') - + + class SmartPlaylistCLITest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() From 58fe63764edcac47cd20d9afdc7d8ab40d7a2c73 Mon Sep 17 00:00:00 2001 From: michaelbub Date: Fri, 11 Nov 2016 22:34:46 +0100 Subject: [PATCH 1388/2280] reduced line length --- test/test_smartplaylist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 084e0694d..fa8658ad3 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -150,8 +150,8 @@ class SmartPlaylistTest(unittest.TestCase): spl = SmartPlaylistPlugin() i = Mock(path=b'/tagada.mp3') - title_replacer = lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() - i.evaluate_template.side_effect = title_replacer + i.evaluate_template.side_effect = \ + lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() lib = Mock() lib.replacements = CHAR_REPLACE From d6242ec207b6ae7013394732d8cc332cf9a3fbcd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 11 Nov 2016 20:00:14 -0500 Subject: [PATCH 1389/2280] Tiny whitespace fix --- test/test_smartplaylist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index fa8658ad3..5e1fed084 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -151,7 +151,7 @@ class SmartPlaylistTest(unittest.TestCase): i = Mock(path=b'/tagada.mp3') i.evaluate_template.side_effect = \ - lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() + lambda pl, _: pl.replace(b'$title', b'ta:ga:da').decode() lib = Mock() lib.replacements = CHAR_REPLACE From 88c7043b2f55608a108a0fc3e9a37902089b8709 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 11 Nov 2016 20:00:36 -0500 Subject: [PATCH 1390/2280] Reclassify a feature as a bug fix --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 02054e87c..607746c4a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -32,8 +32,6 @@ Deprecated configuration optional removals: The are a couple of small new features: -* :doc:`/plugins/smartplaylist`: Playlist names will be sanitized to - ensure valid filenames. :bug:`2258` * :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option is not set, these plugins will now look for the ``$MPD_HOST`` environment variable before falling back to ``localhost``. Thanks to :user:`tarruda`. @@ -88,6 +86,8 @@ And there are a few bug fixes too: :bug:`2228`. * :doc:`/plugins/missing`: ``missing`` is now treated as an integer, allowing the use of (for example) ranges in queries. +* :doc:`/plugins/smartplaylist`: Playlist names will be sanitized to + ensure valid filenames. :bug:`2258` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From d53b677e0f9e4618dd605c55dc51372ed8e06071 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sun, 13 Nov 2016 00:20:01 +0100 Subject: [PATCH 1391/2280] convert: initial cleanup of convert_func Get cli options and configuration in a more readable, uniform way --- beetsplug/convert.py | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 9b7f49e36..a9a3dcf62 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -385,25 +385,21 @@ class ConvertPlugin(BeetsPlugin): util.copy(album.artpath, dest) def convert_func(self, lib, opts, args): - if not opts.dest: - opts.dest = self.config['dest'].get() - if not opts.dest: + dest = opts.dest or self.config['dest'].get() + if not dest: raise ui.UserError(u'no convert destination set') - opts.dest = util.bytestring_path(opts.dest) + dest = util.bytestring_path(dest) - if not opts.threads: - opts.threads = self.config['threads'].get(int) + threads = opts.threads or self.config['threads'].get(int) - if self.config['paths']: - path_formats = ui.get_path_formats(self.config['paths']) + path_formats = ui.get_path_formats(self.config['paths'] or None) + + fmt = opts.format or self.config['format'].as_str().lower() + + if opts.pretend is not None: + pretend = opts.pretend else: - path_formats = ui.get_path_formats() - - if not opts.format: - opts.format = self.config['format'].as_str().lower() - - pretend = opts.pretend if opts.pretend is not None else \ - self.config['pretend'].get(bool) + pretend = self.config['pretend'].get(bool) if not pretend: ui.commands.list_items(lib, ui.decargs(args), opts.album) @@ -416,16 +412,15 @@ class ConvertPlugin(BeetsPlugin): items = (i for a in albums for i in a.items()) if self.config['copy_album_art']: for album in albums: - self.copy_album_art(album, opts.dest, path_formats, - pretend) + self.copy_album_art(album, dest, path_formats, pretend) else: items = iter(lib.items(ui.decargs(args))) - convert = [self.convert_item(opts.dest, + convert = [self.convert_item(dest, opts.keep_new, path_formats, - opts.format, + fmt, pretend) - for _ in range(opts.threads)] + for _ in range(threads)] pipe = util.pipeline.Pipeline([items, convert]) pipe.run_parallel() From 2e78628507386d759dab8ea1e55d7ef23b9fa69b Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sun, 13 Nov 2016 00:23:03 +0100 Subject: [PATCH 1392/2280] convert: Don't ask for confirmation if query result is empty --- beetsplug/convert.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index a9a3dcf62..6639eb7b1 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -401,27 +401,35 @@ class ConvertPlugin(BeetsPlugin): else: pretend = self.config['pretend'].get(bool) - if not pretend: - ui.commands.list_items(lib, ui.decargs(args), opts.album) - - if not (opts.yes or ui.input_yn(u"Convert? (Y/n)")): - return - if opts.album: albums = lib.albums(ui.decargs(args)) - items = (i for a in albums for i in a.items()) - if self.config['copy_album_art']: - for album in albums: - self.copy_album_art(album, dest, path_formats, pretend) + items = [i for a in albums for i in a.items()] + if not pretend: + for a in albums: + ui.print_(format(a, u'')) else: - items = iter(lib.items(ui.decargs(args))) + items = list(lib.items(ui.decargs(args))) + if not pretend: + for i in items: + ui.print_(format(i, u'')) + + if not items: + self._log.error(u'Empty query result.') + return + if not (pretend or opts.yes or ui.input_yn(u"Convert? (Y/n)")): + return + + if opts.album and self.config['copy_album_art']: + for album in albums: + self.copy_album_art(album, dest, path_formats, pretend) + convert = [self.convert_item(dest, opts.keep_new, path_formats, fmt, pretend) for _ in range(threads)] - pipe = util.pipeline.Pipeline([items, convert]) + pipe = util.pipeline.Pipeline([iter(items), convert]) pipe.run_parallel() def convert_on_import(self, lib, item): From 8067d82be8ba65115fcb86359bf7ccf8b8dc7553 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 13 Nov 2016 17:47:07 +0100 Subject: [PATCH 1393/2280] convert: test for #2260 --- test/test_convert.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 8d75fbb57..6b2ae9259 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -20,7 +20,7 @@ import os.path from test import _common from test._common import unittest from test import helper -from test.helper import control_stdin +from test.helper import control_stdin, capture_log from beets.mediafile import MediaFile from beets import util @@ -215,6 +215,11 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFalse(os.path.exists(converted)) + def test_empty_query(self): + with capture_log('beets.convert') as logs: + self.run_convert('An impossible query') + self.assertEqual(logs[0], u'convert: Empty query result.') + @_common.slow_test() class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, From a0a9f5a7a854a41e8a27a51af8439189c55eadec Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 13 Nov 2016 17:49:18 +0100 Subject: [PATCH 1394/2280] Fix typos in tests --- test/_common.py | 2 +- test/test_convert.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/_common.py b/test/_common.py index 11f71a631..09747e595 100644 --- a/test/_common.py +++ b/test/_common.py @@ -44,7 +44,7 @@ beetsplug.__path__ = [os.path.abspath( RSRC = util.bytestring_path(os.path.join(os.path.dirname(__file__), 'rsrc')) PLUGINPATH = os.path.join(os.path.dirname(__file__), 'rsrc', 'beetsplug') -# Propagate to root loger so nosetest can capture it +# Propagate to root logger so nosetest can capture it log = logging.getLogger('beets') log.propagate = True log.setLevel(logging.DEBUG) diff --git a/test/test_convert.py b/test/test_convert.py index 8d75fbb57..123550e54 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -168,7 +168,7 @@ class ConvertCliTest(unittest.TestCase, TestHelper, ConvertCommand): converted = os.path.join(self.convert_dest, b'converted.mp3') self.assertFileTag(converted, 'mp3') - def test_rejecet_confirmation(self): + def test_reject_confirmation(self): with control_stdin('n'): self.run_convert() converted = os.path.join(self.convert_dest, b'converted.mp3') From 862d89001fae85745e8961bdecf022fff1c43ec2 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 13 Nov 2016 17:47:47 +0100 Subject: [PATCH 1395/2280] convert: changelog for #2262 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 607746c4a..a69f8b5a9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,6 +52,8 @@ The are a couple of small new features: And there are a few bug fixes too: +* :doc:`/plugins/convert`: The plugin no longer asks for confirmation if the + query did not return anything to convert. :bug:`2260` :bug:`2262` * :doc:`/plugins/embedart`: The plugin now uses ``jpg`` as an extension rather than ``jpeg``, to ensure consistency with :doc:`plugins/fetchart`. Thanks to :user:`tweitzel`. :bug:`2254` :bug:`2255` From c3b70b5098e7b1594d1e5e03c7053581d1e08277 Mon Sep 17 00:00:00 2001 From: walt Date: Wed, 16 Nov 2016 11:33:16 +0100 Subject: [PATCH 1396/2280] Removed call to .decode('utf-8') when printing flexible attributes --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c02f6accf..cec502636 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -87,7 +87,7 @@ def _print_keys(query): returned row, with identation of 2 spaces. """ for row in query: - print_(u' ' * 2 + row['key'].decode('utf-8')) + print_(u' ' * 2 + row['key']) def fields_func(lib, opts, args): From dafde564f3ea18655b1e15f410df70d05b3eb8f5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 16 Nov 2016 11:58:18 -0500 Subject: [PATCH 1397/2280] Add __future__ imports to a new module --- beets/util/collections.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beets/util/collections.py b/beets/util/collections.py index 6813b95df..696dc9a98 100644 --- a/beets/util/collections.py +++ b/beets/util/collections.py @@ -12,9 +12,12 @@ # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""Custom collections classes + +"""Custom collections classes. """ +from __future__ import division, absolute_import, print_function + class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all From 4c6bf782a25aa1024b87bec3b6aef1391ddd3dae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 16 Nov 2016 12:01:37 -0500 Subject: [PATCH 1398/2280] Ignore a new flake8 style warning It's always fun when the style checker suddenly decides something new is bad style. :/ --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index d11c57507..913880415 100644 --- a/setup.cfg +++ b/setup.cfg @@ -11,6 +11,7 @@ accept-encodings=utf-8 # - E731: do not assign a lambda expression, use a def # - F405 object may be undefined, or defined from star imports # - C901: function/method complexity +# - E305: spacing after a declaration (might be nice to change eventually) # `flake8-future-import` errors we ignore: # - FI50: `__future__` import "division" present # - FI51: `__future__` import "absolute_import" present @@ -18,4 +19,4 @@ accept-encodings=utf-8 # - FI53: `__future__` import "print_function" present # - FI14: `__future__` import "unicode_literals" missing # - FI15: `__future__` import "generator_stop" missing -ignore=C901,E241,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 +ignore=E305,C901,E241,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 From 62e9a15f4dc69c6fe17abd86c92fc32cdf3d8b29 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 16 Nov 2016 12:03:07 -0500 Subject: [PATCH 1399/2280] Fix a copy n' paste error found by flake8 --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 92757a40a..645d52559 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -230,7 +230,7 @@ class SymbolsReplaced(Backend): '>': 'Greater_Than', '#': 'Number_', r'[\[\{]': '(', - r'[\[\{]': ')' + r'[\]\}]': ')', } @classmethod From b8213181f22185f09206ad09dc231e4902b5be53 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Wed, 16 Nov 2016 23:08:00 +0100 Subject: [PATCH 1400/2280] drop IdentityFallbackDict: Used by mediafile to determine the preferred extension of an image That solution looked cool for 2 days, but in hindsight it was pretty bad --- beets/mediafile.py | 6 +++--- beets/util/collections.py | 30 ------------------------------ 2 files changed, 3 insertions(+), 33 deletions(-) delete mode 100644 beets/util/collections.py diff --git a/beets/mediafile.py b/beets/mediafile.py index 784695c1a..87a9d10a6 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -59,7 +59,6 @@ import enum from beets import logging from beets.util import displayable_path, syspath, as_string -from beets.util.collections import IdentityFallbackDict import six @@ -82,7 +81,7 @@ TYPES = { 'aiff': 'AIFF', } -PREFERRED_IMAGE_EXTENSIONS = IdentityFallbackDict({'jpeg': 'jpg'}) +PREFERRED_IMAGE_EXTENSIONS = {'jpeg': 'jpg'} # Exceptions. @@ -355,7 +354,8 @@ def image_mime_type(data): def image_extension(data): - return PREFERRED_IMAGE_EXTENSIONS[_imghdr_what_wrapper(data)] + ext = _imghdr_what_wrapper(data) + return PREFERRED_IMAGE_EXTENSIONS.get(ext, ext) class ImageType(enum.Enum): diff --git a/beets/util/collections.py b/beets/util/collections.py deleted file mode 100644 index 696dc9a98..000000000 --- a/beets/util/collections.py +++ /dev/null @@ -1,30 +0,0 @@ -# -*- coding: utf-8 -*- -# This file is part of beets. -# Copyright 2016, Adrian Sampson. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - -"""Custom collections classes. -""" - -from __future__ import division, absolute_import, print_function - - -class IdentityFallbackDict(dict): - """A dictionary which is "transparent" (maps keys to themselves) for all - keys not in it. - """ - def __getitem__(self, key): - try: - return dict.__getitem__(self, key) - except KeyError: - return key From 31898111ed89bfe079ccc5db16e55b50f0518d05 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Fri, 18 Nov 2016 01:07:02 +0100 Subject: [PATCH 1401/2280] mediafile: prefer latin-1 encoding for ID3 APIC descriptions. Fixes #899 iTunes has problems with everything but latin-1 Try to use latin-1 if possible and fall back to utf-16. --- beets/mediafile.py | 11 +++++++++- test/test_mediafile_edge.py | 40 +++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 87a9d10a6..1ee778406 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -920,7 +920,16 @@ class MP3ImageStorageStyle(ListStorageStyle, MP3StorageStyle): frame.data = image.data frame.mime = image.mime_type frame.desc = image.desc or u'' - frame.encoding = 3 # UTF-8 encoding of desc + + # For compatibility with OS X/iTunes prefer latin-1 if possible. + # See issue #899 + try: + frame.desc.encode("latin-1") + except UnicodeEncodeError: + frame.encoding = 1 # utf-16 + else: + frame.encoding = 0 # latin-1 if possible + frame.type = image.type_index return frame diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 0be177699..4e61b5336 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -375,30 +375,26 @@ class ID3v23Test(unittest.TestCase, TestHelper): finally: self._delete_test() - def test_v24_image_encoding(self): - mf = self._make_test(id3v23=False) - try: - mf.images = [beets.mediafile.Image(b'test data')] - mf.save() - frame = mf.mgfile.tags.getall('APIC')[0] - self.assertEqual(frame.encoding, 3) - finally: - self._delete_test() + def test_image_encoding(self): + """For compatibility with OS X/iTunes. - @unittest.skip("a bug, see #899") - def test_v23_image_encoding(self): - """For compatibility with OS X/iTunes (and strict adherence to - the standard), ID3v2.3 tags need to use an inferior text - encoding: UTF-8 is not supported. + See https://github.com/beetbox/beets/issues/899#issuecomment-62437773 """ - mf = self._make_test(id3v23=True) - try: - mf.images = [beets.mediafile.Image(b'test data')] - mf.save() - frame = mf.mgfile.tags.getall('APIC')[0] - self.assertEqual(frame.encoding, 1) - finally: - self._delete_test() + + for v23 in [True, False]: + mf = self._make_test(id3v23=v23) + try: + mf.images = [ + beets.mediafile.Image(b'data', desc=u""), + beets.mediafile.Image(b'data', desc=u"foo"), + beets.mediafile.Image(b'data', desc=u"\u0185"), + ] + mf.save() + apic_frames = mf.mgfile.tags.getall('APIC') + encodings = dict([(f.desc, f.encoding) for f in apic_frames]) + self.assertEqual(encodings, {u"": 0, u"foo": 0, u"\u0185": 1}) + finally: + self._delete_test() def suite(): From 31f91129f318404dd905d52ef8e1b04e539b66c5 Mon Sep 17 00:00:00 2001 From: Christoph Reiter Date: Sat, 19 Nov 2016 10:36:31 +0100 Subject: [PATCH 1402/2280] Use mutagen id3 encoding constants --- beets/mediafile.py | 4 ++-- test/test_mediafile_edge.py | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 1ee778406..7d1b07280 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -926,9 +926,9 @@ class MP3ImageStorageStyle(ListStorageStyle, MP3StorageStyle): try: frame.desc.encode("latin-1") except UnicodeEncodeError: - frame.encoding = 1 # utf-16 + frame.encoding = mutagen.id3.Encoding.UTF16 else: - frame.encoding = 0 # latin-1 if possible + frame.encoding = mutagen.id3.Encoding.LATIN1 frame.type = image.type_index return frame diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 4e61b5336..ae758f142 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -19,6 +19,7 @@ from __future__ import division, absolute_import, print_function import os import shutil +import mutagen.id3 from test import _common from test._common import unittest @@ -392,7 +393,11 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf.save() apic_frames = mf.mgfile.tags.getall('APIC') encodings = dict([(f.desc, f.encoding) for f in apic_frames]) - self.assertEqual(encodings, {u"": 0, u"foo": 0, u"\u0185": 1}) + self.assertEqual(encodings, { + u"": mutagen.id3.Encoding.LATIN1, + u"foo": mutagen.id3.Encoding.LATIN1, + u"\u0185": mutagen.id3.Encoding.UTF16, + }) finally: self._delete_test() From 6b0249df0806eae6e4ed28a83a1d1a0c3ba66017 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 19 Nov 2016 16:14:24 -0500 Subject: [PATCH 1403/2280] Changelog for #2270 (fix #899, fix #2264) --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a69f8b5a9..67116f3e7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -90,6 +90,10 @@ And there are a few bug fixes too: the use of (for example) ranges in queries. * :doc:`/plugins/smartplaylist`: Playlist names will be sanitized to ensure valid filenames. :bug:`2258` +* The ID3 APIC tag now uses the Latin-1 encoding when possible instead of a + Unicode encoding. This should increase compatibility with other software, + especially with iTunes and when using ID3v2.3. Thanks to :user:`lazka`. + :bug:`899` :bug:`2264` :bug:`2270` The last release, 1.3.19, also erroneously reported its version as "1.3.18" when you typed ``beet version``. This has been corrected. From 1963b52903be66bdebc72e6c9fe6790e290b69eb Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Mon, 31 Oct 2016 12:53:23 +0100 Subject: [PATCH 1404/2280] acousticbrainz: Initial cleanup --- beetsplug/acousticbrainz.py | 208 ++++++++++++++++++------------------ 1 file changed, 104 insertions(+), 104 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index d1dee855b..712428bc9 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -42,7 +42,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - fetch_info(self._log, items, ui.should_write()) + self._fetch_info(items, ui.should_write()) cmd.func = func return [cmd] @@ -50,119 +50,119 @@ class AcousticPlugin(plugins.BeetsPlugin): def import_task_files(self, session, task): """Function is called upon beet import. """ + self._fetch_info(task.imported_items(), False) - items = task.imported_items() - fetch_info(self._log, items, False) + def _fetch_info(self, items, write): + """Get data from AcousticBrainz for the items. + """ - -def fetch_info(log, items, write): - """Get data from AcousticBrainz for the items. - """ - - def get_value(*map_path): - try: - return reduce(operator.getitem, map_path, data) - except KeyError: - log.debug(u'Invalid Path: {}', map_path) - - for item in items: - if item.mb_trackid: - log.info(u'getting data for: {}', item) - - # Fetch the data from the AB API. - urls = [generate_url(item.mb_trackid, path) for path in LEVELS] - log.debug(u'fetching URLs: {}', ' '.join(urls)) + def get_value(*map_path): try: - res = [requests.get(url) for url in urls] + return reduce(operator.getitem, map_path, data) + except KeyError: + log.debug(u'Invalid Path: {}', map_path) + + for item in (item for item in items if item.mb_trackid): + self._log.info(u'getting data for: {}', item) + data = self._get_data(item.mb_trackid) + if data: + # Get each field and assign it on the item. + item.danceable = get_value( + "highlevel", "danceability", "all", "danceable", + ) + item.gender = get_value( + "highlevel", "gender", "value", + ) + item.genre_rosamerica = get_value( + "highlevel", "genre_rosamerica", "value" + ) + item.mood_acoustic = get_value( + "highlevel", "mood_acoustic", "all", "acoustic" + ) + item.mood_aggressive = get_value( + "highlevel", "mood_aggressive", "all", "aggressive" + ) + item.mood_electronic = get_value( + "highlevel", "mood_electronic", "all", "electronic" + ) + item.mood_happy = get_value( + "highlevel", "mood_happy", "all", "happy" + ) + item.mood_party = get_value( + "highlevel", "mood_party", "all", "party" + ) + item.mood_relaxed = get_value( + "highlevel", "mood_relaxed", "all", "relaxed" + ) + item.mood_sad = get_value( + "highlevel", "mood_sad", "all", "sad" + ) + item.rhythm = get_value( + "highlevel", "ismir04_rhythm", "value" + ) + item.tonal = get_value( + "highlevel", "tonal_atonal", "all", "tonal" + ) + item.voice_instrumental = get_value( + "highlevel", "voice_instrumental", "value" + ) + item.average_loudness = get_value( + "lowlevel", "average_loudness" + ) + item.bpm = get_value( + "rhythm", "bpm" + ) + item.chords_changes_rate = get_value( + "tonal", "chords_changes_rate" + ) + item.chords_key = get_value( + "tonal", "chords_key" + ) + item.chords_number_rate = get_value( + "tonal", "chords_number_rate" + ) + item.chords_scale = get_value( + "tonal", "chords_scale" + ) + item.initial_key = '{} {}'.format( + get_value("tonal", "key_key"), + get_value("tonal", "key_scale") + ) + item.key_strength = get_value( + "tonal", "key_strength" + ) + + # Store the data. + item.store() + if write: + item.try_write() + + def _get_data(self, mbid): + data = {} + for url in _generate_urls(mbid): + self._log.debug(u'fetching URL: {}', url) + + try: + res = requests.get(url) except requests.RequestException as exc: - log.info(u'request error: {}', exc) - continue + self._log.info(u'request error: {}', exc) + return {} - # Check for missing tracks. - if any(r.status_code == 404 for r in res): - log.info(u'recording ID {} not found', item.mb_trackid) - continue + if res.status_code == 404: + self._log.info(u'recording ID {} not found', mbid) + return {} - # Parse the JSON response. try: - data = res[0].json() - data.update(res[1].json()) + data.update(res.json()) except ValueError: - log.debug(u'Invalid Response: {} & {}', [r.text for r in res]) + self._log.debug(u'Invalid Response: {}', res.text) + return {} - # Get each field and assign it on the item. - item.danceable = get_value( - "highlevel", "danceability", "all", "danceable", - ) - item.gender = get_value( - "highlevel", "gender", "value", - ) - item.genre_rosamerica = get_value( - "highlevel", "genre_rosamerica", "value" - ) - item.mood_acoustic = get_value( - "highlevel", "mood_acoustic", "all", "acoustic" - ) - item.mood_aggressive = get_value( - "highlevel", "mood_aggressive", "all", "aggressive" - ) - item.mood_electronic = get_value( - "highlevel", "mood_electronic", "all", "electronic" - ) - item.mood_happy = get_value( - "highlevel", "mood_happy", "all", "happy" - ) - item.mood_party = get_value( - "highlevel", "mood_party", "all", "party" - ) - item.mood_relaxed = get_value( - "highlevel", "mood_relaxed", "all", "relaxed" - ) - item.mood_sad = get_value( - "highlevel", "mood_sad", "all", "sad" - ) - item.rhythm = get_value( - "highlevel", "ismir04_rhythm", "value" - ) - item.tonal = get_value( - "highlevel", "tonal_atonal", "all", "tonal" - ) - item.voice_instrumental = get_value( - "highlevel", "voice_instrumental", "value" - ) - item.average_loudness = get_value( - "lowlevel", "average_loudness" - ) - item.bpm = get_value( - "rhythm", "bpm" - ) - item.chords_changes_rate = get_value( - "tonal", "chords_changes_rate" - ) - item.chords_key = get_value( - "tonal", "chords_key" - ) - item.chords_number_rate = get_value( - "tonal", "chords_number_rate" - ) - item.chords_scale = get_value( - "tonal", "chords_scale" - ) - item.initial_key = '{} {}'.format( - get_value("tonal", "key_key"), - get_value("tonal", "key_scale") - ) - item.key_strength = get_value( - "tonal", "key_strength" - ) - - # Store the data. - item.store() - if write: - item.try_write() + return data -def generate_url(mbid, level): +def _generate_urls(mbid): """Generates AcousticBrainz end point url for given MBID. """ - return ACOUSTIC_BASE + mbid + level + for level in LEVELS: + yield ACOUSTIC_BASE + mbid + level From 7a676400dc13e2815fa6510aee547bf50a3aa60e Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Mon, 31 Oct 2016 12:58:42 +0100 Subject: [PATCH 1405/2280] acousticbrainz: Refactor the json handling part --- beetsplug/acousticbrainz.py | 209 +++++++++++++++++++++--------------- 1 file changed, 122 insertions(+), 87 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 712428bc9..26e001d16 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -18,13 +18,90 @@ from __future__ import division, absolute_import, print_function import requests -import operator +from collections import defaultdict +from beets.util.collections import DefaultList from beets import plugins, ui -from functools import reduce ACOUSTIC_BASE = "https://acousticbrainz.org/" LEVELS = ["/low-level", "/high-level"] +ABSCHEME = { + 'highlevel': { + 'danceability': { + 'all': { + 'danceable': 'danceable' + } + }, + 'gender': { + 'value': 'gender' + }, + 'genre_rosamerica': { + 'value': 'genre_rosamerica' + }, + 'mood_acoustic': { + 'all': { + 'acoustic': 'mood_acoustic' + } + }, + 'mood_aggressive': { + 'all': { + 'aggressive': 'mood_aggressive' + } + }, + 'mood_electronic': { + 'all': { + 'electronic': 'mood_electronic' + } + }, + 'mood_happy': { + 'all': { + 'happy': 'mood_happy' + } + }, + 'mood_party': { + 'all': { + 'party': 'mood_party' + } + }, + 'mood_relaxed': { + 'all': { + 'relaxed': 'mood_relaxed' + } + }, + 'mood_sad': { + 'all': { + 'sad': 'mood_sad' + } + }, + 'ismir04_rhythm': { + 'value': 'rhythm' + }, + 'tonal_atonal': { + 'all': { + 'tonal': 'tonal' + } + }, + 'voice_instrumental': { + 'value': 'voice_instrumental' + }, + }, + 'lowlevel': { + 'average_loudness': 'average_loudness' + }, + 'rhythm': { + 'bpm': 'bpm' + }, + 'tonal': { + 'chords_changes_rate': 'chords_changes_rate', + 'chords_key': 'chords_key', + 'chords_number_rate': 'chords_number_rate', + 'chords_scale': 'chords_scale', + 'key_key': ('initial_key', 0), + 'key_scale': ('initial_key', 1), + 'key_strength': 'key_strength' + + } +} class AcousticPlugin(plugins.BeetsPlugin): @@ -52,91 +129,6 @@ class AcousticPlugin(plugins.BeetsPlugin): """ self._fetch_info(task.imported_items(), False) - def _fetch_info(self, items, write): - """Get data from AcousticBrainz for the items. - """ - - def get_value(*map_path): - try: - return reduce(operator.getitem, map_path, data) - except KeyError: - log.debug(u'Invalid Path: {}', map_path) - - for item in (item for item in items if item.mb_trackid): - self._log.info(u'getting data for: {}', item) - data = self._get_data(item.mb_trackid) - if data: - # Get each field and assign it on the item. - item.danceable = get_value( - "highlevel", "danceability", "all", "danceable", - ) - item.gender = get_value( - "highlevel", "gender", "value", - ) - item.genre_rosamerica = get_value( - "highlevel", "genre_rosamerica", "value" - ) - item.mood_acoustic = get_value( - "highlevel", "mood_acoustic", "all", "acoustic" - ) - item.mood_aggressive = get_value( - "highlevel", "mood_aggressive", "all", "aggressive" - ) - item.mood_electronic = get_value( - "highlevel", "mood_electronic", "all", "electronic" - ) - item.mood_happy = get_value( - "highlevel", "mood_happy", "all", "happy" - ) - item.mood_party = get_value( - "highlevel", "mood_party", "all", "party" - ) - item.mood_relaxed = get_value( - "highlevel", "mood_relaxed", "all", "relaxed" - ) - item.mood_sad = get_value( - "highlevel", "mood_sad", "all", "sad" - ) - item.rhythm = get_value( - "highlevel", "ismir04_rhythm", "value" - ) - item.tonal = get_value( - "highlevel", "tonal_atonal", "all", "tonal" - ) - item.voice_instrumental = get_value( - "highlevel", "voice_instrumental", "value" - ) - item.average_loudness = get_value( - "lowlevel", "average_loudness" - ) - item.bpm = get_value( - "rhythm", "bpm" - ) - item.chords_changes_rate = get_value( - "tonal", "chords_changes_rate" - ) - item.chords_key = get_value( - "tonal", "chords_key" - ) - item.chords_number_rate = get_value( - "tonal", "chords_number_rate" - ) - item.chords_scale = get_value( - "tonal", "chords_scale" - ) - item.initial_key = '{} {}'.format( - get_value("tonal", "key_key"), - get_value("tonal", "key_scale") - ) - item.key_strength = get_value( - "tonal", "key_strength" - ) - - # Store the data. - item.store() - if write: - item.try_write() - def _get_data(self, mbid): data = {} for url in _generate_urls(mbid): @@ -160,6 +152,49 @@ class AcousticPlugin(plugins.BeetsPlugin): return data + def _fetch_info(self, items, write): + """Get data from AcousticBrainz for the items. + """ + for item in (item for item in items if item.mb_trackid): + self._log.info(u'getting data for: {}', item) + data = self._get_data(item.mb_trackid) + if data: + # Get each field and assign it on the item. + for attr, val in self._map_dict_to_scheme(data, ABSCHEME): + self._log.debug(u'attribute {} of {} set to {}', + attr, + item, + val) + setattr(item, attr, val) + # Store the data. + item.store() + if write: + item.try_write() + + def _map_dict_to_scheme(self, + d, + s, + composites=defaultdict(lambda: DefaultList('')), + root=True): + for k, v in s.items(): + if k in d: + if type(v) == dict: + for yielded in self._map_dict_to_scheme(d[k], + v, + composites, + root=False): + yield yielded + elif type(v) == tuple: + composites.setdefault(v[0], DefaultList(''))[v[1]] = d[k] + else: + yield (v, d[k]) + else: + self._log.debug(u'Data {} could not be mapped to scheme {} ' + u'because key {} was not found', d, v, k) + if root: + for k, v in composites.items(): + yield k, ' '.join(v) + def _generate_urls(mbid): """Generates AcousticBrainz end point url for given MBID. From 3979619f9f94be85fbf1ccf5300bb9c6da3b5a96 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 31 Oct 2016 18:52:35 +0100 Subject: [PATCH 1406/2280] acousticbrainz: remove redundant comments --- beetsplug/acousticbrainz.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 26e001d16..5223602a1 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -159,14 +159,12 @@ class AcousticPlugin(plugins.BeetsPlugin): self._log.info(u'getting data for: {}', item) data = self._get_data(item.mb_trackid) if data: - # Get each field and assign it on the item. for attr, val in self._map_dict_to_scheme(data, ABSCHEME): self._log.debug(u'attribute {} of {} set to {}', attr, item, val) setattr(item, attr, val) - # Store the data. item.store() if write: item.try_write() From 324c67191d6c4fff628819a9f8f5121ce97fdba1 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 31 Oct 2016 18:54:14 +0100 Subject: [PATCH 1407/2280] acousticbrainz: log fetched attributes and values as info --- beetsplug/acousticbrainz.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 5223602a1..2ec765992 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -160,10 +160,10 @@ class AcousticPlugin(plugins.BeetsPlugin): data = self._get_data(item.mb_trackid) if data: for attr, val in self._map_dict_to_scheme(data, ABSCHEME): - self._log.debug(u'attribute {} of {} set to {}', - attr, - item, - val) + self._log.info(u'attribute {} of {} set to {}', + attr, + item, + val) setattr(item, attr, val) item.store() if write: From 1d972b99075b2263f2bcbb92f70d0dce2ac578b7 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 31 Oct 2016 18:55:55 +0100 Subject: [PATCH 1408/2280] acousticbrainz: rewrite _map_dict_to_scheme: * Less lazy names * Separate root function from childs more naturally * Actually use defaultdict --- beetsplug/acousticbrainz.py | 120 +++++++++++++++++++++++++++++------- 1 file changed, 99 insertions(+), 21 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 2ec765992..b70bc59b7 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -153,13 +153,16 @@ class AcousticPlugin(plugins.BeetsPlugin): return data def _fetch_info(self, items, write): - """Get data from AcousticBrainz for the items. + """Fetch additional information from AcousticBrainz for the `item`s. """ - for item in (item for item in items if item.mb_trackid): + for item in items: + if not item.mb_trackid: + continue + self._log.info(u'getting data for: {}', item) data = self._get_data(item.mb_trackid) if data: - for attr, val in self._map_dict_to_scheme(data, ABSCHEME): + for attr, val in self._map_data_to_scheme(data, ABSCHEME): self._log.info(u'attribute {} of {} set to {}', attr, item, @@ -169,33 +172,108 @@ class AcousticPlugin(plugins.BeetsPlugin): if write: item.try_write() - def _map_dict_to_scheme(self, - d, - s, - composites=defaultdict(lambda: DefaultList('')), - root=True): - for k, v in s.items(): - if k in d: + def _map_data_to_scheme(self, data, scheme): + """Given `data` as a structure of nested dictionaries, and `scheme` as a + structure of nested dictionaries , `yield` tuples `(attr, val)` where + `attr` and `val` are corresponding leaf nodes in `scheme` and `data`. + + As its name indicates, `scheme` defines how the data is structured, + so this function tries to find leaf nodes in `data` that correspond + to the leafs nodes of `scheme`, and not the other way around. + Leaf nodes of `data` that do not exist in the `scheme` do not matter. + If a leaf node of `scheme` is not present in `data`, + no value is yielded for that attribute and a simple warning is issued. + + Finally, to account for attributes of which the value is split between + several leaf nodes in `data`, leaf nodes of `scheme` can be tuples + `(attr, order)` where `attr` is the attribute to which the leaf node + belongs, and `order` is the place at which it should appear in the + value. The different `value`s belonging to the same `attr` are simply + joined with `' '`. This is hardcoded and not very flexible, but it gets + the job done. + + Example: + >>> scheme = { + 'key1': 'attribute', + 'key group': { + 'subkey1': 'subattribute', + 'subkey2': ('composite attribute', 0) + }, + 'key2': ('composite attribute', 1) + } + >>> data = { + 'key1': 'value', + 'key group': { + 'subkey1': 'subvalue', + 'subkey2': 'part 1 of composite attr' + }, + 'key2': 'part 2' + } + >>> print(list(_map_data_to_scheme(data, scheme))) + [('subattribute', 'subvalue'), + ('attribute', 'value'), + ('composite attribute', 'part 1 of composite attr part 2')] + """ + """First, we traverse `scheme` and `data`, `yield`ing all the non + composites attributes straight away and populating the dictionary + `composites` with the composite attributes. + + When we are finished traversing `scheme`, `composites` should map + each composite attribute to an ordered list of the values belonging to + the attribute, for example: + `composites = {'initial_key': ['B', 'minor']}`. + + composites is a `defaultdict` of `DefaultList`s (defined below). + It is a `defaultdict` by pure convenience. It holds `DefaultList`s + because the values of a composite attribute can be inserted out of + order, and we do not know the final length of a composite attribute in + advance. So, if we have + `composites = {}` + and then + `composites['initial_key'][1] = 'minor'` + happens, we want the result to be: + `composites = {'initial_key': ['', 'minor']}` + """ + composites = defaultdict(lambda: DefaultList('')) + # The recursive traversal + for attr, val in self._data_to_scheme_child(data, + scheme, + composites): + yield attr, val + """When composites has been populated, yield the composite attributes + by joining their parts. + """ + for composite_attr, value_parts in composites.items(): + yield composite_attr, ' '.join(value_parts) + + def _data_to_scheme_child(self, subdata, subscheme, composites): + """The recursive business logic of :meth:`_map_data_to_scheme`: + Traverse two structures of nested dictionaries in parallel and `yield` + tuples of corresponding leaf nodes. + + If a leaf node belongs to a composite attribute (is a `tuple`), + populate `composites` rather than yielding straight away. + All the child functions for a single traversal share the same + `composites` instance, which is passed along. + """ + for k, v in subscheme.items(): + if k in subdata: if type(v) == dict: - for yielded in self._map_dict_to_scheme(d[k], - v, - composites, - root=False): + for yielded in self._data_to_scheme_child(subdata[k], + v, + composites): yield yielded elif type(v) == tuple: - composites.setdefault(v[0], DefaultList(''))[v[1]] = d[k] + composites[v[0]][v[1]] = subdata[k] else: - yield (v, d[k]) + yield v, subdata[k] else: self._log.debug(u'Data {} could not be mapped to scheme {} ' - u'because key {} was not found', d, v, k) - if root: - for k, v in composites.items(): - yield k, ' '.join(v) + u'because key {} was not found', subdata, v, k) def _generate_urls(mbid): - """Generates AcousticBrainz end point url for given MBID. + """Generates AcousticBrainz end point urls for given `mbid`. """ for level in LEVELS: yield ACOUSTIC_BASE + mbid + level From 4586e2df5a8026d1d6fe82f9e45c05b26119964d Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 5 Nov 2016 01:30:46 +0100 Subject: [PATCH 1409/2280] acousticbrainz: Add unit tests --- test/test_acousticbrainz.py | 87 +++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 test/test_acousticbrainz.py diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py new file mode 100644 index 000000000..ae56f781f --- /dev/null +++ b/test/test_acousticbrainz.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Nathan Dwek. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests for the 'acousticbrainz' plugin. +""" + +from __future__ import absolute_import, print_function + +from test._common import unittest + +from beetsplug.acousticbrainz import DefaultList, AcousticPlugin + + +class DefaultListTest(unittest.TestCase): + def test_getitem(self): + default_list = DefaultList('foo') + default_value = default_list[2] + self.assertEqual(default_value, 'foo') + self.assertEqual(default_list, ['foo', 'foo', 'foo']) + + def test_setitem(self): + default_list = DefaultList('foo') + default_list[2] = 'bar' + self.assertEqual(default_list, ['foo', 'foo', 'bar']) + default_list[1] = 'baz' + self.assertEqual(default_list, ['foo', 'baz', 'bar']) + + +class MapDataToSchemeTest(unittest.TestCase): + def test_basic(self): + ab = AcousticPlugin() + data = {'key 1': 'value 1', 'key 2': 'value 2'} + scheme = {'key 1': 'attribute 1', 'key 2': 'attribute 2'} + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute 1', 'value 1'), + ('attribute 2', 'value 2')}) + + def test_recurse(self): + ab = AcousticPlugin() + data = { + 'key': 'value', + 'group': { + 'subkey': 'subvalue', + 'subgroup': { + 'subsubkey': 'subsubvalue' + } + } + } + scheme = { + 'key': 'attribute 1', + 'group': { + 'subkey': 'attribute 2', + 'subgroup': { + 'subsubkey': 'attribute 3' + } + } + } + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute 1', 'value'), + ('attribute 2', 'subvalue'), + ('attribute 3', 'subsubvalue')}) + + def test_composite(self): + ab = AcousticPlugin() + data = {'key 1': 'part 1', 'key 2': 'part 2'} + scheme = {'key 1': ('attribute', 0), 'key 2': ('attribute', 1)} + mapping = set(ab._map_data_to_scheme(data, scheme)) + self.assertEqual(mapping, {('attribute', 'part 1 part 2')}) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') From 51243240f62b76b4bd8a7666892d14eb2493afa7 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 5 Nov 2016 13:42:42 +0100 Subject: [PATCH 1410/2280] acousticbrainz: Test _map_data_to_scheme with real data --- test/rsrc/acousticbrainz/data.json | 4115 ++++++++++++++++++++++++++++ test/test_acousticbrainz.py | 38 +- 2 files changed, 4151 insertions(+), 2 deletions(-) create mode 100644 test/rsrc/acousticbrainz/data.json diff --git a/test/rsrc/acousticbrainz/data.json b/test/rsrc/acousticbrainz/data.json new file mode 100644 index 000000000..1a89c9a99 --- /dev/null +++ b/test/rsrc/acousticbrainz/data.json @@ -0,0 +1,4115 @@ +{ + "tonal":{ + "thpcp":[ + 1, + 0.638657510281, + 0.293813556433, + 0.259863913059, + 0.21968896687, + 0.218203336, + 0.252398610115, + 0.22969686985, + 0.447383195162, + 0.749422073364, + 0.580664932728, + 0.310822367668, + 0.238883554935, + 0.178785249591, + 0.194924846292, + 0.299323320389, + 0.282649427652, + 0.18946044147, + 0.181915551424, + 0.231100782752, + 0.554247200489, + 0.831909179688, + 0.589426040649, + 0.387799620628, + 0.422363936901, + 0.429372549057, + 0.408978521824, + 0.326897829771, + 0.266663640738, + 0.429461866617, + 0.633336126804, + 0.477401226759, + 0.261826515198, + 0.238164439797, + 0.287726253271, + 0.690547764301 + ], + "chords_number_rate":0.00194468453992, + "chords_scale":"minor", + "chords_changes_rate":0.0445116683841, + "key_strength":0.636936545372, + "tuning_diatonic_strength":0.495492935181, + "hpcp_entropy":{ + "min":0, + "max":4.48086500168, + "dvar2":0.867867648602, + "median":2.02990412712, + "dmean2":1.14721953869, + "dmean":0.68769723177, + "var":0.635742008686, + "dvar":0.33780092001, + "mean":2.00384068489 + }, + "key_scale":"minor", + "chords_strength":{ + "min":0.24240244925, + "max":0.793840110302, + "dvar2":9.58399032243e-05, + "median":0.586153388023, + "dmean2":0.0106231365353, + "dmean":0.00929547380656, + "var":0.00910324696451, + "dvar":6.61800950184e-05, + "mean":0.576524615288 + }, + "key_key":"A", + "tuning_nontempered_energy_ratio":0.721719145775, + "tuning_equal_tempered_deviation":0.0515233427286, + "chords_histogram":[ + 56.2445983887, + 8.10285186768, + 1.79343128204, + 0.0864304229617, + 0, + 0.605012953281, + 2.20397591591, + 12.1650819778, + 0.0216076057404, + 0.0216076057404, + 0, + 0, + 0, + 0, + 0, + 0, + 2.67934322357, + 0.21607606113, + 10.8686256409, + 0, + 2.07433009148, + 0.0864304229617, + 0.648228168488, + 2.1823682785 + ], + "chords_key":"A", + "tuning_frequency":441.272583008, + "hpcp":{ + "min":[ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "max":[ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "dvar2":[ + 0.159377709031, + 0.118723139167, + 0.0969077348709, + 0.0841393470764, + 0.0857475027442, + 0.0681946650147, + 0.0922033339739, + 0.0763805955648, + 0.08953332901, + 0.134413808584, + 0.117157392204, + 0.0784328207374, + 0.0576078519225, + 0.0540019907057, + 0.0537950210273, + 0.0788798704743, + 0.0758254900575, + 0.0659088715911, + 0.0595937520266, + 0.0897909551859, + 0.117696471512, + 0.141075149179, + 0.116812512279, + 0.143778041005, + 0.157332316041, + 0.206293225288, + 0.187901929021, + 0.16186593473, + 0.119209326804, + 0.107413217425, + 0.119033068419, + 0.101279519498, + 0.102868333459, + 0.108767814934, + 0.105039291084, + 0.133028581738 + ], + "median":[ + 0.200053632259, + 0.138681918383, + 0.0352100357413, + 0.0198299698532, + 0.0150980614126, + 0.0205171480775, + 0.026256872341, + 0.0286095552146, + 0.0424337461591, + 0.0602139532566, + 0.0744276791811, + 0.0494470596313, + 0.0350396670401, + 0.0212194472551, + 0.0196186862886, + 0.0201223343611, + 0.0170610919595, + 0.0120322443545, + 0.0105668697506, + 0.0191436801106, + 0.0846247002482, + 0.135070502758, + 0.113241240382, + 0.0424886606634, + 0.0378469713032, + 0.02946896106, + 0.0286043733358, + 0.0198593121022, + 0.0253958441317, + 0.0672319456935, + 0.0957452505827, + 0.0639808028936, + 0.026175301522, + 0.0180807597935, + 0.0324410535395, + 0.125212281942 + ], + "dmean2":[ + 0.353859990835, + 0.294070899487, + 0.217189013958, + 0.180236533284, + 0.162956178188, + 0.144071772695, + 0.172789543867, + 0.171253859997, + 0.22391949594, + 0.284728109837, + 0.274570196867, + 0.198656648397, + 0.154297873378, + 0.124744221568, + 0.124510832131, + 0.157537952065, + 0.158150732517, + 0.135058999062, + 0.123808719218, + 0.177607372403, + 0.277576059103, + 0.324962347746, + 0.298212528229, + 0.308668285608, + 0.311420857906, + 0.344731658697, + 0.335885316133, + 0.283822774887, + 0.227637752891, + 0.252195805311, + 0.288448363543, + 0.249307155609, + 0.212308287621, + 0.205825775862, + 0.223324626684, + 0.315198987722 + ], + "dmean":[ + 0.206140458584, + 0.16949801147, + 0.121237404644, + 0.101308584213, + 0.0920756608248, + 0.0820758640766, + 0.0983714461327, + 0.0957674309611, + 0.130757495761, + 0.167563140392, + 0.159212738276, + 0.113431841135, + 0.0875298455358, + 0.0698468312621, + 0.0709747001529, + 0.092557400465, + 0.0927894487977, + 0.0761438235641, + 0.0697580873966, + 0.0992580577731, + 0.162719354033, + 0.194310605526, + 0.174188151956, + 0.171439617872, + 0.174783751369, + 0.191449582577, + 0.185274213552, + 0.155063658953, + 0.124152831733, + 0.143824338913, + 0.167870178819, + 0.144021183252, + 0.116702638566, + 0.112653404474, + 0.125104308128, + 0.184472203255 + ], + "var":[ + 0.143021538854, + 0.0637424811721, + 0.0320195667446, + 0.037381041795, + 0.0286979582161, + 0.0301742851734, + 0.0303927082568, + 0.0223984327167, + 0.052778493613, + 0.13409627974, + 0.0731517747045, + 0.0302681028843, + 0.0220995694399, + 0.0194978509098, + 0.0208596177399, + 0.0510722063482, + 0.0462048053741, + 0.0236530210823, + 0.0288583170623, + 0.0295663233846, + 0.0644663274288, + 0.119045428932, + 0.0609758161008, + 0.0493184439838, + 0.0607626289129, + 0.070556551218, + 0.0664848089218, + 0.0493576526642, + 0.0335861295462, + 0.0447917319834, + 0.0859667509794, + 0.0526875928044, + 0.0304508917034, + 0.0315008088946, + 0.0328483134508, + 0.0794815197587 + ], + "dvar":[ + 0.0686646401882, + 0.0436623394489, + 0.0358338914812, + 0.0332863405347, + 0.0316647030413, + 0.027725789696, + 0.0338032282889, + 0.0273791830987, + 0.0345646068454, + 0.0615020208061, + 0.0457257218659, + 0.0297911148518, + 0.0221415478736, + 0.0201385207474, + 0.0201426595449, + 0.033235758543, + 0.0318886972964, + 0.0243560094386, + 0.0229729004204, + 0.0327679589391, + 0.0460740588605, + 0.0626438856125, + 0.0435314439237, + 0.0521778166294, + 0.0578555390239, + 0.0772548541427, + 0.0728902295232, + 0.05926451087, + 0.0424739196897, + 0.0389089211822, + 0.0483759790659, + 0.0381603203714, + 0.036982499063, + 0.0398408733308, + 0.0387278683484, + 0.0517609193921 + ], + "mean":[ + 0.366864055395, + 0.234300479293, + 0.107789635658, + 0.0953347310424, + 0.080595985055, + 0.0800509601831, + 0.0925959795713, + 0.084267526865, + 0.164128810167, + 0.274936020374, + 0.213025093079, + 0.114029549062, + 0.0876377895474, + 0.0655898824334, + 0.0715109184384, + 0.109810970724, + 0.103693917394, + 0.0695062279701, + 0.0667382776737, + 0.0847825706005, + 0.203333377838, + 0.305197566748, + 0.216239228845, + 0.142269745469, + 0.154950141907, + 0.157521352172, + 0.15003952384, + 0.119927063584, + 0.0978293046355, + 0.157554119825, + 0.232348263264, + 0.175141349435, + 0.0960547402501, + 0.0873739719391, + 0.105556420982, + 0.253337144852 + ] + } + }, + "rhythm":{ + "bpm_histogram_second_peak_bpm":{ + "min":167, + "max":167, + "dvar2":0, + "median":167, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":167 + }, + "bpm_histogram_second_peak_spread":{ + "min":0, + "max":0, + "dvar2":0, + "median":0, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0 + }, + "beats_count":577, + "beats_loudness":{ + "min":4.48232695405e-09, + "max":0.181520029902, + "dvar2":0.00434844521806, + "median":0.0302296206355, + "dmean2":0.0709233134985, + "dmean":0.0362482257187, + "var":0.0014705004869, + "dvar":0.00124853104353, + "mean":0.0407853461802 + }, + "bpm":162.532119751, + "bpm_histogram_first_peak_spread":{ + "min":0.164835140109, + "max":0.164835140109, + "dvar2":0, + "median":0.164835140109, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.164835140109 + }, + "danceability":1.14192211628, + "bpm_histogram_first_peak_bpm":{ + "min":161, + "max":161, + "dvar2":0, + "median":161, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":161 + }, + "beats_loudness_band_ratio":{ + "min":[ + 0.00683269277215, + 0.00988945644349, + 0.00177479430567, + 0.000523661612533, + 0.000248342636041, + 0.00070228939876 + ], + "max":[ + 0.970164954662, + 0.725397408009, + 0.739950060844, + 0.658194899559, + 0.676319360733, + 0.622089266777 + ], + "dvar2":[ + 0.0699004009366, + 0.0290632098913, + 0.035205449909, + 0.0226975940168, + 0.0168868545443, + 0.0086750369519 + ], + "median":[ + 0.619332075119, + 0.176913484931, + 0.0926762372255, + 0.0303400773555, + 0.0398489944637, + 0.0262520890683 + ], + "dmean2":[ + 0.369491040707, + 0.230186283588, + 0.192849993706, + 0.106605380774, + 0.107576675713, + 0.0616580061615 + ], + "dmean":[ + 0.207789510489, + 0.129003107548, + 0.110624760389, + 0.0578341074288, + 0.0602345280349, + 0.035002540797 + ], + "var":[ + 0.0565228238702, + 0.0165011454374, + 0.0193302389234, + 0.0086074648425, + 0.00634109321982, + 0.00296737346798 + ], + "dvar":[ + 0.0250691790134, + 0.00962078291923, + 0.0126609709114, + 0.00782771967351, + 0.00567667419091, + 0.00305109703913 + ], + "mean":[ + 0.577607989311, + 0.195795580745, + 0.138790622354, + 0.0610357522964, + 0.065284781158, + 0.04240244627 + ] + }, + "onset_rate":5.17941665649, + "beats_position":[ + 0.383129239082, + 0.789478421211, + 1.16099774837, + 1.53251695633, + 1.90403628349, + 2.27555561066, + 2.6470746994, + 3.01859402657, + 3.39011335373, + 3.76163268089, + 4.13315200806, + 4.5046710968, + 4.87619018555, + 5.24770975113, + 5.60761880875, + 5.9675283432, + 6.33904743195, + 6.71056699753, + 7.08208608627, + 7.45360517502, + 7.81351470947, + 8.17342376709, + 8.54494285583, + 8.91646194458, + 9.287981987, + 9.64789104462, + 10.0194101334, + 10.379319191, + 10.7508392334, + 11.110748291, + 11.4822673798, + 11.8421764374, + 12.2136955261, + 12.5852155685, + 12.9567346573, + 13.3166437149, + 13.6765527725, + 14.0364627838, + 14.3963718414, + 14.7678909302, + 15.1394100189, + 15.5109291077, + 15.870839119, + 16.2307472229, + 16.602268219, + 16.9621772766, + 17.3220863342, + 17.693605423, + 18.0535144806, + 18.4134235382, + 18.7733325958, + 19.1332416534, + 19.4931507111, + 19.853061676, + 20.2245807648, + 20.5844898224, + 20.9560089111, + 21.3159179688, + 21.6874370575, + 22.0473461151, + 22.4072551727, + 22.7787742615, + 23.1386852264, + 23.4985942841, + 23.8701133728, + 24.2416324615, + 24.6131515503, + 24.984670639, + 25.3561897278, + 25.7277088165, + 26.0992279053, + 26.4591369629, + 26.830657959, + 27.2021770477, + 27.5736961365, + 27.9452152252, + 28.316734314, + 28.6766433716, + 29.0481624603, + 29.4196815491, + 29.7912006378, + 30.1627197266, + 30.5342407227, + 30.9057598114, + 31.265668869, + 31.6255779266, + 31.9854869843, + 32.3453979492, + 32.6704750061, + 33.0071640015, + 33.3554649353, + 33.7153739929, + 34.0868911743, + 34.4351921082, + 34.8067131042, + 35.1898422241, + 35.5961914062, + 35.9793205261, + 36.362449646, + 36.7339668274, + 37.1054878235, + 37.4886169434, + 37.8601341248, + 38.2316551208, + 38.6147842407, + 38.9863014221, + 39.3578224182, + 39.7293434143, + 40.1124725342, + 40.4723815918, + 40.8438987732, + 41.2154197693, + 41.5869369507, + 41.9584579468, + 42.3299751282, + 42.7014961243, + 43.0730133057, + 43.4445343018, + 43.8160552979, + 44.1875724792, + 44.5590934753, + 44.9306106567, + 45.3021316528, + 45.6736488342, + 46.0335578918, + 46.3934669495, + 46.7533760071, + 47.1132888794, + 47.4848060608, + 47.8563270569, + 48.2394561768, + 48.6225852966, + 48.994102478, + 49.3656234741, + 49.748752594, + 50.1318817139, + 50.5033988953, + 50.8749198914, + 51.2580490112, + 51.6411781311, + 52.0126991272, + 52.3842163086, + 52.7557373047, + 53.1272544861, + 53.4987754822, + 53.8702926636, + 54.2534217834, + 54.6365509033, + 55.0080718994, + 55.3795890808, + 55.7511100769, + 56.122631073, + 56.4941482544, + 56.8656692505, + 57.2487983704, + 57.6203155518, + 58.0034446716, + 58.3749656677, + 58.7464828491, + 59.1180038452, + 59.4895210266, + 59.8610420227, + 60.2325630188, + 60.6040802002, + 60.9756011963, + 61.3471183777, + 61.7186393738, + 62.0901565552, + 62.4616775513, + 62.8331947327, + 63.2163238525, + 63.5994529724, + 63.9709739685, + 64.3424911499, + 64.714012146, + 65.0855331421, + 65.4570541382, + 65.8285675049, + 66.200088501, + 66.5716094971, + 66.9431304932, + 67.3146438599, + 67.686164856, + 68.0344696045, + 68.4175949097, + 68.8007278442, + 69.1722412109, + 69.5321502686, + 69.8920593262, + 70.2635803223, + 70.6351013184, + 70.995010376, + 71.3549194336, + 71.7264404297, + 72.1095657349, + 72.481086731, + 72.8642196655, + 73.2357330322, + 73.6072540283, + 73.9787750244, + 74.3502960205, + 74.7218093872, + 75.1049423218, + 75.488067627, + 75.859588623, + 76.2311096191, + 76.6026306152, + 76.9741516113, + 77.345664978, + 77.7171859741, + 78.1003189087, + 78.4834442139, + 78.85496521, + 79.2264862061, + 79.5979995728, + 79.9695205688, + 80.3410415649, + 80.712562561, + 81.0840835571, + 81.4555969238, + 81.8271179199, + 82.198638916, + 82.5701599121, + 82.9416732788, + 83.3131942749, + 83.684715271, + 84.0678405762, + 84.4509735107, + 84.8224945068, + 85.1824035645, + 85.5423126221, + 85.9138336182, + 86.2853469849, + 86.656867981, + 87.0283889771, + 87.3999099731, + 87.7714233398, + 88.1429443359, + 88.514465332, + 88.8859863281, + 89.2575073242, + 89.6290206909, + 89.9889297485, + 90.3488388062, + 90.7203598022, + 91.0918807983, + 91.451789856, + 91.8116989136, + 92.1832199097, + 92.5547409058, + 92.9262542725, + 93.2861633301, + 93.6460723877, + 94.0175933838, + 94.3891143799, + 94.760635376, + 95.1205444336, + 95.4804534912, + 95.8403625488, + 96.2002716064, + 96.5717926025, + 96.9433059692, + 97.3148269653, + 97.6863479614, + 98.0578689575, + 98.4293823242, + 98.8009033203, + 99.1724243164, + 99.532333374, + 99.9038543701, + 100.263763428, + 100.635284424, + 101.006797791, + 101.378318787, + 101.738227844, + 102.098136902, + 102.469657898, + 102.841178894, + 103.21269989, + 103.584213257, + 103.944122314, + 104.304031372, + 104.675552368, + 105.047073364, + 105.406982422, + 105.766891479, + 106.138412476, + 106.509933472, + 106.881446838, + 107.252967834, + 107.624488831, + 107.984397888, + 108.355918884, + 108.715827942, + 109.087341309, + 109.458862305, + 109.818771362, + 110.17868042, + 110.538589478, + 110.898498535, + 111.270019531, + 111.641540527, + 112.001449585, + 112.361358643, + 112.732879639, + 113.104400635, + 113.464309692, + 113.82421875, + 114.184127808, + 114.544036865, + 114.915550232, + 115.287071228, + 115.658592224, + 116.006889343, + 116.366798401, + 116.726707458, + 117.086616516, + 117.446525574, + 117.794830322, + 118.15473938, + 118.514648438, + 118.886169434, + 119.269294739, + 119.652427673, + 120.035552979, + 120.418685913, + 120.813423157, + 121.2081604, + 121.602897644, + 121.997642517, + 122.380767822, + 122.763900757, + 123.147026062, + 123.530158997, + 123.92489624, + 124.319633484, + 124.69115448, + 125.085891724, + 125.480628967, + 125.863761902, + 126.246894836, + 126.630020142, + 127.013153076, + 127.396278381, + 127.779411316, + 128.17414856, + 128.568893433, + 128.963623047, + 129.346755981, + 129.729888916, + 130.113006592, + 130.496139526, + 130.867660522, + 131.239181519, + 131.610702515, + 131.982223511, + 132.353744507, + 132.725265503, + 133.09677124, + 133.456680298, + 133.816589355, + 134.188110352, + 134.559631348, + 134.931152344, + 135.30267334, + 135.674194336, + 136.045715332, + 136.417236328, + 136.788757324, + 137.160263062, + 137.520172119, + 137.880081177, + 138.251602173, + 138.623123169, + 138.994644165, + 139.366165161, + 139.737686157, + 140.109207153, + 140.480728149, + 140.852249146, + 141.223754883, + 141.595275879, + 141.943572998, + 142.315093994, + 142.675003052, + 143.034912109, + 143.406433105, + 143.777954102, + 144.149475098, + 144.520996094, + 144.89251709, + 145.264038086, + 145.635559082, + 146.007064819, + 146.378585815, + 146.750106812, + 147.121627808, + 147.493148804, + 147.8646698, + 148.236190796, + 148.607711792, + 148.979232788, + 149.362350464, + 149.745483398, + 150.117004395, + 150.488525391, + 150.860046387, + 151.231567383, + 151.603088379, + 151.974594116, + 152.346115112, + 152.717636108, + 153.089157104, + 153.460678101, + 153.832199097, + 154.203720093, + 154.575241089, + 154.946762085, + 155.318267822, + 155.689788818, + 156.061309814, + 156.432830811, + 156.804351807, + 157.175872803, + 157.547393799, + 157.918914795, + 158.290420532, + 158.661941528, + 159.033462524, + 159.404983521, + 159.776504517, + 160.148025513, + 160.519546509, + 160.891067505, + 161.262588501, + 161.634094238, + 162.005615234, + 162.37713623, + 162.737045288, + 163.096954346, + 163.468475342, + 163.839996338, + 164.211517334, + 164.58303833, + 164.954559326, + 165.326080322, + 165.674377441, + 166.045898438, + 166.417419434, + 166.788925171, + 167.160446167, + 167.531967163, + 167.903488159, + 168.275009155, + 168.646530151, + 169.018051147, + 169.389572144, + 169.772689819, + 170.155822754, + 170.52734375, + 170.898864746, + 171.270385742, + 171.641906738, + 172.025024414, + 172.408157349, + 172.779678345, + 173.151199341, + 173.522720337, + 173.894241333, + 174.265762329, + 174.637283325, + 175.032012939, + 175.415145874, + 175.798278809, + 176.169799805, + 176.541305542, + 176.9012146, + 177.272735596, + 177.632644653, + 178.004165649, + 178.375686646, + 178.747207642, + 179.130340576, + 179.513473511, + 179.884979248, + 180.256500244, + 180.62802124, + 180.999542236, + 181.382675171, + 181.754196167, + 182.137313843, + 182.508834839, + 182.880355835, + 183.251876831, + 183.623397827, + 183.994918823, + 184.378051758, + 184.761169434, + 185.13269043, + 185.504211426, + 185.875732422, + 186.247253418, + 186.618774414, + 186.99029541, + 187.361816406, + 187.733337402, + 188.10484314, + 188.476364136, + 188.847885132, + 189.219406128, + 189.590927124, + 189.96244812, + 190.345581055, + 190.72869873, + 191.100219727, + 191.471740723, + 191.843261719, + 192.214782715, + 192.597915649, + 192.981033325, + 193.352554321, + 193.724075317, + 194.095596313, + 194.478729248, + 194.861862183, + 195.23336792, + 195.604888916, + 195.976409912, + 196.347930908, + 196.719451904, + 197.0909729, + 197.474105835, + 197.857223511, + 198.228744507, + 198.600265503, + 198.971786499, + 199.343307495, + 199.714828491, + 200.086349487, + 200.457870483, + 200.829391479, + 201.200897217, + 201.572418213, + 201.943939209, + 202.303848267, + 202.663757324, + 203.03527832, + 203.406799316, + 203.778320312, + 204.149841309, + 204.521362305, + 204.892883301, + 205.264389038, + 205.647521973, + 206.030654907, + 206.402175903, + 206.773696899, + 207.145217896, + 207.516723633, + 207.888244629, + 208.259765625, + 208.631286621, + 209.002807617, + 209.385940552, + 209.757461548, + 210.128982544, + 210.500488281, + 210.883621216, + 211.255142212, + 211.626663208, + 212.009796143, + 212.392913818, + 212.776046753, + 213.170791626, + 213.565536499, + 213.971878052, + 214.378234863 + ], + "bpm_histogram_second_peak_weight":{ + "min":0.163194447756, + "max":0.163194447756, + "dvar2":0, + "median":0.163194447756, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.163194447756 + }, + "bpm_histogram_first_peak_weight":{ + "min":0.659722208977, + "max":0.659722208977, + "dvar2":0, + "median":0.659722208977, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":0.659722208977 + } + }, + "lowlevel":{ + "spectral_complexity":{ + "min":0, + "max":51, + "dvar2":34.109500885, + "median":15, + "dmean2":5.03252983093, + "dmean":3.31208133698, + "var":108.135475159, + "dvar":16.1623840332, + "mean":15.1260938644 + }, + "silence_rate_20dB":{ + "min":1, + "max":1, + "dvar2":0, + "median":1, + "dmean2":0, + "dmean":0, + "var":0, + "dvar":0, + "mean":1 + }, + "average_loudness":0.815025985241, + "erbbands_spread":{ + "min":0.907018482685, + "max":163.113571167, + "dvar2":511.106719971, + "median":34.9861183167, + "dmean2":17.4016342163, + "dmean":11.4227361679, + "var":572.351501465, + "dvar":220.769592285, + "mean":39.7502365112 + }, + "spectral_kurtosis":{ + "min":-1.22816824913, + "max":77.2247085571, + "dvar2":28.6044521332, + "median":4.62249898911, + "dmean2":4.51546525955, + "dmean":2.82785224915, + "var":33.1767959595, + "dvar":13.1654214859, + "mean":6.00768327713 + }, + "barkbands_kurtosis":{ + "min":-1.96124887466, + "max":732.31427002, + "dvar2":588.577392578, + "median":2.02856016159, + "dmean2":8.05669307709, + "dmean":5.11299228668, + "var":374.321380615, + "dvar":247.842544556, + "mean":7.06718301773 + }, + "spectral_strongpeak":{ + "min":1.71490974199e-10, + "max":16.1200447083, + "dvar2":3.3518705368, + "median":0.39955753088, + "dmean2":0.941311240196, + "dmean":0.545010268688, + "var":2.96148967743, + "dvar":1.33243703842, + "mean":0.93408870697 + }, + "spectral_spread":{ + "min":1388334.875, + "max":41575076, + "dvar2":1619247235070.0, + "median":3420763.25, + "dmean2":983456.875, + "dmean":732694.4375, + "var":4945877663740.0, + "dvar":854983901184, + "mean":4104934.25 + }, + "spectral_rms":{ + "min":3.15950651059e-12, + "max":0.0132316453382, + "dvar2":3.71212809114e-06, + "median":0.00425734650344, + "dmean2":0.0013317943085, + "dmean":0.000880118692294, + "var":5.96411746301e-06, + "dvar":1.66359927789e-06, + "mean":0.0039903158322 + }, + "erbbands":{ + "min":[ + 1.77816177391e-22, + 1.16505097519e-21, + 1.25622764484e-20, + 2.42817334007e-20, + 1.54258117469e-20, + 1.0398112018e-19, + 1.45132858053e-19, + 2.45289269564e-19, + 4.01068342766e-19, + 8.21050273636e-19, + 3.81530310848e-19, + 8.81511903137e-19, + 1.07499647945e-18, + 8.4783438187e-19, + 1.00474413342e-18, + 2.63416224414e-18, + 2.7020495774e-18, + 3.62243276547e-18, + 3.19863277569e-18, + 3.43176763428e-18, + 6.46998299903e-18, + 5.15079866686e-18, + 8.52004633608e-18, + 1.02257547977e-17, + 1.00997123247e-17, + 1.05472856921e-17, + 1.00685656659e-17, + 1.10003920706e-17, + 1.51110777052e-17, + 1.5046216819e-17, + 1.31580720189e-17, + 1.30844504628e-17, + 1.13508668418e-17, + 1.02681982621e-17, + 8.04728449187e-18, + 4.73097927698e-18, + 2.75997186582e-18, + 1.08864568334e-18, + 2.8601904839e-19, + 3.5584382605e-20 + ], + "max":[ + 2.05614852905, + 10.580906868, + 60.5060195923, + 152.843505859, + 450.042755127, + 175.338409424, + 237.807418823, + 238.884460449, + 443.897521973, + 525.930541992, + 518.611022949, + 1031.67468262, + 954.232910156, + 1123.45935059, + 556.857299805, + 356.125640869, + 342.635467529, + 1293.60327148, + 1103.80981445, + 1287.36242676, + 2169.76928711, + 1266.18579102, + 601.754516602, + 1258.96850586, + 444.097320557, + 240.62600708, + 303.504180908, + 56.5521354675, + 72.2374343872, + 85.4121780396, + 25.407957077, + 19.8146400452, + 46.2547264099, + 16.3226490021, + 16.8903636932, + 5.15064907074, + 0.893250703812, + 0.284754753113, + 0.106889992952, + 0.00452945847064 + ], + "dvar2":[ + 0.0137821119279, + 4.26913785934, + 97.7259292603, + 622.611999512, + 3656.42504883, + 376.053527832, + 307.56942749, + 320.293243408, + 2445.90405273, + 1300.15063477, + 729.621582031, + 2693.6159668, + 2013.25512695, + 3353.13598633, + 573.952941895, + 269.22253418, + 457.528259277, + 1406.78710938, + 1557.82128906, + 793.165527344, + 5019.24316406, + 4039.60839844, + 970.312316895, + 1538.21313477, + 721.875244141, + 195.41003418, + 88.4793777466, + 31.4306335449, + 42.7237434387, + 32.8801956177, + 6.04226541519, + 1.52690029144, + 1.47338938713, + 0.542356073856, + 0.211627364159, + 0.0269440039992, + 0.00465576630086, + 0.000269315525657, + 1.98406451091e-05, + 4.38383267465e-08 + ], + "median":[ + 0.00466703856364, + 0.101253904402, + 1.64267027378, + 5.13034963608, + 6.49109458923, + 4.258228302, + 3.18711066246, + 4.03815889359, + 7.81102657318, + 7.54452610016, + 5.75877952576, + 8.21393203735, + 11.6316785812, + 9.69087696075, + 4.23464298248, + 1.69191777706, + 2.67072510719, + 4.43968248367, + 4.24516201019, + 7.75287914276, + 16.0199928284, + 12.5332527161, + 9.28721427917, + 9.18504428864, + 6.87661838531, + 4.15781497955, + 3.11850094795, + 0.707400023937, + 0.422007799149, + 0.326348185539, + 0.171605303884, + 0.0764799118042, + 0.0530340671539, + 0.0369812250137, + 0.0170799326152, + 0.00388540537097, + 0.000607917027082, + 0.000106923354906, + 2.54503829638e-05, + 2.41674279096e-05 + ], + "dmean2":[ + 0.0468679144979, + 1.00080478191, + 4.60071754456, + 11.530172348, + 27.0302009583, + 10.1726131439, + 8.18716049194, + 9.02602672577, + 21.6493034363, + 17.5054721832, + 11.9851293564, + 23.2072429657, + 23.1678962708, + 24.8249855042, + 9.62737751007, + 5.9968290329, + 8.08820819855, + 12.5483970642, + 11.0777654648, + 12.6770420074, + 31.1724281311, + 22.2209968567, + 15.6441850662, + 17.6994724274, + 11.4936075211, + 6.59135293961, + 5.08022689819, + 2.30506944656, + 2.95904040337, + 2.46585559845, + 1.15297198296, + 0.531184136868, + 0.382049500942, + 0.275081396103, + 0.141834661365, + 0.0498343594372, + 0.0225136969239, + 0.00503297196701, + 0.000977287418209, + 5.82068387303e-05 + ], + "dmean":[ + 0.0350424982607, + 0.580041825771, + 2.61035442352, + 6.80757236481, + 16.318693161, + 6.28967905045, + 5.23286628723, + 5.70099258423, + 13.4230766296, + 10.8768568039, + 7.74926900864, + 15.0034389496, + 15.0271100998, + 16.6018199921, + 6.02632713318, + 3.79855132103, + 5.38237333298, + 8.43670463562, + 7.43314123154, + 8.2191324234, + 20.6921386719, + 13.7538080215, + 9.77100944519, + 11.3139772415, + 7.25735664368, + 4.1218457222, + 3.17433810234, + 1.45581579208, + 1.87883663177, + 1.61556243896, + 0.779599308968, + 0.371349811554, + 0.264476120472, + 0.193502560258, + 0.100708886981, + 0.0353026203811, + 0.0144239943475, + 0.00325388251804, + 0.000670222449116, + 3.95594870497e-05 + ], + "var":[ + 0.0116662262008, + 1.27503490448, + 25.6204109192, + 206.069885254, + 1430.30371094, + 234.442382812, + 206.473526001, + 288.805267334, + 1444.05480957, + 817.272949219, + 625.690795898, + 2697.92749023, + 2397.11669922, + 7130.13330078, + 515.86315918, + 346.633789062, + 809.448486328, + 2584.76660156, + 2616.26757812, + 3138.03320312, + 20583.1132812, + 3381.78515625, + 1288.27880859, + 2477.11401367, + 682.099060059, + 216.604751587, + 97.8326339722, + 13.7823019028, + 19.9818115234, + 16.6690158844, + 4.43811273575, + 1.2346996069, + 1.27807950974, + 0.517578363419, + 0.177246898413, + 0.0190207827836, + 0.00211605615914, + 0.000168058744748, + 1.65621640917e-05, + 3.32350325039e-08 + ], + "dvar":[ + 0.00734147289768, + 1.59334981441, + 34.9658050537, + 236.386993408, + 1519.1640625, + 157.498901367, + 126.366111755, + 127.708183289, + 921.020629883, + 497.140319824, + 303.813903809, + 1122.60107422, + 868.916992188, + 1545.74194336, + 241.721923828, + 118.562904358, + 218.458129883, + 734.227844238, + 762.639587402, + 405.900024414, + 2714.4777832, + 1520.69287109, + 428.032836914, + 696.146972656, + 272.255096436, + 80.3479690552, + 38.2512245178, + 12.4188299179, + 17.8483753204, + 13.7868928909, + 2.77658462524, + 0.731714189053, + 0.67433899641, + 0.263227701187, + 0.108624838293, + 0.0132785160094, + 0.00197272375226, + 0.000125091624795, + 1.03948887045e-05, + 2.18264126772e-08 + ], + "mean":[ + 0.0470404699445, + 0.51214581728, + 2.94917726517, + 8.56711673737, + 16.8939933777, + 9.74743175507, + 8.58794498444, + 10.7102499008, + 23.4056625366, + 18.6381034851, + 13.9866991043, + 27.1086997986, + 28.1797733307, + 34.376159668, + 10.7114057541, + 6.6013917923, + 10.7804918289, + 16.5257949829, + 15.1251926422, + 19.3569641113, + 49.2880210876, + 27.8654499054, + 20.180316925, + 22.9017887115, + 15.1088733673, + 8.45034122467, + 5.79618597031, + 1.91187810898, + 2.04077577591, + 1.82269322872, + 0.964613378048, + 0.475511223078, + 0.359998822212, + 0.270887732506, + 0.138232842088, + 0.0431671403348, + 0.0138024548069, + 0.00314460648224, + 0.000714557303581, + 5.64505244256e-05 + ] + }, + "zerocrossingrate":{ + "min":0.00244140625, + "max":0.525390625, + "dvar2":0.000216632659431, + "median":0.04736328125, + "dmean2":0.0121012274176, + "dmean":0.0100563038141, + "var":0.00131242838688, + "dvar":0.000186675912119, + "mean":0.0536084286869 + }, + "spectral_contrast_coeffs":{ + "min":[ + -0.981265366077, + -0.957678437233, + -0.97364538908, + -0.967074155807, + -0.96257597208, + -0.963937044144 + ], + "max":[ + -0.232828617096, + -0.450794398785, + -0.464783608913, + -0.367899239063, + -0.556100070477, + -0.624147236347 + ], + "dvar2":[ + 0.0063711241819, + 0.00358002260327, + 0.00270585925318, + 0.0017158848932, + 0.00113679806236, + 0.00189194327686 + ], + "median":[ + -0.592801511288, + -0.736532092094, + -0.745844006538, + -0.781389117241, + -0.797656714916, + -0.772757589817 + ], + "dmean2":[ + 0.0916584655643, + 0.074229337275, + 0.0648957416415, + 0.0500396862626, + 0.0380141288042, + 0.0374387130141 + ], + "dmean":[ + 0.0592447705567, + 0.0465519614518, + 0.0414465926588, + 0.0322540737689, + 0.024834824726, + 0.0243127625436 + ], + "var":[ + 0.00911337323487, + 0.00655136583373, + 0.00618056347594, + 0.00577284349129, + 0.00380114861764, + 0.00231571029872 + ], + "dvar":[ + 0.00270068016835, + 0.00148758781143, + 0.00118501938414, + 0.000784370582551, + 0.000524090020917, + 0.000761664705351 + ], + "mean":[ + -0.594863533974, + -0.735448241234, + -0.745020091534, + -0.775078713894, + -0.790849328041, + -0.779701292515 + ] + }, + "dissonance":{ + "min":0.155567497015, + "max":0.500000119209, + "dvar2":0.0011708199745, + "median":0.469446510077, + "dmean2":0.0329371914268, + "dmean":0.0200165640563, + "var":0.00120261416305, + "dvar":0.000480501999846, + "mean":0.460001558065 + }, + "spectral_energyband_high":{ + "min":7.11060368084e-21, + "max":0.00607443926856, + "dvar2":2.99654345781e-07, + "median":0.000152749445988, + "dmean2":0.000292699754937, + "dmean":0.000196773456992, + "var":2.3810963512e-07, + "dvar":1.35860290129e-07, + "mean":0.000318794423947 + }, + "gfcc":{ + "mean":[ + -75.1009368896, + 108.134063721, + -114.922393799, + 35.9068107605, + -53.9456176758, + -7.74362421036, + -37.9716300964, + 9.9239988327, + -24.244802475, + -10.4905223846, + -23.3989257812, + -9.61326217651, + -9.66184806824 + ], + "icov":[ + [ + 8.00217167125e-05, + -0.00014524954895, + 0.000159682429512, + -0.000167002261151, + 9.01917956071e-05, + -0.000181695446372, + 0.000171542298631, + -0.000129780688439, + 0.000197500339709, + -0.000278050283669, + 0.000315256824251, + -0.000206819575396, + 0.000114160277008 + ], + [ + -0.00014524954895, + 0.00178359099664, + -0.000247094896622, + 0.00111800106242, + -0.000636783661321, + 0.000774645654019, + -0.000396145915147, + 0.000103466474684, + -0.00112135277595, + 0.00229536322877, + -0.00234188255854, + 0.00232740258798, + -0.00131408020388 + ], + [ + 0.000159682429512, + -0.000247094896622, + 0.00116660131607, + -0.000234406528762, + 0.000154832057888, + -0.00112980930135, + 0.000650760543067, + -5.60496459912e-07, + 0.000167754784343, + -0.000856044876855, + 0.0014209097717, + -0.00128671491984, + 0.00078388658585 + ], + [ + -0.000167002261151, + 0.00111800106242, + -0.000234406528762, + 0.00312983314507, + -0.000794405816123, + -0.00058439996792, + 2.24104460358e-05, + 0.000424961413955, + -0.00152624503244, + 0.00239069177769, + -0.00202889670618, + 0.00110484787729, + -0.00148455286399 + ], + [ + 9.01917956071e-05, + -0.000636783661321, + 0.000154832057888, + -0.000794405816123, + 0.00397709663957, + -0.000828172138426, + -0.000291677570203, + -0.000975954462774, + 0.00101370830089, + -0.00107421039138, + -0.000894718454219, + 0.00066822959343, + -0.000943991879467 + ], + [ + -0.000181695446372, + 0.000774645654019, + -0.00112980930135, + -0.00058439996792, + -0.000828172138426, + 0.00597975216806, + -0.00177403702401, + -0.000384801533073, + 0.00153620564379, + -0.00195281521883, + 0.00158954621293, + 0.000321330269799, + 0.000257747073192 + ], + [ + 0.000171542298631, + -0.000396145915147, + 0.000650760543067, + 2.24104460358e-05, + -0.000291677570203, + -0.00177403702401, + 0.0080866701901, + -0.00180288043339, + 7.330061635e-05, + 0.00111615261994, + -0.0011511715129, + -0.000984402606264, + 0.000181279159733 + ], + [ + -0.000129780688439, + 0.000103466474684, + -5.60496459912e-07, + 0.000424961413955, + -0.000975954462774, + -0.000384801533073, + -0.00180288043339, + 0.00851836241782, + -0.00320849893615, + 0.00141180318315, + -0.00124999764375, + 0.000833041733131, + -0.00159861764405 + ], + [ + 0.000197500339709, + -0.00112135277595, + 0.000167754784343, + -0.00152624503244, + 0.00101370830089, + 0.00153620564379, + 7.330061635e-05, + -0.00320849893615, + 0.0134673845023, + -0.00816399604082, + 0.00590222747996, + -0.00234723254107, + -0.000930359237827 + ], + [ + -0.000278050283669, + 0.00229536322877, + -0.000856044876855, + 0.00239069177769, + -0.00107421039138, + -0.00195281521883, + 0.00111615261994, + 0.00141180318315, + -0.00816399604082, + 0.0195522867143, + -0.0122134555131, + 0.00327054248191, + 0.000577625120059 + ], + [ + 0.000315256824251, + -0.00234188255854, + 0.0014209097717, + -0.00202889670618, + -0.000894718454219, + 0.00158954621293, + -0.0011511715129, + -0.00124999764375, + 0.00590222747996, + -0.0122134555131, + 0.021111080423, + -0.00721056666225, + 0.00365835893899 + ], + [ + -0.000206819575396, + 0.00232740258798, + -0.00128671491984, + 0.00110484787729, + 0.00066822959343, + 0.000321330269799, + -0.000984402606264, + 0.000833041733131, + -0.00234723254107, + 0.00327054248191, + -0.00721056666225, + 0.015932681039, + -0.00565396249294 + ], + [ + 0.000114160277008, + -0.00131408020388, + 0.00078388658585, + -0.00148455286399, + -0.000943991879467, + 0.000257747073192, + 0.000181279159733, + -0.00159861764405, + -0.000930359237827, + 0.000577625120059, + 0.00365835893899, + -0.00565396249294, + 0.0153731228784 + ] + ], + "cov":[ + [ + 21821.4921875, + 1302.12060547, + -2790.62133789, + 583.293151855, + 63.9840736389, + 26.9333572388, + -119.419998169, + 277.984161377, + -110.454193115, + -76.0569458008, + -16.7917041779, + -162.89515686, + 121.933448792 + ], + [ + 1302.12060547, + 1445.02355957, + -661.351135254, + -311.094665527, + 156.139587402, + -306.730987549, + 60.9609375, + 92.3673324585, + 3.47471880913, + -108.692207336, + 66.6088409424, + -147.776809692, + 75.2410125732 + ], + [ + -2790.62133789, + -661.351135254, + 1889.47399902, + 92.8338088989, + -92.8102874756, + 368.803192139, + -78.5678482056, + -95.1785125732, + 24.1375102997, + 86.254699707, + -94.2749252319, + 117.902046204, + -80.0259933472 + ], + [ + 583.293151855, + -311.094665527, + 92.8338088989, + 515.187255859, + 60.5850448608, + 128.642654419, + -2.62003684044, + 6.46807575226, + 13.7108755112, + -3.07335114479, + -7.74705600739, + 28.8581352234, + 29.7626171112 + ], + [ + 63.9840736389, + 156.139587402, + -92.8102874756, + 60.5850448608, + 339.564758301, + 28.9691524506, + 45.5025405884, + 54.3213920593, + -9.63641166687, + 12.0036411285, + 43.2324829102, + -22.4280166626, + 29.361246109 + ], + [ + 26.9333572388, + -306.730987549, + 368.803192139, + 128.642654419, + 28.9691524506, + 324.149993896, + 20.1203899384, + -3.79410982132, + -15.0688257217, + 43.0340042114, + -26.3511829376, + 28.6324996948, + -22.8170604706 + ], + [ + -119.419998169, + 60.9609375, + -78.5678482056, + -2.62003684044, + 45.5025405884, + 20.1203899384, + 155.001724243, + 42.1054992676, + -1.47882866859, + -8.76181983948, + 19.2513332367, + 2.83816099167, + 11.5606393814 + ], + [ + 277.984161377, + 92.3673324585, + -95.1785125732, + 6.46807575226, + 54.3213920593, + -3.79410982132, + 42.1054992676, + 155.586120605, + 33.8702697754, + -2.8296790123, + 9.17068958282, + -6.04741716385, + 28.1404056549 + ], + [ + -110.454193115, + 3.47471880913, + 24.1375102997, + 13.7108755112, + -9.63641166687, + -15.0688257217, + -1.47882866859, + 33.8702697754, + 114.661575317, + 34.3392486572, + -7.06085252762, + 10.0253458023, + 15.4272651672 + ], + [ + -76.0569458008, + -108.692207336, + 86.254699707, + -3.07335114479, + 12.0036411285, + 43.0340042114, + -8.76181983948, + -2.8296790123, + 34.3392486572, + 112.38079071, + 43.6220817566, + 14.6831378937, + -20.7214431763 + ], + [ + -16.7917041779, + 66.6088409424, + -94.2749252319, + -7.74705600739, + 43.2324829102, + -26.3511829376, + 19.2513332367, + 9.17068958282, + -7.06085252762, + 43.6220817566, + 99.527053833, + 15.1529960632, + -6.4773888588 + ], + [ + -162.89515686, + -147.776809692, + 117.902046204, + 28.8581352234, + -22.4280166626, + 28.6324996948, + 2.83816099167, + -6.04741716385, + 10.0253458023, + 14.6831378937, + 15.1529960632, + 101.876480103, + 16.7505264282 + ], + [ + 121.933448792, + 75.2410125732, + -80.0259933472, + 29.7626171112, + 29.361246109, + -22.8170604706, + 11.5606393814, + 28.1404056549, + 15.4272651672, + -20.7214431763, + -6.4773888588, + 16.7505264282, + 91.9189758301 + ] + ] + }, + "spectral_flux":{ + "min":6.40516528705e-11, + "max":0.355690479279, + "dvar2":0.00278266565874, + "median":0.0625253766775, + "dmean2":0.0423415489495, + "dmean":0.0282820314169, + "var":0.00376007612795, + "dvar":0.00135926820803, + "mean":0.0749769806862 + }, + "silence_rate_30dB":{ + "min":0, + "max":1, + "dvar2":0.0354892387986, + "median":1, + "dmean2":0.0246406570077, + "dmean":0.0123189976439, + "var":0.00654759025201, + "dvar":0.0121672395617, + "mean":0.993408977985 + }, + "spectral_energyband_middle_high":{ + "min":1.27805372214e-21, + "max":0.0389622859657, + "dvar2":9.42645056057e-06, + "median":0.00293085677549, + "dmean2":0.00200005969964, + "dmean":0.00133119279053, + "var":2.5883437047e-05, + "dvar":4.14980877395e-06, + "mean":0.00445337453857 + }, + "barkbands_spread":{ + "min":0.167884364724, + "max":139.821090698, + "dvar2":253.175750732, + "median":18.0125980377, + "dmean2":10.9470348358, + "dmean":6.75650119781, + "var":180.234161377, + "dvar":101.147232056, + "mean":20.320306778 + }, + "spectral_centroid":{ + "min":111.030769348, + "max":11065.2148438, + "dvar2":701335.5625, + "median":1143.22497559, + "dmean2":567.022827148, + "dmean":354.07824707, + "var":626410.0625, + "dvar":292997.4375, + "mean":1266.39624023 + }, + "pitch_salience":{ + "min":0.103756688535, + "max":0.928133249283, + "dvar2":0.013650230132, + "median":0.569122076035, + "dmean2":0.124187774956, + "dmean":0.0767409279943, + "var":0.0128469280899, + "dvar":0.00529233785346, + "mean":0.566493272781 + }, + "erbbands_skewness":{ + "min":-8.09688186646, + "max":6.17588758469, + "dvar2":1.00871086121, + "median":0.283587485552, + "dmean2":0.786845207214, + "dmean":0.512230575085, + "var":1.42545306683, + "dvar":0.427418738604, + "mean":0.235957682133 + }, + "erbbands_crest":{ + "min":2.31988024712, + "max":34.2482185364, + "dvar2":16.2832355499, + "median":8.70411396027, + "dmean2":4.28936433792, + "dmean":2.70263242722, + "var":24.3617858887, + "dvar":6.85065603256, + "mean":9.92293930054 + }, + "melbands":{ + "min":[ + 1.7312522864e-24, + 4.69779527492e-24, + 4.46513652814e-24, + 3.32025441336e-24, + 6.6967940523e-24, + 5.54350662457e-24, + 5.62380004294e-24, + 7.24197266845e-24, + 4.37425935743e-24, + 6.31036856572e-24, + 4.53679113075e-24, + 3.08454218323e-24, + 4.01757944901e-24, + 5.05271286808e-24, + 5.25895581858e-24, + 3.18568913964e-24, + 7.13208118891e-24, + 4.5636159514e-24, + 5.04583400098e-24, + 6.17228950832e-24, + 6.96855978959e-24, + 4.44096109684e-24, + 6.9472211021e-24, + 7.30462636813e-24, + 7.82425851273e-24, + 7.32260214157e-24, + 5.87433201125e-24, + 6.79884662102e-24, + 6.23345462746e-24, + 6.36714722381e-24, + 5.56132344254e-24, + 7.90887173342e-24, + 7.08392990812e-24, + 8.85545433259e-24, + 6.01856418372e-24, + 6.31963413149e-24, + 6.85279050744e-24, + 7.75657976909e-24, + 8.50479856047e-24, + 7.94873918585e-24 + ], + "max":[ + 0.0150078302249, + 0.0248268786818, + 0.0372853949666, + 0.0202775932848, + 0.00924268271774, + 0.00459495186806, + 0.00642714649439, + 0.00673051225021, + 0.00483322422951, + 0.0058145863004, + 0.00487699825317, + 0.00474451202899, + 0.00216139364056, + 0.00089383253362, + 0.000890302297194, + 0.00114067236427, + 0.00265396363102, + 0.00179244857281, + 0.00171541213058, + 0.00327429641038, + 0.00261263479479, + 0.00140622933395, + 0.000604341796134, + 0.000546872266568, + 0.00119282689411, + 0.000385722087231, + 0.000307112553855, + 0.000185638607945, + 0.000196822540602, + 7.07383733243e-05, + 3.59257646778e-05, + 4.41324045823e-05, + 5.90648887737e-05, + 5.03649462189e-05, + 1.98958878173e-05, + 1.04367582026e-05, + 1.49458364831e-05, + 3.54613039235e-05, + 2.11343995034e-05, + 1.33671064759e-05 + ], + "dvar2":[ + 1.97027497961e-06, + 1.79839098564e-05, + 3.41721388395e-05, + 6.39068775854e-06, + 4.12703258235e-07, + 1.60991760367e-07, + 5.84672534387e-07, + 1.35801229817e-07, + 5.67447884237e-08, + 9.04100758703e-08, + 5.12682660769e-08, + 6.00754361813e-08, + 8.33282598478e-09, + 2.19900075926e-09, + 2.22529794591e-09, + 2.68628164157e-09, + 6.38194253e-09, + 4.48827552901e-09, + 1.61791646747e-09, + 5.6524527281e-09, + 7.00124225261e-09, + 5.1307971205e-09, + 1.8114484357e-09, + 6.22804863237e-10, + 1.41800715614e-09, + 5.03870334345e-10, + 3.42071621029e-10, + 8.80266623482e-11, + 5.10801435871e-11, + 1.6358601973e-11, + 1.09966497713e-11, + 1.34551406475e-11, + 2.12651927317e-11, + 8.70376774126e-12, + 2.70498077062e-12, + 8.23377390574e-13, + 6.18267915163e-13, + 8.94622212682e-13, + 5.74140724113e-13, + 4.04918747187e-13 + ], + "median":[ + 6.78846045048e-05, + 0.000686653598677, + 0.00100371893495, + 0.000425793463364, + 0.000121567500173, + 8.67325506988e-05, + 0.000119830452604, + 7.64572032494e-05, + 4.73126528959e-05, + 4.95156273246e-05, + 5.10508471052e-05, + 3.72932154278e-05, + 1.39631702041e-05, + 4.18296076532e-06, + 3.36458288075e-06, + 5.95153596805e-06, + 7.06666241967e-06, + 5.36886500413e-06, + 6.55584017295e-06, + 1.27752928165e-05, + 1.80421066034e-05, + 1.10708388092e-05, + 9.13756139198e-06, + 6.40786538497e-06, + 6.87108331476e-06, + 5.39385519005e-06, + 3.31015212396e-06, + 2.2452804842e-06, + 2.11795463656e-06, + 8.45357135404e-07, + 1.55302529947e-07, + 2.16630468231e-07, + 2.0936421663e-07, + 1.59076819273e-07, + 1.03014848207e-07, + 5.60769883862e-08, + 4.16746956944e-08, + 3.91173387015e-08, + 3.08294119122e-08, + 2.99958919925e-08 + ], + "dmean2":[ + 0.000655197829474, + 0.00202016695403, + 0.00265697692521, + 0.00127012608573, + 0.000302697066218, + 0.000204388590646, + 0.000336306344252, + 0.000177521447768, + 0.000107648374978, + 0.000137986353366, + 0.000116639275802, + 0.000105825478386, + 3.63973231288e-05, + 1.78256286745e-05, + 1.63039130712e-05, + 1.98472516786e-05, + 2.55192408076e-05, + 1.86820070667e-05, + 1.45677859109e-05, + 2.93159864668e-05, + 3.81224999728e-05, + 2.55198028754e-05, + 1.86311717698e-05, + 1.29478112285e-05, + 1.63034928846e-05, + 1.03988468254e-05, + 6.90801107339e-06, + 4.38494134869e-06, + 3.91557023249e-06, + 1.95062216335e-06, + 1.26417035062e-06, + 1.61554555689e-06, + 1.957419272e-06, + 1.21927041619e-06, + 7.50478704958e-07, + 4.08925643569e-07, + 3.15493565495e-07, + 2.87596407134e-07, + 2.50877462804e-07, + 2.38469112901e-07 + ], + "dmean":[ + 0.000433199049439, + 0.00115317711607, + 0.00158822687808, + 0.000778516754508, + 0.000194163410924, + 0.000129944470245, + 0.00020776965539, + 0.000110655011667, + 7.02645556885e-05, + 8.88201902853e-05, + 7.56665394874e-05, + 7.11579850758e-05, + 2.26343472605e-05, + 1.1214566257e-05, + 1.06519555629e-05, + 1.3082231817e-05, + 1.72533091245e-05, + 1.2507844076e-05, + 9.44854855334e-06, + 1.93181331269e-05, + 2.54146216321e-05, + 1.58707625815e-05, + 1.14972417578e-05, + 8.10282745078e-06, + 1.0418824786e-05, + 6.57239706925e-06, + 4.29072770203e-06, + 2.71895851256e-06, + 2.42956934926e-06, + 1.20713775686e-06, + 7.98163171112e-07, + 1.02098283605e-06, + 1.22477297282e-06, + 8.0222929455e-07, + 4.99395412135e-07, + 2.76074587191e-07, + 2.18049038381e-07, + 1.94722304059e-07, + 1.73989079144e-07, + 1.64999249819e-07 + ], + "var":[ + 1.04273829038e-06, + 4.88182786285e-06, + 1.22067667689e-05, + 3.09852111968e-06, + 2.95254579896e-07, + 1.60118688086e-07, + 3.36397903311e-07, + 9.02441499306e-08, + 5.12204714198e-08, + 8.87765096991e-08, + 6.13447141973e-08, + 1.30928043518e-07, + 7.16093628839e-09, + 2.90166846106e-09, + 3.30743610277e-09, + 3.75769282357e-09, + 1.11862910046e-08, + 7.38158290048e-09, + 3.41670158832e-09, + 2.24571348184e-08, + 3.01072198283e-08, + 4.89972462603e-09, + 1.57648072374e-09, + 7.79673825502e-10, + 2.14637396745e-09, + 5.14293607701e-10, + 2.73522648975e-10, + 8.45902653479e-11, + 5.53298171169e-11, + 1.09233455614e-11, + 4.45680905375e-12, + 6.09628753728e-12, + 8.53084356628e-12, + 4.52617804347e-12, + 1.82034248786e-12, + 6.15677430912e-13, + 4.4449592119e-13, + 6.71954570979e-13, + 5.48820374997e-13, + 3.48484424911e-13 + ], + "dvar":[ + 8.33708043046e-07, + 6.49838420941e-06, + 1.36113221743e-05, + 2.76258151644e-06, + 1.75387782519e-07, + 6.53309797372e-08, + 2.18858644985e-07, + 5.17116269805e-08, + 2.40723956324e-08, + 3.69722101823e-08, + 2.22425278196e-08, + 2.84932291095e-08, + 3.64641872252e-09, + 9.5759922214e-10, + 9.86244308443e-10, + 1.3016818734e-09, + 3.31316440949e-09, + 2.19745110996e-09, + 7.73902275597e-10, + 3.32642535739e-09, + 3.88597554135e-09, + 1.99106442444e-09, + 7.00074609394e-10, + 2.79730322239e-10, + 6.32938867984e-10, + 2.10190226335e-10, + 1.22236526456e-10, + 3.66416376407e-11, + 2.22450686344e-11, + 6.52528248449e-12, + 4.34595848892e-12, + 5.58480735616e-12, + 8.46765019213e-12, + 3.64534357561e-12, + 1.20417478072e-12, + 3.81005014864e-13, + 2.8428255301e-13, + 3.87186458025e-13, + 2.78560404994e-13, + 1.87431545436e-13 + ], + "mean":[ + 0.00047609579633, + 0.00126094208099, + 0.00185862951912, + 0.000971358967945, + 0.000324478023686, + 0.000246531388257, + 0.000361267186236, + 0.000190427192138, + 0.000126440427266, + 0.000159403600264, + 0.000136641858262, + 0.000143978060805, + 3.71072310372e-05, + 1.87067053048e-05, + 1.93349878828e-05, + 2.34964645642e-05, + 3.1896517612e-05, + 2.36660616793e-05, + 1.83704396477e-05, + 4.34660541941e-05, + 5.81043132115e-05, + 2.89009076369e-05, + 2.15983145608e-05, + 1.50616651808e-05, + 1.95628890651e-05, + 1.24749267343e-05, + 8.04845058155e-06, + 4.90500542583e-06, + 4.20188916905e-06, + 1.82525320724e-06, + 8.70177814249e-07, + 1.09259167402e-06, + 1.25471365209e-06, + 9.23780646644e-07, + 6.02008753958e-07, + 3.45971272964e-07, + 2.69976595746e-07, + 2.55056221476e-07, + 2.36791535713e-07, + 2.26877631349e-07 + ] + }, + "spectral_entropy":{ + "min":4.61501169205, + "max":9.81467628479, + "dvar2":0.184129029512, + "median":7.38190746307, + "dmean2":0.352754920721, + "dmean":0.243219792843, + "var":0.300432950258, + "dvar":0.0902535244823, + "mean":7.3010840416 + }, + "spectral_rolloff":{ + "min":64.599609375, + "max":21037.9394531, + "dvar2":3396222, + "median":861.328125, + "dmean2":1057.10974121, + "dmean":604.693481445, + "var":2179523.25, + "dvar":1425528, + "mean":1383.6763916 + }, + "barkbands":{ + "min":[ + 6.93473619499e-25, + 5.19568601854e-24, + 1.02416202049e-23, + 4.28463410897e-24, + 3.04471689542e-23, + 2.72335547301e-23, + 3.08580014027e-23, + 1.15517745957e-23, + 5.01556722243e-23, + 3.01743335215e-23, + 3.20834273992e-23, + 6.39242832255e-23, + 4.96037188707e-23, + 6.11980114915e-23, + 7.73605723709e-23, + 1.27850093686e-22, + 8.33913319498e-23, + 1.55698133196e-22, + 1.80609161514e-22, + 2.27535985033e-22, + 3.03975723224e-22, + 3.99622470031e-22, + 4.5185483121e-22, + 7.15649816942e-22, + 1.01532623561e-21, + 1.53862207745e-21, + 2.31706194078e-21 + ], + "max":[ + 0.00229191919789, + 0.047907166183, + 0.0691591277719, + 0.0995827168226, + 0.0820566862822, + 0.0232072826475, + 0.0308443717659, + 0.0302771702409, + 0.0344947054982, + 0.0269099473953, + 0.0134304724634, + 0.00715320091695, + 0.00838674418628, + 0.0218261200935, + 0.019664183259, + 0.0362881943583, + 0.0182446800172, + 0.0173479039222, + 0.0146563379094, + 0.00540218688548, + 0.00442544184625, + 0.00217473763041, + 0.0013186649885, + 0.00208773952909, + 0.00195873784833, + 0.000584891589824, + 0.00050722778542 + ], + "dvar2":[ + 2.09710808718e-08, + 5.00840687891e-05, + 9.50076937443e-05, + 0.000209878431633, + 8.73877215781e-05, + 3.97830672227e-06, + 1.24859725474e-05, + 1.86764350474e-06, + 3.62891637451e-06, + 3.01378167933e-06, + 5.96735674208e-07, + 1.57074438789e-07, + 2.46402947823e-07, + 4.87388831516e-07, + 4.96838595154e-07, + 1.52867119141e-06, + 1.2727361991e-06, + 3.34951494096e-07, + 4.58745859078e-07, + 1.02385989464e-07, + 2.90899002664e-08, + 3.47254207611e-08, + 1.03255741735e-08, + 3.98843491567e-09, + 4.08773503935e-09, + 1.11437570283e-09, + 4.70612881998e-10 + ], + "median":[ + 1.01329169411e-06, + 0.000326245411998, + 0.00187892094254, + 0.00155476410873, + 0.0016892075073, + 0.000451811589301, + 0.000548189680558, + 0.000192572828382, + 0.000307663634885, + 0.000414336362155, + 9.44759449339e-05, + 2.73611021839e-05, + 5.38471249456e-05, + 6.47374472464e-05, + 8.72917589732e-05, + 0.000232024758589, + 0.000200124268304, + 0.000144036966958, + 0.000164192693774, + 8.08068361948e-05, + 4.40170915681e-05, + 1.11471890705e-05, + 6.5616086431e-06, + 3.2568784718e-06, + 2.92447043648e-06, + 4.78593108255e-07, + 7.76246977807e-08 + ], + "dmean2":[ + 5.63530775253e-05, + 0.00340586039238, + 0.00441808719188, + 0.00632638018578, + 0.0048057041131, + 0.00103038607631, + 0.00156902591698, + 0.000596007099375, + 0.000905426510144, + 0.000906587869395, + 0.000307931040879, + 0.000146102538565, + 0.000193360538105, + 0.000240257213591, + 0.000224526840611, + 0.00052686111303, + 0.000436997273937, + 0.000281702930806, + 0.000314143690048, + 0.000150212654262, + 8.88355425559e-05, + 8.39097774588e-05, + 4.62743046228e-05, + 2.28419812629e-05, + 2.21090576815e-05, + 1.11555727926e-05, + 5.03497130921e-06 + ], + "dmean":[ + 4.36054288002e-05, + 0.00207182555459, + 0.00250360206701, + 0.00372918182984, + 0.0029777479358, + 0.00065627245931, + 0.000966914638411, + 0.000378262484446, + 0.000581912638154, + 0.000613346113823, + 0.000192098785192, + 9.08574875211e-05, + 0.000126861719764, + 0.000160341092851, + 0.000145415237057, + 0.00034682394471, + 0.000273586803814, + 0.000176411645953, + 0.000198787456611, + 9.40177123994e-05, + 5.56063205295e-05, + 5.36341467523e-05, + 3.11664407491e-05, + 1.60014496942e-05, + 1.57560625667e-05, + 7.42050679037e-06, + 3.44123100149e-06 + ], + "var":[ + 1.73105885182e-08, + 1.84976615856e-05, + 2.50716802839e-05, + 7.04820486135e-05, + 4.76136665384e-05, + 3.67056259165e-06, + 6.74153125146e-06, + 1.57238355314e-06, + 3.58573174708e-06, + 5.54312009626e-06, + 5.51931407244e-07, + 1.78970466891e-07, + 4.17550438669e-07, + 9.57703605309e-07, + 8.59389047037e-07, + 6.6176985456e-06, + 1.22271069358e-06, + 4.2584204607e-07, + 5.58315321086e-07, + 9.85875061588e-08, + 2.47446703128e-08, + 1.64356386279e-08, + 7.04793423623e-09, + 3.46884565516e-09, + 3.82823417411e-09, + 6.34027108593e-10, + 3.8906944333e-10 + ], + "dvar":[ + 1.15370024645e-08, + 1.92330826394e-05, + 3.36813718604e-05, + 8.24065355118e-05, + 3.870560613e-05, + 1.55360748977e-06, + 4.66681467515e-06, + 7.47769490772e-07, + 1.50442451741e-06, + 1.46062268414e-06, + 2.81505151634e-07, + 6.65834889446e-08, + 1.17960382795e-07, + 2.50351632758e-07, + 2.41593681949e-07, + 8.20324487449e-07, + 5.11046778229e-07, + 1.56924727435e-07, + 1.97066171381e-07, + 4.1844121057e-08, + 1.20861924913e-08, + 1.45208129965e-08, + 4.66174743252e-09, + 1.88047488692e-09, + 2.07477035552e-09, + 5.05100294923e-10, + 2.44846420916e-10 + ], + "mean":[ + 5.19759996678e-05, + 0.00199001817964, + 0.00309076649137, + 0.00392009504139, + 0.0039071268402, + 0.00123883492779, + 0.00161516538355, + 0.000634168100078, + 0.00102682900615, + 0.00122780457605, + 0.000289549614536, + 0.000142228382174, + 0.000236654945184, + 0.000305703491904, + 0.000276061356999, + 0.000822361966129, + 0.000508801313117, + 0.000334064679919, + 0.000397378782509, + 0.00017829038552, + 8.88610738912e-05, + 5.81649801461e-05, + 3.79984667234e-05, + 2.1309551812e-05, + 2.22307517106e-05, + 7.82890947448e-06, + 3.57463068212e-06 + ] + }, + "melbands_flatness_db":{ + "min":0.00437760027125, + "max":0.607957184315, + "dvar2":0.00331180845387, + "median":0.219427987933, + "dmean2":0.0528259426355, + "dmean":0.034728333354, + "var":0.00492821913213, + "dvar":0.00150177872274, + "mean":0.230123117566 + }, + "melbands_skewness":{ + "min":-2.44428515434, + "max":15.3962888718, + "dvar2":2.92571592331, + "median":2.28337860107, + "dmean2":1.4999755621, + "dmean":0.987386882305, + "var":4.25560426712, + "dvar":1.34734094143, + "mean":2.84234952927 + }, + "barkbands_skewness":{ + "min":-6.20005989075, + "max":18.9707603455, + "dvar2":2.02687716484, + "median":1.45346200466, + "dmean2":1.15091514587, + "dmean":0.750691831112, + "var":2.42782378197, + "dvar":0.866045475006, + "mean":1.71697402 + }, + "silence_rate_60dB":{ + "min":0, + "max":1, + "dvar2":0.0371209047735, + "median":0, + "dmean2":0.0337187945843, + "dmean":0.0168575756252, + "var":0.179377868772, + "dvar":0.0165733974427, + "mean":0.234251752496 + }, + "spectral_energyband_low":{ + "min":4.89638611687e-23, + "max":0.116083092988, + "dvar2":0.000277574028587, + "median":0.00443472480401, + "dmean2":0.00833203457296, + "dmean":0.00496239587665, + "var":9.57977899816e-05, + "dvar":0.000101656405604, + "mean":0.00667642848566 + }, + "spectral_energyband_middle_low":{ + "min":2.98093395713e-22, + "max":0.171243280172, + "dvar2":0.000569899275433, + "median":0.0082081919536, + "dmean2":0.0117948763072, + "dmean":0.00737277884036, + "var":0.000299356790492, + "dvar":0.000242799738771, + "mean":0.0127554573119 + }, + "melbands_kurtosis":{ + "min":-1.94107413292, + "max":380.680023193, + "dvar2":1038.95019531, + "median":7.13754844666, + "dmean2":17.6919975281, + "dmean":11.5336751938, + "var":1275.55053711, + "dvar":493.653686523, + "mean":19.2873706818 + }, + "spectral_decrease":{ + "min":-4.64023344193e-08, + "max":6.78438804261e-19, + "dvar2":6.20802821665e-17, + "median":-4.53350113006e-09, + "dmean2":4.26796598063e-09, + "dmean":2.69736544212e-09, + "var":3.69683427013e-17, + "dvar":2.61311086979e-17, + "mean":-5.59147705914e-09 + }, + "erbbands_kurtosis":{ + "min":-1.86338639259, + "max":171.201263428, + "dvar2":23.2438850403, + "median":-0.320037484169, + "dmean2":2.39585089684, + "dmean":1.52739417553, + "var":35.0008544922, + "dvar":11.0155954361, + "mean":1.24987971783 + }, + "melbands_crest":{ + "min":1.85922825336, + "max":32.9627304077, + "dvar2":27.1548709869, + "median":12.5910797119, + "dmean2":5.60343551636, + "dmean":3.39730739594, + "var":20.3299713135, + "dvar":10.5175638199, + "mean":13.3324451447 + }, + "melbands_spread":{ + "min":0.26147004962, + "max":299.135498047, + "dvar2":1027.73010254, + "median":17.4329528809, + "dmean2":16.3484096527, + "dmean":10.0459423065, + "var":529.263366699, + "dvar":403.605499268, + "mean":23.2355747223 + }, + "spectral_energy":{ + "min":1.02320440393e-20, + "max":0.179453358054, + "dvar2":0.000923860818148, + "median":0.0185781233013, + "dmean2":0.0165870357305, + "dmean":0.0105188144371, + "var":0.000572183460463, + "dvar":0.00039060486597, + "mean":0.0224339049309 + }, + "mfcc":{ + "mean":[ + -715.191650391, + 133.878646851, + -2.74888682365, + 38.7127075195, + 3.85699295998, + -10.4443674088, + -5.89105558395, + 4.36424779892, + 2.37372231483, + 1.66640949249, + -7.12301874161, + -9.74494552612, + -3.86338329315 + ], + "icov":[ + [ + 7.98077235231e-05, + -5.86888636462e-05, + 0.000145378129673, + -9.86643281067e-05, + 3.03972447e-05, + -0.000187377940165, + 0.000134168396471, + -0.000129314183141, + 1.27186794998e-05, + -7.31398395146e-05, + 1.38320649512e-06, + 0.000111114335596, + -8.96842757356e-05 + ], + [ + -5.86888636462e-05, + 0.000914695789106, + -1.55892048497e-05, + 0.000330161477905, + -0.000239893066464, + 0.00115360564087, + -0.000499361369293, + 0.000324924068991, + -1.15215043479e-05, + -0.000243278453127, + 0.000191972227185, + -9.64893956734e-07, + 0.000270225456916 + ], + [ + 0.000145378129673, + -1.55892048497e-05, + 0.0013757571578, + 7.94086445239e-05, + -0.000468786456622, + -0.00135524733923, + 0.00098228675779, + -0.000316469959216, + -0.000591932330281, + 0.000769039965235, + -0.000745072495192, + 0.000638137804344, + 0.000274067162536 + ], + [ + -9.86643281067e-05, + 0.000330161477905, + 7.94086445239e-05, + 0.00385635741986, + -0.00140862353146, + 0.000500513473526, + 0.000532710750122, + -0.00153480307199, + 0.000852926750667, + -0.000837227795273, + 0.00151946756523, + -0.00070260866778, + 0.000143392870086 + ], + [ + 3.03972447e-05, + -0.000239893066464, + -0.000468786456622, + -0.00140862353146, + 0.0056857005693, + -0.00172490451951, + -0.00111165409908, + 0.000201825780096, + 0.000247466086876, + -0.00217686733231, + 0.00112909392919, + -0.000958321907092, + -0.000166401950992 + ], + [ + -0.000187377940165, + 0.00115360564087, + -0.00135524733923, + 0.000500513473526, + -0.00172490451951, + 0.00837340857834, + -0.00406587868929, + 0.00216831197031, + -0.0023798532784, + 0.00346444058232, + -0.00286303297617, + 0.00123248388991, + -0.000868651026394 + ], + [ + 0.000134168396471, + -0.000499361369293, + 0.00098228675779, + 0.000532710750122, + -0.00111165409908, + -0.00406587868929, + 0.00986782740802, + -0.00542975915596, + 0.00409825751558, + -0.0044681020081, + 0.00282385596074, + -0.00354772782885, + 0.00168551225215 + ], + [ + -0.000129314183141, + 0.000324924068991, + -0.000316469959216, + -0.00153480307199, + 0.000201825780096, + 0.00216831197031, + -0.00542975915596, + 0.0144132943824, + -0.00864001736045, + 0.00550767453387, + -0.00397388311103, + 0.00314126117155, + -0.00206855195574 + ], + [ + 1.27186794998e-05, + -1.15215043479e-05, + -0.000591932330281, + 0.000852926750667, + 0.000247466086876, + -0.0023798532784, + 0.00409825751558, + -0.00864001736045, + 0.0176015142351, + -0.0112102692947, + 0.0083336783573, + -0.00373222492635, + 0.00208288733847 + ], + [ + -7.31398395146e-05, + -0.000243278453127, + 0.000769039965235, + -0.000837227795273, + -0.00217686733231, + 0.00346444058232, + -0.0044681020081, + 0.00550767453387, + -0.0112102692947, + 0.0205363947898, + -0.0105180032551, + 0.00535045098513, + -0.00213157944381 + ], + [ + 1.38320649512e-06, + 0.000191972227185, + -0.000745072495192, + 0.00151946756523, + 0.00112909392919, + -0.00286303297617, + 0.00282385596074, + -0.00397388311103, + 0.0083336783573, + -0.0105180032551, + 0.0160211343318, + -0.00672314595431, + 0.00358490552753 + ], + [ + 0.000111114335596, + -9.64893956734e-07, + 0.000638137804344, + -0.00070260866778, + -0.000958321907092, + 0.00123248388991, + -0.00354772782885, + 0.00314126117155, + -0.00373222492635, + 0.00535045098513, + -0.00672314595431, + 0.0181408431381, + -0.00800348073244 + ], + [ + -8.96842757356e-05, + 0.000270225456916, + 0.000274067162536, + 0.000143392870086, + -0.000166401950992, + -0.000868651026394, + 0.00168551225215, + -0.00206855195574, + 0.00208288733847, + -0.00213157944381, + 0.00358490552753, + -0.00800348073244, + 0.0156487096101 + ] + ], + "cov":[ + [ + 18717.6230469, + 1395.88500977, + -2566.72802734, + 557.851989746, + -126.109024048, + -374.194091797, + 26.1053237915, + 164.080841064, + 80.1878204346, + 192.214401245, + -182.145751953, + -47.5592041016, + 152.686767578 + ], + [ + 1395.88500977, + 1649.59350586, + -550.320007324, + -49.1516876221, + -56.1948204041, + -331.535217285, + 9.86240959167, + -34.6940498352, + -6.41311454773, + 74.1020736694, + -56.9916381836, + -16.3797187805, + -19.4202880859 + ], + [ + -2566.72802734, + -550.320007324, + 1546.81799316, + -94.7429580688, + 133.984313965, + 339.89239502, + -54.6255912781, + 10.0923881531, + 34.4428405762, + -69.080619812, + 85.0990753174, + -36.5973091125, + -56.1265907288 + ], + [ + 557.851989746, + -49.1516876221, + -94.7429580688, + 342.6902771, + 83.1379013062, + -15.0537748337, + 17.4024486542, + 46.2917900085, + 21.9955101013, + 12.8328580856, + -40.3507461548, + 8.21014022827, + 19.1214065552 + ], + [ + -126.109024048, + -56.1948204041, + 133.984313965, + 83.1379013062, + 261.195220947, + 98.0570144653, + 69.749458313, + 21.4776115417, + 23.9828796387, + 28.7067451477, + 2.99768400192, + 18.3751049042, + 10.1154251099 + ], + [ + -374.194091797, + -331.535217285, + 339.89239502, + -15.0537748337, + 98.0570144653, + 288.139526367, + 71.6913833618, + 15.3370637894, + 9.08637428284, + -21.2720279694, + 42.7490844727, + 11.0748538971, + 0.872315227985 + ], + [ + 26.1053237915, + 9.86240959167, + -54.6255912781, + 17.4024486542, + 69.749458313, + 71.6913833618, + 187.006271362, + 49.2006340027, + 4.36477804184, + 25.2697525024, + 7.5669798851, + 29.0018577576, + 7.81967544556 + ], + [ + 164.080841064, + -34.6940498352, + 10.0923881531, + 46.2917900085, + 21.4776115417, + 15.3370637894, + 49.2006340027, + 122.378990173, + 54.7077331543, + 6.68141078949, + -6.7650809288, + -0.911539852619, + 7.60771179199 + ], + [ + 80.1878204346, + -6.41311454773, + 34.4428405762, + 21.9955101013, + 23.9828796387, + 9.08637428284, + 4.36477804184, + 54.7077331543, + 120.954666138, + 41.4050827026, + -25.8017272949, + -5.81494665146, + -0.236202299595 + ], + [ + 192.214401245, + 74.1020736694, + -69.080619812, + 12.8328580856, + 28.7067451477, + -21.2720279694, + 25.2697525024, + 6.68141078949, + 41.4050827026, + 102.835891724, + 31.3814048767, + -2.45175004005, + -1.74627566338 + ], + [ + -182.145751953, + -56.9916381836, + 85.0990753174, + -40.3507461548, + 2.99768400192, + 42.7490844727, + 7.5669798851, + -6.7650809288, + -25.8017272949, + 31.3814048767, + 120.884010315, + 22.8159122467, + -8.79971408844 + ], + [ + -47.5592041016, + -16.3797187805, + -36.5973091125, + 8.21014022827, + 18.3751049042, + 11.0748538971, + 29.0018577576, + -0.911539852619, + -5.81494665146, + -2.45175004005, + 22.8159122467, + 87.9682235718, + 38.346157074 + ], + [ + 152.686767578, + -19.4202880859, + -56.1265907288, + 19.1214065552, + 10.1154251099, + 0.872315227985, + 7.81967544556, + 7.60771179199, + -0.236202299595, + -1.74627566338, + -8.79971408844, + 38.346157074, + 87.662071228 + ] + ] + }, + "spectral_contrast_valleys":{ + "min":[ + -27.644701004, + -27.7437572479, + -27.5804691315, + -27.6421985626, + -27.3466243744, + -27.4174346924 + ], + "max":[ + -5.21189641953, + -4.43200492859, + -5.37789392471, + -5.91939544678, + -5.84870004654, + -8.253657341 + ], + "dvar2":[ + 0.418128162622, + 0.42821636796, + 0.406443417072, + 0.387645244598, + 0.499291837215, + 0.697984993458 + ], + "median":[ + -7.62850189209, + -6.92876195908, + -7.67359733582, + -8.07751655579, + -7.46400737762, + -11.0671672821 + ], + "dmean2":[ + 0.747626721859, + 0.710296332836, + 0.67908090353, + 0.625626146793, + 0.595694363117, + 0.680769026279 + ], + "dmean":[ + 0.493877381086, + 0.47190451622, + 0.458809673786, + 0.433981686831, + 0.418061226606, + 0.529967188835 + ], + "var":[ + 2.56318879128, + 2.56686043739, + 2.68657803535, + 2.71048474312, + 2.86386156082, + 2.03321886063 + ], + "dvar":[ + 0.185303419828, + 0.210249379277, + 0.205063581467, + 0.197276696563, + 0.240655809641, + 0.327577888966 + ], + "mean":[ + -7.9825963974, + -7.30778980255, + -8.13263988495, + -8.62220096588, + -8.10116863251, + -11.1167650223 + ] + }, + "barkbands_flatness_db":{ + "min":0.00845116842538, + "max":0.463767468929, + "dvar2":0.00153901893646, + "median":0.152025014162, + "dmean2":0.0385256558657, + "dmean":0.0259312130511, + "var":0.00293617043644, + "dvar":0.000700293399859, + "mean":0.161552548409 + }, + "dynamic_complexity":5.97568511963, + "spectral_skewness":{ + "min":-0.258594423532, + "max":7.78090715408, + "dvar2":0.501113593578, + "median":1.41668355465, + "dmean2":0.598508477211, + "dmean":0.382409095764, + "var":0.599681735039, + "dvar":0.224964693189, + "mean":1.57063114643 + }, + "erbbands_flatness_db":{ + "min":0.0321905463934, + "max":0.434577912092, + "dvar2":0.00118384102825, + "median":0.181439816952, + "dmean2":0.0333808884025, + "dmean":0.024810899049, + "var":0.00294912024401, + "dvar":0.000594827288296, + "mean":0.178649738431 + }, + "hfc":{ + "min":1.12110872149e-16, + "max":96.712890625, + "dvar2":109.576454163, + "median":11.9836702347, + "dmean2":6.97959280014, + "dmean":4.67007303238, + "var":197.084396362, + "dvar":50.9854736328, + "mean":14.6673564911 + }, + "barkbands_crest":{ + "min":2.1863629818, + "max":25.4534358978, + "dvar2":11.5983400345, + "median":8.56367301941, + "dmean2":3.74820661545, + "dmean":2.30216050148, + "var":11.5966396332, + "dvar":4.54739236832, + "mean":9.14883136749 + } + }, + "highlevel":{ + "timbre":{ + "all":{ + "dark":0.0808309540153, + "bright":0.919169068336 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"bright", + "probability":0.919169068336 + }, + "ismir04_rhythm":{ + "all":{ + "Rumba-American":0.0406456775963, + "VienneseWaltz":0.338310062885, + "Samba":0.0297329928726, + "Rumba-Misc":0.0135653112084, + "Rumba-International":0.0278510767967, + "Tango":0.330144882202, + "Waltz":0.00898563489318, + "ChaChaCha":0.0889096781611, + "Jive":0.11033257097, + "Quickstep":0.0115221142769 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"VienneseWaltz", + "probability":0.338310062885 + }, + "voice_instrumental":{ + "all":{ + "instrumental":0.999981045723, + "voice":1.89501206478e-05 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"instrumental", + "probability":0.999981045723 + }, + "gender":{ + "all":{ + "male":0.108683988452, + "female":0.891315996647 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"female", + "probability":0.891315996647 + }, + "genre_rosamerica":{ + "all":{ + "hip":0.070330247283, + "rhy":0.225707545877, + "jaz":0.0771619826555, + "dan":0.0574826933444, + "roc":0.270465612411, + "cla":0.0938607081771, + "pop":0.175827592611, + "spe":0.0291636306792 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"roc", + "probability":0.270465612411 + }, + "mood_electronic":{ + "all":{ + "electronic":0.339881360531, + "not_electronic":0.660118639469 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_electronic", + "probability":0.660118639469 + }, + "genre_electronic":{ + "all":{ + "house":0.187250360847, + "trance":0.185409858823, + "dnb":0.00702595943585, + "techno":0.0184047427028, + "ambient":0.601909101009 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"ambient", + "probability":0.601909101009 + }, + "mood_sad":{ + "all":{ + "not_sad":0.700305402279, + "sad":0.299694597721 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_sad", + "probability":0.700305402279 + }, + "tonal_atonal":{ + "all":{ + "atonal":0.125749841332, + "tonal":0.874250173569 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"tonal", + "probability":0.874250173569 + }, + "mood_party":{ + "all":{ + "party":0.234383180737, + "not_party":0.765616834164 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_party", + "probability":0.765616834164 + }, + "moods_mirex":{ + "all":{ + "Cluster2":0.0673071071506, + "Cluster3":0.397048592567, + "Cluster1":0.061667304486, + "Cluster4":0.190215244889, + "Cluster5":0.283761769533 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"Cluster3", + "probability":0.397048592567 + }, + "danceability":{ + "all":{ + "danceable":0.143928021193, + "not_danceable":0.85607200861 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_danceable", + "probability":0.85607200861 + }, + "genre_dortmund":{ + "all":{ + "raphiphop":4.74844455312e-05, + "electronic":0.984485208988, + "jazz":0.000787914788816, + "pop":0.000125292601297, + "folkcountry":0.00235203420743, + "rock":0.0010081063956, + "alternative":0.00961782038212, + "funksoulrnb":6.0458383814e-05, + "blues":0.00151570443995 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"electronic", + "probability":0.984485208988 + }, + "mood_acoustic":{ + "all":{ + "acoustic":0.415711194277, + "not_acoustic":0.584288835526 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_acoustic", + "probability":0.584288835526 + }, + "mood_happy":{ + "all":{ + "not_happy":0.910523295403, + "happy":0.0894767045975 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_happy", + "probability":0.910523295403 + }, + "mood_aggressive":{ + "all":{ + "not_aggressive":0.922077834606, + "aggressive":0.0779221653938 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_aggressive", + "probability":0.922077834606 + }, + "genre_tzanetakis":{ + "all":{ + "hip":0.154464527965, + "jaz":0.308918893337, + "bl":0.0514711923897, + "roc":0.0772226303816, + "cla":0.0343172624707, + "pop":0.0617748275399, + "met":0.0441242903471, + "co":0.102957598865, + "reg":0.0617764480412, + "dis":0.102972343564 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"jaz", + "probability":0.308918893337 + }, + "mood_relaxed":{ + "all":{ + "not_relaxed":0.87636756897, + "relaxed":0.123632438481 + }, + "version":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + }, + "value":"not_relaxed", + "probability":0.87636756897 + } + }, + "metadata":{ + "audio_properties":{ + "analysis_sample_rate":44100, + "length":214.866668701, + "downmix":"mix", + "bit_rate":0, + "codec":"flac", + "md5_encoded":"2b46dab358c1b79a3decd5bd93d7221f", + "equal_loudness":0, + "replay_gain":-14.4778690338, + "lossless":1 + }, + "version":{ + "lowlevel":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "essentia_build_sha":"50a0fbec89d6a9cedea3d45b6611406f7e8c7b1a", + "essentia_git_sha":"v2.1_beta1-7-ge0e83e8-dirty" + }, + "highlevel":{ + "essentia":"2.1-beta1", + "extractor":"music 1.0", + "gaia_git_sha":"857329b", + "models_essentia_git_sha":"v2.1_beta1", + "essentia_git_sha":"v2.1_beta1-228-g260734a", + "essentia_build_sha":"8e24b98b71ad84f3024c7541412f02124a26d327", + "gaia":"2.4-dev" + } + }, + "tags":{ + "albumartistsort":[ + "Various Artists" + ], + "disctotal":[ + "1" + ], + "file_name":"04 La Grange.flac", + "artists":[ + "ZZ Top" + ], + "musicbrainz_workid":[ + "42722fe8-9de7-3729-a506-3c7f41c617a9" + ], + "releasecountry":[ + "DE" + ], + "totaldiscs":[ + "1" + ], + "albumartist":[ + "Various Artists" + ], + "musicbrainz_albumartistid":[ + "89ad4ac3-39f7-470e-963a-56509c546377" + ], + "composer":[ + "Dusty Hill", + "Frank Beard", + "Billy Gibbons" + ], + "catalognumber":[ + "491384 2" + ], + "tracknumber":[ + "4" + ], + "replaygain_track_peak":[ + "0.999969" + ], + "engineer":[ + "Terry Manning", + "Robin Hood Brians" + ], + "album":[ + "Armageddon:The Album" + ], + "asin":[ + "B000024C3A" + ], + "replaygain_album_gain":[ + "-9.32 dB" + ], + "musicbrainz_artistid":[ + "a81259a0-a2f5-464b-866e-71220f2739f1" + ], + "producer":[ + "Bill Ham" + ], + "script":[ + "Latn" + ], + "media":[ + "CD" + ], + "label":[ + "Columbia" + ], + "artistsort":[ + "ZZ Top" + ], + "acoustid_id":[ + "3ed3441e-facc-4fcd-9ef7-9fbc68c206a2" + ], + "replaygain_album_peak":[ + "0.999969" + ], + "lyricist":[ + "Dusty Hill", + "Frank Beard", + "Billy Gibbons" + ], + "musicbrainz_releasegroupid":[ + "f51d56e4-0211-3533-a9a5-08c02d8bb04a" + ], + "compilation":[ + "1" + ], + "barcode":[ + "5099749138421" + ], + "releasestatus":[ + "official" + ], + "composersort":[ + "Hill, Dusty", + "Beard, Frank", + "Gibbons, Billy" + ], + "date":[ + "1998" + ], + "isrc":[ + "USWB10505222" + ], + "discnumber":[ + "1" + ], + "musicbrainz_recordingid":[ + "cd3f5efa-bc5e-4064-a765-960494ad4bb4" + ], + "tracktotal":[ + "14" + ], + "originaldate":[ + "1998-06-23" + ], + "language":[ + "eng" + ], + "artist":[ + "ZZ Top" + ], + "title":[ + "La Grange" + ], + "releasetype":[ + "album", + "soundtrack" + ], + "musicbrainz_albumid":[ + "cfc31187-aebd-309f-a92f-7138c17df7c2" + ], + "work":[ + "La Grange" + ], + "totaltracks":[ + "14" + ], + "replaygain_track_gain":[ + "-9.38 dB" + ], + "musicbrainz_releasetrackid":[ + "befe2741-462b-3568-ba06-c8cc8e4f6eaf" + ] + } + } +} diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py index ae56f781f..fb3147e15 100644 --- a/test/test_acousticbrainz.py +++ b/test/test_acousticbrainz.py @@ -18,9 +18,12 @@ from __future__ import absolute_import, print_function -from test._common import unittest +import json +import os.path -from beetsplug.acousticbrainz import DefaultList, AcousticPlugin +from test._common import unittest, RSRC + +from beetsplug.acousticbrainz import DefaultList, AcousticPlugin, ABSCHEME class DefaultListTest(unittest.TestCase): @@ -79,6 +82,37 @@ class MapDataToSchemeTest(unittest.TestCase): mapping = set(ab._map_data_to_scheme(data, scheme)) self.assertEqual(mapping, {('attribute', 'part 1 part 2')}) + def test_realistic(self): + ab = AcousticPlugin() + data_path = os.path.join(RSRC, b'acousticbrainz/data.json') + with open(data_path) as res: + data = json.load(res) + mapping = set(ab._map_data_to_scheme(data, ABSCHEME)) + expected = { + ('chords_key', 'A'), + ('average_loudness', 0.815025985241), + ('mood_acoustic', 0.415711194277), + ('chords_changes_rate', 0.0445116683841), + ('tonal', 0.874250173569), + ('mood_sad', 0.299694597721), + ('bpm', 162.532119751), + ('gender', 'female'), + ('initial_key', 'A minor'), + ('chords_number_rate', 0.00194468453992), + ('mood_relaxed', 0.123632438481), + ('chords_scale', 'minor'), + ('voice_instrumental', 'instrumental'), + ('key_strength', 0.636936545372), + ('genre_rosamerica', 'roc'), + ('mood_party', 0.234383180737), + ('mood_aggressive', 0.0779221653938), + ('danceable', 0.143928021193), + ('rhythm', 'VienneseWaltz'), + ('mood_electronic', 0.339881360531), + ('mood_happy', 0.0894767045975) + } + self.assertEqual(mapping, expected) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From eb1ea6177d73c8af839c26910fd6d0d1f6910404 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Thu, 17 Nov 2016 11:03:44 +0100 Subject: [PATCH 1411/2280] acousticbrainz: drop DefaultList, be explicitly careful * I don't see DefaultList be really helpful in many other cases, so having a beets.util.collections module (which could also conflict with the collections module from standard library) with only that in it is a little silly. * It was elegant and concise, but there are implementation issues: it is not recommended to subclass builtin types, but the alternatives differ between python 2 and 3 (subclass sequence or container or collections.abc?), moreover, interpreters can differ in the way they map syntaxic sugar to magic functions. * Also, slicing and negative indexing could do weird things, so the class wouldn't be really intuitive and simple at the same time --- beetsplug/acousticbrainz.py | 21 +++++++-------------- test/test_acousticbrainz.py | 17 +---------------- 2 files changed, 8 insertions(+), 30 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index b70bc59b7..cc30709be 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -20,7 +20,6 @@ from __future__ import division, absolute_import, print_function import requests from collections import defaultdict -from beets.util.collections import DefaultList from beets import plugins, ui ACOUSTIC_BASE = "https://acousticbrainz.org/" @@ -222,19 +221,8 @@ class AcousticPlugin(plugins.BeetsPlugin): each composite attribute to an ordered list of the values belonging to the attribute, for example: `composites = {'initial_key': ['B', 'minor']}`. - - composites is a `defaultdict` of `DefaultList`s (defined below). - It is a `defaultdict` by pure convenience. It holds `DefaultList`s - because the values of a composite attribute can be inserted out of - order, and we do not know the final length of a composite attribute in - advance. So, if we have - `composites = {}` - and then - `composites['initial_key'][1] = 'minor'` - happens, we want the result to be: - `composites = {'initial_key': ['', 'minor']}` """ - composites = defaultdict(lambda: DefaultList('')) + composites = defaultdict(list) # The recursive traversal for attr, val in self._data_to_scheme_child(data, scheme, @@ -264,7 +252,12 @@ class AcousticPlugin(plugins.BeetsPlugin): composites): yield yielded elif type(v) == tuple: - composites[v[0]][v[1]] = subdata[k] + composite_attribute, part_number = v + attribute_parts = composites[composite_attribute] + # Parts are not guaranteed to be inserted in order + while len(attribute_parts) <= part_number: + attribute_parts.append('') + attribute_parts[part_number] = subdata[k] else: yield v, subdata[k] else: diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py index fb3147e15..82a69c527 100644 --- a/test/test_acousticbrainz.py +++ b/test/test_acousticbrainz.py @@ -23,22 +23,7 @@ import os.path from test._common import unittest, RSRC -from beetsplug.acousticbrainz import DefaultList, AcousticPlugin, ABSCHEME - - -class DefaultListTest(unittest.TestCase): - def test_getitem(self): - default_list = DefaultList('foo') - default_value = default_list[2] - self.assertEqual(default_value, 'foo') - self.assertEqual(default_list, ['foo', 'foo', 'foo']) - - def test_setitem(self): - default_list = DefaultList('foo') - default_list[2] = 'bar' - self.assertEqual(default_list, ['foo', 'foo', 'bar']) - default_list[1] = 'baz' - self.assertEqual(default_list, ['foo', 'baz', 'bar']) +from beetsplug.acousticbrainz import AcousticPlugin, ABSCHEME class MapDataToSchemeTest(unittest.TestCase): From 147ced9eaabd01a3b7e931ba6f721412e289d85b Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sun, 20 Nov 2016 22:45:07 +0100 Subject: [PATCH 1412/2280] acousticbrainz: latest adjustments * Readability and consistency * Better logging: warn by default for attributes that were not found, but don't drown user with info when everything is going well. --- beetsplug/acousticbrainz.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index cc30709be..138fd8809 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -162,10 +162,10 @@ class AcousticPlugin(plugins.BeetsPlugin): data = self._get_data(item.mb_trackid) if data: for attr, val in self._map_data_to_scheme(data, ABSCHEME): - self._log.info(u'attribute {} of {} set to {}', - attr, - item, - val) + self._log.debug(u'attribute {} of {} set to {}', + attr, + item, + val) setattr(item, attr, val) item.store() if write: @@ -247,10 +247,10 @@ class AcousticPlugin(plugins.BeetsPlugin): for k, v in subscheme.items(): if k in subdata: if type(v) == dict: - for yielded in self._data_to_scheme_child(subdata[k], - v, - composites): - yield yielded + for attr, val in self._data_to_scheme_child(subdata[k], + v, + composites): + yield attr, val elif type(v) == tuple: composite_attribute, part_number = v attribute_parts = composites[composite_attribute] @@ -261,6 +261,8 @@ class AcousticPlugin(plugins.BeetsPlugin): else: yield v, subdata[k] else: + self._log.warning(u'Acousticbrainz did not provide info' + u'about {}', k) self._log.debug(u'Data {} could not be mapped to scheme {} ' u'because key {} was not found', subdata, v, k) From 18a14e8005ee22073f1599fdc023e0eeda17eb1d Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 22 Oct 2016 10:29:48 +0200 Subject: [PATCH 1413/2280] Use generators and decorators to match items: The easy parts --- beets/autotag/hooks.py | 36 ++++++++++++++++-------------------- beets/plugins.py | 10 ++++++++++ 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index b5dfb5d39..15fd1e5e4 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -525,10 +525,7 @@ def album_for_mbid(release_id): if the ID is not found. """ try: - album = mb.album_for_id(release_id) - if album: - plugins.send(u'albuminfo_received', info=album) - return album + return mb.album_for_id(release_id) except mb.MusicBrainzAPIError as exc: exc.log(log) @@ -538,32 +535,31 @@ def track_for_mbid(recording_id): if the ID is not found. """ try: - track = mb.track_for_id(recording_id) - if track: - plugins.send(u'trackinfo_received', info=track) - return track + return mb.track_for_id(recording_id) except mb.MusicBrainzAPIError as exc: exc.log(log) +@plugins.notify_info_received(u'albuminfo_received') def albums_for_id(album_id): """Get a list of albums for an ID.""" - candidates = [album_for_mbid(album_id)] - plugin_albums = plugins.album_for_id(album_id) - for a in plugin_albums: - plugins.send(u'albuminfo_received', info=a) - candidates.extend(plugin_albums) - return [a for a in candidates if a] + a = album_for_mbid(album_id) + if a: + yield a + for a in plugins.album_for_id(album_id): + if a: + yield a +@plugins.notify_info_received(u'trackinfo_received') def tracks_for_id(track_id): """Get a list of tracks for an ID.""" - candidates = [track_for_mbid(track_id)] - plugin_tracks = plugins.track_for_id(track_id) - for t in plugin_tracks: - plugins.send(u'trackinfo_received', info=t) - candidates.extend(plugin_tracks) - return [t for t in candidates if t] + t = track_for_mbid(track_id) + if t: + yield t + for t in plugins.track_for_id(track_id): + if t: + yield t def album_candidates(items, artist, album, va_likely): diff --git a/beets/plugins.py b/beets/plugins.py index 6c48d47d2..e62e2e2d8 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -488,3 +488,13 @@ def sanitize_choices(choices, choices_all): if not (s in seen or seen.add(s)): res.extend(list(others) if s == '*' else [s]) return res + + +def notify_info_received(msg): + def decorator(generator): + def decorated(*args, **kwargs): + for v in generator(*args, **kwargs): + send(msg, info=v) + yield v + return decorated + return decorator From 91d1aa9763607cc262dcb0ae29520eb345eb9560 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 30 Oct 2016 17:20:21 +0100 Subject: [PATCH 1414/2280] plugins: rename notify_info_received->notify_info_yielded --- beets/autotag/hooks.py | 4 ++-- beets/plugins.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 15fd1e5e4..a65316505 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -540,7 +540,7 @@ def track_for_mbid(recording_id): exc.log(log) -@plugins.notify_info_received(u'albuminfo_received') +@plugins.notify_info_yielded(u'albuminfo_received') def albums_for_id(album_id): """Get a list of albums for an ID.""" a = album_for_mbid(album_id) @@ -551,7 +551,7 @@ def albums_for_id(album_id): yield a -@plugins.notify_info_received(u'trackinfo_received') +@plugins.notify_info_yielded(u'trackinfo_received') def tracks_for_id(track_id): """Get a list of tracks for an ID.""" t = track_for_mbid(track_id) diff --git a/beets/plugins.py b/beets/plugins.py index e62e2e2d8..b24310df5 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -490,7 +490,7 @@ def sanitize_choices(choices, choices_all): return res -def notify_info_received(msg): +def notify_info_yielded(msg): def decorator(generator): def decorated(*args, **kwargs): for v in generator(*args, **kwargs): From 2b468c1872364cf4caaf6873ced82e97b50e6043 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 30 Oct 2016 17:21:08 +0100 Subject: [PATCH 1415/2280] plugins: make the signature of notify_info_yielded clearer --- beets/plugins.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index b24310df5..aa6b74393 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -490,11 +490,11 @@ def sanitize_choices(choices, choices_all): return res -def notify_info_yielded(msg): +def notify_info_yielded(event): def decorator(generator): def decorated(*args, **kwargs): for v in generator(*args, **kwargs): - send(msg, info=v) + send(event, info=v) yield v return decorated return decorator From a7fed5b2c40b2cdb59db9e286c8aa493744422d6 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sun, 30 Oct 2016 17:21:32 +0100 Subject: [PATCH 1416/2280] plugins: document notify_info_yielded --- beets/plugins.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/beets/plugins.py b/beets/plugins.py index aa6b74393..3ea15f248 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -491,6 +491,12 @@ def sanitize_choices(choices, choices_all): def notify_info_yielded(event): + """Makes a generator send the event 'event' every time it yields. + This decorator is supposed to decorate a generator, but any function + returning an iterable should work. + Each yielded value is passed to plugins using the 'info' parameter of + 'send'. + """ def decorator(generator): def decorated(*args, **kwargs): for v in generator(*args, **kwargs): From 6e3a9d9bc501e503cbad0f60f6b8fe6a920456a5 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 21 Nov 2016 13:39:44 +0100 Subject: [PATCH 1417/2280] collect search results from plugins with yield --- beets/plugins.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index 3ea15f248..2ecdb8472 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -351,41 +351,35 @@ def album_distance(items, album_info, mapping): def candidates(items, artist, album, va_likely): """Gets MusicBrainz candidates for an album from each plugin. """ - out = [] for plugin in find_plugins(): - out.extend(plugin.candidates(items, artist, album, va_likely)) - return out + for candidate in plugin.candidates(items, artist, album, va_likely): + yield candidate def item_candidates(item, artist, title): """Gets MusicBrainz candidates for an item from the plugins. """ - out = [] for plugin in find_plugins(): - out.extend(plugin.item_candidates(item, artist, title)) - return out + for item_candidate in plugin.item_candidates(item, artist, title): + yield item_candidate def album_for_id(album_id): """Get AlbumInfo objects for a given ID string. """ - out = [] for plugin in find_plugins(): - res = plugin.album_for_id(album_id) - if res: - out.append(res) - return out + album = plugin.album_for_id(album_id) + if album: + yield album def track_for_id(track_id): """Get TrackInfo objects for a given ID string. """ - out = [] for plugin in find_plugins(): - res = plugin.track_for_id(track_id) - if res: - out.append(res) - return out + track = plugin.track_for_id(track_id) + if track: + yield track def template_funcs(): From 7dc458aaf54f46b2a57f0afd581bc37a72ca179f Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 21 Nov 2016 13:43:00 +0100 Subject: [PATCH 1418/2280] tagger: finish generator-decorator simplifications * Propagate generators upwards without realizing them * Use plugins.notify_info_yielded decorator --- beets/autotag/hooks.py | 32 ++++++++++++-------------------- beets/autotag/match.py | 16 ++++++++-------- 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index a65316505..1a9aaf908 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -562,6 +562,7 @@ def tracks_for_id(track_id): yield t +@plugins.notify_info_yielded(u'albuminfo_received') def album_candidates(items, artist, album, va_likely): """Search for album matches. ``items`` is a list of Item objects that make up the album. ``artist`` and ``album`` are the respective @@ -569,51 +570,42 @@ def album_candidates(items, artist, album, va_likely): entered by the user. ``va_likely`` is a boolean indicating whether the album is likely to be a "various artists" release. """ - out = [] - # Base candidates if we have album and artist to match. if artist and album: try: - out.extend(mb.match_album(artist, album, len(items))) + for candidate in mb.match_album(artist, album, len(items)): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Also add VA matches from MusicBrainz where appropriate. if va_likely and album: try: - out.extend(mb.match_album(None, album, len(items))) + for candidate in mb.match_album(None, album, len(items)): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Candidates from plugins. - out.extend(plugins.candidates(items, artist, album, va_likely)) - - # Notify subscribed plugins about fetched album info - for a in out: - plugins.send(u'albuminfo_received', info=a) - - return out + for candidate in plugins.candidates(items, artist, album, va_likely): + yield candidate +@plugins.notify_info_yielded(u'trackinfo_received') def item_candidates(item, artist, title): """Search for item matches. ``item`` is the Item to be matched. ``artist`` and ``title`` are strings and either reflect the item or are specified by the user. """ - out = [] # MusicBrainz candidates. if artist and title: try: - out.extend(mb.match_track(artist, title)) + for candidate in mb.match_track(artist, title): + yield candidate except mb.MusicBrainzAPIError as exc: exc.log(log) # Plugin candidates. - out.extend(plugins.item_candidates(item, artist, title)) - - # Notify subscribed plugins about fetched track info - for i in out: - plugins.send(u'trackinfo_received', info=i) - - return out + for candidate in plugins.item_candidates(item, artist, title): + yield candidate diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 5585c7f5c..493fd20c9 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -409,10 +409,10 @@ def tag_album(items, search_artist=None, search_album=None, # Search by explicit ID. if search_ids: - search_cands = [] for search_id in search_ids: log.debug(u'Searching for album ID: {0}', search_id) - search_cands.extend(hooks.albums_for_id(search_id)) + for id_candidate in hooks.albums_for_id(search_id): + _add_candidate(items, candidates, id_candidate) # Use existing metadata or text search. else: @@ -444,13 +444,13 @@ def tag_album(items, search_artist=None, search_album=None, log.debug(u'Album might be VA: {0}', va_likely) # Get the results from the data sources. - search_cands = hooks.album_candidates(items, search_artist, - search_album, va_likely) - - log.debug(u'Evaluating {0} candidates.', len(search_cands)) - for info in search_cands: - _add_candidate(items, candidates, info) + for matched_candidate in hooks.album_candidates(items, + search_artist, + search_album, + va_likely): + _add_candidate(items, candidates, matched_candidate) + log.debug(u'Evaluating {0} candidates.', len(candidates)) # Sort and get the recommendation. candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) From 9f48338291e38b9f9da6727c59315f98e542f90d Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 24 Nov 2016 19:04:42 +0100 Subject: [PATCH 1419/2280] Corrected docs for modify command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit added short form ´mod´ and added switch ´-f´ --- docs/reference/cli.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index b2683cd86..34e5f0471 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -227,7 +227,8 @@ modify `````` :: - beet modify [-MWay] QUERY [FIELD=VALUE...] [FIELD!...] + beet modify [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...] + beet mod [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...] Change the metadata for items or albums in the database. From 488225d837984c4fa3b7e9134ff57949af200417 Mon Sep 17 00:00:00 2001 From: Peter Kessen Date: Thu, 24 Nov 2016 19:41:31 +0100 Subject: [PATCH 1420/2280] Added documentation and FAQ for selective modify --- docs/faq.rst | 55 ++++++++++++++++++++++++++++++++++++++++++ docs/reference/cli.rst | 7 ++++-- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/docs/faq.rst b/docs/faq.rst index e36b589bb..db1a00e59 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -225,6 +225,61 @@ If you've already moved your music *outside* of beets, you have a few options: - Resort to manually modifying the SQLite database (not recommended). +.. _modify-selected: + +…modify a couple of songs without difficult query? +-------------------------------------------------- + +If you want to modify some items in your library but do not want to spend much time +on a query matching all but not more than those songs, you can create a simple query +and select the items afterwards. + +Let's say you want to tag all your songs of the album "Conspiracy of One" with some +self-defined field but you do not like the intro. With +``beet modify -w mysongs=true Conspiracy of one`` will print:: + + Modifying 14 items. + The Offspring - Conspiracy of One - Intro + mysongs: true + The Offspring - Conspiracy of One - Come Out Swinging + mysongs: true + The Offspring - Conspiracy of One - Original Prankster + mysongs: true + The Offspring - Conspiracy of One - Want You Bad + mysongs: true + The Offspring - Conspiracy of One - Million Miles Away + mysongs: true + The Offspring - Conspiracy of One - Dammit, I Changed Again + mysongs: true + The Offspring - Conspiracy of One - Living \in Chaos + mysongs: true + The Offspring - Conspiracy of One - Special Delivery + mysongs: true + The Offspring - Conspiracy of One - One Fine Day + mysongs: true + The Offspring - Conspiracy of One - All Along + mysongs: true + The Offspring - Conspiracy of One - Denial, Revisited + mysongs: true + The Offspring - Conspiracy of One - Vultures + mysongs: true + The Offspring - Conspiracy of One - Conspiracy of One + mysongs: true + The Offspring - Conspiracy of One - Huck It + mysongs: true + Really modify, move and write tags? (Yes/no/select) + +If you hit ``s`` beet will ask you for each item in the list whether +you want to apply changes:: + + The Offspring - Conspiracy of One - All Along + mysongs: true + Really modify, move and write tags? (yes/no) + +If you now say ``y`` to all items but for Intro you will modify all +songs in the list but Intro. + + Why does beets… =============== diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 34e5f0471..f558deb8c 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -243,8 +243,11 @@ individual tracks. Items will automatically be moved around when necessary if they're in your library directory, but you can disable that with ``-M``. Tags will be written to the files according to the settings you have for imports, but these can be overridden with ``-w`` (write tags, the default) and ``-W`` -(don't write tags). Finally, this command politely asks for your permission -before making any changes, but you can skip that prompt with the ``-y`` switch. +(don't write tags). Finally, this command politely prints a list of all +affected items in the library and asks for your permission before making any +changes. You can then select if you want to abort the change with n, confirm +with y or you can select items to apply the changes with s (see +:ref:`modify-selected`). But you can skip that prompt with the ``-y`` switch. .. _move-cmd: From d6b15f4eaa416c8ba1974caf87723b6e1d517233 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 24 Nov 2016 23:51:10 -0500 Subject: [PATCH 1421/2280] Remove duplicated line in docs (#2280) For consistency: we don't show the aliases here for the other commands. --- docs/reference/cli.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index f558deb8c..c49f82bd3 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -228,7 +228,6 @@ modify :: beet modify [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...] - beet mod [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...] Change the metadata for items or albums in the database. From f31e6110e64b345c49727126fac72906cdc81d6a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 24 Nov 2016 23:59:00 -0500 Subject: [PATCH 1422/2280] Simplify #2280 docs I've backed out the FAQ entry, since the main docs seem like the right place for this. --- docs/faq.rst | 55 ------------------------------------------ docs/reference/cli.rst | 13 +++++++--- 2 files changed, 9 insertions(+), 59 deletions(-) diff --git a/docs/faq.rst b/docs/faq.rst index db1a00e59..e36b589bb 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -225,61 +225,6 @@ If you've already moved your music *outside* of beets, you have a few options: - Resort to manually modifying the SQLite database (not recommended). -.. _modify-selected: - -…modify a couple of songs without difficult query? --------------------------------------------------- - -If you want to modify some items in your library but do not want to spend much time -on a query matching all but not more than those songs, you can create a simple query -and select the items afterwards. - -Let's say you want to tag all your songs of the album "Conspiracy of One" with some -self-defined field but you do not like the intro. With -``beet modify -w mysongs=true Conspiracy of one`` will print:: - - Modifying 14 items. - The Offspring - Conspiracy of One - Intro - mysongs: true - The Offspring - Conspiracy of One - Come Out Swinging - mysongs: true - The Offspring - Conspiracy of One - Original Prankster - mysongs: true - The Offspring - Conspiracy of One - Want You Bad - mysongs: true - The Offspring - Conspiracy of One - Million Miles Away - mysongs: true - The Offspring - Conspiracy of One - Dammit, I Changed Again - mysongs: true - The Offspring - Conspiracy of One - Living \in Chaos - mysongs: true - The Offspring - Conspiracy of One - Special Delivery - mysongs: true - The Offspring - Conspiracy of One - One Fine Day - mysongs: true - The Offspring - Conspiracy of One - All Along - mysongs: true - The Offspring - Conspiracy of One - Denial, Revisited - mysongs: true - The Offspring - Conspiracy of One - Vultures - mysongs: true - The Offspring - Conspiracy of One - Conspiracy of One - mysongs: true - The Offspring - Conspiracy of One - Huck It - mysongs: true - Really modify, move and write tags? (Yes/no/select) - -If you hit ``s`` beet will ask you for each item in the list whether -you want to apply changes:: - - The Offspring - Conspiracy of One - All Along - mysongs: true - Really modify, move and write tags? (yes/no) - -If you now say ``y`` to all items but for Intro you will modify all -songs in the list but Intro. - - Why does beets… =============== diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index c49f82bd3..92ddc14d0 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -242,11 +242,16 @@ individual tracks. Items will automatically be moved around when necessary if they're in your library directory, but you can disable that with ``-M``. Tags will be written to the files according to the settings you have for imports, but these can be overridden with ``-w`` (write tags, the default) and ``-W`` -(don't write tags). Finally, this command politely prints a list of all +(don't write tags). + +When you run the ``modify`` command, it prints a list of all affected items in the library and asks for your permission before making any -changes. You can then select if you want to abort the change with n, confirm -with y or you can select items to apply the changes with s (see -:ref:`modify-selected`). But you can skip that prompt with the ``-y`` switch. +changes. You can then choose to abort the change (type `n`), confirm +(`y`), or interactively choose some of the items (`s`). In the latter case, +the command will prompt you for every matching item or album and invite you to +type `y` or `n`. This option lets you choose precisely which data to change +without spending too much time to carefully craft a query. To skip the prompts +entirely, use the ``-y`` option. .. _move-cmd: From bdfa53c503ad8c58f5f5c44c9e386a0d7852f0f4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:05:34 -0500 Subject: [PATCH 1423/2280] Changelog updates and proofreading --- docs/changelog.rst | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 67116f3e7..70ebd2517 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,47 +4,45 @@ Changelog 1.4.0 (in development) ---------------------- -Version 1.4 is our first step toward supporting Python 3 in addition to Python -2. We're not quite there yet, but thanks mainly to the heroic efforts of -:user:`jrobeson`, we're on our way. A few basic commands work now, and we're -working to bring full support over the next few releases. +Version 1.4 has **alpha-level** Python 3 support. Thanks to the heroic efforts +of :user:`jrobeson`, beets should run both under Python 2.7, as before, and +now under Python 3.4 and above. The support is still new: it undoubtedly +contains bugs, so it may replace all your music with Limp Bizkit---but if +you're brave and you have backups, please try installing on Python 3. Let us +know how it goes. -Specifically, if you package beets for distribution, here's what you'll want -to know: +If you package beets for distribution, here's what you'll want to know: * This version of beets now depends on the `six`_ library. * We also bumped our minimum required version of `Mutagen`_ to 1.33 (from 1.27). -* Please don't package beets as a Python 3 application *yet*, even though some - things may appear to work under Python 3.4 and later. +* Please don't package beets as a Python 3 application *yet*, even though most + things work under Python 3.4 and later. -UI Change: +This version also makes a few changes to the command-line interface and +configuration that you may need to know about: * :doc:`/plugins/duplicates` no longer accepts multiple arguments in the form of ``-k title albumartist album``. Each argument must be prefixed with ``-k``. Example: ``-k title -k albumartist -k album`` +* The old top-level ``colors`` configuration option has been removed (the + setting is now under ``ui``). +* The deprecated ``list_format_album`` and ``list_format_item`` + configuration options have been removed (see :ref:`format_album` and + :ref:`format_item`). -Deprecated configuration optional removals: - -* Remove top level ``colors`` configuration option. -* Remove deprecated ``list_format_album`` and ``list_format_item`` - configuration options. - -The are a couple of small new features: +The are a few new features: * :doc:`/plugins/mpdupdate`, :doc:`/plugins/mpdstats`: When the ``host`` option is not set, these plugins will now look for the ``$MPD_HOST`` environment variable before falling back to ``localhost``. Thanks to :user:`tarruda`. :bug:`2175` * :doc:`/plugins/web`: Added an ``expand`` option to show the items of an - album and a ``path`` field to the JSON output of a file which shows the - filled-out path template for each file. :bug:`2050` + album. :bug:`2050` * :doc:`/plugins/embyupdate`: The plugin can now use an API key instead of a password to authenticate with Emby. :bug:`2045` :bug:`2117` -* :doc:`/plugins/acousticbrainz`: The plugin now also adds a ``bpm`` field - when a song can be found on AcousticBrainz, this is faster and more - automatic than using the :doc:`/plugins/bpm`. -* ``beet --version`` now includes the python version used to run beets. +* :doc:`/plugins/acousticbrainz`: The plugin now adds a ``bpm`` field. +* ``beet --version`` now includes the Python version used to run beets. * :doc:`/reference/pathformat` can now include unescaped commas (``,``) when they are not part of a function call. :bug:`2166` :bug:`2213` * The :ref:`update-cmd` command takes a new ``-F`` flag to specify the fields From 55d9233e39aa903558ebe044174ad9d573c3479b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:06:01 -0500 Subject: [PATCH 1424/2280] Capitalize Python --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index cec502636..8ead3bfad 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1337,7 +1337,7 @@ default_commands.append(stats_cmd) def show_version(lib, opts, args): print_(u'beets version %s' % beets.__version__) - print_(u'python version {}'.format(python_version())) + print_(u'Python version {}'.format(python_version())) # Show plugins. names = sorted(p.name for p in plugins.find_plugins()) if names: From e15bee15f59fa7812cbb2ae9297d138558f5922c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:11:54 -0500 Subject: [PATCH 1425/2280] More changelog proofreading --- docs/changelog.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 70ebd2517..45cde53c3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -53,7 +53,7 @@ And there are a few bug fixes too: * :doc:`/plugins/convert`: The plugin no longer asks for confirmation if the query did not return anything to convert. :bug:`2260` :bug:`2262` * :doc:`/plugins/embedart`: The plugin now uses ``jpg`` as an extension rather - than ``jpeg``, to ensure consistency with :doc:`plugins/fetchart`. + than ``jpeg``, to ensure consistency with the :doc:`plugins/fetchart`. Thanks to :user:`tweitzel`. :bug:`2254` :bug:`2255` * :doc:`/plugins/embedart`: The plugin now works for all jpeg files, including those that are only recognizable by their magic bytes. @@ -76,10 +76,11 @@ And there are a few bug fixes too: This is fixed. :bug:`2168` * :doc:`/plugins/embyupdate`: Fixes authentication header problem that caused a problem that it was not possible to get tokens from the Emby API. -* :doc:`/plugins/lyrics`: Search for lyrics using the title part preceding the - colon character. :bug:`2206` -* Fix a crash when a query contains a date field that is not set for all - the items. :bug:`1938` +* :doc:`/plugins/lyrics`: Some titles use a colon to separate the main title + from a subtitle. To find more matches, the plugin now also searches for + lyrics using the part part preceding the colon character. :bug:`2206` +* Fix a crash when a query uses a date field and some items are missing that + field. :bug:`1938` * :doc:`/plugins/discogs`: Subtracks are now detected and combined into a single track, two-sided mediums are treated as single discs, and tracks have ``media``, ``medium_total`` and ``medium`` set correctly. :bug:`2222` From 9fb358d3c015456d160bf72e7a07c2b0e6e1ba93 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:28:41 -0500 Subject: [PATCH 1426/2280] Even more little changelog fixes --- docs/changelog.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 45cde53c3..893753ada 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,9 +22,10 @@ If you package beets for distribution, here's what you'll want to know: This version also makes a few changes to the command-line interface and configuration that you may need to know about: -* :doc:`/plugins/duplicates` no longer accepts multiple arguments in the form - of ``-k title albumartist album``. Each argument must be prefixed with - ``-k``. Example: ``-k title -k albumartist -k album`` +* :doc:`/plugins/duplicates`: The ``duplicates`` command no longer accepts + multiple field arguments in the form ``-k title albumartist album``. Each + argument must be prefixed with ``-k``, as in ``-k title -k albumartist -k + album``. * The old top-level ``colors`` configuration option has been removed (the setting is now under ``ui``). * The deprecated ``list_format_album`` and ``list_format_item`` From 8d902c0da30540d00ffafe43aae0d6e3abe0af55 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:29:06 -0500 Subject: [PATCH 1427/2280] Release date for 1.4.0 --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 893753ada..5277c081f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.0 (in development) ----------------------- +1.4.0 (November 25, 2016) +------------------------- Version 1.4 has **alpha-level** Python 3 support. Thanks to the heroic efforts of :user:`jrobeson`, beets should run both under Python 2.7, as before, and From d54ef99ea5c7e859244e943b24fe72c36973a380 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:32:39 -0500 Subject: [PATCH 1428/2280] Fix a forgotten test --- test/test_ui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index f1c4c0fc1..99459603a 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -1273,7 +1273,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): def test_version(self): l = self.run_with_output(u'version') - self.assertIn(u'python version', l) + self.assertIn(u'Python version', l) self.assertIn(u'no plugins loaded', l) # # Need to have plugin loaded From d99b46612f922b4a2ca39f56b9cc3f72dace5654 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:37:25 -0500 Subject: [PATCH 1429/2280] Fix version bumping in release.py --- extra/release.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extra/release.py b/extra/release.py index 1d3b7eed5..ce3099a69 100755 --- a/extra/release.py +++ b/extra/release.py @@ -35,8 +35,8 @@ VERSION_LOCS = [ os.path.join(BASE, 'beets', '__init__.py'), [ ( - r'__version__\s*=\s*[\'"]([0-9\.]+)[\'"]', - "__version__ = '{version}'", + r'__version__\s*=\s*u[\'"]([0-9\.]+)[\'"]', + "__version__ = u'{version}'", ) ] ), From 60ec732e10a08f83446473d9861e48682696a7e4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 21:38:06 -0500 Subject: [PATCH 1430/2280] Version bump: 1.4.1 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 4b86c8419..96237b387 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.0' +__version__ = u'1.4.1' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 5277c081f..303818b17 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.1 (in development) +---------------------- + +Changelog goes here! + + 1.4.0 (November 25, 2016) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index 6cddd74c0..8af77582b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.0' +release = '1.4.1' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index a19a45b2e..950a8ab31 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.0', + version='1.4.1', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 839a3166733cf640408417e5a8c8144f5b161f82 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 22:13:54 -0500 Subject: [PATCH 1431/2280] Change released version to 1.4.1 Sadly, I uploaded the wrong file to PyPI for 1.4.0. Once you do this, PyPI never lets you change the file associated with a given released version. So we need to use 1.4.1 instead. :cry: --- docs/changelog.rst | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 303818b17..cb3328320 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,13 +1,7 @@ Changelog ========= -1.4.1 (in development) ----------------------- - -Changelog goes here! - - -1.4.0 (November 25, 2016) +1.4.1 (November 25, 2016) ------------------------- Version 1.4 has **alpha-level** Python 3 support. Thanks to the heroic efforts From cf5fa501e21aca624d0f36e15962e305312463cd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 25 Nov 2016 22:16:03 -0500 Subject: [PATCH 1432/2280] Version bump: 1.4.2 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 96237b387..2fe5933d7 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.1' +__version__ = u'1.4.2' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index cb3328320..17024badb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.2 (in development) +---------------------- + +Changelog goes here! + + 1.4.1 (November 25, 2016) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index 8af77582b..9b612711d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.1' +release = '1.4.2' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 950a8ab31..18fbc9d43 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.1', + version='1.4.2', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 692dea39e8db84bfca2cf0053fec1755ec09336f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 17:30:02 -0500 Subject: [PATCH 1433/2280] MediaFile: Use stock logging This is part of the effort to separate MediaFile from beets (#1966). It avoids using the beets-specific logging infrastructure. This commit is part of fdebab657d6e85de56b3996e8fdece09796940ae from the new MediaFile repository. --- beets/mediafile.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 7d1b07280..f953b9b68 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -64,7 +64,7 @@ import six __all__ = ['UnreadableFileError', 'FileTypeError', 'MediaFile'] -log = logging.getLogger('beets') +log = logging.getLogger(__name__) # Human-readable type names. TYPES = { @@ -134,12 +134,12 @@ def mutagen_call(action, path, func, *args, **kwargs): try: return func(*args, **kwargs) except mutagen.MutagenError as exc: - log.debug(u'{} failed: {}', action, six.text_type(exc)) + log.debug(u'%s failed: %s', action, six.text_type(exc)) raise UnreadableFileError(path) except Exception as exc: # Isolate bugs in Mutagen. - log.debug(u'{}', traceback.format_exc()) - log.error(u'uncaught Mutagen exception in {}: {}', action, exc) + log.debug(u'%s', traceback.format_exc()) + log.error(u'uncaught Mutagen exception in %s: %s', action, exc) raise MutagenError(path, exc) @@ -405,7 +405,7 @@ class Image(object): try: type = list(ImageType)[type] except IndexError: - log.debug(u"ignoring unknown image type index {0}", type) + log.debug(u"ignoring unknown image type index %s", type) type = ImageType.other self.type = type From fc6658c110d904e1738a43d1460a9a833bbe4d97 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 17:31:54 -0500 Subject: [PATCH 1434/2280] Add a missing __future__ import --- test/test_acousticbrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py index 82a69c527..c6cce0f13 100644 --- a/test/test_acousticbrainz.py +++ b/test/test_acousticbrainz.py @@ -16,7 +16,7 @@ """Tests for the 'acousticbrainz' plugin. """ -from __future__ import absolute_import, print_function +from __future__ import division, absolute_import, print_function import json import os.path From c70a9bb873c2c83f912ef6ff7a622e46224f0ff4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 17:32:49 -0500 Subject: [PATCH 1435/2280] Enable Python 3 tests by default in Tox config Now that we're supporting it, I plan to run the Python 3 tests as part of my normal coding workflow. --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 28fd3636e..8115395c6 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = py27-test, py27-flake8, docs +envlist = py27-test, py35-test, py27-flake8, docs # The exhaustive list of environments is: # envlist = py{27,34,35}-{test,cov}, py{27,34,35}-flake8, docs From 075a4b6b85ae798f901a7f76f0bc63813c99cf85 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 17:37:01 -0500 Subject: [PATCH 1436/2280] MediaFile: Avoid using some beets utilities Modularization: #1966 --- beets/mediafile.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index f953b9b68..c57073215 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -58,7 +58,7 @@ import traceback import enum from beets import logging -from beets.util import displayable_path, syspath, as_string +from beets.util import as_string import six @@ -90,7 +90,7 @@ class UnreadableFileError(Exception): """Mutagen is not able to extract information from the file. """ def __init__(self, path): - Exception.__init__(self, displayable_path(path)) + Exception.__init__(self, repr(path)) class FileTypeError(UnreadableFileError): @@ -100,11 +100,10 @@ class FileTypeError(UnreadableFileError): mutagen type is not supported by `Mediafile`. """ def __init__(self, path, mutagen_type=None): - path = displayable_path(path) if mutagen_type is None: - msg = path + msg = repr(path) else: - msg = u'{0}: of mutagen type {1}'.format(path, mutagen_type) + msg = u'{0}: of mutagen type {1}'.format(repr(path), mutagen_type) Exception.__init__(self, msg) @@ -112,7 +111,7 @@ class MutagenError(UnreadableFileError): """Raised when Mutagen fails unexpectedly---probably due to a bug. """ def __init__(self, path, mutagen_exc): - msg = u'{0}: {1}'.format(displayable_path(path), mutagen_exc) + msg = u'{0}: {1}'.format(repr(path), mutagen_exc) Exception.__init__(self, msg) @@ -1412,7 +1411,6 @@ class MediaFile(object): By default, MP3 files are saved with ID3v2.4 tags. You can use the older ID3v2.3 standard by specifying the `id3v23` option. """ - path = syspath(path) self.path = path self.mgfile = mutagen_call('open', path, mutagen.File, path) From 2cc1a61ea492e073ba658bd5ff5085baa6b15298 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 17:40:40 -0500 Subject: [PATCH 1437/2280] MediaFile: Remove one last utility function (#1966) --- beets/mediafile.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index c57073215..a3324e03f 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -58,7 +58,6 @@ import traceback import enum from beets import logging -from beets.util import as_string import six @@ -1486,7 +1485,12 @@ class MediaFile(object): """ for property, descriptor in cls.__dict__.items(): if isinstance(descriptor, MediaField): - yield as_string(property) + if isinstance(property, bytes): + # On Python 2, class field names are bytes. This method + # produces text strings. + yield property.decode('utf8', 'ignore') + else: + yield property @classmethod def _field_sort_name(cls, name): From 54cb0b2a159643132797bd0d3c21c419cee94c57 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:08:00 -0500 Subject: [PATCH 1438/2280] Separate beets-specific MediaFile tests Part of the #1966 separation effort. --- test/test_mediafile.py | 83 +------------------------ test/test_plugin_mediafield.py | 107 +++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 80 deletions(-) create mode 100644 test/test_plugin_mediafield.py diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 32d93f815..b17702fa8 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -27,13 +27,9 @@ from six import assertCountEqual from test import _common from test._common import unittest -from beets.mediafile import MediaFile, MediaField, Image, \ - MP3DescStorageStyle, StorageStyle, MP4StorageStyle, \ - ASFStorageStyle, ImageType, CoverArtField, UnreadableFileError -from beets.library import Item -from beets.plugins import BeetsPlugin +from beets.mediafile import MediaFile, Image, \ + ImageType, CoverArtField, UnreadableFileError from beets.util import bytestring_path -import six class ArtTestMixin(object): @@ -298,80 +294,7 @@ class GenreListTestMixin(object): assertCountEqual(self, mediafile.genres, [u'the genre', u'another']) -field_extension = MediaField( - MP3DescStorageStyle(u'customtag'), - MP4StorageStyle('----:com.apple.iTunes:customtag'), - StorageStyle('customtag'), - ASFStorageStyle('customtag'), -) - - -class ExtendedFieldTestMixin(object): - - def test_extended_field_write(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - try: - mediafile = self._mediafile_fixture('empty') - mediafile.customtag = u'F#' - mediafile.save() - - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, u'F#') - - finally: - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_write_extended_tag_from_item(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - try: - mediafile = self._mediafile_fixture('empty') - self.assertIsNone(mediafile.customtag) - - item = Item(path=mediafile.path, customtag=u'Gb') - item.write() - mediafile = MediaFile(mediafile.path) - self.assertEqual(mediafile.customtag, u'Gb') - - finally: - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_read_flexible_attribute_from_file(self): - plugin = BeetsPlugin() - plugin.add_media_field('customtag', field_extension) - - try: - mediafile = self._mediafile_fixture('empty') - mediafile.update({'customtag': u'F#'}) - mediafile.save() - - item = Item.from_path(mediafile.path) - self.assertEqual(item['customtag'], u'F#') - - finally: - delattr(MediaFile, 'customtag') - Item._media_fields.remove('customtag') - - def test_invalid_descriptor(self): - with self.assertRaises(ValueError) as cm: - MediaFile.add_field('somekey', True) - self.assertIn(u'must be an instance of MediaField', - six.text_type(cm.exception)) - - def test_overwrite_property(self): - with self.assertRaises(ValueError) as cm: - MediaFile.add_field('artist', MediaField()) - self.assertIn(u'property "artist" already exists', - six.text_type(cm.exception)) - - -class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, - ExtendedFieldTestMixin): +class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin): """Test writing and reading tags. Subclasses must set ``extension`` and ``audio_properties``. """ diff --git a/test/test_plugin_mediafield.py b/test/test_plugin_mediafield.py new file mode 100644 index 000000000..d9d2b0a1f --- /dev/null +++ b/test/test_plugin_mediafield.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Tests the facility that lets plugins add custom field to MediaFile. +""" +from __future__ import division, absolute_import, print_function + +import os +import six +import shutil + +from test import _common +from beets.library import Item +from beets import mediafile +from beets.plugins import BeetsPlugin +from beets.util import bytestring_path + + +field_extension = mediafile.MediaField( + mediafile.MP3DescStorageStyle(u'customtag'), + mediafile.MP4StorageStyle('----:com.apple.iTunes:customtag'), + mediafile.StorageStyle('customtag'), + mediafile.ASFStorageStyle('customtag'), +) + + +class ExtendedFieldTestMixin(_common.TestCase): + + def _mediafile_fixture(self, name, extension='mp3'): + name = bytestring_path(name + '.' + extension) + src = os.path.join(_common.RSRC, name) + target = os.path.join(self.temp_dir, name) + shutil.copy(src, target) + return mediafile.MediaFile(target) + + def test_extended_field_write(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + mf.customtag = u'F#' + mf.save() + + mf = mediafile.MediaFile(mf.path) + self.assertEqual(mf.customtag, u'F#') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_write_extended_tag_from_item(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + self.assertIsNone(mf.customtag) + + item = Item(path=mf.path, customtag=u'Gb') + item.write() + mf = mediafile.MediaFile(mf.path) + self.assertEqual(mf.customtag, u'Gb') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_read_flexible_attribute_from_file(self): + plugin = BeetsPlugin() + plugin.add_media_field('customtag', field_extension) + + try: + mf = self._mediafile_fixture('empty') + mf.update({'customtag': u'F#'}) + mf.save() + + item = Item.from_path(mf.path) + self.assertEqual(item['customtag'], u'F#') + + finally: + delattr(mediafile.MediaFile, 'customtag') + Item._media_fields.remove('customtag') + + def test_invalid_descriptor(self): + with self.assertRaises(ValueError) as cm: + mediafile.MediaFile.add_field('somekey', True) + self.assertIn(u'must be an instance of MediaField', + six.text_type(cm.exception)) + + def test_overwrite_property(self): + with self.assertRaises(ValueError) as cm: + mediafile.MediaFile.add_field('artist', mediafile.MediaField()) + self.assertIn(u'property "artist" already exists', + six.text_type(cm.exception)) From 47049e1ff1395a42870e95365eb0f0aea30cad19 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:23:46 -0500 Subject: [PATCH 1439/2280] Avoid one last beets utility in MediaFile tests This is a little dirty, what with the hard-coded encoding, but I don't feel too bad about it because we're only manipulating our test fixtures and temporary directory that way. More on #1966. --- test/test_mediafile.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index b17702fa8..280698a9a 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -29,7 +29,6 @@ from test import _common from test._common import unittest from beets.mediafile import MediaFile, Image, \ ImageType, CoverArtField, UnreadableFileError -from beets.util import bytestring_path class ArtTestMixin(object): @@ -379,7 +378,10 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin): ] def setUp(self): - self.temp_dir = bytestring_path(tempfile.mkdtemp()) + name = tempfile.mkdtemp() + if not isinstance(name, bytes): + name = name.encode('utf8') + self.temp_dir = name def tearDown(self): if os.path.isdir(self.temp_dir): @@ -632,7 +634,9 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin): self.fail('\n '.join(errors)) def _mediafile_fixture(self, name): - name = bytestring_path(name + '.' + self.extension) + name = name + '.' + self.extension + if not isinstance(name, bytes): + name = name.encode('utf8') src = os.path.join(_common.RSRC, name) target = os.path.join(self.temp_dir, name) shutil.copy(src, target) From 788654736d0ed75b673e9a1b378d9c8e9e7a8cde Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:26:18 -0500 Subject: [PATCH 1440/2280] Obviate the need for a beets utility in MF tests Even more on #1966. --- test/test_mediafile_edge.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index ae758f142..af3bdfa6b 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -25,7 +25,6 @@ from test import _common from test._common import unittest from test.helper import TestHelper -from beets.util import bytestring_path import beets.mediafile import six @@ -334,12 +333,12 @@ class SoundCheckTest(unittest.TestCase): class ID3v23Test(unittest.TestCase, TestHelper): - def _make_test(self, ext='mp3', id3v23=False): + def _make_test(self, ext=b'mp3', id3v23=False): self.create_temp_dir() src = os.path.join(_common.RSRC, - bytestring_path('full.{0}'.format(ext))) + b'full.' + ext) self.path = os.path.join(self.temp_dir, - bytestring_path('test.{0}'.format(ext))) + b'test.' + ext) shutil.copy(src, self.path) return beets.mediafile.MediaFile(self.path, id3v23=id3v23) @@ -369,7 +368,7 @@ class ID3v23Test(unittest.TestCase, TestHelper): self._delete_test() def test_v23_on_non_mp3_is_noop(self): - mf = self._make_test('m4a', id3v23=True) + mf = self._make_test(b'm4a', id3v23=True) try: mf.year = 2013 mf.save() From 24940c0de76aa8fcb2797024511652b99d7c3557 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:27:20 -0500 Subject: [PATCH 1441/2280] In MediaFile tests, use simpler import path This will make it easier to copy these tests into their own repository. --- test/test_mediafile_edge.py | 76 ++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index af3bdfa6b..81a6c4416 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -25,11 +25,11 @@ from test import _common from test._common import unittest from test.helper import TestHelper -import beets.mediafile +from beets import mediafile import six -_sc = beets.mediafile._safe_cast +_sc = mediafile._safe_cast class EdgeTest(unittest.TestCase): @@ -37,7 +37,7 @@ class EdgeTest(unittest.TestCase): # Some files have an ID3 frame that has a list with no elements. # This is very hard to produce, so this is just the first 8192 # bytes of a file found "in the wild". - emptylist = beets.mediafile.MediaFile( + emptylist = mediafile.MediaFile( os.path.join(_common.RSRC, b'emptylist.mp3') ) genre = emptylist.genre @@ -46,7 +46,7 @@ class EdgeTest(unittest.TestCase): def test_release_time_with_space(self): # Ensures that release times delimited by spaces are ignored. # Amie Street produces such files. - space_time = beets.mediafile.MediaFile( + space_time = mediafile.MediaFile( os.path.join(_common.RSRC, b'space_time.mp3') ) self.assertEqual(space_time.year, 2009) @@ -56,7 +56,7 @@ class EdgeTest(unittest.TestCase): def test_release_time_with_t(self): # Ensures that release times delimited by Ts are ignored. # The iTunes Store produces such files. - t_time = beets.mediafile.MediaFile( + t_time = mediafile.MediaFile( os.path.join(_common.RSRC, b't_time.m4a') ) self.assertEqual(t_time.year, 1987) @@ -66,20 +66,20 @@ class EdgeTest(unittest.TestCase): def test_tempo_with_bpm(self): # Some files have a string like "128 BPM" in the tempo field # rather than just a number. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, b'bpm.mp3')) + f = mediafile.MediaFile(os.path.join(_common.RSRC, b'bpm.mp3')) self.assertEqual(f.bpm, 128) def test_discc_alternate_field(self): # Different taggers use different vorbis comments to reflect # the disc and disc count fields: ensure that the alternative # style works. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, b'discc.ogg')) + f = mediafile.MediaFile(os.path.join(_common.RSRC, b'discc.ogg')) self.assertEqual(f.disc, 4) self.assertEqual(f.disctotal, 5) def test_old_ape_version_bitrate(self): media_file = os.path.join(_common.RSRC, b'oldape.ape') - f = beets.mediafile.MediaFile(media_file) + f = mediafile.MediaFile(media_file) self.assertEqual(f.bitrate, 0) def test_only_magic_bytes_jpeg(self): @@ -91,13 +91,13 @@ class EdgeTest(unittest.TestCase): with open(magic_bytes_file, 'rb') as f: jpg_data = f.read() self.assertEqual( - beets.mediafile._imghdr_what_wrapper(jpg_data), 'jpeg') + mediafile._imghdr_what_wrapper(jpg_data), 'jpeg') def test_soundcheck_non_ascii(self): # Make sure we don't crash when the iTunes SoundCheck field contains # non-ASCII binary data. - f = beets.mediafile.MediaFile(os.path.join(_common.RSRC, - b'soundcheck-nonascii.m4a')) + f = mediafile.MediaFile(os.path.join(_common.RSRC, + b'soundcheck-nonascii.m4a')) self.assertEqual(f.rg_track_gain, 0.0) @@ -157,35 +157,35 @@ class SafetyTest(unittest.TestCase, TestHelper): with open(fn, 'w') as f: f.write(data) try: - self.assertRaises(exc, beets.mediafile.MediaFile, fn) + self.assertRaises(exc, mediafile.MediaFile, fn) finally: os.unlink(fn) # delete the temporary file def test_corrupt_mp3_raises_unreadablefileerror(self): # Make sure we catch Mutagen reading errors appropriately. - self._exccheck(b'corrupt.mp3', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.mp3', mediafile.UnreadableFileError) def test_corrupt_mp4_raises_unreadablefileerror(self): - self._exccheck(b'corrupt.m4a', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.m4a', mediafile.UnreadableFileError) def test_corrupt_flac_raises_unreadablefileerror(self): - self._exccheck(b'corrupt.flac', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.flac', mediafile.UnreadableFileError) def test_corrupt_ogg_raises_unreadablefileerror(self): - self._exccheck(b'corrupt.ogg', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ogg', mediafile.UnreadableFileError) def test_invalid_ogg_header_raises_unreadablefileerror(self): - self._exccheck(b'corrupt.ogg', beets.mediafile.UnreadableFileError, + self._exccheck(b'corrupt.ogg', mediafile.UnreadableFileError, 'OggS\x01vorbis') def test_corrupt_monkeys_raises_unreadablefileerror(self): - self._exccheck(b'corrupt.ape', beets.mediafile.UnreadableFileError) + self._exccheck(b'corrupt.ape', mediafile.UnreadableFileError) def test_invalid_extension_raises_filetypeerror(self): - self._exccheck(b'something.unknown', beets.mediafile.FileTypeError) + self._exccheck(b'something.unknown', mediafile.FileTypeError) def test_magic_xml_raises_unreadablefileerror(self): - self._exccheck(b'nothing.xml', beets.mediafile.UnreadableFileError, + self._exccheck(b'nothing.xml', mediafile.UnreadableFileError, "ftyp") @unittest.skipUnless(_common.HAVE_SYMLINK, u'platform lacks symlink') @@ -193,8 +193,8 @@ class SafetyTest(unittest.TestCase, TestHelper): fn = os.path.join(_common.RSRC, b'brokenlink') os.symlink('does_not_exist', fn) try: - self.assertRaises(beets.mediafile.UnreadableFileError, - beets.mediafile.MediaFile, fn) + self.assertRaises(mediafile.UnreadableFileError, + mediafile.MediaFile, fn) finally: os.unlink(fn) @@ -205,7 +205,7 @@ class SideEffectsTest(unittest.TestCase): def test_opening_tagless_file_leaves_untouched(self): old_mtime = os.stat(self.empty).st_mtime - beets.mediafile.MediaFile(self.empty) + mediafile.MediaFile(self.empty) new_mtime = os.stat(self.empty).st_mtime self.assertEqual(old_mtime, new_mtime) @@ -217,7 +217,7 @@ class MP4EncodingTest(unittest.TestCase, TestHelper): self.path = os.path.join(self.temp_dir, b'test.m4a') shutil.copy(src, self.path) - self.mf = beets.mediafile.MediaFile(self.path) + self.mf = mediafile.MediaFile(self.path) def tearDown(self): self.remove_temp_dir() @@ -225,7 +225,7 @@ class MP4EncodingTest(unittest.TestCase, TestHelper): def test_unicode_label_in_m4a(self): self.mf.label = u'foo\xe8bar' self.mf.save() - new_mf = beets.mediafile.MediaFile(self.path) + new_mf = mediafile.MediaFile(self.path) self.assertEqual(new_mf.label, u'foo\xe8bar') @@ -236,7 +236,7 @@ class MP3EncodingTest(unittest.TestCase, TestHelper): self.path = os.path.join(self.temp_dir, b'test.mp3') shutil.copy(src, self.path) - self.mf = beets.mediafile.MediaFile(self.path) + self.mf = mediafile.MediaFile(self.path) def test_comment_with_latin1_encoding(self): # Set up the test file with a Latin1-encoded COMM frame. The encoding @@ -249,7 +249,7 @@ class MP3EncodingTest(unittest.TestCase, TestHelper): self.mf.save() -class ZeroLengthMediaFile(beets.mediafile.MediaFile): +class ZeroLengthMediaFile(mediafile.MediaFile): @property def length(self): return 0.0 @@ -270,7 +270,7 @@ class TypeTest(unittest.TestCase): def setUp(self): super(TypeTest, self).setUp() path = os.path.join(_common.RSRC, b'full.mp3') - self.mf = beets.mediafile.MediaFile(path) + self.mf = mediafile.MediaFile(path) def test_year_integer_in_string(self): self.mf.year = u'2009' @@ -302,32 +302,32 @@ class TypeTest(unittest.TestCase): class SoundCheckTest(unittest.TestCase): def test_round_trip(self): - data = beets.mediafile._sc_encode(1.0, 1.0) - gain, peak = beets.mediafile._sc_decode(data) + data = mediafile._sc_encode(1.0, 1.0) + gain, peak = mediafile._sc_decode(data) self.assertEqual(gain, 1.0) self.assertEqual(peak, 1.0) def test_decode_zero(self): data = b' 80000000 80000000 00000000 00000000 00000000 00000000 ' \ b'00000000 00000000 00000000 00000000' - gain, peak = beets.mediafile._sc_decode(data) + gain, peak = mediafile._sc_decode(data) self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) def test_malformatted(self): - gain, peak = beets.mediafile._sc_decode(b'foo') + gain, peak = mediafile._sc_decode(b'foo') self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) def test_special_characters(self): - gain, peak = beets.mediafile._sc_decode(u'caf\xe9'.encode('utf-8')) + gain, peak = mediafile._sc_decode(u'caf\xe9'.encode('utf-8')) self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) def test_decode_handles_unicode(self): # Most of the time, we expect to decode the raw bytes. But some formats # might give us text strings, which we need to handle. - gain, peak = beets.mediafile._sc_decode(u'caf\xe9') + gain, peak = mediafile._sc_decode(u'caf\xe9') self.assertEqual(gain, 0.0) self.assertEqual(peak, 0.0) @@ -340,7 +340,7 @@ class ID3v23Test(unittest.TestCase, TestHelper): self.path = os.path.join(self.temp_dir, b'test.' + ext) shutil.copy(src, self.path) - return beets.mediafile.MediaFile(self.path, id3v23=id3v23) + return mediafile.MediaFile(self.path, id3v23=id3v23) def _delete_test(self): self.remove_temp_dir() @@ -385,9 +385,9 @@ class ID3v23Test(unittest.TestCase, TestHelper): mf = self._make_test(id3v23=v23) try: mf.images = [ - beets.mediafile.Image(b'data', desc=u""), - beets.mediafile.Image(b'data', desc=u"foo"), - beets.mediafile.Image(b'data', desc=u"\u0185"), + mediafile.Image(b'data', desc=u""), + mediafile.Image(b'data', desc=u"foo"), + mediafile.Image(b'data', desc=u"\u0185"), ] mf.save() apic_frames = mf.mgfile.tags.getall('APIC') From a88682e7bbc03b94aabb3290058b8c9b8aba80e0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:46:44 -0500 Subject: [PATCH 1442/2280] Undo `from _common import unittest` indirection This was a vestige from when we used to need the unittest2 library for pre-2.7 compatibility. Now that we require Python 2.7, we aren't using that library and this indirection wasn't doing any good. --- test/test_acousticbrainz.py | 3 ++- test/test_art.py | 2 +- test/test_autotag.py | 2 +- test/test_bucket.py | 2 +- test/test_config_command.py | 2 +- test/test_convert.py | 3 ++- test/test_datequery.py | 2 +- test/test_dbcore.py | 2 +- test/test_discogs.py | 3 ++- test/test_edit.py | 2 +- test/test_embedart.py | 2 +- test/test_embyupdate.py | 2 +- test/test_fetchart.py | 2 +- test/test_filefilter.py | 2 +- test/test_files.py | 2 +- test/test_ftintitle.py | 2 +- test/test_hidden.py | 2 +- test/test_hook.py | 2 +- test/test_ihate.py | 2 +- test/test_importadded.py | 2 +- test/test_importer.py | 2 +- test/test_importfeeds.py | 2 +- test/test_info.py | 2 +- test/test_ipfs.py | 7 ++++--- test/test_keyfinder.py | 2 +- test/test_lastgenre.py | 2 +- test/test_library.py | 2 +- test/test_logging.py | 3 ++- test/test_lyrics.py | 4 ++-- test/test_mb.py | 3 ++- test/test_mbsubmit.py | 2 +- test/test_mbsync.py | 2 +- test/test_mediafile.py | 2 +- test/test_mediafile_edge.py | 2 +- test/test_metasync.py | 2 +- test/test_mpdstats.py | 2 +- test/test_permissions.py | 2 +- test/test_pipeline.py | 2 +- test/test_play.py | 2 +- test/test_player.py | 2 +- test/test_plexupdate.py | 2 +- test/test_plugins.py | 3 ++- test/test_query.py | 2 +- test/test_replaygain.py | 5 +++-- test/test_smartplaylist.py | 2 +- test/test_sort.py | 2 +- test/test_spotify.py | 2 +- test/test_template.py | 4 ++-- test/test_the.py | 2 +- test/test_thumbnails.py | 2 +- test/test_types_plugin.py | 2 +- test/test_ui.py | 2 +- test/test_ui_commands.py | 2 +- test/test_ui_importer.py | 3 ++- test/test_ui_init.py | 2 +- test/test_util.py | 2 +- test/test_vfs.py | 2 +- test/test_web.py | 2 +- test/test_zero.py | 2 +- test/testall.py | 3 +-- 60 files changed, 74 insertions(+), 66 deletions(-) diff --git a/test/test_acousticbrainz.py b/test/test_acousticbrainz.py index c6cce0f13..0b1407581 100644 --- a/test/test_acousticbrainz.py +++ b/test/test_acousticbrainz.py @@ -20,8 +20,9 @@ from __future__ import division, absolute_import, print_function import json import os.path +import unittest -from test._common import unittest, RSRC +from test._common import RSRC from beetsplug.acousticbrainz import AcousticPlugin, ABSCHEME diff --git a/test/test_art.py b/test/test_art.py index 5c3a4d7e9..aba180780 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -19,12 +19,12 @@ from __future__ import division, absolute_import, print_function import os import shutil +import unittest import responses from mock import patch from test import _common -from test._common import unittest from beetsplug import fetchart from beets.autotag import AlbumInfo, AlbumMatch from beets import config diff --git a/test/test_autotag.py b/test/test_autotag.py index b2f3fd61d..6f107afa4 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -19,9 +19,9 @@ from __future__ import division, absolute_import, print_function import re import copy +import unittest from test import _common -from test._common import unittest from beets import autotag from beets.autotag import match from beets.autotag.hooks import Distance, string_dist diff --git a/test/test_bucket.py b/test/test_bucket.py index daade86ad..61f6cfe24 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -17,7 +17,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beetsplug import bucket from beets import config, ui diff --git a/test/test_config_command.py b/test/test_config_command.py index 26242132d..35ba6ca0e 100644 --- a/test/test_config_command.py +++ b/test/test_config_command.py @@ -7,11 +7,11 @@ import yaml from mock import patch from tempfile import mkdtemp from shutil import rmtree +import unittest from beets import ui from beets import config -from test._common import unittest from test.helper import TestHelper from beets.library import Library import six diff --git a/test/test_convert.py b/test/test_convert.py index 0d1804288..2a32e51e7 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -17,8 +17,9 @@ from __future__ import division, absolute_import, print_function import re import os.path +import unittest + from test import _common -from test._common import unittest from test import helper from test.helper import control_stdin, capture_log diff --git a/test/test_datequery.py b/test/test_datequery.py index c139c0c4a..1e1625db2 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -18,8 +18,8 @@ from __future__ import division, absolute_import, print_function from test import _common -from test._common import unittest from datetime import datetime +import unittest import time from beets.dbcore.query import _parse_periods, DateInterval, DateQuery diff --git a/test/test_dbcore.py b/test/test_dbcore.py index bb6a56fab..d070e257e 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -20,10 +20,10 @@ from __future__ import division, absolute_import, print_function import os import shutil import sqlite3 +import unittest from six import assertRaisesRegex from test import _common -from test._common import unittest from beets import dbcore from tempfile import mkstemp import six diff --git a/test/test_discogs.py b/test/test_discogs.py index 0f89ff923..5fe5926b8 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -17,8 +17,9 @@ """ from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest, Bag +from test._common import Bag from beetsplug.discogs import DiscogsPlugin diff --git a/test/test_edit.py b/test/test_edit.py index a23860b07..2900d092a 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -15,10 +15,10 @@ from __future__ import division, absolute_import, print_function import codecs +import unittest from mock import patch from test import _common -from test._common import unittest from test.helper import TestHelper, control_stdin from test.test_ui_importer import TerminalImportSessionSetup from test.test_importer import ImportHelper, AutotagStub diff --git a/test/test_embedart.py b/test/test_embedart.py index 0d64b0d9a..ee08ecb4e 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -19,9 +19,9 @@ import os.path import shutil from mock import patch, MagicMock import tempfile +import unittest from test import _common -from test._common import unittest from test.helper import TestHelper from beets.mediafile import MediaFile diff --git a/test/test_embyupdate.py b/test/test_embyupdate.py index 17e82c73e..2b83a4896 100644 --- a/test/test_embyupdate.py +++ b/test/test_embyupdate.py @@ -2,9 +2,9 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest from test.helper import TestHelper from beetsplug import embyupdate +import unittest import responses diff --git a/test/test_fetchart.py b/test/test_fetchart.py index 5def538eb..91bc34101 100644 --- a/test/test_fetchart.py +++ b/test/test_fetchart.py @@ -16,7 +16,7 @@ from __future__ import division, absolute_import, print_function import os -from test._common import unittest +import unittest from test.helper import TestHelper from beets import util diff --git a/test/test_filefilter.py b/test/test_filefilter.py index 09b6d94a4..e7a4119d4 100644 --- a/test/test_filefilter.py +++ b/test/test_filefilter.py @@ -20,9 +20,9 @@ from __future__ import division, absolute_import, print_function import os import shutil +import unittest from test import _common -from test._common import unittest from test.helper import capture_log from test.test_importer import ImportHelper from beets import config diff --git a/test/test_files.py b/test/test_files.py index 884aa40d0..b566f363e 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -21,9 +21,9 @@ import shutil import os import stat from os.path import join +import unittest from test import _common -from test._common import unittest from test._common import item, touch import beets.library from beets import util diff --git a/test/test_ftintitle.py b/test/test_ftintitle.py index 711b5daa6..d698263be 100644 --- a/test/test_ftintitle.py +++ b/test/test_ftintitle.py @@ -17,7 +17,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import TestHelper from beetsplug import ftintitle diff --git a/test/test_hidden.py b/test/test_hidden.py index cb673a64a..e2dd1afb3 100644 --- a/test/test_hidden.py +++ b/test/test_hidden.py @@ -17,7 +17,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest import sys import tempfile from beets.util import hidden diff --git a/test/test_hook.py b/test/test_hook.py index cd6b2734f..39fd08959 100644 --- a/test/test_hook.py +++ b/test/test_hook.py @@ -17,9 +17,9 @@ from __future__ import division, absolute_import, print_function import os.path import tempfile +import unittest from test import _common -from test._common import unittest from test.helper import TestHelper from beets import config diff --git a/test/test_ihate.py b/test/test_ihate.py index 1b23964ae..f52617481 100644 --- a/test/test_ihate.py +++ b/test/test_ihate.py @@ -4,7 +4,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beets import importer from beets.library import Item from beetsplug.ihate import IHatePlugin diff --git a/test/test_importadded.py b/test/test_importadded.py index bd8d8b506..52aa26756 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -18,8 +18,8 @@ from __future__ import division, absolute_import, print_function """Tests for the `importadded` plugin.""" import os +import unittest -from test._common import unittest from test.test_importer import ImportHelper, AutotagStub from beets import importer from beets import util diff --git a/test/test_importer.py b/test/test_importer.py index 55b03378c..500ca027d 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -27,9 +27,9 @@ from tempfile import mkstemp from zipfile import ZipFile from tarfile import TarFile from mock import patch, Mock +import unittest from test import _common -from test._common import unittest from beets.util import displayable_path, bytestring_path, py3_path from test.helper import TestImportSession, TestHelper, has_program, capture_log from beets import importer diff --git a/test/test_importfeeds.py b/test/test_importfeeds.py index adb2885c7..064f5eee5 100644 --- a/test/test_importfeeds.py +++ b/test/test_importfeeds.py @@ -6,8 +6,8 @@ import os import os.path import tempfile import shutil +import unittest -from test._common import unittest from beets import config from beets.library import Item, Album, Library from beetsplug.importfeeds import ImportFeedsPlugin diff --git a/test/test_info.py b/test/test_info.py index f7973796e..f5375e2f6 100644 --- a/test/test_info.py +++ b/test/test_info.py @@ -15,7 +15,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import TestHelper from beets.mediafile import MediaFile diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 66d895f2e..9c523d6e5 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -20,11 +20,12 @@ from beets import library from beets.util import bytestring_path, _fsencoding from beetsplug.ipfs import IPFSPlugin -from test import _common -from test._common import unittest -from test.helper import TestHelper +import unittest import os +from test import _common +from test.helper import TestHelper + @patch('beets.util.command_output', Mock()) class IPFSPluginTest(unittest.TestCase, TestHelper): diff --git a/test/test_keyfinder.py b/test/test_keyfinder.py index 57e2bcd9c..c2b4227d7 100644 --- a/test/test_keyfinder.py +++ b/test/test_keyfinder.py @@ -16,7 +16,7 @@ from __future__ import division, absolute_import, print_function from mock import patch -from test._common import unittest +import unittest from test.helper import TestHelper from beets.library import Item diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index c060e95a9..f57471f1c 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -17,10 +17,10 @@ from __future__ import division, absolute_import, print_function +import unittest from mock import Mock from test import _common -from test._common import unittest from beetsplug import lastgenre from beets import config diff --git a/test/test_library.py b/test/test_library.py index 174e6d527..26c78c99d 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -25,9 +25,9 @@ import re import unicodedata import sys import time +import unittest from test import _common -from test._common import unittest from test._common import item import beets.library import beets.mediafile diff --git a/test/test_logging.py b/test/test_logging.py index 6e5e6c8b6..a6b02a572 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -7,12 +7,13 @@ import sys import threading import logging as log from six import StringIO +import unittest import beets.logging as blog from beets import plugins, ui import beetsplug from test import _common -from test._common import unittest, TestCase +from test._common import TestCase from test import helper import six diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 429dee4e8..13ba07fdf 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -18,13 +18,13 @@ from __future__ import division, absolute_import, print_function import os -from test import _common import sys import re +import unittest +from test import _common from mock import MagicMock -from test._common import unittest from beetsplug import lyrics from beets.library import Item from beets.util import confit, bytestring_path diff --git a/test/test_mb.py b/test/test_mb.py index 43656451d..ecbcf3c59 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -18,9 +18,10 @@ from __future__ import division, absolute_import, print_function from test import _common -from test._common import unittest from beets.autotag import mb from beets import config + +import unittest import mock diff --git a/test/test_mbsubmit.py b/test/test_mbsubmit.py index a33d8418b..3402c8464 100644 --- a/test/test_mbsubmit.py +++ b/test/test_mbsubmit.py @@ -15,7 +15,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import capture_stdout, control_stdin, TestHelper from test.test_importer import ImportHelper, AutotagStub from test.test_ui_importer import TerminalImportSessionSetup diff --git a/test/test_mbsync.py b/test/test_mbsync.py index 57213878c..411af8d0a 100644 --- a/test/test_mbsync.py +++ b/test/test_mbsync.py @@ -15,9 +15,9 @@ from __future__ import division, absolute_import, print_function +import unittest from mock import patch -from test._common import unittest from test.helper import TestHelper,\ generate_album_info, \ generate_track_info, \ diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 280698a9a..458ad6d8a 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -23,10 +23,10 @@ import shutil import tempfile import datetime import time +import unittest from six import assertCountEqual from test import _common -from test._common import unittest from beets.mediafile import MediaFile, Image, \ ImageType, CoverArtField, UnreadableFileError diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 81a6c4416..2aae30c55 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -19,10 +19,10 @@ from __future__ import division, absolute_import, print_function import os import shutil +import unittest import mutagen.id3 from test import _common -from test._common import unittest from test.helper import TestHelper from beets import mediafile diff --git a/test/test_metasync.py b/test/test_metasync.py index 60f63c413..ef16c57a2 100644 --- a/test/test_metasync.py +++ b/test/test_metasync.py @@ -21,9 +21,9 @@ import time from datetime import datetime from beets.library import Item from beets.util import py3_path +import unittest from test import _common -from test._common import unittest from test.helper import TestHelper diff --git a/test/test_mpdstats.py b/test/test_mpdstats.py index febf292d8..7452be86b 100644 --- a/test/test_mpdstats.py +++ b/test/test_mpdstats.py @@ -15,8 +15,8 @@ from __future__ import division, absolute_import, print_function +import unittest from mock import Mock, patch, call, ANY -from test._common import unittest from test.helper import TestHelper from beets.library import Item diff --git a/test/test_permissions.py b/test/test_permissions.py index 040839110..ed84798f1 100644 --- a/test/test_permissions.py +++ b/test/test_permissions.py @@ -6,9 +6,9 @@ from __future__ import division, absolute_import, print_function import os import platform +import unittest from mock import patch, Mock -from test._common import unittest from test.helper import TestHelper from beets.util import displayable_path from beetsplug.permissions import (check_permissions, diff --git a/test/test_pipeline.py b/test/test_pipeline.py index 4d3bde4d0..228deb50e 100644 --- a/test/test_pipeline.py +++ b/test/test_pipeline.py @@ -18,8 +18,8 @@ from __future__ import division, absolute_import, print_function import six +import unittest -from test._common import unittest from beets.util import pipeline diff --git a/test/test_play.py b/test/test_play.py index c05e24c51..9d66d7466 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -19,9 +19,9 @@ from __future__ import division, absolute_import, print_function import os +import unittest from mock import patch, ANY -from test._common import unittest from test.helper import TestHelper, control_stdin from beets.ui import UserError diff --git a/test/test_player.py b/test/test_player.py index c8fec446b..0a576f0ba 100644 --- a/test/test_player.py +++ b/test/test_player.py @@ -17,7 +17,7 @@ """ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from beetsplug import bpd diff --git a/test/test_plexupdate.py b/test/test_plexupdate.py index 2a2b1cbaf..f8b0bdcd9 100644 --- a/test/test_plexupdate.py +++ b/test/test_plexupdate.py @@ -2,9 +2,9 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest from test.helper import TestHelper from beetsplug.plexupdate import get_music_section, update_plex +import unittest import responses diff --git a/test/test_plugins.py b/test/test_plugins.py index d45e317ca..c4a5792ff 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -19,6 +19,7 @@ import os from mock import patch, Mock, ANY import shutil import itertools +import unittest from beets.importer import SingletonImportTask, SentinelImportTask, \ ArchiveImportTask, action @@ -30,7 +31,7 @@ from beets.util import displayable_path, bytestring_path from test.test_importer import ImportHelper, AutotagStub from test.test_ui_importer import TerminalImportSessionSetup -from test._common import unittest, RSRC +from test._common import RSRC from test import helper diff --git a/test/test_query.py b/test/test_query.py index e0bbebfe1..41672ab35 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -21,9 +21,9 @@ from functools import partial from mock import patch import os import sys +import unittest from test import _common -from test._common import unittest from test import helper import beets.library diff --git a/test/test_replaygain.py b/test/test_replaygain.py index d2a8aa9ba..6ea21ecb6 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -16,14 +16,15 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest +import six + from test.helper import TestHelper, has_program from beets import config from beets.mediafile import MediaFile from beetsplug.replaygain import (FatalGstreamerPluginReplayGainError, GStreamerBackend) -import six try: import gi diff --git a/test/test_smartplaylist.py b/test/test_smartplaylist.py index 5e1fed084..af60501a4 100644 --- a/test/test_smartplaylist.py +++ b/test/test_smartplaylist.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function from os import path, remove from tempfile import mkdtemp from shutil import rmtree +import unittest from mock import Mock, MagicMock @@ -29,7 +30,6 @@ from beets.util import syspath, bytestring_path, py3_path, CHAR_REPLACE from beets.ui import UserError from beets import config -from test._common import unittest from test.helper import TestHelper diff --git a/test/test_sort.py b/test/test_sort.py index d10bd5759..d611ff2d6 100644 --- a/test/test_sort.py +++ b/test/test_sort.py @@ -17,8 +17,8 @@ """ from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest import beets.library from beets import dbcore from beets import config diff --git a/test/test_spotify.py b/test/test_spotify.py index 20101d76c..17f3ef42f 100644 --- a/test/test_spotify.py +++ b/test/test_spotify.py @@ -6,9 +6,9 @@ from __future__ import division, absolute_import, print_function import os import responses +import unittest from test import _common -from test._common import unittest from beets import config from beets.library import Item from beetsplug import spotify diff --git a/test/test_template.py b/test/test_template.py index 67d5d97fe..1cbe9be0c 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -17,9 +17,9 @@ """ from __future__ import division, absolute_import, print_function -from test._common import unittest -from beets.util import functemplate +import unittest import six +from beets.util import functemplate def _normexpr(expr): diff --git a/test/test_the.py b/test/test_the.py index 422723386..72e9bf161 100644 --- a/test/test_the.py +++ b/test/test_the.py @@ -4,7 +4,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test import _common from beets import config from beetsplug.the import ThePlugin, PATTERN_A, PATTERN_THE, FORMAT diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index fe1c80f4a..d287c073a 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -19,8 +19,8 @@ import os.path from mock import Mock, patch, call from tempfile import mkdtemp from shutil import rmtree +import unittest -from test._common import unittest from test.helper import TestHelper from beets.util import bytestring_path diff --git a/test/test_types_plugin.py b/test/test_types_plugin.py index 826dd5ea7..541bd30df 100644 --- a/test/test_types_plugin.py +++ b/test/test_types_plugin.py @@ -17,8 +17,8 @@ from __future__ import division, absolute_import, print_function import time from datetime import datetime +import unittest -from test._common import unittest from test.helper import TestHelper from beets.util.confit import ConfigValueError diff --git a/test/test_ui.py b/test/test_ui.py index 99459603a..681900ae4 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -24,10 +24,10 @@ import subprocess import platform from copy import deepcopy import six +import unittest from mock import patch, Mock from test import _common -from test._common import unittest from test.helper import capture_stdout, has_program, TestHelper, control_stdin from beets import library diff --git a/test/test_ui_commands.py b/test/test_ui_commands.py index 5cd1131eb..764d1b009 100644 --- a/test/test_ui_commands.py +++ b/test/test_ui_commands.py @@ -20,9 +20,9 @@ from __future__ import division, absolute_import, print_function import os import shutil +import unittest from test import _common -from test._common import unittest from beets import library from beets import ui diff --git a/test/test_ui_importer.py b/test/test_ui_importer.py index cc2938ad3..48a66dc5f 100644 --- a/test/test_ui_importer.py +++ b/test/test_ui_importer.py @@ -20,8 +20,9 @@ test_importer module. But here the test importer inherits from """ from __future__ import division, absolute_import, print_function +import unittest -from test._common import unittest, DummyIO +from test._common import DummyIO from test import test_importer from beets.ui.commands import TerminalImportSession from beets import importer diff --git a/test/test_ui_init.py b/test/test_ui_init.py index 0628d3879..3a146b0c0 100644 --- a/test/test_ui_init.py +++ b/test/test_ui_init.py @@ -18,8 +18,8 @@ from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest from beets import ui diff --git a/test/test_util.py b/test/test_util.py index 96d02f955..0d0bbd7b0 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -20,10 +20,10 @@ import sys import re import os import subprocess +import unittest from mock import patch, Mock -from test._common import unittest from test import _common from beets import util import six diff --git a/test/test_vfs.py b/test/test_vfs.py index 0b25a1031..b94acfd09 100644 --- a/test/test_vfs.py +++ b/test/test_vfs.py @@ -16,8 +16,8 @@ """Tests for the virtual filesystem builder..""" from __future__ import division, absolute_import, print_function +import unittest from test import _common -from test._common import unittest from beets import library from beets import vfs diff --git a/test/test_web.py b/test/test_web.py index 7d477227c..e72ecf33d 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -4,9 +4,9 @@ from __future__ import division, absolute_import, print_function +import unittest from six import assertCountEqual -from test._common import unittest from test import _common import json from beets.library import Item, Album diff --git a/test/test_zero.py b/test/test_zero.py index 7b90e22b3..5842d9ed4 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -4,7 +4,7 @@ from __future__ import division, absolute_import, print_function -from test._common import unittest +import unittest from test.helper import TestHelper from beets.library import Item diff --git a/test/testall.py b/test/testall.py index aebda21ee..88eb70117 100755 --- a/test/testall.py +++ b/test/testall.py @@ -20,8 +20,7 @@ from __future__ import division, absolute_import, print_function import os import re import sys - -from test._common import unittest +import unittest pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) From d8c0a42e6caf0c155ad70e8e8ce0e77dfca67cdd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 18:55:58 -0500 Subject: [PATCH 1443/2280] Avoid TestHelper dependency in MediaFile tests Part of #1966. This also introduces a nicer, more lightweight way to create and destroy temporary directories, decoupling that functionality from the giant morass that is TestHelper. --- test/_common.py | 22 ++++++++++++++++++++++ test/test_mediafile.py | 12 ++++-------- test/test_mediafile_edge.py | 9 ++++----- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/test/_common.py b/test/_common.py index 09747e595..4522d2da5 100644 --- a/test/_common.py +++ b/test/_common.py @@ -333,6 +333,28 @@ class Bag(object): return self.fields.get(key) +# Convenience methods for setting up a temporary sandbox directory for tests +# that need to interact with the filesystem. + +class TempDirMixin(object): + """Text mixin for creating and deleting a temporary directory. + """ + + def create_temp_dir(self): + """Create a temporary directory and assign it into `self.temp_dir`. + Call `remove_temp_dir` later to delete it. + """ + path = tempfile.mkdtemp() + if not isinstance(path, bytes): + path = path.encode('utf8') + self.temp_dir = path + + def remove_temp_dir(self): + """Delete the temporary directory created by `create_temp_dir`. + """ + shutil.rmtree(self.temp_dir) + + # Platform mocking. @contextmanager diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 458ad6d8a..463cd534d 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -20,7 +20,6 @@ from __future__ import division, absolute_import, print_function import os import shutil -import tempfile import datetime import time import unittest @@ -293,7 +292,8 @@ class GenreListTestMixin(object): assertCountEqual(self, mediafile.genres, [u'the genre', u'another']) -class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin): +class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, + _common.TempDirMixin): """Test writing and reading tags. Subclasses must set ``extension`` and ``audio_properties``. """ @@ -378,14 +378,10 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin): ] def setUp(self): - name = tempfile.mkdtemp() - if not isinstance(name, bytes): - name = name.encode('utf8') - self.temp_dir = name + self.create_temp_dir() def tearDown(self): - if os.path.isdir(self.temp_dir): - shutil.rmtree(self.temp_dir) + self.remove_temp_dir() def test_read_nonexisting(self): mediafile = self._mediafile_fixture('full') diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 2aae30c55..657ca455d 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -23,7 +23,6 @@ import unittest import mutagen.id3 from test import _common -from test.helper import TestHelper from beets import mediafile import six @@ -145,7 +144,7 @@ class InvalidValueToleranceTest(unittest.TestCase): self.assertEqual(v, 1.0) -class SafetyTest(unittest.TestCase, TestHelper): +class SafetyTest(unittest.TestCase, _common.TempDirMixin): def setUp(self): self.create_temp_dir() @@ -210,7 +209,7 @@ class SideEffectsTest(unittest.TestCase): self.assertEqual(old_mtime, new_mtime) -class MP4EncodingTest(unittest.TestCase, TestHelper): +class MP4EncodingTest(unittest.TestCase, _common.TempDirMixin): def setUp(self): self.create_temp_dir() src = os.path.join(_common.RSRC, b'full.m4a') @@ -229,7 +228,7 @@ class MP4EncodingTest(unittest.TestCase, TestHelper): self.assertEqual(new_mf.label, u'foo\xe8bar') -class MP3EncodingTest(unittest.TestCase, TestHelper): +class MP3EncodingTest(unittest.TestCase, _common.TempDirMixin): def setUp(self): self.create_temp_dir() src = os.path.join(_common.RSRC, b'full.mp3') @@ -332,7 +331,7 @@ class SoundCheckTest(unittest.TestCase): self.assertEqual(peak, 0.0) -class ID3v23Test(unittest.TestCase, TestHelper): +class ID3v23Test(unittest.TestCase, _common.TempDirMixin): def _make_test(self, ext=b'mp3', id3v23=False): self.create_temp_dir() src = os.path.join(_common.RSRC, From 9de27c6b70d460a43839728704332fc71587191c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Nov 2016 20:48:12 -0500 Subject: [PATCH 1444/2280] Sync up with separate MediaFile repository --- beets/mediafile.py | 3 +-- test/_common.py | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index a3324e03f..9db6ba4db 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -56,8 +56,7 @@ import imghdr import os import traceback import enum - -from beets import logging +import logging import six diff --git a/test/_common.py b/test/_common.py index 4522d2da5..597f0dc38 100644 --- a/test/_common.py +++ b/test/_common.py @@ -352,7 +352,8 @@ class TempDirMixin(object): def remove_temp_dir(self): """Delete the temporary directory created by `create_temp_dir`. """ - shutil.rmtree(self.temp_dir) + if os.path.isdir(self.temp_dir): + shutil.rmtree(self.temp_dir) # Platform mocking. From c3e63084d2299920396d976604f7ae896e22be37 Mon Sep 17 00:00:00 2001 From: xarph Date: Sat, 26 Nov 2016 23:08:35 -0800 Subject: [PATCH 1445/2280] =?UTF-8?q?fix=20for=20unidecode=20converting=20?= =?UTF-8?q?=C2=A2=20into=20C/,=20ruining=20paths.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beets/library.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index e80c4da72..78155d2b2 100755 --- a/beets/library.py +++ b/beets/library.py @@ -824,7 +824,11 @@ class Item(LibModel): subpath = unicodedata.normalize('NFC', subpath) if beets.config['asciify_paths']: - subpath = unidecode(subpath) + path_components = subpath.split(os.path.sep) + sep_replace = beets.config['path_sep_replace'].get() + for index, item in enumerate(path_components): + path_components[index] = unidecode(item).replace(os.path.sep,sep_replace) + subpath = os.path.sep.join(path_components) maxlen = beets.config['max_filename_length'].get(int) if not maxlen: From 430369062bf899b8a650e0f8eace011c53c86e4a Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Tue, 29 Nov 2016 00:28:38 +0530 Subject: [PATCH 1446/2280] Fixed a small typo --- beetsplug/mbcollection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index a590a7605..992c51fe3 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -80,7 +80,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): self.update_album_list([task.album]) def update_album_list(self, album_list): - """Update the MusicBrainz colleciton from a list of Beets albums + """Update the MusicBrainz collection from a list of Beets albums """ # Get the available collections. collections = mb_call(musicbrainzngs.get_collections) From 318661b4a90ef61c328587eb8dc74f607daf5d98 Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Tue, 29 Nov 2016 01:53:59 +0530 Subject: [PATCH 1447/2280] Added parsing of secondary album types. Fixes #2200 --- beets/autotag/mb.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 78d382d87..6ce75772c 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -276,11 +276,18 @@ def album_info(release): disambig.append(release.get('disambiguation')) info.albumdisambig = u', '.join(disambig) - # Release type not always populated. - if 'type' in release['release-group']: - reltype = release['release-group']['type'] - if reltype: - info.albumtype = reltype.lower() + # Considers all release types (both primary and secondary) and stores as a comma-separated string + all_types = [] + if 'primary-type' in release['release-group']: + rel_primarytype = release['release-group']['primary-type'] + if rel_primarytype: + all_types.append(rel_primarytype.lower()) + if 'secondary-type-list' in release['release-group']: + for secondarytype in release['release-group']['secondary-type-list']: + all_types.append(secondarytype.lower()) + if len(all_types) != 0: + all_types = ','.join(all_types) + info.albumtype = all_types.lower() # Release dates. release_date = release.get('date') From 0701e66391385def2670a9afa6ccd5afe9026be3 Mon Sep 17 00:00:00 2001 From: Nathan Musoke Date: Tue, 29 Nov 2016 12:11:12 +1300 Subject: [PATCH 1448/2280] Fix rst syntax error in docs --- docs/plugins/fetchart.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index c839b90ba..7eb8c194e 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -60,7 +60,7 @@ file. The available options are: Default: None. - **google_engine**: The custom search engine to use. Default: The `beets custom search engine`_, which searches the entire web. - **fanarttv_key**: The personal API key for requesting art from +- **fanarttv_key**: The personal API key for requesting art from fanart.tv. See below. - **store_source**: If enabled, fetchart stores the artwork's source in a flexible tag named ``art_source``. See below for the rationale behind this. From a9d9d83660fccce266dd439567ccce62f803104d Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Tue, 29 Nov 2016 10:05:17 +0530 Subject: [PATCH 1449/2280] Added support for type field and made code more elegant --- beets/autotag/mb.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 6ce75772c..452aa7d50 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -276,18 +276,22 @@ def album_info(release): disambig.append(release.get('disambiguation')) info.albumdisambig = u', '.join(disambig) - # Considers all release types (both primary and secondary) and stores as a comma-separated string + # Considers all release types (both primary and secondary) and + # stores them as a comma-separated string all_types = [] if 'primary-type' in release['release-group']: rel_primarytype = release['release-group']['primary-type'] if rel_primarytype: all_types.append(rel_primarytype.lower()) if 'secondary-type-list' in release['release-group']: - for secondarytype in release['release-group']['secondary-type-list']: - all_types.append(secondarytype.lower()) - if len(all_types) != 0: - all_types = ','.join(all_types) - info.albumtype = all_types.lower() + all_types.extend([secondarytype.lower() for secondarytype in\ + release['release-group']['secondary-type-list']]) + if 'type' in release['release-group']: + rel_type = release['release-group']['type'] + if rel_type and rel_type.lower() not in all_types: + all_types.append(rel_type) + if len(all_types): + info.albumtype = ', '.join(all_types).lower() # Release dates. release_date = release.get('date') From 957bfacf21229bda17b4ba145fad5c2e5171bdbe Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 30 Nov 2016 08:40:15 -0500 Subject: [PATCH 1450/2280] Fix Backbone.js link --- docs/plugins/web.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index b267af9d2..f4ae063e0 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -72,7 +72,7 @@ The Web backend is built using a simple REST+JSON API with the excellent `Backbone.js`_. This allows future non-Web clients to use the same backend API. .. _Flask: http://flask.pocoo.org/ -.. _Backbone.js: http://documentcloud.github.com/backbone/ +.. _Backbone.js: http://backbonejs.org Eventually, to make the Web player really viable, we should use a Flash fallback for unsupported formats/browsers. There are a number of options for this: From 0c61e08d7fa2e98cf03bacd631fc57bd1460f0be Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Wed, 30 Nov 2016 20:34:40 +0530 Subject: [PATCH 1451/2280] Added new Album types as logs --- beets/autotag/mb.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 452aa7d50..17cb62776 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -278,20 +278,19 @@ def album_info(release): # Considers all release types (both primary and secondary) and # stores them as a comma-separated string - all_types = [] + if 'type' in release['release-group']: + reltype = release['release-group']['type'] + if reltype: + info.albumtype = reltype.lower() if 'primary-type' in release['release-group']: rel_primarytype = release['release-group']['primary-type'] if rel_primarytype: - all_types.append(rel_primarytype.lower()) + log.debug('Primary Type (new data): ' + rel_primarytype.lower()) if 'secondary-type-list' in release['release-group']: - all_types.extend([secondarytype.lower() for secondarytype in\ - release['release-group']['secondary-type-list']]) - if 'type' in release['release-group']: - rel_type = release['release-group']['type'] - if rel_type and rel_type.lower() not in all_types: - all_types.append(rel_type) - if len(all_types): - info.albumtype = ', '.join(all_types).lower() + if release['release-group']['secondary-type-list']: + log.debug('Secondary Type(s) (new data): ' + ', '.join( + [secondarytype.lower() for secondarytype in \ + release['release-group']['secondary-type-list']])) # Release dates. release_date = release.get('date') From 1217efd2bd4a63645a605136856cee30de25bec9 Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Wed, 30 Nov 2016 20:44:12 +0530 Subject: [PATCH 1452/2280] Changed comment to reflect current status --- beets/autotag/mb.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 17cb62776..0d689917e 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -276,8 +276,9 @@ def album_info(release): disambig.append(release.get('disambiguation')) info.albumdisambig = u', '.join(disambig) - # Considers all release types (both primary and secondary) and - # stores them as a comma-separated string + # Retrieves the Release type. + # Considers all other release types(including primary and secondary) (new) + # and logs them. if 'type' in release['release-group']: reltype = release['release-group']['type'] if reltype: From 082f944ac68d7b34f8ea3bcefb3a9cf5bacc15de Mon Sep 17 00:00:00 2001 From: anshuman73 Date: Thu, 1 Dec 2016 02:07:00 +0530 Subject: [PATCH 1453/2280] Removed redundant backslash --- beets/autotag/mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 0d689917e..ed7287860 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -290,7 +290,7 @@ def album_info(release): if 'secondary-type-list' in release['release-group']: if release['release-group']['secondary-type-list']: log.debug('Secondary Type(s) (new data): ' + ', '.join( - [secondarytype.lower() for secondarytype in \ + [secondarytype.lower() for secondarytype in release['release-group']['secondary-type-list']])) # Release dates. From 991c9936fdcb65627d0f2f37afc116a4e62a3e22 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 3 Dec 2016 11:20:06 -0500 Subject: [PATCH 1454/2280] Fix #2299: non-Unicode logging in badfiles --- beetsplug/badfiles.py | 2 +- docs/changelog.rst | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index bb14c7762..5ab0ae983 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -105,7 +105,7 @@ class BadFiles(BeetsPlugin): ui.print_(u"{}: checker exited withs status {}" .format(ui.colorize('text_error', dpath), status)) for line in output: - ui.print_(" {}".format(displayable_path(line))) + ui.print_(u" {}".format(displayable_path(line))) elif errors > 0: ui.print_(u"{}: checker found {} errors or warnings" .format(ui.colorize('text_warning', dpath), errors)) diff --git a/docs/changelog.rst b/docs/changelog.rst index 17024badb..22e453f57 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,9 @@ Changelog 1.4.2 (in development) ---------------------- -Changelog goes here! +Fixes: + +* :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` 1.4.1 (November 25, 2016) From edd34267c69f776c949c477d12d1da0a718f307b Mon Sep 17 00:00:00 2001 From: xarph Date: Sat, 3 Dec 2016 15:29:27 -0800 Subject: [PATCH 1455/2280] modify DestinationTest.test_asciify_and_replace to include unicode titles that decode to path separator. Added an empty .mp3 file with problematic characters for asciify_paths in id3v2 tags for future tests if needed. --- test/rsrc/unicode_path_sep.mp3 | Bin 0 -> 10368 bytes test/test_library.py | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 test/rsrc/unicode_path_sep.mp3 diff --git a/test/rsrc/unicode_path_sep.mp3 b/test/rsrc/unicode_path_sep.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..fa543b7fb957dd0e8612d983de27786a58ea3a0e GIT binary patch literal 10368 zcmeZtF=l39U|`^>4+(HJWME+6XJBAREGo$?E;+OaLWel|I599V@PZ_Al1g(AElLDY zA)X;dP~noylAP2-i@+4fuu(i30;3@?8UmvsFd72HhQR;d0Y@;@dgi6&L+d0B1_s4) z1~xVx9${f&Nl66-1vNDt9UWt1OG`@!2RAo2AD`gh;K;~?goL!ToSdBE;>ya(hK9Db zww|8JlPAxdxnRM9Wy{vAS+jZb&Ye3C95{CD*qJkzFJHcS^TC4$&z`+`^XBvCpFe;8 z|Ifg{VCm!N>uRiLX|BMy6yzq|e+&#F4l1lQP7DkVAa}&?{u&38z=Og5VdgMg^~ZrF zMB;|2k`F_7XF~|bajE|x;FRH4++Ha?p`})m!-2tg-f`>aPQt&8_WzpyUeW%S@V{CP z=Y>)&>P`ZT6FNBm#^y55PGdc&n4o4cJv7NcJuo7Hu_0q&>i_@q|KBvKyc+rB|L>q9ip}hr z8+jZ!YB?>;5*ipcFWfreL79@AS^Ju1wD?t5B09QRf|Inmhh+j|NsA2RC4vEndg?I zaJ_riS#s?-OJ=iS-*WBCc1hF2^VZMaxBdVB|9}4f%DS6fR_m!%ES&Mi`4+FT<#Lgk zEeuB#7sxVPFWsGev3hG(_OcZ-Pik`nI&9~Ad~18`tee`~`gZ01|Mt@D|Ngx9kDeb6 z|0;Fj^LmhnteZL3Zsl^|xPIXKw!{ub=>>kub4=dMVfL66zRoL@!+u#@`q}5U`*wwN zzb>i!S$p3r{L|dpd)Go{xGu4K$$i4N%Sm}!;}RF4nH=^f{=c6Vlk(8tR&n_S+ zz3N460X^GSbVTTt<(%*ac__S@bM00Z1zuZ5#%+omjOq*bwqDblSu_9t_gz09=WUJf z6U~-?dpAksK38J6m}l9E_C<2)9wFlDLJmw)nQ5ChD;3?GDz>%C>f5Hbi)~&#=!%L8 zW9i6Q8s@xg-kB{a{_DSUxNF zuloQ0f4!f(EAoAA*tWOnSFV+B4QZRmRne;GuBh%_a+T*y`p;|qMlZefR{goQb#?B& z$-BC;=L8vsE=y*5J?XXD3AR&QM=~zEwSqj9*W4Mo5#%9G@ofr67}XatO=6h9ue@YS zXi8Y-{h}E?Jk$N+CK+z8xqK&3lKIusDBFAIUi+IzZ98_UxAy1b3BNb5zJ9FyA+yv+ z=RMJBPK(yt@lI;v2-524(pb!6f3BzRf3~&HivBdMyx@hwm1m06GVg}8Y8l<^Qd{@f zTKmM*_y3pmZspnkPPi#D_-nFIq>0$my+v%2o2of2{S>p7uk@=fhRg^LRwMlvj6{=M(T zgB)v_V?Cz_E%2dtg|C& zA-{}cWcxfG37KA_mg-r)t5vt^T-omAjXT_?{4l&XA#BQ(`}R&h{-{s9f1>;M{eStdRi*_+ za~@48>0i&P%w@8X+dGm;6__~E_`<|G~VHU5Q zxhMZj*P73&C*HjLGV|a%F3r;lD(Y+I#e}O1m~Nglf4-T$`u~3gf6lAjoq6wZA;?1; znmJCc2YE=+a@&Fv42vVaEWG(w9USU-k_zRu#1s=_gheue`A8#fg@fFJHFW``X|AKk0VF{g=+E+6Iw~ z;yK@zUCb0R;b_!JO88;x;L^bu{{R1fUCI2=Wz)r)JwvS18c%J{n#gth>LjZ-B^O(H zcD^V!^}ZXea?Ad*vI|eg^8O$H?Eh6fpDg*h<4oh1HM*vZA30OvQ#afc;$RAX!ftt7 zOj<=p0py`0%wA_Vvncf1GV+>%3xykr|LXtS%L~2yHYMSZXJ^xt*z?|*yCqUTr&+%g z&QuPPm*(20Z!Kiy7Cfic=ZM7hV(!aV&WFow`@DFXZN?7CWX>ffF_3d|G$1(;kBGC@1o95#SEPn)2__ozLb*H ztD7mlNnyW>N6ZwEhpsYnE?m!|z&lq`-t-{{qx8a_8K)f^c)U2fj&U$MFx>zD|G#UP z(&8OwvPI9N22K24u6be2@sg_bde2-HUwN<0dvUC+YG-(~#LaRgF z19K*ny9#lzZR&ipM%n#Cz=Mg+8+JY7@Vlctd*eB|_@BXN=FOWpXN`Th^xsAOlarec z`#CLDUHST4UVOxh=ESEL4K^K2&Dsd^(2Hhn)2%ECtfGwV+a9n8DDLpwcKkgkn@MMW zIy2qaP+~^(tn<42Tlim zjbqQ=v+KKrcI?hxIOl?|bdG^tz>kEV7XubpMEJ-v9}5xHN%Sdf;Q#;s|G%Y?_5c5u zuC=TDxaoaS`_!_BZRdaP@bbQ1TJvbC;Vsv+bz2N3@f6ADyjiyQ-_@lrznR74=jo=T zMNXNueck;`?yGMuYDvn-2rg33wPZW0=%TFrz|!I;#6vu(n;8@ubx%5OTgbzx_M`s) z|Nra%|NnpQPrs7k*2$4GjJQr^25GzQmFreNE-xmaAj0Lx@ZhY!*AtDz8#7aGskT>g ztlawVx3RTqnncmMbe+}nBLZgZ{NsJaaLtxISJ@}L3szHHEtmc`?0Q3>MI|H*9-Bi9`k*NK|Nme4Y2PBNtdyvUg40WzPdUsv`!u}i1ilo$ixt9l4th z>h)Ge%sVGzvq@+Bx##b~0~6MzMO*FCPERRf+A?9%bfdDX21eS-2{Qsblr(-!Wxl}w z|DEqj6Bo0M9Ot`@re5{>d3RIZ8iTl=^eCl?&N*QdmTZ*0vg*=1*UGy2pWkn+-?!<{ zg3e#9ClXCVx?01RrDSETNEB2)c{0SshtJ_c&Xkx-+m1BI|NsC0^@sZZAP>D__AcDa zXBHA^0y!J(2NIVWz5 z81Kc20iH*m>c5N&HhExwX7*|0iyIBY{bRIC`6S=<{GHOqJ$;E)qoT)-20u}58U3!7 z;;r@qEDj7m?I3|Q-};KCR{VrjJF`-}dY-BrpD7%fxP{B7=as^#<_?~g^AGwh*fj4iMYn*plwD`!A+zE0*|Nr#<5BAW@ zX6~6ASwJ2tG*j?kT=w(V|NsA=Gv+w1|NT9u=IegZkXO00H2%%}+wn@5xrpmS?#3&r z+uom8ZW%fA>9R+&|NToYzn?F?=DYv-Gi{0GVQVL^(45Sa;@v%O!-EgUo=#RfH^auI z#YDHlL~Yjez()*r6^#G?|Nl9qZ`1$(uOHspcbd0%PXDjiox+Hq&9pV4Sp?CJD!A-C)4QfuXi zu2W%)CN#C~JSQtL-Nm9&j4!0ry~HiLYogwj_n)+P8%+Cp_EpZNi^l_BIre3#EEBP> z6Mn_dK2<})!PhTLeV!1Ppe{?#w3Q5I1t2fI|Mlzt|A}*EN(IDRSfp?N<)xGA`lxGK zUL}hX_0pdGJt#Lz^xBn41)W=Ui~sB0|Nqx=|Cjym?7eM!w_Wy*OFzHn;M8lf#@z~5 zy1ET_{#t!&na$06JHY{z*ZOIdhhwq?csm_{QRtat$P24PhWkW_7pelnt$bp zkmsTkZ(I^gMOY3W$PhMDXq@V3=rBQO>L!qfUN?Ks+{$vGcP?YA*#Zxt%{LfNskk)0 zUR8Je|Nm~A@5wSrCP#~7V$M5lzwojsO7v-c-20h%ZBKoV+zQ?^GbsJct~ck;-LItNQygsi39EDM=CPw=^Q&DqPqp!YDzg=fR32L=MW z_5Xj>oEy)3cEKL0jC-lc->&R_`6SuZc=MHuDL3C|9A?+pp7H(GxlhgS?AF)+|JfO5 z|NsB~-~V=Zy!}(^+9Q=Z;n;$eR|2_Or^vBQIV57m$FqR*!b6aUUNv)9f;=?uV3t`z z52M;o2LAv5|HaR8urAyGf8|;cmj!>E4L+1A&D9Z1-{ah}j7!<9?cbc5^^=d9w*1UH zd&#`NW5Uk!=jPu_FPfKk|L2}9Cg04z-j02`MqHcqUehztMCU6f{9~;={5vA98!*^q zFs5D=)#+bb|Le`&s~USlX61F7u6krr+PwGWw7>KBMcFjY5dL=c^=9VZ?2k93N69Z1 zU-I~4vGn|%dhdKcSEZ$u&Hp@C-+ukx9NR6WUxwEEBK@<^-jszn>fLvNXQ zY_~EwaGE-1nskf&x&QzF|L&o&QgDY$)tokC3D*nj zQkNUcEVC9=3q171GQU*yXr6-el%^D0?fC!y|J@aQ5wbgCrmDq5Rv`%+g(Q!|?%mu? z28N8zO`Hr2e1VeS5SuG&YFsV<|JR}ow~9|r<5*gEzovDj<3*FR{iinub3C*tv2~+2WQ(`YVsL zK51v)h1l*m3f8mx{p?pU8sSU;qD~vpj#*-juLO)fTHteoYMIF;vdY7nb%Y z*%Fyr6y)L~tO52AGw;NW3F=C zc$RW5=xAb)T;)7K~+-|*BZXR@ZRA$O25sNxUVp1OEr-;1s;&QqZx zI))b+`=+s|9Bkyd%D^C(aEXO?>zb=ErAjlT>;He*KU3=2!dCm$xfZWOL^O4NddL6X z7Z)1%+4$>P4{?FEm7k{Ab$&8Zty5m#|KsPsI;+0hB^t#R*B32W(Y9KO_oESu8)xHP z=8XwoE|g~rH11?Nc2c9G0pcO=ubbH&dgn5hno|M#4T z&+~B!Pxd@&Joy&S3U@`#m{XPYzeQcG`i>V|JFHgkoa-BP)4YAj|7rhfcFp|1LgB<4 zwOcpm`ONIplGa$LB$OoKb5%u2m~ld^qSnf(pfo24N^}2Nd4mtFN&WxREnR=oW)rpa zl&ZpbOf1Vf5*R(0Wzjn)_eIfE} z-3n{n4oSKeDZSWIqT}S#AM{$X0_36BOgy1mnG$(z8STv$eqrd!kY?iE;~}WAf`R@2 z|1a^!Tt3X;+W-I4my51*eq}_ho~(a#Pt4^Hp8tFz-<*22>X`T~89NEp#>t($!CEfG z_4EIZ&Zu07y%D}+D#Jk0z z@zVDH?{20SSO5Pxb)}8qF*Uy;+jo`cj_niQQ})JU|IBBTzO5FGxNXfL=`Qj_aQB*3 z&;MWE{`U2$b&CVN-gKQ(;5qjuS>%Y}(SQy$DR~(akcZwk^VDu+b>I~2tlg#niXjUz z5!1xgDFXKY|9{H0KVT$tIcomjQ)!iV4?mn5C^`SUrfRfyPWrmA#mW;G#;tiUL0EKx zR^wgPT`T8`UVruG-uK_P_v;PZ3;|6L#Dr!9$dp7-kBx$?_g3D?33RlN^$SKgIlUF2*V^;zXgx0Up%l0}l2 z>OcL8i@90<{OGEBt(V=+oF@fkb#m1?=NP#uOjyD?YYE6hubX&EH?unQ+MR3y6$;BU zd}a$Cm=L5HbL$s_(8F1vMQi&R z7#M`^esO4==)95jm-l0v(7Us@GkKh}T)AOY(d0Zyh1Tth?#;UzWXrF0E2C9nP1oKD z*WB;^um5`8*Sl!1mVUUL<(X$pt7RN{4tJQI;<0p6e$DW-kbwcxmV3_39k`Km0ng@> z#ikF=2&ymq|E?>0>codZ9Z&uL|4-brsj?>DAn5wF>Adg7n z)q?cnGW~D8e}t)=*PeR%U;Sx=sy}-SjiZdGMYJ5w*m?bt-@)I@pH0$nK7J=Ca+8X1 zP{gaSAX89ki!*j<{Qv*|_N3?p?rz)p|35w2YZCTz37hLlFS&${j+1^nn~cwXzQvlv z^07p2mGCSh6SJqO>fzp1bH1Mc{QUp_liKh8{xAESogdWtCfKBLijZH_C7VWjPz=3f z;;G%r>dE{49g z28P<2|Ks{eSyuJ)&K3yA{TSUwXK#2Io*}BkmJKs&snFxP7aJvcJex+ zIP>Fa=72BOcB;A;SU?_n*~H_yo^v6uwP%D`;ueP97qfZ(|Np;H?99=EHiyLvbH8 z-E+FVO?^dDl<*aeX&$G!WgBL`oqT4>iUr-wS^G*E7?=g3vojg$|Gk_3zprO;DsSSq z{XbKy9!#5R_lHzgNl{r}sW-Rwxic;Pm+kBlHi*UmyU9(=$lWzz4lc6|A}dL zUO#(tdhXm#sj0K8_f<1nGQO|5Wnm|4ASA)Z{hEhAp*59(fq~CE+mq40d(*t48;3VP z&+S=#=krF*Ntc+7{+(mKa?EDwjq_8BEjxE9Mqa5rlO*FivrUFuOUp{)%yqfki=ok= zlyG7S3w^7%H$`wmEpn6xs1)*7JN}u`%%AG z-D<~li>=A6#@oKUd|xc!ctLLU*H!BGf3G+BUTt*QJNc^JiPi|Ancb;JOpKk3@8-4s zte-#q>HmDM_)a_JuVhLyY>F_Mlw&9U~5=o+grWUJ~l+JcwTI4>9X9Fmbd1fy34J#``L!s z_v_>T?0^6K<5!8e_`6@N)`mTdHd&YWebR2u3qtxVTGCD}SGYkQdd0+*yIgbu&)S<) zwkd2;+`MqH9OLO^m&Q5EkAH5QIA!4lhx=Mv_CMM*-}}Fb^4EeX(F?OfJzGQ=Mch@) zH5aB|yQOkA=i2Fo%;z{Z+yDRnyL@^2Ze!UpSw6>>m51)Eaxh*v;hmd`z$uVV-fwnb z{Qv*vCV!U{%R|jx=1QjL|1AA?eMY#GZ}H1$N50hPx6T0*Z$Q1w0!sPBv3mp}72}gxA9cRl`tqWDzUfimgSs6zcrC7ou-YoI|^XEVRU;ktO&1_Ab6IFOvw&y1IFqD)$xhl+TeD7Y| zXZ!vC%9p$A+tmtnt)73_?CUMjaA98$jfRfrPBMndtGeAfk11a}*SC1l0kiu5zwLdR z!W?GEF)%PRz5ndd@MK?JM^Gz=z*Gs*dS;{D!YSR7+td4JeeaI0+V^1A-45Ghn!j|8 z>=m#}&AI+=LU+dOS1V_&pa1jqzF+_USDbZa-06?22H41y6en=jhTBH81{KwRN+e9`R=_!M z+R)>y-Ogn2+#+1Jr-A+d|5Lgk4?S<n~UPaTdH4cWH&c4NC5)0FvOui-x6M0R}^c=W8{r{6|r)Nr? z^f+;K+QNyGBV~G{P6wQvIz>QTIkH}D(`m&iJJ-zF^v%ot&;I}4Ca&49JXvSc71L~; zKDW*1H$990Db>izB6xb5hJs(8+rq{*Gn!^~rNw|e^pS}tax>=wR{n$S+Y~bdXZ Date: Sat, 3 Dec 2016 15:35:26 -0800 Subject: [PATCH 1456/2280] changelog note for unidecode/asciify_paths path separator fixes. --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 22e453f57..3a312c8e8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,6 +7,7 @@ Changelog Fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` +* With :ref:`asciify_paths` set to "yes", some unicode tags could decode in such a way that erroneous directories were created mid-filename. This has been fixed. 1.4.1 (November 25, 2016) From 16056ea6b2ad17cb9ca08ec7ed96f6ac5ac95459 Mon Sep 17 00:00:00 2001 From: xarph Date: Sat, 3 Dec 2016 15:47:15 -0800 Subject: [PATCH 1457/2280] In the changelog note, it should be asciify-paths, not asciify_paths. --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3a312c8e8..88479955c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,7 +7,7 @@ Changelog Fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` -* With :ref:`asciify_paths` set to "yes", some unicode tags could decode in such a way that erroneous directories were created mid-filename. This has been fixed. +* With :ref:`asciify-paths` set to "yes", some unicode tags could decode in such a way that erroneous directories were created mid-filename. This has been fixed. 1.4.1 (November 25, 2016) From 87942af4c43b09e9d8e59df3b3fe85184742428f Mon Sep 17 00:00:00 2001 From: xarph Date: Sat, 3 Dec 2016 16:15:40 -0800 Subject: [PATCH 1458/2280] fix line wrapping for py34-flake8 --- beets/library.py | 4 +++- test/test_library.py | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/beets/library.py b/beets/library.py index 78155d2b2..37d701283 100755 --- a/beets/library.py +++ b/beets/library.py @@ -827,7 +827,9 @@ class Item(LibModel): path_components = subpath.split(os.path.sep) sep_replace = beets.config['path_sep_replace'].get() for index, item in enumerate(path_components): - path_components[index] = unidecode(item).replace(os.path.sep,sep_replace) + path_components[index] = unidecode(item).replace( + os.path.sep, sep_replace + ) subpath = os.path.sep.join(path_components) maxlen = beets.config['max_filename_length'].get(int) diff --git a/test/test_library.py b/test/test_library.py index a2f399593..105a4d7cd 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -416,7 +416,10 @@ class DestinationTest(_common.TestCase): def test_asciify_and_replace(self): config['asciify_paths'] = True - self.lib.replacements = [(re.compile(u'"'), u'q'), (re.compile(os.path.sep), config['path_sep_replace'].get())] + self.lib.replacements = [ + (re.compile(u'"'), u'q'), + (re.compile(os.path.sep), config['path_sep_replace'].get()) + ] self.lib.directory = b'lib' self.lib.path_formats = [(u'default', u'$title')] self.i.title = u'\u201c\xa2\u00f6\u2014\u00cf\xbd\u201d' From 7436f093fe121d3815cf39bda9788de46cfb049f Mon Sep 17 00:00:00 2001 From: tweitzel Date: Sat, 3 Dec 2016 17:42:17 -0800 Subject: [PATCH 1459/2280] clear trailing whitespace --- test/test_library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_library.py b/test/test_library.py index 105a4d7cd..e30c305e6 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -417,7 +417,7 @@ class DestinationTest(_common.TestCase): def test_asciify_and_replace(self): config['asciify_paths'] = True self.lib.replacements = [ - (re.compile(u'"'), u'q'), + (re.compile(u'"'), u'q'), (re.compile(os.path.sep), config['path_sep_replace'].get()) ] self.lib.directory = b'lib' From ae5e55cad638dbde87af29bc21d0fb89996da995 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 4 Dec 2016 20:59:04 -0500 Subject: [PATCH 1460/2280] Always use `syspath` to construct MediaFile Related to #1966. Previously, we used a `syspath` call inside MediaFile, which probably wasn't right: the constructor should behave like `open` in that we need to use pass an OS path. --- test/test_library.py | 14 ++++++++------ test/test_plugins.py | 4 ++-- test/test_ui.py | 27 ++++++++++++++------------- test/test_zero.py | 17 +++++++++-------- 4 files changed, 33 insertions(+), 29 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 26c78c99d..bea34b998 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -1104,18 +1104,20 @@ class WriteTest(unittest.TestCase, TestHelper): shutil.copy(syspath(item.path), syspath(custom_path)) item['artist'] = 'new artist' - self.assertNotEqual(MediaFile(custom_path).artist, 'new artist') - self.assertNotEqual(MediaFile(item.path).artist, 'new artist') + self.assertNotEqual(MediaFile(syspath(custom_path)).artist, + 'new artist') + self.assertNotEqual(MediaFile(syspath(item.path)).artist, + 'new artist') item.write(custom_path) - self.assertEqual(MediaFile(custom_path).artist, 'new artist') - self.assertNotEqual(MediaFile(item.path).artist, 'new artist') + self.assertEqual(MediaFile(syspath(custom_path)).artist, 'new artist') + self.assertNotEqual(MediaFile(syspath(item.path)).artist, 'new artist') def test_write_custom_tags(self): item = self.add_item_fixture(artist='old artist') item.write(tags={'artist': 'new artist'}) self.assertNotEqual(item.artist, 'new artist') - self.assertEqual(MediaFile(item.path).artist, 'new artist') + self.assertEqual(MediaFile(syspath(item.path)).artist, 'new artist') def test_write_date_field(self): # Since `date` is not a MediaField, this should do nothing. @@ -1123,7 +1125,7 @@ class WriteTest(unittest.TestCase, TestHelper): clean_year = item.year item.date = u'foo' item.write() - self.assertEqual(MediaFile(item.path).year, clean_year) + self.assertEqual(MediaFile(syspath(item.path)).year, clean_year) class ItemReadTest(unittest.TestCase): diff --git a/test/test_plugins.py b/test/test_plugins.py index c4a5792ff..7c32e9aca 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -27,7 +27,7 @@ from beets import plugins, config, ui from beets.library import Item from beets.dbcore import types from beets.mediafile import MediaFile -from beets.util import displayable_path, bytestring_path +from beets.util import displayable_path, bytestring_path, syspath from test.test_importer import ImportHelper, AutotagStub from test.test_ui_importer import TerminalImportSessionSetup @@ -118,7 +118,7 @@ class ItemWriteTest(unittest.TestCase, TestHelper): item = self.add_item_fixture(artist=u'XXX') item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.artist, u'YYY') def register_listener(self, event, func): diff --git a/test/test_ui.py b/test/test_ui.py index 681900ae4..39504aa4e 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -40,6 +40,7 @@ from beets import config from beets import plugins from beets.util.confit import ConfigError from beets import util +from beets.util import syspath class ListTest(unittest.TestCase): @@ -289,7 +290,7 @@ class ModifyTest(unittest.TestCase, TestHelper): def test_write_initial_key_tag(self): self.modify(u"initial_key=C#m") item = self.lib.items().get() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.initial_key, u'C#m') def test_set_flexattr(self): @@ -313,11 +314,11 @@ class ModifyTest(unittest.TestCase, TestHelper): item.write() item.store() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.initial_key, u'C#m') self.modify(u"initial_key!") - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertIsNone(mediafile.initial_key) def test_arg_parsing_colon_query(self): @@ -528,7 +529,7 @@ class UpdateTest(_common.TestCase): self.assertNotExists(artpath) def test_modified_metadata_detected(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.save() self._update() @@ -536,7 +537,7 @@ class UpdateTest(_common.TestCase): self.assertEqual(item.title, u'differentTitle') def test_modified_metadata_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.save() self._update(move=True) @@ -544,7 +545,7 @@ class UpdateTest(_common.TestCase): self.assertTrue(b'differentTitle' in item.path) def test_modified_metadata_not_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.save() self._update(move=False) @@ -552,7 +553,7 @@ class UpdateTest(_common.TestCase): self.assertTrue(b'differentTitle' not in item.path) def test_selective_modified_metadata_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.genre = u'differentGenre' mf.save() @@ -562,7 +563,7 @@ class UpdateTest(_common.TestCase): self.assertNotEqual(item.genre, u'differentGenre') def test_selective_modified_metadata_not_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.genre = u'differentGenre' mf.save() @@ -572,7 +573,7 @@ class UpdateTest(_common.TestCase): self.assertNotEqual(item.genre, u'differentGenre') def test_modified_album_metadata_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.album = u'differentAlbum' mf.save() self._update(move=True) @@ -581,7 +582,7 @@ class UpdateTest(_common.TestCase): def test_modified_album_metadata_art_moved(self): artpath = self.album.artpath - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.album = u'differentAlbum' mf.save() self._update(move=True) @@ -589,7 +590,7 @@ class UpdateTest(_common.TestCase): self.assertNotEqual(artpath, album.artpath) def test_selective_modified_album_metadata_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.album = u'differentAlbum' mf.genre = u'differentGenre' mf.save() @@ -599,7 +600,7 @@ class UpdateTest(_common.TestCase): self.assertNotEqual(item.genre, u'differentGenre') def test_selective_modified_album_metadata_not_moved(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.album = u'differentAlbum' mf.genre = u'differentGenre' mf.save() @@ -609,7 +610,7 @@ class UpdateTest(_common.TestCase): self.assertEqual(item.genre, u'differentGenre') def test_mtime_match_skips_update(self): - mf = MediaFile(self.i.path) + mf = MediaFile(syspath(self.i.path)) mf.title = u'differentTitle' mf.save() diff --git a/test/test_zero.py b/test/test_zero.py index 5842d9ed4..fb28330ee 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -11,6 +11,7 @@ from beets.library import Item from beets import config from beetsplug.zero import ZeroPlugin from beets.mediafile import MediaFile +from beets.util import syspath class ZeroPluginTest(unittest.TestCase, TestHelper): @@ -61,7 +62,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): item.rg_track_peak = 0.0 item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertIsNotNone(mediafile.rg_track_peak) self.assertIsNotNone(mediafile.rg_track_gain) @@ -71,28 +72,28 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.load_plugins('zero') item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertIsNone(mediafile.rg_track_peak) self.assertIsNone(mediafile.rg_track_gain) def test_do_not_change_database(self): item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(2000, mediafile.year) config['zero'] = {'fields': ['year']} self.load_plugins('zero') item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(item['year'], 2000) self.assertIsNone(mediafile.year) def test_change_database(self): item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(2000, mediafile.year) config['zero'] = { @@ -102,7 +103,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.load_plugins('zero') item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(item['year'], 0) self.assertIsNone(mediafile.year) @@ -110,14 +111,14 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): path = self.create_mediafile_fixture(images=['jpg']) item = Item.from_path(path) - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertNotEqual(0, len(mediafile.images)) config['zero'] = {'fields': [u'images']} self.load_plugins('zero') item.write() - mediafile = MediaFile(item.path) + mediafile = MediaFile(syspath(item.path)) self.assertEqual(0, len(mediafile.images)) From 43fcb3d908cdc73314030f48527b142fb97d2041 Mon Sep 17 00:00:00 2001 From: tigranl Date: Mon, 5 Dec 2016 19:09:44 +0300 Subject: [PATCH 1461/2280] Check python version and enable https where it's possible --- beets/autotag/mb.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 78d382d87..8ceec9d87 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -28,9 +28,14 @@ import beets from beets import util from beets import config import six +import sys VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' -BASE_URL = 'http://musicbrainz.org/' + +if sys.version_info > (2, 7, 9): + BASE_URL = 'https://musicbrainz.org/' +else: + BASE_URL = 'http://musicbrainz.org/' musicbrainzngs.set_useragent('beets', beets.__version__, 'http://beets.io/') From 4461835cdafddfdf6f85395d2c028eb673a0250c Mon Sep 17 00:00:00 2001 From: xarph Date: Mon, 5 Dec 2016 22:03:00 -0800 Subject: [PATCH 1462/2280] sampsyo's better test of unicode path escaping revert my lame test --- test/test_library.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 105a4d7cd..1a176b37a 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -416,14 +416,18 @@ class DestinationTest(_common.TestCase): def test_asciify_and_replace(self): config['asciify_paths'] = True - self.lib.replacements = [ - (re.compile(u'"'), u'q'), - (re.compile(os.path.sep), config['path_sep_replace'].get()) - ] + self.lib.replacements = [(re.compile(u'"'), u'q')] self.lib.directory = b'lib' self.lib.path_formats = [(u'default', u'$title')] - self.i.title = u'\u201c\xa2\u00f6\u2014\u00cf\xbd\u201d' - self.assertEqual(self.i.destination(), np('lib/qC_o--I1_2q')) + self.i.title = u'\u201c\u00f6\u2014\u00cf\u201d' + self.assertEqual(self.i.destination(), np('lib/qo--Iq')) + + def test_asciify_character_expanding_to_slash(self): + config['asciify_paths'] = True + self.lib.directory = b'lib' + self.lib.path_formats = [(u'default', u'$title')] + self.i.title = u'ab\xa2\xbdd' + self.assertEqual(self.i.destination(), np('lib/abC_1_2d')) def test_destination_with_replacements(self): self.lib.directory = b'base' From cb8e57536cbf4f8e11c4940827cde9981f0c0c19 Mon Sep 17 00:00:00 2001 From: xarph Date: Mon, 5 Dec 2016 22:04:07 -0800 Subject: [PATCH 1463/2280] remove unused unicode_path_sep.mp3 --- test/rsrc/unicode_path_sep.mp3 | Bin 10368 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 test/rsrc/unicode_path_sep.mp3 diff --git a/test/rsrc/unicode_path_sep.mp3 b/test/rsrc/unicode_path_sep.mp3 deleted file mode 100644 index fa543b7fb957dd0e8612d983de27786a58ea3a0e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10368 zcmeZtF=l39U|`^>4+(HJWME+6XJBAREGo$?E;+OaLWel|I599V@PZ_Al1g(AElLDY zA)X;dP~noylAP2-i@+4fuu(i30;3@?8UmvsFd72HhQR;d0Y@;@dgi6&L+d0B1_s4) z1~xVx9${f&Nl66-1vNDt9UWt1OG`@!2RAo2AD`gh;K;~?goL!ToSdBE;>ya(hK9Db zww|8JlPAxdxnRM9Wy{vAS+jZb&Ye3C95{CD*qJkzFJHcS^TC4$&z`+`^XBvCpFe;8 z|Ifg{VCm!N>uRiLX|BMy6yzq|e+&#F4l1lQP7DkVAa}&?{u&38z=Og5VdgMg^~ZrF zMB;|2k`F_7XF~|bajE|x;FRH4++Ha?p`})m!-2tg-f`>aPQt&8_WzpyUeW%S@V{CP z=Y>)&>P`ZT6FNBm#^y55PGdc&n4o4cJv7NcJuo7Hu_0q&>i_@q|KBvKyc+rB|L>q9ip}hr z8+jZ!YB?>;5*ipcFWfreL79@AS^Ju1wD?t5B09QRf|Inmhh+j|NsA2RC4vEndg?I zaJ_riS#s?-OJ=iS-*WBCc1hF2^VZMaxBdVB|9}4f%DS6fR_m!%ES&Mi`4+FT<#Lgk zEeuB#7sxVPFWsGev3hG(_OcZ-Pik`nI&9~Ad~18`tee`~`gZ01|Mt@D|Ngx9kDeb6 z|0;Fj^LmhnteZL3Zsl^|xPIXKw!{ub=>>kub4=dMVfL66zRoL@!+u#@`q}5U`*wwN zzb>i!S$p3r{L|dpd)Go{xGu4K$$i4N%Sm}!;}RF4nH=^f{=c6Vlk(8tR&n_S+ zz3N460X^GSbVTTt<(%*ac__S@bM00Z1zuZ5#%+omjOq*bwqDblSu_9t_gz09=WUJf z6U~-?dpAksK38J6m}l9E_C<2)9wFlDLJmw)nQ5ChD;3?GDz>%C>f5Hbi)~&#=!%L8 zW9i6Q8s@xg-kB{a{_DSUxNF zuloQ0f4!f(EAoAA*tWOnSFV+B4QZRmRne;GuBh%_a+T*y`p;|qMlZefR{goQb#?B& z$-BC;=L8vsE=y*5J?XXD3AR&QM=~zEwSqj9*W4Mo5#%9G@ofr67}XatO=6h9ue@YS zXi8Y-{h}E?Jk$N+CK+z8xqK&3lKIusDBFAIUi+IzZ98_UxAy1b3BNb5zJ9FyA+yv+ z=RMJBPK(yt@lI;v2-524(pb!6f3BzRf3~&HivBdMyx@hwm1m06GVg}8Y8l<^Qd{@f zTKmM*_y3pmZspnkPPi#D_-nFIq>0$my+v%2o2of2{S>p7uk@=fhRg^LRwMlvj6{=M(T zgB)v_V?Cz_E%2dtg|C& zA-{}cWcxfG37KA_mg-r)t5vt^T-omAjXT_?{4l&XA#BQ(`}R&h{-{s9f1>;M{eStdRi*_+ za~@48>0i&P%w@8X+dGm;6__~E_`<|G~VHU5Q zxhMZj*P73&C*HjLGV|a%F3r;lD(Y+I#e}O1m~Nglf4-T$`u~3gf6lAjoq6wZA;?1; znmJCc2YE=+a@&Fv42vVaEWG(w9USU-k_zRu#1s=_gheue`A8#fg@fFJHFW``X|AKk0VF{g=+E+6Iw~ z;yK@zUCb0R;b_!JO88;x;L^bu{{R1fUCI2=Wz)r)JwvS18c%J{n#gth>LjZ-B^O(H zcD^V!^}ZXea?Ad*vI|eg^8O$H?Eh6fpDg*h<4oh1HM*vZA30OvQ#afc;$RAX!ftt7 zOj<=p0py`0%wA_Vvncf1GV+>%3xykr|LXtS%L~2yHYMSZXJ^xt*z?|*yCqUTr&+%g z&QuPPm*(20Z!Kiy7Cfic=ZM7hV(!aV&WFow`@DFXZN?7CWX>ffF_3d|G$1(;kBGC@1o95#SEPn)2__ozLb*H ztD7mlNnyW>N6ZwEhpsYnE?m!|z&lq`-t-{{qx8a_8K)f^c)U2fj&U$MFx>zD|G#UP z(&8OwvPI9N22K24u6be2@sg_bde2-HUwN<0dvUC+YG-(~#LaRgF z19K*ny9#lzZR&ipM%n#Cz=Mg+8+JY7@Vlctd*eB|_@BXN=FOWpXN`Th^xsAOlarec z`#CLDUHST4UVOxh=ESEL4K^K2&Dsd^(2Hhn)2%ECtfGwV+a9n8DDLpwcKkgkn@MMW zIy2qaP+~^(tn<42Tlim zjbqQ=v+KKrcI?hxIOl?|bdG^tz>kEV7XubpMEJ-v9}5xHN%Sdf;Q#;s|G%Y?_5c5u zuC=TDxaoaS`_!_BZRdaP@bbQ1TJvbC;Vsv+bz2N3@f6ADyjiyQ-_@lrznR74=jo=T zMNXNueck;`?yGMuYDvn-2rg33wPZW0=%TFrz|!I;#6vu(n;8@ubx%5OTgbzx_M`s) z|Nra%|NnpQPrs7k*2$4GjJQr^25GzQmFreNE-xmaAj0Lx@ZhY!*AtDz8#7aGskT>g ztlawVx3RTqnncmMbe+}nBLZgZ{NsJaaLtxISJ@}L3szHHEtmc`?0Q3>MI|H*9-Bi9`k*NK|Nme4Y2PBNtdyvUg40WzPdUsv`!u}i1ilo$ixt9l4th z>h)Ge%sVGzvq@+Bx##b~0~6MzMO*FCPERRf+A?9%bfdDX21eS-2{Qsblr(-!Wxl}w z|DEqj6Bo0M9Ot`@re5{>d3RIZ8iTl=^eCl?&N*QdmTZ*0vg*=1*UGy2pWkn+-?!<{ zg3e#9ClXCVx?01RrDSETNEB2)c{0SshtJ_c&Xkx-+m1BI|NsC0^@sZZAP>D__AcDa zXBHA^0y!J(2NIVWz5 z81Kc20iH*m>c5N&HhExwX7*|0iyIBY{bRIC`6S=<{GHOqJ$;E)qoT)-20u}58U3!7 z;;r@qEDj7m?I3|Q-};KCR{VrjJF`-}dY-BrpD7%fxP{B7=as^#<_?~g^AGwh*fj4iMYn*plwD`!A+zE0*|Nr#<5BAW@ zX6~6ASwJ2tG*j?kT=w(V|NsA=Gv+w1|NT9u=IegZkXO00H2%%}+wn@5xrpmS?#3&r z+uom8ZW%fA>9R+&|NToYzn?F?=DYv-Gi{0GVQVL^(45Sa;@v%O!-EgUo=#RfH^auI z#YDHlL~Yjez()*r6^#G?|Nl9qZ`1$(uOHspcbd0%PXDjiox+Hq&9pV4Sp?CJD!A-C)4QfuXi zu2W%)CN#C~JSQtL-Nm9&j4!0ry~HiLYogwj_n)+P8%+Cp_EpZNi^l_BIre3#EEBP> z6Mn_dK2<})!PhTLeV!1Ppe{?#w3Q5I1t2fI|Mlzt|A}*EN(IDRSfp?N<)xGA`lxGK zUL}hX_0pdGJt#Lz^xBn41)W=Ui~sB0|Nqx=|Cjym?7eM!w_Wy*OFzHn;M8lf#@z~5 zy1ET_{#t!&na$06JHY{z*ZOIdhhwq?csm_{QRtat$P24PhWkW_7pelnt$bp zkmsTkZ(I^gMOY3W$PhMDXq@V3=rBQO>L!qfUN?Ks+{$vGcP?YA*#Zxt%{LfNskk)0 zUR8Je|Nm~A@5wSrCP#~7V$M5lzwojsO7v-c-20h%ZBKoV+zQ?^GbsJct~ck;-LItNQygsi39EDM=CPw=^Q&DqPqp!YDzg=fR32L=MW z_5Xj>oEy)3cEKL0jC-lc->&R_`6SuZc=MHuDL3C|9A?+pp7H(GxlhgS?AF)+|JfO5 z|NsB~-~V=Zy!}(^+9Q=Z;n;$eR|2_Or^vBQIV57m$FqR*!b6aUUNv)9f;=?uV3t`z z52M;o2LAv5|HaR8urAyGf8|;cmj!>E4L+1A&D9Z1-{ah}j7!<9?cbc5^^=d9w*1UH zd&#`NW5Uk!=jPu_FPfKk|L2}9Cg04z-j02`MqHcqUehztMCU6f{9~;={5vA98!*^q zFs5D=)#+bb|Le`&s~USlX61F7u6krr+PwGWw7>KBMcFjY5dL=c^=9VZ?2k93N69Z1 zU-I~4vGn|%dhdKcSEZ$u&Hp@C-+ukx9NR6WUxwEEBK@<^-jszn>fLvNXQ zY_~EwaGE-1nskf&x&QzF|L&o&QgDY$)tokC3D*nj zQkNUcEVC9=3q171GQU*yXr6-el%^D0?fC!y|J@aQ5wbgCrmDq5Rv`%+g(Q!|?%mu? z28N8zO`Hr2e1VeS5SuG&YFsV<|JR}ow~9|r<5*gEzovDj<3*FR{iinub3C*tv2~+2WQ(`YVsL zK51v)h1l*m3f8mx{p?pU8sSU;qD~vpj#*-juLO)fTHteoYMIF;vdY7nb%Y z*%Fyr6y)L~tO52AGw;NW3F=C zc$RW5=xAb)T;)7K~+-|*BZXR@ZRA$O25sNxUVp1OEr-;1s;&QqZx zI))b+`=+s|9Bkyd%D^C(aEXO?>zb=ErAjlT>;He*KU3=2!dCm$xfZWOL^O4NddL6X z7Z)1%+4$>P4{?FEm7k{Ab$&8Zty5m#|KsPsI;+0hB^t#R*B32W(Y9KO_oESu8)xHP z=8XwoE|g~rH11?Nc2c9G0pcO=ubbH&dgn5hno|M#4T z&+~B!Pxd@&Joy&S3U@`#m{XPYzeQcG`i>V|JFHgkoa-BP)4YAj|7rhfcFp|1LgB<4 zwOcpm`ONIplGa$LB$OoKb5%u2m~ld^qSnf(pfo24N^}2Nd4mtFN&WxREnR=oW)rpa zl&ZpbOf1Vf5*R(0Wzjn)_eIfE} z-3n{n4oSKeDZSWIqT}S#AM{$X0_36BOgy1mnG$(z8STv$eqrd!kY?iE;~}WAf`R@2 z|1a^!Tt3X;+W-I4my51*eq}_ho~(a#Pt4^Hp8tFz-<*22>X`T~89NEp#>t($!CEfG z_4EIZ&Zu07y%D}+D#Jk0z z@zVDH?{20SSO5Pxb)}8qF*Uy;+jo`cj_niQQ})JU|IBBTzO5FGxNXfL=`Qj_aQB*3 z&;MWE{`U2$b&CVN-gKQ(;5qjuS>%Y}(SQy$DR~(akcZwk^VDu+b>I~2tlg#niXjUz z5!1xgDFXKY|9{H0KVT$tIcomjQ)!iV4?mn5C^`SUrfRfyPWrmA#mW;G#;tiUL0EKx zR^wgPT`T8`UVruG-uK_P_v;PZ3;|6L#Dr!9$dp7-kBx$?_g3D?33RlN^$SKgIlUF2*V^;zXgx0Up%l0}l2 z>OcL8i@90<{OGEBt(V=+oF@fkb#m1?=NP#uOjyD?YYE6hubX&EH?unQ+MR3y6$;BU zd}a$Cm=L5HbL$s_(8F1vMQi&R z7#M`^esO4==)95jm-l0v(7Us@GkKh}T)AOY(d0Zyh1Tth?#;UzWXrF0E2C9nP1oKD z*WB;^um5`8*Sl!1mVUUL<(X$pt7RN{4tJQI;<0p6e$DW-kbwcxmV3_39k`Km0ng@> z#ikF=2&ymq|E?>0>codZ9Z&uL|4-brsj?>DAn5wF>Adg7n z)q?cnGW~D8e}t)=*PeR%U;Sx=sy}-SjiZdGMYJ5w*m?bt-@)I@pH0$nK7J=Ca+8X1 zP{gaSAX89ki!*j<{Qv*|_N3?p?rz)p|35w2YZCTz37hLlFS&${j+1^nn~cwXzQvlv z^07p2mGCSh6SJqO>fzp1bH1Mc{QUp_liKh8{xAESogdWtCfKBLijZH_C7VWjPz=3f z;;G%r>dE{49g z28P<2|Ks{eSyuJ)&K3yA{TSUwXK#2Io*}BkmJKs&snFxP7aJvcJex+ zIP>Fa=72BOcB;A;SU?_n*~H_yo^v6uwP%D`;ueP97qfZ(|Np;H?99=EHiyLvbH8 z-E+FVO?^dDl<*aeX&$G!WgBL`oqT4>iUr-wS^G*E7?=g3vojg$|Gk_3zprO;DsSSq z{XbKy9!#5R_lHzgNl{r}sW-Rwxic;Pm+kBlHi*UmyU9(=$lWzz4lc6|A}dL zUO#(tdhXm#sj0K8_f<1nGQO|5Wnm|4ASA)Z{hEhAp*59(fq~CE+mq40d(*t48;3VP z&+S=#=krF*Ntc+7{+(mKa?EDwjq_8BEjxE9Mqa5rlO*FivrUFuOUp{)%yqfki=ok= zlyG7S3w^7%H$`wmEpn6xs1)*7JN}u`%%AG z-D<~li>=A6#@oKUd|xc!ctLLU*H!BGf3G+BUTt*QJNc^JiPi|Ancb;JOpKk3@8-4s zte-#q>HmDM_)a_JuVhLyY>F_Mlw&9U~5=o+grWUJ~l+JcwTI4>9X9Fmbd1fy34J#``L!s z_v_>T?0^6K<5!8e_`6@N)`mTdHd&YWebR2u3qtxVTGCD}SGYkQdd0+*yIgbu&)S<) zwkd2;+`MqH9OLO^m&Q5EkAH5QIA!4lhx=Mv_CMM*-}}Fb^4EeX(F?OfJzGQ=Mch@) zH5aB|yQOkA=i2Fo%;z{Z+yDRnyL@^2Ze!UpSw6>>m51)Eaxh*v;hmd`z$uVV-fwnb z{Qv*vCV!U{%R|jx=1QjL|1AA?eMY#GZ}H1$N50hPx6T0*Z$Q1w0!sPBv3mp}72}gxA9cRl`tqWDzUfimgSs6zcrC7ou-YoI|^XEVRU;ktO&1_Ab6IFOvw&y1IFqD)$xhl+TeD7Y| zXZ!vC%9p$A+tmtnt)73_?CUMjaA98$jfRfrPBMndtGeAfk11a}*SC1l0kiu5zwLdR z!W?GEF)%PRz5ndd@MK?JM^Gz=z*Gs*dS;{D!YSR7+td4JeeaI0+V^1A-45Ghn!j|8 z>=m#}&AI+=LU+dOS1V_&pa1jqzF+_USDbZa-06?22H41y6en=jhTBH81{KwRN+e9`R=_!M z+R)>y-Ogn2+#+1Jr-A+d|5Lgk4?S<n~UPaTdH4cWH&c4NC5)0FvOui-x6M0R}^c=W8{r{6|r)Nr? z^f+;K+QNyGBV~G{P6wQvIz>QTIkH}D(`m&iJJ-zF^v%ot&;I}4Ca&49JXvSc71L~; zKDW*1H$990Db>izB6xb5hJs(8+rq{*Gn!^~rNw|e^pS}tax>=wR{n$S+Y~bdXZ Date: Tue, 6 Dec 2016 16:17:25 +0300 Subject: [PATCH 1464/2280] Python version check for lyrics.py --- beetsplug/lyrics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 645d52559..7cd65b045 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -648,7 +648,8 @@ class LyricsPlugin(plugins.BeetsPlugin): params = { 'client_id': 'beets', 'client_secret': self.config['bing_client_secret'], - 'scope': 'http://api.microsofttranslator.com', + 'scope': 'https://api.microsofttranslator.com' if sys.version_info >= (2, 7, 9) else + 'http://api.microsofttranslator.com', 'grant_type': 'client_credentials', } From f60c911ffc0b5dca7247c7ed2d136decbbbf940c Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 17:10:35 +0300 Subject: [PATCH 1465/2280] Add SNI_SUPPORTED variable for https check --- beets/ui/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ae30a9c60..5e852262b 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -43,6 +43,8 @@ from beets.autotag import mb from beets.dbcore import query as db_query import six +SNI_SUPPORTED = sys.version_info + # On Windows platforms, use colorama to support "ANSI" terminal colors. if sys.platform == 'win32': try: From 73a7a4ff675894a542a5eade7c27be30d0c58a6a Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 17:10:35 +0300 Subject: [PATCH 1466/2280] Add SNI_SUPPORTED variable for https check --- beetsplug/fetchart.py | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 27ffa49cb..b03ed9788 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -292,8 +292,12 @@ class RemoteArtSource(ArtSource): class CoverArtArchive(RemoteArtSource): NAME = u"Cover Art Archive" - URL = 'http://coverartarchive.org/release/{mbid}/front' - GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' + if ui.SNI_SUPPORTED >= (2, 7, 9): + URL = 'https://coverartarchive.org/release/{mbid}/front' + GROUP_URL = 'https://coverartarchive.org/release-group/{mbid}/front' + else: + URL = 'http://coverartarchive.org/release/{mbid}/front' + GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' def get(self, album, extra): """Return the Cover Art Archive and Cover Art Archive release group URLs @@ -310,7 +314,10 @@ class CoverArtArchive(RemoteArtSource): class Amazon(RemoteArtSource): NAME = u"Amazon" - URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' + if ui.SNI_SUPPORTED >= (2, 7, 9): + URL = 'https://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' + else: + URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) def get(self, album, extra): @@ -324,7 +331,10 @@ class Amazon(RemoteArtSource): class AlbumArtOrg(RemoteArtSource): NAME = u"AlbumArt.org scraper" - URL = 'http://www.albumart.org/index_detail.php' + if ui.SNI_SUPPORTED >= (2, 7, 9): + URL = 'https://www.albumart.org/index_detail.php' + else: + URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' def get(self, album, extra): @@ -394,8 +404,10 @@ class GoogleImages(RemoteArtSource): class FanartTV(RemoteArtSource): """Art from fanart.tv requested using their API""" NAME = u"fanart.tv" - - API_URL = 'http://webservice.fanart.tv/v3/' + if ui.SNI_SUPPORTED >= (2, 7, 9): + API_URL = 'https://webservice.fanart.tv/v3/' + else: + API_URL = 'htts://webservice.fanart.tv/v3/' API_ALBUMS = API_URL + 'music/albums/' PROJECT_KEY = '61a7d0ab4e67162b7a0c7c35915cd48e' @@ -488,8 +500,12 @@ class ITunesStore(RemoteArtSource): class Wikipedia(RemoteArtSource): NAME = u"Wikipedia (queried through DBpedia)" - DBPEDIA_URL = 'http://dbpedia.org/sparql' - WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' + if ui.SNI_SUPPORTED >= (2, 7, 9): + DBPEDIA_URL = 'https://dbpedia.org/sparql' + WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' + else: + DBPEDIA_URL = 'http://dbpedia.org/sparql' + WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' SPARQL_QUERY = u'''PREFIX rdf: PREFIX dbpprop: PREFIX owl: From d065b33a816fa3aceef1aae214957a1c40d4b978 Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 17:10:35 +0300 Subject: [PATCH 1467/2280] Add SNI_SUPPORTED variable for https check --- beetsplug/lastimport.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 0ed9daf3c..1bf21c7d4 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -23,7 +23,10 @@ from beets import config from beets import plugins from beets.dbcore import types -API_URL = 'http://ws.audioscrobbler.com/2.0/' +if ui.SNI_SUPPORTED >= (2, 7, 9): + API_URL = 'https://ws.audioscrobbler.com/2.0/' +else: + API_URL = 'https://ws.audioscrobbler.com/2.0/' class LastImportPlugin(plugins.BeetsPlugin): From 5ae13764d88adcc9159c2ef8cdc40115a3ab23c4 Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 17:10:35 +0300 Subject: [PATCH 1468/2280] Add SNI_SUPPORTED variable for https check --- beets/util/artresizer.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 4c2e92532..4cedf96d3 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -25,6 +25,7 @@ from tempfile import NamedTemporaryFile from six.moves.urllib.parse import urlencode from beets import logging from beets import util +from beets import ui import six # Resizing methods @@ -32,7 +33,10 @@ PIL = 1 IMAGEMAGICK = 2 WEBPROXY = 3 -PROXY_URL = 'http://images.weserv.nl/' +if ui.SNI_SUPPORTED >= (2, 7, 9): + PROXY_URL = 'https://images.weserv.nl/' +else: + PROXY_URL = 'http://images.weserv.nl/' log = logging.getLogger('beets') From 25ebf8948fcbf5d003a699be3aab8467fd095304 Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 17:10:35 +0300 Subject: [PATCH 1469/2280] Revert "Add SNI_SUPPORTED variable for https check" This reverts commit f60c911ffc0b5dca7247c7ed2d136decbbbf940c. --- beets/ui/__init__.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 5e852262b..ae30a9c60 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -43,8 +43,6 @@ from beets.autotag import mb from beets.dbcore import query as db_query import six -SNI_SUPPORTED = sys.version_info - # On Windows platforms, use colorama to support "ANSI" terminal colors. if sys.platform == 'win32': try: From 91819b2c80799aa9cb6f942676b4150f8356bc6f Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 19:31:42 +0300 Subject: [PATCH 1470/2280] Add SNI_SUPPORTED --- beets/util/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5e1c30df1..dec97153e 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -33,6 +33,7 @@ import six MAX_FILENAME_LENGTH = 200 WINDOWS_MAGIC_PREFIX = u'\\\\?\\' +SNI_SUPPORTED = sys.version_info >= (2, 7, 9) class HumanReadableException(Exception): From efa90416a0437859c12a29709feaa1f01de3c030 Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 19:31:42 +0300 Subject: [PATCH 1471/2280] Add SNI_SUPPORTED Add SNI_SUPPORTED --- beetsplug/fetchart.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b03ed9788..b852eba17 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -292,7 +292,7 @@ class RemoteArtSource(ArtSource): class CoverArtArchive(RemoteArtSource): NAME = u"Cover Art Archive" - if ui.SNI_SUPPORTED >= (2, 7, 9): + if uti.SNI_SUPPORTED: URL = 'https://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'https://coverartarchive.org/release-group/{mbid}/front' else: @@ -314,7 +314,7 @@ class CoverArtArchive(RemoteArtSource): class Amazon(RemoteArtSource): NAME = u"Amazon" - if ui.SNI_SUPPORTED >= (2, 7, 9): + if util.SNI_SUPPORTED: URL = 'https://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' else: URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' @@ -331,7 +331,7 @@ class Amazon(RemoteArtSource): class AlbumArtOrg(RemoteArtSource): NAME = u"AlbumArt.org scraper" - if ui.SNI_SUPPORTED >= (2, 7, 9): + if util.SNI_SUPPORTED: URL = 'https://www.albumart.org/index_detail.php' else: URL = 'http://www.albumart.org/index_detail.php' @@ -404,7 +404,7 @@ class GoogleImages(RemoteArtSource): class FanartTV(RemoteArtSource): """Art from fanart.tv requested using their API""" NAME = u"fanart.tv" - if ui.SNI_SUPPORTED >= (2, 7, 9): + if util.SNI_SUPPORTED: API_URL = 'https://webservice.fanart.tv/v3/' else: API_URL = 'htts://webservice.fanart.tv/v3/' @@ -500,7 +500,7 @@ class ITunesStore(RemoteArtSource): class Wikipedia(RemoteArtSource): NAME = u"Wikipedia (queried through DBpedia)" - if ui.SNI_SUPPORTED >= (2, 7, 9): + if uti.SNI_SUPPORTED: DBPEDIA_URL = 'https://dbpedia.org/sparql' WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' else: From 420c451928840f9fe824351361e63935a40cfa00 Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 19:31:42 +0300 Subject: [PATCH 1472/2280] Add SNI_SUPPORTED Add SNI_SUPPORTED Add SNI_SUPPORTED --- beets/autotag/mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 8ceec9d87..8d5641ca4 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -32,7 +32,7 @@ import sys VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' -if sys.version_info > (2, 7, 9): +if util.SNI_SUPPORTED: BASE_URL = 'https://musicbrainz.org/' else: BASE_URL = 'http://musicbrainz.org/' From 0e895c8b317bddbc9321a4a6d5cc3c58ec403bb4 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Tue, 6 Dec 2016 23:03:28 -0500 Subject: [PATCH 1473/2280] install/update requests to satisfy sphinx --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index bb67723f5..f8ceb9934 100644 --- a/.travis.yml +++ b/.travis.yml @@ -53,6 +53,8 @@ addons: # test. install: - travis_retry pip install tox sphinx + # upgrade requests to satisfy sphinx linkcheck (for building man pages) + - if [[ $TRAVIS_PYTHON_VERSION == *_site_packages ]]; then pip install -U requests; fi - travis_retry tox -e $TOX_ENV --notest script: From 53a677b8fd0c4db9d6f62a6756cc2b161b067ed4 Mon Sep 17 00:00:00 2001 From: xarph Date: Wed, 7 Dec 2016 20:59:33 -0800 Subject: [PATCH 1474/2280] * break the asciify-paths code out into the util.asciify_paths function * make asciifying handle both os.sep and os.altsep (testing needed as I don't have a windows box handy) * make %asciify{} use the same code path as the asciify_paths goop. * added a discrete test to %asciify{} so my life acts as a warning to others * changelog note now with 80% less antihistamine-induced runon sentences --- beets/library.py | 19 +++++++++---------- beets/util/__init__.py | 20 ++++++++++++++++++++ docs/changelog.rst | 4 +++- test/test_library.py | 4 ++++ 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/beets/library.py b/beets/library.py index 37d701283..5cffdbe34 100755 --- a/beets/library.py +++ b/beets/library.py @@ -23,7 +23,6 @@ import unicodedata import time import re import six -from unidecode import unidecode from beets import logging from beets.mediafile import MediaFile, UnreadableFileError @@ -824,13 +823,10 @@ class Item(LibModel): subpath = unicodedata.normalize('NFC', subpath) if beets.config['asciify_paths']: - path_components = subpath.split(os.path.sep) - sep_replace = beets.config['path_sep_replace'].get() - for index, item in enumerate(path_components): - path_components[index] = unidecode(item).replace( - os.path.sep, sep_replace - ) - subpath = os.path.sep.join(path_components) + subpath = util.asciify_path( + subpath, + beets.config['path_sep_replace'].as_str() + ) maxlen = beets.config['max_filename_length'].get(int) if not maxlen: @@ -1082,7 +1078,10 @@ class Album(LibModel): beets.config['art_filename'].as_str()) subpath = self.evaluate_template(filename_tmpl, True) if beets.config['asciify_paths']: - subpath = unidecode(subpath) + subpath = util.asciify_path( + subpath, + beets.config['path_sep_replace'].as_str() + ) subpath = util.sanitize_path(subpath, replacements=self._db.replacements) subpath = bytestring_path(subpath) @@ -1434,7 +1433,7 @@ class DefaultTemplateFunctions(object): def tmpl_asciify(s): """Translate non-ASCII characters to their ASCII equivalents. """ - return unidecode(s) + return util.asciify_path(s, beets.config['path_sep_replace'].as_str()) @staticmethod def tmpl_time(s, fmt): diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5e1c30df1..bbd386bca 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -29,6 +29,7 @@ import platform import shlex from beets.util import hidden import six +from unidecode import unidecode MAX_FILENAME_LENGTH = 200 @@ -941,3 +942,22 @@ def raw_seconds_short(string): raise ValueError(u'String not in M:SS format') minutes, seconds = map(int, match.groups()) return float(minutes * 60 + seconds) + + +def asciify_path(path, sep_replace): + """Decodes all unicode characters in a path into ASCII equivalents. + + Substitutions are provided by the unidecode module. Path separators in the + input are preserved. + + Keyword arguments: + path -- The path to be asciified. + sep_replace -- the string to be used to replace extraneous path separators. + """ + # if this platform has an os.altsep, change it to os.sep. + if os.altsep: + path.replace(os.altsep, os.sep) + path_components = path.split(os.sep) + for index, item in enumerate(path_components): + path_components[index] = unidecode(item).replace(os.sep, sep_replace) + return os.sep.join(path_components) diff --git a/docs/changelog.rst b/docs/changelog.rst index 88479955c..0ed4d6377 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,7 +7,9 @@ Changelog Fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` -* With :ref:`asciify-paths` set to "yes", some unicode tags could decode in such a way that erroneous directories were created mid-filename. This has been fixed. +* The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` + setting properly substitute path separators generated by converting some + unicode characters into ASCII, such as ½ and ¢. 1.4.1 (November 25, 2016) diff --git a/test/test_library.py b/test/test_library.py index 1a176b37a..b428693c3 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -589,6 +589,10 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): self._setf(u'%title{$title}') self._assert_dest(b'/base/The Title') + def test_asciify_variable(self): + self._setf(u'%asciify{ab\xa2\xbdd}') + self._assert_dest(b'/base/abC_1_2d') + def test_left_variable(self): self._setf(u'%left{$title, 3}') self._assert_dest(b'/base/the') From 5adf053c01dada01a3aa67fc1d3bc70f9a357653 Mon Sep 17 00:00:00 2001 From: xarph Date: Wed, 7 Dec 2016 21:26:10 -0800 Subject: [PATCH 1475/2280] another attempt at fixing windows path stuff --- beets/util/__init__.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index bbd386bca..a33d0e02e 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -956,8 +956,13 @@ def asciify_path(path, sep_replace): """ # if this platform has an os.altsep, change it to os.sep. if os.altsep: - path.replace(os.altsep, os.sep) + path = path.replace(os.altsep, os.sep) path_components = path.split(os.sep) for index, item in enumerate(path_components): path_components[index] = unidecode(item).replace(os.sep, sep_replace) + if os.altsep: + path_components[index] = unidecode(item).replace( + os.altsep, + sep_replace + ) return os.sep.join(path_components) From 9bba178b5cf06df29afb73b71d5782c12ab8b0ed Mon Sep 17 00:00:00 2001 From: tigranl Date: Tue, 6 Dec 2016 19:31:42 +0300 Subject: [PATCH 1476/2280] Add tests for https --- test/test_art.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/test_art.py b/test/test_art.py index aba180780..393527eef 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -68,6 +68,7 @@ class FetchImageHelper(_common.TestCase): class FetchImageTest(FetchImageHelper, UseThePlugin): URL = 'http://example.com/test.jpg' + URL_HTTPS = 'https://example.com/test.jpg' def setUp(self): super(FetchImageTest, self).setUp() @@ -75,10 +76,13 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} self.candidate = fetchart.Candidate(logger, url=self.URL) + self.candidate_https = fetchart.Candidate(logger, url=self.URL_HTTPS) def test_invalid_type_returns_none(self): self.mock_response(self.URL, 'image/watercolour') + self.mock_response(self.URL_HTTPS, 'image/watercolour') self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): @@ -88,13 +92,17 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): def test_extension_set_by_content_type(self): self.mock_response(self.URL, 'image/png') + self.mock_response(self.URL_HTTPS, 'image/png') self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) def test_does_not_rely_on_server_content_type(self): self.mock_response(self.URL, 'image/jpeg', 'image/png') + self.mock_response(self.URL_HTTPS, 'image/jpeg', 'imsge/png') self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -157,6 +165,13 @@ class CombinedTest(FetchImageHelper, UseThePlugin): CAA_URL = 'http://coverartarchive.org/release/{0}/front' \ .format(MBID) + AMAZON_URL_HTTPS = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ + .format(ASIN) + AAO_URL_HTTPS = 'http://www.albumart.org/index_detail.php?asin={0}' \ + .format(ASIN) + CAA_URL_HTTPS = 'http://coverartarchive.org/release/{0}/front' \ + .format(MBID) + def setUp(self): super(CombinedTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') @@ -164,6 +179,7 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_returns_amazon_art(self): self.mock_response(self.AMAZON_URL) + self.mock_response(self.AMAZON_URL_HTTPS) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) @@ -176,6 +192,7 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, b'art.jpg')) self.mock_response(self.AMAZON_URL) + self.mock_response(self.AMAZON_URL_HTTPS) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) @@ -183,6 +200,7 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_falls_back_to_amazon(self): self.mock_response(self.AMAZON_URL) + self.mock_response(self.AMAZON_URL_HTTPS) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) @@ -190,24 +208,30 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_tries_amazon_before_aao(self): self.mock_response(self.AMAZON_URL) + self.mock_response(self.AMAZON_URL_HTTPS) album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) self.assertEqual(len(responses.calls), 1) self.assertEqual(responses.calls[0].request.url, self.AMAZON_URL) + self.assertEqual(responses.calls[0].request.url, self.AMAZON_URL_HTTPS) def test_main_interface_falls_back_to_aao(self): self.mock_response(self.AMAZON_URL, content_type='text/html') + self.mock_response(self.AMAZON_URL_HTTPS, content_type='text/html') album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) self.assertEqual(responses.calls[-1].request.url, self.AAO_URL) + self.assertEqual(responses.calls[-1].request.url, self.AAO_URL_HTTPS) def test_main_interface_uses_caa_when_mbid_available(self): self.mock_response(self.CAA_URL) + self.mock_response(self.CAA_URL_HTTPS) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) self.assertEqual(len(responses.calls), 1) self.assertEqual(responses.calls[0].request.url, self.CAA_URL) + self.assertEqual(responses.calls[0].request.url, self.CAA_URL_HTTPS) def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) From 21208b8c399287185a98aab9a85543dd6408e082 Mon Sep 17 00:00:00 2001 From: tigranl Date: Thu, 8 Dec 2016 19:09:15 +0300 Subject: [PATCH 1477/2280] Add SNI_SUPPORTED --- beets/util/artresizer.py | 3 +-- beetsplug/fetchart.py | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index 4cedf96d3..e84b775dc 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -25,7 +25,6 @@ from tempfile import NamedTemporaryFile from six.moves.urllib.parse import urlencode from beets import logging from beets import util -from beets import ui import six # Resizing methods @@ -33,7 +32,7 @@ PIL = 1 IMAGEMAGICK = 2 WEBPROXY = 3 -if ui.SNI_SUPPORTED >= (2, 7, 9): +if util.SNI_SUPPORTED: PROXY_URL = 'https://images.weserv.nl/' else: PROXY_URL = 'http://images.weserv.nl/' diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b852eba17..8af29ae75 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -292,7 +292,7 @@ class RemoteArtSource(ArtSource): class CoverArtArchive(RemoteArtSource): NAME = u"Cover Art Archive" - if uti.SNI_SUPPORTED: + if util.SNI_SUPPORTED: URL = 'https://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'https://coverartarchive.org/release-group/{mbid}/front' else: @@ -500,7 +500,7 @@ class ITunesStore(RemoteArtSource): class Wikipedia(RemoteArtSource): NAME = u"Wikipedia (queried through DBpedia)" - if uti.SNI_SUPPORTED: + if util.SNI_SUPPORTED: DBPEDIA_URL = 'https://dbpedia.org/sparql' WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' else: From b65a7da8e2e6497ab1ef168e2073545875ec39d7 Mon Sep 17 00:00:00 2001 From: tigranl Date: Thu, 8 Dec 2016 19:20:18 +0300 Subject: [PATCH 1478/2280] Add SNI_SUPPORTED --- beetsplug/lastimport.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 1bf21c7d4..c9cadc6a0 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -17,13 +17,13 @@ from __future__ import division, absolute_import, print_function import pylast from pylast import TopItem, _extract, _number -from beets import ui +from beets import util from beets import dbcore from beets import config from beets import plugins from beets.dbcore import types -if ui.SNI_SUPPORTED >= (2, 7, 9): +if util.SNI_SUPPORTED: API_URL = 'https://ws.audioscrobbler.com/2.0/' else: API_URL = 'https://ws.audioscrobbler.com/2.0/' From bca6d2af018cd8217b543184bf5aefccfa069aac Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 9 Dec 2016 00:52:24 -0500 Subject: [PATCH 1479/2280] Remove requests/urllib3 logging override in discogs Discog plugin overrides the global logging for `requests` for a reason that seems no longer valid. I can't seem to reproduce the logging behavior mentioned in the preceding comment, so I'm removing it. If we do want to modify `requests` logging in the future, then we should hook it into beets verbose logging. --- beetsplug/discogs.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 97834c500..28b863d4b 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -19,7 +19,6 @@ discogs-client library. from __future__ import division, absolute_import, print_function import beets.ui -from beets import logging from beets import config from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance from beets.plugins import BeetsPlugin @@ -38,10 +37,6 @@ import traceback from string import ascii_lowercase -# Silence spurious INFO log lines generated by urllib3. -urllib3_logger = logging.getLogger('requests.packages.urllib3') -urllib3_logger.setLevel(logging.CRITICAL) - USER_AGENT = u'beets/{0} +http://beets.io/'.format(beets.__version__) # Exceptions that discogs_client should really handle but does not. From 3f78578a88cdbb387a4f9a60d0102178522b2d5f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 9 Dec 2016 09:26:58 -0500 Subject: [PATCH 1480/2280] Fix links to pip --- docs/guides/main.rst | 2 +- docs/plugins/chroma.rst | 2 +- docs/plugins/fetchart.rst | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 4e833fe3c..b89e11f0a 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -61,7 +61,7 @@ To install without pip, download beets from `its PyPI page`_ and run ``python setup.py install`` in the directory therein. .. _its PyPI page: http://pypi.python.org/pypi/beets#downloads -.. _pip: http://pip.openplans.org/ +.. _pip: http://www.pip-installer.org/ The best way to upgrade beets to a new version is by running ``pip install -U beets``. You may want to follow `@b33ts`_ on Twitter to hear about progress on diff --git a/docs/plugins/chroma.rst b/docs/plugins/chroma.rst index d26a6a92f..617d8cf69 100644 --- a/docs/plugins/chroma.rst +++ b/docs/plugins/chroma.rst @@ -31,7 +31,7 @@ First, install pyacoustid itself. You can do this using `pip`_, like so:: $ pip install pyacoustid -.. _pip: http://pip.openplans.org/ +.. _pip: http://www.pip-installer.org/ Then, you will need to install `Chromaprint`_, either as a dynamic library or in the form of a command-line tool (``fpcalc``). diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 7eb8c194e..ee0014072 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -157,7 +157,7 @@ Once the library is installed, the plugin will use it to search automatically. .. _a problem: https://github.com/ocelma/python-itunes/issues/9 .. _python-itunes: https://github.com/ocelma/python-itunes -.. _pip: http://pip.openplans.org/ +.. _pip: http://www.pip-installer.org/ Google custom search '''''''''''''''''''' From 936dc58a1cfa7515115babb4e008631de378c0b4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 9 Dec 2016 16:46:01 -0500 Subject: [PATCH 1481/2280] Changelog note about #2311 --- docs/changelog.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0ed4d6377..7ea1f1c6a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,10 +7,14 @@ Changelog Fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` -* The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` - setting properly substitute path separators generated by converting some +* The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` + setting properly substitute path separators generated by converting some unicode characters into ASCII, such as ½ and ¢. +Also, we've removed some special handling for logging in the +:doc:`/plugins/discogs` that we believe was unnecessary. If spurious log +messages appear in this version, please let us know by filing a bug. + 1.4.1 (November 25, 2016) ------------------------- From 68b4a03ecd96fa42b7afcedeb00e8859b43569fa Mon Sep 17 00:00:00 2001 From: tigranl Date: Sat, 10 Dec 2016 19:54:44 +0300 Subject: [PATCH 1482/2280] Add tests for https --- beetsplug/fetchart.py | 10 ++----- test/test_art.py | 69 +++++++++++++++++-------------------------- 2 files changed, 29 insertions(+), 50 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 8af29ae75..2ba5bcb7e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -314,10 +314,7 @@ class CoverArtArchive(RemoteArtSource): class Amazon(RemoteArtSource): NAME = u"Amazon" - if util.SNI_SUPPORTED: - URL = 'https://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' - else: - URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' + URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) def get(self, album, extra): @@ -331,10 +328,7 @@ class Amazon(RemoteArtSource): class AlbumArtOrg(RemoteArtSource): NAME = u"AlbumArt.org scraper" - if util.SNI_SUPPORTED: - URL = 'https://www.albumart.org/index_detail.php' - else: - URL = 'http://www.albumart.org/index_detail.php' + URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' def get(self, album, extra): diff --git a/test/test_art.py b/test/test_art.py index 393527eef..694d9a05c 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -67,42 +67,38 @@ class FetchImageHelper(_common.TestCase): class FetchImageTest(FetchImageHelper, UseThePlugin): - URL = 'http://example.com/test.jpg' - URL_HTTPS = 'https://example.com/test.jpg' + URL = '{0}example.com/test.jpg' def setUp(self): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} - self.candidate = fetchart.Candidate(logger, url=self.URL) - self.candidate_https = fetchart.Candidate(logger, url=self.URL_HTTPS) + self.candidate = fetchart.Candidate(logger, url=self.URL.format('http://')) def test_invalid_type_returns_none(self): - self.mock_response(self.URL, 'image/watercolour') - self.mock_response(self.URL_HTTPS, 'image/watercolour') + self.mock_response(self.URL.format('http://'), 'image/watercolour') + self.mock_response(self.URL.format('https://'), 'image/watercolour') self.source.fetch_image(self.candidate, self.extra) - self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): - self.mock_response(self.URL, 'image/jpeg') + self.mock_response(self.URL.format('http://'), 'image/jpeg') + self.mock_response(self.URL.format('https://')) self.source.fetch_image(self.candidate, self.extra) self.assertNotEqual(self.candidate.path, None) def test_extension_set_by_content_type(self): - self.mock_response(self.URL, 'image/png') - self.mock_response(self.URL_HTTPS, 'image/png') + self.mock_response(self.URL.format('http://'), 'image/png') + self.mock_response(self.URL.format('https://'), 'image/png') self.source.fetch_image(self.candidate, self.extra) - self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) def test_does_not_rely_on_server_content_type(self): - self.mock_response(self.URL, 'image/jpeg', 'image/png') - self.mock_response(self.URL_HTTPS, 'image/jpeg', 'imsge/png') + self.mock_response(self.URL.format('http://'), 'image/jpeg', 'image/png') + self.mock_response(self.URL.format('https://'), 'image/jpeg', 'imsge/png') self.source.fetch_image(self.candidate, self.extra) - self.source.fetch_image(self.candidate_https, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -158,28 +154,20 @@ class FSArtTest(UseThePlugin): class CombinedTest(FetchImageHelper, UseThePlugin): ASIN = 'xxxx' MBID = 'releaseid' - AMAZON_URL = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ + AMAZON_URL = 'images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ .format(ASIN) - AAO_URL = 'http://www.albumart.org/index_detail.php?asin={0}' \ + AAO_URL = 'www.albumart.org/index_detail.php?asin={0}' \ .format(ASIN) - CAA_URL = 'http://coverartarchive.org/release/{0}/front' \ + CAA_URL = 'coverartarchive.org/release/{0}/front' \ .format(MBID) - AMAZON_URL_HTTPS = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ - .format(ASIN) - AAO_URL_HTTPS = 'http://www.albumart.org/index_detail.php?asin={0}' \ - .format(ASIN) - CAA_URL_HTTPS = 'http://coverartarchive.org/release/{0}/front' \ - .format(MBID) - def setUp(self): super(CombinedTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') os.mkdir(self.dpath) def test_main_interface_returns_amazon_art(self): - self.mock_response(self.AMAZON_URL) - self.mock_response(self.AMAZON_URL_HTTPS) + self.mock_response("http://"+self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) @@ -191,47 +179,44 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, b'art.jpg')) - self.mock_response(self.AMAZON_URL) - self.mock_response(self.AMAZON_URL_HTTPS) + self.mock_response("http://"+self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_main_interface_falls_back_to_amazon(self): - self.mock_response(self.AMAZON_URL) - self.mock_response(self.AMAZON_URL_HTTPS) + self.mock_response("http://"+self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): - self.mock_response(self.AMAZON_URL) - self.mock_response(self.AMAZON_URL_HTTPS) + self.mock_response("http://"+self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) self.assertEqual(len(responses.calls), 1) - self.assertEqual(responses.calls[0].request.url, self.AMAZON_URL) - self.assertEqual(responses.calls[0].request.url, self.AMAZON_URL_HTTPS) + self.assertEqual(responses.calls[0].request.url, "http://"+self.AMAZON_URL) def test_main_interface_falls_back_to_aao(self): - self.mock_response(self.AMAZON_URL, content_type='text/html') - self.mock_response(self.AMAZON_URL_HTTPS, content_type='text/html') + self.mock_response("http://"+self.AMAZON_URL, content_type='text/html') album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) - self.assertEqual(responses.calls[-1].request.url, self.AAO_URL) - self.assertEqual(responses.calls[-1].request.url, self.AAO_URL_HTTPS) + self.assertEqual(responses.calls[-1].request.url, "http://"+self.AAO_URL) def test_main_interface_uses_caa_when_mbid_available(self): - self.mock_response(self.CAA_URL) - self.mock_response(self.CAA_URL_HTTPS) + self.mock_response("http://"+self.CAA_URL) + self.mock_response("https://"+self.CAA_URL) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) self.assertEqual(len(responses.calls), 1) - self.assertEqual(responses.calls[0].request.url, self.CAA_URL) - self.assertEqual(responses.calls[0].request.url, self.CAA_URL_HTTPS) + if util.SNI_SUPPORTED: + url = "https://"+self.CAA_URL + else: + url = "http://"+self.CAA_URL + self.assertEqual(responses.calls[0].request.url, url) def test_local_only_does_not_access_network(self): album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) From 0868299e92fb966c7d9c3351a7697693a74248eb Mon Sep 17 00:00:00 2001 From: tigranl Date: Sat, 10 Dec 2016 20:08:27 +0300 Subject: [PATCH 1483/2280] PEP8 corrections --- test/test_art.py | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index 694d9a05c..bc3319cc2 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -74,7 +74,8 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} - self.candidate = fetchart.Candidate(logger, url=self.URL.format('http://')) + self.candidate = fetchart.Candidate(logger, + url=self.URL.format('http://')) def test_invalid_type_returns_none(self): self.mock_response(self.URL.format('http://'), 'image/watercolour') @@ -96,8 +97,10 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): self.assertExists(self.candidate.path) def test_does_not_rely_on_server_content_type(self): - self.mock_response(self.URL.format('http://'), 'image/jpeg', 'image/png') - self.mock_response(self.URL.format('https://'), 'image/jpeg', 'imsge/png') + self.mock_response(self.URL.format('http://'), + 'image/jpeg', 'image/png') + self.mock_response(self.URL.format('https://'), + 'image/jpeg', 'imsge/png') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -167,7 +170,7 @@ class CombinedTest(FetchImageHelper, UseThePlugin): os.mkdir(self.dpath) def test_main_interface_returns_amazon_art(self): - self.mock_response("http://"+self.AMAZON_URL) + self.mock_response("http://" + self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) @@ -179,43 +182,46 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, b'art.jpg')) - self.mock_response("http://"+self.AMAZON_URL) + self.mock_response("http://" + self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_main_interface_falls_back_to_amazon(self): - self.mock_response("http://"+self.AMAZON_URL) + self.mock_response("http://" + self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): - self.mock_response("http://"+self.AMAZON_URL) + self.mock_response("http://" + self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) self.assertEqual(len(responses.calls), 1) - self.assertEqual(responses.calls[0].request.url, "http://"+self.AMAZON_URL) + self.assertEqual(responses.calls[0].request.url, + "http://" + self.AMAZON_URL) def test_main_interface_falls_back_to_aao(self): - self.mock_response("http://"+self.AMAZON_URL, content_type='text/html') + self.mock_response("http://" + self.AMAZON_URL, + content_type='text/html') album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) - self.assertEqual(responses.calls[-1].request.url, "http://"+self.AAO_URL) + self.assertEqual(responses.calls[-1].request.url, + "http://" + self.AAO_URL) def test_main_interface_uses_caa_when_mbid_available(self): - self.mock_response("http://"+self.CAA_URL) - self.mock_response("https://"+self.CAA_URL) + self.mock_response("http://" + self.CAA_URL) + self.mock_response("https://" + self.CAA_URL) album = _common.Bag(mb_albumid=self.MBID, asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) self.assertEqual(len(responses.calls), 1) if util.SNI_SUPPORTED: - url = "https://"+self.CAA_URL + url = "https://" + self.CAA_URL else: - url = "http://"+self.CAA_URL + url = "http://" + self.CAA_URL self.assertEqual(responses.calls[0].request.url, url) def test_local_only_does_not_access_network(self): From 471f875dc17bbd9bad0388671d51a828f0039073 Mon Sep 17 00:00:00 2001 From: tigranl Date: Sat, 10 Dec 2016 21:26:51 +0300 Subject: [PATCH 1484/2280] Fix typo --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 2ba5bcb7e..855a1df10 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -401,7 +401,7 @@ class FanartTV(RemoteArtSource): if util.SNI_SUPPORTED: API_URL = 'https://webservice.fanart.tv/v3/' else: - API_URL = 'htts://webservice.fanart.tv/v3/' + API_URL = 'https://webservice.fanart.tv/v3/' API_ALBUMS = API_URL + 'music/albums/' PROJECT_KEY = '61a7d0ab4e67162b7a0c7c35915cd48e' From 5ca664e4aaeb9c666f7d95af85f73c356309406a Mon Sep 17 00:00:00 2001 From: tigranl Date: Sun, 11 Dec 2016 00:25:37 +0300 Subject: [PATCH 1485/2280] Fix typos --- beets/autotag/mb.py | 1 - beetsplug/lastimport.py | 1 + beetsplug/lyrics.py | 7 ++++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 8d5641ca4..88fa16c3a 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -28,7 +28,6 @@ import beets from beets import util from beets import config import six -import sys VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index c9cadc6a0..25624731e 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import pylast from pylast import TopItem, _extract, _number from beets import util +from beets import ui from beets import dbcore from beets import config from beets import plugins diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7cd65b045..b837aef15 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -50,7 +50,7 @@ except ImportError: pass from beets import plugins -from beets import ui +from beets import util DIV_RE = re.compile(r'<(/?)div>?', re.I) @@ -645,11 +645,12 @@ class LyricsPlugin(plugins.BeetsPlugin): for source in sources] def get_bing_access_token(self): + url = "{0}api.microsofttranslator.com" params = { 'client_id': 'beets', 'client_secret': self.config['bing_client_secret'], - 'scope': 'https://api.microsofttranslator.com' if sys.version_info >= (2, 7, 9) else - 'http://api.microsofttranslator.com', + 'scope': url.format('https://') if util.SNI_SUPPORTED + else url.format('http://'), 'grant_type': 'client_credentials', } From dd115b13106ee9755ac2796179c91bde0b4545db Mon Sep 17 00:00:00 2001 From: tigranl Date: Sun, 11 Dec 2016 00:35:51 +0300 Subject: [PATCH 1486/2280] Add ui import --- beetsplug/lyrics.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index b837aef15..feab2180e 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -51,6 +51,7 @@ except ImportError: from beets import plugins from beets import util +from beets import ui DIV_RE = re.compile(r'<(/?)div>?', re.I) From fc8411f3b82901a92a6af70ea0ad7c9f90276bc3 Mon Sep 17 00:00:00 2001 From: diomekes Date: Thu, 15 Dec 2016 16:04:56 -0500 Subject: [PATCH 1487/2280] random: add --time option, update docs --- beetsplug/random.py | 71 +++++++++++++++++++++++++++++++---------- docs/plugins/random.rst | 4 +++ 2 files changed, 59 insertions(+), 16 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index a0719dcad..0dc438927 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -32,6 +32,23 @@ def random_item(lib, opts, args): else: objs = list(lib.items(query)) + if opts.time: + total_time = 0.0 + time_sec = (opts.time * 60) + objs_shuffled = objs + random.shuffle(objs_shuffled) + + if not opts.equal_chance: + objs = [] + + for item in objs_shuffled: + if (total_time + item.length) <= time_sec: + objs.append(item) + total_time += item.length + + else: + pass + if opts.equal_chance: # Group the objects by artist so we can sample from them. key = attrgetter('albumartist') @@ -39,25 +56,44 @@ def random_item(lib, opts, args): objs_by_artists = {} for artist, v in groupby(objs, key): objs_by_artists[artist] = list(v) - objs = [] - for _ in range(opts.number): - # Terminate early if we're out of objects to select. - if not objs_by_artists: - break - # Choose an artist and an object for that artist, removing - # this choice from the pool. - artist = random.choice(list(objs_by_artists.keys())) - objs_from_artist = objs_by_artists[artist] - i = random.randint(0, len(objs_from_artist) - 1) - objs.append(objs_from_artist.pop(i)) + if opts.time: + for item in objs_shuffled: + if not objs_by_artists: + break - # Remove the artist if we've used up all of its objects. - if not objs_from_artist: - del objs_by_artists[artist] + if (total_time + item.length) <= time_sec: + artist = random.choice(list(objs_by_artists.keys())) + objs_from_artist = objs_by_artists[artist] + i = random.randint(0, len(objs_from_artist) - 1) + objs.append(objs_from_artist.pop(i)) + total_time += item.length - else: + if not objs_from_artist: + del objs_by_artists[artist] + + else: + pass + + else: + for _ in range(opts.number): + # Terminate early if we're out of objects to select. + if not objs_by_artists: + break + + # Choose an artist and an object for that artist, removing + # this choice from the pool. + artist = random.choice(list(objs_by_artists.keys())) + objs_from_artist = objs_by_artists[artist] + i = random.randint(0, len(objs_from_artist) - 1) + objs.append(objs_from_artist.pop(i)) + + # Remove the artist if we've used up all of its objects. + if not objs_from_artist: + del objs_by_artists[artist] + + elif not opts.time: number = min(len(objs), opts.number) objs = random.sample(objs, number) @@ -65,13 +101,16 @@ def random_item(lib, opts, args): print_(format(item)) random_cmd = Subcommand('random', - help=u'chose a random track or album') + help=u'choose a random track or album') random_cmd.parser.add_option( u'-n', u'--number', action='store', type="int", help=u'number of objects to choose', default=1) random_cmd.parser.add_option( u'-e', u'--equal-chance', action='store_true', help=u'each artist has the same chance') +random_cmd.parser.add_option( + u'-t', u'--time', action='store', type="float", + help=u'total length in minutes of objects to choose') random_cmd.parser.add_all_common_options() random_cmd.func = random_item diff --git a/docs/plugins/random.rst b/docs/plugins/random.rst index 5b04d5ab7..8025eef4b 100644 --- a/docs/plugins/random.rst +++ b/docs/plugins/random.rst @@ -23,3 +23,7 @@ of Bob Dylan won't make you listen to Bob Dylan 50% of the time. The ``-n NUMBER`` option controls the number of objects that are selected and printed (default 1). To select 5 tracks from your library, type ``beet random -n5``. + +The ``-t MINUTES`` option controls the combined length of the objects that are +selected and printed. To select tracks that total one hour, tyoe ``beet random +-t60`` From eb85ff422b9295b3831cab58004677c3a8d4a817 Mon Sep 17 00:00:00 2001 From: Kier Davis Date: Fri, 16 Dec 2016 00:21:35 +0000 Subject: [PATCH 1488/2280] convert plugin: fix braces in filenames causing tracebacks in "pretend" mode Previously "pretend" mode (a.k.a. dry run mode) passed the command to be printed directly to _log.info, whose first argument is technically a format string. Thus the command string was parsed for replacement fields, such as '{foo}', which could cause the format evaluation to fail if the filenames contained in the command contained valid (or partially valid) replacement fields. This fix simply inserts an argument '{0}' to the call to _log.info, which is a format string that simply evaluates to the second argument to _log.info (the command string). By doing this, the command string is not parsed for replacement fields. --- beetsplug/convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 6639eb7b1..dfdf4e310 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -202,7 +202,7 @@ class ConvertPlugin(BeetsPlugin): encode_cmd.append(args[i].encode(util.arg_encoding())) if pretend: - self._log.info(u' '.join(ui.decargs(args))) + self._log.info(u'{0}', u' '.join(ui.decargs(args))) return try: From 6406918940080df1b4007a941aa8abb3ba725f9a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Dec 2016 20:39:43 -0500 Subject: [PATCH 1489/2280] Changelog for #2323 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 7ea1f1c6a..867edebc9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,8 @@ Fixes: * The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` setting properly substitute path separators generated by converting some unicode characters into ASCII, such as ½ and ¢. +* :doc:`/plugins/convert`: Fix a logging-related crash when filenames contain + curly brackets. Thanks to :user:`kierdavis`. :bug:`2323` Also, we've removed some special handling for logging in the :doc:`/plugins/discogs` that we believe was unnecessary. If spurious log From e08afea0f0d016da9174ff46ab6e801bb975542a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 21:45:58 -0500 Subject: [PATCH 1490/2280] Mention Python 3 in "getting started" guide --- docs/guides/main.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index b89e11f0a..b0bc8e0e9 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -9,12 +9,14 @@ collection better. Installing ---------- -You will need Python. (Beets is written for `Python 2.7`_. 2.6 support has been -dropped, and Python 3.x is not yet supported.) +You will need Python. +Beets works on `Python 2.7`_ and Python 3.4 or later. .. _Python 2.7: http://www.python.org/download/ * **macOS** v10.7 (Lion) and later include Python 2.7 out of the box. + You can opt for Python 3 by installing it via `Homebrew`_: + ``brew install python3`` * On **Debian or Ubuntu**, depending on the version, beets is available as an official package (`Debian details`_, `Ubuntu details`_), so try typing: @@ -55,7 +57,7 @@ dropped, and Python 3.x is not yet supported.) .. _beets is in [community]: https://www.archlinux.org/packages/community/any/beets/ If you have `pip`_, just say ``pip install beets`` (you might need ``sudo`` in -front of that). On Arch, you'll need to use ``pip2`` instead of ``pip``. +front of that). To install without pip, download beets from `its PyPI page`_ and run ``python setup.py install`` in the directory therein. From 8e03f9f7b2f1c2da0021169c114e7a6d1163fbbf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 21:48:33 -0500 Subject: [PATCH 1491/2280] Python 3 status note in changelog --- docs/changelog.rst | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 867edebc9..4108753f1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,13 @@ Changelog 1.4.2 (in development) ---------------------- -Fixes: +This is just a little bug fix release. With 1.4.2, we're also confident enough +to recommend that anyone who's interested give Python 3 a try: bugs may still +lurk, but we've deemed things safe enough for broad adoption. If you can, +please install beets with ``pip3`` instead of ``pip2`` this time and let us +know how it goes! + +Here are the fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` * The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` From 46e242b2b916621587c80366e4eaedd8e72d0df4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 21:49:36 -0500 Subject: [PATCH 1492/2280] Roll back zsh completion to 9dc7995 See #2266. The recently introduced caching mechanism is nifty, but it's causing problems for many users. We're rolling it back until the author can get to the bottom of the problem. --- extra/_beet | 45 +++++++++++++++------------------------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/extra/_beet b/extra/_beet index 520c212fc..9f20151f7 100644 --- a/extra/_beet +++ b/extra/_beet @@ -2,24 +2,19 @@ # zsh completion for beets music library manager and MusicBrainz tagger: http://beets.radbox.org/ -# IMPORTANT: You need to change the $completionsdir variable defined below to point to the directory where your completion files -# are stored. -# It will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins), -# but a cache file (_beet_cached) will be created after the first completion which will make subsequent calls much -# faster. -# If you enable new plugins or fields you should update the cache file by deleting it, entering the following commands: -# unfunction _beet -# autoload -z _beet -# and then performing another completion in a new shell. - -# If cache file exists, use that -local completionsdir="$HOME/.oh-my-zsh/custom/completions" -local cachefile=$completionsdir/_beet_cached -if [[ -r "$cachefile" ]]; then - source "$cachefile" - _beet "$@" - return -fi +# NOTE: it will be very slow the first time you try to complete in a zsh shell (especially if you've enable many plugins) +# You can make it faster in future by creating a cached version: +# 1) perform a query completion with this file (_beet), e.g. do: beet list artist:" +# to create the completion function (takes a few seconds) +# 2) save a copy of the completion function: which _beet > _beet_cached +# 3) save a copy of the query completion function: which _beet_query > _beet_query_cached +# 4) copy the contents of _beet_query_cached to the top of _beet_cached +# 5) copy and paste the _beet_field_values function from _beet to the top of _beet_cached +# 6) add the following line to the top of _beet_cached: #compdef beet +# 7) add the following line to the bottom of _beet_cached: _beet "$@" +# 8) save _beet_cached to your completions directory (e.g. /usr/share/zsh/functions/Completion) +# 9) add the following line to your .zshrc file: compdef _beet_cached beet +# You will need to repeat this proceedure each time you enable new plugins if you want them to complete properly. # useful: argument to _regex_arguments for matching any word local matchany=/$'[^\0]##\0'/ @@ -73,7 +68,8 @@ queryelem="_values -S : 'query field (add an extra : to match by regexp)' '::' $ # store call to _values function for completing modify terms (no need to complete field values) modifyelem="_values -S = 'modify field (replace = with ! to remove field)' $(echo "'${^fields[@]}:: '")" # Create completion function for queries -_regex_arguments _beet_query "$matchany" \# \( "$matchquery" ":query:query string:$queryelem" \) \( "$matchquery" ":query:query string:$queryelem" \) \# +_regex_arguments _beet_query "$matchany" \# \( "$matchquery" ":query:query string:$queryelem" \) \ + \( "$matchquery" ":query:query string:$queryelem" \) \# # store regexps for completing lists of queries and modifications local -a query modify query=( \( "$matchquery" ":query:query string:{_beet_query}" \) \( "$matchquery" ":query:query string:{_beet_query}" \) \# ) @@ -265,17 +261,6 @@ _regex_arguments _beet "$matchany" \( "${globalopts[@]}" \# \) "${subcmds[@]}" # Set tag-order so that options are completed separately from arguments zstyle ":completion:${curcontext}:" tag-order '! options' -# Save completion functions to _beet_cached -echo "# Cached completion file for beet\n# Note: this was created from _beet, and should be regenerated when new fields or plugins are added.\n# To regenerate this file just delete it, open a new zshell and try completing beet.\n\n" > $cachefile -which _beet_field_values >> $cachefile -echo "\n\n" >> $cachefile -which _beet_query >> $cachefile -echo "\n\n" >> $cachefile -which _beet >> $cachefile -echo "\n\n" >> $cachefile -echo zstyle \":completion:\${curcontext}:\" tag-order \'! options\' >> $cachefile -echo "\n\n_beet \"\$@\"\n" >> $cachefile - # Execute the completion function _beet "$@" From d803878297abb66e84755e8d915723d420092782 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 21:56:46 -0500 Subject: [PATCH 1493/2280] Try linking to the Discourse It's about time we gave that a try... --- docs/faq.rst | 3 ++- docs/guides/main.rst | 3 ++- docs/guides/tagger.rst | 5 +++-- docs/index.rst | 7 ++++--- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/faq.rst b/docs/faq.rst index e36b589bb..b7ec10df5 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -2,11 +2,12 @@ FAQ ### Here are some answers to frequently-asked questions from IRC and elsewhere. -Got a question that isn't answered here? Try `IRC`_, the `mailing list`_, or +Got a question that isn't answered here? Try `IRC`_, the `discussion board`_, or :ref:`filing an issue ` in the bug tracker. .. _IRC: irc://irc.freenode.net/beets .. _mailing list: http://groups.google.com/group/beets-users +.. _discussion board: http://discourse.beets.io .. contents:: :local: diff --git a/docs/guides/main.rst b/docs/guides/main.rst index b0bc8e0e9..4ee2debed 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -281,8 +281,9 @@ You can always get help using the ``beet help`` command. The plain ``beet help`` command lists all the available commands; then, for example, ``beet help import`` gives more specific help about the ``import`` command. -Please let me know what you think of beets via `the mailing list`_ or +Please let me know what you think of beets via `the discussion board`_ or `Twitter`_. .. _the mailing list: http://groups.google.com/group/beets-users +.. _the discussion board: http://discourse.beets.io .. _twitter: http://twitter.com/b33ts diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 0b21644bf..6c0e44f9e 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -291,7 +291,8 @@ If you think beets is ignoring an album that's listed in MusicBrainz, please I Hope That Makes Sense ----------------------- -If I haven't made the process clear, please send an email to `the mailing -list`_ and I'll try to improve this guide. +If we haven't made the process clear, please post on `the discussion +board`_ and we'll try to improve this guide. .. _the mailing list: http://groups.google.com/group/beets-users +.. _the discussion board: http://discourse.beets.io diff --git a/docs/index.rst b/docs/index.rst index 772869389..43ba0526a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -13,13 +13,14 @@ Then you can get a more detailed look at beets' features in the be interested in exploring the :doc:`plugins `. If you still need help, your can drop by the ``#beets`` IRC channel on -Freenode, send email to `the mailing list`_, or `file a bug`_ in the issue -tracker. Please let us know where you think this documentation can be -improved. +Freenode, drop by `the discussion board`_, send email to `the mailing list`_, +or `file a bug`_ in the issue tracker. Please let us know where you think this +documentation can be improved. .. _beets: http://beets.io/ .. _the mailing list: http://groups.google.com/group/beets-users .. _file a bug: https://github.com/beetbox/beets/issues +.. _the discussion board: http://discourse.beets.io Contents -------- From 51ba7803218917e901a1176d051c0d9e3c2e4632 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 22:03:34 -0500 Subject: [PATCH 1494/2280] Changelog note about #2266 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4108753f1..7857df2f0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,8 @@ Here are the fixes: unicode characters into ASCII, such as ½ and ¢. * :doc:`/plugins/convert`: Fix a logging-related crash when filenames contain curly brackets. Thanks to :user:`kierdavis`. :bug:`2323` +* We've rolled back some changes to the included zsh completion script that + were causing problems for some users. :bug:`2266` Also, we've removed some special handling for logging in the :doc:`/plugins/discogs` that we believe was unnecessary. If spurious log From 30d8b2e212354d5244d2c4232912b084ef0cd17e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 22:04:42 -0500 Subject: [PATCH 1495/2280] Tiny changelog fixes --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 7857df2f0..4bdf2d246 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,9 +15,9 @@ Here are the fixes: * :doc:`/plugins/badfiles`: Fix a crash on non-ASCII filenames. :bug:`2299` * The ``%asciify{}`` path formatting function and the :ref:`asciify-paths` setting properly substitute path separators generated by converting some - unicode characters into ASCII, such as ½ and ¢. + Unicode characters, such as ½ and ¢, into ASCII. * :doc:`/plugins/convert`: Fix a logging-related crash when filenames contain - curly brackets. Thanks to :user:`kierdavis`. :bug:`2323` + curly braces. Thanks to :user:`kierdavis`. :bug:`2323` * We've rolled back some changes to the included zsh completion script that were causing problems for some users. :bug:`2266` From 1df66a93db9b5963596e862d8a749bc35cf18eac Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 22:05:45 -0500 Subject: [PATCH 1496/2280] Add date to changelog --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4bdf2d246..46652ddb9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.2 (in development) ----------------------- +1.4.2 (December 16, 2016) +------------------------- This is just a little bug fix release. With 1.4.2, we're also confident enough to recommend that anyone who's interested give Python 3 a try: bugs may still From faf2b9feb326cc31d7630eff7c62819cd2a1e859 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Dec 2016 22:07:34 -0500 Subject: [PATCH 1497/2280] Version bump: 1.4.3 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 2fe5933d7..5d82b05f7 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.2' +__version__ = u'1.4.3' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 46652ddb9..40b044941 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.3 (in development) +---------------------- + +Changelog goes here! + + 1.4.2 (December 16, 2016) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index 9b612711d..99771e7b1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.2' +release = '1.4.3' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 18fbc9d43..07048b3fa 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.2', + version='1.4.3', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 1bc54569860264e4d6184f59f5373f5869fc983b Mon Sep 17 00:00:00 2001 From: diomekes Date: Sat, 17 Dec 2016 17:24:58 -0500 Subject: [PATCH 1498/2280] random: make --album work with --time --- beetsplug/random.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beetsplug/random.py b/beetsplug/random.py index 0dc438927..d719b5910 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -42,6 +42,8 @@ def random_item(lib, opts, args): objs = [] for item in objs_shuffled: + if opts.album: + item.length = sum(a.length for a in item.items()) if (total_time + item.length) <= time_sec: objs.append(item) total_time += item.length @@ -63,6 +65,8 @@ def random_item(lib, opts, args): if not objs_by_artists: break + if opts.album: + item.length = sum(a.length for a in item.items()) if (total_time + item.length) <= time_sec: artist = random.choice(list(objs_by_artists.keys())) objs_from_artist = objs_by_artists[artist] From a5b37d01c94eb53bffaf14997205840f60692b71 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 16:46:00 -0600 Subject: [PATCH 1499/2280] added zero subcommand --- beetsplug/zero.py | 54 ++++++++++++++++++++++++++++++++++- test/test_zero.py | 72 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 1 deletion(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 1401b11de..403def807 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -21,7 +21,8 @@ import re from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action -from beets.util import confit +from beets.util import confit, syspath +from beets.ui import Subcommand, decargs import six __author__ = 'baobab@heresiarch.info' @@ -41,6 +42,7 @@ class ZeroPlugin(BeetsPlugin): self.import_task_choice_event) self.config.add({ + 'auto': True, 'fields': [], 'keep_fields': [], 'update_database': False, @@ -75,6 +77,16 @@ class ZeroPlugin(BeetsPlugin): if key in self.patterns: del self.patterns[key] + def commands(self): + zero_command = Subcommand('zero', help='set fields to null') + + def zero_fields(lib, opts, args): + for item in lib.items(decargs(args)): + self.process_item(item) + + zero_command.func = zero_fields + return [zero_command] + def validate_config(self, mode): """Check whether fields in the configuration are valid. @@ -120,10 +132,39 @@ class ZeroPlugin(BeetsPlugin): return True return False + def process_item(self, item): + if not self.patterns: + self._log.warning(u'no fields, nothing to do') + return + + for field, patterns in self.patterns.items(): + if field in item.keys(): + if not self.should_update(item, field): + continue + + value = item[field] + match = self.match_patterns(item[field], patterns) + + else: + value = '' + match = patterns is True + + if match: + self._log.warning(u'{0}: {1} -> None', field, value) + item[field] = None + if self.config['update_database']: + item.update({field: None}) + item.store() + + item.write() + def write_event(self, item, path, tags): """Set values in tags to `None` if the key and value are matched by `self.patterns`. """ + if not self.config['auto']: + return + if not self.patterns: self._log.warning(u'no fields, nothing to do') return @@ -141,3 +182,14 @@ class ZeroPlugin(BeetsPlugin): tags[field] = None if self.config['update_database']: item[field] = None + + def should_update(self, item, field): + media = MediaFile(syspath(item.path)) + attributes = media.fields() + if field in attributes: + return True + + if self.config['update_database'] and item[field]: + return True + + return False diff --git a/test/test_zero.py b/test/test_zero.py index fb28330ee..ca4a2dd67 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -121,6 +121,78 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): mediafile = MediaFile(syspath(item.path)) self.assertEqual(0, len(mediafile.images)) + def test_auto_false(self): + item = self.add_item_fixture(year=2000) + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(2000, mediafile.year) + + config['zero'] = { + 'fields': [u'year'], + 'update_database': True, + 'auto': False + } + self.load_plugins('zero') + + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(item['year'], 2000) + self.assertEqual(mediafile.year, 2000) + + def test_subcommand(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + config['zero'] = { + 'fields': [u'comments'], + 'update_database': True, + 'auto': False + } + self.load_plugins('zero') + self.run_command('zero') + + mediafile = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, None) + self.assertEqual(item['comments'], u'') + + def test_subcommand_update_database_False(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + self.load_plugins('zero') + + z = ZeroPlugin() + z.debug = False + self.run_command('zero') + + mediafile = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + self.assertEqual(item['comments'], u'test comment') + self.assertEqual(mediafile.comments, None) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From fec7e30fe18a441c4d5b18b640e122f92790f908 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:17:55 -0600 Subject: [PATCH 1500/2280] added documentation for zero subcommand --- docs/plugins/zero.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index ecaa60a3d..282bb4fc8 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -18,6 +18,7 @@ Configuration Make a ``zero:`` section in your configuration file. You can specify the fields to nullify and the conditions for nullifying them: +* Set ``auto`` to ``yes`` to null fields automatically on import. Default ``yes`` * Set ``fields`` to a whitespace-separated list of fields to change. You can get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images @@ -42,3 +43,9 @@ If a custom pattern is not defined for a given field, the field will be nulled unconditionally. Note that the plugin currently does not zero fields when importing "as-is". + +Manually Triggering Zero +------------------------ + +The ``zero`` command will invoke the zero plugin on items matching a query. Use the +command ``beet zero [QUERY]`` From 148354c5c499bed665813a4631c5fd6f3e4e788a Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:30:07 -0600 Subject: [PATCH 1501/2280] additional zero tests --- test/test_zero.py | 54 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/test/test_zero.py b/test/test_zero.py index ca4a2dd67..38fdb3726 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -139,7 +139,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(item['year'], 2000) self.assertEqual(mediafile.year, 2000) - def test_subcommand(self): + def test_subcommand_update_database_true(self): item = self.add_item_fixture( year=2016, day=13, @@ -164,7 +164,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(mediafile.comments, None) self.assertEqual(item['comments'], u'') - def test_subcommand_update_database_False(self): + def test_subcommand_update_database_false(self): item = self.add_item_fixture( year=2016, day=13, @@ -179,9 +179,6 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): 'auto': False } self.load_plugins('zero') - - z = ZeroPlugin() - z.debug = False self.run_command('zero') mediafile = MediaFile(syspath(item.path)) @@ -192,6 +189,53 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(item['comments'], u'test comment') self.assertEqual(mediafile.comments, None) + def test_subcommand_query_include(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + + item.write() + + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + + self.load_plugins('zero') + self.run_command('zero', 'year: 2016') + + mediafile = MediaFile(syspath(item.path)) + + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, None) + + def test_subcommand_query_exclude(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + + item.write() + + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + + self.load_plugins('zero') + self.run_command('zero', 'year: 0000') + + mediafile = MediaFile(syspath(item.path)) + + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, u'test comment') def suite(): From c40a587e68d6dd6cb579183c4728d06a95090945 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:49:45 -0600 Subject: [PATCH 1502/2280] update changelog --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 40b044941..b5ea8a62b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,10 @@ Changelog Changelog goes here! +Features: + +* :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero + plugin. 1.4.2 (December 16, 2016) ------------------------- From 88f59e64eab8ea44a773a807115ac992cbd2fbf0 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 17 Dec 2016 18:55:59 -0500 Subject: [PATCH 1503/2280] Add Python 3 trove classifiers --- setup.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup.py b/setup.py index 07048b3fa..7a7dbe83e 100755 --- a/setup.py +++ b/setup.py @@ -135,5 +135,8 @@ setup( 'Environment :: Web Environment', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', ], ) From 510fe6f146f1be757d321fae639fadb769f41986 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sun, 18 Dec 2016 14:27:42 -0600 Subject: [PATCH 1504/2280] refactor changes to zero plugin --- beetsplug/zero.py | 55 +++++++++++++++-------------------------------- 1 file changed, 17 insertions(+), 38 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 403def807..73961134a 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -21,7 +21,7 @@ import re from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action -from beets.util import confit, syspath +from beets.util import confit from beets.ui import Subcommand, decargs import six @@ -94,13 +94,13 @@ class ZeroPlugin(BeetsPlugin): the section of the configuration to validate. """ for field in self.config[mode].as_str_seq(): - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue if mode == 'fields' and field in ('id', 'path', 'album_id'): self._log.warning(u'field \'{0}\' ignored, zeroing ' u'it would be dangerous', field) continue + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + continue def set_pattern(self, field): """Set a field in `self.patterns` to a string list corresponding to @@ -133,30 +133,12 @@ class ZeroPlugin(BeetsPlugin): return False def process_item(self, item): - if not self.patterns: - self._log.warning(u'no fields, nothing to do') - return + tags = dict(item) - for field, patterns in self.patterns.items(): - if field in item.keys(): - if not self.should_update(item, field): - continue - - value = item[field] - match = self.match_patterns(item[field], patterns) - - else: - value = '' - match = patterns is True - - if match: - self._log.warning(u'{0}: {1} -> None', field, value) - item[field] = None - if self.config['update_database']: - item.update({field: None}) - item.store() - - item.write() + if self.set_fields(item, tags): + item.write(tags=tags) + if self.config['update_database']: + item.store(fields=tags) def write_event(self, item, path, tags): """Set values in tags to `None` if the key and value are matched @@ -165,9 +147,14 @@ class ZeroPlugin(BeetsPlugin): if not self.config['auto']: return + self.set_fields(item, tags) + + def set_fields(self, item, tags): + fields_set = False + if not self.patterns: self._log.warning(u'no fields, nothing to do') - return + return False for field, patterns in self.patterns.items(): if field in tags: @@ -178,18 +165,10 @@ class ZeroPlugin(BeetsPlugin): match = patterns is True if match: + fields_set = True self._log.debug(u'{0}: {1} -> None', field, value) tags[field] = None if self.config['update_database']: item[field] = None - def should_update(self, item, field): - media = MediaFile(syspath(item.path)) - attributes = media.fields() - if field in attributes: - return True - - if self.config['update_database'] and item[field]: - return True - - return False + return fields_set From 69a58ca842e9741a1125e5622e3d1c1c5b613ef9 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sun, 18 Dec 2016 14:28:55 -0600 Subject: [PATCH 1505/2280] additional test coverage for zero plugin --- test/test_zero.py | 71 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/test/test_zero.py b/test/test_zero.py index 38fdb3726..e7af5fee8 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -19,6 +19,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.setup_beets() def tearDown(self): + self.remove_mediafile_fixtures() self.teardown_beets() self.unload_plugins() @@ -237,6 +238,76 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(mediafile.year, 2016) self.assertEqual(mediafile.comments, u'test comment') + def test_no_fields(self): + item = self.add_item_fixture(year=2016) + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.year, 2016) + + item_id = item.id + config['zero'] = {} + self.load_plugins('zero') + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + + def test_whitelist_and_blacklist(self): + item = self.add_item_fixture(year=2016) + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.year, 2016) + + item_id = item.id + config['zero'] = {'fields': [u'year'], + 'keep_fields': [u'comments']} + + self.load_plugins('zero') + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + + def test_keep_fields(self): + item = self.add_item_fixture(year=2016, comments=u'test comment') + config['zero'] = {'keep_fields': [u'year'], + 'fields': None, + 'update_database': True, + 'auto': True} + + tags = { + 'comments': u'test comment', + 'year': 2016, + } + self.load_plugins('zero') + z = ZeroPlugin() + z.write_event(item, item.path, tags) + self.assertEqual(tags['comments'], None) + self.assertEqual(tags['year'], 2016) + + def test_keep_fields_removes_preserved_tags(self): + config['zero'] = {'keep_fields': [u'year id'], + 'fields': None, + 'update_database': True, + 'auto': True} + + z = ZeroPlugin() + + self.assertNotIn('id', z.patterns) + + def test_field_preserved_tags(self): + config['zero'] = {'fields': [u'year id'], + 'update_database': True, + 'auto': True} + + z = ZeroPlugin() + + self.assertNotIn('id', z.patterns) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 7060b512b848fb36f49dcc091f65a6e7baa83d4f Mon Sep 17 00:00:00 2001 From: Shen-Ta Hsieh Date: Tue, 20 Dec 2016 20:15:46 +0800 Subject: [PATCH 1506/2280] Add Composer, Lyricist and Arranger tags MusicBrainz provids composer, lyricist and arranger infomations related to individual recordings. This commit adds query parameters to fetch them, and write down to media files. Tagging mapping is implemented according MusicBrainz Picard's data: https://picard.musicbrainz.org/docs/mappings/ Signed-off-by: Shen-Ta Hsieh --- beets/autotag/__init__.py | 15 +++++++++++ beets/autotag/hooks.py | 8 +++++- beets/autotag/mb.py | 33 ++++++++++++++++++++++-- beets/library.py | 2 ++ beets/mediafile.py | 52 ++++++++++++++++++++++++++++++++++++++ test/_common.py | 2 ++ test/rsrc/unicode’d.mp3 | Bin 12820 -> 12820 bytes test/test_mediafile.py | 2 ++ 8 files changed, 111 insertions(+), 3 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index b3cfa9541..09aed89ce 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -44,6 +44,14 @@ def apply_item_metadata(item, track_info): item.mb_artistid = track_info.artist_id if track_info.data_source: item.data_source = track_info.data_source + + if track_info.lyricist is not None: + item.lyricist = track_info.lyricist + if track_info.composer is not None: + item.composer = track_info.composer + if track_info.arranger is not None: + item.arranger = track_info.arranger + # At the moment, the other metadata is left intact (including album # and track number). Perhaps these should be emptied? @@ -142,3 +150,10 @@ def apply_metadata(album_info, mapping): if track_info.media is not None: item.media = track_info.media + + if track_info.lyricist is not None: + item.lyricist = track_info.lyricist + if track_info.composer is not None: + item.composer = track_info.composer + if track_info.arranger is not None: + item.arranger = track_info.arranger diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 1a9aaf908..40db6e8d3 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -142,6 +142,9 @@ class TrackInfo(object): - ``artist_credit``: Recording-specific artist name - ``data_source``: The original data source (MusicBrainz, Discogs, etc.) - ``data_url``: The data source release URL. + - ``lyricist``: individual track lyricist name + - ``composer``: individual track composer name + - ``arranger`: individual track arranger name Only ``title`` and ``track_id`` are required. The rest of the fields may be None. The indices ``index``, ``medium``, and ``medium_index`` @@ -151,7 +154,7 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None): + media=None, lyricist=None, composer=None, arranger=None): self.title = title self.track_id = track_id self.artist = artist @@ -167,6 +170,9 @@ class TrackInfo(object): self.artist_credit = artist_credit self.data_source = data_source self.data_url = data_url + self.lyricist = lyricist + self.composer = composer + self.arranger = arranger # As above, work around a bug in python-musicbrainz-ngs. def decode(self, codec='utf-8'): diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 78d382d87..9c80c149e 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -54,8 +54,10 @@ class MusicBrainzAPIError(util.HumanReadableException): log = logging.getLogger('beets') RELEASE_INCLUDES = ['artists', 'media', 'recordings', 'release-groups', - 'labels', 'artist-credits', 'aliases'] -TRACK_INCLUDES = ['artists', 'aliases'] + 'labels', 'artist-credits', 'aliases', + 'recording-level-rels', 'work-rels', + 'work-level-rels', 'artist-rels'] +TRACK_INCLUDES = ['artists', 'aliases', 'work-level-rels', 'artist-rels'] def track_url(trackid): @@ -179,6 +181,33 @@ def track_info(recording, index=None, medium=None, medium_index=None, if recording.get('length'): info.length = int(recording['length']) / (1000.0) + lyricist = [] + composer = [] + for work_relation in recording.get('work-relation-list', ()): + if work_relation['type'] != 'performance': + continue + for artist_relation in work_relation['work'].get( + 'artist-relation-list', ()): + if 'type' in artist_relation: + type = artist_relation['type'] + if type == 'lyricist': + lyricist.append(artist_relation['artist']['name']) + elif type == 'composer': + composer.append(artist_relation['artist']['name']) + if lyricist: + info.lyricist = u', '.join(lyricist) + if composer: + info.composer = u', '.join(composer) + + arranger = [] + for artist_relation in recording.get('artist-relation-list', ()): + if 'type' in artist_relation: + type = artist_relation['type'] + if type == 'arranger': + arranger.append(artist_relation['artist']['name']) + if arranger: + info.arranger = u', '.join(arranger) + info.decode() return info diff --git a/beets/library.py b/beets/library.py index 5cffdbe34..32176b68d 100755 --- a/beets/library.py +++ b/beets/library.py @@ -415,7 +415,9 @@ class Item(LibModel): 'albumartist_sort': types.STRING, 'albumartist_credit': types.STRING, 'genre': types.STRING, + 'lyricist': types.STRING, 'composer': types.STRING, + 'arranger': types.STRING, 'grouping': types.STRING, 'year': types.PaddedInt(4), 'month': types.PaddedInt(2), diff --git a/beets/mediafile.py b/beets/mediafile.py index 9db6ba4db..65420761f 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -752,6 +752,45 @@ class MP3StorageStyle(StorageStyle): mutagen_file.tags.setall(self.key, [frame]) +class MP3PeopleStorageStyle(MP3StorageStyle): + """Store list of people in ID3 frames. + """ + def __init__(self, key, involvement='', **kwargs): + self.involvement = involvement + super(MP3PeopleStorageStyle, self).__init__(key, **kwargs) + + def store(self, mutagen_file, value): + frames = mutagen_file.tags.getall(self.key) + print(frames) + + # Try modifying in place. + found = False + for frame in frames: + if frame.encoding == mutagen.id3.Encoding.UTF8: + for pair in frame.people: + if pair[0].lower() == self.involvement.lower(): + pair[1] = value + found = True + + # Try creating a new frame. + if not found: + frame = mutagen.id3.Frames[self.key]( + encoding=mutagen.id3.Encoding.UTF8, + people=[[self.involvement, value]] + ) + print(frame) + mutagen_file.tags.add(frame) + + def fetch(self, mutagen_file): + for frame in mutagen_file.tags.getall(self.key): + for pair in frame.people: + if pair[0].lower() == self.involvement.lower(): + try: + return pair[1] + except IndexError: + return None + + class MP3ListStorageStyle(ListStorageStyle, MP3StorageStyle): """Store lists of data in multiple ID3 frames. """ @@ -1590,12 +1629,25 @@ class MediaFile(object): ) genre = genres.single_field() + lyricist = MediaField( + MP3StorageStyle('TEXT'), + MP4StorageStyle('----:com.apple.iTunes:LYRICIST'), + StorageStyle('LYRICIST'), + ASFStorageStyle('WM/Writer'), + ) composer = MediaField( MP3StorageStyle('TCOM'), MP4StorageStyle('\xa9wrt'), StorageStyle('COMPOSER'), ASFStorageStyle('WM/Composer'), ) + arranger = MediaField( + MP3PeopleStorageStyle('TIPL', involvement='arranger'), + MP4StorageStyle('----:com.apple.iTunes:Arranger'), + StorageStyle('ARRANGER'), + ASFStorageStyle('beets/Arranger'), + ) + grouping = MediaField( MP3StorageStyle('TIT1'), MP4StorageStyle('\xa9grp'), diff --git a/test/_common.py b/test/_common.py index 597f0dc38..2e7418516 100644 --- a/test/_common.py +++ b/test/_common.py @@ -65,7 +65,9 @@ def item(lib=None): albumartist=u'the album artist', album=u'the album', genre=u'the genre', + lyricist=u'the lyricist', composer=u'the composer', + arranger=u'the arranger', grouping=u'the grouping', year=1, month=2, diff --git a/test/rsrc/unicode’d.mp3 b/test/rsrc/unicode’d.mp3 index a1418194129a59975c475decb4e845c71c2389a3..7be1e05186ffc38ed3f61c3d5bd56f5b8f37b151 100644 GIT binary patch delta 36 rcmbP|G9_h$B$H5p4+8@OHv Date: Tue, 20 Dec 2016 15:16:46 -0500 Subject: [PATCH 1507/2280] Fix #2332: Unicode trouble in bpd --- beetsplug/bpd/__init__.py | 19 ++++++++++--------- docs/changelog.rst | 4 +++- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/beetsplug/bpd/__init__.py b/beetsplug/bpd/__init__.py index c789d32b5..1049f0c76 100644 --- a/beetsplug/bpd/__init__.py +++ b/beetsplug/bpd/__init__.py @@ -40,13 +40,13 @@ import six PROTOCOL_VERSION = '0.13.0' BUFSIZE = 1024 -HELLO = 'OK MPD %s' % PROTOCOL_VERSION -CLIST_BEGIN = 'command_list_begin' -CLIST_VERBOSE_BEGIN = 'command_list_ok_begin' -CLIST_END = 'command_list_end' -RESP_OK = 'OK' -RESP_CLIST_VERBOSE = 'list_OK' -RESP_ERR = 'ACK' +HELLO = u'OK MPD %s' % PROTOCOL_VERSION +CLIST_BEGIN = u'command_list_begin' +CLIST_VERBOSE_BEGIN = u'command_list_ok_begin' +CLIST_END = u'command_list_end' +RESP_OK = u'OK' +RESP_CLIST_VERBOSE = u'list_OK' +RESP_ERR = u'ACK' NEWLINE = u"\n" @@ -604,7 +604,8 @@ class Connection(object): line = line.strip() if not line: break - log.debug('{}', line) + line = line.decode('utf8') # MPD protocol uses UTF-8. + log.debug(u'{}', line) if clist is not None: # Command list already opened. @@ -656,7 +657,7 @@ class Command(object): if match[0]: # Quoted argument. arg = match[0] - arg = arg.replace('\\"', '"').replace('\\\\', '\\') + arg = arg.replace(u'\\"', u'"').replace(u'\\\\', u'\\') else: # Unquoted argument. arg = match[1] diff --git a/docs/changelog.rst b/docs/changelog.rst index 40b044941..34551ce9d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,9 @@ Changelog 1.4.3 (in development) ---------------------- -Changelog goes here! +Fixes: + +* :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` 1.4.2 (December 16, 2016) From 97e558185a0fd3dd1e0e7e62560e2427542025bf Mon Sep 17 00:00:00 2001 From: Shen-Ta Hsieh Date: Wed, 21 Dec 2016 10:10:59 +0800 Subject: [PATCH 1508/2280] add compatibility to old version of musicbrainzngs Signed-off-by: Shen-Ta Hsieh --- beets/autotag/mb.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 9c80c149e..55ecfc185 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -57,7 +57,9 @@ RELEASE_INCLUDES = ['artists', 'media', 'recordings', 'release-groups', 'labels', 'artist-credits', 'aliases', 'recording-level-rels', 'work-rels', 'work-level-rels', 'artist-rels'] -TRACK_INCLUDES = ['artists', 'aliases', 'work-level-rels', 'artist-rels'] +TRACK_INCLUDES = ['artists', 'aliases'] +if 'work-level-rels' in musicbrainzngs.VALID_INCLUDES['recording']: + TRACK_INCLUDES += ['work-level-rels', 'artist-rels'] def track_url(trackid): From 3528a675fad03ab0c5b9bcd7f5878f24d7e28bc4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 21 Dec 2016 11:17:26 -0500 Subject: [PATCH 1509/2280] Changelog for #2333 --- docs/changelog.rst | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 34551ce9d..2720ffe19 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,13 @@ Changelog 1.4.3 (in development) ---------------------- +Features: + +* We now support the composer, lyricist, and arranger tags. The MusicBrainz + data source will fetch data for these fields when the next version of + `python-musicbrainzngs`_ is released. Thanks to :user:`ibmibmibm`. + :bug:`506` :bug:`507` :bug:`1547` :bug:`2333` + Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` @@ -553,7 +560,7 @@ The new features: how the items will be moved without actually changing anything. * The importer now supports matching of "pregap" or HTOA (hidden track-one audio) tracks when they are listed in MusicBrainz. (This feature depends on a - new version of the ``musicbrainzngs`` library that is not yet released, but + new version of the `python-musicbrainzngs`_ library that is not yet released, but will start working when it is available.) Thanks to :user:`ruippeixotog`. :bug:`1104` :bug:`1493` * :doc:`/plugins/plexupdate`: A new ``token`` configuration option lets you @@ -2001,7 +2008,7 @@ query syntax. New configuration options: * :ref:`languages` controls the preferred languages when selecting an alias - from MusicBrainz. This feature requires `python-musicbrainz-ngs`_ 0.3 or + from MusicBrainz. This feature requires `python-musicbrainzngs`_ 0.3 or later. Thanks to Sam Doshi. * :ref:`detail` enables a mode where all tracks are listed in the importer UI, as opposed to only changed tracks. @@ -2667,7 +2674,7 @@ tracks from a given release. Two other new plugins are also included with this release: one for assigning genres and another for ReplayGain analysis. * Beets now communicates with MusicBrainz via the new `Next Generation Schema`_ - (NGS) service via `python-musicbrainz-ngs`_. The bindings are included with + (NGS) service via `python-musicbrainzngs`_. The bindings are included with this version of beets, but a future version will make them an external dependency. * The importer now detects **multi-disc albums** and tags them together. Using a @@ -2713,7 +2720,7 @@ release: one for assigning genres and another for ReplayGain analysis. .. _KraYmer: https://github.com/KraYmer .. _Next Generation Schema: http://musicbrainz.org/doc/XML_Web_Service/Version_2 -.. _python-musicbrainz-ngs: https://github.com/alastair/python-musicbrainz-ngs +.. _python-musicbrainzngs: https://github.com/alastair/python-musicbrainzngs .. _acoustid: http://acoustid.org/ .. _Peter Brunner: https://github.com/Lugoues .. _Simon Chopin: https://github.com/laarmen From 8cc2ac5b39262a9afb05ce2170b91f2bf2b45c16 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 21 Dec 2016 21:11:16 -0500 Subject: [PATCH 1510/2280] Remove stray prints (#2333) --- beets/mediafile.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 65420761f..ad66b74c5 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -761,7 +761,6 @@ class MP3PeopleStorageStyle(MP3StorageStyle): def store(self, mutagen_file, value): frames = mutagen_file.tags.getall(self.key) - print(frames) # Try modifying in place. found = False @@ -778,7 +777,6 @@ class MP3PeopleStorageStyle(MP3StorageStyle): encoding=mutagen.id3.Encoding.UTF8, people=[[self.involvement, value]] ) - print(frame) mutagen_file.tags.add(frame) def fetch(self, mutagen_file): From fd3ff917d21a1e99bb88b8ef4ecd9d3417e4e1ea Mon Sep 17 00:00:00 2001 From: inytar Date: Fri, 23 Dec 2016 17:27:46 -0500 Subject: [PATCH 1511/2280] Implement the basic AcousticBrainz Submit plugin --- beetsplug/absubmit.py | 159 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 beetsplug/absubmit.py diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py new file mode 100644 index 000000000..3eb883366 --- /dev/null +++ b/beetsplug/absubmit.py @@ -0,0 +1,159 @@ +"""Calculate acoustic information and submit to AcousticBrainz. +""" + +from __future__ import division, absolute_import, print_function + +import hashlib +import json +import os +import subprocess +import tempfile + +import distutils +import requests + +from beets import plugins +from beets import util +from beets import ui + + +class ABSubmitError(Exception): + """Base exception for all excpetions this plugin can raise.""" + + +class FatalABSubmitError(ABSubmitError): + """Raised if the plugin is not able to start.""" + + +class AnalysisABSubmitError(ABSubmitError): + """Raised if analysis of file fails.""" + + +class SubmitABSubmitError(ABSubmitError): + """Raised if submitting data fails.""" + + +def call(args): + """Execute the command and return its output. + + Raise a AnalysisABSubmitError on failure. + """ + try: + return util.command_output(args) + except subprocess.CalledProcessError as e: + raise AnalysisABSubmitError( + u"{0} exited with status {1}".format(args[0], e.returncode) + ) + + +class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): + + def __init__(self): + super(AcousticBrainzSubmitPlugin, self).__init__() + + self.config.add({'extractor': u''}) + + self.extractor = self.config['extractor'].as_str() + if self.extractor: + self.extractor = util.normpath(self.extractor) + # Expicit path to extractor + if not os.path.isfile(self.extractor): + raise FatalABSubmitError( + u'extractor command does not exist: {0}'. + format(self.extractor) + ) + else: + # Implicit path to extractor, search for it in path + # TODO how to check for on Windows? + self.extractor = 'streaming_extractor_music' + try: + call([self.extractor]) + except OSError: + raise FatalABSubmitError( + u'no extractor command found: install "{0}"'. + format(self.extractor) + ) + except AnalysisABSubmitError: + # Extractor found, will exit with an error if not called with + # the correct amount of arguments. + pass + # Get the executable needed to calculate the sha1 hash. + self.extractor = distutils.spawn.find_executable(self.extractor) + + supported_formats = {'mp3', 'ogg', 'oga', 'flac', 'mp4', 'm4a', 'm4r', + 'm4b', 'm4p', 'aac', 'wma', 'asf', 'mpc', 'wv', + 'spx', 'tta', '3g2', 'aif', 'aiff', 'ape'} + + base_url = 'https://acousticbrainz.org/api/v1/{mbid}/low-level' + + def commands(self): + cmd = ui.Subcommand( + 'absubmit', + help=u'calculate and submit AcousticBrainz analysis' + ) + cmd.func = self.command + return [cmd] + + def command(self, lib, opts, args): + # Get items from arguments + items = lib.items(ui.decargs(args)) + # Get no_submit option. + # TODO get a should submit option from the command line. + for item in items: + analysis = self._get_analysis(item) + if analysis: + self._submit_data(item, analysis) + + def _get_analysis(self, item): + mbid = item['mb_trackid'] + # If file has no mbid skip it. + if not mbid: + self._log.info('Not analysing {}, missing ' + 'musicbrainz track id.', item) + return None + # If file format is not supported skip it. + if item['format'].lower() not in self.supported_formats: + self._log.info('Not analysing {}, file not in ' + 'supported format.', item) + return None + + # Temporary file to save extractor output to. + tmp_file, filename = tempfile.mkstemp(suffix='.json') + try: + # Close the file, so the extractor can overwrite it. + call([self.extractor, util.syspath(item.path), filename]) + with open(filename) as tmp_file: + analysis = json.loads(tmp_file.read()) + # Calculate extractor hash. + m = hashlib.sha1() + with open(self.extractor, 'rb') as extractor: + m.update(extractor.read()) + # Add the hash to the output. + analysis['metadata']['version']['essentia_build_sha'] = \ + m.hexdigest() + return analysis + finally: + try: + os.remove(filename) + except OSError as e: + # errno 2 means file does not exist, just ignore this error. + if e.errno != 2: + raise + + def _submit_data(self, item, data): + mbid = item['mb_trackid'] + headers = {'Content-Type': 'application/json'} + response = requests.post(self.base_url.format(mbid=mbid), + json=data, headers=headers) + # Test that request was successful and raise an error on failure. + if response.status_code != 200: + try: + message = response.json()['message'] + except Exception as e: + message = 'unable to get error message: {}'.format(e) + raise ABSubmitError( + 'Failed to submit analysis: {message})'. + format(status_code=response.status_code, message=message) + ) + self._log.debug('Successfully submitted AcousticBrainz analysis ' + 'for {}.', item) From f61aa7a0160effb1a45d8610f86c0e4da2c25805 Mon Sep 17 00:00:00 2001 From: inytar Date: Fri, 23 Dec 2016 17:48:29 -0500 Subject: [PATCH 1512/2280] Move extractor sha calculation to pluging init. --- beetsplug/absubmit.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index 3eb883366..ec48aef04 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -80,6 +80,12 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): # Get the executable needed to calculate the sha1 hash. self.extractor = distutils.spawn.find_executable(self.extractor) + # Calculate extractor hash. + self.extractor_sha = hashlib.sha1() + with open(self.extractor, 'rb') as extractor: + self.extractor_sha.update(extractor.read()) + self.extractor_sha = self.extractor_sha.hexdigest() + supported_formats = {'mp3', 'ogg', 'oga', 'flac', 'mp4', 'm4a', 'm4r', 'm4b', 'm4p', 'aac', 'wma', 'asf', 'mpc', 'wv', 'spx', 'tta', '3g2', 'aif', 'aiff', 'ape'} @@ -124,13 +130,9 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): call([self.extractor, util.syspath(item.path), filename]) with open(filename) as tmp_file: analysis = json.loads(tmp_file.read()) - # Calculate extractor hash. - m = hashlib.sha1() - with open(self.extractor, 'rb') as extractor: - m.update(extractor.read()) # Add the hash to the output. analysis['metadata']['version']['essentia_build_sha'] = \ - m.hexdigest() + self.extractor_sha return analysis finally: try: From 10f0d03d790da2e849125104a718a9f14ac535e6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 23 Dec 2016 20:23:23 -0500 Subject: [PATCH 1513/2280] Test "true" FLAC bitrate from Mutagen 1.35 Fix #2343. --- test/test_mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 3002b18b5..5fcb14187 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -830,7 +830,7 @@ class FlacTest(ReadWriteTestBase, PartialTestMixin, extension = 'flac' audio_properties = { 'length': 1.0, - 'bitrate': 175120, + 'bitrate': 108688, 'format': u'FLAC', 'samplerate': 44100, 'bitdepth': 16, From 57338f803f767d9714b27749592dd31d3c429640 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Sat, 24 Dec 2016 04:39:30 -0500 Subject: [PATCH 1514/2280] Use released version of Python 3.6 for travis (#2341) --- .travis.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index f8ceb9934..9a6236bed 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,7 +19,7 @@ matrix: env: {TOX_ENV: py34-test} - python: 3.5 env: {TOX_ENV: py35-test} - - python: 3.6-dev + - python: 3.6 env: {TOX_ENV: py36-test} # - python: pypy # - env: {TOX_ENV: pypy-test} @@ -27,8 +27,6 @@ matrix: env: {TOX_ENV: py34-flake8} - python: 2.7 env: {TOX_ENV: docs} - allow_failures: - - python: 3.6-dev # Non-Python dependencies. addons: apt: From 96d331ace01014623ada85266cbdedcd86d43867 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 24 Dec 2016 19:13:10 +0100 Subject: [PATCH 1515/2280] Zero: cleanup plugin --- beetsplug/zero.py | 97 +++++++++++++++++++---------------------------- 1 file changed, 39 insertions(+), 58 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 1401b11de..5659207fe 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -16,22 +16,20 @@ """ Clears tag fields in media files.""" from __future__ import division, absolute_import, print_function +import six import re + from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action from beets.util import confit -import six __author__ = 'baobab@heresiarch.info' __version__ = '0.10' class ZeroPlugin(BeetsPlugin): - - _instance = None - def __init__(self): super(ZeroPlugin, self).__init__() @@ -46,60 +44,43 @@ class ZeroPlugin(BeetsPlugin): 'update_database': False, }) - self.patterns = {} + self.fields_to_progs = {} self.warned = False - # We'll only handle `fields` or `keep_fields`, but not both. if self.config['fields'] and self.config['keep_fields']: self._log.warning( u'cannot blacklist and whitelist at the same time' ) - # Blacklist mode. - if self.config['fields']: - self.validate_config('fields') + elif self.config['fields']: for field in self.config['fields'].as_str_seq(): - self.set_pattern(field) - + self._set_pattern(field) # Whitelist mode. elif self.config['keep_fields']: - self.validate_config('keep_fields') - for field in MediaFile.fields(): - if field in self.config['keep_fields'].as_str_seq(): - continue - self.set_pattern(field) + if (field not in self.config['keep_fields'].as_str_seq() and + # These fields should always be preserved. + field not in ('id', 'path', 'album_id')): + self._set_pattern(field) - # These fields should always be preserved. - for key in ('id', 'path', 'album_id'): - if key in self.patterns: - del self.patterns[key] - - def validate_config(self, mode): - """Check whether fields in the configuration are valid. - - `mode` should either be "fields" or "keep_fields", indicating - the section of the configuration to validate. - """ - for field in self.config[mode].as_str_seq(): - if field not in MediaFile.fields(): - self._log.error(u'invalid field: {0}', field) - continue - if mode == 'fields' and field in ('id', 'path', 'album_id'): - self._log.warning(u'field \'{0}\' ignored, zeroing ' - u'it would be dangerous', field) - continue - - def set_pattern(self, field): + def _set_pattern(self, field): """Set a field in `self.patterns` to a string list corresponding to the configuration, or `True` if the field has no specific configuration. """ - try: - self.patterns[field] = self.config[field].as_str_seq() - except confit.NotFoundError: - # Matches everything - self.patterns[field] = True + if field not in MediaFile.fields(): + self._log.error(u'invalid field: {0}', field) + elif field in ('id', 'path', 'album_id'): + self._log.warning(u'field \'{0}\' ignored, zeroing ' + u'it would be dangerous', field) + else: + try: + for pattern in self.config[field].as_str_seq(): + prog = re.compile(pattern, re.IGNORECASE) + self.fields_to_progs.setdefault(field, []).append(prog) + except confit.NotFoundError: + # Matches everything + self.fields_to_progs[field] = [] def import_task_choice_event(self, session, task): """Listen for import_task_choice event.""" @@ -108,36 +89,36 @@ class ZeroPlugin(BeetsPlugin): self.warned = True # TODO request write in as-is mode - @classmethod - def match_patterns(cls, field, patterns): - """Check if field (as string) is matching any of the patterns in - the list. - """ - if patterns is True: - return True - for p in patterns: - if re.search(p, six.text_type(field), flags=re.IGNORECASE): - return True - return False - def write_event(self, item, path, tags): """Set values in tags to `None` if the key and value are matched by `self.patterns`. """ - if not self.patterns: + if not self.fields_to_progs: self._log.warning(u'no fields, nothing to do') return - for field, patterns in self.patterns.items(): + for field, progs in self.fields_to_progs.items(): if field in tags: value = tags[field] - match = self.match_patterns(tags[field], patterns) + match = _match_progs(value, progs, self._log) else: value = '' - match = patterns is True + match = not progs if match: self._log.debug(u'{0}: {1} -> None', field, value) tags[field] = None if self.config['update_database']: item[field] = None + + +def _match_progs(value, progs, log): + """Check if field (as string) is matching any of the patterns in + the list. + """ + if not progs: + return True + for prog in progs: + if prog.search(six.text_type(value)): + return True + return False From 7de97df209cc2c7d2b029d7aa5817562349c2e2a Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Sat, 24 Dec 2016 19:13:34 +0100 Subject: [PATCH 1516/2280] Zero: rewrite tests. Rely on plugin interface only. Unregister listeners by hand for the moment. --- test/test_zero.py | 125 +++++++++++++++++++++------------------------- 1 file changed, 56 insertions(+), 69 deletions(-) diff --git a/test/test_zero.py b/test/test_zero.py index fb28330ee..1223e5c9e 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -8,7 +8,6 @@ import unittest from test.helper import TestHelper from beets.library import Item -from beets import config from beetsplug.zero import ZeroPlugin from beets.mediafile import MediaFile from beets.util import syspath @@ -17,108 +16,96 @@ from beets.util import syspath class ZeroPluginTest(unittest.TestCase, TestHelper): def setUp(self): self.setup_beets() + self.config['zero'] = { + 'fields': [], + 'keep_fields': [], + 'update_database': False, + } def tearDown(self): + ZeroPlugin.listeners = None self.teardown_beets() self.unload_plugins() def test_no_patterns(self): - tags = { - 'comments': u'test comment', - 'day': 13, - 'month': 3, - 'year': 2012, - } - z = ZeroPlugin() - z.debug = False - z.fields = ['comments', 'month', 'day'] - z.patterns = {'comments': [u'.'], - 'month': [u'.'], - 'day': [u'.']} - z.write_event(None, None, tags) - self.assertEqual(tags['comments'], None) - self.assertEqual(tags['day'], None) - self.assertEqual(tags['month'], None) - self.assertEqual(tags['year'], 2012) + self.config['zero']['fields'] = ['comments', 'month'] - def test_patterns(self): - z = ZeroPlugin() - z.debug = False - z.fields = ['comments', 'year'] - z.patterns = {'comments': u'eac lame'.split(), - 'year': u'2098 2099'.split()} - - tags = { - 'comments': u'from lame collection, ripped by eac', - 'year': 2012, - } - z.write_event(None, None, tags) - self.assertEqual(tags['comments'], None) - self.assertEqual(tags['year'], 2012) - - def test_delete_replaygain_tag(self): - path = self.create_mediafile_fixture() - item = Item.from_path(path) - item.rg_track_peak = 0.0 + item = self.add_item_fixture( + comments=u'test comment', + title=u'Title', + month=1, + year=2000, + ) item.write() - mediafile = MediaFile(syspath(item.path)) - self.assertIsNotNone(mediafile.rg_track_peak) - self.assertIsNotNone(mediafile.rg_track_gain) - - config['zero'] = { - 'fields': ['rg_track_peak', 'rg_track_gain'], - } self.load_plugins('zero') - item.write() - mediafile = MediaFile(syspath(item.path)) - self.assertIsNone(mediafile.rg_track_peak) - self.assertIsNone(mediafile.rg_track_gain) + + mf = MediaFile(syspath(item.path)) + self.assertIsNone(mf.comments) + self.assertIsNone(mf.month) + self.assertEqual(mf.title, u'Title') + self.assertEqual(mf.year, 2000) + + def test_pattern_match(self): + self.config['zero']['fields'] = ['comments'] + self.config['zero']['comments'] = [u'encoded by'] + + item = self.add_item_fixture(comments=u'encoded by encoder') + item.write() + + self.load_plugins('zero') + item.write() + + mf = MediaFile(syspath(item.path)) + self.assertIsNone(mf.comments) + + def test_pattern_nomatch(self): + self.config['zero']['fields'] = ['comments'] + self.config['zero']['comments'] = [u'encoded by'] + + item = self.add_item_fixture(comments=u'recorded at place') + item.write() + + self.load_plugins('zero') + item.write() + + mf = MediaFile(syspath(item.path)) + self.assertEqual(mf.comments, u'recorded at place') def test_do_not_change_database(self): + self.config['zero']['fields'] = ['year'] + item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(syspath(item.path)) - self.assertEqual(2000, mediafile.year) - config['zero'] = {'fields': ['year']} self.load_plugins('zero') - item.write() - mediafile = MediaFile(syspath(item.path)) + self.assertEqual(item['year'], 2000) - self.assertIsNone(mediafile.year) def test_change_database(self): + self.config['zero']['fields'] = ['year'] + self.config['zero']['update_database'] = True + item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(syspath(item.path)) - self.assertEqual(2000, mediafile.year) - config['zero'] = { - 'fields': [u'year'], - 'update_database': True, - } self.load_plugins('zero') - item.write() - mediafile = MediaFile(syspath(item.path)) + self.assertEqual(item['year'], 0) - self.assertIsNone(mediafile.year) def test_album_art(self): + self.config['zero']['fields'] = ['images'] + path = self.create_mediafile_fixture(images=['jpg']) item = Item.from_path(path) - mediafile = MediaFile(syspath(item.path)) - self.assertNotEqual(0, len(mediafile.images)) - - config['zero'] = {'fields': [u'images']} self.load_plugins('zero') - item.write() - mediafile = MediaFile(syspath(item.path)) + + mediafile = MediaFile(syspath(path)) self.assertEqual(0, len(mediafile.images)) From 4cc4fe1290a018486becff8a023cabad10214061 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 16:46:00 -0600 Subject: [PATCH 1517/2280] added zero subcommand --- test/test_zero.py | 72 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/test/test_zero.py b/test/test_zero.py index 1223e5c9e..e7eb95413 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -108,6 +108,78 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): mediafile = MediaFile(syspath(path)) self.assertEqual(0, len(mediafile.images)) + def test_auto_false(self): + item = self.add_item_fixture(year=2000) + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(2000, mediafile.year) + + config['zero'] = { + 'fields': [u'year'], + 'update_database': True, + 'auto': False + } + self.load_plugins('zero') + + item.write() + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(item['year'], 2000) + self.assertEqual(mediafile.year, 2000) + + def test_subcommand(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + config['zero'] = { + 'fields': [u'comments'], + 'update_database': True, + 'auto': False + } + self.load_plugins('zero') + self.run_command('zero') + + mediafile = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, None) + self.assertEqual(item['comments'], u'') + + def test_subcommand_update_database_False(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + self.load_plugins('zero') + + z = ZeroPlugin() + z.debug = False + self.run_command('zero') + + mediafile = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + self.assertEqual(item['comments'], u'test comment') + self.assertEqual(mediafile.comments, None) + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 5b8b61f0c0d3f10250f3e3622b7f08c2a4f6d219 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:17:55 -0600 Subject: [PATCH 1518/2280] added documentation for zero subcommand --- docs/plugins/zero.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index ecaa60a3d..282bb4fc8 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -18,6 +18,7 @@ Configuration Make a ``zero:`` section in your configuration file. You can specify the fields to nullify and the conditions for nullifying them: +* Set ``auto`` to ``yes`` to null fields automatically on import. Default ``yes`` * Set ``fields`` to a whitespace-separated list of fields to change. You can get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images @@ -42,3 +43,9 @@ If a custom pattern is not defined for a given field, the field will be nulled unconditionally. Note that the plugin currently does not zero fields when importing "as-is". + +Manually Triggering Zero +------------------------ + +The ``zero`` command will invoke the zero plugin on items matching a query. Use the +command ``beet zero [QUERY]`` From ef802293502aa07398bae723e9347d2b295874b2 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:30:07 -0600 Subject: [PATCH 1519/2280] additional zero tests --- test/test_zero.py | 54 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/test/test_zero.py b/test/test_zero.py index e7eb95413..4baacba90 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -126,7 +126,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(item['year'], 2000) self.assertEqual(mediafile.year, 2000) - def test_subcommand(self): + def test_subcommand_update_database_true(self): item = self.add_item_fixture( year=2016, day=13, @@ -151,7 +151,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(mediafile.comments, None) self.assertEqual(item['comments'], u'') - def test_subcommand_update_database_False(self): + def test_subcommand_update_database_false(self): item = self.add_item_fixture( year=2016, day=13, @@ -166,9 +166,6 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): 'auto': False } self.load_plugins('zero') - - z = ZeroPlugin() - z.debug = False self.run_command('zero') mediafile = MediaFile(syspath(item.path)) @@ -179,6 +176,53 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertEqual(item['comments'], u'test comment') self.assertEqual(mediafile.comments, None) + def test_subcommand_query_include(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + + item.write() + + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + + self.load_plugins('zero') + self.run_command('zero', 'year: 2016') + + mediafile = MediaFile(syspath(item.path)) + + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, None) + + def test_subcommand_query_exclude(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + + item.write() + + config['zero'] = { + 'fields': [u'comments'], + 'update_database': False, + 'auto': False + } + + self.load_plugins('zero') + self.run_command('zero', 'year: 0000') + + mediafile = MediaFile(syspath(item.path)) + + self.assertEqual(mediafile.year, 2016) + self.assertEqual(mediafile.comments, u'test comment') def suite(): From 30ae211e66c101aaeb3917253033b528d29a7bc5 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Sat, 17 Dec 2016 17:49:45 -0600 Subject: [PATCH 1520/2280] update changelog --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2720ffe19..9cdf298c0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,10 @@ Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` +Features: + +* :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero + plugin. 1.4.2 (December 16, 2016) ------------------------- From 2903925e2f18f7e9cf3db59b9ad05a7182ffaeb7 Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Mon, 26 Dec 2016 13:34:34 -0600 Subject: [PATCH 1521/2280] Rewrite zero plugin manual mode --- beetsplug/zero.py | 33 ++++++++++- test/test_zero.py | 143 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 131 insertions(+), 45 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 5659207fe..975a9944f 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -23,6 +23,7 @@ import re from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action +from beets.ui import Subcommand, decargs from beets.util import confit __author__ = 'baobab@heresiarch.info' @@ -39,6 +40,7 @@ class ZeroPlugin(BeetsPlugin): self.import_task_choice_event) self.config.add({ + 'auto': True, 'fields': [], 'keep_fields': [], 'update_database': False, @@ -63,6 +65,16 @@ class ZeroPlugin(BeetsPlugin): field not in ('id', 'path', 'album_id')): self._set_pattern(field) + def commands(self): + zero_command = Subcommand('zero', help='set fields to null') + + def zero_fields(lib, opts, args): + for item in lib.items(decargs(args)): + self.process_item(item) + + zero_command.func = zero_fields + return [zero_command] + def _set_pattern(self, field): """Set a field in `self.patterns` to a string list corresponding to the configuration, or `True` if the field has no specific @@ -93,24 +105,41 @@ class ZeroPlugin(BeetsPlugin): """Set values in tags to `None` if the key and value are matched by `self.patterns`. """ + if self.config['auto']: + self.set_fields(item, tags) + + def set_fields(self, item, tags): + fields_set = False + if not self.fields_to_progs: self._log.warning(u'no fields, nothing to do') - return + return False for field, progs in self.fields_to_progs.items(): if field in tags: value = tags[field] - match = _match_progs(value, progs, self._log) + match = _match_progs(tags[field], progs, self._log) else: value = '' match = not progs if match: + fields_set = True self._log.debug(u'{0}: {1} -> None', field, value) tags[field] = None if self.config['update_database']: item[field] = None + return fields_set + + def process_item(self, item): + tags = dict(item) + + if self.set_fields(item, tags): + item.write(tags=tags) + if self.config['update_database']: + item.store(fields=tags) + def _match_progs(value, progs, log): """Check if field (as string) is matching any of the patterns in diff --git a/test/test_zero.py b/test/test_zero.py index 4baacba90..87e31c539 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -105,26 +105,21 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.load_plugins('zero') item.write() - mediafile = MediaFile(syspath(path)) - self.assertEqual(0, len(mediafile.images)) + mf = MediaFile(syspath(path)) + self.assertEqual(0, len(mf.images)) def test_auto_false(self): + self.config['zero']['fields'] = ['year'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + item = self.add_item_fixture(year=2000) item.write() - mediafile = MediaFile(syspath(item.path)) - self.assertEqual(2000, mediafile.year) - config['zero'] = { - 'fields': [u'year'], - 'update_database': True, - 'auto': False - } self.load_plugins('zero') - item.write() - mediafile = MediaFile(syspath(item.path)) + self.assertEqual(item['year'], 2000) - self.assertEqual(mediafile.year, 2000) def test_subcommand_update_database_true(self): item = self.add_item_fixture( @@ -135,20 +130,19 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): ) item.write() item_id = item.id - config['zero'] = { - 'fields': [u'comments'], - 'update_database': True, - 'auto': False - } + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + self.load_plugins('zero') self.run_command('zero') - mediafile = MediaFile(syspath(item.path)) + mf = MediaFile(syspath(item.path)) item = self.lib.get_item(item_id) self.assertEqual(item['year'], 2016) - self.assertEqual(mediafile.year, 2016) - self.assertEqual(mediafile.comments, None) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, None) self.assertEqual(item['comments'], u'') def test_subcommand_update_database_false(self): @@ -160,21 +154,21 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): ) item.write() item_id = item.id - config['zero'] = { - 'fields': [u'comments'], - 'update_database': False, - 'auto': False - } + + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False + self.load_plugins('zero') self.run_command('zero') - mediafile = MediaFile(syspath(item.path)) + mf = MediaFile(syspath(item.path)) item = self.lib.get_item(item_id) self.assertEqual(item['year'], 2016) - self.assertEqual(mediafile.year, 2016) + self.assertEqual(mf.year, 2016) self.assertEqual(item['comments'], u'test comment') - self.assertEqual(mediafile.comments, None) + self.assertEqual(mf.comments, None) def test_subcommand_query_include(self): item = self.add_item_fixture( @@ -186,19 +180,17 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): item.write() - config['zero'] = { - 'fields': [u'comments'], - 'update_database': False, - 'auto': False - } + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False self.load_plugins('zero') self.run_command('zero', 'year: 2016') - mediafile = MediaFile(syspath(item.path)) + mf = MediaFile(syspath(item.path)) - self.assertEqual(mediafile.year, 2016) - self.assertEqual(mediafile.comments, None) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, None) def test_subcommand_query_exclude(self): item = self.add_item_fixture( @@ -210,19 +202,84 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): item.write() - config['zero'] = { - 'fields': [u'comments'], - 'update_database': False, - 'auto': False - } + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = False + self.config['zero']['auto'] = False self.load_plugins('zero') self.run_command('zero', 'year: 0000') - mediafile = MediaFile(syspath(item.path)) + mf = MediaFile(syspath(item.path)) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, u'test comment') + + def test_no_fields(self): + item = self.add_item_fixture(year=2016) + item.write() + mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.year, 2016) - self.assertEqual(mediafile.comments, u'test comment') + + item_id = item.id + + self.load_plugins('zero') + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mediafile.year, 2016) + + def test_whitelist_and_blacklist(self): + item = self.add_item_fixture(year=2016) + item.write() + mf = MediaFile(syspath(item.path)) + self.assertEqual(mf.year, 2016) + + item_id = item.id + self.config['zero']['fields'] = [u'year'] + self.config['zero']['keep_fields'] = [u'comments'] + + self.load_plugins('zero') + self.run_command('zero') + + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + + def test_keep_fields(self): + item = self.add_item_fixture(year=2016, comments=u'test comment') + self.config['zero']['keep_fields'] = [u'year'] + self.config['zero']['fields'] = None + self.config['zero']['update_database'] = True + + tags = { + 'comments': u'test comment', + 'year': 2016, + } + self.load_plugins('zero') + z = ZeroPlugin() + z.write_event(item, item.path, tags) + self.assertEqual(tags['comments'], None) + self.assertEqual(tags['year'], 2016) + + def test_keep_fields_removes_preserved_tags(self): + self.config['zero']['keep_fields'] = [u'year'] + self.config['zero']['fields'] = None + self.config['zero']['update_database'] = True + + z = ZeroPlugin() + + self.assertNotIn('id', z.fields_to_progs) + + def test_fields_removes_preserved_tags(self): + self.config['zero']['fields'] = [u'year id'] + self.config['zero']['update_database'] = True + + z = ZeroPlugin() + + self.assertNotIn('id', z.fields_to_progs) def suite(): From 7833469261c9e15e922691beb8c698ec543c362e Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Mon, 26 Dec 2016 14:13:01 -0600 Subject: [PATCH 1522/2280] add confirmation for empty query --- beetsplug/zero.py | 4 +++- test/test_zero.py | 40 +++++++++++++++++++++++++++++++++++----- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 975a9944f..d3c3a697f 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -23,7 +23,7 @@ import re from beets.plugins import BeetsPlugin from beets.mediafile import MediaFile from beets.importer import action -from beets.ui import Subcommand, decargs +from beets.ui import Subcommand, decargs, input_yn from beets.util import confit __author__ = 'baobab@heresiarch.info' @@ -69,6 +69,8 @@ class ZeroPlugin(BeetsPlugin): zero_command = Subcommand('zero', help='set fields to null') def zero_fields(lib, opts, args): + if not decargs(args) and not input_yn(u"Remove fields for all items? (Y/n)", True): + return for item in lib.items(decargs(args)): self.process_item(item) diff --git a/test/test_zero.py b/test/test_zero.py index 87e31c539..025eaa540 100644 --- a/test/test_zero.py +++ b/test/test_zero.py @@ -5,7 +5,7 @@ from __future__ import division, absolute_import, print_function import unittest -from test.helper import TestHelper +from test.helper import TestHelper, control_stdin from beets.library import Item from beetsplug.zero import ZeroPlugin @@ -135,7 +135,8 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.config['zero']['auto'] = False self.load_plugins('zero') - self.run_command('zero') + with control_stdin('y'): + self.run_command('zero') mf = MediaFile(syspath(item.path)) item = self.lib.get_item(item_id) @@ -160,7 +161,8 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.config['zero']['auto'] = False self.load_plugins('zero') - self.run_command('zero') + with control_stdin('y'): + self.run_command('zero') mf = MediaFile(syspath(item.path)) item = self.lib.get_item(item_id) @@ -223,7 +225,8 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): item_id = item.id self.load_plugins('zero') - self.run_command('zero') + with control_stdin('y'): + self.run_command('zero') item = self.lib.get_item(item_id) @@ -241,7 +244,8 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.config['zero']['keep_fields'] = [u'comments'] self.load_plugins('zero') - self.run_command('zero') + with control_stdin('y'): + self.run_command('zero') item = self.lib.get_item(item_id) @@ -259,6 +263,7 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): 'year': 2016, } self.load_plugins('zero') + z = ZeroPlugin() z.write_event(item, item.path, tags) self.assertEqual(tags['comments'], None) @@ -281,6 +286,31 @@ class ZeroPluginTest(unittest.TestCase, TestHelper): self.assertNotIn('id', z.fields_to_progs) + def test_empty_query_n_response_no_changes(self): + item = self.add_item_fixture( + year=2016, + day=13, + month=3, + comments=u'test comment' + ) + item.write() + item_id = item.id + self.config['zero']['fields'] = ['comments'] + self.config['zero']['update_database'] = True + self.config['zero']['auto'] = False + + self.load_plugins('zero') + with control_stdin('n'): + self.run_command('zero') + + mf = MediaFile(syspath(item.path)) + item = self.lib.get_item(item_id) + + self.assertEqual(item['year'], 2016) + self.assertEqual(mf.year, 2016) + self.assertEqual(mf.comments, u'test comment') + self.assertEqual(item['comments'], u'test comment') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From b6577b42267ab4c4fc0112ef6720cbbe4cda470d Mon Sep 17 00:00:00 2001 From: Josh Brown Date: Mon, 26 Dec 2016 14:42:10 -0600 Subject: [PATCH 1523/2280] refactor long line for PEP8 --- beetsplug/zero.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index d3c3a697f..6a3013069 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -69,7 +69,9 @@ class ZeroPlugin(BeetsPlugin): zero_command = Subcommand('zero', help='set fields to null') def zero_fields(lib, opts, args): - if not decargs(args) and not input_yn(u"Remove fields for all items? (Y/n)", True): + if not decargs(args) and not input_yn( + u"Remove fields for all items? (Y/n)", + True): return for item in lib.items(decargs(args)): self.process_item(item) From b86187089b5db1d4f86e90fd49dcee3358737495 Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 26 Dec 2016 16:05:10 -0500 Subject: [PATCH 1524/2280] Update errors and logging of ABSubmit plugin A UserError is now raised if the plugin can be started. If an item fails to be analyzed or be submited an error is logged and the next item is tried. --- beetsplug/absubmit.py | 62 ++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index ec48aef04..a048f32ee 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -18,19 +18,7 @@ from beets import ui class ABSubmitError(Exception): - """Base exception for all excpetions this plugin can raise.""" - - -class FatalABSubmitError(ABSubmitError): - """Raised if the plugin is not able to start.""" - - -class AnalysisABSubmitError(ABSubmitError): - """Raised if analysis of file fails.""" - - -class SubmitABSubmitError(ABSubmitError): - """Raised if submitting data fails.""" + """Raised when failing to analyse file with extractor.""" def call(args): @@ -41,8 +29,8 @@ def call(args): try: return util.command_output(args) except subprocess.CalledProcessError as e: - raise AnalysisABSubmitError( - u"{0} exited with status {1}".format(args[0], e.returncode) + raise ABSubmitError( + u'{0} exited with status {1}'.format(args[0], e.returncode) ) @@ -58,8 +46,8 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): self.extractor = util.normpath(self.extractor) # Expicit path to extractor if not os.path.isfile(self.extractor): - raise FatalABSubmitError( - u'extractor command does not exist: {0}'. + raise ui.UserError( + u'Extractor command does not exist: {0}.'. format(self.extractor) ) else: @@ -69,11 +57,11 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): try: call([self.extractor]) except OSError: - raise FatalABSubmitError( - u'no extractor command found: install "{0}"'. - format(self.extractor) + raise ui.UserError( + u'No extractor command found: please install the ' + u'extractor binary from http://acousticbrainz.org/download' ) - except AnalysisABSubmitError: + except ABSubmitError: # Extractor found, will exit with an error if not called with # the correct amount of arguments. pass @@ -114,20 +102,27 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): mbid = item['mb_trackid'] # If file has no mbid skip it. if not mbid: - self._log.info('Not analysing {}, missing ' - 'musicbrainz track id.', item) + self._log.info(u'Not analysing {}, missing ' + u'musicbrainz track id.', item) return None # If file format is not supported skip it. if item['format'].lower() not in self.supported_formats: - self._log.info('Not analysing {}, file not in ' - 'supported format.', item) + self._log.info(u'Not analysing {}, file not in ' + u'supported format.', item) return None # Temporary file to save extractor output to. tmp_file, filename = tempfile.mkstemp(suffix='.json') try: # Close the file, so the extractor can overwrite it. - call([self.extractor, util.syspath(item.path), filename]) + try: + call([self.extractor, util.syspath(item.path), filename]) + except ABSubmitError as e: + self._log.error( + u'Failed to analyse {item} for AcousticBrainz: {error}', + item=item, error=e + ) + return None with open(filename) as tmp_file: analysis = json.loads(tmp_file.read()) # Add the hash to the output. @@ -151,11 +146,12 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): if response.status_code != 200: try: message = response.json()['message'] - except Exception as e: - message = 'unable to get error message: {}'.format(e) - raise ABSubmitError( - 'Failed to submit analysis: {message})'. - format(status_code=response.status_code, message=message) + except (ValueError, KeyError) as e: + message = u'unable to get error message: {}'.format(e) + self._log.error( + u'Failed to submit AcousticBrainz analysis of {item}: ' + u'{message}).', item=item, message=message ) - self._log.debug('Successfully submitted AcousticBrainz analysis ' - 'for {}.', item) + else: + self._log.debug(u'Successfully submitted AcousticBrainz analysis ' + u'for {}.', item) From c86b3097625e8f76ce7917b48242023b95424869 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 16:09:43 -0500 Subject: [PATCH 1525/2280] Changelog for #2322 (fix #2305) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2720ffe19..e18c624c7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,9 @@ Features: data source will fetch data for these fields when the next version of `python-musicbrainzngs`_ is released. Thanks to :user:`ibmibmibm`. :bug:`506` :bug:`507` :bug:`1547` :bug:`2333` +* :doc:`/plugins/random`: A new ``--time`` option lets you generate a random + playlist that takes a given amount of time. Thanks to :user:`diomekes`. + :bug:`2305` :bug:`2322` Fixes: From 3a650a151e2e0cdfd1bf5bf3d1083e4eae1ddd2f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 16:10:46 -0500 Subject: [PATCH 1526/2280] Docs fixes for #2322 --- docs/plugins/random.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/random.rst b/docs/plugins/random.rst index 8025eef4b..b0c437819 100644 --- a/docs/plugins/random.rst +++ b/docs/plugins/random.rst @@ -24,6 +24,6 @@ The ``-n NUMBER`` option controls the number of objects that are selected and printed (default 1). To select 5 tracks from your library, type ``beet random -n5``. -The ``-t MINUTES`` option controls the combined length of the objects that are -selected and printed. To select tracks that total one hour, tyoe ``beet random --t60`` +As an alternative, you can use ``-t MINUTES`` to choose a set of music with a +given play time. To select tracks that total one hour, for example, type +``beet random -t60``. From 146516704ffaef5e6e401fee91b70fd0df3dcbe3 Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 26 Dec 2016 16:09:45 -0500 Subject: [PATCH 1527/2280] Update comments for clarification --- beetsplug/absubmit.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index a048f32ee..804930b07 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -65,7 +65,8 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): # Extractor found, will exit with an error if not called with # the correct amount of arguments. pass - # Get the executable needed to calculate the sha1 hash. + # Get the executable location on the system, + # needed to calculate the sha1 hash. self.extractor = distutils.spawn.find_executable(self.extractor) # Calculate extractor hash. @@ -91,8 +92,6 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): def command(self, lib, opts, args): # Get items from arguments items = lib.items(ui.decargs(args)) - # Get no_submit option. - # TODO get a should submit option from the command line. for item in items: analysis = self._get_analysis(item) if analysis: @@ -111,7 +110,10 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): u'supported format.', item) return None - # Temporary file to save extractor output to. + # Temporary file to save extractor output to, extractor only works + # if an output file is given. Here we use a temporary file to copy + # the data into a python object and then remove the file from the + # system. tmp_file, filename = tempfile.mkstemp(suffix='.json') try: # Close the file, so the extractor can overwrite it. From 4c2457d6cea6e8530d971aef80d36952c1ea3d9e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 16:27:31 -0500 Subject: [PATCH 1528/2280] Refactor `random` plugin a bit Separate the callback function from the random selection logic. --- beetsplug/random.py | 58 +++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index d719b5910..06c17a4e3 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -24,25 +24,26 @@ from operator import attrgetter from itertools import groupby -def random_item(lib, opts, args): - query = decargs(args) +def random_objs(objs, album, number=1, time=None, equal_chance=False): + """Get a random subset of the provided `objs`. - if opts.album: - objs = list(lib.albums(query)) - else: - objs = list(lib.items(query)) - - if opts.time: + If `number` is provided, produce that many matches. Otherwise, if + `time` is provided, instead select a list whose total time is close + to that number of minutes. If `equal_chance` is true, give each + artist an equal chance of being included so that artists with more + songs are not represented disproportionately. + """ + if time: total_time = 0.0 - time_sec = (opts.time * 60) + time_sec = (time * 60) objs_shuffled = objs random.shuffle(objs_shuffled) - if not opts.equal_chance: + if not equal_chance: objs = [] for item in objs_shuffled: - if opts.album: + if album: item.length = sum(a.length for a in item.items()) if (total_time + item.length) <= time_sec: objs.append(item) @@ -51,7 +52,7 @@ def random_item(lib, opts, args): else: pass - if opts.equal_chance: + if equal_chance: # Group the objects by artist so we can sample from them. key = attrgetter('albumartist') objs.sort(key=key) @@ -60,12 +61,12 @@ def random_item(lib, opts, args): objs_by_artists[artist] = list(v) objs = [] - if opts.time: + if time: for item in objs_shuffled: if not objs_by_artists: break - if opts.album: + if album: item.length = sum(a.length for a in item.items()) if (total_time + item.length) <= time_sec: artist = random.choice(list(objs_by_artists.keys())) @@ -81,7 +82,7 @@ def random_item(lib, opts, args): pass else: - for _ in range(opts.number): + for _ in range(number): # Terminate early if we're out of objects to select. if not objs_by_artists: break @@ -97,12 +98,29 @@ def random_item(lib, opts, args): if not objs_from_artist: del objs_by_artists[artist] - elif not opts.time: - number = min(len(objs), opts.number) + elif not time: + number = min(len(objs), number) objs = random.sample(objs, number) - for item in objs: - print_(format(item)) + return objs + + +def random_func(lib, opts, args): + """Select some random items or albums and print the results. + """ + # Fetch all the objects matching the query into a list. + query = decargs(args) + if opts.album: + objs = list(lib.albums(query)) + else: + objs = list(lib.items(query)) + + # Print a random subset. + objs = random_objs(objs, opts.album, opts.number, opts.time, + opts.equal_chance) + for obj in objs: + print_(format(obj)) + random_cmd = Subcommand('random', help=u'choose a random track or album') @@ -116,7 +134,7 @@ random_cmd.parser.add_option( u'-t', u'--time', action='store', type="float", help=u'total length in minutes of objects to choose') random_cmd.parser.add_all_common_options() -random_cmd.func = random_item +random_cmd.func = random_func class Random(BeetsPlugin): From 5bbf16c2b1f56bda6adf767367d63eb91377d533 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 16:32:03 -0500 Subject: [PATCH 1529/2280] Refactor length calculation (#2322) Also, avoid setting an unnecessary field on the album objects. :/ --- beetsplug/random.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index 06c17a4e3..c8e1f3fd4 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -24,6 +24,15 @@ from operator import attrgetter from itertools import groupby +def _length(obj, album): + """Get the duration of an item or album. + """ + if album: + return sum(i.length for i in obj.items()) + else: + return obj.length + + def random_objs(objs, album, number=1, time=None, equal_chance=False): """Get a random subset of the provided `objs`. @@ -42,12 +51,11 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): if not equal_chance: objs = [] - for item in objs_shuffled: - if album: - item.length = sum(a.length for a in item.items()) - if (total_time + item.length) <= time_sec: - objs.append(item) - total_time += item.length + for obj in objs_shuffled: + length = _length(obj, album) + if (total_time + length) <= time_sec: + objs.append(obj) + total_time += length else: pass @@ -62,18 +70,17 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): objs = [] if time: - for item in objs_shuffled: + for obj in objs_shuffled: if not objs_by_artists: break - if album: - item.length = sum(a.length for a in item.items()) - if (total_time + item.length) <= time_sec: + length = _length(obj, album) + if (total_time + length) <= time_sec: artist = random.choice(list(objs_by_artists.keys())) objs_from_artist = objs_by_artists[artist] i = random.randint(0, len(objs_from_artist) - 1) objs.append(objs_from_artist.pop(i)) - total_time += item.length + total_time += length if not objs_from_artist: del objs_by_artists[artist] From d053f98e81f710d091adf436d4cb8235b13e1834 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 16:43:47 -0500 Subject: [PATCH 1530/2280] random: Refactor equal chance logic --- beetsplug/random.py | 64 +++++++++++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index c8e1f3fd4..5e7b038d7 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -33,6 +33,46 @@ def _length(obj, album): return obj.length +def _equal_chance_permutation(objs, field='albumartist'): + """Generate (lazily) a permutation of the objects where every group + with equal values for `field` have an equal chance of appearing in + any given position. + """ + # Group the objects by artist so we can sample from them. + key = attrgetter(field) + objs.sort(key=key) + objs_by_artists = {} + for artist, v in groupby(objs, key): + objs_by_artists[artist] = list(v) + + # While we still have artists with music to choose from, pick one + # randomly and pick a track from that artist. + while objs_by_artists: + # Choose an artist and an object for that artist, removing + # this choice from the pool. + artist = random.choice(list(objs_by_artists.keys())) + objs_from_artist = objs_by_artists[artist] + i = random.randint(0, len(objs_from_artist) - 1) + yield objs_from_artist.pop(i) + + # Remove the artist if we've used up all of its objects. + if not objs_from_artist: + del objs_by_artists[artist] + + +def _take(iter, num): + """Return a list containing the first `num` values in `iter` (or + fewer, if the iterable ends early). + """ + out = [] + for val in iter: + out.append(val) + num -= 1 + if num <= 0: + break + return out + + def random_objs(objs, album, number=1, time=None, equal_chance=False): """Get a random subset of the provided `objs`. @@ -44,7 +84,7 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): """ if time: total_time = 0.0 - time_sec = (time * 60) + time_sec = time * 60 objs_shuffled = objs random.shuffle(objs_shuffled) @@ -61,13 +101,6 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): pass if equal_chance: - # Group the objects by artist so we can sample from them. - key = attrgetter('albumartist') - objs.sort(key=key) - objs_by_artists = {} - for artist, v in groupby(objs, key): - objs_by_artists[artist] = list(v) - objs = [] if time: for obj in objs_shuffled: @@ -89,21 +122,8 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): pass else: - for _ in range(number): - # Terminate early if we're out of objects to select. - if not objs_by_artists: - break + return _take(_equal_chance_permutation(objs), number) - # Choose an artist and an object for that artist, removing - # this choice from the pool. - artist = random.choice(list(objs_by_artists.keys())) - objs_from_artist = objs_by_artists[artist] - i = random.randint(0, len(objs_from_artist) - 1) - objs.append(objs_from_artist.pop(i)) - - # Remove the artist if we've used up all of its objects. - if not objs_from_artist: - del objs_by_artists[artist] elif not time: number = min(len(objs), number) From 90ea8425cfae6cf9b50589e7f2b06589b9bed7e4 Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 26 Dec 2016 16:50:51 -0500 Subject: [PATCH 1531/2280] Add documentation for the absubmit plugin --- docs/plugins/absubmit.rst | 31 +++++++++++++++++++++++++++++++ docs/plugins/index.rst | 3 +++ 2 files changed, 34 insertions(+) create mode 100644 docs/plugins/absubmit.rst diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst new file mode 100644 index 000000000..5c9e6025e --- /dev/null +++ b/docs/plugins/absubmit.rst @@ -0,0 +1,31 @@ +AcousticBrainz Submit Plugin +============================ + +The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyse an audio file and calculate different acoustic properties of the audio, the plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration options is set to ``yes``. + +Installation +------------ + +The `absubmit` plugin requires the the `streaming_extractor_music`_ program to run. Its source can be found on `github`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used thier binary (see the AcousticBrainz `FAQ`_). + +The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing: + + pip install requests + +After installing both the extractor binary and request you can enable the plgin ``absubmit`` in your configuration (see :ref:`using-plugins`). + +Configuration +------------- + +To configute the plugin, make a ``absubmit:`` section in your configuration file. The available options are: + +- **auto**: Analyze every file on import. Otherwise, you need to use the ``beet absubmit`` command explicitly. + Default: ``no`` +- **extractor**: The path to the `streaming_extractor_music`_ binary. + Default: search for the program in your ``$PATH`` + +.. _streaming_extractor_music: http://acousticbrainz.org/download +.. _FAQ: http://acousticbrainz.org/faq +.. _pip: http://www.pip-installer.org/ +.. _requests: http://docs.python-requests.org/en/master/ +.. _github: https://github.com/MTG/essentia diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index e0f9521e2..0e851d7da 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -38,6 +38,7 @@ like this:: .. toctree:: :hidden: + absubmit acousticbrainz badfiles beatport @@ -105,6 +106,7 @@ Autotagger Extensions Metadata -------- +* :doc:`absubmit`: Analyse audio with the `streaming_extractor_music`_ program and submit the metadata to the AcousticBrainz server * :doc:`acousticbrainz`: Fetch various AcousticBrainz metadata * :doc:`bpm`: Measure tempo using keystrokes. * :doc:`edit`: Edit metadata from a text editor. @@ -128,6 +130,7 @@ Metadata * :doc:`zero`: Nullify fields by pattern or unconditionally. .. _KeyFinder: http://www.ibrahimshaath.co.uk/keyfinder/ +.. _streaming_extractor_music: http://acousticbrainz.org/download Path Formats ------------ From d0dd0b2a058b1ff44dfc1d7c9661b63bd6ebe997 Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 26 Dec 2016 16:51:14 -0500 Subject: [PATCH 1532/2280] Add absubmit plugins dependencies to the extras_require field --- setup.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 7a7dbe83e..f88fe28b6 100755 --- a/setup.py +++ b/setup.py @@ -111,6 +111,7 @@ setup( # Plugin (optional) dependencies: extras_require={ + 'absubmit': ['requests'], 'fetchart': ['requests'], 'chroma': ['pyacoustid'], 'discogs': ['discogs-client>=2.1.0'], @@ -126,6 +127,7 @@ setup( # Non-Python/non-PyPI plugin dependencies: # convert: ffmpeg # bpd: python-gi and GStreamer + # absubmit: extractor binary from http://acousticbrainz.org/download classifiers=[ 'Topic :: Multimedia :: Sound/Audio', From 33eb4ff91baac58939152948f520fa68a601c2bb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 17:01:02 -0500 Subject: [PATCH 1533/2280] Refactor time-based selection (#2322) --- beetsplug/random.py | 47 ++++++++++++++++----------------------------- 1 file changed, 17 insertions(+), 30 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index 5e7b038d7..8222339a6 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -73,6 +73,21 @@ def _take(iter, num): return out +def _take_time(iter, secs, album): + """Return a list containing the first values in `iter`, which should + be Item or Album objects, that add up to the given amount of time in + seconds. + """ + out = [] + total_time = 0.0 + for obj in iter: + length = _length(obj, album) + if total_time + length <= secs: + out.append(obj) + total_time += length + return out + + def random_objs(objs, album, number=1, time=None, equal_chance=False): """Get a random subset of the provided `objs`. @@ -83,48 +98,20 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): songs are not represented disproportionately. """ if time: - total_time = 0.0 time_sec = time * 60 objs_shuffled = objs random.shuffle(objs_shuffled) if not equal_chance: - objs = [] - - for obj in objs_shuffled: - length = _length(obj, album) - if (total_time + length) <= time_sec: - objs.append(obj) - total_time += length - - else: - pass + return _take_time(objs_shuffled, time_sec, album) if equal_chance: - if time: - for obj in objs_shuffled: - if not objs_by_artists: - break - - length = _length(obj, album) - if (total_time + length) <= time_sec: - artist = random.choice(list(objs_by_artists.keys())) - objs_from_artist = objs_by_artists[artist] - i = random.randint(0, len(objs_from_artist) - 1) - objs.append(objs_from_artist.pop(i)) - total_time += length - - if not objs_from_artist: - del objs_by_artists[artist] - - else: - pass + return _take_time(_equal_chance_permutation(objs), time_sec, album) else: return _take(_equal_chance_permutation(objs), number) - elif not time: number = min(len(objs), number) objs = random.sample(objs, number) From 641e62f2e0cea6bc2fbb154e57a27514c368d8b6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 17:04:21 -0500 Subject: [PATCH 1534/2280] Vastly simplify main random function This is the payoff from the earlier refactorings: the control flow is now consistent and clear, and the two factors (time vs. number, equal-chance or not) are orthogonal. See also #2322. --- beetsplug/random.py | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/beetsplug/random.py b/beetsplug/random.py index 8222339a6..65caaf908 100644 --- a/beetsplug/random.py +++ b/beetsplug/random.py @@ -97,26 +97,19 @@ def random_objs(objs, album, number=1, time=None, equal_chance=False): artist an equal chance of being included so that artists with more songs are not represented disproportionately. """ - if time: - time_sec = time * 60 - objs_shuffled = objs - random.shuffle(objs_shuffled) - - if not equal_chance: - return _take_time(objs_shuffled, time_sec, album) - + # Permute the objects either in a straightforward way or an + # artist-balanced way. if equal_chance: - if time: - return _take_time(_equal_chance_permutation(objs), time_sec, album) + perm = _equal_chance_permutation(objs) + else: + perm = objs + random.shuffle(perm) # N.B. This shuffles the original list. - else: - return _take(_equal_chance_permutation(objs), number) - - elif not time: - number = min(len(objs), number) - objs = random.sample(objs, number) - - return objs + # Select objects by time our count. + if time: + return _take_time(perm, time * 60, album) + else: + return _take(perm, number) def random_func(lib, opts, args): From a9fd3df6810526055654ab4336fc1bac0ac66f82 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 17:33:23 -0500 Subject: [PATCH 1535/2280] Docs fixes for #2329 --- docs/changelog.rst | 6 ++---- docs/plugins/zero.rst | 7 ++++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index bce5e86d2..43c651200 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,15 +13,13 @@ Features: * :doc:`/plugins/random`: A new ``--time`` option lets you generate a random playlist that takes a given amount of time. Thanks to :user:`diomekes`. :bug:`2305` :bug:`2322` +* :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero + plugin. Thanks to :user:`SJoshBrown`. :bug:`2274` :bug:`2329` Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` -Features: - -* :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero - plugin. 1.4.2 (December 16, 2016) ------------------------- diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 282bb4fc8..20e1fa171 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -18,7 +18,8 @@ Configuration Make a ``zero:`` section in your configuration file. You can specify the fields to nullify and the conditions for nullifying them: -* Set ``auto`` to ``yes`` to null fields automatically on import. Default ``yes`` +* Set ``auto`` to ``yes`` to null fields automatically on import. + Default: ``yes``. * Set ``fields`` to a whitespace-separated list of fields to change. You can get the list of all available fields by running ``beet fields``. In addition, the ``images`` field allows you to remove any images @@ -47,5 +48,5 @@ Note that the plugin currently does not zero fields when importing "as-is". Manually Triggering Zero ------------------------ -The ``zero`` command will invoke the zero plugin on items matching a query. Use the -command ``beet zero [QUERY]`` +You can also type ``beet zero [QUERY]`` to manually invoke the plugin on music +in your library. From 84082641427b88ba353bc2b022067d20fe2b9a12 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 26 Dec 2016 17:41:44 -0500 Subject: [PATCH 1536/2280] Update test file for new set of tags The new MediaFile tags in #2333 mean that the `test_unicode_path` test will write new tags to this test fixture file. --- test/rsrc/unicode’d.mp3 | Bin 12820 -> 12820 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/test/rsrc/unicode’d.mp3 b/test/rsrc/unicode’d.mp3 index 7be1e05186ffc38ed3f61c3d5bd56f5b8f37b151..663f43910b83fd13227fc0abcbbab1e87576cdaa 100644 GIT binary patch delta 192 zcmbP|G9_g~$K*YX(#kIWK@1EGYzz#{1_lNO3?ZHYJ`4;D+zbrNiA6<;dFiP|43p!T z#KoNbeHj=S_!tkiOV11`%?ogM z3}7%|UC#f`7A+e|= kv$$mPf2NShrA)4qgPC0??_zSBxTIpT8Drb#P0UGp0PFlT0ssI2 delta 186 zcmbP|G9_g~$K*&xnaNw2DufvX7#J8*^U^azO7jBT9RnB)7$&PS_ezF11^6;BFfcPP zFq<)iIQs@bIffH&OYyn*2Qe@(urV+&8yFZEOy*{knz%{K-800Hfq{XKfq}UsBUK^2 zD8IBIGcTPXB*4{(fq_8?DxR2=RGO=hSX7c(T*43%5bDIhz`zZa%SlX1&6)g|(QR@b YliTEpjKPyNnOrB^GfHjV#GIrD03GWt5&!@I From f93ee3accc6673674cfc98d2a1e09afb119d3eea Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Mon, 26 Dec 2016 23:47:10 +0100 Subject: [PATCH 1537/2280] First hack of ignoring already tagged items --- beetsplug/acousticbrainz.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 138fd8809..9985ade87 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -155,6 +155,12 @@ class AcousticPlugin(plugins.BeetsPlugin): """Fetch additional information from AcousticBrainz for the `item`s. """ for item in items: + + mood_str = item.get('mood_acoustic', u'') + if len(mood_str) != 0: + self._log.info(u'Already set acousticbrainz tag for {} ', item) + continue + if not item.mb_trackid: continue From 767798ca0748e6cf9aabe07312647efbcc879ba5 Mon Sep 17 00:00:00 2001 From: Ben Petty Date: Mon, 26 Dec 2016 20:27:35 -0800 Subject: [PATCH 1538/2280] typo in docs --- docs/plugins/spotify.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/spotify.rst b/docs/plugins/spotify.rst index 2295c70b4..b993a66d2 100644 --- a/docs/plugins/spotify.rst +++ b/docs/plugins/spotify.rst @@ -73,7 +73,7 @@ Here's an example:: spotify: mode: open region_filter: US - show_faiulres: on + show_failures: on tiebreak: first regex: [ From bbaad2f17dedf3394065f9bea3eb30fc85df2fae Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Tue, 27 Dec 2016 13:22:16 +0100 Subject: [PATCH 1539/2280] Introduce force option in acousticbrainz --- beetsplug/acousticbrainz.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 9985ade87..9f5232953 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -107,7 +107,8 @@ class AcousticPlugin(plugins.BeetsPlugin): def __init__(self): super(AcousticPlugin, self).__init__() - self.config.add({'auto': True}) + self.config.add({'auto': True,'force': False}) + if self.config['auto']: self.register_listener('import_task_files', self.import_task_files) @@ -118,7 +119,13 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - self._fetch_info(items, ui.should_write()) + self._fetch_info(items, ui.should_write(),opts.force_refetch or self.config['force']) + + cmd.parser.add_option( + u'-f', u'--force', dest='force_refetch', + action='store_true', default=False, + help=u'always fetch acousticbrainz data', + ) cmd.func = func return [cmd] @@ -151,15 +158,16 @@ class AcousticPlugin(plugins.BeetsPlugin): return data - def _fetch_info(self, items, write): + def _fetch_info(self, items, write, force): """Fetch additional information from AcousticBrainz for the `item`s. """ for item in items: - mood_str = item.get('mood_acoustic', u'') - if len(mood_str) != 0: - self._log.info(u'Already set acousticbrainz tag for {} ', item) - continue + if not force: + mood_str = item.get('mood_acoustic', u'') + if len(mood_str) != 0: + self._log.info(u'Already set acousticbrainz tag for {} ', item) + continue if not item.mb_trackid: continue From 8e29a3ffcb3b36fe2baf7ee80c233c9af18a953f Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Tue, 27 Dec 2016 18:46:46 +0100 Subject: [PATCH 1540/2280] Zero: Last minute unimportant fixes: *Remove the artifact of a debug log. *Remove meaningless version number. *Rephrase some docstrings. *Remove tautological comments. --- beetsplug/zero.py | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/beetsplug/zero.py b/beetsplug/zero.py index 6a3013069..022c2c721 100644 --- a/beetsplug/zero.py +++ b/beetsplug/zero.py @@ -27,14 +27,12 @@ from beets.ui import Subcommand, decargs, input_yn from beets.util import confit __author__ = 'baobab@heresiarch.info' -__version__ = '0.10' class ZeroPlugin(BeetsPlugin): def __init__(self): super(ZeroPlugin, self).__init__() - # Listeners. self.register_listener('write', self.write_event) self.register_listener('import_task_choice', self.import_task_choice_event) @@ -49,6 +47,13 @@ class ZeroPlugin(BeetsPlugin): self.fields_to_progs = {} self.warned = False + """Read the bulk of the config into `self.fields_to_progs`. + After construction, `fields_to_progs` contains all the fields that + should be zeroed as keys and maps each of those to a list of compiled + regexes (progs) as values. + A field is zeroed if its value matches one of the associated progs. If + progs is empty, then the associated field is always zeroed. + """ if self.config['fields'] and self.config['keep_fields']: self._log.warning( u'cannot blacklist and whitelist at the same time' @@ -80,9 +85,8 @@ class ZeroPlugin(BeetsPlugin): return [zero_command] def _set_pattern(self, field): - """Set a field in `self.patterns` to a string list corresponding to - the configuration, or `True` if the field has no specific - configuration. + """Populate `self.fields_to_progs` for a given field. + Do some sanity checks then compile the regexes. """ if field not in MediaFile.fields(): self._log.error(u'invalid field: {0}', field) @@ -99,20 +103,22 @@ class ZeroPlugin(BeetsPlugin): self.fields_to_progs[field] = [] def import_task_choice_event(self, session, task): - """Listen for import_task_choice event.""" if task.choice_flag == action.ASIS and not self.warned: self._log.warning(u'cannot zero in \"as-is\" mode') self.warned = True # TODO request write in as-is mode def write_event(self, item, path, tags): - """Set values in tags to `None` if the key and value are matched - by `self.patterns`. - """ if self.config['auto']: self.set_fields(item, tags) def set_fields(self, item, tags): + """Set values in `tags` to `None` if the field is in + `self.fields_to_progs` and any of the corresponding `progs` matches the + field value. + Also update the `item` itself if `update_database` is set in the + config. + """ fields_set = False if not self.fields_to_progs: @@ -122,7 +128,7 @@ class ZeroPlugin(BeetsPlugin): for field, progs in self.fields_to_progs.items(): if field in tags: value = tags[field] - match = _match_progs(tags[field], progs, self._log) + match = _match_progs(tags[field], progs) else: value = '' match = not progs @@ -145,9 +151,9 @@ class ZeroPlugin(BeetsPlugin): item.store(fields=tags) -def _match_progs(value, progs, log): - """Check if field (as string) is matching any of the patterns in - the list. +def _match_progs(value, progs): + """Check if `value` (as string) is matching any of the compiled regexes in + the `progs` list. """ if not progs: return True From c632949b648b90b044aa58089a43bfd39f3d6170 Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Tue, 27 Dec 2016 21:48:06 +0100 Subject: [PATCH 1541/2280] Changes suggested by @Kraymer --- beetsplug/acousticbrainz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 9f5232953..09078402f 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -119,7 +119,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - self._fetch_info(items, ui.should_write(),opts.force_refetch or self.config['force']) + self._fetch_info(items, ui.should_write(), opts.force_refetch or self.config['force']) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', @@ -165,8 +165,8 @@ class AcousticPlugin(plugins.BeetsPlugin): if not force: mood_str = item.get('mood_acoustic', u'') - if len(mood_str) != 0: - self._log.info(u'Already set acousticbrainz tag for {} ', item) + if mood_str: + self._log.info(u'Already set acousticbrainz tags for {} ', item) continue if not item.mb_trackid: From 00371de0bb739cd2f632e57525cbff0db6ea5008 Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Tue, 27 Dec 2016 21:56:39 +0100 Subject: [PATCH 1542/2280] Changes suggested by @sampsyo --- beetsplug/acousticbrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 09078402f..5fc60634d 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -124,7 +124,7 @@ class AcousticPlugin(plugins.BeetsPlugin): cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, - help=u'always fetch acousticbrainz data', + help=u're-download data when already present' ) cmd.func = func From 8be0a271b599aa0151f0074d36fb904982735b12 Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Tue, 27 Dec 2016 22:11:27 +0100 Subject: [PATCH 1543/2280] Add documentation for the force-option --- docs/plugins/acousticbrainz.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index b66bf17de..5d72b8517 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -8,7 +8,12 @@ The ``acousticbrainz`` plugin gets acoustic-analysis information from the Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plugins`) and run it by typing:: - $ beet acousticbrainz [QUERY] + $ beet acousticbrainz [-f] [QUERY] + +By default, the command will only look for acousticbrainz data when the tracks doesn't +already have it; the ``-f`` or ``--force`` switch makes it fetch acousticbrainz +for the item. If you specify a query, only matching tracks will be processed; +otherwise, the command processes every track in your library. For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: @@ -52,3 +57,6 @@ configuration file. There is one option: - **auto**: Enable AcousticBrainz during ``beet import``. Default: ``yes``. +- **force**: By default, beets will not override already fetched acousticbrainz data. To instead fetch acousticbrainz and override data, + set the ``force`` option to ``yes``. + Default: ``no``. \ No newline at end of file From 165f2e189ea93c4391b48df710af6ae812e850d4 Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Wed, 28 Dec 2016 15:11:03 +0100 Subject: [PATCH 1544/2280] Repair findings from Travis CI --- beetsplug/acousticbrainz.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 5fc60634d..3dea02fd2 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -107,7 +107,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def __init__(self): super(AcousticPlugin, self).__init__() - self.config.add({'auto': True,'force': False}) + self.config.add({'auto': True, 'force': False}) if self.config['auto']: self.register_listener('import_task_files', @@ -119,8 +119,8 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - self._fetch_info(items, ui.should_write(), opts.force_refetch or self.config['force']) - + self._fetch_info(items, ui.should_write(), + opts.force_refetch or self.config['force']) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, @@ -162,11 +162,11 @@ class AcousticPlugin(plugins.BeetsPlugin): """Fetch additional information from AcousticBrainz for the `item`s. """ for item in items: - if not force: mood_str = item.get('mood_acoustic', u'') if mood_str: - self._log.info(u'Already set acousticbrainz tags for {} ', item) + self._log.info(u'Already set acoustic\ + brainz tags for {} ', item) continue if not item.mb_trackid: From 7e1e31bdddea3d30c3a61c0514298bfb1fdbbe6c Mon Sep 17 00:00:00 2001 From: Susanna Maria Hepp Date: Wed, 28 Dec 2016 15:30:57 +0100 Subject: [PATCH 1545/2280] E128: continuation line under-indented for visual indent? --- beetsplug/acousticbrainz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 3dea02fd2..725c55089 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -119,8 +119,8 @@ class AcousticPlugin(plugins.BeetsPlugin): def func(lib, opts, args): items = lib.items(ui.decargs(args)) - self._fetch_info(items, ui.should_write(), - opts.force_refetch or self.config['force']) + self._fetch_info(items, ui.should_write(), + opts.force_refetch or self.config['force']) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, From c27879edbc5d5a3dacc09fc7f853a29cbcd8dacc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 11:59:14 -0500 Subject: [PATCH 1546/2280] Slight code formatting tweaks for #2349 --- beetsplug/acousticbrainz.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 725c55089..93647170b 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -107,7 +107,10 @@ class AcousticPlugin(plugins.BeetsPlugin): def __init__(self): super(AcousticPlugin, self).__init__() - self.config.add({'auto': True, 'force': False}) + self.config.add({ + 'auto': True, + 'force': False, + }) if self.config['auto']: self.register_listener('import_task_files', @@ -116,17 +119,17 @@ class AcousticPlugin(plugins.BeetsPlugin): def commands(self): cmd = ui.Subcommand('acousticbrainz', help=u"fetch metadata from AcousticBrainz") - - def func(lib, opts, args): - items = lib.items(ui.decargs(args)) - self._fetch_info(items, ui.should_write(), - opts.force_refetch or self.config['force']) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, help=u're-download data when already present' ) + def func(lib, opts, args): + items = lib.items(ui.decargs(args)) + self._fetch_info(items, ui.should_write(), + opts.force_refetch or self.config['force']) + cmd.func = func return [cmd] @@ -162,13 +165,17 @@ class AcousticPlugin(plugins.BeetsPlugin): """Fetch additional information from AcousticBrainz for the `item`s. """ for item in items: + # If we're not forcing re-downloading for all tracks, check + # whether the data is already present. We use one + # representative field name to check for previously fetched + # data. if not force: mood_str = item.get('mood_acoustic', u'') if mood_str: - self._log.info(u'Already set acoustic\ - brainz tags for {} ', item) + self._log.info(u'data already present for: {}', item) continue + # We can only fetch data for tracks with MBIDs. if not item.mb_trackid: continue From 2a3f3d9bfa9015dbddc838342d4c6f091d7d7d92 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 12:01:08 -0500 Subject: [PATCH 1547/2280] acousticbrainz: Make some strings into comments When not in the docstring position, it's better to use "real" comments instead of string literals. --- beetsplug/acousticbrainz.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 93647170b..2e99637b3 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -212,7 +212,8 @@ class AcousticPlugin(plugins.BeetsPlugin): joined with `' '`. This is hardcoded and not very flexible, but it gets the job done. - Example: + For example: + >>> scheme = { 'key1': 'attribute', 'key group': { @@ -234,24 +235,24 @@ class AcousticPlugin(plugins.BeetsPlugin): ('attribute', 'value'), ('composite attribute', 'part 1 of composite attr part 2')] """ - """First, we traverse `scheme` and `data`, `yield`ing all the non - composites attributes straight away and populating the dictionary - `composites` with the composite attributes. + # First, we traverse `scheme` and `data`, `yield`ing all the non + # composites attributes straight away and populating the dictionary + # `composites` with the composite attributes. - When we are finished traversing `scheme`, `composites` should map - each composite attribute to an ordered list of the values belonging to - the attribute, for example: - `composites = {'initial_key': ['B', 'minor']}`. - """ + # When we are finished traversing `scheme`, `composites` should map + # each composite attribute to an ordered list of the values belonging to + # the attribute, for example: + # `composites = {'initial_key': ['B', 'minor']}`. + + # The recursive traversal. composites = defaultdict(list) - # The recursive traversal for attr, val in self._data_to_scheme_child(data, scheme, composites): yield attr, val - """When composites has been populated, yield the composite attributes - by joining their parts. - """ + + # When composites has been populated, yield the composite attributes + # by joining their parts. for composite_attr, value_parts in composites.items(): yield composite_attr, ' '.join(value_parts) From 8a62087376ce27cbb694298599ec4f76b4cf9d3e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 12:03:57 -0500 Subject: [PATCH 1548/2280] Documentation tweaks for #2349 --- beetsplug/acousticbrainz.py | 6 +++--- docs/plugins/acousticbrainz.rst | 15 ++++++++------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 2e99637b3..a323ce681 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -239,9 +239,9 @@ class AcousticPlugin(plugins.BeetsPlugin): # composites attributes straight away and populating the dictionary # `composites` with the composite attributes. - # When we are finished traversing `scheme`, `composites` should map - # each composite attribute to an ordered list of the values belonging to - # the attribute, for example: + # When we are finished traversing `scheme`, `composites` should + # map each composite attribute to an ordered list of the values + # belonging to the attribute, for example: # `composites = {'initial_key': ['B', 'minor']}`. # The recursive traversal. diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index 5d72b8517..de4c667c0 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -10,10 +10,11 @@ Enable the ``acousticbrainz`` plugin in your configuration (see :ref:`using-plug $ beet acousticbrainz [-f] [QUERY] -By default, the command will only look for acousticbrainz data when the tracks doesn't -already have it; the ``-f`` or ``--force`` switch makes it fetch acousticbrainz -for the item. If you specify a query, only matching tracks will be processed; -otherwise, the command processes every track in your library. +By default, the command will only look for AcousticBrainz data when the tracks +doesn't already have it; the ``-f`` or ``--force`` switch makes it re-download +data even when it already exists. If you specify a query, only matching tracks +will be processed; otherwise, the command processes every track in your +library. For all tracks with a MusicBrainz recording ID, the plugin currently sets these fields: @@ -57,6 +58,6 @@ configuration file. There is one option: - **auto**: Enable AcousticBrainz during ``beet import``. Default: ``yes``. -- **force**: By default, beets will not override already fetched acousticbrainz data. To instead fetch acousticbrainz and override data, - set the ``force`` option to ``yes``. - Default: ``no``. \ No newline at end of file +- **force**: Download AcousticBrainz data even for tracks that already have + it. + Default: ``no``. From d447d3e6552780759944910a7c653bfe6f63333c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 12:06:29 -0500 Subject: [PATCH 1549/2280] Changelog note for #2349 (fix #2347) --- docs/changelog.rst | 4 ++++ docs/plugins/acousticbrainz.rst | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 43c651200..f3124271c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,10 @@ Features: :bug:`2305` :bug:`2322` * :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero plugin. Thanks to :user:`SJoshBrown`. :bug:`2274` :bug:`2329` +* :doc:`/plugins/acousticbrainz`: The plugin will avoid re-downloading data + for files that already have it by default. You can override this behavior + using a new ``force`` option. Thanks to :user:`SusannaMaria`. :bug:`2347` + :bug:`2349` Fixes: diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index de4c667c0..bf2102790 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -46,7 +46,7 @@ Automatic Tagging ----------------- To automatically tag files using AcousticBrainz data during import, just -enable the ``acousticbrainz`` plugin (see :ref:`using-plugins`). When importing +enable the ``acousticbrainz`` plugin (see :ref:`using-plugins`). When importing new files, beets will query the AcousticBrainz API using MBID and set the appropriate metadata. From 9b0a867c73da102f4e620bbf4faef31be2c018a7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 12:40:33 -0500 Subject: [PATCH 1550/2280] Expand some comments in choose_match --- beets/ui/commands.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 8ead3bfad..b9a3e0b91 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -728,27 +728,35 @@ class TerminalImportSession(importer.ImportSession): # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: - # Gather extra choices from plugins. + # Gather additional menu choices from plugins. We build a + # map from selection characters to callback functions. extra_choices = self._get_plugin_choices(task) extra_ops = {c.short: c.callback for c in extra_choices} - # Ask for a choice from the user. + # Ask for a choice from the user. The result of + # `choose_candidate` may be an `importer.action` flag or an + # `AlbumMatch` object for a specific selection. choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, itemcount=len(task.items), extra_choices=extra_choices ) - # Choose which tags to use. + # Basic choices that require no more action here. if choice in (importer.action.SKIP, importer.action.ASIS, importer.action.TRACKS, importer.action.ALBUMS): # Pass selection to main control flow. return choice + + # Manual search. We ask for the search terms and run the + # loop again. elif choice is importer.action.MANUAL: # Try again with manual search terms. search_artist, search_album = manual_search(False) _, _, candidates, rec = autotag.tag_album( task.items, search_artist, search_album ) + + # Manual ID. We prompt for the ID and run the loop again. elif choice is importer.action.MANUAL_ID: # Try a manually-entered ID. search_id = manual_id(False) @@ -756,12 +764,16 @@ class TerminalImportSession(importer.ImportSession): _, _, candidates, rec = autotag.tag_album( task.items, search_ids=search_id.split() ) + + # Plugin-provided choices. We invoke the associated callback + # function. elif choice in list(extra_ops.keys()): - # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) if isinstance(post_choice, importer.action): # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice + + # Otherwise, we have a specific match selection. else: # We have a candidate! Finish tagging. Here, choice is an # AlbumMatch object. From 3578f0d429d9a3203cd37cdff55312db85e3e433 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 13:21:55 -0500 Subject: [PATCH 1551/2280] Introduce a new Proposal type for tag results tag_album and tag_item now return a Proposal. The idea is that plugin actions should also be able to return Proposal values, just like the built-in actions. --- beets/autotag/match.py | 32 ++++++++++++++++++++------------ beets/importer.py | 13 ++++++------- beets/ui/commands.py | 24 ++++++++++++++++++------ 3 files changed, 44 insertions(+), 25 deletions(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 493fd20c9..71d80e821 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -22,6 +22,7 @@ from __future__ import division, absolute_import, print_function import datetime import re from munkres import Munkres +from collections import namedtuple from beets import logging from beets import plugins @@ -52,6 +53,13 @@ class Recommendation(OrderedEnum): strong = 3 +# A structure for holding a set of possible matches to choose between. This +# consists of a list of possible candidates (i.e., AlbumInfo or TrackInfo +# objects) and a recommendation value. + +Proposal = namedtuple('Proposal', ('candidates', 'recommendation')) + + # Primary matching functionality. def current_metadata(items): @@ -379,9 +387,8 @@ def _add_candidate(items, results, info): def tag_album(items, search_artist=None, search_album=None, search_ids=[]): - """Return a tuple of a artist name, an album name, a list of - `AlbumMatch` candidates from the metadata backend, and a - `Recommendation`. + """Return a tuple of the current artist name, the current album + name, and a `Proposal` containing `AlbumMatch` candidates. The artist and album are the most common values of these fields among `items`. @@ -429,7 +436,7 @@ def tag_album(items, search_artist=None, search_album=None, if rec == Recommendation.strong: log.debug(u'ID match.') return cur_artist, cur_album, \ - list(candidates.values()), rec + Proposal(list(candidates.values()), rec) # Search terms. if not (search_artist and search_album): @@ -454,14 +461,15 @@ def tag_album(items, search_artist=None, search_album=None, # Sort and get the recommendation. candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) - return cur_artist, cur_album, candidates, rec + return cur_artist, cur_album, Proposal(candidates, rec) def tag_item(item, search_artist=None, search_title=None, search_ids=[]): - """Attempts to find metadata for a single track. Returns a - `(candidates, recommendation)` pair where `candidates` is a list of - TrackMatch objects. `search_artist` and `search_title` may be used + """Find metadata for a single track. Return a `Proposal` consisting + of `TrackMatch` objects. + + `search_artist` and `search_title` may be used to override the current metadata for the purposes of the MusicBrainz title. `search_ids` may be used for restricting the search to a list of metadata backend IDs. @@ -484,14 +492,14 @@ def tag_item(item, search_artist=None, search_title=None, if rec == Recommendation.strong and \ not config['import']['timid']: log.debug(u'Track ID match.') - return _sort_candidates(candidates.values()), rec + return Proposal(_sort_candidates(candidates.values()), rec) # If we're searching by ID, don't proceed. if search_ids: if candidates: - return _sort_candidates(candidates.values()), rec + return Proposal(_sort_candidates(candidates.values()), rec) else: - return [], Recommendation.none + return Proposal([], Recommendation.none) # Search terms. if not (search_artist and search_title): @@ -507,4 +515,4 @@ def tag_item(item, search_artist=None, search_title=None, log.debug(u'Found {0} candidates.', len(candidates)) candidates = _sort_candidates(candidates.values()) rec = _recommendation(candidates) - return candidates, rec + return Proposal(candidates, rec) diff --git a/beets/importer.py b/beets/importer.py index 2c1d07c5c..3daf90cdc 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -587,12 +587,12 @@ class ImportTask(BaseImportTask): candidate IDs are stored in self.search_ids: if present, the initial lookup is restricted to only those IDs. """ - artist, album, candidates, recommendation = \ + artist, album, prop = \ autotag.tag_album(self.items, search_ids=self.search_ids) self.cur_artist = artist self.cur_album = album - self.candidates = candidates - self.rec = recommendation + self.candidates = prop.candidates + self.rec = prop.recommendation def find_duplicates(self, lib): """Return a list of albums from `lib` with the same artist and @@ -830,10 +830,9 @@ class SingletonImportTask(ImportTask): plugins.send('item_imported', lib=lib, item=item) def lookup_candidates(self): - candidates, recommendation = autotag.tag_item( - self.item, search_ids=self.search_ids) - self.candidates = candidates - self.rec = recommendation + prop = autotag.tag_item(self.item, search_ids=self.search_ids) + self.candidates = prop.candidates + self.rec = prop.recommendation def find_duplicates(self, lib): """Return a list of items from `lib` that have the same artist diff --git a/beets/ui/commands.py b/beets/ui/commands.py index b9a3e0b91..1a42561fd 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -752,18 +752,22 @@ class TerminalImportSession(importer.ImportSession): elif choice is importer.action.MANUAL: # Try again with manual search terms. search_artist, search_album = manual_search(False) - _, _, candidates, rec = autotag.tag_album( + _, _, prop = autotag.tag_album( task.items, search_artist, search_album ) + candidates = prop.candidates + rec = prop.recommendation # Manual ID. We prompt for the ID and run the loop again. elif choice is importer.action.MANUAL_ID: # Try a manually-entered ID. search_id = manual_id(False) if search_id: - _, _, candidates, rec = autotag.tag_album( + _, _, prop = autotag.tag_album( task.items, search_ids=search_id.split() ) + candidates = prop.candidates + rec = prop.recommendation # Plugin-provided choices. We invoke the associated callback # function. @@ -807,25 +811,33 @@ class TerminalImportSession(importer.ImportSession): if choice in (importer.action.SKIP, importer.action.ASIS): return choice + elif choice == importer.action.TRACKS: assert False # TRACKS is only legal for albums. + elif choice == importer.action.MANUAL: # Continue in the loop with a new set of candidates. search_artist, search_title = manual_search(True) - candidates, rec = autotag.tag_item(task.item, search_artist, - search_title) + prop = autotag.tag_item(task.item, search_artist, search_title) + candidates = prop.candidates + rec = prop.recommendation + elif choice == importer.action.MANUAL_ID: # Ask for a track ID. search_id = manual_id(True) if search_id: - candidates, rec = autotag.tag_item( - task.item, search_ids=search_id.split()) + prop = autotag.tag_item(task.item, + search_ids=search_id.split()) + candidates = prop.candidates + rec = prop.recommendation + elif choice in list(extra_ops.keys()): # Allow extra ops to automatically set the post-choice. post_choice = extra_ops[choice](self, task) if isinstance(post_choice, importer.action): # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice + else: # Chose a candidate. assert isinstance(choice, autotag.TrackMatch) From 22610b768408c0abc89a90c15a0348d6f814ab98 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 13:34:27 -0500 Subject: [PATCH 1552/2280] Refactor extra choice return value The `choose_candidate` function now returns the `PromptChoice` object instead of a short letter that selects the `PromptChoice`. --- beets/ui/commands.py | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 1a42561fd..1606953b6 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -511,8 +511,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, Returns one of the following: * the result of the choice, which may be SKIP, ASIS, TRACKS, or MANUAL * a candidate (an AlbumMatch/TrackMatch object) - * the short letter of a `PromptChoice` (if the user selected one of - the `extra_choices`). + * a chosen `PromptChoice` from `extra_choices` """ # Sanity check. if singleton: @@ -523,7 +522,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Build helper variables for extra choices. extra_opts = tuple(c.long for c in extra_choices) - extra_actions = tuple(c.short for c in extra_choices) + extra_actions = {c.short: c for c in extra_choices} # Zero candidates. if not candidates: @@ -555,7 +554,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: - return sel + return extra_actions[sel] else: assert False @@ -629,7 +628,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: - return sel + return extra_actions[sel] else: # Numerical selection. match = candidates[sel - 1] if sel != 1: @@ -684,7 +683,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u'i': return importer.action.MANUAL_ID elif sel in extra_actions: - return sel + return extra_actions[sel] def manual_search(singleton): @@ -728,14 +727,13 @@ class TerminalImportSession(importer.ImportSession): # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: - # Gather additional menu choices from plugins. We build a - # map from selection characters to callback functions. + # Gather additional menu choices from plugins. extra_choices = self._get_plugin_choices(task) - extra_ops = {c.short: c.callback for c in extra_choices} # Ask for a choice from the user. The result of - # `choose_candidate` may be an `importer.action` flag or an - # `AlbumMatch` object for a specific selection. + # `choose_candidate` may be an `importer.action`, an + # `AlbumMatch` object for a specific selection, or a + # `PromptChoice`. choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, itemcount=len(task.items), extra_choices=extra_choices @@ -771,8 +769,8 @@ class TerminalImportSession(importer.ImportSession): # Plugin-provided choices. We invoke the associated callback # function. - elif choice in list(extra_ops.keys()): - post_choice = extra_ops[choice](self, task) + elif choice in extra_choices: + post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice @@ -803,7 +801,6 @@ class TerminalImportSession(importer.ImportSession): while True: extra_choices = self._get_plugin_choices(task) - extra_ops = {c.short: c.callback for c in extra_choices} # Ask for a choice. choice = choose_candidate(candidates, True, rec, item=task.item, @@ -831,9 +828,8 @@ class TerminalImportSession(importer.ImportSession): candidates = prop.candidates rec = prop.recommendation - elif choice in list(extra_ops.keys()): - # Allow extra ops to automatically set the post-choice. - post_choice = extra_ops[choice](self, task) + elif choice in extra_choices: + post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice From a414872430960546c8c5d768a73028e0066b11cf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 13:36:19 -0500 Subject: [PATCH 1553/2280] Fix a missing parameter (#2349) --- beetsplug/acousticbrainz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index a323ce681..4291d9117 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -136,7 +136,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def import_task_files(self, session, task): """Function is called upon beet import. """ - self._fetch_info(task.imported_items(), False) + self._fetch_info(task.imported_items(), False, True) def _get_data(self, mbid): data = {} From 7c6eafa2855b97f8e8ac2f21a9aa6238bb379373 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 13:50:53 -0500 Subject: [PATCH 1554/2280] Refactor manual search options to use Proposal This is the first step to making them behave like plugin actions. --- beets/ui/commands.py | 65 +++++++++++++++++++++++++------------------- test/test_ui.py | 15 ---------- 2 files changed, 37 insertions(+), 43 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 1606953b6..0d19d7818 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -686,20 +686,40 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return extra_actions[sel] -def manual_search(singleton): - """Input either an artist and album (for full albums) or artist and +def manual_search(task): + """Get a new `Proposal` using manual search criteria. + + Input either an artist and album (for full albums) or artist and track name (for singletons) for manual search. """ - artist = input_(u'Artist:') - name = input_(u'Track:' if singleton else u'Album:') - return artist.strip(), name.strip() + artist = input_(u'Artist:').strip() + name = input_(u'Album:' if task.is_album else u'Track:').strip() + + if task.is_album: + _, _, prop = autotag.tag_album( + task.items, artist, name + ) + return prop + else: + return autotag.tag_item(task.item, artist, name) -def manual_id(singleton): - """Input an ID, either for an album ("release") or a track ("recording"). +def manual_id(task): + """Get a new `Proposal` using a manually-entered ID. + + Input an ID, either for an album ("release") or a track ("recording"). """ - prompt = u'Enter {0} ID:'.format(u'recording' if singleton else u'release') - return input_(prompt).strip() + prompt = u'Enter {0} ID:'.format(u'release' if task.is_album + else u'recording') + search_id = input_(prompt).strip() + + if task.is_album: + _, _, prop = autotag.tag_album( + task.items, search_ids=search_id.split() + ) + return prop + else: + return autotag.tag_item(task.item, search_ids=search_id.split()) class TerminalImportSession(importer.ImportSession): @@ -749,23 +769,16 @@ class TerminalImportSession(importer.ImportSession): # loop again. elif choice is importer.action.MANUAL: # Try again with manual search terms. - search_artist, search_album = manual_search(False) - _, _, prop = autotag.tag_album( - task.items, search_artist, search_album - ) + prop = manual_search(task) candidates = prop.candidates rec = prop.recommendation # Manual ID. We prompt for the ID and run the loop again. elif choice is importer.action.MANUAL_ID: # Try a manually-entered ID. - search_id = manual_id(False) - if search_id: - _, _, prop = autotag.tag_album( - task.items, search_ids=search_id.split() - ) - candidates = prop.candidates - rec = prop.recommendation + prop = manual_id(task) + candidates = prop.candidates + rec = prop.recommendation # Plugin-provided choices. We invoke the associated callback # function. @@ -814,19 +827,15 @@ class TerminalImportSession(importer.ImportSession): elif choice == importer.action.MANUAL: # Continue in the loop with a new set of candidates. - search_artist, search_title = manual_search(True) - prop = autotag.tag_item(task.item, search_artist, search_title) + prop = manual_search(task) candidates = prop.candidates rec = prop.recommendation elif choice == importer.action.MANUAL_ID: # Ask for a track ID. - search_id = manual_id(True) - if search_id: - prop = autotag.tag_item(task.item, - search_ids=search_id.split()) - candidates = prop.candidates - rec = prop.recommendation + prop = manual_id(task) + candidates = prop.candidates + rec = prop.recommendation elif choice in extra_choices: post_choice = choice.callback(self, task) diff --git a/test/test_ui.py b/test/test_ui.py index 39504aa4e..c519e66fb 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -670,21 +670,6 @@ class ImportTest(_common.TestCase): None) -class InputTest(_common.TestCase): - def setUp(self): - super(InputTest, self).setUp() - self.io.install() - - def test_manual_search_gets_unicode(self): - # The input here uses "native strings": bytes on Python 2, Unicode on - # Python 3. - self.io.addinput('foö') - self.io.addinput('bár') - artist, album = commands.manual_search(False) - self.assertEqual(artist, u'foö') - self.assertEqual(album, u'bár') - - @_common.slow_test() class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): def setUp(self): From 6c825970aca8f0ac026138e3072cec10d3a5cf83 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 13:54:04 -0500 Subject: [PATCH 1555/2280] Tolerate missing AlbumInfo.mediums field --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0d19d7818..f7b32eefe 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -158,7 +158,7 @@ def disambig_string(info): if isinstance(info, hooks.AlbumInfo): if info.media: - if info.mediums > 1: + if info.mediums and info.mediums > 1: disambig.append(u'{0}x{1}'.format( info.mediums, info.media )) From 2f6538aee2ea49fadccf38cd638fe7117b427e43 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:08:09 -0500 Subject: [PATCH 1556/2280] Refactor search options to ordinary choices `PromptChoice`s can now return `Proposal` values, which makes these two options just "normal" actions that could be provided by plugins. --- beets/autotag/__init__.py | 2 +- beets/importer.py | 4 +- beets/ui/commands.py | 88 +++++++++++++-------------------------- docs/dev/plugins.rst | 5 +-- 4 files changed, 33 insertions(+), 66 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 09aed89ce..3e79a4498 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -23,7 +23,7 @@ from beets import config # Parts of external interface. from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa -from .match import tag_item, tag_album # noqa +from .match import tag_item, tag_album, Proposal # noqa from .match import Recommendation # noqa # Global logger. diff --git a/beets/importer.py b/beets/importer.py index 3daf90cdc..6a10f4c97 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -43,8 +43,7 @@ from enum import Enum from beets import mediafile action = Enum('action', - ['SKIP', 'ASIS', 'TRACKS', 'MANUAL', 'APPLY', 'MANUAL_ID', - 'ALBUMS', 'RETAG']) + ['SKIP', 'ASIS', 'TRACKS', 'APPLY', 'ALBUMS', 'RETAG']) # The RETAG action represents "don't apply any match, but do record # new metadata". It's not reachable via the standard command prompt but # can be used by plugins. @@ -443,7 +442,6 @@ class ImportTask(BaseImportTask): indicates that an action has been selected for this task. """ # Not part of the task structure: - assert choice not in (action.MANUAL, action.MANUAL_ID) assert choice != action.APPLY # Only used internally. if choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS, action.RETAG): diff --git a/beets/ui/commands.py b/beets/ui/commands.py index f7b32eefe..82f5da686 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -509,7 +509,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, to the user. Returns one of the following: - * the result of the choice, which may be SKIP, ASIS, TRACKS, or MANUAL + * the result of the choice, which may be SKIP, ASIS, or TRACKS * a candidate (an AlbumMatch/TrackMatch object) * a chosen `PromptChoice` from `extra_choices` """ @@ -536,21 +536,17 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, 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') + u'aBort') sel = ui.input_options(opts + extra_opts) if sel == u'u': return importer.action.ASIS elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == u'e': - return importer.action.MANUAL elif sel == u's': return importer.action.SKIP elif sel == u'b': raise importer.ImportAbort() - elif sel == u'i': - return importer.action.MANUAL_ID elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: @@ -603,11 +599,10 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Ask the user for a choice. if singleton: - opts = (u'Skip', u'Use as-is', u'Enter search', u'enter Id', - u'aBort') + opts = (u'Skip', u'Use as-is', u'aBort') else: opts = (u'Skip', u'Use as-is', u'as Tracks', u'Group albums', - u'Enter search', u'enter Id', u'aBort') + u'aBort') sel = ui.input_options(opts + extra_opts, numrange=(1, len(candidates))) if sel == u's': @@ -616,15 +611,11 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.ASIS elif sel == u'm': pass - elif sel == u'e': - return importer.action.MANUAL elif sel == u't': assert not singleton return importer.action.TRACKS elif sel == u'b': raise importer.ImportAbort() - elif sel == u'i': - return importer.action.MANUAL_ID elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: @@ -650,11 +641,10 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Ask for confirmation. if singleton: opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'Enter search', u'enter Id', u'aBort') + u'aBort') else: 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') + u'as Tracks', u'Group albums', u'aBort') default = config['import']['default_action'].as_choice({ u'apply': u'a', u'skip': u's', @@ -676,17 +666,13 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == u'e': - return importer.action.MANUAL elif sel == u'b': raise importer.ImportAbort() - elif sel == u'i': - return importer.action.MANUAL_ID elif sel in extra_actions: return extra_actions[sel] -def manual_search(task): +def manual_search(session, task): """Get a new `Proposal` using manual search criteria. Input either an artist and album (for full albums) or artist and @@ -704,7 +690,7 @@ def manual_search(task): return autotag.tag_item(task.item, artist, name) -def manual_id(task): +def manual_id(session, task): """Get a new `Proposal` using a manually-entered ID. Input an ID, either for an album ("release") or a track ("recording"). @@ -747,8 +733,12 @@ class TerminalImportSession(importer.ImportSession): # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: - # Gather additional menu choices from plugins. - extra_choices = self._get_plugin_choices(task) + # Set up menu choices. + choices = [ + PromptChoice(u'e', u'Enter search', manual_search), + PromptChoice(u'i', u'enter Id', manual_id), + ] + choices += self._get_plugin_choices(task) # Ask for a choice from the user. The result of # `choose_candidate` may be an `importer.action`, an @@ -756,7 +746,7 @@ class TerminalImportSession(importer.ImportSession): # `PromptChoice`. choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, - itemcount=len(task.items), extra_choices=extra_choices + itemcount=len(task.items), extra_choices=choices ) # Basic choices that require no more action here. @@ -765,28 +755,16 @@ class TerminalImportSession(importer.ImportSession): # Pass selection to main control flow. return choice - # Manual search. We ask for the search terms and run the - # loop again. - elif choice is importer.action.MANUAL: - # Try again with manual search terms. - prop = manual_search(task) - candidates = prop.candidates - rec = prop.recommendation - - # Manual ID. We prompt for the ID and run the loop again. - elif choice is importer.action.MANUAL_ID: - # Try a manually-entered ID. - prop = manual_id(task) - candidates = prop.candidates - rec = prop.recommendation - # Plugin-provided choices. We invoke the associated callback # function. - elif choice in extra_choices: + elif choice in choices: post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): - # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice + elif isinstance(post_choice, autotag.Proposal): + # Use the new candidates and continue around the loop. + candidates = post_choice.candidates + rec = post_choice.recommendation # Otherwise, we have a specific match selection. else: @@ -813,11 +791,15 @@ class TerminalImportSession(importer.ImportSession): return action while True: - extra_choices = self._get_plugin_choices(task) + choices = [ + PromptChoice(u'e', u'Enter search', manual_search), + PromptChoice(u'i', u'enter Id', manual_id), + ] + choices += self._get_plugin_choices(task) # Ask for a choice. choice = choose_candidate(candidates, True, rec, item=task.item, - extra_choices=extra_choices) + extra_choices=choices) if choice in (importer.action.SKIP, importer.action.ASIS): return choice @@ -825,23 +807,13 @@ class TerminalImportSession(importer.ImportSession): elif choice == importer.action.TRACKS: assert False # TRACKS is only legal for albums. - elif choice == importer.action.MANUAL: - # Continue in the loop with a new set of candidates. - prop = manual_search(task) - candidates = prop.candidates - rec = prop.recommendation - - elif choice == importer.action.MANUAL_ID: - # Ask for a track ID. - prop = manual_id(task) - candidates = prop.candidates - rec = prop.recommendation - - elif choice in extra_choices: + elif choice in choices: post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): - # MANUAL and MANUAL_ID have no effect, even if returned. return post_choice + elif isinstance(post_choice, autotag.Proposal): + candidates = post_choice.candidates + rec = post_choice.recommendation else: # Chose a candidate. diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 80409d5f5..ba1b3e250 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -593,7 +593,4 @@ by the choices on the core importer prompt, and hence should not be used: Additionally, the callback function can optionally specify the next action to be performed by returning one of the values from ``importer.action``, which -will be passed to the main loop upon the callback has been processed. Note that -``action.MANUAL`` and ``action.MANUAL_ID`` will have no effect even if -returned by the callback, due to the current architecture of the import -process. +will be passed to the main loop upon the callback has been processed. From 8937eec50a36a8556fd7789529f6cbd2518ca734 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:15:40 -0500 Subject: [PATCH 1557/2280] Refactor built-in stnadard choices --- beets/ui/commands.py | 38 ++++++++++++++++++-------------------- docs/dev/plugins.rst | 5 +++-- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 82f5da686..dbfd987d0 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -733,17 +733,11 @@ class TerminalImportSession(importer.ImportSession): # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: - # Set up menu choices. - choices = [ - PromptChoice(u'e', u'Enter search', manual_search), - PromptChoice(u'i', u'enter Id', manual_id), - ] - choices += self._get_plugin_choices(task) - # Ask for a choice from the user. The result of # `choose_candidate` may be an `importer.action`, an # `AlbumMatch` object for a specific selection, or a # `PromptChoice`. + choices = self._get_choices(task) choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, itemcount=len(task.items), extra_choices=choices @@ -791,13 +785,8 @@ class TerminalImportSession(importer.ImportSession): return action while True: - choices = [ - PromptChoice(u'e', u'Enter search', manual_search), - PromptChoice(u'i', u'enter Id', manual_id), - ] - choices += self._get_plugin_choices(task) - # Ask for a choice. + choices = self._get_choices(task) choice = choose_candidate(candidates, True, rec, item=task.item, extra_choices=choices) @@ -866,8 +855,10 @@ class TerminalImportSession(importer.ImportSession): u"was interrupted. Resume (Y/n)?" .format(displayable_path(path))) - def _get_plugin_choices(self, task): - """Get the extra choices appended to the plugins to the ui prompt. + def _get_choices(self, task): + """Get the list of prompt choices that should be presented to the + user. This consists of both built-in choices and ones provided by + plugins. The `before_choose_candidate` event is sent to the plugins, with session and task as its parameters. Plugins are responsible for @@ -880,18 +871,24 @@ class TerminalImportSession(importer.ImportSession): Returns a list of `PromptChoice`s. """ + # Standard, built-in choices. + choices = [ + PromptChoice(u'e', u'Enter search', manual_search), + PromptChoice(u'i', u'enter Id', manual_id), + ] + # Send the before_choose_candidate event and flatten list. extra_choices = list(chain(*plugins.send('before_choose_candidate', session=self, task=task))) - # Take into account default options, for duplicate checking. + # Add "dummy" choices for the other baked-in options, for + # duplicate checking. 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)] +\ + PromptChoice(u'b', u'aBort', None)] + \ + choices + \ extra_choices short_letters = [c.short for c in all_choices] @@ -907,7 +904,8 @@ class TerminalImportSession(importer.ImportSession): u"with '{1}' (short letter: '{2}')", c.long, dup_choices[0].long, c.short) extra_choices.remove(c) - return extra_choices + + return choices + extra_choices # The import command. diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index ba1b3e250..fb063aee0 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -592,5 +592,6 @@ by the choices on the core importer prompt, and hence should not be used: ``a``, ``s``, ``u``, ``t``, ``g``, ``e``, ``i``, ``b``. Additionally, the callback function can optionally specify the next action to -be performed by returning one of the values from ``importer.action``, which -will be passed to the main loop upon the callback has been processed. +be performed by returning a ``importer.action`` value. It may also return a +``autotag.Proposal`` value to update the set of current proposals to be +considered. From 6afe407f45721a31651622b82e722f70b69b78ef Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:16:33 -0500 Subject: [PATCH 1558/2280] Remove one last duplicated set of prompts --- beets/ui/commands.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index dbfd987d0..9d1ba7322 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -528,8 +528,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, if not candidates: if singleton: print_(u"No matching recordings found.") - opts = (u'Use as-is', u'Skip', u'Enter search', u'enter Id', - u'aBort') + opts = (u'Use as-is', u'Skip', u'aBort') else: print_(u"No matching release found for {0} tracks." .format(itemcount)) From 3ede874e9653a98fc461d566e956c5bd0bf7af4e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:18:27 -0500 Subject: [PATCH 1559/2280] Changelog note about new prompt interface --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f3124271c..116f564df 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,8 @@ Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` +For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. + 1.4.2 (December 16, 2016) ------------------------- From a357cc4e1a4349dc3cce53a01358c2b650cccbe8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:20:39 -0500 Subject: [PATCH 1560/2280] Fix tests for new prompt order --- test/test_plugins.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/test_plugins.py b/test/test_plugins.py index 7c32e9aca..9aac5f608 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -444,8 +444,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + (u'Foo', u'baR') + u'as Tracks', u'Group albums', u'aBort', u'Enter search', + u'enter Id') + (u'Foo', u'baR') self.importer.add_choice(action.SKIP) self.importer.run() @@ -467,8 +467,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'Enter search', - u'enter Id', u'aBort') + (u'Foo', u'baR') + u'aBort', u'Enter search', u'enter Id') + \ + (u'Foo', u'baR') config['import']['singletons'] = True self.importer.add_choice(action.SKIP) @@ -493,8 +493,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + not dupe extra choices by the plugin ('baZ') 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') + (u'baZ',) + u'as Tracks', u'Group albums', u'aBort', u'Enter search', + u'enter Id',) + (u'baZ',) self.importer.add_choice(action.SKIP) self.importer.run() self.mock_input_options.assert_called_once_with(opts, default='a', @@ -517,8 +517,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + (u'Foo',) + u'as Tracks', u'Group albums', u'aBort', u'Enter search', + u'enter Id') + (u'Foo',) # DummyPlugin.foo() should be called once with patch.object(DummyPlugin, 'foo', autospec=True) as mock_foo: @@ -548,8 +548,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') 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') + (u'Foo',) + u'as Tracks', u'Group albums', u'aBort', u'Enter search', + u'enter Id') + (u'Foo',) # DummyPlugin.foo() should be called once with helper.control_stdin('f\n'): From e5a12615e479bf68da95e88971c2f38783063e8f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:32:41 -0500 Subject: [PATCH 1561/2280] Subsume `abort` action into declarative style --- beets/ui/commands.py | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 9d1ba7322..dcc6776b1 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -528,14 +528,13 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, if not candidates: if singleton: print_(u"No matching recordings found.") - opts = (u'Use as-is', u'Skip', u'aBort') + opts = (u'Use as-is', u'Skip') else: print_(u"No matching release found for {0} tracks." .format(itemcount)) 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'aBort') + opts = (u'Use as-is', u'as Tracks', u'Group albums', u'Skip') sel = ui.input_options(opts + extra_opts) if sel == u'u': return importer.action.ASIS @@ -544,8 +543,6 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.TRACKS elif sel == u's': return importer.action.SKIP - elif sel == u'b': - raise importer.ImportAbort() elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: @@ -598,10 +595,9 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Ask the user for a choice. if singleton: - opts = (u'Skip', u'Use as-is', u'aBort') + opts = (u'Skip', u'Use as-is') else: - opts = (u'Skip', u'Use as-is', u'as Tracks', u'Group albums', - u'aBort') + opts = (u'Skip', u'Use as-is', u'as Tracks', u'Group albums') sel = ui.input_options(opts + extra_opts, numrange=(1, len(candidates))) if sel == u's': @@ -613,8 +609,6 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == u'b': - raise importer.ImportAbort() elif sel == u'g': return importer.action.ALBUMS elif sel in extra_actions: @@ -639,11 +633,10 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, # Ask for confirmation. if singleton: - opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'aBort') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is') else: opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums', u'aBort') + u'as Tracks', u'Group albums') default = config['import']['default_action'].as_choice({ u'apply': u'a', u'skip': u's', @@ -665,8 +658,6 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, elif sel == u't': assert not singleton return importer.action.TRACKS - elif sel == u'b': - raise importer.ImportAbort() elif sel in extra_actions: return extra_actions[sel] @@ -707,6 +698,12 @@ def manual_id(session, task): return autotag.tag_item(task.item, search_ids=search_id.split()) +def abort_action(session, task): + """A prompt choice callback that aborts the importer. + """ + raise importer.ImportAbort() + + class TerminalImportSession(importer.ImportSession): """An import session that runs in a terminal. """ @@ -874,6 +871,7 @@ class TerminalImportSession(importer.ImportSession): choices = [ PromptChoice(u'e', u'Enter search', manual_search), PromptChoice(u'i', u'enter Id', manual_id), + PromptChoice(u'b', u'aBort', abort_action), ] # Send the before_choose_candidate event and flatten list. @@ -881,14 +879,13 @@ class TerminalImportSession(importer.ImportSession): session=self, task=task))) # Add "dummy" choices for the other baked-in options, for # duplicate checking. - 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'b', u'aBort', None)] + \ - choices + \ - extra_choices + 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), + ] + choices + extra_choices short_letters = [c.short for c in all_choices] if len(short_letters) != len(set(short_letters)): From 8763be5423219cd81aa5d742bd04a6d4226a944a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:33:11 -0500 Subject: [PATCH 1562/2280] Revert "Fix tests for new prompt order" This reverts commit a357cc4e1a4349dc3cce53a01358c2b650cccbe8. We no longer need the tests to change---I was able to fix the order by bringing the "abort" action into the standard list of options. --- test/test_plugins.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/test_plugins.py b/test/test_plugins.py index 9aac5f608..7c32e9aca 100644 --- a/test/test_plugins.py +++ b/test/test_plugins.py @@ -444,8 +444,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums', u'aBort', u'Enter search', - u'enter Id') + (u'Foo', u'baR') + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo', u'baR') self.importer.add_choice(action.SKIP) self.importer.run() @@ -467,8 +467,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'aBort', u'Enter search', u'enter Id') + \ - (u'Foo', u'baR') + u'Enter search', + u'enter Id', u'aBort') + (u'Foo', u'baR') config['import']['singletons'] = True self.importer.add_choice(action.SKIP) @@ -493,8 +493,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + not dupe extra choices by the plugin ('baZ') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums', u'aBort', u'Enter search', - u'enter Id',) + (u'baZ',) + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'baZ',) self.importer.add_choice(action.SKIP) self.importer.run() self.mock_input_options.assert_called_once_with(opts, default='a', @@ -517,8 +517,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums', u'aBort', u'Enter search', - u'enter Id') + (u'Foo',) + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo',) # DummyPlugin.foo() should be called once with patch.object(DummyPlugin, 'foo', autospec=True) as mock_foo: @@ -548,8 +548,8 @@ class PromptChoicesTest(TerminalImportSessionSetup, unittest.TestCase, self.register_plugin(DummyPlugin) # Default options + extra choices by the plugin ('Foo', 'Bar') opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums', u'aBort', u'Enter search', - u'enter Id') + (u'Foo',) + u'as Tracks', u'Group albums', u'Enter search', + u'enter Id', u'aBort') + (u'Foo',) # DummyPlugin.foo() should be called once with helper.control_stdin('f\n'): From 9dff841afe403db91349ba76d5b79998e9cd779c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:33:55 -0500 Subject: [PATCH 1563/2280] Fix class anme of PromptChoice --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index dcc6776b1..0911d78d0 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -42,7 +42,7 @@ from beets.util.confit import _package_path import six VARIOUS_ARTISTS = u'Various Artists' -PromptChoice = namedtuple('ExtraChoice', ['short', 'long', 'callback']) +PromptChoice = namedtuple('PromptChoice', ['short', 'long', 'callback']) # Global logger. log = logging.getLogger('beets') From 1e8be0a19fdf525da81cbdcb65f1b014bed0bacc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:40:06 -0500 Subject: [PATCH 1564/2280] Use declarative style for ALBUMS/TRACKS choices This unifies the set of choices that are shown at each prompt variant in `choose_candidate`, making its code much shorter. Declarative programming FTW. --- beets/ui/commands.py | 46 ++++++++++++-------------------------------- 1 file changed, 12 insertions(+), 34 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0911d78d0..0c50314d2 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -509,7 +509,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, to the user. Returns one of the following: - * the result of the choice, which may be SKIP, ASIS, or TRACKS + * the result of the choice, which may be SKIP or ASIS * a candidate (an AlbumMatch/TrackMatch object) * a chosen `PromptChoice` from `extra_choices` """ @@ -528,23 +528,17 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, if not candidates: if singleton: print_(u"No matching recordings found.") - opts = (u'Use as-is', u'Skip') else: print_(u"No matching release found for {0} tracks." .format(itemcount)) 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') + opts = (u'Use as-is', u'Skip') sel = ui.input_options(opts + extra_opts) if sel == u'u': return importer.action.ASIS - elif sel == u't': - assert not singleton - return importer.action.TRACKS elif sel == u's': return importer.action.SKIP - elif sel == u'g': - return importer.action.ALBUMS elif sel in extra_actions: return extra_actions[sel] else: @@ -594,10 +588,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, print_(u' '.join(line)) # Ask the user for a choice. - if singleton: - opts = (u'Skip', u'Use as-is') - else: - opts = (u'Skip', u'Use as-is', u'as Tracks', u'Group albums') + opts = (u'Skip', u'Use as-is') sel = ui.input_options(opts + extra_opts, numrange=(1, len(candidates))) if sel == u's': @@ -606,11 +597,6 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return importer.action.ASIS elif sel == u'm': pass - elif sel == u't': - assert not singleton - return importer.action.TRACKS - elif sel == u'g': - return importer.action.ALBUMS elif sel in extra_actions: return extra_actions[sel] else: # Numerical selection. @@ -632,11 +618,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return match # Ask for confirmation. - if singleton: - opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is') - else: - opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is', - u'as Tracks', u'Group albums') + opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is') default = config['import']['default_action'].as_choice({ u'apply': u'a', u'skip': u's', @@ -649,15 +631,10 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, default=default) if sel == u'a': return match - elif sel == u'g': - return importer.action.ALBUMS elif sel == u's': return importer.action.SKIP elif sel == u'u': return importer.action.ASIS - elif sel == u't': - assert not singleton - return importer.action.TRACKS elif sel in extra_actions: return extra_actions[sel] @@ -740,8 +717,7 @@ class TerminalImportSession(importer.ImportSession): ) # Basic choices that require no more action here. - if choice in (importer.action.SKIP, importer.action.ASIS, - importer.action.TRACKS, importer.action.ALBUMS): + if choice in (importer.action.SKIP, importer.action.ASIS): # Pass selection to main control flow. return choice @@ -789,9 +765,6 @@ class TerminalImportSession(importer.ImportSession): if choice in (importer.action.SKIP, importer.action.ASIS): return choice - elif choice == importer.action.TRACKS: - assert False # TRACKS is only legal for albums. - elif choice in choices: post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): @@ -873,6 +846,13 @@ class TerminalImportSession(importer.ImportSession): PromptChoice(u'i', u'enter Id', manual_id), PromptChoice(u'b', u'aBort', abort_action), ] + if task.is_album: + choices = [ + PromptChoice(u't', u'as Tracks', + lambda s, t: importer.action.TRACKS), + PromptChoice(u'g', u'Group albums', + lambda s, t: importer.action.ALBUMS), + ] + choices # Send the before_choose_candidate event and flatten list. extra_choices = list(chain(*plugins.send('before_choose_candidate', @@ -883,8 +863,6 @@ class TerminalImportSession(importer.ImportSession): 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), ] + choices + extra_choices short_letters = [c.short for c in all_choices] From f5e4853bb3b027360c17053e5b791dac97d7b647 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:46:33 -0500 Subject: [PATCH 1565/2280] Move as-is and skip choices to declarative choices That's all the standard choices that don't depend on which prompt you're looking at! Woohoo! --- beets/ui/commands.py | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 0c50314d2..f8b48568e 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -533,13 +533,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, .format(itemcount)) print_(u'For help, see: ' u'http://beets.readthedocs.org/en/latest/faq.html#nomatch') - opts = (u'Use as-is', u'Skip') - sel = ui.input_options(opts + extra_opts) - if sel == u'u': - return importer.action.ASIS - elif sel == u's': - return importer.action.SKIP - elif sel in extra_actions: + sel = ui.input_options(extra_opts) + if sel in extra_actions: return extra_actions[sel] else: assert False @@ -588,14 +583,9 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, print_(u' '.join(line)) # Ask the user for a choice. - opts = (u'Skip', u'Use as-is') - sel = ui.input_options(opts + extra_opts, + sel = ui.input_options(extra_opts, numrange=(1, len(candidates))) - if sel == u's': - return importer.action.SKIP - elif sel == u'u': - return importer.action.ASIS - elif sel == u'm': + if sel == u'm': pass elif sel in extra_actions: return extra_actions[sel] @@ -618,7 +608,6 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, return match # Ask for confirmation. - opts = (u'Apply', u'More candidates', u'Skip', u'Use as-is') default = config['import']['default_action'].as_choice({ u'apply': u'a', u'skip': u's', @@ -627,14 +616,10 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, }) if default is None: require = True - sel = ui.input_options(opts + extra_opts, require=require, - default=default) + sel = ui.input_options((u'Apply', u'More candidates') + extra_opts, + require=require, default=default) if sel == u'a': return match - elif sel == u's': - return importer.action.SKIP - elif sel == u'u': - return importer.action.ASIS elif sel in extra_actions: return extra_actions[sel] @@ -842,6 +827,10 @@ class TerminalImportSession(importer.ImportSession): """ # Standard, built-in choices. choices = [ + PromptChoice(u's', u'Skip', + lambda s, t: importer.action.SKIP), + PromptChoice(u'u', u'Use as-is', + lambda s, t: importer.action.ASIS), PromptChoice(u'e', u'Enter search', manual_search), PromptChoice(u'i', u'enter Id', manual_id), PromptChoice(u'b', u'aBort', abort_action), @@ -857,14 +846,14 @@ class TerminalImportSession(importer.ImportSession): # Send the before_choose_candidate event and flatten list. extra_choices = list(chain(*plugins.send('before_choose_candidate', session=self, task=task))) - # Add "dummy" choices for the other baked-in options, for + + # Add a "dummy" choice for the other baked-in option, for # duplicate checking. all_choices = [ PromptChoice(u'a', u'Apply', None), - PromptChoice(u's', u'Skip', None), - PromptChoice(u'u', u'Use as-is', None), ] + choices + extra_choices + # Check for conflicts. short_letters = [c.short for c in all_choices] if len(short_letters) != len(set(short_letters)): # Duplicate short letter has been found. From c98972894a24575477d4438091a3529c9a88dcfa Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:49:26 -0500 Subject: [PATCH 1566/2280] Better prompt order --- beets/ui/commands.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index f8b48568e..723c3f27b 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -830,18 +830,20 @@ class TerminalImportSession(importer.ImportSession): PromptChoice(u's', u'Skip', lambda s, t: importer.action.SKIP), PromptChoice(u'u', u'Use as-is', - lambda s, t: importer.action.ASIS), - PromptChoice(u'e', u'Enter search', manual_search), - PromptChoice(u'i', u'enter Id', manual_id), - PromptChoice(u'b', u'aBort', abort_action), + lambda s, t: importer.action.ASIS) ] if task.is_album: - choices = [ + choices += [ PromptChoice(u't', u'as Tracks', lambda s, t: importer.action.TRACKS), PromptChoice(u'g', u'Group albums', lambda s, t: importer.action.ALBUMS), - ] + choices + ] + choices += [ + PromptChoice(u'e', u'Enter search', manual_search), + PromptChoice(u'i', u'enter Id', manual_id), + PromptChoice(u'b', u'aBort', abort_action), + ] # Send the before_choose_candidate event and flatten list. extra_choices = list(chain(*plugins.send('before_choose_candidate', From 63f50287d589aec5fef0000a357aad9548f35f9c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 14:54:25 -0500 Subject: [PATCH 1567/2280] Rename some choice-related variables These are no longer "extra"---they're *all* the choices that will be used. --- beets/ui/commands.py | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 723c3f27b..168f0d515 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -495,7 +495,7 @@ def _summary_judgment(rec): def choose_candidate(candidates, singleton, rec, cur_artist=None, cur_album=None, item=None, itemcount=None, - extra_choices=[]): + choices=[]): """Given a sorted list of candidates, ask the user for a selection of which candidate to use. Applies to both full albums and singletons (tracks). Candidates are either AlbumMatch or TrackMatch @@ -503,15 +503,12 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, `cur_album`, and `itemcount` must be provided. For singletons, `item` must be provided. - `extra_choices` is a list of `PromptChoice`s, containg the choices - appended by the plugins after receiving the `before_choose_candidate` - event. If not empty, the choices are appended to the prompt presented - to the user. + `choices` is a list of `PromptChoice`s to be used in each prompt. Returns one of the following: * the result of the choice, which may be SKIP or ASIS * a candidate (an AlbumMatch/TrackMatch object) - * a chosen `PromptChoice` from `extra_choices` + * a chosen `PromptChoice` from `choices` """ # Sanity check. if singleton: @@ -520,9 +517,9 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, assert cur_artist is not None assert cur_album is not None - # Build helper variables for extra choices. - extra_opts = tuple(c.long for c in extra_choices) - extra_actions = {c.short: c for c in extra_choices} + # Build helper variables for the prompt choices. + choice_opts = tuple(c.long for c in choices) + choice_actions = {c.short: c for c in choices} # Zero candidates. if not candidates: @@ -533,9 +530,9 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, .format(itemcount)) print_(u'For help, see: ' u'http://beets.readthedocs.org/en/latest/faq.html#nomatch') - sel = ui.input_options(extra_opts) - if sel in extra_actions: - return extra_actions[sel] + sel = ui.input_options(choice_opts) + if sel in choice_actions: + return choice_actions[sel] else: assert False @@ -583,12 +580,12 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, print_(u' '.join(line)) # Ask the user for a choice. - sel = ui.input_options(extra_opts, + sel = ui.input_options(choice_opts, numrange=(1, len(candidates))) if sel == u'm': pass - elif sel in extra_actions: - return extra_actions[sel] + elif sel in choice_actions: + return choice_actions[sel] else: # Numerical selection. match = candidates[sel - 1] if sel != 1: @@ -616,12 +613,12 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, }) if default is None: require = True - sel = ui.input_options((u'Apply', u'More candidates') + extra_opts, + sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': return match - elif sel in extra_actions: - return extra_actions[sel] + elif sel in choice_actions: + return choice_actions[sel] def manual_search(session, task): @@ -698,7 +695,7 @@ class TerminalImportSession(importer.ImportSession): choices = self._get_choices(task) choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, - itemcount=len(task.items), extra_choices=choices + itemcount=len(task.items), choices=choices ) # Basic choices that require no more action here. @@ -745,7 +742,7 @@ class TerminalImportSession(importer.ImportSession): # Ask for a choice. choices = self._get_choices(task) choice = choose_candidate(candidates, True, rec, item=task.item, - extra_choices=choices) + choices=choices) if choice in (importer.action.SKIP, importer.action.ASIS): return choice From 02666424d474339d787085525dc89ad1e9e7f4c6 Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Wed, 28 Dec 2016 21:07:18 +0100 Subject: [PATCH 1568/2280] discogs: improve robustness when parsing an album Improve the robustness of `get_album_info()` by preferring the use of `get()` over accesing the dictionary keys directly for several fields, plus adding extra checks for fields that depend on nested containers on the Release data. Add a test for parsing a release that contains a minimal amount of fields. --- beetsplug/discogs.py | 33 ++++++++++++++++++++++----------- test/test_discogs.py | 10 ++++++++++ 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 28b863d4b..9434ab895 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -218,25 +218,36 @@ class DiscogsPlugin(BeetsPlugin): # information and leave us with skeleton `Artist` objects that will # each make an API call just to get the same data back. tracks = self.get_tracks(result.data['tracklist']) - albumtype = ', '.join( - result.data['formats'][0].get('descriptions', [])) or None - va = result.data['artists'][0]['name'].lower() == 'various' + + # Extract information for the optional AlbumInfo fields, if possible. + va = result.data['artists'][0].get('name', '').lower() == 'various' + year = result.data.get('year') + mediums = len(set(t.medium for t in tracks)) + country = result.data.get('country') + data_url = result.data.get('uri') + + # Extract information for the optional AlbumInfo fields that are + # contained on nested discogs fields. + albumtype = media = label = catalogno = None + if result.data.get('formats'): + albumtype = ', '.join( + result.data['formats'][0].get('descriptions', [])) or None + media = result.data['formats'][0]['name'] + if result.data.get('labels'): + label = result.data['labels'][0].get('name') + catalogno = result.data['labels'][0].get('catno') + + # Additional cleanups (various artists name, catalog number, media). if va: 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)) - catalogno = result.data['labels'][0]['catno'] if catalogno == 'none': - catalogno = None - country = result.data.get('country') - media = result.data['formats'][0]['name'] + catalogno = None # Explicitly set the `media` for the tracks, since it is expected by # `autotag.apply_metadata`, and set `medium_total`. for track in tracks: track.media = media track.medium_total = mediums - data_url = result.data['uri'] + return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, day=None, label=label, mediums=mediums, diff --git a/test/test_discogs.py b/test/test_discogs.py index 5fe5926b8..061f8e65d 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -290,6 +290,16 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(len(d.tracks), 3) self.assertEqual(d.tracks[1].title, 'TRACK GROUP TITLE') + def test_parse_minimal_release(self): + """Test parsing of a release with the minimal amount of information.""" + artists = [{'name': 'ARTIST NAME', 'id': 'ARTIST ID', 'join': ''}] + release = Bag(data={'id': 123, 'tracklist': [], 'artists': artists}, + title='TITLE', artists=[Bag(data=d) for d in artists]) + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.artist, 'ARTIST NAME') + self.assertEqual(d.album, 'TITLE') + self.assertEqual(len(d.tracks), 0) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 0efb0c3472ea21b41d86d9380117047858c131f7 Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Wed, 28 Dec 2016 21:16:44 +0100 Subject: [PATCH 1569/2280] discogs: add changelog entry for robustness fix --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 43c651200..bf6c5cdd7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -19,6 +19,9 @@ Features: Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` +* :doc:`/plugins/discogs`: Fix a crash when a release did not contain Format + information, and increased robustness when other fields are missing. + :bug:`2302` 1.4.2 (December 16, 2016) From c7351d9086914b6a314ced7fac1be136dfc17b20 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 16:18:02 -0500 Subject: [PATCH 1570/2280] Flip an erroneous execute bit --- beets/library.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 beets/library.py diff --git a/beets/library.py b/beets/library.py old mode 100755 new mode 100644 From 24d43635cd6862ae82a780fc01af8ae85ef1e3bb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 16:33:43 -0500 Subject: [PATCH 1571/2280] Slightly more helpful UnreadableFileError (#2351) The exception now says something about what caused it, instead of just listing the path that led to the error. --- beets/mediafile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index ad66b74c5..0f595a36a 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -87,8 +87,8 @@ PREFERRED_IMAGE_EXTENSIONS = {'jpeg': 'jpg'} class UnreadableFileError(Exception): """Mutagen is not able to extract information from the file. """ - def __init__(self, path): - Exception.__init__(self, repr(path)) + def __init__(self, path, msg): + Exception.__init__(self, msg if msg else repr(path)) class FileTypeError(UnreadableFileError): @@ -132,7 +132,7 @@ def mutagen_call(action, path, func, *args, **kwargs): return func(*args, **kwargs) except mutagen.MutagenError as exc: log.debug(u'%s failed: %s', action, six.text_type(exc)) - raise UnreadableFileError(path) + raise UnreadableFileError(path, six.text_type(exc)) except Exception as exc: # Isolate bugs in Mutagen. log.debug(u'%s', traceback.format_exc()) From 413666a82531bed46291f6e458aa78b92b1ee9c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 28 Dec 2016 16:36:51 -0500 Subject: [PATCH 1572/2280] Fix #2351: crash in scrub on MediaFile errors --- beetsplug/scrub.py | 1 + docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 4dcefe572..8ecf8ad5d 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -122,6 +122,7 @@ class ScrubPlugin(BeetsPlugin): except mediafile.UnreadableFileError as exc: self._log.error(u'could not open file to scrub: {0}', exc) + return art = mf.art # Remove all tags. diff --git a/docs/changelog.rst b/docs/changelog.rst index 116f564df..e5e027016 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,8 @@ Features: Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` +* :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. + :bug:`2351` For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 8bb703619f5ecdeb98c637cd46fea2b6e25bf6e5 Mon Sep 17 00:00:00 2001 From: dopefishh Date: Thu, 29 Dec 2016 11:38:27 +0100 Subject: [PATCH 1573/2280] use util.py3_path for web attachment filenames (#2353) Web attachment filenames must be passed as a string for Python 3 --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 810de8718..e7b9ec81f 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -206,7 +206,7 @@ def item_file(item_id): response = flask.send_file( util.py3_path(item.path), as_attachment=True, - attachment_filename=os.path.basename(item.path), + attachment_filename=os.path.basename(util.py3_path(item.path)), ) response.headers['Content-Length'] = os.path.getsize(item.path) return response From 30f238151ea0136ea4002421c75ba40751434c34 Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Thu, 29 Dec 2016 13:19:01 +0100 Subject: [PATCH 1574/2280] discogs: additional sanity checks parsing release Add extra checks for the presence of specific field (artists, title, id, tracklist) when parsing a Release from discogs, failing gracefully if the fields could not be found. Add a test for releases without required fields. --- beetsplug/discogs.py | 18 +++++++++++++++++- test/test_discogs.py | 22 ++++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 9434ab895..6a55669a8 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -205,11 +205,27 @@ class DiscogsPlugin(BeetsPlugin): self._log.debug(u"Communication error while searching for {0!r}", query, exc_info=True) return [] - return [self.get_album_info(release) for release in releases[:5]] + return filter(None, [self.get_album_info(release) + for release in releases[:5]]) def get_album_info(self, result): """Returns an AlbumInfo object for a discogs Release object. """ + # Explicitly reload the `Release` fields, as they might not be yet + # present if the result is from a `discogs_client.search()`. + if not result.data.get('artists'): + result.refresh() + + # Sanity check for required fields. The list of required fields is + # defined at Guideline 1.3.1.a, but in practice some releases might be + # lacking some of these fields. This function expects at least: + # `artists` (>0), `title`, `id`, `tracklist` (>0) + # https://www.discogs.com/help/doc/submission-guidelines-general-rules + if not all([result.data.get(k) for k in ['artists', 'title', 'id', + 'tracklist']]): + self._log.warn(u"Release does not contain the required fields") + return None + artist, artist_id = self.get_artist([a.data for a in result.artists]) album = re.sub(r' +', ' ', result.title) album_id = result.data['id'] diff --git a/test/test_discogs.py b/test/test_discogs.py index 061f8e65d..2e7677e0a 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function import unittest from test import _common from test._common import Bag +from test.helper import capture_log from beetsplug.discogs import DiscogsPlugin @@ -292,13 +293,26 @@ class DGAlbumInfoTest(_common.TestCase): def test_parse_minimal_release(self): """Test parsing of a release with the minimal amount of information.""" - artists = [{'name': 'ARTIST NAME', 'id': 'ARTIST ID', 'join': ''}] - release = Bag(data={'id': 123, 'tracklist': [], 'artists': artists}, - title='TITLE', artists=[Bag(data=d) for d in artists]) + data = {'id': 123, + 'tracklist': [self._make_track('A', '1', '01:01')], + 'artists': [{'name': 'ARTIST NAME', 'id': 321, 'join': ''}], + 'title': 'TITLE'} + release = Bag(data=data, + title=data['title'], + artists=[Bag(data=d) for d in data['artists']]) d = DiscogsPlugin().get_album_info(release) self.assertEqual(d.artist, 'ARTIST NAME') self.assertEqual(d.album, 'TITLE') - self.assertEqual(len(d.tracks), 0) + self.assertEqual(len(d.tracks), 1) + + def test_parse_release_without_required_fields(self): + """Test parsing of a release that does not have the required fields.""" + release = Bag(data={}, refresh=lambda *args: None) + with capture_log() as logs: + d = DiscogsPlugin().get_album_info(release) + + self.assertEqual(d, None) + self.assertIn('Release does not contain the required fields', logs[0]) def suite(): From 0a9cb1fd3ded5f768e04883db7486058565d3e79 Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Thu, 29 Dec 2016 18:03:54 +0100 Subject: [PATCH 1575/2280] discogs: revise subtrack merging based on subindex Modify the coalescing of subtracks by taking into account the subindices of the subtracks for deciding if they represent "logical" tracks (merging them into one single track, as previously) or if they represent physical tracks (treating them as individual tracks). Add unit tests for nested logical/physical subtracks, and disc titles. --- beetsplug/discogs.py | 26 +++++++++++++++++++------- test/test_discogs.py | 41 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 28b863d4b..d69e92913 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -354,15 +354,27 @@ class DiscogsPlugin(BeetsPlugin): """Modify `tracklist` in place, merging a list of `subtracks` into a single track into `tracklist`.""" # Calculate position based on first subtrack, without subindex. - idx, medium_idx, _ = self.get_track_index(subtracks[0]['position']) + idx, medium_idx, sub_idx = \ + self.get_track_index(subtracks[0]['position']) position = '%s%s' % (idx or '', medium_idx or '') - if len(tracklist) > 1 and not tracklist[-1]['position']: - # Assume the previous index track contains the track title, and - # "convert" it to a real track. The only exception is if the - # index track is the only one on the tracklist, as it probably - # is a medium title. - tracklist[-1]['position'] = position + if tracklist and not tracklist[-1]['position']: + # Assume the previous index track contains the track title. + if sub_idx: + # "Convert" the track title to a real track, discarding the + # subtracks assuming they are logical divisions of a + # physical track (12.2.9 Subtracks). + tracklist[-1]['position'] = position + else: + # Promote the subtracks to real tracks, discarding the + # index track, assumeing the subtracks are physical tracks. + index_track = tracklist.pop() + # Fix artists when they are specified on the index track. + if index_track.get('artists'): + for subtrack in subtracks: + if not subtrack.get('artists'): + subtrack['artists'] = index_track['artists'] + tracklist.extend(subtracks) else: # Merge the subtracks, pick a title, and append the new track. track = subtracks[0].copy() diff --git a/test/test_discogs.py b/test/test_discogs.py index 5fe5926b8..95f5e7554 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -272,11 +272,14 @@ class DGAlbumInfoTest(_common.TestCase): d = DiscogsPlugin().get_album_info(release) self.assertEqual(d.mediums, 1) + self.assertEqual(d.tracks[0].disctitle, 'MEDIUM TITLE') self.assertEqual(len(d.tracks), 1) self.assertEqual(d.tracks[0].title, 'TRACK GROUP TITLE') - def test_parse_tracklist_subtracks_nested(self): - """Test parsing of subtracks defined inside a index track.""" + def test_parse_tracklist_subtracks_nested_logical(self): + """Test parsing of subtracks defined inside a index track that are + logical subtracks (ie. should be grouped together into a single track). + """ release = self._make_release_from_positions(['1', '', '3']) # Track 2: Index track with track group title, and sub_tracks release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' @@ -290,6 +293,40 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(len(d.tracks), 3) self.assertEqual(d.tracks[1].title, 'TRACK GROUP TITLE') + def test_parse_tracklist_subtracks_nested_physical(self): + """Test parsing of subtracks defined inside a index track that are + physical subtracks (ie. should not be grouped together). + """ + release = self._make_release_from_positions(['1', '', '4']) + # Track 2: Index track with track group title, and sub_tracks + release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE' + release.data['tracklist'][1]['sub_tracks'] = [ + self._make_track('TITLE ONE', '2', '01:01'), + self._make_track('TITLE TWO', '3', '02:02') + ] + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 1) + self.assertEqual(len(d.tracks), 4) + self.assertEqual(d.tracks[1].title, 'TITLE ONE') + self.assertEqual(d.tracks[2].title, 'TITLE TWO') + + def test_parse_tracklist_disctitles(self): + """Test parsing of index tracks that act as disc titles.""" + release = self._make_release_from_positions(['', '1-1', '1-2', '', + '2-1']) + # Track 1: Index track with medium title (Cd1) + release.data['tracklist'][0]['title'] = 'MEDIUM TITLE CD1' + # Track 4: Index track with medium title (Cd2) + release.data['tracklist'][3]['title'] = 'MEDIUM TITLE CD2' + + d = DiscogsPlugin().get_album_info(release) + self.assertEqual(d.mediums, 2) + self.assertEqual(d.tracks[0].disctitle, 'MEDIUM TITLE CD1') + self.assertEqual(d.tracks[1].disctitle, 'MEDIUM TITLE CD1') + self.assertEqual(d.tracks[2].disctitle, 'MEDIUM TITLE CD2') + self.assertEqual(len(d.tracks), 3) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From ac41b6d6e5f432d92d21cdc9802e5caf6e20e61c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 29 Dec 2016 13:30:17 -0500 Subject: [PATCH 1576/2280] Fix #2339: scrub resets art type We now use the richer `images` field instead of the more basic `art` field. --- beetsplug/scrub.py | 6 +++--- docs/changelog.rst | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index 8ecf8ad5d..b652fa2f5 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -123,7 +123,7 @@ class ScrubPlugin(BeetsPlugin): self._log.error(u'could not open file to scrub: {0}', exc) return - art = mf.art + images = mf.images # Remove all tags. self._scrub(item.path) @@ -132,12 +132,12 @@ class ScrubPlugin(BeetsPlugin): if restore: self._log.debug(u'writing new tags after scrub') item.try_write() - if art: + if images: self._log.debug(u'restoring art') try: mf = mediafile.MediaFile(util.syspath(item.path), config['id3v23'].get(bool)) - mf.art = art + mf.images = images mf.save() except mediafile.UnreadableFileError as exc: self._log.error(u'could not write tags: {0}', exc) diff --git a/docs/changelog.rst b/docs/changelog.rst index e5e027016..b7095acff 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -25,6 +25,8 @@ Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` * :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. :bug:`2351` +* :doc:`/plugins/scrub`: The image type values on scrubbed files are preserved + instead of being reset to "other." :bug:`2339` For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 26425448679151bf6b1a7cac10381c6f4983dc8b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 29 Dec 2016 13:34:23 -0500 Subject: [PATCH 1577/2280] Changelog note for #2353 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index b7095acff..2303bfdd2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ Fixes: :bug:`2351` * :doc:`/plugins/scrub`: The image type values on scrubbed files are preserved instead of being reset to "other." :bug:`2339` +* :doc:`/plugins/web`: Fix a crash on Python 3 when serving files from the + filesystem. :bug:`2353` For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 072e6de3aeb43df75a821f4fc4fdda1ee17a5c7e Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Fri, 30 Dec 2016 10:17:53 +0100 Subject: [PATCH 1578/2280] discogs: add changelog for #2318, fix typo --- beetsplug/discogs.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index d69e92913..dbd45ece4 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -367,7 +367,7 @@ class DiscogsPlugin(BeetsPlugin): tracklist[-1]['position'] = position else: # Promote the subtracks to real tracks, discarding the - # index track, assumeing the subtracks are physical tracks. + # index track, assuming the subtracks are physical tracks. index_track = tracklist.pop() # Fix artists when they are specified on the index track. if index_track.get('artists'): diff --git a/docs/changelog.rst b/docs/changelog.rst index e5e027016..74526f940 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -25,6 +25,8 @@ Fixes: * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` * :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. :bug:`2351` +* :doc:`/plugins/discogs`: Improve the handling of releases that contain + subtracks. :bug:`2318` For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 3f36f679401ffa8a95b1e7308b80b8f874b247de Mon Sep 17 00:00:00 2001 From: "Diego M. Rodriguez" Date: Fri, 30 Dec 2016 11:39:19 +0100 Subject: [PATCH 1579/2280] discogs: tweak pruning of empty candidate albums --- beetsplug/discogs.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index f3f891688..cf10a2a36 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -205,8 +205,8 @@ class DiscogsPlugin(BeetsPlugin): self._log.debug(u"Communication error while searching for {0!r}", query, exc_info=True) return [] - return filter(None, [self.get_album_info(release) - for release in releases[:5]]) + return [album for album in map(self.get_album_info, releases[:5]) + if album] def get_album_info(self, result): """Returns an AlbumInfo object for a discogs Release object. From 8bb24e31343c9707493d3c37668ebb55c69bcc0e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 30 Dec 2016 10:55:24 -0500 Subject: [PATCH 1580/2280] lyrics: Set User-Agent header (fix #2357) --- beetsplug/lyrics.py | 11 +++++++++-- docs/changelog.rst | 2 ++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 645d52559..a642159c2 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -51,6 +51,7 @@ except ImportError: from beets import plugins from beets import ui +import beets DIV_RE = re.compile(r'<(/?)div>?', re.I) @@ -71,6 +72,7 @@ URL_CHARACTERS = { u'\u2016': u'-', u'\u2026': u'...', } +USER_AGENT = 'beets/{}'.format(beets.__version__) # Utilities. @@ -210,7 +212,9 @@ class Backend(object): # We're not overly worried about the NSA MITMing our lyrics scraper with warnings.catch_warnings(): warnings.simplefilter('ignore') - r = requests.get(url, verify=False) + r = requests.get(url, verify=False, headers={ + 'User-Agent': USER_AGENT, + }) except requests.RequestException as exc: self._log.debug(u'lyrics request failed: {0}', exc) return @@ -263,7 +267,10 @@ class Genius(Backend): def __init__(self, config, log): super(Genius, self).__init__(config, log) self.api_key = config['genius_api_key'].as_str() - self.headers = {'Authorization': "Bearer %s" % self.api_key} + self.headers = { + 'Authorization': "Bearer %s" % self.api_key, + 'User-Agent': USER_AGENT, + } def search_genius(self, artist, title): query = u"%s %s" % (artist, title) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2f7d35fac..9be90c766 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -34,6 +34,8 @@ Fixes: * :doc:`/plugins/discogs`: Fix a crash when a release did not contain Format information, and increased robustness when other fields are missing. :bug:`2302` +* :doc:`/plugins/lyrics`: The plugin now reports a beets-specific User-Agent + header when requesting lyrics. :bug:`2357` For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 2eb47e9ea581f60be3d25c4c69585581d44e67e7 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Fri, 30 Dec 2016 21:30:20 -0500 Subject: [PATCH 1581/2280] Temporarily allow empty checksum for unrar on appveyor (#2359) Obviously it'd be best if we didn't have to do it, but I doubt we can wait forever for the packagers to add it. --- appveyor.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 974bff4db..4f350b938 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -20,7 +20,8 @@ environment: # Install Tox for running tests. install: - cinst imagemagick -y - - cinst unrar -y + # TODO: remove --allow-empty-checksums when unrar offers a proper checksum + - cinst unrar -y --allow-empty-checksums - "%PYTHON%/Scripts/pip.exe install tox" - "%PYTHON%/Scripts/tox.exe -e %TOX_ENV% --notest" From ab4246c5db8fe015b7928c262dc59917a3af0559 Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 30 Dec 2016 13:08:56 -0500 Subject: [PATCH 1582/2280] add prompt choice to play items before import fix line number add comments --- beetsplug/play.py | 143 +++++++++++++++++++++++++++++++--------------- 1 file changed, 98 insertions(+), 45 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 4a2174909..2f708e5cb 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -19,17 +19,35 @@ from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin from beets.ui import Subcommand +from beets.ui.commands import PromptChoice from beets import config from beets import ui from beets import util from os.path import relpath from tempfile import NamedTemporaryFile +import subprocess # Indicate where arguments should be inserted into the command string. # If this is missing, they're placed at the end. ARGS_MARKER = '$args' +def play(command_str, paths, open_args, keep_open=False): + """Play items in paths with command_str and optional arguments. If + keep_open, return to beets, otherwise exit once command runs. + """ + try: + if keep_open: + command = command_str.split() + command = command + open_args + subprocess.call(command) + else: + util.interactive_open(open_args, command_str) + except OSError as exc: + raise ui.UserError( + "Could not play the query: {0}".format(exc)) + + class PlayPlugin(BeetsPlugin): def __init__(self): @@ -40,11 +58,14 @@ class PlayPlugin(BeetsPlugin): 'use_folders': False, 'relative_to': None, 'raw': False, - # Backwards compatibility. See #1803 and line 74 + # Backwards compatibility. See #1803 and line 155 'warning_threshold': -2, 'warning_treshold': 100, }) + self.register_listener('before_choose_candidate', + self.before_choose_candidate_listener) + def commands(self): play_command = Subcommand( 'play', @@ -56,44 +77,17 @@ class PlayPlugin(BeetsPlugin): action='store', help=u'add additional arguments to the command', ) - play_command.func = self.play_music + play_command.func = self._play_command return [play_command] - def play_music(self, lib, opts, args): - """Execute query, create temporary playlist and execute player - command passing that playlist, at request insert optional arguments. + def _play_command(self, lib, opts, args): + """The CLI command function for `beet play`. Creates a list of paths + from query, determines if tracks or albums are to be played. """ - command_str = config['play']['command'].get() - if not command_str: - command_str = util.open_anything() use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() - raw = config['play']['raw'].get(bool) - warning_threshold = config['play']['warning_threshold'].get(int) - # We use -2 as a default value for warning_threshold to detect if it is - # set or not. We can't use a falsey value because it would have an - # actual meaning in the configuration of this plugin, and we do not use - # -1 because some people might use it as a value to obtain no warning, - # which wouldn't be that bad of a practice. - if warning_threshold == -2: - # if warning_threshold has not been set by user, look for - # warning_treshold, to preserve backwards compatibility. See #1803. - # warning_treshold has the correct default value of 100. - warning_threshold = config['play']['warning_treshold'].get(int) - if relative_to: relative_to = util.normpath(relative_to) - - # Add optional arguments to the player command. - if opts.args: - if ARGS_MARKER in command_str: - command_str = command_str.replace(ARGS_MARKER, opts.args) - else: - command_str = u"{} {}".format(command_str, opts.args) - else: - # Don't include the marker in the command. - command_str = command_str.replace(" " + ARGS_MARKER, "") - # Perform search by album and add folders rather than tracks to # playlist. if opts.album: @@ -117,14 +111,64 @@ class PlayPlugin(BeetsPlugin): paths = [relpath(path, relative_to) for path in paths] item_type = 'track' - item_type += 's' if len(selection) > 1 else '' - if not selection: ui.print_(ui.colorize('text_warning', u'No {0} to play.'.format(item_type))) return + open_args = self._playlist_or_paths(paths) + command_str = self._create_command_str(opts.args) + + # If user aborts due to long playlist: + cancel = self._print_info(selection, command_str, open_args, item_type) + + # Otherwise proceed with play command. + if not cancel: + play(command_str, paths, open_args) + + def _create_command_str(self, args=None): + """Creates a command string from the config command and optional args. + """ + command_str = config['play']['command'].get() + if not command_str: + return util.open_anything() + # Add optional arguments to the player command. + if args: + if ARGS_MARKER in command_str: + return command_str.replace(ARGS_MARKER, args) + else: + return u"{} {}".format(command_str, args) + else: + # Don't include the marker in the command. + return command_str.replace(" " + ARGS_MARKER, "") + + def _playlist_or_paths(self, paths): + """Returns either the raw paths of items or a playlist of the items. + """ + raw = config['play']['raw'].get(bool) + if raw: + return paths + else: + return [self._create_tmp_playlist(paths)] + + def _print_info(self, selection, command_str, open_args, + item_type='track'): + """Prompts user whether to continue if playlist exceeds threshold. + """ + warning_threshold = config['play']['warning_threshold'].get(int) + # We use -2 as a default value for warning_threshold to detect if it is + # set or not. We can't use a falsey value because it would have an + # actual meaning in the configuration of this plugin, and we do not use + # -1 because some people might use it as a value to obtain no warning, + # which wouldn't be that bad of a practice. + if warning_threshold == -2: + # if warning_threshold has not been set by user, look for + # warning_treshold, to preserve backwards compatibility. See #1803. + # warning_treshold has the correct default value of 100. + warning_threshold = config['play']['warning_treshold'].get(int) + # Warn user before playing any huge playlists. + item_type += 's' if len(selection) > 1 else '' if warning_threshold and len(selection) > warning_threshold: ui.print_(ui.colorize( 'text_warning', @@ -132,20 +176,11 @@ class PlayPlugin(BeetsPlugin): len(selection), item_type))) if ui.input_options((u'Continue', u'Abort')) == 'a': - return + return True + # Print number of tracks or albums to be played, log command to be run. ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) - if raw: - open_args = paths - else: - open_args = [self._create_tmp_playlist(paths)] - self._log.debug(u'executing command: {} {!r}', command_str, open_args) - try: - util.interactive_open(open_args, command_str) - except OSError as exc: - raise ui.UserError( - "Could not play the query: {0}".format(exc)) def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. @@ -155,3 +190,21 @@ class PlayPlugin(BeetsPlugin): m3u.write(item + b'\n') m3u.close() return m3u.name + + def before_choose_candidate_listener(self, session, task): + """Append a "Play" choice to the interactive importer prompt. + """ + return [PromptChoice('y', 'plaY', self.importer_play)] + + def importer_play(self, session, task): + """Get items from current import task and send to play function. + """ + selection = task.items + paths = [item.path for item in selection] + + open_args = self._playlist_or_paths(paths) + command_str = self._create_command_str() + cancel = self._print_info(selection, command_str, open_args) + + if not cancel: + play(command_str, paths, open_args, keep_open=True) From af99ee21aacd0908c3de30032957571a1f9b2f18 Mon Sep 17 00:00:00 2001 From: diomekes Date: Sat, 31 Dec 2016 00:15:36 -0500 Subject: [PATCH 1583/2280] add documentation for play importer prompt choice --- docs/plugins/play.rst | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 1ac51a1f3..6a34cda57 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -4,8 +4,8 @@ Play Plugin The ``play`` plugin allows you to pass the results of a query to a music player in the form of an m3u playlist or paths on the command line. -Usage ------ +Command Line Usage +------------------ To use the ``play`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then use it by invoking the ``beet play`` command with @@ -29,6 +29,18 @@ would on the command-line):: While playing you'll be able to interact with the player if it is a command-line oriented, and you'll get its output in real time. +Interactive Usage +----------------- + +The `play` plugin can also be invoked during an import. If enabled, the plugin +adds a `plaY` option to the prompt, so pressing `y` will execute the configured +command and play the items currently being imported. + +Once you exit your configured player, you will be returned to the import +decision prompt. If your player is configured to run in the background (in a +client/server setup), the music will play until you choose to stop it, and the +import operation continues immediately. + Configuration ------------- From 1c5c74f1d73fdb943074c6e89d2affb44511aa71 Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Sat, 31 Dec 2016 18:46:01 +0300 Subject: [PATCH 1584/2280] Fix a typo --- beetsplug/lastimport.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 25624731e..238e447bc 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -27,7 +27,7 @@ from beets.dbcore import types if util.SNI_SUPPORTED: API_URL = 'https://ws.audioscrobbler.com/2.0/' else: - API_URL = 'https://ws.audioscrobbler.com/2.0/' + API_URL = 'http://ws.audioscrobbler.com/2.0/' class LastImportPlugin(plugins.BeetsPlugin): From cfe9c0f3d4155924bd330378ab846da014c4d2cb Mon Sep 17 00:00:00 2001 From: inytar Date: Sat, 31 Dec 2016 14:11:55 -0500 Subject: [PATCH 1585/2280] Remove fixed TODO comment --- beetsplug/absubmit.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index 804930b07..807d6618c 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -52,7 +52,6 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): ) else: # Implicit path to extractor, search for it in path - # TODO how to check for on Windows? self.extractor = 'streaming_extractor_music' try: call([self.extractor]) From 9ab67d5ffec1e6069e0cf2a46363e69c5ada59b6 Mon Sep 17 00:00:00 2001 From: inytar Date: Sat, 31 Dec 2016 14:12:28 -0500 Subject: [PATCH 1586/2280] Fix typos in absubmit documentation --- docs/plugins/absubmit.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index 5c9e6025e..d9dcd2c21 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -1,23 +1,23 @@ AcousticBrainz Submit Plugin ============================ -The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyse an audio file and calculate different acoustic properties of the audio, the plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration options is set to ``yes``. +The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyse an audio file and calculate different acoustic properties of the audio. The plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration option is set to ``yes``. Installation ------------ -The `absubmit` plugin requires the the `streaming_extractor_music`_ program to run. Its source can be found on `github`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used thier binary (see the AcousticBrainz `FAQ`_). +The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used thier binary (see the AcousticBrainz `FAQ`_). The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing: pip install requests -After installing both the extractor binary and request you can enable the plgin ``absubmit`` in your configuration (see :ref:`using-plugins`). +After installing both the extractor binary and requests you can enable the plugin ``absubmit`` in your configuration (see :ref:`using-plugins`). Configuration ------------- -To configute the plugin, make a ``absubmit:`` section in your configuration file. The available options are: +To configure the plugin, make a ``absubmit:`` section in your configuration file. The available options are: - **auto**: Analyze every file on import. Otherwise, you need to use the ``beet absubmit`` command explicitly. Default: ``no`` From 1a4c74ae5ea6b372be82afd5134bef5783d13a48 Mon Sep 17 00:00:00 2001 From: inytar Date: Sat, 31 Dec 2016 18:26:56 -0500 Subject: [PATCH 1587/2280] More spelling corrections for the absubmit plugin documentation --- docs/plugins/absubmit.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index d9dcd2c21..a22ec8860 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -1,12 +1,12 @@ AcousticBrainz Submit Plugin ============================ -The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyse an audio file and calculate different acoustic properties of the audio. The plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration option is set to ``yes``. +The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyze an audio file and calculate different acoustic properties of the audio. The plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration option is set to ``yes``. Installation ------------ -The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used thier binary (see the AcousticBrainz `FAQ`_). +The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used their binary (see the AcousticBrainz `FAQ`_). The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing: From b57b3f761e11e8fb000d797385a9f03d9a55b4fe Mon Sep 17 00:00:00 2001 From: inytar Date: Sat, 31 Dec 2016 18:27:27 -0500 Subject: [PATCH 1588/2280] Add header to the absubmit plugin --- beetsplug/absubmit.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index 807d6618c..ae3717470 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -1,3 +1,18 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2016, Pieter Mulder. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + """Calculate acoustic information and submit to AcousticBrainz. """ From 32dc808f716a534ccc1923451269d2ee2ea044f5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 1 Jan 2017 00:47:03 -0500 Subject: [PATCH 1589/2280] Changelog entry for #2342 (fix #2253) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 9be90c766..909315ff3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -10,6 +10,9 @@ Features: data source will fetch data for these fields when the next version of `python-musicbrainzngs`_ is released. Thanks to :user:`ibmibmibm`. :bug:`506` :bug:`507` :bug:`1547` :bug:`2333` +* A new :doc:`/plugins/absubmit` lets you run acoustic analysis software and + upload the results for others to use. Thanks to :user:`inytar`. :bug:`2253` + :bug:`2342` * :doc:`/plugins/random`: A new ``--time`` option lets you generate a random playlist that takes a given amount of time. Thanks to :user:`diomekes`. :bug:`2305` :bug:`2322` From 0d68a126095bbc6969516f63d99c8a9e44399e55 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Sun, 1 Jan 2017 04:36:48 -0500 Subject: [PATCH 1590/2280] Added alternate track field when importing from MusicBrains. Useful when importing multi-sided medias such as vinyls and cassettes. --- beets/autotag/__init__.py | 4 +++- beets/autotag/hooks.py | 3 ++- beets/autotag/mb.py | 5 +++-- beets/library.py | 7 ++++--- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 3e79a4498..eb3dae519 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -34,7 +34,7 @@ log = logging.getLogger('beets') def apply_item_metadata(item, track_info): """Set an item's metadata from its matched TrackInfo object. - """ + """ item.artist = track_info.artist item.artist_sort = track_info.artist_sort item.artist_credit = track_info.artist_credit @@ -157,3 +157,5 @@ def apply_metadata(album_info, mapping): item.composer = track_info.composer if track_info.arranger is not None: item.arranger = track_info.arranger + + item.alt_track_no = track_info.alt_track_no \ No newline at end of file diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 40db6e8d3..e64b42513 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -154,7 +154,7 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None, lyricist=None, composer=None, arranger=None): + media=None, lyricist=None, composer=None, arranger=None, alt_track_no=None): self.title = title self.track_id = track_id self.artist = artist @@ -173,6 +173,7 @@ class TrackInfo(object): self.lyricist = lyricist self.composer = composer self.arranger = arranger + self.alt_track_no = alt_track_no # As above, work around a bug in python-musicbrainz-ngs. def decode(self, codec='utf-8'): diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 55ecfc185..aad342e98 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -252,8 +252,8 @@ def album_info(release): all_tracks = medium['track-list'] if 'pregap' in medium: all_tracks.insert(0, medium['pregap']) - - for track in all_tracks: + + for track in all_tracks: # Basic information from the recording. index += 1 ti = track_info( @@ -265,6 +265,7 @@ def album_info(release): ) ti.disctitle = disctitle ti.media = format + ti.alt_track_no = track['number'] # Prefer track data, where present, over recording data. if track.get('title'): diff --git a/beets/library.py b/beets/library.py index 32176b68d..d9ffd38fd 100644 --- a/beets/library.py +++ b/beets/library.py @@ -322,7 +322,7 @@ class LibModel(dbcore.Model): funcs.update(plugins.template_funcs()) return funcs - def store(self, fields=None): + def store(self, fields=None): super(LibModel, self).store(fields) plugins.send('database_change', lib=self._db, model=self) @@ -423,9 +423,10 @@ class Item(LibModel): 'month': types.PaddedInt(2), 'day': types.PaddedInt(2), 'track': types.PaddedInt(2), + 'alt_track_no': types.STRING, 'tracktotal': types.PaddedInt(2), 'disc': types.PaddedInt(2), - 'disctotal': types.PaddedInt(2), + 'disctotal': types.PaddedInt(2), 'lyrics': types.STRING, 'comments': types.STRING, 'bpm': types.INTEGER, @@ -456,7 +457,7 @@ class Item(LibModel): 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), - 'initial_key': MusicalKey(), + 'initial_key': MusicalKey(), 'length': DurationType(), 'bitrate': types.ScaledInt(1000, u'kbps'), From 76b3212e781bcaba85713e5d5c24751adfebb0d2 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Sun, 1 Jan 2017 04:51:34 -0500 Subject: [PATCH 1591/2280] Added alternate track numbers for Discogs. --- beets/autotag/hooks.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index e64b42513..a9a35e635 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -154,7 +154,8 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None, lyricist=None, composer=None, arranger=None, alt_track_no=None): + media=None, lyricist=None, composer=None, arranger=None, + alt_track_no=None): self.title = title self.track_id = track_id self.artist = artist From 8a00791ecca90999b570f0d3f385d99f288413dd Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Sun, 1 Jan 2017 04:52:32 -0500 Subject: [PATCH 1592/2280] Oops. Forgot to actually stage the correct file. --- beetsplug/discogs.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index cf10a2a36..905358024 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -314,7 +314,9 @@ class DiscogsPlugin(BeetsPlugin): # Only real tracks have `position`. Otherwise, it's an index track. if track['position']: index += 1 - tracks.append(self.get_track_info(track, index)) + ti = self.get_track_info(track, index) + ti.alt_track_no = track['position'] + tracks.append(ti) else: index_tracks[index + 1] = track['title'] From 8cb6ff389252576d62983434db6736add02301ae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 1 Jan 2017 19:18:25 -0500 Subject: [PATCH 1593/2280] Simplify the example config I never meant for people to copy and paste this example---it's redundant and probably wrong---but lots of people do! Removing a few weird options makes the example clearer, I think, and will result in less-strange initial configs for people who do copy & paste. --- docs/guides/main.rst | 2 +- docs/reference/config.rst | 7 ------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 4ee2debed..7feacb6bf 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -137,7 +137,7 @@ favorite text editor. The file will start out empty, but here's good place to start:: directory: ~/music - library: ~/data/musiclibrary.blb + library: ~/data/musiclibrary.db Change that first path to a directory where you'd like to keep your music. Then, for ``library``, choose a good place to keep a database file that keeps an index diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 264cd6413..ffedb14d4 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -814,21 +814,14 @@ Example Here's an example file:: - library: /var/music.blb directory: /var/mp3 import: copy: yes write: yes - resume: ask - quiet_fallback: skip - timid: no log: beetslog.txt - ignore: .AppleDouble ._* *~ .DS_Store - ignore_hidden: yes art_filename: albumart plugins: bpd pluginpath: ~/beets/myplugins - threaded: yes ui: color: yes From 969e58841fe54a7abdb4180580b7077cc5bd088c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 1 Jan 2017 23:10:58 -0500 Subject: [PATCH 1594/2280] Improve changelog for #1992 --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 49a7a6245..c5113bdfa 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,8 +22,8 @@ Features: for files that already have it by default. You can override this behavior using a new ``force`` option. Thanks to :user:`SusannaMaria`. :bug:`2347` :bug:`2349` -* :doc:`/plugins/bpm`: Now uses ``import.write`` option to write tracks after - updating their BPM. +* :doc:`/plugins/bpm`: Now uses the ``import.write`` configuration option to + decide whether or not to write tracks after updating their BPM. :bug:`1992` Fixes: From e46a802ebba4b4f20e39718214913dda5f7df550 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20B?= Date: Mon, 2 Jan 2017 18:54:50 +0100 Subject: [PATCH 1595/2280] Add notes about AcousticBrainz requirements --- docs/plugins/absubmit.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index a22ec8860..9848e5fd3 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -21,9 +21,13 @@ To configure the plugin, make a ``absubmit:`` section in your configuration file - **auto**: Analyze every file on import. Otherwise, you need to use the ``beet absubmit`` command explicitly. Default: ``no`` -- **extractor**: The path to the `streaming_extractor_music`_ binary. +- **extractor**: The absolute path to the `streaming_extractor_music`_ binary. Default: search for the program in your ``$PATH`` +Notes +----- +MusicBrainz track id is needed to use AcousticBrainz. Check the `streaming_extractor_music`_ download page for more information. + .. _streaming_extractor_music: http://acousticbrainz.org/download .. _FAQ: http://acousticbrainz.org/faq .. _pip: http://www.pip-installer.org/ From b95c01fbea890334056f32f215a689aada1845fd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 13:41:48 -0500 Subject: [PATCH 1596/2280] Improve absumbit docs (c.f. #2364) --- docs/plugins/absubmit.rst | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index 9848e5fd3..a8cd1b380 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -1,19 +1,30 @@ AcousticBrainz Submit Plugin ============================ -The `absubmit` plugin uses the `streaming_extractor_music`_ program to analyze an audio file and calculate different acoustic properties of the audio. The plugin then uploads this metadata to the AcousticBrainz server. The plugin does this when calling the ``beet absumbit [QUERY]`` command or on importing if the `auto` configuration option is set to ``yes``. +The `absubmit` plugin lets you submit acoustic analysis results to the +`AcousticBrainz`_ server. Installation ------------ The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used their binary (see the AcousticBrainz `FAQ`_). -The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing: +The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing:: pip install requests After installing both the extractor binary and requests you can enable the plugin ``absubmit`` in your configuration (see :ref:`using-plugins`). +Submitting Data +--------------- + +Type:: + + beet absubmit [QUERY] + +to run the analysis program and upload its results. This will work on any +music with a MusicBrainz track ID attached. + Configuration ------------- @@ -24,12 +35,9 @@ To configure the plugin, make a ``absubmit:`` section in your configuration file - **extractor**: The absolute path to the `streaming_extractor_music`_ binary. Default: search for the program in your ``$PATH`` -Notes ------ -MusicBrainz track id is needed to use AcousticBrainz. Check the `streaming_extractor_music`_ download page for more information. - .. _streaming_extractor_music: http://acousticbrainz.org/download .. _FAQ: http://acousticbrainz.org/faq .. _pip: http://www.pip-installer.org/ .. _requests: http://docs.python-requests.org/en/master/ .. _github: https://github.com/MTG/essentia +.. _AcousticBrainz: https://acousticbrainz.org From 0975ee709b4924604a317690a01050151b0c8608 Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 2 Jan 2017 14:05:17 -0500 Subject: [PATCH 1597/2280] Absubmit fix failing to load distutils.spawn --- beetsplug/absubmit.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index ae3717470..95f3342ac 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -24,7 +24,7 @@ import os import subprocess import tempfile -import distutils +from distutils import spawn import requests from beets import plugins @@ -81,7 +81,7 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): pass # Get the executable location on the system, # needed to calculate the sha1 hash. - self.extractor = distutils.spawn.find_executable(self.extractor) + self.extractor = spawn.find_executable(self.extractor) # Calculate extractor hash. self.extractor_sha = hashlib.sha1() From a5aee3f677acf33dcea4825e3971fd7c422edcec Mon Sep 17 00:00:00 2001 From: inytar Date: Mon, 2 Jan 2017 14:05:59 -0500 Subject: [PATCH 1598/2280] Absubmit close temporary file Fix error when deleting the file under Windows --- beetsplug/absubmit.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index 95f3342ac..646f0fb84 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -131,6 +131,7 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): tmp_file, filename = tempfile.mkstemp(suffix='.json') try: # Close the file, so the extractor can overwrite it. + os.close(tmp_file) try: call([self.extractor, util.syspath(item.path), filename]) except ABSubmitError as e: From 869d0781d55c0d9c631f12e1009126ff18f18382 Mon Sep 17 00:00:00 2001 From: Pieter Mulder Date: Mon, 2 Jan 2017 14:34:00 -0500 Subject: [PATCH 1599/2280] Absubmit add section on skipped file by the plugin Add a section to the absubmit plugin documentation about files that are skipped by this plugin. --- docs/plugins/absubmit.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index a8cd1b380..6519e6159 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -25,6 +25,8 @@ Type:: to run the analysis program and upload its results. This will work on any music with a MusicBrainz track ID attached. +The plugin skips any file missing a MusicBrainz ID (MBID). This should rarely happen as Beets tags all files with their MBID on import. Files of in an unsupported encoding format are also skipped. `streaming_extractor_music`_ currently supports files with the following extensions: ``mp3``, ``ogg``, ``oga``, ``flac``, ``mp4``, ``m4a``, ``m4r``, ``m4b``, ``m4p``, ``aac``, ``wma``, ``asf``, ``mpc``, ``wv``, ``spx``, ``tta``, ``3g2``, ``aif``, ``aiff`` and ``ape``. + Configuration ------------- From 4711bf708bd184fd5369bca335941c1627141ab2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 15:59:14 -0500 Subject: [PATCH 1600/2280] Docs tweaks for #2365 --- docs/plugins/absubmit.rst | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index 6519e6159..665133c64 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -22,10 +22,14 @@ Type:: beet absubmit [QUERY] -to run the analysis program and upload its results. This will work on any -music with a MusicBrainz track ID attached. +to run the analysis program and upload its results. -The plugin skips any file missing a MusicBrainz ID (MBID). This should rarely happen as Beets tags all files with their MBID on import. Files of in an unsupported encoding format are also skipped. `streaming_extractor_music`_ currently supports files with the following extensions: ``mp3``, ``ogg``, ``oga``, ``flac``, ``mp4``, ``m4a``, ``m4r``, ``m4b``, ``m4p``, ``aac``, ``wma``, ``asf``, ``mpc``, ``wv``, ``spx``, ``tta``, ``3g2``, ``aif``, ``aiff`` and ``ape``. +The plugin works on music with a MusicBrainz track ID attached. The plugin +will also skip music that the analysis tool doesn't support. +`streaming_extractor_music`_ currently supports files with the extensions +``mp3``, ``ogg``, ``oga``, ``flac``, ``mp4``, ``m4a``, ``m4r``, ``m4b``, +``m4p``, ``aac``, ``wma``, ``asf``, ``mpc``, ``wv``, ``spx``, ``tta``, +``3g2``, ``aif``, ``aiff`` and ``ape``. Configuration ------------- From 3acd4480ffe8cabb19dd676caca7f699ed43ed8a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 18:29:37 -0500 Subject: [PATCH 1601/2280] Use a stdlib method for _to_epoch_time on py3 This also works around a bug in Python 3.6.0 on Windows: see #2358. --- beets/dbcore/query.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index d27897e69..470ca2ac6 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -503,9 +503,13 @@ def _to_epoch_time(date): """Convert a `datetime` object to an integer number of seconds since the (local) Unix epoch. """ - epoch = datetime.fromtimestamp(0) - delta = date - epoch - return int(delta.total_seconds()) + if hasattr(date, 'timestamp'): + # The `timestamp` method exists on Python 3.3+. + return int(date.timestamp()) + else: + epoch = datetime.fromtimestamp(0) + delta = date - epoch + return int(delta.total_seconds()) def _parse_periods(pattern): From bd340b29107200cde50529f83ec1680deb6831b5 Mon Sep 17 00:00:00 2001 From: Johnny Robeson Date: Mon, 2 Jan 2017 19:06:49 -0500 Subject: [PATCH 1602/2280] Replace Python 3.4 with 3.6 on Appveyor (#2358) Python 3.4 is quite old and offers little value on Windows. Closes #2344 --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 4f350b938..938d3a5a4 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -12,10 +12,10 @@ environment: matrix: - PYTHON: C:\Python27 TOX_ENV: py27-test - - PYTHON: C:\Python34 - TOX_ENV: py34-test - PYTHON: C:\Python35 TOX_ENV: py35-test + - PYTHON: C:\Python36 + TOX_ENV: py36-test # Install Tox for running tests. install: From f941fd42de2966686301ceb657bd10b89febea08 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 20:39:10 -0500 Subject: [PATCH 1603/2280] Always use SSL on servers that don't require SNI I did a little audit using the `openssl` command-line tool to find the servers that don't require SNI. Here's what I found: icbrainz.org: SNI images.weserv.nl: inconclusive, but docs say yes SNI coverartarchive.org: SNI webservice.fanart.tv: *no* SNI dbpedia.org: *no* SNI en.wikipedia.org: *no* SNI ws.audioscrobbler.com: *no* SNI api.microsofttranslator.com: *no* SNI In summary, *only* MusicBrainz and CoverArtArchive were found to require SNI. So I'm using SSL unconditionally on all the other sites. --- beetsplug/fetchart.py | 13 +++---------- beetsplug/lastimport.py | 6 +----- beetsplug/lyrics.py | 5 +---- 3 files changed, 5 insertions(+), 19 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 855a1df10..d87a5dc48 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -398,10 +398,7 @@ class GoogleImages(RemoteArtSource): class FanartTV(RemoteArtSource): """Art from fanart.tv requested using their API""" NAME = u"fanart.tv" - if util.SNI_SUPPORTED: - API_URL = 'https://webservice.fanart.tv/v3/' - else: - API_URL = 'https://webservice.fanart.tv/v3/' + API_URL = 'https://webservice.fanart.tv/v3/' API_ALBUMS = API_URL + 'music/albums/' PROJECT_KEY = '61a7d0ab4e67162b7a0c7c35915cd48e' @@ -494,12 +491,8 @@ class ITunesStore(RemoteArtSource): class Wikipedia(RemoteArtSource): NAME = u"Wikipedia (queried through DBpedia)" - if util.SNI_SUPPORTED: - DBPEDIA_URL = 'https://dbpedia.org/sparql' - WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' - else: - DBPEDIA_URL = 'http://dbpedia.org/sparql' - WIKIPEDIA_URL = 'http://en.wikipedia.org/w/api.php' + DBPEDIA_URL = 'https://dbpedia.org/sparql' + WIKIPEDIA_URL = 'https://en.wikipedia.org/w/api.php' SPARQL_QUERY = u'''PREFIX rdf: PREFIX dbpprop: PREFIX owl: diff --git a/beetsplug/lastimport.py b/beetsplug/lastimport.py index 238e447bc..d7b84b0aa 100644 --- a/beetsplug/lastimport.py +++ b/beetsplug/lastimport.py @@ -17,17 +17,13 @@ from __future__ import division, absolute_import, print_function import pylast from pylast import TopItem, _extract, _number -from beets import util from beets import ui from beets import dbcore from beets import config from beets import plugins from beets.dbcore import types -if util.SNI_SUPPORTED: - API_URL = 'https://ws.audioscrobbler.com/2.0/' -else: - API_URL = 'http://ws.audioscrobbler.com/2.0/' +API_URL = 'https://ws.audioscrobbler.com/2.0/' class LastImportPlugin(plugins.BeetsPlugin): diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index feab2180e..bce95759e 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -50,7 +50,6 @@ except ImportError: pass from beets import plugins -from beets import util from beets import ui @@ -646,12 +645,10 @@ class LyricsPlugin(plugins.BeetsPlugin): for source in sources] def get_bing_access_token(self): - url = "{0}api.microsofttranslator.com" params = { 'client_id': 'beets', 'client_secret': self.config['bing_client_secret'], - 'scope': url.format('https://') if util.SNI_SUPPORTED - else url.format('http://'), + 'scope': "https://api.microsofttranslator.com", 'grant_type': 'client_credentials', } From 33a8e81f08641b4dee8a1767ab45646271222f58 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 20:49:12 -0500 Subject: [PATCH 1604/2280] Simplify test changes We don't need quite so many checks now that SSL isn't conditional most of the time. --- test/test_art.py | 40 +++++++++++++++------------------------- 1 file changed, 15 insertions(+), 25 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index bc3319cc2..50ff26b00 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -67,40 +67,33 @@ class FetchImageHelper(_common.TestCase): class FetchImageTest(FetchImageHelper, UseThePlugin): - URL = '{0}example.com/test.jpg' + URL = 'http://example.com/test.jpg' def setUp(self): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) self.extra = {'maxwidth': 0} - self.candidate = fetchart.Candidate(logger, - url=self.URL.format('http://')) + self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): - self.mock_response(self.URL.format('http://'), 'image/watercolour') - self.mock_response(self.URL.format('https://'), 'image/watercolour') + self.mock_response(self.URL, 'image/watercolour') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): - self.mock_response(self.URL.format('http://'), 'image/jpeg') - self.mock_response(self.URL.format('https://')) + self.mock_response(self.URL, 'image/jpeg') self.source.fetch_image(self.candidate, self.extra) self.assertNotEqual(self.candidate.path, None) def test_extension_set_by_content_type(self): - self.mock_response(self.URL.format('http://'), 'image/png') - self.mock_response(self.URL.format('https://'), 'image/png') + self.mock_response(self.URL, 'image/png') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) def test_does_not_rely_on_server_content_type(self): - self.mock_response(self.URL.format('http://'), - 'image/jpeg', 'image/png') - self.mock_response(self.URL.format('https://'), - 'image/jpeg', 'imsge/png') + self.mock_response(self.URL, 'image/jpeg', 'image/png') self.source.fetch_image(self.candidate, self.extra) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -157,9 +150,9 @@ class FSArtTest(UseThePlugin): class CombinedTest(FetchImageHelper, UseThePlugin): ASIN = 'xxxx' MBID = 'releaseid' - AMAZON_URL = 'images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ + AMAZON_URL = 'http://images.amazon.com/images/P/{0}.01.LZZZZZZZ.jpg' \ .format(ASIN) - AAO_URL = 'www.albumart.org/index_detail.php?asin={0}' \ + AAO_URL = 'http://www.albumart.org/index_detail.php?asin={0}' \ .format(ASIN) CAA_URL = 'coverartarchive.org/release/{0}/front' \ .format(MBID) @@ -170,7 +163,7 @@ class CombinedTest(FetchImageHelper, UseThePlugin): os.mkdir(self.dpath) def test_main_interface_returns_amazon_art(self): - self.mock_response("http://" + self.AMAZON_URL) + self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, None) self.assertIsNotNone(candidate) @@ -182,34 +175,31 @@ class CombinedTest(FetchImageHelper, UseThePlugin): def test_main_interface_gives_precedence_to_fs_art(self): _common.touch(os.path.join(self.dpath, b'art.jpg')) - self.mock_response("http://" + self.AMAZON_URL) + self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_main_interface_falls_back_to_amazon(self): - self.mock_response("http://" + self.AMAZON_URL) + self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) candidate = self.plugin.art_for_album(album, [self.dpath]) self.assertIsNotNone(candidate) self.assertFalse(candidate.path.startswith(self.dpath)) def test_main_interface_tries_amazon_before_aao(self): - self.mock_response("http://" + self.AMAZON_URL) + self.mock_response(self.AMAZON_URL) album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) self.assertEqual(len(responses.calls), 1) - self.assertEqual(responses.calls[0].request.url, - "http://" + self.AMAZON_URL) + self.assertEqual(responses.calls[0].request.url, self.AMAZON_URL) def test_main_interface_falls_back_to_aao(self): - self.mock_response("http://" + self.AMAZON_URL, - content_type='text/html') + self.mock_response(self.AMAZON_URL, content_type='text/html') album = _common.Bag(asin=self.ASIN) self.plugin.art_for_album(album, [self.dpath]) - self.assertEqual(responses.calls[-1].request.url, - "http://" + self.AAO_URL) + self.assertEqual(responses.calls[-1].request.url, self.AAO_URL) def test_main_interface_uses_caa_when_mbid_available(self): self.mock_response("http://" + self.CAA_URL) From 9e76c839f6869dd154c99b3cbe15c9a93d0b5783 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 20:57:50 -0500 Subject: [PATCH 1605/2280] Changelog for #2307 Close #2247, close #2243, close #2245, close #2244, close #2248. --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index c5113bdfa..102154bbc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,9 @@ Features: Fixes: +* We now use SSL to access Web services whenever possible. That includes + MusicBrainz itself, several album art sources, some lyrics sources, and + other servers. Thanks to :user:`tigranl`. :bug:`2307` * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` * :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. :bug:`2351` From d389ac15e156de8abd67b7a680000bf8788f2ccd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 2 Jan 2017 21:00:01 -0500 Subject: [PATCH 1606/2280] Use HTTPS for MS translator API (from #2247) --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index a93b0f7a3..92abe377e 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -762,7 +762,7 @@ class LyricsPlugin(plugins.BeetsPlugin): if self.bing_auth_token: # Extract unique lines to limit API request size per song text_lines = set(text.split('\n')) - url = ('http://api.microsofttranslator.com/v2/Http.svc/' + url = ('https://api.microsofttranslator.com/v2/Http.svc/' 'Translate?text=%s&to=%s' % ('|'.join(text_lines), to_lang)) r = requests.get(url, headers={"Authorization ": self.bing_auth_token}) From 8d97257647ab313805b5583522316c3ce4be109a Mon Sep 17 00:00:00 2001 From: diomekes Date: Tue, 3 Jan 2017 22:10:35 -0500 Subject: [PATCH 1607/2280] use shlex_split, clean up code and docs --- beetsplug/play.py | 58 +++++++++++++++++++++++-------------------- docs/plugins/play.rst | 2 +- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 2f708e5cb..032894777 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -32,13 +32,19 @@ import subprocess ARGS_MARKER = '$args' -def play(command_str, paths, open_args, keep_open=False): +def play(command_str, selection, paths, open_args, log, item_type='track', + keep_open=False): """Play items in paths with command_str and optional arguments. If keep_open, return to beets, otherwise exit once command runs. """ + # Print number of tracks or albums to be played, log command to be run. + item_type += 's' if len(selection) > 1 else '' + ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) + log.debug(u'executing command: {} {!r}', command_str, open_args) + try: if keep_open: - command = command_str.split() + command = util.shlex_split(command_str) command = command + open_args subprocess.call(command) else: @@ -81,8 +87,8 @@ class PlayPlugin(BeetsPlugin): return [play_command] def _play_command(self, lib, opts, args): - """The CLI command function for `beet play`. Creates a list of paths - from query, determines if tracks or albums are to be played. + """The CLI command function for `beet play`. Create a list of paths + from query, determine if tracks or albums are to be played. """ use_folders = config['play']['use_folders'].get(bool) relative_to = config['play']['relative_to'].get() @@ -117,17 +123,17 @@ class PlayPlugin(BeetsPlugin): return open_args = self._playlist_or_paths(paths) - command_str = self._create_command_str(opts.args) + command_str = self._command_str(opts.args) - # If user aborts due to long playlist: - cancel = self._print_info(selection, command_str, open_args, item_type) + # Check if the selection exceeds configured threshold. If True, + # cancel, otherwise proceed with play command. + if not self._exceeds_threshold(selection, command_str, open_args, + item_type): + play(command_str, selection, paths, open_args, self._log, + item_type) - # Otherwise proceed with play command. - if not cancel: - play(command_str, paths, open_args) - - def _create_command_str(self, args=None): - """Creates a command string from the config command and optional args. + def _command_str(self, args=None): + """Create a command string from the config command and optional args. """ command_str = config['play']['command'].get() if not command_str: @@ -143,17 +149,18 @@ class PlayPlugin(BeetsPlugin): return command_str.replace(" " + ARGS_MARKER, "") def _playlist_or_paths(self, paths): - """Returns either the raw paths of items or a playlist of the items. + """Return either the raw paths of items or a playlist of the items. """ - raw = config['play']['raw'].get(bool) - if raw: + if config['play']['raw']: return paths else: return [self._create_tmp_playlist(paths)] - def _print_info(self, selection, command_str, open_args, - item_type='track'): - """Prompts user whether to continue if playlist exceeds threshold. + def _exceeds_threshold(self, selection, command_str, open_args, + item_type='track'): + """Prompt user whether to continue if playlist exceeds threshold. If + this returns True, the tracks or albums are not played, if False, + the play command is run. """ warning_threshold = config['play']['warning_threshold'].get(int) # We use -2 as a default value for warning_threshold to detect if it is @@ -168,7 +175,6 @@ class PlayPlugin(BeetsPlugin): warning_threshold = config['play']['warning_treshold'].get(int) # Warn user before playing any huge playlists. - item_type += 's' if len(selection) > 1 else '' if warning_threshold and len(selection) > warning_threshold: ui.print_(ui.colorize( 'text_warning', @@ -178,9 +184,7 @@ class PlayPlugin(BeetsPlugin): if ui.input_options((u'Continue', u'Abort')) == 'a': return True - # Print number of tracks or albums to be played, log command to be run. - ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type)) - self._log.debug(u'executing command: {} {!r}', command_str, open_args) + return False def _create_tmp_playlist(self, paths_list): """Create a temporary .m3u file. Return the filename. @@ -203,8 +207,8 @@ class PlayPlugin(BeetsPlugin): paths = [item.path for item in selection] open_args = self._playlist_or_paths(paths) - command_str = self._create_command_str() - cancel = self._print_info(selection, command_str, open_args) + command_str = self._command_str() - if not cancel: - play(command_str, paths, open_args, keep_open=True) + if not self._exceeds_threshold(selection, command_str, open_args): + play(command_str, selection, paths, open_args, self._log, + keep_open=True) diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 6a34cda57..9b9110bde 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -36,7 +36,7 @@ The `play` plugin can also be invoked during an import. If enabled, the plugin adds a `plaY` option to the prompt, so pressing `y` will execute the configured command and play the items currently being imported. -Once you exit your configured player, you will be returned to the import +Once the configured command exits, you will be returned to the import decision prompt. If your player is configured to run in the background (in a client/server setup), the music will play until you choose to stop it, and the import operation continues immediately. From efbd58cd556999617736e09e0a58cfd61c5730ec Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Fri, 6 Jan 2017 11:44:32 +0100 Subject: [PATCH 1608/2280] embyupdate: fix bug that config for password and api is needed even if it only used api key it needed the password key. this is fixed now. --- beetsplug/embyupdate.py | 10 +++++++++- docs/changelog.rst | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 3af285973..6f74b4452 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -6,6 +6,7 @@ host: localhost port: 8096 username: user + apikey: apikey password: password """ from __future__ import division, absolute_import, print_function @@ -150,7 +151,9 @@ class EmbyUpdate(BeetsPlugin): # Adding defaults. config['emby'].add({ u'host': u'http://localhost', - u'port': 8096 + u'port': 8096, + u'apikey': None, + u'password': None }) self.register_listener('database_change', self.listen_for_db_change) @@ -171,6 +174,11 @@ class EmbyUpdate(BeetsPlugin): password = config['emby']['password'].get() token = config['emby']['apikey'].get() + # Check if at least a apikey or password is given. + if not any([password, token]): + self._log.warning(u'Provide at least Emby password or apikey.') + return + # Get user information from the Emby API. user = get_user(host, port, username) if not user: diff --git a/docs/changelog.rst b/docs/changelog.rst index 102154bbc..5a3451017 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -44,6 +44,7 @@ Fixes: :bug:`2302` * :doc:`/plugins/lyrics`: The plugin now reports a beets-specific User-Agent header when requesting lyrics. :bug:`2357` +* :doc:`/plugins/embyupdate`: Fix a bug that apikey and password is needed in config. For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 8d613425fd6b4125399f18fe701b007738c85645 Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 6 Jan 2017 23:46:16 -0500 Subject: [PATCH 1609/2280] small docstring rewrite --- beetsplug/play.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 032894777..af658114b 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -158,9 +158,8 @@ class PlayPlugin(BeetsPlugin): def _exceeds_threshold(self, selection, command_str, open_args, item_type='track'): - """Prompt user whether to continue if playlist exceeds threshold. If - this returns True, the tracks or albums are not played, if False, - the play command is run. + """Prompt user whether to abort if playlist exceeds threshold. If + True, cancel playback. If False, execute play command. """ warning_threshold = config['play']['warning_threshold'].get(int) # We use -2 as a default value for warning_threshold to detect if it is From 5ee89666b6b8e2a8f3be1a004e33d8b309e90fb5 Mon Sep 17 00:00:00 2001 From: diomekes Date: Sat, 7 Jan 2017 09:54:54 -0500 Subject: [PATCH 1610/2280] fix typo in config docs --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 8f009fc3f..8e43e2dd7 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -229,7 +229,7 @@ Default sort order to use when fetching items from the database. Defaults to sort_album ~~~~~~~~~~ -Default sort order to use when fetching items from the database. Defaults to +Default sort order to use when fetching albums from the database. Defaults to ``albumartist+ album+``. Explicit sort orders override this default. .. _sort_case_insensitive: From d992221853e7b332da9cdd2c06c648b9b78dca9e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Jan 2017 17:03:30 -0500 Subject: [PATCH 1611/2280] Changelog for #2360 (fix #2008) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5a3451017..28605fba2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ Features: :bug:`2349` * :doc:`/plugins/bpm`: Now uses the ``import.write`` configuration option to decide whether or not to write tracks after updating their BPM. :bug:`1992` +* :doc:`/plugins/play`: The plugin now provides an importer prompt choice to + play the music you're about to import. Thanks to :user:`diomekes`. + :bug:`2008` :bug:`2360` Fixes: From c9ec5e411ca67880224f6491fed9548f58aba1e8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Jan 2017 17:07:01 -0500 Subject: [PATCH 1612/2280] A little fiddling with embyupdate Clean up some wording w/r/t efbd58cd556999617736e09e0a58cfd61c5730ec. --- beetsplug/embyupdate.py | 2 +- docs/changelog.rst | 3 ++- docs/plugins/embyupdate.rst | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/beetsplug/embyupdate.py b/beetsplug/embyupdate.py index 6f74b4452..5c731954b 100644 --- a/beetsplug/embyupdate.py +++ b/beetsplug/embyupdate.py @@ -153,7 +153,7 @@ class EmbyUpdate(BeetsPlugin): u'host': u'http://localhost', u'port': 8096, u'apikey': None, - u'password': None + u'password': None, }) self.register_listener('database_change', self.listen_for_db_change) diff --git a/docs/changelog.rst b/docs/changelog.rst index 28605fba2..69ee77e8c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -47,7 +47,8 @@ Fixes: :bug:`2302` * :doc:`/plugins/lyrics`: The plugin now reports a beets-specific User-Agent header when requesting lyrics. :bug:`2357` -* :doc:`/plugins/embyupdate`: Fix a bug that apikey and password is needed in config. +* :doc:`/plugins/embyupdate`: The plugin now checks whether an API key or a + password is provided in the configuration. For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. diff --git a/docs/plugins/embyupdate.rst b/docs/plugins/embyupdate.rst index 8dbb7c1db..00373b98c 100644 --- a/docs/plugins/embyupdate.rst +++ b/docs/plugins/embyupdate.rst @@ -3,7 +3,7 @@ EmbyUpdate Plugin ``embyupdate`` is a plugin that lets you automatically update `Emby`_'s library whenever you change your beets library. -To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll probably want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: +To use ``embyupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). Then, you'll want to configure the specifics of your Emby server. You can do that using an ``emby:`` section in your ``config.yaml``, which looks like this:: emby: host: localhost From 6b9d766082ad1f0a96d22430c3659a9c182f7f67 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Jan 2017 17:09:51 -0500 Subject: [PATCH 1613/2280] Remove compatibility with misspelled config option This has been hanging around long enough; it's about time to drop the old name. --- beetsplug/play.py | 14 +------------- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index af658114b..636d98d46 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -64,9 +64,7 @@ class PlayPlugin(BeetsPlugin): 'use_folders': False, 'relative_to': None, 'raw': False, - # Backwards compatibility. See #1803 and line 155 - 'warning_threshold': -2, - 'warning_treshold': 100, + 'warning_threshold': 100, }) self.register_listener('before_choose_candidate', @@ -162,16 +160,6 @@ class PlayPlugin(BeetsPlugin): True, cancel playback. If False, execute play command. """ warning_threshold = config['play']['warning_threshold'].get(int) - # We use -2 as a default value for warning_threshold to detect if it is - # set or not. We can't use a falsey value because it would have an - # actual meaning in the configuration of this plugin, and we do not use - # -1 because some people might use it as a value to obtain no warning, - # which wouldn't be that bad of a practice. - if warning_threshold == -2: - # if warning_threshold has not been set by user, look for - # warning_treshold, to preserve backwards compatibility. See #1803. - # warning_treshold has the correct default value of 100. - warning_threshold = config['play']['warning_treshold'].get(int) # Warn user before playing any huge playlists. if warning_threshold and len(selection) > warning_threshold: diff --git a/docs/changelog.rst b/docs/changelog.rst index 69ee77e8c..68b3e12e3 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -49,6 +49,8 @@ Fixes: header when requesting lyrics. :bug:`2357` * :doc:`/plugins/embyupdate`: The plugin now checks whether an API key or a password is provided in the configuration. +* :doc:`/plugins/play`: The misspelled configuration option + ``warning_treshold`` is no longer supported. For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. From 0b5b20d7990d2aec879e7c03cb4c6f8257054435 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Jan 2017 17:15:13 -0500 Subject: [PATCH 1614/2280] Robust import of distutils submodule (fix #2376) This would fail if the `spawn` module in the `distutils` package was not already imported somewhere else. --- beetsplug/absubmit.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index ae3717470..e96d4f033 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -24,7 +24,7 @@ import os import subprocess import tempfile -import distutils +from distutils.spawn import find_executable import requests from beets import plugins @@ -79,9 +79,10 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): # Extractor found, will exit with an error if not called with # the correct amount of arguments. pass - # Get the executable location on the system, - # needed to calculate the sha1 hash. - self.extractor = distutils.spawn.find_executable(self.extractor) + + # Get the executable location on the system, which we need + # to calculate the SHA-1 hash. + self.extractor = find_executable(self.extractor) # Calculate extractor hash. self.extractor_sha = hashlib.sha1() From e5e710033cfb971e76fc03fca7a32e818b94e514 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Jan 2017 17:19:02 -0500 Subject: [PATCH 1615/2280] Remove old test for misspelled config option See 6b9d766, which removed the option. --- test/test_play.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/test/test_play.py b/test/test_play.py index 9d66d7466..86fef99a9 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -115,15 +115,6 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_not_called() - def test_warning_threshold_backwards_compat(self, open_mock): - self.config['play']['warning_treshold'] = 1 - self.add_item(title=u'another NiceTitle') - - with control_stdin("a"): - self.run_command(u'play', u'nice') - - open_mock.assert_not_called() - def test_command_failed(self, open_mock): open_mock.side_effect = OSError(u"some reason") From 2cef4703f8f9c20e872404e62b9df8ca39f91968 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Jan 2017 10:37:37 -0500 Subject: [PATCH 1616/2280] Prepare 1.4.3 changelog for release --- docs/changelog.rst | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 68b3e12e3..6910643dc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,15 @@ Changelog 1.4.3 (in development) ---------------------- -Features: +Happy new year! This new version includes a cornucopia of new features from +contributors, including new tags related to classical music and a new +:doc:`/plugins/absubmit` for performing acoustic analysis on your music. The +:doc:`/plugins/random` has a new mode that lets you generate time-limited +music---for example, you might generate a random playlist that lasts the +perfect length for your walk to work. We also access as many Web services as +possible over secure connections now---HTTPS everywhere! + +The most visible new features are: * We now support the composer, lyricist, and arranger tags. The MusicBrainz data source will fetch data for these fields when the next version of @@ -13,26 +21,29 @@ Features: * A new :doc:`/plugins/absubmit` lets you run acoustic analysis software and upload the results for others to use. Thanks to :user:`inytar`. :bug:`2253` :bug:`2342` +* :doc:`/plugins/play`: The plugin now provides an importer prompt choice to + play the music you're about to import. Thanks to :user:`diomekes`. + :bug:`2008` :bug:`2360` +* We now use SSL to access Web services whenever possible. That includes + MusicBrainz itself, several album art sources, some lyrics sources, and + other servers. Thanks to :user:`tigranl`. :bug:`2307` * :doc:`/plugins/random`: A new ``--time`` option lets you generate a random playlist that takes a given amount of time. Thanks to :user:`diomekes`. :bug:`2305` :bug:`2322` -* :doc:`/plugins/zero`: Added ``zero`` command to manually trigger the zero + +Some smaller new features: + +* :doc:`/plugins/zero`: A new ``zero`` command manually triggers the zero plugin. Thanks to :user:`SJoshBrown`. :bug:`2274` :bug:`2329` * :doc:`/plugins/acousticbrainz`: The plugin will avoid re-downloading data for files that already have it by default. You can override this behavior using a new ``force`` option. Thanks to :user:`SusannaMaria`. :bug:`2347` :bug:`2349` -* :doc:`/plugins/bpm`: Now uses the ``import.write`` configuration option to - decide whether or not to write tracks after updating their BPM. :bug:`1992` -* :doc:`/plugins/play`: The plugin now provides an importer prompt choice to - play the music you're about to import. Thanks to :user:`diomekes`. - :bug:`2008` :bug:`2360` +* :doc:`/plugins/bpm`: The ``import.write`` configuration option now + decides whether or not to write tracks after updating their BPM. :bug:`1992` -Fixes: +And the fixes: -* We now use SSL to access Web services whenever possible. That includes - MusicBrainz itself, several album art sources, some lyrics sources, and - other servers. Thanks to :user:`tigranl`. :bug:`2307` * :doc:`/plugins/bpd`: Fix a crash on non-ASCII MPD commands. :bug:`2332` * :doc:`/plugins/scrub`: Avoid a crash when files cannot be read or written. :bug:`2351` @@ -42,8 +53,8 @@ Fixes: filesystem. :bug:`2353` * :doc:`/plugins/discogs`: Improve the handling of releases that contain subtracks. :bug:`2318` -* :doc:`/plugins/discogs`: Fix a crash when a release did not contain Format - information, and increased robustness when other fields are missing. +* :doc:`/plugins/discogs`: Fix a crash when a release does not contain format + information, and increase robustness when other fields are missing. :bug:`2302` * :doc:`/plugins/lyrics`: The plugin now reports a beets-specific User-Agent header when requesting lyrics. :bug:`2357` @@ -52,7 +63,11 @@ Fixes: * :doc:`/plugins/play`: The misspelled configuration option ``warning_treshold`` is no longer supported. -For plugin developers: new importer prompt choices (see :ref:`append_prompt_choices`), you can now provide new candidates for the user to consider. +For plugin developers: when providing new importer prompt choices (see +:ref:`append_prompt_choices`), you can now provide new candidates for the user +to consider. For example, you might provide an alternative strategy for +picking between the available alternatives or for looking up a release on +MusicBrainz. 1.4.2 (December 16, 2016) From 497c3076d2f9a4ed2221cb29b028f5f4fabe0671 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Jan 2017 10:38:06 -0500 Subject: [PATCH 1617/2280] Add 1.4.3 release date --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 6910643dc..354aae23e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.3 (in development) ----------------------- +1.4.3 (January 9, 2017) +----------------------- Happy new year! This new version includes a cornucopia of new features from contributors, including new tags related to classical music and a new From 0bd6062ee9dd53dee26fa29b5c08285fff711081 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Jan 2017 10:40:06 -0500 Subject: [PATCH 1618/2280] Version bump: 1.4.4 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 5d82b05f7..964d2592c 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.3' +__version__ = u'1.4.4' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 354aae23e..f2c7d803c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.4 (in development) +---------------------- + +Changelog goes here! + + 1.4.3 (January 9, 2017) ----------------------- diff --git a/docs/conf.py b/docs/conf.py index 99771e7b1..9573b2fba 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.3' +release = '1.4.4' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index f88fe28b6..35131cb55 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.3', + version='1.4.4', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From b9500c379ee1a18dfa3bfc2d41579d200c2c9dea Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Jan 2017 12:44:53 -0500 Subject: [PATCH 1619/2280] Remove some unnecessary imports in mediafile.py --- beets/mediafile.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 0f595a36a..9e3f81db3 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -36,15 +36,11 @@ data from the tags. In turn ``MediaField`` uses a number of from __future__ import division, absolute_import, print_function import mutagen -import mutagen.mp3 import mutagen.id3 -import mutagen.oggopus -import mutagen.oggvorbis import mutagen.mp4 import mutagen.flac -import mutagen.monkeysaudio import mutagen.asf -import mutagen.aiff + import codecs import datetime import re From f7742939ef65767dc3fa98ca5a57e4eb53f8de6f Mon Sep 17 00:00:00 2001 From: Boris Pruessmann Date: Sun, 8 Jan 2017 19:47:59 +0100 Subject: [PATCH 1620/2280] Support for DSF files --- beets/mediafile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 9e3f81db3..59959b8f5 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -40,7 +40,6 @@ import mutagen.id3 import mutagen.mp4 import mutagen.flac import mutagen.asf - import codecs import datetime import re @@ -73,6 +72,7 @@ TYPES = { 'mpc': 'Musepack', 'asf': 'Windows Media', 'aiff': 'AIFF', + 'dsf': 'DSD Stream File', } PREFERRED_IMAGE_EXTENSIONS = {'jpeg': 'jpg'} @@ -728,7 +728,7 @@ class MP4ImageStorageStyle(MP4ListStorageStyle): class MP3StorageStyle(StorageStyle): """Store data in ID3 frames. """ - formats = ['MP3', 'AIFF'] + formats = ['MP3', 'AIFF', 'DSF'] def __init__(self, key, id3_lang=None, **kwargs): """Create a new ID3 storage style. `id3_lang` is the value for @@ -1475,6 +1475,8 @@ class MediaFile(object): self.type = 'asf' elif type(self.mgfile).__name__ == 'AIFF': self.type = 'aiff' + elif type(self.mgfile).__name__ == 'DSF': + self.type = 'dsf' else: raise FileTypeError(path, type(self.mgfile).__name__) From 1e10e62d8294770445ce34017b203d87b1ccc113 Mon Sep 17 00:00:00 2001 From: Boris Pruessmann Date: Mon, 9 Jan 2017 18:32:11 +0100 Subject: [PATCH 1621/2280] Added DSF to test_mediafile --- test/rsrc/empty.dsf | Bin 0 -> 4188 bytes test/rsrc/full.dsf | Bin 0 -> 113475 bytes test/rsrc/unparseable.dsf | Bin 0 -> 4208 bytes test/test_mediafile.py | 12 ++++++++++++ 4 files changed, 12 insertions(+) create mode 100644 test/rsrc/empty.dsf create mode 100644 test/rsrc/full.dsf create mode 100644 test/rsrc/unparseable.dsf diff --git a/test/rsrc/empty.dsf b/test/rsrc/empty.dsf new file mode 100644 index 0000000000000000000000000000000000000000..4cbceb3c97977747977423c92b2e39e7f7a7d192 GIT binary patch literal 4188 zcmZ<>c2SUFfPfeQ2n{3Ca!V9Upd3ad8q5~dW&qPraR#W~l*E!m9w-|oHA;_$z-S1J lhQMeDjE2By2#kinXb6mkz-S1JhQMeDjE2By2n^p4003D!1tkCg literal 0 HcmV?d00001 diff --git a/test/rsrc/full.dsf b/test/rsrc/full.dsf new file mode 100644 index 0000000000000000000000000000000000000000..a90e6946fc44cd97a56c9846cbea855201a22808 GIT binary patch literal 113475 zcmZ<>c2SUFfB@&+j9^C0P6(ZrTcThB7GYq3h%hiPF+ebbQW#jQ;SN-R0EA9SEJ@^n z>W7GolA|Fo8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8Umvs zFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF z0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71* zAut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@? z8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*O zqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8Umvs zFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF z0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71* zAut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@? z8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*O zqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8Umvs zFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF0;3@?8UmvsFd71*Aut*OqaiRF z0;3@?8UmvsFd71*U^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ON zU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU z1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0q zLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$( zGz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!n zMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ON zU^E0qLtr!nMnhmU1V%$(6pV(zXb6mkz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeD zjE2By2#kinXb6mkz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeDjE2By2#kinXb6mk zz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeDjE2By2#kinXb6mkz-S1JhQMeDjE2By z2n@Cm@N_X|0lA4eHpDZ;h=GBDm4Sgdtu!YmB*4{>fq{XWfq}UsBUK@>s3fzvB*f9j ziGhKE3nrM8RGJ$S2@eBc(&kHpwy(qu5ATuvL#MvLD1SXuEpIeY$oLUs(?C*zUae8WAQEG^@ZvfOZ z!;pYbWQXM>CZ*;$`}=~75@cXtPR&ba0Qn+0KQ}iuucSCM*e8U6fq@@MDyOn2Gr2g_ z&C`W}fx()AA)}c2SUFfPex42pt2Z({f7`OdvuGj7T(?EvO9_14}{mq$HLk@<7>O@lj$l1V%$( wGz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtt2kfTxQw3)q8PU=mCK0RAopa{vGU literal 0 HcmV?d00001 diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 5fcb14187..2adb57c85 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -887,6 +887,18 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): } +class DSFTest(ReadWriteTestBase, unittest.TestCase): + extension = 'dsf' + audio_properties = { + 'length': 0.01, + 'bitrate': 11289600, + 'format': u'DSD Stream File', + 'samplerate': 5644800, + 'bitdepth': 1, + 'channels': 2, + } + + class MediaFieldTest(unittest.TestCase): def test_properties_from_fields(self): From a2d37dd5886dc23f652a13d7faaba4301d8451c4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Jan 2017 13:02:28 -0500 Subject: [PATCH 1622/2280] Document how to add tests for a new format (#2379) --- test/test_mediafile.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 5fcb14187..a948fe31f 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -294,8 +294,20 @@ class GenreListTestMixin(object): class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, _common.TempDirMixin): - """Test writing and reading tags. Subclasses must set ``extension`` and - ``audio_properties``. + """Test writing and reading tags. Subclasses must set ``extension`` + and ``audio_properties``. + + The basic tests for all audio formats encompass three files provided + in our `rsrc` folder: `full.*`, `empty.*`, and `unparseable.*`. + Respectively, they should contain a full slate of common fields + listed in `full_initial_tags` below; no fields contents at all; and + an unparseable release date field. + + To add support for a new file format to MediaFile, add these three + files and then create a `ReadWriteTestBase` subclass by copying n' + pasting one of the existing subclasses below. You will want to + update the `format` field in that subclass, and you will probably + need to fiddle with the `bitrate` and other format-specific fields. """ full_initial_tags = { @@ -554,6 +566,9 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, self.assertEqual(mediafile.disctotal, None) def test_unparseable_date(self): + """The `unparseable.*` fixture should not crash but should return None + for all parts of the release date. + """ mediafile = self._mediafile_fixture('unparseable') self.assertIsNone(mediafile.date) From e0a4dc67a85be25156f8012be83faff2cf60cb9a Mon Sep 17 00:00:00 2001 From: Boris Pruessmann Date: Tue, 10 Jan 2017 11:06:57 +0100 Subject: [PATCH 1623/2280] Test improvements for DSF. - Fixed unparseable.dsf - Added DSF feature detection to test_mediafile.py --- test/rsrc/unparseable.dsf | Bin 4208 -> 5243 bytes test/test_mediafile.py | 10 +++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/test/rsrc/unparseable.dsf b/test/rsrc/unparseable.dsf index c5463d5c181ca3261180d4fdedde9888bbc0c325..3b6292e32df6494bca8782c8795627babe575f50 100644 GIT binary patch delta 52 zcmeyM@LPk=CD=tlh5-VqMKnIpnTAFT5{Lc&k DAPEZ_ delta 36 gcmeyZ@j-#lCD=tlh5-T!1UB-83Ggs*LAW3i0E^276aWAK diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 2adb57c85..fa55d3cdb 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -886,8 +886,16 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): 'channels': 1, } +try: + import mutagen.dsf +except: + HAVE_DSF = False +else: + HAVE_DSF = True -class DSFTest(ReadWriteTestBase, unittest.TestCase): +@unittest.skipIf(not HAVE_DSF, "mutagen < 1.37") +class DSFTest(ReadWriteTestBase, + ExtendedImageStructureTestMixin, unittest.TestCase): extension = 'dsf' audio_properties = { 'length': 0.01, From 2706339a838eca42c23c3da3d991bc2989b9495b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 12:22:30 -0500 Subject: [PATCH 1624/2280] Fix #2381: mpdupdate on Python 3 Communicate bytes over the socket, obvi. --- beetsplug/mpdupdate.py | 22 +++++++++++----------- docs/changelog.rst | 4 +++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/beetsplug/mpdupdate.py b/beetsplug/mpdupdate.py index 6c39375be..6ecc92131 100644 --- a/beetsplug/mpdupdate.py +++ b/beetsplug/mpdupdate.py @@ -35,14 +35,14 @@ import six # easier. class BufferedSocket(object): """Socket abstraction that allows reading by line.""" - def __init__(self, host, port, sep='\n'): + def __init__(self, host, port, sep=b'\n'): if host[0] in ['/', '~']: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(os.path.expanduser(host)) else: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) - self.buf = '' + self.buf = b'' self.sep = sep def readline(self): @@ -51,11 +51,11 @@ class BufferedSocket(object): if not data: break self.buf += data - if '\n' in self.buf: + if self.sep in self.buf: res, self.buf = self.buf.split(self.sep, 1) return res + self.sep else: - return '' + return b'' def send(self, data): self.sock.send(data) @@ -106,24 +106,24 @@ class MPDUpdatePlugin(BeetsPlugin): return resp = s.readline() - if 'OK MPD' not in resp: + if b'OK MPD' not in resp: self._log.warning(u'MPD connection failed: {0!r}', resp) return if password: - s.send('password "%s"\n' % password) + s.send(b'password "%s"\n' % password.encode('utf8')) resp = s.readline() - if 'OK' not in resp: + if b'OK' not in resp: self._log.warning(u'Authentication failed: {0!r}', resp) - s.send('close\n') + s.send(b'close\n') s.close() return - s.send('update\n') + s.send(b'update\n') resp = s.readline() - if 'updating_db' not in resp: + if b'updating_db' not in resp: self._log.warning(u'Update failed: {0!r}', resp) - s.send('close\n') + s.send(b'close\n') s.close() self._log.info(u'Database updated.') diff --git a/docs/changelog.rst b/docs/changelog.rst index f2c7d803c..8bce7c62a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,9 @@ Changelog 1.4.4 (in development) ---------------------- -Changelog goes here! +Fixes: + +* :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` 1.4.3 (January 9, 2017) From da89be81fcb526a731650218677d2607a5aa9111 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 12:30:48 -0500 Subject: [PATCH 1625/2280] Changelog for #2379 --- beets/mediafile.py | 1 + docs/changelog.rst | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/beets/mediafile.py b/beets/mediafile.py index 59959b8f5..c910c9a86 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -40,6 +40,7 @@ import mutagen.id3 import mutagen.mp4 import mutagen.flac import mutagen.asf + import codecs import datetime import re diff --git a/docs/changelog.rst b/docs/changelog.rst index 8bce7c62a..a6de16f9c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,11 @@ Changelog 1.4.4 (in development) ---------------------- +New features: + +* Added support for DSF files, once a future version of Mutagen is released + that supports them. Thanks to :user:`docbobo`. :bug:`459` :bug:`2379` + Fixes: * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` From 5e20cfd26e3d9d25ae9fca1cd4ae81a0ccc928ed Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 12:33:23 -0500 Subject: [PATCH 1626/2280] flake8 fixes for 2379 --- test/test_mediafile.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 1bb30f560..29f1efa9f 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -901,6 +901,7 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): 'channels': 1, } + try: import mutagen.dsf except: @@ -908,6 +909,7 @@ except: else: HAVE_DSF = True + @unittest.skipIf(not HAVE_DSF, "mutagen < 1.37") class DSFTest(ReadWriteTestBase, ExtendedImageStructureTestMixin, unittest.TestCase): From 5863859a5d5e2259078d0077940083a70a9d213d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 12:38:44 -0500 Subject: [PATCH 1627/2280] Remove image tests for DSF (#2379) There isn't currently an `image.dsf`, so those tests fail. --- test/test_mediafile.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 29f1efa9f..133883942 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -910,9 +910,8 @@ else: HAVE_DSF = True -@unittest.skipIf(not HAVE_DSF, "mutagen < 1.37") -class DSFTest(ReadWriteTestBase, - ExtendedImageStructureTestMixin, unittest.TestCase): +@unittest.skipIf(not HAVE_DSF, "Mutagen does not have DSF support") +class DSFTest(ReadWriteTestBase, unittest.TestCase): extension = 'dsf' audio_properties = { 'length': 0.01, From f137f878781a3cd9af82f1700be854724b107792 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 12:41:34 -0500 Subject: [PATCH 1628/2280] More test docs about the image.* mixin --- test/test_mediafile.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 133883942..e003e5dcc 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -175,7 +175,11 @@ class ImageStructureTestMixin(ArtTestMixin): class ExtendedImageStructureTestMixin(ImageStructureTestMixin): - """Checks for additional attributes in the image structure.""" + """Checks for additional attributes in the image structure. + + Like the base `ImageStructureTestMixin`, per-format test classes + should include this mixin to add image-related tests. + """ def assertExtendedImageAttributes(self, image, desc=None, type=None): # noqa self.assertEqual(image.desc, desc) @@ -308,6 +312,9 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, pasting one of the existing subclasses below. You will want to update the `format` field in that subclass, and you will probably need to fiddle with the `bitrate` and other format-specific fields. + + You can also add image tests (using an additional `image.*` fixture + file) by including one of the image-related mixins. """ full_initial_tags = { From f7ebf5524f3107e230707b2c49c8a64cc9ab5d1b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 13:24:33 -0500 Subject: [PATCH 1629/2280] flake8 fix for #2379 --- test/test_mediafile.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index e003e5dcc..63df38b8e 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -909,8 +909,10 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): } +# Check whether we have a Mutagen version with DSF support. We can +# remove this once we require a version that includes the feature. try: - import mutagen.dsf + import mutagen.dsf # noqa except: HAVE_DSF = False else: From 153b01e5a6e981d1939296a6061319a35c20a443 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 14:24:18 -0500 Subject: [PATCH 1630/2280] replaygain: Don't muck with logging level This is now handled by the central logging infrastructure; no need to change it here. I think this must be a leftover from the era when plugins had to explicitly muck with their verbosity level, but even still it doesn't make sense to do set the level to INFO unconditionally... --- beetsplug/replaygain.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 2d3af58a6..c2376ce60 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -794,7 +794,7 @@ class ReplayGainPlugin(BeetsPlugin): "command": CommandBackend, "gstreamer": GStreamerBackend, "audiotools": AudioToolsBackend, - "bs1770gain": Bs1770gainBackend + "bs1770gain": Bs1770gainBackend, } def __init__(self): @@ -934,8 +934,6 @@ class ReplayGainPlugin(BeetsPlugin): """Return the "replaygain" ui subcommand. """ def func(lib, opts, args): - self._log.setLevel(logging.INFO) - write = ui.should_write() if opts.album: From bc93a11141c5154a8aee5c59107eec54acf084f8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 14:45:57 -0500 Subject: [PATCH 1631/2280] Fix #2382: replaygain backend parsing on Python 3 --- beetsplug/replaygain.py | 6 +++--- docs/changelog.rst | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index c2376ce60..eaa01d3a9 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -194,8 +194,8 @@ class Bs1770gainBackend(Backend): """ # Construct shell command. cmd = [self.command] - cmd = cmd + [self.method] - cmd = cmd + ['-p'] + cmd += [self.method] + cmd += ['-p'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This @@ -227,7 +227,7 @@ class Bs1770gainBackend(Backend): ':|done\\.\\s)', re.DOTALL | re.UNICODE) results = re.findall(regex, data) for parts in results[0:num_lines]: - part = parts.split(b'\n') + part = parts.split(u'\n') if len(part) == 0: self._log.debug(u'bad tool output: {0!r}', text) raise ReplayGainError(u'bs1770gain failed') diff --git a/docs/changelog.rst b/docs/changelog.rst index a6de16f9c..4e0d7405f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,8 @@ New features: Fixes: * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` +* :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` + backend. :bug:`2382` 1.4.3 (January 9, 2017) From 998e6ac1c77ce4f270915863bbbbfffdce589b36 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 14:54:17 -0500 Subject: [PATCH 1632/2280] Remove unused import --- beetsplug/replaygain.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index eaa01d3a9..4cf7da7c5 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -23,7 +23,6 @@ import warnings import re from six.moves import zip -from beets import logging from beets import ui from beets.plugins import BeetsPlugin from beets.util import syspath, command_output, displayable_path, py3_path From 3f67a27989d264fe96005b96eaf86e3750547f3d Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 18:21:28 -0500 Subject: [PATCH 1633/2280] Fixed failing test because mocked data was missing property umber. --- test/test_importer.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_importer.py b/test/test_importer.py index 500ca027d..87724f8da 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1723,6 +1723,7 @@ def mocked_get_release_by_id(id_, includes=[], release_status=[], 'length': 59, }, 'position': 9, + 'number': 'A2' }], 'position': 5, }], From c58c49d77ff484965215f07975f9f410ad8b6777 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 18:39:01 -0500 Subject: [PATCH 1634/2280] Fixed trailing whitespace issue. Changed alternate track property name. --- beets/autotag/__init__.py | 6 +++--- beets/autotag/hooks.py | 7 ++++--- beets/autotag/mb.py | 6 +++--- beets/library.py | 8 ++++---- beetsplug/discogs.py | 6 +++--- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index eb3dae519..7487477e5 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -34,7 +34,7 @@ log = logging.getLogger('beets') def apply_item_metadata(item, track_info): """Set an item's metadata from its matched TrackInfo object. - """ + """ item.artist = track_info.artist item.artist_sort = track_info.artist_sort item.artist_credit = track_info.artist_credit @@ -157,5 +157,5 @@ def apply_metadata(album_info, mapping): item.composer = track_info.composer if track_info.arranger is not None: item.arranger = track_info.arranger - - item.alt_track_no = track_info.alt_track_no \ No newline at end of file + + item.track_alt = track_info.track_alt \ No newline at end of file diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index a9a35e635..3c403fcf4 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -145,6 +145,7 @@ class TrackInfo(object): - ``lyricist``: individual track lyricist name - ``composer``: individual track composer name - ``arranger`: individual track arranger name + - ``track_alt``: alternative track number (tape, vinyl, etc.) Only ``title`` and ``track_id`` are required. The rest of the fields may be None. The indices ``index``, ``medium``, and ``medium_index`` @@ -154,8 +155,8 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None, lyricist=None, composer=None, arranger=None, - alt_track_no=None): + media=None, lyricist=None, composer=None, arranger=None, + track_alt=None): self.title = title self.track_id = track_id self.artist = artist @@ -174,7 +175,7 @@ class TrackInfo(object): self.lyricist = lyricist self.composer = composer self.arranger = arranger - self.alt_track_no = alt_track_no + self.track_alt = track_alt # As above, work around a bug in python-musicbrainz-ngs. def decode(self, codec='utf-8'): diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index fc3b1926c..a0d4dc33a 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -256,8 +256,8 @@ def album_info(release): all_tracks = medium['track-list'] if 'pregap' in medium: all_tracks.insert(0, medium['pregap']) - - for track in all_tracks: + + for track in all_tracks: # Basic information from the recording. index += 1 ti = track_info( @@ -269,7 +269,7 @@ def album_info(release): ) ti.disctitle = disctitle ti.media = format - ti.alt_track_no = track['number'] + ti.track_alt = track['number'] # Prefer track data, where present, over recording data. if track.get('title'): diff --git a/beets/library.py b/beets/library.py index d9ffd38fd..99a84cee6 100644 --- a/beets/library.py +++ b/beets/library.py @@ -322,7 +322,7 @@ class LibModel(dbcore.Model): funcs.update(plugins.template_funcs()) return funcs - def store(self, fields=None): + def store(self, fields=None): super(LibModel, self).store(fields) plugins.send('database_change', lib=self._db, model=self) @@ -423,10 +423,10 @@ class Item(LibModel): 'month': types.PaddedInt(2), 'day': types.PaddedInt(2), 'track': types.PaddedInt(2), - 'alt_track_no': types.STRING, + 'track_alt': types.STRING, 'tracktotal': types.PaddedInt(2), 'disc': types.PaddedInt(2), - 'disctotal': types.PaddedInt(2), + 'disctotal': types.PaddedInt(2), 'lyrics': types.STRING, 'comments': types.STRING, 'bpm': types.INTEGER, @@ -457,7 +457,7 @@ class Item(LibModel): 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), - 'initial_key': MusicalKey(), + 'initial_key': MusicalKey(), 'length': DurationType(), 'bitrate': types.ScaledInt(1000, u'kbps'), diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 905358024..3b3f5f201 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -314,9 +314,9 @@ class DiscogsPlugin(BeetsPlugin): # Only real tracks have `position`. Otherwise, it's an index track. if track['position']: index += 1 - ti = self.get_track_info(track, index) - ti.alt_track_no = track['position'] - tracks.append(ti) + track_info = self.get_track_info(track, index) + track_info.track_alt = track['position'] + tracks.append(track_info) else: index_tracks[index + 1] = track['title'] From 3cd4f1c0910bd50bfaeb2e5aad38f22e6aad1a61 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 18:57:42 -0500 Subject: [PATCH 1635/2280] Fixed failing test where track number was missing from mocked data. --- test/test_mb.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_mb.py b/test/test_mb.py index ecbcf3c59..9e4226307 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -68,6 +68,7 @@ class MBAlbumInfoTest(_common.TestCase): track = { 'recording': recording, 'position': i + 1, + 'number': 'A1', } if track_length: # Track lengths are distinct from recording lengths. @@ -182,12 +183,12 @@ class MBAlbumInfoTest(_common.TestCase): second_track_list = [{ 'recording': tracks[1], 'position': '1', + 'number': 'A1', }] release['medium-list'].append({ 'position': '2', 'track-list': second_track_list, }) - d = mb.album_info(release) self.assertEqual(d.mediums, 2) t = d.tracks @@ -454,6 +455,7 @@ class MBLibraryTest(unittest.TestCase): 'length': 42, }, 'position': 9, + 'number': 'A1', }], 'position': 5, }], From bba5a7c7126178802d1e205cccba4abff3fb6bec Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 19:08:18 -0500 Subject: [PATCH 1636/2280] Fixed (?) failing test where umber was rack_alt was missing during import. --- test/test_edit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_edit.py b/test/test_edit.py index 2900d092a..0449f2333 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -276,7 +276,7 @@ class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, ImportHelper, TestHelper, EditMixin): """TODO """ - IGNORED = ['added', 'album_id', 'id', 'mtime', 'path'] + IGNORED = ['added', 'album_id', 'id', 'mtime', 'path', 'track_alt'] def setUp(self): self.setup_beets() From 0dd763c5ef8e84351cd2a73d628a65fa4eb31638 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 19:19:09 -0500 Subject: [PATCH 1637/2280] Fixed flake8 warning W292 for Python 3.4 about missing newline at end of file. --- beets/autotag/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 7487477e5..822bb60ef 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -158,4 +158,4 @@ def apply_metadata(album_info, mapping): if track_info.arranger is not None: item.arranger = track_info.arranger - item.track_alt = track_info.track_alt \ No newline at end of file + item.track_alt = track_info.track_alt From 5250ba80202408bb58c00a7157c0331ab0e556b6 Mon Sep 17 00:00:00 2001 From: Mike Cameron Date: Tue, 10 Jan 2017 19:40:23 -0500 Subject: [PATCH 1638/2280] Added changelog entry of new rack_alt path template value and updated changelog with description of change. --- docs/changelog.rst | 3 +++ docs/reference/pathformat.rst | 1 + 2 files changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4e0d7405f..a9210554a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,9 @@ New features: * Added support for DSF files, once a future version of Mutagen is released that supports them. Thanks to :user:`docbobo`. :bug:`459` :bug:`2379` +* A new template path value ``track_alt`` let's you use the tracks actual + number rather than its position media. Useful when importing albums that + have multiple sides, such as tapes and vinyls. Fixes: diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 72453a6e5..6b1fe5021 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -197,6 +197,7 @@ Ordinary metadata: * original_year, original_month, original_day: The release date of the original version of the album. * track +* track_alt * tracktotal * disc * disctotal From 703f47ae976ed4e95de4cb974d7785ab53b8cea5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 21:01:36 -0500 Subject: [PATCH 1639/2280] Use flexible attribute for track_alt No need for a built-in field for a simple string-type optional field like this. --- beets/library.py | 1 - docs/reference/pathformat.rst | 1 - test/test_edit.py | 2 +- test/test_mb.py | 1 + 4 files changed, 2 insertions(+), 3 deletions(-) diff --git a/beets/library.py b/beets/library.py index 99a84cee6..32176b68d 100644 --- a/beets/library.py +++ b/beets/library.py @@ -423,7 +423,6 @@ class Item(LibModel): 'month': types.PaddedInt(2), 'day': types.PaddedInt(2), 'track': types.PaddedInt(2), - 'track_alt': types.STRING, 'tracktotal': types.PaddedInt(2), 'disc': types.PaddedInt(2), 'disctotal': types.PaddedInt(2), diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 6b1fe5021..72453a6e5 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -197,7 +197,6 @@ Ordinary metadata: * original_year, original_month, original_day: The release date of the original version of the album. * track -* track_alt * tracktotal * disc * disctotal diff --git a/test/test_edit.py b/test/test_edit.py index 0449f2333..2900d092a 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -276,7 +276,7 @@ class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, ImportHelper, TestHelper, EditMixin): """TODO """ - IGNORED = ['added', 'album_id', 'id', 'mtime', 'path', 'track_alt'] + IGNORED = ['added', 'album_id', 'id', 'mtime', 'path'] def setUp(self): self.setup_beets() diff --git a/test/test_mb.py b/test/test_mb.py index 9e4226307..ca1bf2a1a 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -189,6 +189,7 @@ class MBAlbumInfoTest(_common.TestCase): 'position': '2', 'track-list': second_track_list, }) + d = mb.album_info(release) self.assertEqual(d.mediums, 2) t = d.tracks From da86a410fe77f7e37aa5f3527569bc48abb1326a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 10 Jan 2017 21:04:51 -0500 Subject: [PATCH 1640/2280] A little more detail in the changelog --- docs/changelog.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index a9210554a..eaf8c7d5a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,9 +8,11 @@ New features: * Added support for DSF files, once a future version of Mutagen is released that supports them. Thanks to :user:`docbobo`. :bug:`459` :bug:`2379` -* A new template path value ``track_alt`` let's you use the tracks actual - number rather than its position media. Useful when importing albums that - have multiple sides, such as tapes and vinyls. +* The MusicBrainz backend and :doc:`/plugins/discogs` now both provide a new + attribute called ``track_alt`` that stores more nuanced, possibly + non-numeric track index data. For example, some vinyl or tape media will + report the side of the record using a letter instead of a number in that + field. :bug:`1831` :bug:`2363` Fixes: From 272aa8870386b171c132206829509b410cd11d18 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 12 Jan 2017 13:16:35 -0500 Subject: [PATCH 1641/2280] Expand convert format config docs (fix #2384) --- docs/plugins/convert.rst | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index f2f28c63d..b8069506d 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -87,7 +87,14 @@ file. The available options are: By default, the plugin will detect the number of processors available and use them all. -You can also configure the format to use for transcoding. +You can also configure the format to use for transcoding (see the next +section): + +- **format**: The name of the format to transcode to when none is specified on + the command line. + Default: ``mp3``. +- **formats**: A set of formats and associated command lines for transcoding + each. .. _convert-format-config: From 0f1a93c6666b90bd79e1390240c87ce9b22e2bd1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 14 Jan 2017 17:33:36 -0800 Subject: [PATCH 1642/2280] Add missing unittest suite declaration (#2389) --- test/test_plugin_mediafield.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/test_plugin_mediafield.py b/test/test_plugin_mediafield.py index d9d2b0a1f..983f6e2c8 100644 --- a/test/test_plugin_mediafield.py +++ b/test/test_plugin_mediafield.py @@ -20,6 +20,7 @@ from __future__ import division, absolute_import, print_function import os import six import shutil +import unittest from test import _common from beets.library import Item @@ -105,3 +106,10 @@ class ExtendedFieldTestMixin(_common.TestCase): mediafile.MediaFile.add_field('artist', mediafile.MediaField()) self.assertIn(u'property "artist" already exists', six.text_type(cm.exception)) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == '__main__': + unittest.main(defaultTest='suite') From 31c49a62166a5ad073ca76c3b59c603540a3cea9 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 11:28:42 -0800 Subject: [PATCH 1643/2280] beets.library.Library adds custom bytelower function to all connections, not just one --- beets/dbcore/db.py | 27 +++++++++++++++++---------- beets/library.py | 7 +++++-- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index d01e8a5c3..edd611928 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -733,19 +733,26 @@ class Database(object): if thread_id in self._connections: return self._connections[thread_id] else: - # Make a new connection. The `sqlite3` module can't use - # bytestring paths here on Python 3, so we need to - # provide a `str` using `py3_path`. - conn = sqlite3.connect( - py3_path(self.path), timeout=self.timeout - ) - - # Access SELECT results like dictionaries. - conn.row_factory = sqlite3.Row - + conn = self._create_connection() self._connections[thread_id] = conn return conn + def _create_connection(self): + """Create a SQLite connection to the underlying database. Makes + a new connection every time. If you need to add custom functions + to each connection, override this method. + """ + # Make a new connection. The `sqlite3` module can't use + # bytestring paths here on Python 3, so we need to + # provide a `str` using `py3_path`. + conn = sqlite3.connect( + py3_path(self.path), timeout=self.timeout + ) + + # Access SELECT results like dictionaries. + conn.row_factory = sqlite3.Row + return conn + def _close(self): """Close the all connections to the underlying SQLite database from all threads. This does not render the database object diff --git a/beets/library.py b/beets/library.py index 32176b68d..e3ac1bd40 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1237,14 +1237,17 @@ class Library(dbcore.Database): timeout = beets.config['timeout'].as_number() super(Library, self).__init__(path, timeout=timeout) - self._connection().create_function('bytelower', 1, _sqlite_bytelower) - self.directory = bytestring_path(normpath(directory)) self.path_formats = path_formats self.replacements = replacements self._memotable = {} # Used for template substitution performance. + def _create_connection(self): + conn = super(Library, self)._create_connection() + conn.create_function('bytelower', 1, _sqlite_bytelower) + return conn + # Adding objects to the database. def add(self, obj): From dd7f8a3a6fa754821dd1aa76e7a7e47a6da4d415 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 15 Jan 2017 10:12:49 -0800 Subject: [PATCH 1644/2280] Tiny docstring tweak for #2390 --- beets/dbcore/db.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index edd611928..6b0ed8b43 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -738,9 +738,11 @@ class Database(object): return conn def _create_connection(self): - """Create a SQLite connection to the underlying database. Makes - a new connection every time. If you need to add custom functions - to each connection, override this method. + """Create a SQLite connection to the underlying database. + + Makes a new connection every time. If you need to configure the + connection settings (e.g., add custom functions), override this + method. """ # Make a new connection. The `sqlite3` module can't use # bytestring paths here on Python 3, so we need to From 29d61ca634aeccbe2c8f007c8cfeed4001cdeeff Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 00:11:56 -0800 Subject: [PATCH 1645/2280] web.exclude_paths_from_items option More exclude_paths_from_items --- beetsplug/web/__init__.py | 9 ++++++++- docs/plugins/web.rst | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index e7b9ec81f..05872f6d2 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -37,7 +37,10 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - del out['path'] + if app.config['exclude_paths_from_items']: + del out['path'] + else: + out['path'] = out['path'].decode('utf-8') # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. @@ -309,6 +312,7 @@ class WebPlugin(BeetsPlugin): 'host': u'127.0.0.1', 'port': 8337, 'cors': '', + 'exclude_paths_from_items': True, }) def commands(self): @@ -327,6 +331,9 @@ class WebPlugin(BeetsPlugin): # Normalizes json output app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False + app.config['exclude_paths_from_items'] = ( + self.config['exclude_paths_from_items']) + # Enable CORS if required. if self.config['cors']: self._log.info(u'Enabling CORS with origin: {0}', diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index f4ae063e0..45000dc26 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,6 +63,8 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. +- **exclude_paths_from_items**: The 'path' key of items is filtered out of JSON + responses for security reasons. Default: true. Implementation -------------- From 43936cd84c030e2588602c9eb99b47419ca905f8 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 00:12:07 -0800 Subject: [PATCH 1646/2280] /item/at_path/ endpoint More at_path /item/by_path docs --- beetsplug/web/__init__.py | 8 ++++++++ docs/plugins/web.rst | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 05872f6d2..88bf299e4 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -221,6 +221,14 @@ def item_query(queries): return g.lib.items(queries) +@app.route('/item/at_path/') +def item_at_path(path): + try: + return flask.jsonify(_rep(beets.library.Item.from_path('/' + path))) + except beets.library.ReadError: + return flask.abort(404) + + @app.route('/item/values/') def item_unique_field_values(key): sort_key = flask.request.args.get('sort_key', key) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 45000dc26..93a67e7ea 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -162,6 +162,13 @@ response includes all the items requested. If a track is not found it is silentl dropped from the response. +``GET /item/by_path/...`` ++++++++++++++++++++++ + +Look for an item at the given path on the server. If it corresponds to a track, +return the track in the same format as /item/*. + + ``GET /item/query/querystring`` +++++++++++++++++++++++++++++++ From f6cb46d4900b4fe3e8d8453277bf5779e5589eeb Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 09:53:46 -0800 Subject: [PATCH 1647/2280] Fix broken tests (no new ones yet) --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 88bf299e4..a981ccabc 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -340,7 +340,7 @@ class WebPlugin(BeetsPlugin): app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False app.config['exclude_paths_from_items'] = ( - self.config['exclude_paths_from_items']) + self.config.get('exclude_paths_from_items', True)) # Enable CORS if required. if self.config['cors']: From 50ea74635b365e0d20906572f829c9135c4c81e5 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 10:08:39 -0800 Subject: [PATCH 1648/2280] Fix tests I broke --- beetsplug/web/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index a981ccabc..1344b898d 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -37,7 +37,7 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - if app.config['exclude_paths_from_items']: + if app.config.get('EXCLUDE_PATHS_FROM_ITEMS', True): del out['path'] else: out['path'] = out['path'].decode('utf-8') @@ -339,7 +339,7 @@ class WebPlugin(BeetsPlugin): # Normalizes json output app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False - app.config['exclude_paths_from_items'] = ( + app.config['EXCLUDE_PATHS_FROM_ITEMS'] = ( self.config.get('exclude_paths_from_items', True)) # Enable CORS if required. From cedd93b7786a10308448c33bfd0191729ace03ef Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 10:15:41 -0800 Subject: [PATCH 1649/2280] Add tests for exclude_paths_from_items --- test/test_web.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/test/test_web.py b/test/test_web.py index e72ecf33d..d64341f3f 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -21,15 +21,24 @@ class WebPluginTest(_common.LibTestCase): # Add fixtures for track in self.lib.items(): track.remove() - self.lib.add(Item(title=u'title', path='', id=1)) - self.lib.add(Item(title=u'another title', path='', id=2)) + self.lib.add(Item(title=u'title', path='/path_1', id=1)) + self.lib.add(Item(title=u'another title', path='/path_2', id=2)) self.lib.add(Album(album=u'album', id=3)) self.lib.add(Album(album=u'another album', id=4)) web.app.config['TESTING'] = True web.app.config['lib'] = self.lib + web.app.config['EXCLUDE_PATHS_FROM_ITEMS'] = True self.client = web.app.test_client() + def test_config_exclude_paths_from_items(self): + web.app.config['EXCLUDE_PATHS_FROM_ITEMS'] = False + response = self.client.get('/item/1') + response.json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json['path'], u'/path_1') + def test_get_all_items(self): response = self.client.get('/item/') response.json = json.loads(response.data.decode('utf-8')) From c409a71ea1d9eeb5785d75d87d77a6652a0360bf Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 10:31:33 -0800 Subject: [PATCH 1650/2280] Add missing plus signs to web.rst --- docs/plugins/web.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 93a67e7ea..6bb5b0e4b 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -163,7 +163,7 @@ dropped from the response. ``GET /item/by_path/...`` -+++++++++++++++++++++ ++++++++++++++++++++++++++ Look for an item at the given path on the server. If it corresponds to a track, return the track in the same format as /item/*. From a994df6aa6cce5dff6bee8b08cd8816181b8ffb1 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 10:34:02 -0800 Subject: [PATCH 1651/2280] Fix bad doc formatting --- docs/plugins/web.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 6bb5b0e4b..ef5769a2c 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -166,7 +166,7 @@ dropped from the response. +++++++++++++++++++++++++ Look for an item at the given path on the server. If it corresponds to a track, -return the track in the same format as /item/*. +return the track in the same format as ``/item/*``. ``GET /item/query/querystring`` From 05bc4996a832fa9be7f20e2c5c5f8794001d91e0 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 11:08:24 -0800 Subject: [PATCH 1652/2280] Rename and invert new config option --- beetsplug/web/__init__.py | 12 ++++++------ docs/plugins/web.rst | 4 ++-- test/test_web.py | 14 +++++++++++--- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 1344b898d..4d5dcba54 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -37,10 +37,10 @@ def _rep(obj, expand=False): out = dict(obj) if isinstance(obj, beets.library.Item): - if app.config.get('EXCLUDE_PATHS_FROM_ITEMS', True): - del out['path'] - else: + if app.config.get('INCLUDE_PATHS', False): out['path'] = out['path'].decode('utf-8') + else: + del out['path'] # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. @@ -320,7 +320,7 @@ class WebPlugin(BeetsPlugin): 'host': u'127.0.0.1', 'port': 8337, 'cors': '', - 'exclude_paths_from_items': True, + 'include_paths': False, }) def commands(self): @@ -339,8 +339,8 @@ class WebPlugin(BeetsPlugin): # Normalizes json output app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False - app.config['EXCLUDE_PATHS_FROM_ITEMS'] = ( - self.config.get('exclude_paths_from_items', True)) + app.config['INCLUDE_PATHS'] = ( + self.config.get('include_paths', False)) # Enable CORS if required. if self.config['cors']: diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index ef5769a2c..54c507cf0 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,8 +63,8 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. -- **exclude_paths_from_items**: The 'path' key of items is filtered out of JSON - responses for security reasons. Default: true. +- **include_paths**: If true, includes paths in item objects. + Default: false. Implementation -------------- diff --git a/test/test_web.py b/test/test_web.py index d64341f3f..871fd1b09 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -28,17 +28,25 @@ class WebPluginTest(_common.LibTestCase): web.app.config['TESTING'] = True web.app.config['lib'] = self.lib - web.app.config['EXCLUDE_PATHS_FROM_ITEMS'] = True + web.app.config['INCLUDE_PATHS'] = False self.client = web.app.test_client() - def test_config_exclude_paths_from_items(self): - web.app.config['EXCLUDE_PATHS_FROM_ITEMS'] = False + def test_config_include_paths_true(self): + web.app.config['INCLUDE_PATHS'] = True response = self.client.get('/item/1') response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(response.json['path'], u'/path_1') + def test_config_include_paths_false(self): + web.app.config['INCLUDE_PATHS'] = False + response = self.client.get('/item/1') + response.json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertNotIn('path', response.json) + def test_get_all_items(self): response = self.client.get('/item/') response.json = json.loads(response.data.decode('utf-8')) From 866a650bc0d7d3e48484afca2855dd0828e2683d Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 11:15:18 -0800 Subject: [PATCH 1653/2280] Rename /item/by_path to /item/path and use PathQuery instead of direct file access --- beetsplug/web/__init__.py | 14 ++++++++------ docs/plugins/web.rst | 4 ++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 4d5dcba54..d47f1d183 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -221,11 +221,14 @@ def item_query(queries): return g.lib.items(queries) -@app.route('/item/at_path/') +@app.route('/item/path/') def item_at_path(path): - try: - return flask.jsonify(_rep(beets.library.Item.from_path('/' + path))) - except beets.library.ReadError: + g.lib._connection().create_function('bytelower', 1, beets.library._sqlite_bytelower) + query = beets.library.PathQuery('path', u'/' + path) + item = g.lib.items(query).get() + if item: + return flask.jsonify(_rep(item)) + else: return flask.abort(404) @@ -339,8 +342,7 @@ class WebPlugin(BeetsPlugin): # Normalizes json output app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False - app.config['INCLUDE_PATHS'] = ( - self.config.get('include_paths', False)) + app.config['INCLUDE_PATHS'] = self.config['include_paths'] # Enable CORS if required. if self.config['cors']: diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 54c507cf0..f0adacc00 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -162,8 +162,8 @@ response includes all the items requested. If a track is not found it is silentl dropped from the response. -``GET /item/by_path/...`` -+++++++++++++++++++++++++ +``GET /item/path/...`` +++++++++++++++++++++++ Look for an item at the given path on the server. If it corresponds to a track, return the track in the same format as ``/item/*``. From 4434569ddc9b55c6799e8ef56583185ec9d3b4d6 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 11:28:42 -0800 Subject: [PATCH 1654/2280] beets.library.Library adds custom bytelower function to all connections, not just one --- beetsplug/web/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index d47f1d183..360e018e6 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -223,7 +223,6 @@ def item_query(queries): @app.route('/item/path/') def item_at_path(path): - g.lib._connection().create_function('bytelower', 1, beets.library._sqlite_bytelower) query = beets.library.PathQuery('path', u'/' + path) item = g.lib.items(query).get() if item: From d8fbdbc16ad4cd1ce3606042c5400001229207fa Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 11:36:57 -0800 Subject: [PATCH 1655/2280] Update changelog --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index eaf8c7d5a..be7020dc1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,10 @@ New features: non-numeric track index data. For example, some vinyl or tape media will report the side of the record using a letter instead of a number in that field. :bug:`1831` :bug:`2363` +* The :doc:`/plugins/web` has a new endpoint, ``/item/path/foo``, which will + return the item info for the file at the given path, or 404. +* The :doc:`/plugins/web` also has a new config option, ``include_paths``, + which will cause paths to be included in item API responses if set to true. Fixes: From 6b7a6baaf21ad3d017a0d940b7fcaa10c450a039 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 12:12:20 -0800 Subject: [PATCH 1656/2280] Add test for /item/path/ endpoint --- test/test_web.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/test/test_web.py b/test/test_web.py index 871fd1b09..867e2c3e3 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -4,11 +4,12 @@ from __future__ import division, absolute_import, print_function +import json import unittest +import os.path from six import assertCountEqual from test import _common -import json from beets.library import Item, Album from beetsplug import web @@ -75,6 +76,23 @@ class WebPluginTest(_common.LibTestCase): response = self.client.get('/item/3') self.assertEqual(response.status_code, 404) + def test_get_single_item_by_path(self): + data_path = os.path.join(_common.RSRC, b'full.mp3') + self.lib.add(Item.from_path(data_path)) + response = self.client.get('/item/path' + data_path.decode('utf-8')) + response.json = json.loads(response.data.decode('utf-8')) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json['title'], u'full') + + def test_get_single_item_by_path_not_found_if_not_in_library(self): + data_path = os.path.join(_common.RSRC, b'full.mp3') + # data_path points to a valid file, but we have not added the file + # to the library. + response = self.client.get('/item/path' + data_path.decode('utf-8')) + + self.assertEqual(response.status_code, 404) + def test_get_item_empty_query(self): response = self.client.get('/item/query/') response.json = json.loads(response.data.decode('utf-8')) From e2be6ba7814dafc30f9a025dacf8769687ef26c5 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 12:44:07 -0800 Subject: [PATCH 1657/2280] Query path with bytestring. Might fix tests. --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 360e018e6..7977eda94 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -223,7 +223,7 @@ def item_query(queries): @app.route('/item/path/') def item_at_path(path): - query = beets.library.PathQuery('path', u'/' + path) + query = beets.library.PathQuery('path', b'/' + path.encode('utf-8')) item = g.lib.items(query).get() if item: return flask.jsonify(_rep(item)) From e3707e45f3308ab7767dd6e690a388004477b43e Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 20:40:30 -0800 Subject: [PATCH 1658/2280] Maybe fix code and tests for Windows --- beetsplug/web/__init__.py | 9 +++++++-- test/test_web.py | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 7977eda94..f955b6d63 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -176,11 +176,16 @@ class QueryConverter(PathConverter): return ','.join(value) +class EverythingConverter(PathConverter): + regex = '.*?' + + # Flask setup. app = flask.Flask(__name__) app.url_map.converters['idlist'] = IdListConverter app.url_map.converters['query'] = QueryConverter +app.url_map.converters['everything'] = EverythingConverter @app.before_request @@ -221,9 +226,9 @@ def item_query(queries): return g.lib.items(queries) -@app.route('/item/path/') +@app.route('/item/path/') def item_at_path(path): - query = beets.library.PathQuery('path', b'/' + path.encode('utf-8')) + query = beets.library.PathQuery('path', path.encode('utf-8')) item = g.lib.items(query).get() if item: return flask.jsonify(_rep(item)) diff --git a/test/test_web.py b/test/test_web.py index 867e2c3e3..98347d8af 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -79,7 +79,7 @@ class WebPluginTest(_common.LibTestCase): def test_get_single_item_by_path(self): data_path = os.path.join(_common.RSRC, b'full.mp3') self.lib.add(Item.from_path(data_path)) - response = self.client.get('/item/path' + data_path.decode('utf-8')) + response = self.client.get('/item/path/' + data_path.decode('utf-8')) response.json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) @@ -89,7 +89,7 @@ class WebPluginTest(_common.LibTestCase): data_path = os.path.join(_common.RSRC, b'full.mp3') # data_path points to a valid file, but we have not added the file # to the library. - response = self.client.get('/item/path' + data_path.decode('utf-8')) + response = self.client.get('/item/path/' + data_path.decode('utf-8')) self.assertEqual(response.status_code, 404) From 1426aea4a28d63d2228692a34678f4bf8071c05d Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sat, 14 Jan 2017 21:06:38 -0800 Subject: [PATCH 1659/2280] Update docs --- docs/plugins/web.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index f0adacc00..9f1bbcd99 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -165,8 +165,11 @@ dropped from the response. ``GET /item/path/...`` ++++++++++++++++++++++ -Look for an item at the given path on the server. If it corresponds to a track, -return the track in the same format as ``/item/*``. +Look for an item at the given absolute path on the server. If it corresponds to +a track, return the track in the same format as ``/item/*``. + +If the server runs UNIX, you'll need to include an extra leading slash: +``http://localhost:8337/item/path//Users/beets/Music/Foo/Bar/Baz.mp3`` ``GET /item/query/querystring`` From 926dce241ca759d407dea4e14ca624f827cb0591 Mon Sep 17 00:00:00 2001 From: Steve Johnson Date: Sun, 15 Jan 2017 11:25:03 -0800 Subject: [PATCH 1660/2280] Use util.displayable_path instead of naive .decode() --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index f955b6d63..bd4677bd8 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -38,7 +38,7 @@ def _rep(obj, expand=False): if isinstance(obj, beets.library.Item): if app.config.get('INCLUDE_PATHS', False): - out['path'] = out['path'].decode('utf-8') + out['path'] = util.displayable_path(out['path']) else: del out['path'] From 958ad430fc4854b2589ec3a2726b7ee269e5322e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 17 Jan 2017 11:37:10 -0800 Subject: [PATCH 1661/2280] bpd: Use integers for time values (fix 2394) --- beetsplug/bpd/gstplayer.py | 4 ++-- docs/changelog.rst | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/bpd/gstplayer.py b/beetsplug/bpd/gstplayer.py index fffa8a6ed..705692aa5 100644 --- a/beetsplug/bpd/gstplayer.py +++ b/beetsplug/bpd/gstplayer.py @@ -177,12 +177,12 @@ class GstPlayer(object): posq = self.player.query_position(fmt) if not posq[0]: raise QueryError("query_position failed") - pos = posq[1] / (10 ** 9) + pos = posq[1] // (10 ** 9) lengthq = self.player.query_duration(fmt) if not lengthq[0]: raise QueryError("query_duration failed") - length = lengthq[1] / (10 ** 9) + length = lengthq[1] // (10 ** 9) self.cached_time = (pos, length) return (pos, length) diff --git a/docs/changelog.rst b/docs/changelog.rst index be7020dc1..4fa8aa50f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -23,6 +23,7 @@ Fixes: * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` backend. :bug:`2382` +* :doc:`/plugins/bpd`: Report playback times as integer. :bug:`2394` 1.4.3 (January 9, 2017) From 5233e0fcddcba20fb9b79dc650dc137197316791 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Jan 2017 11:31:25 -0800 Subject: [PATCH 1662/2280] Avoid stdout encoding issues (#2393) --- beets/ui/__init__.py | 17 +++++++++++------ docs/changelog.rst | 3 +++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ae30a9c60..d69870737 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -126,8 +126,7 @@ def print_(*strings, **kwargs): Python 3. The `end` keyword argument behaves similarly to the built-in `print` - (it defaults to a newline). The value should have the same string - type as the arguments. + (it defaults to a newline). """ if not strings: strings = [u''] @@ -136,11 +135,17 @@ def print_(*strings, **kwargs): txt = u' '.join(strings) txt += kwargs.get('end', u'\n') - # Send bytes to the stdout stream on Python 2. + # Encode the string and write it to stdout. + txt = txt.encode(_out_encoding(), 'replace') if six.PY2: - txt = txt.encode(_out_encoding(), 'replace') - - sys.stdout.write(txt) + # On Python 2, sys.stdout expects bytes. + sys.stdout.write(txt) + else: + # On Python 3, sys.stdout expects text strings and uses the + # exception-throwing encoding error policy. To avoid throwing + # errors and use our configurable encoding override, we use the + # underlying bytes buffer instead. + sys.stdout.buffer.write(txt) # Configuration wrappers. diff --git a/docs/changelog.rst b/docs/changelog.rst index 4fa8aa50f..3b920e51a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ Fixes: * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` backend. :bug:`2382` * :doc:`/plugins/bpd`: Report playback times as integer. :bug:`2394` +* On Python 3, the :ref:`terminal_encoding` setting is respected again for + output and printing will no longer crash on systems configured with a + limited encoding. 1.4.3 (January 9, 2017) From a99d5d2ed2081172a3d486a492319cd87e02d141 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 19 Jan 2017 11:42:46 -0800 Subject: [PATCH 1663/2280] On Python 3 in tests, record `str` output directly This is a little ugly. Eventually, it would be nice to create a single output stream set up with the appropriate encoding settings *at startup* and use that repeatedly, instead of having `print_` check the settings every time. This output stream could be cleanly replaced with a mock harness for testing. Yet another reason to desire a big "beets context" object... --- beets/ui/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index d69870737..df370b52e 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -136,16 +136,22 @@ def print_(*strings, **kwargs): txt += kwargs.get('end', u'\n') # Encode the string and write it to stdout. - txt = txt.encode(_out_encoding(), 'replace') if six.PY2: # On Python 2, sys.stdout expects bytes. - sys.stdout.write(txt) + out = txt.encode(_out_encoding(), 'replace') + sys.stdout.write(out) else: # On Python 3, sys.stdout expects text strings and uses the # exception-throwing encoding error policy. To avoid throwing # errors and use our configurable encoding override, we use the # underlying bytes buffer instead. - sys.stdout.buffer.write(txt) + if hasattr(sys.stdout, 'buffer'): + out = txt.encode(_out_encoding(), 'replace') + sys.stdout.buffer.write(out) + else: + # In our test harnesses (e.g., DummyOut), sys.stdout.buffer + # does not exist. We instead just record the text string. + sys.stdout.write(txt) # Configuration wrappers. From 377a2a6964caaaff0e8d8a8059d57d65d838a517 Mon Sep 17 00:00:00 2001 From: diomekes Date: Thu, 19 Jan 2017 15:09:12 -0500 Subject: [PATCH 1664/2280] add bracket argument to aunique --- beets/library.py | 15 ++++++++++++--- docs/reference/pathformat.rst | 25 +++++++++++++++---------- test/test_library.py | 4 ++-- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/beets/library.py b/beets/library.py index e3ac1bd40..1cfe87f0c 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1447,7 +1447,7 @@ class DefaultTemplateFunctions(object): 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): + def tmpl_aunique(self, keys=None, disam=None, bracket=None): """Generate a string that is guaranteed to be unique among all albums in the library who share the same set of keys. A fields from "disam" is used in the string if one is sufficient to @@ -1467,8 +1467,10 @@ class DefaultTemplateFunctions(object): keys = keys or 'albumartist album' disam = disam or 'albumtype year label catalognum albumdisambig' + bracket = bracket or '[]' keys = keys.split() disam = disam.split() + bracket = None if bracket is ' ' else list(bracket) album = self.lib.get_album(self.item) if not album: @@ -1502,13 +1504,20 @@ class DefaultTemplateFunctions(object): else: # No disambiguator distinguished all fields. - res = u' {0}'.format(album.id) + res = u' {1}{0}{2}'.format(album.id, bracket[0] if bracket else + u'', bracket[1] if bracket else u'') self.lib._memotable[memokey] = res return res # Flatten disambiguation value into a string. disam_value = album.formatted(True).get(disambiguator) - res = u' [{0}]'.format(disam_value) + res = u' {1}{0}{2}'.format(disam_value, bracket[0] if bracket else u'', + bracket[1] if bracket else u'') + + # Remove space and/or brackets if disambiguation value is empty + if bracket and res == u' ' + ''.join(bracket) or res.isspace(): + res = u'' + self.lib._memotable[memokey] = res return res diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 72453a6e5..de1185ae0 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -71,8 +71,8 @@ These functions are built in to beets: For example, "café" becomes "cafe". Uses the mapping provided by the `unidecode module`_. See the :ref:`asciify-paths` configuration option. -* ``%aunique{identifiers,disambiguators}``: Provides a unique string to - disambiguate similar albums in the database. See :ref:`aunique`, below. +* ``%aunique{identifiers,disambiguators,brackets}``: Provides a unique string + to disambiguate similar albums in the database. See :ref:`aunique`, below. * ``%time{date_time,format}``: Return the date and time in any format accepted by `strftime`_. For example, to get the year some music was added to your library, use ``%time{$added,%Y}``. @@ -112,14 +112,16 @@ will expand to "[2008]" for one album and "[2010]" for the other. The function detects that you have two albums with the same artist and title but that they have different release years. -For full flexibility, the ``%aunique`` function takes two arguments, each of -which are whitespace-separated lists of album field names: a set of -*identifiers* and a set of *disambiguators*. Any group of albums with identical -values for all the identifiers will be considered "duplicates". Then, the -function tries each disambiguator field, looking for one that distinguishes each -of the duplicate albums from each other. The first such field is used as the -result for ``%aunique``. If no field suffices, an arbitrary number is used to -distinguish the two albums. +For full flexibility, the ``%aunique`` function takes three arguments. The +first two are whitespace-separated lists of album field names: a set of +*identifiers* and a set of *disambiguators*. The third argument is a pair of +characters used to surround the disambiguator. + +Any group of albums with identical values for all the identifiers will be +considered "duplicates". Then, the function tries each disambiguator field, +looking for one that distinguishes each of the duplicate albums from each +other. The first such field is used as the result for ``%aunique``. If no field +suffices, an arbitrary number is used to distinguish the two albums. The default identifiers are ``albumartist album`` and the default disambiguators are ``albumtype year label catalognum albumdisambig``. So you can get reasonable @@ -127,6 +129,9 @@ disambiguation behavior if you just use ``%aunique{}`` with no parameters in your path forms (as in the default path formats), but you can customize the disambiguation if, for example, you include the year by default in path formats. +The default characters used as brackets are ``[]``. If a single blank space is +used, then the disambiguator will not be surrounded by anything. + One caveat: When you import an album that is named identically to one already in your library, the *first* album—the one already in your library— will not consider itself a duplicate at import time. This means that ``%aunique{}`` will diff --git a/test/test_library.py b/test/test_library.py index 7aa88e064..d2c21d5f6 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -713,8 +713,8 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): album2.year = 2001 album2.store() - self._assert_dest(b'/base/foo 1/the title', self.i1) - self._assert_dest(b'/base/foo 2/the title', self.i2) + self._assert_dest(b'/base/foo [1]/the title', self.i1) + self._assert_dest(b'/base/foo [2]/the title', self.i2) def test_unique_falls_back_to_second_distinguishing_field(self): self._setf(u'foo%aunique{albumartist album,month year}/$title') From 3a967df3961022f3787a99b19b963a623c3ba3fa Mon Sep 17 00:00:00 2001 From: diomekes Date: Thu, 19 Jan 2017 20:30:13 -0500 Subject: [PATCH 1665/2280] simplify check for empty disam_val, update changelog and docs, add change bracket test --- beets/library.py | 25 +++++++++++++++++-------- docs/changelog.rst | 5 +++++ docs/reference/pathformat.rst | 6 ++++-- test/test_library.py | 10 ++++++++++ 4 files changed, 36 insertions(+), 10 deletions(-) diff --git a/beets/library.py b/beets/library.py index 1cfe87f0c..86fcf7c20 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1453,7 +1453,9 @@ class DefaultTemplateFunctions(object): from "disam" is used in the string if one is sufficient to disambiguate the albums. Otherwise, a fallback opaque value is used. Both "keys" and "disam" should be given as - whitespace-separated lists of field names. + whitespace-separated lists of field names, while "bracket" is a + pair of characters to be used as brackets surrounding the + disambiguator or a white space to have no brackets. """ # Fast paths: no album, no item or library, or memoized value. if not self.item or not self.lib: @@ -1470,7 +1472,15 @@ class DefaultTemplateFunctions(object): bracket = bracket or '[]' keys = keys.split() disam = disam.split() - bracket = None if bracket is ' ' else list(bracket) + bracket = None if bracket == ' ' else list(bracket) + + # Assign a left and right bracket from bracket list. + if bracket: + bracket_l = bracket[0] + bracket_r = bracket[1] + else: + bracket_l = u'' + bracket_r = u'' album = self.lib.get_album(self.item) if not album: @@ -1504,18 +1514,17 @@ class DefaultTemplateFunctions(object): else: # No disambiguator distinguished all fields. - res = u' {1}{0}{2}'.format(album.id, bracket[0] if bracket else - u'', bracket[1] if bracket else u'') + res = u' {1}{0}{2}'.format(album.id, bracket_l, bracket_r) self.lib._memotable[memokey] = res return res # Flatten disambiguation value into a string. disam_value = album.formatted(True).get(disambiguator) - res = u' {1}{0}{2}'.format(disam_value, bracket[0] if bracket else u'', - bracket[1] if bracket else u'') - # Remove space and/or brackets if disambiguation value is empty - if bracket and res == u' ' + ''.join(bracket) or res.isspace(): + # Return empty string if disambiguator is empty. + if disam_value: + res = u' {1}{0}{2}'.format(disam_value, bracket_l, bracket_r) + else: res = u'' self.lib._memotable[memokey] = res diff --git a/docs/changelog.rst b/docs/changelog.rst index 4fa8aa50f..e2849c22d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -17,6 +17,11 @@ New features: return the item info for the file at the given path, or 404. * The :doc:`/plugins/web` also has a new config option, ``include_paths``, which will cause paths to be included in item API responses if set to true. +* The ``%aunique`` template function for :ref:`aunique` now takes a third + argument that specifies which brackets to use around the disambiguator + value. The argument can be any two characters that represent the left and + right brackets. It defaults to `[]` and can also be a white space to turn off + bracketing. :bug:`2397` :bug:`2399` Fixes: diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index de1185ae0..873a51c5e 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -129,8 +129,10 @@ disambiguation behavior if you just use ``%aunique{}`` with no parameters in your path forms (as in the default path formats), but you can customize the disambiguation if, for example, you include the year by default in path formats. -The default characters used as brackets are ``[]``. If a single blank space is -used, then the disambiguator will not be surrounded by anything. +The default characters used as brackets are ``[]``. To change this, provide a +third argument to the ``%aunique`` function consisting of two characters: the left +and right brackets. Or, to turn off bracketing entirely, use a single blank +space. One caveat: When you import an album that is named identically to one already in your library, the *first* album—the one already in your library— will not diff --git a/test/test_library.py b/test/test_library.py index d2c21d5f6..9e1301880 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -730,6 +730,16 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self._setf(u'foo%aunique{albumartist album,albumtype}/$title') self._assert_dest(b'/base/foo [foo_bar]/the title', self.i1) + def test_drop_empty_disam_string(self): + album1 = self.lib.get_album(self.i1) + album1.year = None + album1.store() + self._assert_dest(b'/base/foo/the title', self.i1) + + def test_change_brackets(self): + self._setf(u'foo%aunique{albumartist album,year,()}/$title') + self._assert_dest(b'/base/foo (2001)/the title', self.i1) + class PluginDestinationTest(_common.TestCase): def setUp(self): From d10df34c65bbdcff39c9c7660ae4b9f5593cd26c Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 20 Jan 2017 09:06:38 -0500 Subject: [PATCH 1666/2280] add test for aunique without brackets --- test/test_library.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_library.py b/test/test_library.py index 9e1301880..263254f6b 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -740,6 +740,10 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self._setf(u'foo%aunique{albumartist album,year,()}/$title') self._assert_dest(b'/base/foo (2001)/the title', self.i1) + def test_remove_brackets(self): + self._setf(u'foo%aunique{albumartist album,year, }/$title') + self._assert_dest(b'/base/foo 2001/the title', self.i1) + class PluginDestinationTest(_common.TestCase): def setUp(self): From eaa2161a903ba8ec5d33f3497100e1900fa468a5 Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 20 Jan 2017 19:40:09 -0500 Subject: [PATCH 1667/2280] fix empty disambig string test --- test/test_library.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index 263254f6b..34e5437e5 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -730,10 +730,14 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self._setf(u'foo%aunique{albumartist album,albumtype}/$title') self._assert_dest(b'/base/foo [foo_bar]/the title', self.i1) - def test_drop_empty_disam_string(self): + def test_drop_empty_disambig_string(self): album1 = self.lib.get_album(self.i1) - album1.year = None + album1.albumdisambig = None + album2 = self.lib.get_album(self.i2) + album2.albumdisambig = u'foo' album1.store() + album2.store() + self._setf(u'foo%aunique{albumartist album,albumdisambig}/$title') self._assert_dest(b'/base/foo/the title', self.i1) def test_change_brackets(self): From 04f7915d41c246c7d8305d079fd1b130389b5a61 Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 20 Jan 2017 22:47:47 -0500 Subject: [PATCH 1668/2280] change no-bracket argument from white space to empty --- beets/library.py | 9 +++++---- docs/changelog.rst | 2 +- docs/reference/pathformat.rst | 3 +-- test/test_library.py | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/beets/library.py b/beets/library.py index 86fcf7c20..6f68e7434 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1469,13 +1469,14 @@ class DefaultTemplateFunctions(object): keys = keys or 'albumartist album' disam = disam or 'albumtype year label catalognum albumdisambig' - bracket = bracket or '[]' + if bracket is None: + bracket = '[]' keys = keys.split() disam = disam.split() - bracket = None if bracket == ' ' else list(bracket) - # Assign a left and right bracket from bracket list. - if bracket: + # Assign a left and right bracket or leave blank if argument is empty. + if len(bracket) == 2: + bracket = list(bracket) bracket_l = bracket[0] bracket_r = bracket[1] else: diff --git a/docs/changelog.rst b/docs/changelog.rst index e2849c22d..0a32752d1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,7 +20,7 @@ New features: * The ``%aunique`` template function for :ref:`aunique` now takes a third argument that specifies which brackets to use around the disambiguator value. The argument can be any two characters that represent the left and - right brackets. It defaults to `[]` and can also be a white space to turn off + right brackets. It defaults to `[]` and can also be blank to turn off bracketing. :bug:`2397` :bug:`2399` Fixes: diff --git a/docs/reference/pathformat.rst b/docs/reference/pathformat.rst index 873a51c5e..667be3150 100644 --- a/docs/reference/pathformat.rst +++ b/docs/reference/pathformat.rst @@ -131,8 +131,7 @@ disambiguation if, for example, you include the year by default in path formats. The default characters used as brackets are ``[]``. To change this, provide a third argument to the ``%aunique`` function consisting of two characters: the left -and right brackets. Or, to turn off bracketing entirely, use a single blank -space. +and right brackets. Or, to turn off bracketing entirely, leave argument blank. One caveat: When you import an album that is named identically to one already in your library, the *first* album—the one already in your library— will not diff --git a/test/test_library.py b/test/test_library.py index 34e5437e5..aaab6fe03 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -745,7 +745,7 @@ class DisambiguationTest(_common.TestCase, PathFormattingMixin): self._assert_dest(b'/base/foo (2001)/the title', self.i1) def test_remove_brackets(self): - self._setf(u'foo%aunique{albumartist album,year, }/$title') + self._setf(u'foo%aunique{albumartist album,year,}/$title') self._assert_dest(b'/base/foo 2001/the title', self.i1) From 672fc36cc8b3c51d7332a4dbba2a9613e36d17d4 Mon Sep 17 00:00:00 2001 From: diomekes Date: Fri, 20 Jan 2017 23:08:36 -0500 Subject: [PATCH 1669/2280] fix docstring for aunique empty bracket --- beets/library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 6f68e7434..a63694804 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1455,7 +1455,7 @@ class DefaultTemplateFunctions(object): used. Both "keys" and "disam" should be given as whitespace-separated lists of field names, while "bracket" is a pair of characters to be used as brackets surrounding the - disambiguator or a white space to have no brackets. + disambiguator or empty to have no brackets. """ # Fast paths: no album, no item or library, or memoized value. if not self.item or not self.lib: From c2b6623aaccd82aa695ba9583e34b879fa674b1a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Jan 2017 20:47:03 -0800 Subject: [PATCH 1670/2280] Remove an unnecessary list conversion (#2399) Indexing a string works just fine. --- beets/library.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index a63694804..4e5d9ccf6 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1476,7 +1476,6 @@ class DefaultTemplateFunctions(object): # Assign a left and right bracket or leave blank if argument is empty. if len(bracket) == 2: - bracket = list(bracket) bracket_l = bracket[0] bracket_r = bracket[1] else: From c21f456f032864030adde9916b9a0aae9edb9851 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Jan 2017 20:47:40 -0800 Subject: [PATCH 1671/2280] tox: Use Python 3.6 in default tests Just typing `tox` should use the most relevant Python versions. --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 8115395c6..43bff8014 100644 --- a/tox.ini +++ b/tox.ini @@ -4,7 +4,7 @@ # and then run "tox" from this directory. [tox] -envlist = py27-test, py35-test, py27-flake8, docs +envlist = py27-test, py36-test, py27-flake8, docs # The exhaustive list of environments is: # envlist = py{27,34,35}-{test,cov}, py{27,34,35}-flake8, docs From ca904a9d0c93cee65eedad3a0d67b6ddbc7fd5fb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 21 Jan 2017 23:21:11 -0800 Subject: [PATCH 1672/2280] mpdstats: Fix Python 3 compatibility (fix #2405) We previously needed a hack to get the client to consume and produce Unicode strings. The library has since added Unicode support, behind a constructor flag. We can remove the hack now, which was causing a crash on Python 3 because the library uses Unicode by default there, and instead use its built-in support. --- beetsplug/mpdstats.py | 16 +--------------- docs/changelog.rst | 2 ++ setup.py | 2 +- 3 files changed, 4 insertions(+), 16 deletions(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 89b99a9df..4258cbc4c 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -46,20 +46,6 @@ def is_url(path): return path.split('://', 1)[0] in ['http', 'https'] -# Use the MPDClient internals to get unicode. -# see http://www.tarmack.eu/code/mpdunicode.py for the general idea -class MPDClient(mpd.MPDClient): - def _write_command(self, command, args=[]): - args = [six.text_type(arg).encode('utf-8') for arg in args] - super(MPDClient, self)._write_command(command, args) - - def _read_line(self): - line = super(MPDClient, self)._read_line() - if line is not None: - return line.decode('utf-8') - return None - - class MPDClientWrapper(object): def __init__(self, log): self._log = log @@ -67,7 +53,7 @@ class MPDClientWrapper(object): self.music_directory = ( mpd_config['music_directory'].as_str()) - self.client = MPDClient() + self.client = mpd.MPDClient(use_unicode=True) def connect(self): """Connect to the MPD. diff --git a/docs/changelog.rst b/docs/changelog.rst index 0a32752d1..667d9b99f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -29,6 +29,8 @@ Fixes: * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` backend. :bug:`2382` * :doc:`/plugins/bpd`: Report playback times as integer. :bug:`2394` +* :doc:`/plugins/mpdstats`: Fix Python 3 compatibility. The plugin also now + requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` 1.4.3 (January 9, 2017) diff --git a/setup.py b/setup.py index 35131cb55..1019a74a7 100755 --- a/setup.py +++ b/setup.py @@ -117,7 +117,7 @@ setup( 'discogs': ['discogs-client>=2.1.0'], 'beatport': ['requests-oauthlib>=0.6.1'], 'lastgenre': ['pylast'], - 'mpdstats': ['python-mpd2'], + 'mpdstats': ['python-mpd2>=0.4.2'], 'web': ['flask', 'flask-cors'], 'import': ['rarfile'], 'thumbnails': ['pyxdg'] + From 44963598e8bdfed1fcf064b947aad1012123acc5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 21 Jan 2017 23:32:36 -0800 Subject: [PATCH 1673/2280] Remove unused import --- beetsplug/mpdstats.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 4258cbc4c..896a34415 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -27,7 +27,6 @@ from beets import plugins from beets import library from beets.util import displayable_path from beets.dbcore import types -import six # If we lose the connection, how many times do we want to retry and how # much time should we wait between retries? From 3a6967eb7a4909117466fd20bbc577bf807be70e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 22 Jan 2017 12:59:04 -0800 Subject: [PATCH 1674/2280] Remove dependencies from convert_stub.py See: https://github.com/beetbox/beets/pull/2403#issuecomment-274358494 --- test/rsrc/convert_stub.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index 3ca71352a..f32bce09a 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -6,15 +6,19 @@ a specified text tag. """ from __future__ import division, absolute_import, print_function -from os.path import dirname, abspath -import six import sys import platform +import locale -beets_src = dirname(dirname(dirname(abspath(__file__)))) -sys.path.insert(0, beets_src) +PY2 = sys.version_info[0] == 2 -from beets.util import arg_encoding # noqa: E402 + +# From `beets.util`. +def arg_encoding(): + try: + return locale.getdefaultlocale()[1] or 'utf-8' + except ValueError: + return 'utf-8' def convert(in_file, out_file, tag): @@ -27,7 +31,7 @@ def convert(in_file, out_file, tag): # On Windows, use Unicode paths. (The test harness gives them to us # as UTF-8 bytes.) if platform.system() == 'Windows': - if not six.PY2: + if not PY2: in_file = in_file.encode(arg_encoding()) out_file = out_file.encode(arg_encoding()) in_file = in_file.decode('utf-8') From 77d155cdea473873b8e179eefa180901f12c1623 Mon Sep 17 00:00:00 2001 From: Pauligrinder Date: Mon, 23 Jan 2017 12:43:40 +0200 Subject: [PATCH 1675/2280] Add a plugin to update a Kodi music library I created one for an older version before, but it didn't work since the change to Python 3. So I created a new one that works. --- beetsplug/kodiupdate.py | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 beetsplug/kodiupdate.py diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py new file mode 100644 index 000000000..236f914bf --- /dev/null +++ b/beetsplug/kodiupdate.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +"""Updates a Kodi library whenever the beets library is changed. This is based on the Plex Update plugin. + +Put something like the following in your config.yaml to configure: + kodi: + host: localhost + port: 8080 + user: user + pwd: secret +""" +from __future__ import division, absolute_import, print_function + +import requests +import json +from requests.auth import HTTPBasicAuth +from beets import config +from beets.plugins import BeetsPlugin + + +def update_kodi(host, port, user, password): + """Sends request to the Kodi api to start a library refresh. + """ + url = "http://{0}:{1}/jsonrpc/".format(host, port) + + # The kodi jsonrpc documentation states that Content-Type: application/json is mandatory + headers = {'Content-Type': 'application/json'} + # Create the payload. Id seems to be mandatory. + payload = {'jsonrpc': '2.0', 'method':'AudioLibrary.Scan', 'id':1} + r = requests.post(url, auth=HTTPBasicAuth(user, password), json=payload, headers=headers) + return r + +class KodiUpdate(BeetsPlugin): + def __init__(self): + super(KodiUpdate, self).__init__() + + # Adding defaults. + config['kodi'].add({ + u'host': u'localhost', + u'port': 8080, + u'user': u'kodi', + u'pwd': u'kodi'}) + + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update for the end""" + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to Kodi server. + """ + self._log.info(u'Updating Kodi library...') + + # Try to send update request. + try: + update_kodi( + config['kodi']['host'].get(), + config['kodi']['port'].get(), + config['kodi']['user'].get(), + config['kodi']['pwd'].get()) + self._log.info(u'... started.') + + except requests.exceptions.RequestException: + self._log.warning(u'Update failed.') + From ca8832809daf6e57b5bd61a3b2c03640b22dbe9c Mon Sep 17 00:00:00 2001 From: Pauligrinder Date: Mon, 23 Jan 2017 13:14:36 +0200 Subject: [PATCH 1676/2280] Removed a couple of unnecessary imports json and requests.BasicAuthentication --- beetsplug/kodiupdate.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py index 236f914bf..31c978dd6 100644 --- a/beetsplug/kodiupdate.py +++ b/beetsplug/kodiupdate.py @@ -12,8 +12,6 @@ Put something like the following in your config.yaml to configure: from __future__ import division, absolute_import, print_function import requests -import json -from requests.auth import HTTPBasicAuth from beets import config from beets.plugins import BeetsPlugin @@ -27,7 +25,7 @@ def update_kodi(host, port, user, password): headers = {'Content-Type': 'application/json'} # Create the payload. Id seems to be mandatory. payload = {'jsonrpc': '2.0', 'method':'AudioLibrary.Scan', 'id':1} - r = requests.post(url, auth=HTTPBasicAuth(user, password), json=payload, headers=headers) + r = requests.post(url, auth=(user, password), json=payload, headers=headers) return r class KodiUpdate(BeetsPlugin): From 2ab1f3ae89eb74c43acbcf8addfcdb5a52b31106 Mon Sep 17 00:00:00 2001 From: Artem Utin Date: Mon, 23 Jan 2017 23:15:14 +1000 Subject: [PATCH 1677/2280] More general approach to multiple on_play calls for the same song - now it ignores such calls, if time between calls was below threshold --- beetsplug/mpdstats.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 896a34415..9f63181b9 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -263,25 +263,27 @@ class MPDStats(object): played, duration = map(int, status['time'].split(':', 1)) remaining = duration - played - if self.now_playing and self.now_playing['path'] != path: - skipped = self.handle_song_change(self.now_playing) - # mpd responds twice on a natural new song start - going_to_happen_twice = not skipped - else: - going_to_happen_twice = False + if self.now_playing: + if self.now_playing['path'] != path: + self.handle_song_change(self.now_playing) + else: # in case we got mpd play event with same song playing multiple times + # assume low diff means redundant second play event after natural song start + diff = abs(time.time() - self.now_playing['started']) - if not going_to_happen_twice: - self._log.info(u'playing {0}', displayable_path(path)) + if diff <= self.time_threshold: + return - self.now_playing = { - 'started': time.time(), - 'remaining': remaining, - 'path': path, - 'beets_item': self.get_item(path), - } + self._log.info(u'playing {0}', displayable_path(path)) - self.update_item(self.now_playing['beets_item'], - 'last_played', value=int(time.time())) + self.now_playing = { + 'started': time.time(), + 'remaining': remaining, + 'path': path, + 'beets_item': self.get_item(path), + } + + self.update_item(self.now_playing['beets_item'], + 'last_played', value=int(time.time())) def run(self): self.mpd.connect() From 40eef2056cedee5b9cc5f1d01d89a67ca85fc8ee Mon Sep 17 00:00:00 2001 From: Artem Utin Date: Tue, 24 Jan 2017 11:41:26 +1000 Subject: [PATCH 1678/2280] Add changelog entry, wrap long comment lines. --- beetsplug/mpdstats.py | 7 +++++-- docs/changelog.rst | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 9f63181b9..bcc3da808 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -266,8 +266,11 @@ class MPDStats(object): if self.now_playing: if self.now_playing['path'] != path: self.handle_song_change(self.now_playing) - else: # in case we got mpd play event with same song playing multiple times - # assume low diff means redundant second play event after natural song start + else: + # In case we got mpd play event with same song playing + # multiple times, + # assume low diff means redundant second play event + # after natural song start. diff = abs(time.time() - self.now_playing['started']) if diff <= self.time_threshold: diff --git a/docs/changelog.rst b/docs/changelog.rst index 667d9b99f..3ab7940e2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,6 +31,7 @@ Fixes: * :doc:`/plugins/bpd`: Report playback times as integer. :bug:`2394` * :doc:`/plugins/mpdstats`: Fix Python 3 compatibility. The plugin also now requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` +* :doc:`/plugins/mpdstats`: Improve handling of mpd status queries. 1.4.3 (January 9, 2017) From bc582701ffca952e2e618912518b8e5c994fa5dc Mon Sep 17 00:00:00 2001 From: wordofglass Date: Wed, 25 Jan 2017 00:01:05 +0100 Subject: [PATCH 1679/2280] fetchart: Internally pass settings in a cleaner way. Dump the 'extra' dictionary which only duplicated attributes of the plugin onject in favor of passing a reference to the plugin directly. --- beetsplug/fetchart.py | 88 ++++++++++++++++++------------------------- test/test_art.py | 69 ++++++++++++++++++--------------- 2 files changed, 76 insertions(+), 81 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index d87a5dc48..91b77c0a4 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -69,7 +69,7 @@ class Candidate(object): self.match = match self.size = size - def _validate(self, extra): + def _validate(self, plugin): """Determine whether the candidate artwork is valid based on its dimensions (width and ratio). @@ -80,9 +80,7 @@ class Candidate(object): if not self.path: return self.CANDIDATE_BAD - if not (extra['enforce_ratio'] or - extra['minwidth'] or - extra['maxwidth']): + if not (plugin.enforce_ratio or plugin.minwidth or plugin.maxwidth): return self.CANDIDATE_EXACT # get_size returns None if no local imaging backend is available @@ -101,22 +99,22 @@ class Candidate(object): long_edge = max(self.size) # Check minimum size. - if extra['minwidth'] and self.size[0] < extra['minwidth']: + if plugin.minwidth and self.size[0] < plugin.minwidth: self._log.debug(u'image too small ({} < {})', - self.size[0], extra['minwidth']) + self.size[0], plugin.minwidth) return self.CANDIDATE_BAD # Check aspect ratio. edge_diff = long_edge - short_edge - if extra['enforce_ratio']: - if extra['margin_px']: - if edge_diff > extra['margin_px']: + if plugin.enforce_ratio: + if plugin.margin_px: + if edge_diff > plugin.margin_px: self._log.debug(u'image is not close enough to being ' u'square, ({} - {} > {})', - long_edge, short_edge, extra['margin_px']) + long_edge, short_edge, plugin.margin_px) return self.CANDIDATE_BAD - elif extra['margin_percent']: - margin_px = extra['margin_percent'] * long_edge + elif plugin.margin_percent: + margin_px = plugin.margin_percent * long_edge if edge_diff > margin_px: self._log.debug(u'image is not close enough to being ' u'square, ({} - {} > {})', @@ -129,20 +127,20 @@ class Candidate(object): return self.CANDIDATE_BAD # Check maximum size. - if extra['maxwidth'] and self.size[0] > extra['maxwidth']: + if plugin.maxwidth and self.size[0] > plugin.maxwidth: self._log.debug(u'image needs resizing ({} > {})', - self.size[0], extra['maxwidth']) + self.size[0], plugin.maxwidth) return self.CANDIDATE_DOWNSCALE return self.CANDIDATE_EXACT - def validate(self, extra): - self.check = self._validate(extra) + def validate(self, plugin): + self.check = self._validate(plugin) return self.check - def resize(self, extra): - if extra['maxwidth'] and self.check == self.CANDIDATE_DOWNSCALE: - self.path = ArtResizer.shared.resize(extra['maxwidth'], self.path) + def resize(self, plugin): + if plugin.maxwidth and self.check == self.CANDIDATE_DOWNSCALE: + self.path = ArtResizer.shared.resize(plugin.maxwidth, self.path) def _logged_get(log, *args, **kwargs): @@ -198,13 +196,13 @@ class ArtSource(RequestMixin): self._log = log self._config = config - def get(self, album, extra): + def get(self, album, plugin, paths): raise NotImplementedError() def _candidate(self, **kwargs): return Candidate(source=self, log=self._log, **kwargs) - def fetch_image(self, candidate, extra): + def fetch_image(self, candidate, plugin): raise NotImplementedError() @@ -212,7 +210,7 @@ class LocalArtSource(ArtSource): IS_LOCAL = True LOC_STR = u'local' - def fetch_image(self, candidate, extra): + def fetch_image(self, candidate, plugin): pass @@ -220,13 +218,13 @@ class RemoteArtSource(ArtSource): IS_LOCAL = False LOC_STR = u'remote' - def fetch_image(self, candidate, extra): + def fetch_image(self, candidate, plugin): """Downloads an image from a URL and checks whether it seems to actually be an image. If so, returns a path to the downloaded image. Otherwise, returns None. """ - if extra['maxwidth']: - candidate.url = ArtResizer.shared.proxy_url(extra['maxwidth'], + if plugin.maxwidth: + candidate.url = ArtResizer.shared.proxy_url(plugin.maxwidth, candidate.url) try: with closing(self.request(candidate.url, stream=True, @@ -299,7 +297,7 @@ class CoverArtArchive(RemoteArtSource): URL = 'http://coverartarchive.org/release/{mbid}/front' GROUP_URL = 'http://coverartarchive.org/release-group/{mbid}/front' - def get(self, album, extra): + def get(self, album, plugin, paths): """Return the Cover Art Archive and Cover Art Archive release group URLs using album MusicBrainz release ID and release group ID. """ @@ -317,7 +315,7 @@ class Amazon(RemoteArtSource): URL = 'http://images.amazon.com/images/P/%s.%02i.LZZZZZZZ.jpg' INDICES = (1, 2) - def get(self, album, extra): + def get(self, album, plugin, paths): """Generate URLs using Amazon ID (ASIN) string. """ if album.asin: @@ -331,7 +329,7 @@ class AlbumArtOrg(RemoteArtSource): URL = 'http://www.albumart.org/index_detail.php' PAT = r'href\s*=\s*"([^>"]*)"[^>]*title\s*=\s*"View larger image"' - def get(self, album, extra): + def get(self, album, plugin, paths): """Return art URL from AlbumArt.org using album ASIN. """ if not album.asin: @@ -362,7 +360,7 @@ class GoogleImages(RemoteArtSource): self.key = self._config['google_key'].get(), self.cx = self._config['google_engine'].get(), - def get(self, album, extra): + def get(self, album, plugin, paths): """Return art URL from google custom search engine given an album title and interpreter. """ @@ -406,7 +404,7 @@ class FanartTV(RemoteArtSource): super(FanartTV, self).__init__(*args, **kwargs) self.client_key = self._config['fanarttv_key'].get() - def get(self, album, extra): + def get(self, album, plugin, paths): if not album.mb_releasegroupid: return @@ -457,7 +455,7 @@ class FanartTV(RemoteArtSource): class ITunesStore(RemoteArtSource): NAME = u"iTunes Store" - def get(self, album, extra): + def get(self, album, plugin, paths): """Return art URL from iTunes Store given an album title. """ if not (album.albumartist and album.album): @@ -515,7 +513,7 @@ class Wikipedia(RemoteArtSource): }} Limit 1''' - def get(self, album, extra): + def get(self, album, plugin, paths): if not (album.albumartist and album.album): return @@ -627,16 +625,14 @@ class FileSystem(LocalArtSource): """ return [idx for (idx, x) in enumerate(cover_names) if x in filename] - def get(self, album, extra): + def get(self, album, plugin, paths): """Look for album art files in the specified directories. """ - paths = extra['paths'] if not paths: return - cover_names = list(map(util.bytestring_path, extra['cover_names'])) + cover_names = list(map(util.bytestring_path, plugin.cover_names)) cover_names_str = b'|'.join(cover_names) cover_pat = br''.join([br"(\b|_)(", cover_names_str, br")(\b|_)"]) - cautious = extra['cautious'] for path in paths: if not os.path.isdir(syspath(path)): @@ -666,7 +662,7 @@ class FileSystem(LocalArtSource): remaining.append(fn) # Fall back to any image in the folder. - if remaining and not cautious: + if remaining and not plugin.cautious: self._log.debug(u'using fallback art file {0}', util.displayable_path(remaining[0])) yield self._candidate(path=os.path.join(path, remaining[0]), @@ -845,16 +841,6 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): """ out = None - # all the information any of the sources might need - extra = {'paths': paths, - 'cover_names': self.cover_names, - 'cautious': self.cautious, - 'enforce_ratio': self.enforce_ratio, - 'margin_px': self.margin_px, - 'margin_percent': self.margin_percent, - 'minwidth': self.minwidth, - 'maxwidth': self.maxwidth} - for source in self.sources: if source.IS_LOCAL or not local_only: self._log.debug( @@ -864,9 +850,9 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): ) # URLs might be invalid at this point, or the image may not # fulfill the requirements - for candidate in source.get(album, extra): - source.fetch_image(candidate, extra) - if candidate.validate(extra): + for candidate in source.get(album, self, paths): + source.fetch_image(candidate, self) + if candidate.validate(self): out = candidate self._log.debug( u'using {0.LOC_STR} image {1}'.format( @@ -876,7 +862,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): break if out: - out.resize(extra) + out.resize(self) return out diff --git a/test/test_art.py b/test/test_art.py index 50ff26b00..d47b280c2 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -39,6 +39,13 @@ from beets.util import confit logger = logging.getLogger('beets.test_art') +class Settings(): + """Used to pass settings to the ArtSources when the plugin isn't fully + instantiated. + """ + pass + + class UseThePlugin(_common.TestCase): def setUp(self): super(UseThePlugin, self).setUp() @@ -73,28 +80,29 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) - self.extra = {'maxwidth': 0} + self.settings = Settings() + self.settings.maxwidth = 0 self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): self.mock_response(self.URL, 'image/watercolour') - self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate, self.settings) self.assertEqual(self.candidate.path, None) def test_jpeg_type_returns_path(self): self.mock_response(self.URL, 'image/jpeg') - self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate, self.settings) self.assertNotEqual(self.candidate.path, None) def test_extension_set_by_content_type(self): self.mock_response(self.URL, 'image/png') - self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate, self.settings) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) def test_does_not_rely_on_server_content_type(self): self.mock_response(self.URL, 'image/jpeg', 'image/png') - self.source.fetch_image(self.candidate, self.extra) + self.source.fetch_image(self.candidate, self.settings) self.assertEqual(os.path.splitext(self.candidate.path)[1], b'.png') self.assertExists(self.candidate.path) @@ -106,44 +114,44 @@ class FSArtTest(UseThePlugin): os.mkdir(self.dpath) self.source = fetchart.FileSystem(logger, self.plugin.config) - self.extra = {'cautious': False, - 'cover_names': ('art',), - 'paths': [self.dpath]} + self.settings = Settings() + self.settings.cautious = False + self.settings.cover_names = ('art',) def test_finds_jpg_in_directory(self): _common.touch(os.path.join(self.dpath, b'a.jpg')) - candidate = next(self.source.get(None, self.extra)) + candidate = next(self.source.get(None, self.settings, [self.dpath])) self.assertEqual(candidate.path, os.path.join(self.dpath, b'a.jpg')) def test_appropriately_named_file_takes_precedence(self): _common.touch(os.path.join(self.dpath, b'a.jpg')) _common.touch(os.path.join(self.dpath, b'art.jpg')) - candidate = next(self.source.get(None, self.extra)) + candidate = next(self.source.get(None, self.settings, [self.dpath])) self.assertEqual(candidate.path, os.path.join(self.dpath, b'art.jpg')) def test_non_image_file_not_identified(self): _common.touch(os.path.join(self.dpath, b'a.txt')) with self.assertRaises(StopIteration): - next(self.source.get(None, self.extra)) + next(self.source.get(None, self.settings, [self.dpath])) def test_cautious_skips_fallback(self): _common.touch(os.path.join(self.dpath, b'a.jpg')) - self.extra['cautious'] = True + self.settings.cautious = True with self.assertRaises(StopIteration): - next(self.source.get(None, self.extra)) + next(self.source.get(None, self.settings, [self.dpath])) def test_empty_dir(self): with self.assertRaises(StopIteration): - next(self.source.get(None, self.extra)) + next(self.source.get(None, self.settings, [self.dpath])) def test_precedence_amongst_correct_files(self): images = [b'front-cover.jpg', b'front.jpg', b'back.jpg'] paths = [os.path.join(self.dpath, i) for i in images] for p in paths: _common.touch(p) - self.extra['cover_names'] = ['cover', 'front', 'back'] + self.settings.cover_names = ['cover', 'front', 'back'] candidates = [candidate.path for candidate in - self.source.get(None, self.extra)] + self.source.get(None, self.settings, [self.dpath])] self.assertEqual(candidates, paths) @@ -236,7 +244,7 @@ class AAOTest(UseThePlugin): def setUp(self): super(AAOTest, self).setUp() self.source = fetchart.AlbumArtOrg(logger, self.plugin.config) - self.extra = dict() + self.settings = Settings() @responses.activate def run(self, *args, **kwargs): @@ -256,21 +264,21 @@ class AAOTest(UseThePlugin): """ self.mock_response(self.AAO_URL, body) album = _common.Bag(asin=self.ASIN) - candidate = next(self.source.get(album, self.extra)) + candidate = next(self.source.get(album, self.settings, [])) self.assertEqual(candidate.url, 'TARGET_URL') def test_aao_scraper_returns_no_result_when_no_image_present(self): self.mock_response(self.AAO_URL, 'blah blah') album = _common.Bag(asin=self.ASIN) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) class GoogleImageTest(UseThePlugin): def setUp(self): super(GoogleImageTest, self).setUp() self.source = fetchart.GoogleImages(logger, self.plugin.config) - self.extra = dict() + self.settings = Settings() @responses.activate def run(self, *args, **kwargs): @@ -284,7 +292,7 @@ class GoogleImageTest(UseThePlugin): album = _common.Bag(albumartist="some artist", album="some album") json = '{"items": [{"link": "url_to_the_image"}]}' self.mock_response(fetchart.GoogleImages.URL, json) - candidate = next(self.source.get(album, self.extra)) + candidate = next(self.source.get(album, self.settings, [])) self.assertEqual(candidate.url, 'url_to_the_image') def test_google_art_returns_no_result_when_error_received(self): @@ -292,14 +300,14 @@ class GoogleImageTest(UseThePlugin): json = '{"error": {"errors": [{"reason": "some reason"}]}}' self.mock_response(fetchart.GoogleImages.URL, json) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) def test_google_art_returns_no_result_with_malformed_response(self): album = _common.Bag(albumartist="some artist", album="some album") json = """bla blup""" self.mock_response(fetchart.GoogleImages.URL, json) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) class FanartTVTest(UseThePlugin): @@ -363,7 +371,7 @@ class FanartTVTest(UseThePlugin): def setUp(self): super(FanartTVTest, self).setUp() self.source = fetchart.FanartTV(logger, self.plugin.config) - self.extra = dict() + self.settings = Settings() @responses.activate def run(self, *args, **kwargs): @@ -377,7 +385,7 @@ class FanartTVTest(UseThePlugin): album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', self.RESPONSE_MULTIPLE) - candidate = next(self.source.get(album, self.extra)) + candidate = next(self.source.get(album, self.settings, [])) self.assertEqual(candidate.url, 'http://example.com/1.jpg') def test_fanarttv_returns_no_result_when_error_received(self): @@ -385,14 +393,14 @@ class FanartTVTest(UseThePlugin): self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', self.RESPONSE_ERROR) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) def test_fanarttv_returns_no_result_with_malformed_response(self): album = _common.Bag(mb_releasegroupid=u'thereleasegroupid') self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', self.RESPONSE_MALFORMED) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) def test_fanarttv_only_other_images(self): # The source used to fail when there were images present, but no cover @@ -400,7 +408,7 @@ class FanartTVTest(UseThePlugin): self.mock_response(fetchart.FanartTV.API_ALBUMS + u'thereleasegroupid', self.RESPONSE_NO_ART) with self.assertRaises(StopIteration): - next(self.source.get(album, self.extra)) + next(self.source.get(album, self.settings, [])) @_common.slow_test() @@ -528,8 +536,8 @@ class ArtForAlbumTest(UseThePlugin): self.old_fs_source_get = fetchart.FileSystem.get - def fs_source_get(_self, album, extra): - if extra['paths']: + def fs_source_get(_self, album, settings, paths): + if paths: yield fetchart.Candidate(logger, path=self.image_file) fetchart.FileSystem.get = fs_source_get @@ -657,5 +665,6 @@ class EnforceRatioConfigTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) + if __name__ == '__main__': unittest.main(defaultTest='suite') From 24027d1bf8f1910fb9dfb3e7d6e76a6f2185d1af Mon Sep 17 00:00:00 2001 From: "A.L. Kleijngeld" Date: Fri, 27 Jan 2017 21:48:46 +0100 Subject: [PATCH 1680/2280] Update config.rst: see issue #2410 `When a match is above the *medium* recommendation threshold` -> `When a match is below the *medium* recommendation threshold` As discussed in issue #2410, which is fixed by this edit. --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 8e43e2dd7..779e920d2 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -620,7 +620,7 @@ automatically accept any matches above 90% similarity, use:: The default strong recommendation threshold is 0.04. The ``medium_rec_thresh`` and ``rec_gap_thresh`` options work similarly. When a -match is above the *medium* recommendation threshold or the distance between it +match is below the *medium* recommendation threshold or the distance between it and the next-best match is above the *gap* threshold, the importer will suggest that match but not automatically confirm it. Otherwise, you'll see a list of options to choose from. From 47b0b54fa1a6d76c5035f82b4cde9903f4381d7c Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 19:15:21 +0100 Subject: [PATCH 1681/2280] trying relative dates --- beets/dbcore/query.py | 51 +++++++++++++++++++++++++++++++------------ tox.ini | 1 + 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 470ca2ac6..8d778074f 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -21,6 +21,7 @@ import re from operator import mul from beets import util from datetime import datetime, timedelta +from dateutil.relativedelta import relativedelta import unicodedata from functools import reduce import six @@ -533,8 +534,9 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day') + precisions = ('year', 'month', 'day', 'relative') date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') + relative = ('y', 'm', 'w', 'd') def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -550,19 +552,38 @@ class Period(object): """Parse a date and return a `Period` object or `None` if the string is empty. """ - if not string: - return None - ordinal = string.count('-') - if ordinal >= len(cls.date_formats): - # Too many components. - return None - date_format = cls.date_formats[ordinal] - try: - date = datetime.strptime(string, date_format) - except ValueError: - # Parsing failed. - return None - precision = cls.precisions[ordinal] + if re.match('@([+|-]?)(\d+)([y|m|w|d])', string) is not None: + sign = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(1) + quantity = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(2) + timespan = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(3) + if sign == '-': + m = -1 + else: + m = 1 + if timespan == 'y': + date = datetime.now() + m*relativedelta(years=int(quantity)) + elif timespan == 'm': + date = datetime.now() + m*relativedelta(months=int(quantity)) + elif timespan == 'w': + date = datetime.now() + m*relativedelta(weeks=int(quantity)) + elif timespan == 'd': + date = datetime.now() + m*relativedelta(days=int(quantity)) + + precision = 'relative' + else: + if not string: + return None + ordinal = string.count('-') + if ordinal >= len(cls.date_formats): + # Too many components. + return None + date_format = cls.date_formats[ordinal] + try: + date = datetime.strptime(string, date_format) + except ValueError: + # Parsing failed. + return None + precision = cls.precisions[ordinal] return cls(date, precision) def open_right_endpoint(self): @@ -571,6 +592,8 @@ class Period(object): """ precision = self.precision date = self.date + if 'relative' == self.precision: + return date if 'year' == self.precision: return date.replace(year=date.year + 1, month=1) elif 'month' == precision: diff --git a/tox.ini b/tox.ini index 43bff8014..477e3c874 100644 --- a/tox.ini +++ b/tox.ini @@ -24,6 +24,7 @@ deps = python-mpd2 coverage discogs-client + dateutils [_flake8] deps = From 5624e24622b2554f9cce1d002868b25e80122e8e Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 19:19:01 +0100 Subject: [PATCH 1682/2280] trying relative dates --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 1019a74a7..ec582105f 100755 --- a/setup.py +++ b/setup.py @@ -106,7 +106,8 @@ setup( 'pyxdg', 'pathlib', 'python-mpd2', - 'discogs-client' + 'discogs-client', + 'dateutils' ], # Plugin (optional) dependencies: From 03dfaf97ee0ca7778db4799a07e7aa1662f6447d Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 20:15:08 +0100 Subject: [PATCH 1683/2280] wrong dateutil package --- setup.py | 2 +- tox.ini | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index ec582105f..cd3911134 100755 --- a/setup.py +++ b/setup.py @@ -107,7 +107,7 @@ setup( 'pathlib', 'python-mpd2', 'discogs-client', - 'dateutils' + 'python-dateutil' ], # Plugin (optional) dependencies: diff --git a/tox.ini b/tox.ini index 477e3c874..8ba69faff 100644 --- a/tox.ini +++ b/tox.ini @@ -24,7 +24,7 @@ deps = python-mpd2 coverage discogs-client - dateutils + python-dateutil [_flake8] deps = From bee758a19643998b1841bcfe3440e94fdd053a13 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 20:15:25 +0100 Subject: [PATCH 1684/2280] some flake8 spacing --- beets/dbcore/query.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 8d778074f..dcbecd595 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -561,13 +561,13 @@ class Period(object): else: m = 1 if timespan == 'y': - date = datetime.now() + m*relativedelta(years=int(quantity)) + date = datetime.now() + m * relativedelta(years=int(quantity)) elif timespan == 'm': - date = datetime.now() + m*relativedelta(months=int(quantity)) + date = datetime.now() + m * relativedelta(months=int(quantity)) elif timespan == 'w': - date = datetime.now() + m*relativedelta(weeks=int(quantity)) + date = datetime.now() + m * relativedelta(weeks=int(quantity)) elif timespan == 'd': - date = datetime.now() + m*relativedelta(days=int(quantity)) + date = datetime.now() + m * relativedelta(days=int(quantity)) precision = 'relative' else: From 9bc75b042f3728f53a7c8598d6f04838071d0506 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 20:27:28 +0100 Subject: [PATCH 1685/2280] need dateutil in install ? --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index cd3911134..672402603 100755 --- a/setup.py +++ b/setup.py @@ -93,6 +93,7 @@ setup( 'musicbrainzngs>=0.4', 'pyyaml', 'jellyfish', + 'python-dateutil', ] + (['colorama'] if (sys.platform == 'win32') else []) + (['enum34>=1.0.4'] if sys.version_info < (3, 4, 0) else []), @@ -107,7 +108,7 @@ setup( 'pathlib', 'python-mpd2', 'discogs-client', - 'python-dateutil' + 'python-dateutil', ], # Plugin (optional) dependencies: From 48337870cc8318efc7a69ed230f4f2004bb237b7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 28 Jan 2017 15:21:10 -0500 Subject: [PATCH 1686/2280] Bump the required discogs-client version (#2387) --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 1019a74a7..148643837 100755 --- a/setup.py +++ b/setup.py @@ -114,7 +114,7 @@ setup( 'absubmit': ['requests'], 'fetchart': ['requests'], 'chroma': ['pyacoustid'], - 'discogs': ['discogs-client>=2.1.0'], + 'discogs': ['discogs-client>=2.2.1'], 'beatport': ['requests-oauthlib>=0.6.1'], 'lastgenre': ['pylast'], 'mpdstats': ['python-mpd2>=0.4.2'], From 868746bb5110b09f16162a4f47b8f6e473b4403b Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 21:23:03 +0100 Subject: [PATCH 1687/2280] tests --- test/test_datequery.py | 44 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index 1e1625db2..4b01edd2c 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -17,6 +17,7 @@ """ from __future__ import division, absolute_import, print_function +from dateutil.relativedelta import relativedelta from test import _common from datetime import datetime import unittest @@ -28,6 +29,10 @@ def _date(string): return datetime.strptime(string, '%Y-%m-%dT%H:%M:%S') +def _datepattern(datetimedate): + return datetimedate.strftime('%Y-%m-%dT%H:%M:%S') + + class DateIntervalTest(unittest.TestCase): def test_year_precision_intervals(self): self.assertContains('2000..2001', '2000-01-01T00:00:00') @@ -43,6 +48,9 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..2001', '2001-12-31T23:59:59') self.assertExcludes('..2001', '2002-01-01T00:00:00') + self.assertContains('@-1d..@1d', _datepattern(datetime.now())) + self.assertExcludes('@-2d..@-1d', _datepattern(datetime.now())) + def test_day_precision_intervals(self): self.assertContains('2000-06-20..2000-06-20', '2000-06-20T00:00:00') self.assertContains('2000-06-20..2000-06-20', '2000-06-20T10:20:30') @@ -62,7 +70,8 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..', date=datetime.min) self.assertContains('..', '1000-01-01T00:00:00') - def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa + def assertContains(self, interval_pattern, date_pattern=None, + date=None): # noqa if date is None: date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) @@ -114,6 +123,39 @@ class DateQueryTest(_common.LibTestCase): matched = self.lib.items(query) self.assertEqual(len(matched), 0) +class DateQueryTestRelative(_common.LibTestCase): + def setUp(self): + super(DateQueryTestRelative, self).setUp() + self.i.added = _parsetime(datetime.now().strftime('%Y-%m-%d %H:%M')) + self.i.store() + + def test_single_month_match_fast(self): + query = DateQuery('added', datetime.now().strftime('%Y-%m')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_single_month_nonmatch_fast(self): + query = DateQuery('added', (datetime.now()+relativedelta(months=1)).strftime('%Y-%m')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_single_month_match_slow(self): + query = DateQuery('added', datetime.now().strftime('%Y-%m')) + self.assertTrue(query.match(self.i)) + + def test_single_month_nonmatch_slow(self): + query = DateQuery('added', (datetime.now()+relativedelta(months=1)).strftime('%Y-%m')) + self.assertFalse(query.match(self.i)) + + def test_single_day_match_fast(self): + query = DateQuery('added', datetime.now().strftime('%Y-%m-%d')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_single_day_nonmatch_fast(self): + query = DateQuery('added', (datetime.now()+ relativedelta(days=1)).strftime('%Y-%m-%d')) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): From 8d054f3656aa74762d9473dec67cdc39ea9d471c Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 21:40:26 +0100 Subject: [PATCH 1688/2280] tests flake8 issues added some doc --- docs/reference/query.rst | 15 +++++++++++++++ test/test_datequery.py | 14 +++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 2f3366d4c..c2a5cdf0a 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -162,6 +162,20 @@ Dates are written separated by hyphens, like ``year-month-day``, but the month and day are optional. If you leave out the day, for example, you will get matches for the whole month. +You can also use relative dates to the current time. +Relative dates begin by the ``@`` character, followed by an optional ``+`` or +``-`` sign that will increment or decrement now, followed by the time quantity +that will be represented as an integer followed by either ``d`` for days, ``w`` +for weeks, ``m`` for months and finally ``y`` for year. + +Here is an example that finds all the albums added between now and last week:: + + $ beet ls -a 'added:@-1w..@0d' + +Find all items added in a 2 weeks period 4 weeks ago:: + + $ beet ls -a 'added:@-6w..@-2w' + Date *intervals*, like the numeric intervals described above, are separated by two dots (``..``). You can specify a start, an end, or both. @@ -186,6 +200,7 @@ Find all items with a file modification time between 2008-12-01 and $ beet ls 'mtime:2008-12-01..2008-12-02' + .. _not_query: Query Term Negation diff --git a/test/test_datequery.py b/test/test_datequery.py index 4b01edd2c..e2d1d23a3 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -123,6 +123,7 @@ class DateQueryTest(_common.LibTestCase): matched = self.lib.items(query) self.assertEqual(len(matched), 0) + class DateQueryTestRelative(_common.LibTestCase): def setUp(self): super(DateQueryTestRelative, self).setUp() @@ -135,7 +136,9 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertEqual(len(matched), 1) def test_single_month_nonmatch_fast(self): - query = DateQuery('added', (datetime.now()+relativedelta(months=1)).strftime('%Y-%m')) + query = DateQuery('added', + (datetime.now() + relativedelta(months=1)).strftime( + '%Y-%m')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) @@ -144,7 +147,9 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertTrue(query.match(self.i)) def test_single_month_nonmatch_slow(self): - query = DateQuery('added', (datetime.now()+relativedelta(months=1)).strftime('%Y-%m')) + query = DateQuery('added', + (datetime.now() + relativedelta(months=1)).strftime( + '%Y-%m')) self.assertFalse(query.match(self.i)) def test_single_day_match_fast(self): @@ -153,10 +158,13 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertEqual(len(matched), 1) def test_single_day_nonmatch_fast(self): - query = DateQuery('added', (datetime.now()+ relativedelta(days=1)).strftime('%Y-%m-%d')) + query = DateQuery('added', + (datetime.now() + relativedelta(days=1)).strftime( + '%Y-%m-%d')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) + class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): DateQuery('added', '1409830085..1412422089') From 2b89b90ab6683922687d179147aafe2565d331d4 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 21:47:01 +0100 Subject: [PATCH 1689/2280] tests flake8 fixed I think finally --- test/test_datequery.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index e2d1d23a3..95e617084 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -70,8 +70,7 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..', date=datetime.min) self.assertContains('..', '1000-01-01T00:00:00') - def assertContains(self, interval_pattern, date_pattern=None, - date=None): # noqa + def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa if date is None: date = _date(date_pattern) (start, end) = _parse_periods(interval_pattern) From 3e76c219fb6a6d893f45efcb49f574970e65e073 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sat, 28 Jan 2017 22:39:37 +0100 Subject: [PATCH 1690/2280] without dateutil --- beets/dbcore/query.py | 10 ++++------ setup.py | 2 -- test/test_datequery.py | 18 +++++++----------- tox.ini | 1 - 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index dcbecd595..0b0cfa6f7 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -21,7 +21,6 @@ import re from operator import mul from beets import util from datetime import datetime, timedelta -from dateutil.relativedelta import relativedelta import unicodedata from functools import reduce import six @@ -561,14 +560,13 @@ class Period(object): else: m = 1 if timespan == 'y': - date = datetime.now() + m * relativedelta(years=int(quantity)) + date = datetime.now() + m * timedelta(days=int(quantity) * 365) elif timespan == 'm': - date = datetime.now() + m * relativedelta(months=int(quantity)) + date = datetime.now() + m * timedelta(days=int(quantity) * 30) elif timespan == 'w': - date = datetime.now() + m * relativedelta(weeks=int(quantity)) + date = datetime.now() + timedelta(days=int(quantity) * 7) elif timespan == 'd': - date = datetime.now() + m * relativedelta(days=int(quantity)) - + date = datetime.now() + m * timedelta(days=int(quantity)) precision = 'relative' else: if not string: diff --git a/setup.py b/setup.py index 672402603..f6e686d35 100755 --- a/setup.py +++ b/setup.py @@ -93,7 +93,6 @@ setup( 'musicbrainzngs>=0.4', 'pyyaml', 'jellyfish', - 'python-dateutil', ] + (['colorama'] if (sys.platform == 'win32') else []) + (['enum34>=1.0.4'] if sys.version_info < (3, 4, 0) else []), @@ -108,7 +107,6 @@ setup( 'pathlib', 'python-mpd2', 'discogs-client', - 'python-dateutil', ], # Plugin (optional) dependencies: diff --git a/test/test_datequery.py b/test/test_datequery.py index 95e617084..cefc03b61 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -17,9 +17,8 @@ """ from __future__ import division, absolute_import, print_function -from dateutil.relativedelta import relativedelta from test import _common -from datetime import datetime +from datetime import datetime, timedelta import unittest import time from beets.dbcore.query import _parse_periods, DateInterval, DateQuery @@ -135,9 +134,8 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertEqual(len(matched), 1) def test_single_month_nonmatch_fast(self): - query = DateQuery('added', - (datetime.now() + relativedelta(months=1)).strftime( - '%Y-%m')) + query = DateQuery('added', (datetime.now() + timedelta(days=30)) + .strftime('%Y-%m')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) @@ -146,9 +144,8 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertTrue(query.match(self.i)) def test_single_month_nonmatch_slow(self): - query = DateQuery('added', - (datetime.now() + relativedelta(months=1)).strftime( - '%Y-%m')) + query = DateQuery('added', (datetime.now() + timedelta(days=30)) + .strftime('%Y-%m')) self.assertFalse(query.match(self.i)) def test_single_day_match_fast(self): @@ -157,9 +154,8 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertEqual(len(matched), 1) def test_single_day_nonmatch_fast(self): - query = DateQuery('added', - (datetime.now() + relativedelta(days=1)).strftime( - '%Y-%m-%d')) + query = DateQuery('added', (datetime.now() + timedelta(days=1)) + .strftime('%Y-%m-%d')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) diff --git a/tox.ini b/tox.ini index 8ba69faff..43bff8014 100644 --- a/tox.ini +++ b/tox.ini @@ -24,7 +24,6 @@ deps = python-mpd2 coverage discogs-client - python-dateutil [_flake8] deps = From af679de8ec1b15035926c1ba69884994046ef20f Mon Sep 17 00:00:00 2001 From: euri10 Date: Sun, 29 Jan 2017 03:51:24 +0100 Subject: [PATCH 1691/2280] using a pattern may avoid copy-paste error when used 3 times after fixed an error with the weeks that didn't use the sign correctly added more tests, this is where py.test fixtures would shine --- beets/dbcore/query.py | 11 ++++++----- test/test_datequery.py | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 0b0cfa6f7..76679b021 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -551,10 +551,11 @@ class Period(object): """Parse a date and return a `Period` object or `None` if the string is empty. """ - if re.match('@([+|-]?)(\d+)([y|m|w|d])', string) is not None: - sign = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(1) - quantity = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(2) - timespan = re.match('@([+|-]?)(\d+)([y|m|w|d])', string).group(3) + pattern_dq = '@([+|-]?)(\d+)([y|m|w|d])' + if re.match(pattern_dq, string) is not None: + sign = re.match(pattern_dq, string).group(1) + quantity = re.match(pattern_dq, string).group(2) + timespan = re.match(pattern_dq, string).group(3) if sign == '-': m = -1 else: @@ -564,7 +565,7 @@ class Period(object): elif timespan == 'm': date = datetime.now() + m * timedelta(days=int(quantity) * 30) elif timespan == 'w': - date = datetime.now() + timedelta(days=int(quantity) * 7) + date = datetime.now() + m * timedelta(days=int(quantity) * 7) elif timespan == 'd': date = datetime.now() + m * timedelta(days=int(quantity)) precision = 'relative' diff --git a/test/test_datequery.py b/test/test_datequery.py index cefc03b61..e74c9a0db 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -160,6 +160,49 @@ class DateQueryTestRelative(_common.LibTestCase): self.assertEqual(len(matched), 0) +class DateQueryTestRelativeMore(_common.LibTestCase): + def setUp(self): + super(DateQueryTestRelativeMore, self).setUp() + self.i.added = _parsetime(datetime.now().strftime('%Y-%m-%d %H:%M')) + self.i.store() + + def test_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '@-4'+timespan+'..@+4'+timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '@-2'+timespan+'..@-1'+timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_start_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '@-4' + timespan + '..') + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_start_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '@4' + timespan + '..') + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + def test_end_relative(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '..@+4' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 1) + + def test_end_relative_fail(self): + for timespan in ['d', 'w', 'm', 'y']: + query = DateQuery('added', '..@-4' + timespan) + matched = self.lib.items(query) + self.assertEqual(len(matched), 0) + + class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): DateQuery('added', '1409830085..1412422089') From d48d1f8e3cf10e158f2398040caec2d778fb73b4 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sun, 29 Jan 2017 03:54:10 +0100 Subject: [PATCH 1692/2280] fixed E226 flake8 --- test/test_datequery.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index e74c9a0db..3e546b195 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -168,13 +168,13 @@ class DateQueryTestRelativeMore(_common.LibTestCase): def test_relative(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-4'+timespan+'..@+4'+timespan) + query = DateQuery('added', '@-4' + timespan + '..@+4'+ timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_relative_fail(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-2'+timespan+'..@-1'+timespan) + query = DateQuery('added', '@-2' + timespan + '..@-1' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 0) From e4a7d37a6d55a9a8cf06423330635b128857fab9 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sun, 29 Jan 2017 11:49:22 +0100 Subject: [PATCH 1693/2280] implementing changes asked corrected rst fixed flake8 in test --- beets/dbcore/query.py | 42 ++++++++++++++++++++++++---------------- docs/reference/query.rst | 2 +- test/test_datequery.py | 2 +- 3 files changed, 27 insertions(+), 19 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 76679b021..337e3074c 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -535,7 +535,7 @@ class Period(object): precisions = ('year', 'month', 'day', 'relative') date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') - relative = ('y', 'm', 'w', 'd') + relative = {'y': 365, 'm': 30, 'w': 7, 'd': 1} def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -550,24 +550,30 @@ class Period(object): def parse(cls, string): """Parse a date and return a `Period` object or `None` if the string is empty. + Depending on the string, the date can be absolute or + relative. + An absolute date has to be like one of the date_formats '%Y' or '%Y-%m' + or '%Y-%m-%d' + A relative date begins by '@ 'and has to follow the pattern_dq format + '@([+|-]?)(\d+)([y|m|w|d])' + - '@' indicates it's a date relative to now() + - the optional '+' or '-' sign, which defaults to '+' will increment or + decrement now() by a certain quantity + - that quantity can be expressed in days, weeks, months or years + respectively 'd', 'w', 'm', 'y' + Please note that this relative calculation is rather approximate as it + makes the assumption of 30 days per month and 365 days per year """ pattern_dq = '@([+|-]?)(\d+)([y|m|w|d])' - if re.match(pattern_dq, string) is not None: - sign = re.match(pattern_dq, string).group(1) - quantity = re.match(pattern_dq, string).group(2) - timespan = re.match(pattern_dq, string).group(3) - if sign == '-': - m = -1 - else: - m = 1 - if timespan == 'y': - date = datetime.now() + m * timedelta(days=int(quantity) * 365) - elif timespan == 'm': - date = datetime.now() + m * timedelta(days=int(quantity) * 30) - elif timespan == 'w': - date = datetime.now() + m * timedelta(days=int(quantity) * 7) - elif timespan == 'd': - date = datetime.now() + m * timedelta(days=int(quantity)) + match_dq = re.match(pattern_dq, string) + if match_dq is not None: + sign = match_dq.group(1) + quantity = match_dq.group(2) + timespan = match_dq.group(3) + multiplier = -1 if sign == '-' else 1 + days = cls.relative[timespan] + date = datetime.now() + multiplier * timedelta( + days=int(quantity) * days) precision = 'relative' else: if not string: @@ -648,6 +654,7 @@ class DateQuery(FieldQuery): The value of a date field can be matched against a date interval by using an ellipsis interval syntax similar to that of NumericQuery. """ + def __init__(self, field, pattern, fast=True): super(DateQuery, self).__init__(field, pattern, fast) start, end = _parse_periods(pattern) @@ -691,6 +698,7 @@ class DurationQuery(NumericQuery): Raises InvalidQueryError when the pattern does not represent an int, float or M:SS time interval. """ + def _convert(self, s): """Convert a M:SS or numeric string to a float. diff --git a/docs/reference/query.rst b/docs/reference/query.rst index c2a5cdf0a..da97b0d87 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -170,7 +170,7 @@ for weeks, ``m`` for months and finally ``y`` for year. Here is an example that finds all the albums added between now and last week:: - $ beet ls -a 'added:@-1w..@0d' + $ beet ls -a 'added:@-1w..' Find all items added in a 2 weeks period 4 weeks ago:: diff --git a/test/test_datequery.py b/test/test_datequery.py index 3e546b195..d0c18e229 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -168,7 +168,7 @@ class DateQueryTestRelativeMore(_common.LibTestCase): def test_relative(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-4' + timespan + '..@+4'+ timespan) + query = DateQuery('added', '@-4' + timespan + '..@+4' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 1) From c9177f2b5672642c19542c4a8c7c8c42baf4d221 Mon Sep 17 00:00:00 2001 From: euri10 Date: Sun, 29 Jan 2017 14:38:25 +0100 Subject: [PATCH 1694/2280] removed unrelated PR changes corrected docs with correct example added relative date usage to it --- docs/reference/query.rst | 17 +++++++++++------ setup.py | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index da97b0d87..6c0dae5ae 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -163,10 +163,16 @@ and day are optional. If you leave out the day, for example, you will get matches for the whole month. You can also use relative dates to the current time. -Relative dates begin by the ``@`` character, followed by an optional ``+`` or -``-`` sign that will increment or decrement now, followed by the time quantity -that will be represented as an integer followed by either ``d`` for days, ``w`` -for weeks, ``m`` for months and finally ``y`` for year. +A relative date begins by ``@`` and has to follow the pattern_dq format +``@([+|-]?)(\d+)([y|m|w|d])`` +- ``@`` indicates it's a date relative to now() +- the optional ``+`` or ``-`` sign, which defaults to ``+`` will increment or +decrement now() by a certain quantity +- that quantity can be expressed in days, weeks, months or years respectively +'d', 'w', 'm', 'y' + +Please note that this relative calculation is rather approximate as it makes +the assumption of 30 days per month and 365 days per year. Here is an example that finds all the albums added between now and last week:: @@ -174,7 +180,7 @@ Here is an example that finds all the albums added between now and last week:: Find all items added in a 2 weeks period 4 weeks ago:: - $ beet ls -a 'added:@-6w..@-2w' + $ beet ls -a 'added:@-6w..@-4w' Date *intervals*, like the numeric intervals described above, are separated by two dots (``..``). You can specify a start, an end, or both. @@ -200,7 +206,6 @@ Find all items with a file modification time between 2008-12-01 and $ beet ls 'mtime:2008-12-01..2008-12-02' - .. _not_query: Query Term Negation diff --git a/setup.py b/setup.py index f6e686d35..1019a74a7 100755 --- a/setup.py +++ b/setup.py @@ -106,7 +106,7 @@ setup( 'pyxdg', 'pathlib', 'python-mpd2', - 'discogs-client', + 'discogs-client' ], # Plugin (optional) dependencies: From f0aca5e0d352b1273db464f910948f851311784b Mon Sep 17 00:00:00 2001 From: euri10 Date: Mon, 30 Jan 2017 09:06:26 +0100 Subject: [PATCH 1695/2280] Explain relative dates The previous version wasn't user-friendly enough and too technical. --- docs/reference/query.rst | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 6c0dae5ae..4e379f70f 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -163,16 +163,20 @@ and day are optional. If you leave out the day, for example, you will get matches for the whole month. You can also use relative dates to the current time. -A relative date begins by ``@`` and has to follow the pattern_dq format -``@([+|-]?)(\d+)([y|m|w|d])`` -- ``@`` indicates it's a date relative to now() -- the optional ``+`` or ``-`` sign, which defaults to ``+`` will increment or -decrement now() by a certain quantity -- that quantity can be expressed in days, weeks, months or years respectively -'d', 'w', 'm', 'y' +A relative date begins with an ``@``. +It looks like ``@-3w``, ``@2m`` or ``@-4d`` which means the date 3 weeks ago, +the date 2 months from now and the date 4 days ago. +A relative date consists of four parts: +- ``@`` indicates it's a date relative from now +- ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will +add a time quantity to the current date while the ``-`` sign will do the +opposite +- a number follows and indicates the amount to add or substract +- a final letter ends and represents the amount in either days, weeks, months or +years (``d``, ``w``, ``m`` or ``y``) -Please note that this relative calculation is rather approximate as it makes -the assumption of 30 days per month and 365 days per year. +Please note that this relative calculation makes the assumption of 30 days per +month and 365 days per year. Here is an example that finds all the albums added between now and last week:: From 7c79d8ce89ff1ee9096ba0d12847e0999764c08e Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 30 Jan 2017 10:01:19 +0100 Subject: [PATCH 1696/2280] fetchart: minor restructuring of tests. --- test/test_art.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/test_art.py b/test/test_art.py index d47b280c2..6b0e5bbc5 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -43,7 +43,9 @@ class Settings(): """Used to pass settings to the ArtSources when the plugin isn't fully instantiated. """ - pass + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) class UseThePlugin(_common.TestCase): @@ -80,8 +82,7 @@ class FetchImageTest(FetchImageHelper, UseThePlugin): super(FetchImageTest, self).setUp() self.dpath = os.path.join(self.temp_dir, b'arttest') self.source = fetchart.RemoteArtSource(logger, self.plugin.config) - self.settings = Settings() - self.settings.maxwidth = 0 + self.settings = Settings(maxwidth=0) self.candidate = fetchart.Candidate(logger, url=self.URL) def test_invalid_type_returns_none(self): @@ -114,9 +115,8 @@ class FSArtTest(UseThePlugin): os.mkdir(self.dpath) self.source = fetchart.FileSystem(logger, self.plugin.config) - self.settings = Settings() - self.settings.cautious = False - self.settings.cover_names = ('art',) + self.settings = Settings(cautious=False, + cover_names=('art',)) def test_finds_jpg_in_directory(self): _common.touch(os.path.join(self.dpath, b'a.jpg')) From 8638157e17c74ef54bd319958151f972317be852 Mon Sep 17 00:00:00 2001 From: Jeffrey Aylesworth Date: Mon, 30 Jan 2017 23:37:01 -0500 Subject: [PATCH 1697/2280] Change license and email address in mbcollection plugin. --- beetsplug/mbcollection.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index a590a7605..909e6a0a5 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -1,17 +1,17 @@ # -*- coding: utf-8 -*- -# Copyright (c) 2011, Jeffrey Aylesworth +# This file is part of beets. +# Copyright (c) 2011, Jeffrey Aylesworth # -# Permission to use, copy, modify, and/or distribute this software for any -# purpose with or without fee is hereby granted, provided that the above -# copyright notice and this permission notice appear in all copies. +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: # -# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. from __future__ import division, absolute_import, print_function From d2cd4c0f218a5ba433d9d11e8693472c69496fbe Mon Sep 17 00:00:00 2001 From: euri10 Date: Tue, 31 Jan 2017 16:56:03 +0100 Subject: [PATCH 1698/2280] Change relative date's format to further simplify it A relative date doesn't need to be prefixed by @ anymore. The relative date pattern now displays named groups. Digits have been change to [0-9] to avoid other digit characters. Removed the @ character in tests. Updated subsequent documentation. --- beets/dbcore/query.py | 29 ++++++++++++++++------------- docs/reference/query.rst | 9 ++++----- test/test_datequery.py | 16 ++++++++-------- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 337e3074c..51f011a1d 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -554,22 +554,25 @@ class Period(object): relative. An absolute date has to be like one of the date_formats '%Y' or '%Y-%m' or '%Y-%m-%d' - A relative date begins by '@ 'and has to follow the pattern_dq format - '@([+|-]?)(\d+)([y|m|w|d])' - - '@' indicates it's a date relative to now() - - the optional '+' or '-' sign, which defaults to '+' will increment or - decrement now() by a certain quantity - - that quantity can be expressed in days, weeks, months or years - respectively 'd', 'w', 'm', 'y' - Please note that this relative calculation is rather approximate as it - makes the assumption of 30 days per month and 365 days per year + A relative date consists of three parts: + - a ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` + sign will add a time quantity to the current date while the ``-`` sign + will do the opposite + - a number follows and indicates the amount to add or substract + - a final letter ends and represents the amount in either days, weeks, + months or years (``d``, ``w``, ``m`` or ``y``) + Please note that this relative calculation makes the assumption of 30 + days per month and 365 days per year. """ - pattern_dq = '@([+|-]?)(\d+)([y|m|w|d])' + + pattern_dq = '(?P[+|-]?)(?P[0-9]+)(?P[y|m|w|d])' # noqa: E501 match_dq = re.match(pattern_dq, string) + # test if the string matches the relative date pattern, add the parsed + # quantity to now in that case if match_dq is not None: - sign = match_dq.group(1) - quantity = match_dq.group(2) - timespan = match_dq.group(3) + sign = match_dq.group('sign') + quantity = match_dq.group('quantity') + timespan = match_dq.group('timespan') multiplier = -1 if sign == '-' else 1 days = cls.relative[timespan] date = datetime.now() + multiplier * timedelta( diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 4e379f70f..c9678589f 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -166,8 +166,7 @@ You can also use relative dates to the current time. A relative date begins with an ``@``. It looks like ``@-3w``, ``@2m`` or ``@-4d`` which means the date 3 weeks ago, the date 2 months from now and the date 4 days ago. -A relative date consists of four parts: -- ``@`` indicates it's a date relative from now +A relative date consists of three parts: - ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will add a time quantity to the current date while the ``-`` sign will do the opposite @@ -180,11 +179,11 @@ month and 365 days per year. Here is an example that finds all the albums added between now and last week:: - $ beet ls -a 'added:@-1w..' + $ beet ls -a 'added:-1w..' -Find all items added in a 2 weeks period 4 weeks ago:: +Find all items added in a 2 weeks period 4 weeks ago:: - $ beet ls -a 'added:@-6w..@-4w' + $ beet ls -a 'added:-6w..-4w' Date *intervals*, like the numeric intervals described above, are separated by two dots (``..``). You can specify a start, an end, or both. diff --git a/test/test_datequery.py b/test/test_datequery.py index d0c18e229..0864cac23 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -47,8 +47,8 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('..2001', '2001-12-31T23:59:59') self.assertExcludes('..2001', '2002-01-01T00:00:00') - self.assertContains('@-1d..@1d', _datepattern(datetime.now())) - self.assertExcludes('@-2d..@-1d', _datepattern(datetime.now())) + self.assertContains('-1d..1d', _datepattern(datetime.now())) + self.assertExcludes('-2d..-1d', _datepattern(datetime.now())) def test_day_precision_intervals(self): self.assertContains('2000-06-20..2000-06-20', '2000-06-20T00:00:00') @@ -168,37 +168,37 @@ class DateQueryTestRelativeMore(_common.LibTestCase): def test_relative(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-4' + timespan + '..@+4' + timespan) + query = DateQuery('added', '-4' + timespan + '..+4' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_relative_fail(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-2' + timespan + '..@-1' + timespan) + query = DateQuery('added', '-2' + timespan + '..-1' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 0) def test_start_relative(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@-4' + timespan + '..') + query = DateQuery('added', '-4' + timespan + '..') matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_start_relative_fail(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '@4' + timespan + '..') + query = DateQuery('added', '4' + timespan + '..') matched = self.lib.items(query) self.assertEqual(len(matched), 0) def test_end_relative(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '..@+4' + timespan) + query = DateQuery('added', '..+4' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_end_relative_fail(self): for timespan in ['d', 'w', 'm', 'y']: - query = DateQuery('added', '..@-4' + timespan) + query = DateQuery('added', '..-4' + timespan) matched = self.lib.items(query) self.assertEqual(len(matched), 0) From 707796e60997fb4f4ce14e315b423e324d6a407f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 1 Feb 2017 00:36:37 -0500 Subject: [PATCH 1699/2280] Update Windows registry file for Python 3.6 Closes #2424. --- extra/beets.reg | Bin 434 -> 464 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/extra/beets.reg b/extra/beets.reg index 30fb6e0e4dd1a1879fef9f6108a66cac9337588d..c02303d3d896c404e45cc5fa6e0038e70d32db6d 100644 GIT binary patch delta 55 zcmdnQe1UmG2%~lpLq0<~LlHwFLoR~?gBwF8Lk>eKLoq`PLkvRzLnT8ALk2@WLmq=M KgW2Rn#y|jW0}MR? delta 25 gcmcb>yoq^32qSMLLkU9$Lq0 Date: Sat, 4 Feb 2017 13:42:24 -0600 Subject: [PATCH 1700/2280] badfiles: Better logging and error handling (#2428) --- beetsplug/badfiles.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 5ab0ae983..64b75ee3b 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -44,10 +44,11 @@ class BadFiles(BeetsPlugin): status = e.returncode except OSError as e: if e.errno == errno.ENOENT: - ui.print_(u"command not found: {}".format(cmd[0])) - sys.exit(1) + raise ui.UserError(u"command not found: {}".format(cmd[0])) else: - raise + raise ui.UserError( + u"error invoking {}: {}".format(cmd[0], e) + ) output = output.decode(sys.getfilesystemencoding()) return status, errors, [line for line in output.split("\n") if line] @@ -96,6 +97,7 @@ class BadFiles(BeetsPlugin): ext = os.path.splitext(item.path)[1][1:] checker = self.get_checker(ext) if not checker: + self._log.debug(u"no checker available for {}", ext) continue path = item.path if not isinstance(path, six.text_type): From 0216ef294a9151e1971f5bb590ca88753dd47dfb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 4 Feb 2017 13:43:23 -0600 Subject: [PATCH 1701/2280] badfiles: Python 3 compatibility Discovered while working on #2428 that we were using an implicit bytes-to-str conversion on the extension. This broke dict lookup on Python 3. --- beetsplug/badfiles.py | 2 +- docs/changelog.rst | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 64b75ee3b..368b6eba0 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -94,7 +94,7 @@ class BadFiles(BeetsPlugin): ui.colorize('text_error', dpath))) # Run the checker against the file if one is found - ext = os.path.splitext(item.path)[1][1:] + ext = os.path.splitext(item.path)[1][1:].decode('utf8', 'ignore') checker = self.get_checker(ext) if not checker: self._log.debug(u"no checker available for {}", ext) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3ab7940e2..50a2ad518 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -32,6 +32,7 @@ Fixes: * :doc:`/plugins/mpdstats`: Fix Python 3 compatibility. The plugin also now requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` * :doc:`/plugins/mpdstats`: Improve handling of mpd status queries. +* :doc:`/plugins/badfiles`: Fix Python 3 compatibility. 1.4.3 (January 9, 2017) From cb7c6bfb69a0d01a06f1d444f1518c0b1e00a34c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 4 Feb 2017 14:16:11 -0600 Subject: [PATCH 1702/2280] Use free-form MP4 tag for album gain (#2426) I'm not sure how this got messed up, but this was: - Trying to store album gain in the track peak part of the SoundCheck tag! - Not writing the album gain to the non-SC free-form RG tag! Together, this led to serious weirdness when writing these fields on AAC files. To be clear, we currently *only* support track-level data for SoundCheck. We also record album-level RG information in non-iTunes tags, but that's separate. A little googling suggests that SoundCheck now has album-level data, but supporting that is a separate issue. --- beets/mediafile.py | 6 +++--- docs/changelog.rst | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index c910c9a86..13f1b2dfb 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1941,9 +1941,9 @@ class MediaFile(object): u'replaygain_album_gain', float_places=2, suffix=u' dB' ), - MP4SoundCheckStorageStyle( - '----:com.apple.iTunes:iTunNORM', - index=1 + MP4StorageStyle( + '----:com.apple.iTunes:replaygain_album_gain', + float_places=2, suffix=' dB' ), StorageStyle( u'REPLAYGAIN_ALBUM_GAIN', diff --git a/docs/changelog.rst b/docs/changelog.rst index 50a2ad518..3ec604a55 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -33,6 +33,8 @@ Fixes: requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` * :doc:`/plugins/mpdstats`: Improve handling of mpd status queries. * :doc:`/plugins/badfiles`: Fix Python 3 compatibility. +* Fix some cases where album-level ReplayGain/SoundCheck metadata would be + written to files incorrectly. :bug:`2426` 1.4.3 (January 9, 2017) From 88d26e76944c66c7f6bd490f4e5269bd37d700a7 Mon Sep 17 00:00:00 2001 From: karpinski Date: Mon, 6 Feb 2017 18:26:15 +0100 Subject: [PATCH 1703/2280] Adding a move option to the importer's CLI and updating the docs. --- beets/ui/commands.py | 4 ++++ docs/changelog.rst | 3 +++ docs/guides/tagger.rst | 3 +++ docs/reference/cli.rst | 3 ++- 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 168f0d515..8a07f6147 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -941,6 +941,10 @@ import_cmd.parser.add_option( u'-C', u'--nocopy', action='store_false', dest='copy', help=u"don't copy tracks (opposite of -c)" ) +import_cmd.parser.add_option( + u'-m', u'--move', action='store_true', dest='move', + help=u"move tracks into the library (overrides -c)" +) import_cmd.parser.add_option( u'-w', u'--write', action='store_true', default=None, help=u"write new metadata to files' tags (default)" diff --git a/docs/changelog.rst b/docs/changelog.rst index 3ec604a55..c78a6fc21 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,9 @@ New features: value. The argument can be any two characters that represent the left and right brackets. It defaults to `[]` and can also be blank to turn off bracketing. :bug:`2397` :bug:`2399` +* Added a ``--move`` or ``-m`` option to the importer so that the files can be + moved to the library instead of being copied or added "in place". + :bug:`2252` :bug:`2429` Fixes: diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 6c0e44f9e..4c9df42f8 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -95,6 +95,9 @@ command-line options you should know: * ``beet import -C``: don't copy imported files to your music directory; leave them where they are +* ``beet import -m``: move imported files to your music directory (overrides + the ``-c`` option) + * ``beet import -l LOGFILE``: write a message to ``LOGFILE`` every time you skip an album or choose to take its tags "as-is" (see below) or the album is skipped as a duplicate; this lets you come back later and reexamine albums diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 92ddc14d0..59e2eeb68 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -72,7 +72,8 @@ box. To extract `rar` files, install the `rarfile`_ package and the Optional command flags: * By default, the command copies files your the library directory and - updates the ID3 tags on your music. If you'd like to leave your music + updates the ID3 tags on your music. In order to move the files, instead of + copying, use the ``-m`` (move) option. If you'd like to leave your music files untouched, try the ``-C`` (don't copy) and ``-W`` (don't write tags) options. You can also disable this behavior by default in the configuration file (below). From ffca8f549fde5904d333613d84e8f28d7d83190d Mon Sep 17 00:00:00 2001 From: karpinski Date: Wed, 8 Feb 2017 18:52:49 +0100 Subject: [PATCH 1704/2280] Allowing the execution to continue to other files if validator is not found or exits with an error. --- beetsplug/badfiles.py | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 368b6eba0..b02923dca 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -30,6 +30,24 @@ import sys import six +class CheckerCommandException(Exception): + """Raised when running a checker failed. + + Attributes: + checker: Checker command name. + path: Path to the file being validated. + errno: Error number from the checker execution error. + msg: Message from the checker execution error. + + """ + + def __init__(self, cmd, oserror): + self.checker = cmd[0] + self.path = cmd[-1] + self.errno = oserror.errno + self.msg = str(oserror) + + class BadFiles(BeetsPlugin): def run_command(self, cmd): self._log.debug(u"running command: {}", @@ -43,12 +61,7 @@ class BadFiles(BeetsPlugin): errors = 1 status = e.returncode except OSError as e: - if e.errno == errno.ENOENT: - raise ui.UserError(u"command not found: {}".format(cmd[0])) - else: - raise ui.UserError( - u"error invoking {}: {}".format(cmd[0], e) - ) + raise CheckerCommandException(cmd, e) output = output.decode(sys.getfilesystemencoding()) return status, errors, [line for line in output.split("\n") if line] @@ -97,12 +110,24 @@ class BadFiles(BeetsPlugin): ext = os.path.splitext(item.path)[1][1:].decode('utf8', 'ignore') checker = self.get_checker(ext) if not checker: - self._log.debug(u"no checker available for {}", ext) + self._log.debug(u"no checker specified in the config for {}", + ext) continue path = item.path if not isinstance(path, six.text_type): path = item.path.decode(sys.getfilesystemencoding()) - status, errors, output = checker(path) + try: + status, errors, output = checker(path) + except CheckerCommandException as e: + if e.errno == errno.ENOENT: + self._log.error( + u"command not found: {} when validating file: {}", + e.checker, + e.path + ) + else: + self._log.error(u"error invoking {}: {}", e.checker, e.msg) + continue if status > 0: ui.print_(u"{}: checker exited withs status {}" .format(ui.colorize('text_error', dpath), status)) From 291803d49ac4ce7b0af2335c6c97132b3e78a317 Mon Sep 17 00:00:00 2001 From: karpinski Date: Wed, 8 Feb 2017 18:54:18 +0100 Subject: [PATCH 1705/2280] Fixing a small typo. --- beetsplug/badfiles.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index b02923dca..beb8942a5 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -129,7 +129,7 @@ class BadFiles(BeetsPlugin): self._log.error(u"error invoking {}: {}", e.checker, e.msg) continue if status > 0: - ui.print_(u"{}: checker exited withs status {}" + ui.print_(u"{}: checker exited with status {}" .format(ui.colorize('text_error', dpath), status)) for line in output: ui.print_(u" {}".format(displayable_path(line))) From b46fb956b76d559c7ce1b7ef912e28edb5c71e9d Mon Sep 17 00:00:00 2001 From: karpinski Date: Thu, 9 Feb 2017 11:31:26 +0100 Subject: [PATCH 1706/2280] Making logging level consistent when checker is not found. --- beetsplug/badfiles.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index beb8942a5..ae378ed20 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -110,7 +110,7 @@ class BadFiles(BeetsPlugin): ext = os.path.splitext(item.path)[1][1:].decode('utf8', 'ignore') checker = self.get_checker(ext) if not checker: - self._log.debug(u"no checker specified in the config for {}", + self._log.error(u"no checker specified in the config for {}", ext) continue path = item.path From 7e6e043f2dbbd3aaa623e3b682a4a539dc5f2971 Mon Sep 17 00:00:00 2001 From: karpinski Date: Fri, 10 Feb 2017 12:53:24 +0100 Subject: [PATCH 1707/2280] Adding a changelog entry. --- docs/changelog.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index c78a6fc21..77b1a61cc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -38,7 +38,9 @@ Fixes: * :doc:`/plugins/badfiles`: Fix Python 3 compatibility. * Fix some cases where album-level ReplayGain/SoundCheck metadata would be written to files incorrectly. :bug:`2426` - +* Fixed the badfiles plugin to allow the execution to continue to other files + if validator command is not found or exists with an error. :bug:`2430` + :bug:`2433` 1.4.3 (January 9, 2017) ----------------------- From 8ef9f68843a0c7a3b6da0a02b807c7e4893209d1 Mon Sep 17 00:00:00 2001 From: Marcin Karpinski Date: Fri, 10 Feb 2017 22:51:23 +0100 Subject: [PATCH 1708/2280] badfiles: only output corrupt files by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit badfiles now only outputs corrupt files by default — to get full output enable verbose mode using -v or --verbose --- beetsplug/badfiles.py | 7 ++++++- docs/changelog.rst | 3 +++ docs/plugins/badfiles.rst | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 368b6eba0..40a3ef7a8 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -113,11 +113,16 @@ class BadFiles(BeetsPlugin): .format(ui.colorize('text_warning', dpath), errors)) for line in output: ui.print_(u" {}".format(displayable_path(line))) - else: + elif opts.verbose: ui.print_(u"{}: ok".format(ui.colorize('text_success', dpath))) def commands(self): bad_command = Subcommand('bad', help=u'check for corrupt or missing files') + bad_command.parser.add_option( + u'-v', u'--verbose', + action='store_true', default=False, dest='verbose', + help=u'view results for both the bad and uncorrupted files' + ) bad_command.func = self.check_bad return [bad_command] diff --git a/docs/changelog.rst b/docs/changelog.rst index c78a6fc21..af03df646 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -25,6 +25,9 @@ New features: * Added a ``--move`` or ``-m`` option to the importer so that the files can be moved to the library instead of being copied or added "in place". :bug:`2252` :bug:`2429` +* Added a ``--verbose`` or ``-v`` option to the badfiles plugin. Results are + now displayed only for corrupted files by default and for all the files when + the verbose option is set. :bug:`1654` :bug:`2434` Fixes: diff --git a/docs/plugins/badfiles.rst b/docs/plugins/badfiles.rst index 80f543c54..0a32f1a36 100644 --- a/docs/plugins/badfiles.rst +++ b/docs/plugins/badfiles.rst @@ -52,3 +52,7 @@ Note that the default `mp3val` checker is a bit verbose and can output a lot of "stream error" messages, even for files that play perfectly well. Generally, if more than one stream error happens, or if a stream error happens in the middle of a file, this is a bad sign. + +By default, only errors for the bad files will be shown. In order for the +results for all of the checked files to be seen, including the uncorrupted +ones, use the ``-v`` or ``--verbose`` option. From 2fcb68afd885b326eefe06150e24462b7c24e45e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 11 Feb 2017 19:23:39 -0500 Subject: [PATCH 1709/2280] Little changelog fixes (#2433) --- docs/changelog.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5fd388e4f..1d191383e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,8 +24,8 @@ New features: bracketing. :bug:`2397` :bug:`2399` * Added a ``--move`` or ``-m`` option to the importer so that the files can be moved to the library instead of being copied or added "in place". - :bug:`2252` :bug:`2429` -* Added a ``--verbose`` or ``-v`` option to the badfiles plugin. Results are + :bug:`2252` :bug:`2429` +* :doc:`/plugins/badfiles`: Added a ``--verbose`` or ``-v`` option. Results are now displayed only for corrupted files by default and for all the files when the verbose option is set. :bug:`1654` :bug:`2434` @@ -41,9 +41,9 @@ Fixes: * :doc:`/plugins/badfiles`: Fix Python 3 compatibility. * Fix some cases where album-level ReplayGain/SoundCheck metadata would be written to files incorrectly. :bug:`2426` -* Fixed the badfiles plugin to allow the execution to continue to other files - if validator command is not found or exists with an error. :bug:`2430` - :bug:`2433` +* :doc:`/plugins/badfiles`: The command no longer bails out if validator + command is not found or exists with an error. :bug:`2430` :bug:`2433` + 1.4.3 (January 9, 2017) ----------------------- From 86c8cffa6c218ddb5499f28f22a273cb26d5109f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 11 Feb 2017 19:24:47 -0500 Subject: [PATCH 1710/2280] Fix some whitespace (#2433) --- beetsplug/badfiles.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/badfiles.py b/beetsplug/badfiles.py index 1d9396875..62c6d8af5 100644 --- a/beetsplug/badfiles.py +++ b/beetsplug/badfiles.py @@ -32,13 +32,12 @@ import six class CheckerCommandException(Exception): """Raised when running a checker failed. - + Attributes: checker: Checker command name. path: Path to the file being validated. errno: Error number from the checker execution error. msg: Message from the checker execution error. - """ def __init__(self, cmd, oserror): From 8087e828914a917a864dad32bd4ce06ed286b527 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 12 Feb 2017 10:30:22 -0500 Subject: [PATCH 1711/2280] lyrics: Use Requests for Google backend (fix #2437) --- beetsplug/lyrics.py | 4 ++-- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 92abe377e..c020a93ae 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -563,8 +563,8 @@ class Google(Backend): % (self.api_key, self.engine_id, urllib.parse.quote(query.encode('utf-8'))) - data = urllib.request.urlopen(url) - data = json.load(data) + data = self.fetch_url(url) + data = json.loads(data) if 'error' in data: reason = data['error']['errors'][0]['reason'] self._log.debug(u'google lyrics backend error: {0}', reason) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1d191383e..0774722c8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -43,6 +43,8 @@ Fixes: written to files incorrectly. :bug:`2426` * :doc:`/plugins/badfiles`: The command no longer bails out if validator command is not found or exists with an error. :bug:`2430` :bug:`2433` +* :doc:`/plugins/lyrics`: The Google search backend no longer crashes when the + server responds with an error. :bug:`2437` 1.4.3 (January 9, 2017) From 3361aaafdaead7eaeac206decaf6c21331ef556d Mon Sep 17 00:00:00 2001 From: Aaron Date: Tue, 31 Jan 2017 02:15:29 -0800 Subject: [PATCH 1712/2280] =?UTF-8?q?Embedart=20plugin=20asks=20for=20conf?= =?UTF-8?q?irmation=20before=20making=20changes=20to=20item=E2=80=99s=20ar?= =?UTF-8?q?twork.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beetsplug/embedart.py | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 948da6291..ff65e34db 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -20,7 +20,7 @@ import os.path from beets.plugins import BeetsPlugin from beets import ui -from beets.ui import decargs +from beets.ui import print_, decargs from beets.util import syspath, normpath, displayable_path, bytestring_path from beets.util.artresizer import ArtResizer from beets import config @@ -60,10 +60,28 @@ class EmbedCoverArtPlugin(BeetsPlugin): embed_cmd.parser.add_option( u'-f', u'--file', metavar='PATH', help=u'the image file to embed' ) + embed_cmd.parser.add_option( + u"-y", u"--yes", action="store_true", help=u"skip confirmation" + ) maxwidth = self.config['maxwidth'].get(int) compare_threshold = self.config['compare_threshold'].get(int) ifempty = self.config['ifempty'].get(bool) + def _confirmation(items, opts, fmt, prompt): + # Confirm artwork changes to library items. + if not opts.yes: + # Prepare confirmation with user. + print_() + + # Show all the items. + for item in items: + print_(format(item, fmt)) + + # Confirm with user. + if not ui.input_yn(prompt, True): + return False + return True + def embed_func(lib, opts, args): if opts.file: imagepath = normpath(opts.file) @@ -71,11 +89,30 @@ class EmbedCoverArtPlugin(BeetsPlugin): raise ui.UserError(u'image file {0} not found'.format( displayable_path(imagepath) )) - for item in lib.items(decargs(args)): + + items = lib.items(decargs(args)) + + # Confirm with user. + fmt = u'$albumartist - $album - $title' + prompt = u'Modify artwork for %i file%s (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') + if not _confirmation(items, opts, fmt, prompt): + return + + for item in items: art.embed_item(self._log, item, imagepath, maxwidth, None, compare_threshold, ifempty) else: - for album in lib.albums(decargs(args)): + items = lib.albums(decargs(args)) + + # Confirm with user. + fmt = u'$albumartist - $album' + prompt = u'Modify artwork for %i album%s (y/n)?' % \ + (len(items), 's' if len(items) > 1 else '') + if not _confirmation(items, opts, fmt, prompt): + return + + for album in items: art.embed_album(self._log, album, maxwidth, False, compare_threshold, ifempty) self.remove_artfile(album) From 9c97f95073c026114ef7d80b8a549ba7fed63452 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 1 Feb 2017 03:38:38 -0800 Subject: [PATCH 1713/2280] Updated embedart test cases to accomodate confirmation prompt. --- test/test_embedart.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index ee08ecb4e..5360ea372 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -51,6 +51,9 @@ class EmbedartCliTest(_common.TestCase, TestHelper): abbey_differentpath = os.path.join(_common.RSRC, b'abbey-different.jpg') def setUp(self): + super(EmbedartCliTest, self).setUp() + self.io.install() + self.setup_beets() # Converter is threaded self.load_plugins('embedart') @@ -68,6 +71,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data() album = self.add_album_fixture() item = album.items()[0] + self.io.addinput('y') self.run_command('embedart', '-f', self.small_artpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -78,6 +82,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): item = album.items()[0] album.artpath = self.small_artpath album.store() + self.io.addinput('y') self.run_command('embedart') mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -96,6 +101,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): album.store() config['embedart']['remove_art_file'] = True + self.io.addinput('y') self.run_command('embedart') if os.path.isfile(tmp_path): @@ -106,6 +112,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.add_album_fixture() logging.getLogger('beets.embedart').setLevel(logging.DEBUG) with self.assertRaises(ui.UserError): + self.io.addinput('y') self.run_command('embedart', '-f', '/doesnotexist') def test_embed_non_image_file(self): @@ -117,6 +124,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): os.close(handle) try: + self.io.addinput('y') self.run_command('embedart', '-f', tmp_path) finally: os.remove(tmp_path) @@ -129,8 +137,10 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data(self.abbey_artpath) album = self.add_album_fixture() item = album.items()[0] + self.io.addinput('y') self.run_command('embedart', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 + self.io.addinput('y') self.run_command('embedart', '-f', self.abbey_differentpath) mediafile = MediaFile(syspath(item.path)) @@ -143,9 +153,10 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data(self.abbey_similarpath) album = self.add_album_fixture() item = album.items()[0] + self.io.addinput('y') self.run_command('embedart', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 - self.run_command('embedart', '-f', self.abbey_similarpath) + self.run_command('embedart', '-y', '-f', self.abbey_similarpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, @@ -169,7 +180,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): trackpath = album.items()[0].path albumpath = album.path shutil.copy(syspath(resource_path), syspath(trackpath)) - + self.run_command('extractart', '-n', 'extracted') self.assertExists(os.path.join(albumpath, b'extracted.jpg')) From d1ac8939155dab36b03a757c7e6c3b73fd35b634 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 1 Feb 2017 14:32:52 -0800 Subject: [PATCH 1714/2280] Style changes to pass PEP8 tests. --- beetsplug/embedart.py | 2 +- test/test_embedart.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index ff65e34db..056c8f36a 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -95,7 +95,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): # Confirm with user. fmt = u'$albumartist - $album - $title' prompt = u'Modify artwork for %i file%s (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') + (len(items), 's' if len(items) > 1 else '') if not _confirmation(items, opts, fmt, prompt): return diff --git a/test/test_embedart.py b/test/test_embedart.py index 5360ea372..b0e66dddb 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -180,7 +180,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): trackpath = album.items()[0].path albumpath = album.path shutil.copy(syspath(resource_path), syspath(trackpath)) - + self.run_command('extractart', '-n', 'extracted') self.assertExists(os.path.join(albumpath, b'extracted.jpg')) From c250a53b4d8073f0346c82eda66c1d47a9a86999 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 1 Feb 2017 17:04:01 -0800 Subject: [PATCH 1715/2280] Updated changelog and embedart docs. --- docs/changelog.rst | 2 ++ docs/plugins/embedart.rst | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0774722c8..0c3779c3c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,6 +28,8 @@ New features: * :doc:`/plugins/badfiles`: Added a ``--verbose`` or ``-v`` option. Results are now displayed only for corrupted files by default and for all the files when the verbose option is set. :bug:`1654` :bug:`2434` + * :doc:`/plugins/embedart` by default now asks for confirmation before + embedding art into music files. Thanks to :user:`Stunner`. :bug:`1999` Fixes: diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index 94e91d995..717bfb8e2 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -81,7 +81,8 @@ embedded album art: * ``beet embedart [-f IMAGE] QUERY``: embed images into the every track on the albums matching the query. If the ``-f`` (``--file``) option is given, then use a specific image file from the filesystem; otherwise, each album embeds - its own currently associated album art. + its own currently associated album art. Will prompt for confirmation before + making the change unless the ``-y`` (``--yes``) option is specified. * ``beet extractart [-a] [-n FILE] QUERY``: extracts the images for all albums matching the query. The images are placed inside the album folder. You can From 3e13971c545d376ec6ad555231f6dd9faee4eb8e Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 13 Feb 2017 02:30:01 -0800 Subject: [PATCH 1716/2280] Some code cleanup/consolidation. --- beetsplug/embedart.py | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 056c8f36a..21fb0188c 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -67,12 +67,20 @@ class EmbedCoverArtPlugin(BeetsPlugin): compare_threshold = self.config['compare_threshold'].get(int) ifempty = self.config['ifempty'].get(bool) - def _confirmation(items, opts, fmt, prompt): + def _confirmation(items, opts): # Confirm artwork changes to library items. if not opts.yes: # Prepare confirmation with user. print_() + fmt = u'$albumartist - $album' + item_type = u'album' + if opts.file: + fmt = u'$albumartist - $album - $title' + item_type = u'file' + prompt = u'Modify artwork for %i %s%s (y/n)?' % \ + (len(items), item_type, 's' if len(items) > 1 else '') + # Show all the items. for item in items: print_(format(item, fmt)) @@ -93,10 +101,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): items = lib.items(decargs(args)) # Confirm with user. - fmt = u'$albumartist - $album - $title' - prompt = u'Modify artwork for %i file%s (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') - if not _confirmation(items, opts, fmt, prompt): + if not _confirmation(items, opts): return for item in items: @@ -106,10 +111,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): items = lib.albums(decargs(args)) # Confirm with user. - fmt = u'$albumartist - $album' - prompt = u'Modify artwork for %i album%s (y/n)?' % \ - (len(items), 's' if len(items) > 1 else '') - if not _confirmation(items, opts, fmt, prompt): + if not _confirmation(items, opts): return for album in items: From 733c1839fb3e67dc79f5ad707d993efc9676194d Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 13 Feb 2017 02:43:13 -0800 Subject: [PATCH 1717/2280] Addressed coding style issue. --- beetsplug/embedart.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 21fb0188c..6344dc2b9 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -74,12 +74,12 @@ class EmbedCoverArtPlugin(BeetsPlugin): print_() fmt = u'$albumartist - $album' - item_type = u'album' + istr = u'album' if opts.file: fmt = u'$albumartist - $album - $title' - item_type = u'file' + istr = u'file' prompt = u'Modify artwork for %i %s%s (y/n)?' % \ - (len(items), item_type, 's' if len(items) > 1 else '') + (len(items), istr, 's' if len(items) > 1 else '') # Show all the items. for item in items: From 0a4709f7ef231ff6499f8ef24aeaa5017ce8d07c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 13 Feb 2017 16:54:56 -0500 Subject: [PATCH 1718/2280] lyrics: Tolerate empty Google response (#2437) --- beetsplug/lyrics.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c020a93ae..6714b2fee 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -564,11 +564,17 @@ class Google(Backend): urllib.parse.quote(query.encode('utf-8'))) data = self.fetch_url(url) - data = json.loads(data) + if not data: + self._log.debug(u'google backend returned no data') + return None + try: + data = json.loads(data) + except ValueError as exc: + self._log.debug(u'google backend returned malformed JSON: {}', exc) if 'error' in data: reason = data['error']['errors'][0]['reason'] - self._log.debug(u'google lyrics backend error: {0}', reason) - return + self._log.debug(u'google backend error: {0}', reason) + return None if 'items' in data.keys(): for item in data['items']: From b4efecb709598b5a8bd362d9a1bdf8d9f2e272a5 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 15:56:13 -0600 Subject: [PATCH 1719/2280] Add option to hardlink when importing --- beets/importer.py | 17 ++++++++++++----- beets/library.py | 26 +++++++++++++++++--------- beets/util/__init__.py | 26 ++++++++++++++++++++++++++ beetsplug/importadded.py | 3 ++- docs/dev/plugins.rst | 4 ++++ docs/reference/config.rst | 19 +++++++++++++++++-- test/_common.py | 1 + test/test_files.py | 17 +++++++++++++++++ test/test_importadded.py | 1 + test/test_importer.py | 23 ++++++++++++++++++++++- test/test_mediafile_edge.py | 9 +++++++++ 11 files changed, 128 insertions(+), 18 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 6a10f4c97..275e889f6 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -220,13 +220,19 @@ class ImportSession(object): iconfig['resume'] = False iconfig['incremental'] = False - # Copy, move, and link are mutually exclusive. + # Copy, move, link, and hardlink are mutually exclusive. if iconfig['move']: iconfig['copy'] = False iconfig['link'] = False + iconfig['hardlink'] = False elif iconfig['link']: iconfig['copy'] = False iconfig['move'] = False + iconfig['hardlink'] = False + elif iconfig['hardlink']: + iconfig['copy'] = False + iconfig['move'] = False + iconfig['link'] = False # Only delete when copying. if not iconfig['copy']: @@ -654,18 +660,18 @@ class ImportTask(BaseImportTask): item.update(changes) def manipulate_files(self, move=False, copy=False, write=False, - link=False, session=None): + link=False, hardlink=False, session=None): items = self.imported_items() # Save the original paths of all items for deletion and pruning # in the next step (finalization). self.old_paths = [item.path for item in items] for item in items: - if move or copy or link: + if move or copy or link or hardlink: # In copy and link modes, treat re-imports specially: # move in-library files. (Out-of-library files are # copied/moved as usual). old_path = item.path - if (copy or link) and self.replaced_items[item] and \ + if (copy or link or hardlink) and self.replaced_items[item] and \ session.lib.directory in util.ancestry(old_path): item.move() # We moved the item, so remove the @@ -674,7 +680,7 @@ class ImportTask(BaseImportTask): else: # A normal import. Just copy files and keep track of # old paths. - item.move(copy, link) + item.move(copy, link, hardlink) if write and (self.apply or self.choice_flag == action.RETAG): item.try_write() @@ -1412,6 +1418,7 @@ def manipulate_files(session, task): copy=session.config['copy'], write=session.config['write'], link=session.config['link'], + hardlink=session.config['hardlink'], session=session, ) diff --git a/beets/library.py b/beets/library.py index 4e5d9ccf6..b263ecd64 100644 --- a/beets/library.py +++ b/beets/library.py @@ -663,7 +663,7 @@ class Item(LibModel): # Files themselves. - def move_file(self, dest, copy=False, link=False): + def move_file(self, dest, copy=False, link=False, hardlink=False): """Moves or copies the item's file, updating the path value if the move succeeds. If a file exists at ``dest``, then it is slightly modified to be unique. @@ -678,6 +678,10 @@ class Item(LibModel): util.link(self.path, dest) plugins.send("item_linked", item=self, source=self.path, destination=dest) + elif hardlink: + util.hardlink(self.path, dest) + plugins.send("item_hardlinked", item=self, source=self.path, + destination=dest) else: plugins.send("before_item_moved", item=self, source=self.path, destination=dest) @@ -730,15 +734,16 @@ class Item(LibModel): self._db._memotable = {} - def move(self, copy=False, link=False, basedir=None, with_album=True, - store=True): + def move(self, copy=False, link=False, hardlink=False, basedir=None, + with_album=True, store=True): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path field is updated to reflect the new location. If `copy` is true, moving the file is copied rather than moved. - Similarly, `link` creates a symlink instead. + Similarly, `link` creates a symlink instead, and `hardlink` + creates a hardlink. basedir overrides the library base directory for the destination. @@ -761,7 +766,7 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path - self.move_file(dest, copy, link) + self.move_file(dest, copy, link, hardlink) if store: self.store() @@ -979,7 +984,7 @@ class Album(LibModel): for item in self.items(): item.remove(delete, False) - def move_art(self, copy=False, link=False): + def move_art(self, copy=False, link=False, hardlink=False): """Move or copy any existing album art so that it remains in the same directory as the items. """ @@ -999,6 +1004,8 @@ class Album(LibModel): util.copy(old_art, new_art) elif link: util.link(old_art, new_art) + elif hardlink: + util.hardlink(old_art, new_art) else: util.move(old_art, new_art) self.artpath = new_art @@ -1008,7 +1015,8 @@ class Album(LibModel): util.prune_dirs(os.path.dirname(old_art), self._db.directory) - def move(self, copy=False, link=False, basedir=None, store=True): + def move(self, copy=False, link=False, hardlink=False, basedir=None, + store=True): """Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base directory for the destination. By default, the album is stored to the @@ -1026,11 +1034,11 @@ class Album(LibModel): # Move items. items = list(self.items()) for item in items: - item.move(copy, link, basedir=basedir, with_album=False, + item.move(copy, link, hardlink, basedir=basedir, with_album=False, store=store) # Move art. - self.move_art(copy, link) + self.move_art(copy, link, hardlink) if store: self.store() diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 18d89ddd9..ba78dfa30 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -500,6 +500,32 @@ def link(path, dest, replace=False): traceback.format_exc()) +def hardlink(path, dest, replace=False): + """Create a hard link from path to `dest`. Raises an OSError if + `dest` already exists, unless `replace` is True. Does nothing if + `path` == `dest`.""" + if (samefile(path, dest)): + return + + path = syspath(path) + dest = syspath(dest) + if os.path.exists(dest) and not replace: + raise FilesystemError(u'file exists', 'rename', (path, dest)) + try: + os.link(path, dest) + except NotImplementedError: + # raised on python >= 3.2 and Windows versions before Vista + raise FilesystemError(u'OS does not support hard links.' + 'link', (path, dest), traceback.format_exc()) + except OSError as exc: + # TODO: Windows version checks can be removed for python 3 + if hasattr('sys', 'getwindowsversion'): + if sys.getwindowsversion()[0] < 6: # is before Vista + exc = u'OS does not support hard links.' + raise FilesystemError(exc, 'link', (path, dest), + traceback.format_exc()) + + def unique_path(path): """Returns a version of ``path`` that does not exist on the filesystem. Specifically, if ``path` itself already exists, then diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index 07434ee72..c1838884b 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -36,6 +36,7 @@ class ImportAddedPlugin(BeetsPlugin): register('before_item_moved', self.record_import_mtime) register('item_copied', self.record_import_mtime) register('item_linked', self.record_import_mtime) + register('item_hardlinked', self.record_import_mtime) register('album_imported', self.update_album_times) register('item_imported', self.update_item_times) register('after_write', self.update_after_write_time) @@ -51,7 +52,7 @@ class ImportAddedPlugin(BeetsPlugin): def record_if_inplace(self, task, session): if not (session.config['copy'] or session.config['move'] or - session.config['link']): + session.config['link'] or session.config['hardlink']): self._log.debug(u"In place import detected, recording mtimes from " u"source paths") items = [task.item] \ diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index fb063aee0..4d41c8971 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -161,6 +161,10 @@ The events currently available are: for a file. Parameters: ``item``, ``source`` path, ``destination`` path +* `item_hardlinked`: called with an ``Item`` object whenever a hardlink is + created for a file. + Parameters: ``item``, ``source`` path, ``destination`` path + * `item_removed`: called with an ``Item`` object every time an item (singleton or album's part) is removed from the library (even when its file is not deleted from disk). diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 779e920d2..679b036f6 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -433,8 +433,8 @@ link ~~~~ Either ``yes`` or ``no``, indicating whether to use symbolic links instead of -moving or copying files. (It conflicts with the ``move`` and ``copy`` -options.) Defaults to ``no``. +moving or copying files. (It conflicts with the ``move``, ``copy`` and +``hardlink`` options.) Defaults to ``no``. This option only works on platforms that support symbolic links: i.e., Unixes. It will fail on Windows. @@ -442,6 +442,21 @@ It will fail on Windows. It's likely that you'll also want to set ``write`` to ``no`` if you use this option to preserve the metadata on the linked files. +.. _hardlink: + +hardlink +~~~~ + +Either ``yes`` or ``no``, indicating whether to use hard links instead of +moving or copying or symlinking files. (It conflicts with the ``move``, +``copy``, and ``link`` options.) Defaults to ``no``. + +This option only works on platforms that support hardlinks: i.e., Unixes. +It will fail on Windows. + +It's likely that you'll also want to set ``write`` to ``no`` if you use this +option to preserve the metadata on the linked files. + resume ~~~~~~ diff --git a/test/_common.py b/test/_common.py index 2e7418516..f3213ec31 100644 --- a/test/_common.py +++ b/test/_common.py @@ -54,6 +54,7 @@ _item_ident = 0 # OS feature test. HAVE_SYMLINK = sys.platform != 'win32' +HAVE_HARDLINK = sys.platform != 'win32' def item(lib=None): diff --git a/test/test_files.py b/test/test_files.py index b566f363e..4a81b8c20 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -141,6 +141,23 @@ class MoveTest(_common.TestCase): self.i.move(link=True) self.assertEqual(self.i.path, util.normpath(self.dest)) + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_arrives(self): + self.i.move(hardlink=True) + self.assertExists(self.dest) + self.assertTrue(os.path.islink(self.dest)) + self.assertEqual(os.readlink(self.dest), self.path) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_does_not_depart(self): + self.i.move(hardlink=True) + self.assertExists(self.path) + + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_hardlink_changes_path(self): + self.i.move(hardlink=True) + self.assertEqual(self.i.path, util.normpath(self.dest)) + class HelperTest(_common.TestCase): def test_ancestry_works_on_file(self): diff --git a/test/test_importadded.py b/test/test_importadded.py index 52aa26756..dd933c3c8 100644 --- a/test/test_importadded.py +++ b/test/test_importadded.py @@ -93,6 +93,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper): self.config['import']['copy'] = False self.config['import']['move'] = False self.config['import']['link'] = False + self.config['import']['hardlink'] = False self.assertAlbumImport() def test_import_album_with_preserved_mtimes(self): diff --git a/test/test_importer.py b/test/test_importer.py index 87724f8da..c372d04da 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -22,6 +22,7 @@ import re import shutil import unicodedata import sys +import stat from six import StringIO from tempfile import mkstemp from zipfile import ZipFile @@ -209,7 +210,8 @@ class ImportHelper(TestHelper): def _setup_import_session(self, import_dir=None, delete=False, threaded=False, copy=True, singletons=False, - move=False, autotag=True, link=False): + move=False, autotag=True, link=False, + hardlink=False): config['import']['copy'] = copy config['import']['delete'] = delete config['import']['timid'] = True @@ -219,6 +221,7 @@ class ImportHelper(TestHelper): config['import']['autotag'] = autotag config['import']['resume'] = False config['import']['link'] = link + config['import']['hardlink'] = hardlink self.importer = TestImportSession( self.lib, loghandler=None, query=None, @@ -353,6 +356,24 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): mediafile.path ) + @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") + def test_import_hardlink_arrives(self): + config['import']['hardlink'] = True + self.importer.run() + for mediafile in self.import_media: + filename = os.path.join( + self.libdir, + b'Tag Artist', b'Tag Album', + util.bytestring_path('{0}.mp3'.format(mediafile.title)) + ) + self.assertExists(filename) + s1 = os.stat(mediafile.path) + s2 = os.stat(filename) + self.assertTrue( + (s1[stat.ST_INO], s1[stat.ST_DEV]) == \ + (s2[stat.ST_INO], s2[stat.ST_DEV]) + ) + def create_archive(session): (handle, path) = mkstemp(dir=py3_path(session.temp_dir)) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 657ca455d..8b28890be 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -197,6 +197,15 @@ class SafetyTest(unittest.TestCase, _common.TempDirMixin): finally: os.unlink(fn) + @unittest.skipUnless(_common.HAVE_HARDLINK, u'platform lacks hardlink') + def test_broken_hardlink(self): + fn = os.path.join(_common.RSRC, b'brokenlink') + os.link('does_not_exist', fn) + try: + self.assertRaises(mediafile.UnreadableFileError, + mediafile.MediaFile, fn) + finally: + os.unlink(fn) class SideEffectsTest(unittest.TestCase): def setUp(self): From 076c753943e764b2e2a5707a9f9322cc73dfee61 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 16:54:11 -0600 Subject: [PATCH 1720/2280] Remove windows hardlink checks --- beets/util/__init__.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index ba78dfa30..83f35f563 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -514,14 +514,9 @@ def hardlink(path, dest, replace=False): try: os.link(path, dest) except NotImplementedError: - # raised on python >= 3.2 and Windows versions before Vista raise FilesystemError(u'OS does not support hard links.' 'link', (path, dest), traceback.format_exc()) except OSError as exc: - # TODO: Windows version checks can be removed for python 3 - if hasattr('sys', 'getwindowsversion'): - if sys.getwindowsversion()[0] < 6: # is before Vista - exc = u'OS does not support hard links.' raise FilesystemError(exc, 'link', (path, dest), traceback.format_exc()) From e5c93b6b16c0160ca86552d4a1ea07cfd295f9b5 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 16:57:16 -0600 Subject: [PATCH 1721/2280] Add hardlink: no to default config --- beets/config_default.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index fa77a82dc..3b0377966 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -6,6 +6,7 @@ import: copy: yes move: no link: no + hardlink: no delete: no resume: ask incremental: no From 0c836f9369646abf781e90fcc85d951377fd1944 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 17:12:47 -0600 Subject: [PATCH 1722/2280] Add a user-friendly error for cross-device hardlinks --- beets/util/__init__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 83f35f563..d7d45941c 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function import os import sys +import errno import locale import re import shutil @@ -517,8 +518,12 @@ def hardlink(path, dest, replace=False): raise FilesystemError(u'OS does not support hard links.' 'link', (path, dest), traceback.format_exc()) except OSError as exc: - raise FilesystemError(exc, 'link', (path, dest), - traceback.format_exc()) + if exc.errno == errno.EXDEV: + raise FilesystemError(u'Cannot hard link across devices.' + 'link', (path, dest), traceback.format_exc()) + else: + raise FilesystemError(exc, 'link', (path, dest), + traceback.format_exc()) def unique_path(path): From ccd0f5d12933903a479edcd35205a7c79e5eb7a2 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 17:19:42 -0600 Subject: [PATCH 1723/2280] Remove not-found hardlink test (the OS prevents this from happening) --- test/test_mediafile_edge.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 8b28890be..c631cdecf 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -197,16 +197,6 @@ class SafetyTest(unittest.TestCase, _common.TempDirMixin): finally: os.unlink(fn) - @unittest.skipUnless(_common.HAVE_HARDLINK, u'platform lacks hardlink') - def test_broken_hardlink(self): - fn = os.path.join(_common.RSRC, b'brokenlink') - os.link('does_not_exist', fn) - try: - self.assertRaises(mediafile.UnreadableFileError, - mediafile.MediaFile, fn) - finally: - os.unlink(fn) - class SideEffectsTest(unittest.TestCase): def setUp(self): self.empty = os.path.join(_common.RSRC, b'empty.mp3') From 902b955696e1a4fbd214802f29f7af32d12d200c Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 17:22:01 -0600 Subject: [PATCH 1724/2280] Fix test_hardlink_arrives --- test/test_files.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/test_files.py b/test/test_files.py index 4a81b8c20..38689bbd9 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -145,8 +145,12 @@ class MoveTest(_common.TestCase): def test_hardlink_arrives(self): self.i.move(hardlink=True) self.assertExists(self.dest) - self.assertTrue(os.path.islink(self.dest)) - self.assertEqual(os.readlink(self.dest), self.path) + s1 = os.stat(self.path) + s2 = os.stat(self.dest) + self.assertTrue( + (s1[stat.ST_INO], s1[stat.ST_DEV]) == \ + (s2[stat.ST_INO], s2[stat.ST_DEV]) + ) @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") def test_hardlink_does_not_depart(self): From 1fd22604fb50d8c53e9eb733ddba624e887225b0 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 17:33:26 -0600 Subject: [PATCH 1725/2280] Fix linter issues --- beets/importer.py | 4 ++-- docs/reference/config.rst | 2 +- test/test_files.py | 4 ++-- test/test_importer.py | 4 ++-- test/test_mediafile_edge.py | 1 + 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 275e889f6..bbe152cd4 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -671,8 +671,8 @@ class ImportTask(BaseImportTask): # move in-library files. (Out-of-library files are # copied/moved as usual). old_path = item.path - if (copy or link or hardlink) and self.replaced_items[item] and \ - session.lib.directory in util.ancestry(old_path): + if (copy or link or hardlink) and self.replaced_items[item] \ + and session.lib.directory in util.ancestry(old_path): item.move() # We moved the item, so remove the # now-nonexistent file from old_paths. diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 679b036f6..bf3d89b2e 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -445,7 +445,7 @@ option to preserve the metadata on the linked files. .. _hardlink: hardlink -~~~~ +~~~~~~~~ Either ``yes`` or ``no``, indicating whether to use hard links instead of moving or copying or symlinking files. (It conflicts with the ``move``, diff --git a/test/test_files.py b/test/test_files.py index 38689bbd9..834d3391c 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -148,8 +148,8 @@ class MoveTest(_common.TestCase): s1 = os.stat(self.path) s2 = os.stat(self.dest) self.assertTrue( - (s1[stat.ST_INO], s1[stat.ST_DEV]) == \ - (s2[stat.ST_INO], s2[stat.ST_DEV]) + (s1[stat.ST_INO], s1[stat.ST_DEV]) == + (s2[stat.ST_INO], s2[stat.ST_DEV]) ) @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") diff --git a/test/test_importer.py b/test/test_importer.py index c372d04da..26dec3de8 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -370,8 +370,8 @@ class NonAutotaggedImportTest(_common.TestCase, ImportHelper): s1 = os.stat(mediafile.path) s2 = os.stat(filename) self.assertTrue( - (s1[stat.ST_INO], s1[stat.ST_DEV]) == \ - (s2[stat.ST_INO], s2[stat.ST_DEV]) + (s1[stat.ST_INO], s1[stat.ST_DEV]) == + (s2[stat.ST_INO], s2[stat.ST_DEV]) ) diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index c631cdecf..657ca455d 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -197,6 +197,7 @@ class SafetyTest(unittest.TestCase, _common.TempDirMixin): finally: os.unlink(fn) + class SideEffectsTest(unittest.TestCase): def setUp(self): self.empty = os.path.join(_common.RSRC, b'empty.mp3') From 4e77ef44844810e0749f86fd0b6c6c8e7ceb5178 Mon Sep 17 00:00:00 2001 From: Jacob Gillespie Date: Sun, 19 Feb 2017 20:48:34 -0600 Subject: [PATCH 1726/2280] Address review comments --- beets/util/__init__.py | 22 ++++++++++------------ docs/reference/config.rst | 8 +++----- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index d7d45941c..f6cd488d6 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -478,16 +478,15 @@ def move(path, dest, replace=False): def link(path, dest, replace=False): """Create a symbolic link from path to `dest`. Raises an OSError if `dest` already exists, unless `replace` is True. Does nothing if - `path` == `dest`.""" - if (samefile(path, dest)): + `path` == `dest`. + """ + if samefile(path, dest): return - path = syspath(path) - dest = syspath(dest) - if os.path.exists(dest) and not replace: + if os.path.exists(syspath(dest)) and not replace: raise FilesystemError(u'file exists', 'rename', (path, dest)) try: - os.symlink(path, dest) + os.symlink(syspath(path), syspath(dest)) except NotImplementedError: # raised on python >= 3.2 and Windows versions before Vista raise FilesystemError(u'OS does not support symbolic links.' @@ -504,16 +503,15 @@ def link(path, dest, replace=False): def hardlink(path, dest, replace=False): """Create a hard link from path to `dest`. Raises an OSError if `dest` already exists, unless `replace` is True. Does nothing if - `path` == `dest`.""" - if (samefile(path, dest)): + `path` == `dest`. + """ + if samefile(path, dest): return - path = syspath(path) - dest = syspath(dest) - if os.path.exists(dest) and not replace: + if os.path.exists(syspath(dest)) and not replace: raise FilesystemError(u'file exists', 'rename', (path, dest)) try: - os.link(path, dest) + os.link(syspath(path), syspath(dest)) except NotImplementedError: raise FilesystemError(u'OS does not support hard links.' 'link', (path, dest), traceback.format_exc()) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index bf3d89b2e..40f8e9185 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -451,11 +451,9 @@ Either ``yes`` or ``no``, indicating whether to use hard links instead of moving or copying or symlinking files. (It conflicts with the ``move``, ``copy``, and ``link`` options.) Defaults to ``no``. -This option only works on platforms that support hardlinks: i.e., Unixes. -It will fail on Windows. - -It's likely that you'll also want to set ``write`` to ``no`` if you use this -option to preserve the metadata on the linked files. +As with symbolic links (see :ref:`link`, above), this will not work on Windows +and you will want to set ``write`` to ``no``. Otherwise meatadata on the +original file will be modified. resume ~~~~~~ From 26408dd58da631673c23c2ffd2e5dbf660bdae1f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Feb 2017 22:44:28 -0500 Subject: [PATCH 1727/2280] Add a little more logging about matching process This could help debug #2446. It will help, at least, narrow down when the Munkres algorithm is taking too long. --- beets/autotag/match.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beets/autotag/match.py b/beets/autotag/match.py index 71d80e821..71b62adb7 100644 --- a/beets/autotag/match.py +++ b/beets/autotag/match.py @@ -103,7 +103,9 @@ def assign_items(items, tracks): costs.append(row) # Find a minimum-cost bipartite matching. + log.debug('Computing track assignment...') matching = Munkres().compute(costs) + log.debug('...done.') # Produce the output matching. mapping = dict((items[i], tracks[j]) for (i, j) in matching) @@ -349,7 +351,8 @@ def _add_candidate(items, results, info): checking the track count, ordering the items, checking for duplicates, and calculating the distance. """ - log.debug(u'Candidate: {0} - {1}', info.artist, info.album) + log.debug(u'Candidate: {0} - {1} ({2})', + info.artist, info.album, info.album_id) # Discard albums with zero tracks. if not info.tracks: From 8ccdb1c77e2becc851e2996b182eecedf40c16ba Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Feb 2017 22:54:14 -0500 Subject: [PATCH 1728/2280] More logging for MusicBrainz requests Even more performance-isolating logging to help debug #2446. --- beets/autotag/mb.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index a0d4dc33a..a6133adb1 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -374,6 +374,7 @@ def match_album(artist, album, tracks=None): return try: + log.debug(u'Searching for MusicBrainz releases with: {!r}', criteria) res = musicbrainzngs.search_releases( limit=config['musicbrainz']['searchlimit'].get(int), **criteria) except musicbrainzngs.MusicBrainzError as exc: @@ -424,6 +425,7 @@ def album_for_id(releaseid): object or None if the album is not found. May raise a MusicBrainzAPIError. """ + log.debug(u'Requesting MusicBrainz release {}', releaseid) albumid = _parse_id(releaseid) if not albumid: log.debug(u'Invalid MBID ({0}).', releaseid) From d10bfa1af6309e50a7e0954cba21e6491206bcf0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 20 Feb 2017 22:11:34 -0500 Subject: [PATCH 1729/2280] Changelog & thanks for #2445 --- docs/changelog.rst | 3 +++ docs/reference/config.rst | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0774722c8..4734ba05a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,6 +28,9 @@ New features: * :doc:`/plugins/badfiles`: Added a ``--verbose`` or ``-v`` option. Results are now displayed only for corrupted files by default and for all the files when the verbose option is set. :bug:`1654` :bug:`2434` +* A new :ref:`hardlink` config option instructs the importer to create hard + links on filesystems that support them. Thanks to :user:`jacobwgillespie`. + :bug:`2445` Fixes: diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 40f8e9185..094462d2f 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -452,7 +452,7 @@ moving or copying or symlinking files. (It conflicts with the ``move``, ``copy``, and ``link`` options.) Defaults to ``no``. As with symbolic links (see :ref:`link`, above), this will not work on Windows -and you will want to set ``write`` to ``no``. Otherwise meatadata on the +and you will want to set ``write`` to ``no``. Otherwise, metadata on the original file will be modified. resume From 3e4c9b8c06fb78477aa95e1056f44b9c17ed7d0b Mon Sep 17 00:00:00 2001 From: "Robin H. Johnson" Date: Mon, 20 Feb 2017 16:24:17 -0800 Subject: [PATCH 1730/2280] discogs: support simple auth. The official OAuth authentication seems to have broken, so allow usage of simple configuration instead. See-Also: https://github.com/discogs/discogs_client/issues/78 Signed-off-by: Robin H. Johnson --- beetsplug/discogs.py | 8 ++++++++ docs/plugins/discogs.rst | 22 ++++++++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 3b3f5f201..c9e4f3c18 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -54,9 +54,11 @@ class DiscogsPlugin(BeetsPlugin): 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', 'source_weight': 0.5, + 'user_token': None, }) self.config['apikey'].redact = True self.config['apisecret'].redact = True + self.config['user_token'].redact = True self.discogs_client = None self.register_listener('import_begin', self.setup) @@ -66,6 +68,12 @@ class DiscogsPlugin(BeetsPlugin): c_key = self.config['apikey'].as_str() c_secret = self.config['apisecret'].as_str() + user_token = self.config['user_token'].as_str() + + if user_token is not None and user_token != '': + self.discogs_client = Client(USER_AGENT, user_token=user_token) + return + # Get the OAuth token from a file or log in. try: with open(self._tokenfile()) as f: diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index eb60cca58..56413eed6 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -14,10 +14,9 @@ To use the ``discogs`` plugin, first enable it in your configuration (see pip install discogs-client -You will also need to register for a `Discogs`_ account. The first time you -run the :ref:`import-cmd` command after enabling the plugin, it will ask you -to authorize with Discogs by visiting the site in a browser. Subsequent runs -will not require re-authorization. +You will also need to register for a `Discogs`_ account, and provide +authentication credentials via a personal access token or an OAuth2 +authorization. Matches from Discogs will now show up during import alongside matches from MusicBrainz. @@ -25,6 +24,21 @@ MusicBrainz. If you have a Discogs ID for an album you want to tag, you can also enter it at the "enter Id" prompt in the importer. +OAuth authorization +``````````````````` +The first time you run the :ref:`import-cmd` command after enabling the plugin, +it will ask you to authorize with Discogs by visiting the site in a browser. +Subsequent runs will not require re-authorization. + +Authentication via personal access token +```````````````````````````````````````` +To get a personal access token (called a user token in the `discogs-client`_ +documentation), login to `Discogs`_, and visit the +`Developer settings page +`_. Press the ``Generate new +token`` button, and place the generated token in your configuration, as the +``user_token`` config option in the ``discogs`` section. + Troubleshooting --------------- From a29b29f533d3efb71f3df56fd2bb406679b8712d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Feb 2017 09:49:22 -0500 Subject: [PATCH 1731/2280] Docs improvements for #2447 --- beetsplug/discogs.py | 4 ++-- docs/plugins/discogs.rst | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index c9e4f3c18..a9b708619 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -68,9 +68,9 @@ class DiscogsPlugin(BeetsPlugin): c_key = self.config['apikey'].as_str() c_secret = self.config['apisecret'].as_str() + # Try using a configured user token (bypassing OAuth login). user_token = self.config['user_token'].as_str() - - if user_token is not None and user_token != '': + if user_token: self.discogs_client = Client(USER_AGENT, user_token=user_token) return diff --git a/docs/plugins/discogs.rst b/docs/plugins/discogs.rst index 56413eed6..a02b34590 100644 --- a/docs/plugins/discogs.rst +++ b/docs/plugins/discogs.rst @@ -24,15 +24,19 @@ MusicBrainz. If you have a Discogs ID for an album you want to tag, you can also enter it at the "enter Id" prompt in the importer. -OAuth authorization +OAuth Authorization ``````````````````` + The first time you run the :ref:`import-cmd` command after enabling the plugin, it will ask you to authorize with Discogs by visiting the site in a browser. Subsequent runs will not require re-authorization. -Authentication via personal access token +Authentication via Personal Access Token ```````````````````````````````````````` -To get a personal access token (called a user token in the `discogs-client`_ + +As an alternative to OAuth, you can get a token from Discogs and add it to +your configuration. +To get a personal access token (called a "user token" in the `discogs-client`_ documentation), login to `Discogs`_, and visit the `Developer settings page `_. Press the ``Generate new From 6cb9504403f5acba07d1614f037cbd37e65735f5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Feb 2017 09:49:56 -0500 Subject: [PATCH 1732/2280] Changelog for #2447 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4734ba05a..2fbb453c7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -48,6 +48,8 @@ Fixes: command is not found or exists with an error. :bug:`2430` :bug:`2433` * :doc:`/plugins/lyrics`: The Google search backend no longer crashes when the server responds with an error. :bug:`2437` +* :doc:`/plugins/discogs`: You can now authenticate with Discogs using a + personal access token. :bug:`2447` 1.4.3 (January 9, 2017) From d6905fa4c0ba3fcf8ddfbc1d8cc1c863c4c6dc62 Mon Sep 17 00:00:00 2001 From: Stephane Fontaine Date: Tue, 21 Feb 2017 21:29:52 +0400 Subject: [PATCH 1733/2280] Decode bytes to str before call to path_test Fixes #2443 --- beets/importer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index bbe152cd4..690a499ff 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -988,7 +988,7 @@ class ArchiveImportTask(SentinelImportTask): `toppath` to that directory. """ for path_test, handler_class in self.handlers(): - if path_test(self.toppath): + if path_test(util.py3_path(self.toppath)): break try: From 74c0e0d6e9075df94361a4588d4c4271e062e88f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Feb 2017 13:56:20 -0500 Subject: [PATCH 1734/2280] Fix default for user_token Always match the expected type. --- beetsplug/discogs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index a9b708619..0957b3403 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -54,7 +54,7 @@ class DiscogsPlugin(BeetsPlugin): 'apisecret': 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy', 'tokenfile': 'discogs_token.json', 'source_weight': 0.5, - 'user_token': None, + 'user_token': '', }) self.config['apikey'].redact = True self.config['apisecret'].redact = True From 8bfdabb0c60acbd379f20b6682b114943233bf17 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Feb 2017 21:43:13 -0500 Subject: [PATCH 1735/2280] Changelog entry for #2448 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2fbb453c7..c3f950d2d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -50,6 +50,8 @@ Fixes: server responds with an error. :bug:`2437` * :doc:`/plugins/discogs`: You can now authenticate with Discogs using a personal access token. :bug:`2447` +* Fix Python 3 compatibility when extracting rar archives in the importer. + Thanks to :user:`Lompik`. :bug:`2443` :bug:`2448` 1.4.3 (January 9, 2017) From 77a6b0edf8d38a3600b27c6754915dc64e56b8d7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 21 Feb 2017 22:00:31 -0500 Subject: [PATCH 1736/2280] duplicates: Fix 2nd bug in #2444 about path types --- beetsplug/duplicates.py | 7 ++++--- docs/changelog.rst | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 5ca314d3f..93d53c58a 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -21,7 +21,8 @@ import shlex from beets.plugins import BeetsPlugin from beets.ui import decargs, print_, Subcommand, UserError -from beets.util import command_output, displayable_path, subprocess +from beets.util import command_output, displayable_path, subprocess, \ + bytestring_path from beets.library import Item, Album import six @@ -112,14 +113,14 @@ class DuplicatesPlugin(BeetsPlugin): self.config.set_args(opts) album = self.config['album'].get(bool) checksum = self.config['checksum'].get(str) - copy = self.config['copy'].get(str) + copy = bytestring_path(self.config['copy'].as_str()) count = self.config['count'].get(bool) delete = self.config['delete'].get(bool) fmt = self.config['format'].get(str) full = self.config['full'].get(bool) keys = self.config['keys'].as_str_seq() merge = self.config['merge'].get(bool) - move = self.config['move'].get(str) + move = bytestring_path(self.config['move'].as_str()) path = self.config['path'].get(bool) tiebreak = self.config['tiebreak'].get(dict) strict = self.config['strict'].get(bool) diff --git a/docs/changelog.rst b/docs/changelog.rst index c3f950d2d..f7315e8c1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,6 +52,8 @@ Fixes: personal access token. :bug:`2447` * Fix Python 3 compatibility when extracting rar archives in the importer. Thanks to :user:`Lompik`. :bug:`2443` :bug:`2448` +* :doc:`/plugins/duplicates`: Fix Python 3 compatibility when using the + ``copy`` and ``move`` options. :bug:`2444` 1.4.3 (January 9, 2017) From b1ee9716bfb11a2999e4280715c6d4a0abdf7d71 Mon Sep 17 00:00:00 2001 From: rachmadaniHaryono Date: Fri, 24 Feb 2017 10:18:56 +0800 Subject: [PATCH 1737/2280] chg: dev: add main module. --- beets/__main__.py | 6 ++++++ beets/ui/__init__.py | 10 ++++++++++ 2 files changed, 16 insertions(+) create mode 100644 beets/__main__.py diff --git a/beets/__main__.py b/beets/__main__.py new file mode 100644 index 000000000..8cb407ae6 --- /dev/null +++ b/beets/__main__.py @@ -0,0 +1,6 @@ +"""main module.""" +import sys +from .ui import main + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ae30a9c60..907687588 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -946,6 +946,16 @@ class SubcommandsOptionParser(CommonOptionsParser): self.subcommands = [] + def get_prog_name(self): + """Get program name. + + Returns: + Program name. + """ + prog_name = super(SubcommandsOptionParser, self).get_prog_name() + prog_name = 'beets' if prog_name == '__main__.py' else prog_name + return prog_name + def add_subcommand(self, *cmds): """Adds a Subcommand object to the parser's list of commands. """ From 87311d69f19c2fb391d7d6ab7085753d8afb101d Mon Sep 17 00:00:00 2001 From: rachmadaniHaryono Date: Fri, 24 Feb 2017 13:47:22 +0800 Subject: [PATCH 1738/2280] fix: dev: fix c101 from flake8. --- beets/__main__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/__main__.py b/beets/__main__.py index 8cb407ae6..7b5fc798f 100644 --- a/beets/__main__.py +++ b/beets/__main__.py @@ -1,4 +1,5 @@ """main module.""" +# -*- coding: utf-8 -*- import sys from .ui import main From 2dff0254190e0f6d9361b25b96d7c5662b1d4f66 Mon Sep 17 00:00:00 2001 From: rachmadaniHaryono Date: Sat, 25 Feb 2017 03:46:26 +0800 Subject: [PATCH 1739/2280] chg: dev: let program decide the name. --- beets/ui/__init__.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 907687588..ae30a9c60 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -946,16 +946,6 @@ class SubcommandsOptionParser(CommonOptionsParser): self.subcommands = [] - def get_prog_name(self): - """Get program name. - - Returns: - Program name. - """ - prog_name = super(SubcommandsOptionParser, self).get_prog_name() - prog_name = 'beets' if prog_name == '__main__.py' else prog_name - return prog_name - def add_subcommand(self, *cmds): """Adds a Subcommand object to the parser's list of commands. """ From 8fa50a41cda9dd8a460182d262090059a7de1665 Mon Sep 17 00:00:00 2001 From: rachmadaniHaryono Date: Sat, 25 Feb 2017 12:13:47 +0800 Subject: [PATCH 1740/2280] chg: dev: add doc and license. --- beets/__main__.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/beets/__main__.py b/beets/__main__.py index 7b5fc798f..5f10c5b9b 100644 --- a/beets/__main__.py +++ b/beets/__main__.py @@ -1,5 +1,31 @@ -"""main module.""" # -*- coding: utf-8 -*- +"""main module. + +This module will be executed when beets module is run with `-m`. + +Example : `python -m beets` + +Related links about __main__.py: + +* python3 docs entry: https://docs.python.org/3/library/__main__.html +* related SO: http://stackoverflow.com/q/4042905 +""" +# This file is part of beets. +# Copyright 2017, Adrian Sampson. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +from __future__ import division, absolute_import, print_function + import sys from .ui import main From 0fe2279129787ac5a369b0b6e402f0283e915fe2 Mon Sep 17 00:00:00 2001 From: rachmadaniHaryono Date: Sat, 25 Feb 2017 12:14:53 +0800 Subject: [PATCH 1741/2280] chg: docs: add changelog entry. --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f7315e8c1..f9051dd73 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,6 +31,7 @@ New features: * A new :ref:`hardlink` config option instructs the importer to create hard links on filesystems that support them. Thanks to :user:`jacobwgillespie`. :bug:`2445` +* Added support to run program from module, e.g. `python -m beets`. Fixes: From 35e2ecf3dd64f2fc8a7fe7455e4b2207434d0994 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Feb 2017 13:37:44 -0500 Subject: [PATCH 1742/2280] Fix order of header comment vs. docstring (#2453) --- beets/__main__.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/beets/__main__.py b/beets/__main__.py index 5f10c5b9b..608cc0bd0 100644 --- a/beets/__main__.py +++ b/beets/__main__.py @@ -1,15 +1,4 @@ # -*- coding: utf-8 -*- -"""main module. - -This module will be executed when beets module is run with `-m`. - -Example : `python -m beets` - -Related links about __main__.py: - -* python3 docs entry: https://docs.python.org/3/library/__main__.html -* related SO: http://stackoverflow.com/q/4042905 -""" # This file is part of beets. # Copyright 2017, Adrian Sampson. # @@ -24,6 +13,18 @@ Related links about __main__.py: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. +"""main module. + +This module will be executed when beets module is run with `-m`. + +Example : `python -m beets` + +Related links about __main__.py: + +* python3 docs entry: https://docs.python.org/3/library/__main__.html +* related SO: http://stackoverflow.com/q/4042905 +""" + from __future__ import division, absolute_import, print_function import sys From a8d47f2c309c2fe97a162234a371308e332a2c92 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Feb 2017 13:39:14 -0500 Subject: [PATCH 1743/2280] Simpler __main__ docstring (#2453) --- beets/__main__.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/beets/__main__.py b/beets/__main__.py index 608cc0bd0..8010ca0dd 100644 --- a/beets/__main__.py +++ b/beets/__main__.py @@ -13,16 +13,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""main module. - -This module will be executed when beets module is run with `-m`. - -Example : `python -m beets` - -Related links about __main__.py: - -* python3 docs entry: https://docs.python.org/3/library/__main__.html -* related SO: http://stackoverflow.com/q/4042905 +"""The __main__ module lets you run the beets CLI interface by typing +`python -m beets`. """ from __future__ import division, absolute_import, print_function From 1ee53d4e76a55914ddf59ddeb3fb48dd3241afee Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Feb 2017 13:40:15 -0500 Subject: [PATCH 1744/2280] Fix up changelog for #2453 --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f9051dd73..a0ae8d43b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,7 +31,7 @@ New features: * A new :ref:`hardlink` config option instructs the importer to create hard links on filesystems that support them. Thanks to :user:`jacobwgillespie`. :bug:`2445` -* Added support to run program from module, e.g. `python -m beets`. +* You can now run beets by typing `python -m beets`. :bug:`2453` Fixes: From 1305c9407f7ad7beaf6d72a46756cf556ea838ec Mon Sep 17 00:00:00 2001 From: Teh Awesomer Date: Sat, 25 Feb 2017 12:01:34 -0800 Subject: [PATCH 1745/2280] mbsubmit plugin : numeric sort in print_tracks (for >=10 track releases) --- beetsplug/mbsubmit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/mbsubmit.py b/beetsplug/mbsubmit.py index 58b357dd3..02bd5f697 100644 --- a/beetsplug/mbsubmit.py +++ b/beetsplug/mbsubmit.py @@ -56,5 +56,5 @@ class MBSubmitPlugin(BeetsPlugin): return [PromptChoice(u'p', u'Print tracks', self.print_tracks)] def print_tracks(self, session, task): - for i in task.items: + for i in sorted(task.items, key=lambda i: i.track): print_data(None, i, self.config['format'].as_str()) From 1c9d42da95e09b67dc496a328d81ba79e179f84d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Feb 2017 15:30:36 -0500 Subject: [PATCH 1746/2280] Changelog/thanks for #2457 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a0ae8d43b..60d60bc40 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -55,6 +55,8 @@ Fixes: Thanks to :user:`Lompik`. :bug:`2443` :bug:`2448` * :doc:`/plugins/duplicates`: Fix Python 3 compatibility when using the ``copy`` and ``move`` options. :bug:`2444` +* :doc:`/plugins/mbsubmit`: The tracks are now sorted. Thanks to + :user:`awesomer`. :bug:`2457` 1.4.3 (January 9, 2017) From d7a12dbe1cb2722496e6a7796a07100ef1b97804 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 27 Feb 2017 13:23:07 -0500 Subject: [PATCH 1747/2280] Update recommended Python version to 3.6 On the topic of #2460, which points this out for the Windows beets.reg extra. --- docs/guides/main.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 7feacb6bf..e2e1665da 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -82,7 +82,7 @@ into this if you've installed Python yourself with `Homebrew`_ or otherwise.) If this happens, you can install beets for the current user only (sans ``sudo``) by typing ``pip install --user beets``. If you do that, you might want -to add ``~/Library/Python/2.7/bin`` to your ``$PATH``. +to add ``~/Library/Python/3.6/bin`` to your ``$PATH``. .. _System Integrity Protection: https://support.apple.com/en-us/HT204899 .. _Homebrew: http://brew.sh @@ -93,7 +93,7 @@ Installing on Windows Installing beets on Windows can be tricky. Following these steps might help you get it right: -1. If you don't have it, `install Python`_ (you want Python 2.7). +1. If you don't have it, `install Python`_ (you want Python 3.6). 2. If you haven't done so already, set your ``PATH`` environment variable to include Python and its scripts. To do so, you have to get the "Properties" From 53ccdad964ea7e1ed19db0e296074bc9fc03004b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Feb 2017 18:44:10 -0500 Subject: [PATCH 1748/2280] Update guide for installing Python on Windows As pointed out in #2461. I also notice that the installer now has a checkbox to extend the PATH, so I'm recommending that. --- docs/guides/main.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index e2e1665da..b4e62f472 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -93,14 +93,17 @@ Installing on Windows Installing beets on Windows can be tricky. Following these steps might help you get it right: -1. If you don't have it, `install Python`_ (you want Python 3.6). +1. If you don't have it, `install Python`_ (you want Python 3.6). On the last + screen, the installer gives you the option to "add Python to PATH." Check + this box. If you do that, you can skip the next step. 2. If you haven't done so already, set your ``PATH`` environment variable to include Python and its scripts. To do so, you have to get the "Properties" window for "My Computer", then choose the "Advanced" tab, then hit the "Environment Variables" button, and then look for the ``PATH`` variable in the table. Add the following to the end of the variable's value: - ``;C:\Python27;C:\Python27\Scripts``. + ``;C:\Python36;C:\Python36\Scripts``. You may need to adjust these paths to + point to your Python installation. 3. Next, `install pip`_ (if you don't have it already) by downloading and running the `get-pip.py`_ script. From c420f5917334f937959ba713959e1395e8008873 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Feb 2017 18:46:16 -0500 Subject: [PATCH 1749/2280] Remove the "install pip" step Python versions 2.7.9+ and 3.4+ come with pip, so we no longer need to instruct people to install it. See #2461. --- docs/guides/main.rst | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index b4e62f472..c90bfc98f 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -105,12 +105,9 @@ get it right: ``;C:\Python36;C:\Python36\Scripts``. You may need to adjust these paths to point to your Python installation. -3. Next, `install pip`_ (if you don't have it already) by downloading and - running the `get-pip.py`_ script. +3. Now install beets by running: ``pip install beets`` -4. Now install beets by running: ``pip install beets`` - -5. You're all set! Type ``beet`` at the command prompt to make sure everything's +4. You're all set! Type ``beet`` at the command prompt to make sure everything's in order. Windows users may also want to install a context menu item for importing files From 55f9b27428961e42a0e195f5d3a9dfbea0b79ed3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 28 Feb 2017 18:49:52 -0500 Subject: [PATCH 1750/2280] More admonition to check the beets.reg paths See #2461. --- docs/guides/main.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index c90bfc98f..ec23e8a8f 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -111,10 +111,10 @@ get it right: in order. Windows users may also want to install a context menu item for importing files -into beets. Just download and open `beets.reg`_ to add the necessary keys to the -registry. You can then right-click a directory and choose "Import with beets". -If Python is in a nonstandard location on your system, you may have to edit the -command path manually. +into beets. Download the `beets.reg`_ file and open it in a text file to make +sure the paths to Python match your system. Then double-click the file add the +necessary keys to your registry. You can then right-click a directory and +choose "Import with beets". Because I don't use Windows myself, I may have missed something. If you have trouble or you have more detail to contribute here, please direct it to From f315a17bb21e4c8eb57f8de5fc5f47557d3ad99b Mon Sep 17 00:00:00 2001 From: Pauligrinder Date: Wed, 1 Mar 2017 10:39:40 +0200 Subject: [PATCH 1751/2280] Added the copyright header Also added config['kodi']['pwd'].redact = True as suggested. --- beetsplug/kodiupdate.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py index 31c978dd6..47ad76d7a 100644 --- a/beetsplug/kodiupdate.py +++ b/beetsplug/kodiupdate.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2017, Pauli Kettunen. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. """Updates a Kodi library whenever the beets library is changed. This is based on the Plex Update plugin. @@ -39,6 +52,7 @@ class KodiUpdate(BeetsPlugin): u'user': u'kodi', u'pwd': u'kodi'}) + config['kodi']['pwd'].redact = True self.register_listener('database_change', self.listen_for_db_change) def listen_for_db_change(self, lib, model): From 659c17f8257767a8c2b00ff9100d9971a105d692 Mon Sep 17 00:00:00 2001 From: Pauligrinder Date: Wed, 1 Mar 2017 11:11:54 +0200 Subject: [PATCH 1752/2280] Code fixed according to flake8 --- beetsplug/kodiupdate.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py index 47ad76d7a..78f120d89 100644 --- a/beetsplug/kodiupdate.py +++ b/beetsplug/kodiupdate.py @@ -13,7 +13,8 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""Updates a Kodi library whenever the beets library is changed. This is based on the Plex Update plugin. +"""Updates a Kodi library whenever the beets library is changed. +This is based on the Plex Update plugin. Put something like the following in your config.yaml to configure: kodi: @@ -34,13 +35,22 @@ def update_kodi(host, port, user, password): """ url = "http://{0}:{1}/jsonrpc/".format(host, port) - # The kodi jsonrpc documentation states that Content-Type: application/json is mandatory + """Content-Type: application/json is mandatory + according to the kodi jsonrpc documentation""" + headers = {'Content-Type': 'application/json'} + # Create the payload. Id seems to be mandatory. - payload = {'jsonrpc': '2.0', 'method':'AudioLibrary.Scan', 'id':1} - r = requests.post(url, auth=(user, password), json=payload, headers=headers) + payload = {'jsonrpc': '2.0', 'method': 'AudioLibrary.Scan', 'id': 1} + r = requests.post( + url, + auth=(user, password), + json=payload, + headers=headers) + return r + class KodiUpdate(BeetsPlugin): def __init__(self): super(KodiUpdate, self).__init__() @@ -56,7 +66,7 @@ class KodiUpdate(BeetsPlugin): self.register_listener('database_change', self.listen_for_db_change) def listen_for_db_change(self, lib, model): - """Listens for beets db change and register the update for the end""" + """Listens for beets db change and register the update""" self.register_listener('cli_exit', self.update) def update(self, lib): @@ -75,4 +85,3 @@ class KodiUpdate(BeetsPlugin): except requests.exceptions.RequestException: self._log.warning(u'Update failed.') - From 877d4af3443113ef3d33a912a972864828a298d7 Mon Sep 17 00:00:00 2001 From: Pauli Kettunen Date: Wed, 1 Mar 2017 14:55:17 +0200 Subject: [PATCH 1753/2280] Added documentation for kodiupdate --- docs/plugins/kodiupdate.rst | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 docs/plugins/kodiupdate.rst diff --git a/docs/plugins/kodiupdate.rst b/docs/plugins/kodiupdate.rst new file mode 100644 index 000000000..243e384f2 --- /dev/null +++ b/docs/plugins/kodiupdate.rst @@ -0,0 +1,44 @@ +KodiUpdate Plugin +================= + +``kodiupdate`` is a very simple plugin for beets that lets you automatically +update `Kodi`_'s music library whenever you change your beets library. + +To use ``kodiupdate`` plugin, enable it in your configuration +(see :ref:`using-plugins`). +Then, you'll probably want to configure the specifics of your Kodi host. +You can do that using a ``kodi:`` section in your ``config.yaml``, +which looks like this:: + + kodi: + host: localhost + port: 8080 + user: kodi + pwd: kodi + +To use the ``kodiupdate`` plugin you need to install the `requests`_ library with: + + pip install requests + +You'll also need to enable jsonrpc in Kodi in order the use the plugin. +(System/Settings/Network/Services > Allow control of Kodi via HTTP) + +With that all in place, you'll see beets send the "update" command to your Kodi +host every time you change your beets library. + +.. _Kodi: http://kodi.tv/ +.. _requests: http://docs.python-requests.org/en/latest/ + +Configuration +------------- + +The available options under the ``kodi:`` section are: + +- **host**: The Kodi host name. + Default: ``localhost`` +- **port**: The Kodi host port. + Default: 8080 +- **user**: The Kodi host user. + Default: ``kodi`` +- **pwd**: The Kodi host password. + Default: ``kodi`` From c3c9c50b6ac6967c29773e0c1c2fdfab7f9c47e7 Mon Sep 17 00:00:00 2001 From: Mayuresh Kadu Date: Wed, 1 Mar 2017 13:06:47 +0000 Subject: [PATCH 1754/2280] Updated main.rst - Updates to seeing your music Modified "Seeing your Music" section to add explanation of the ``-f`` param of the list command. I strongly believe that first time users would very much like to start by overriding the default format of displaying results. --- docs/guides/main.rst | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index e2e1665da..d221ff810 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -230,11 +230,14 @@ songs. Thus:: The Magnetic Fields - Distortion - Three-Way The Magnetic Fields - Distortion - California Girls The Magnetic Fields - Distortion - Old Fools + $ beet ls hissing gronlandic of Montreal - Hissing Fauna, Are You the Destroyer? - Gronlandic Edit + $ beet ls bird The Knife - The Knife - Bird The Mae Shi - Terrorbird - Revelation Six + $ beet ls album:bird The Mae Shi - Terrorbird - Revelation Six @@ -245,16 +248,33 @@ put the field before the term, separated by a : character. So ``album:bird`` only looks for ``bird`` in the "album" field of your songs. (Need to know more? :doc:`/reference/query/` will answer all your questions.) -The ``beet list`` command has another useful option worth mentioning, ``-a``, -which searches for albums instead of songs:: +The ``beet list`` command has couple of other useful options worth mentioning. + +``-a``, which searches for albums instead of songs:: $ beet ls -a forever Bon Iver - For Emma, Forever Ago Freezepop - Freezepop Forever +``-f``, which lets you specify what gets displayed in the results of a search:: + + $ beet ls -a forever -f "[$format] $album ($year) - $artist - $title" + [MP3] For Emma, Forever Ago (2009) - Bon Iver - Flume + [AAC] Freezepop Forever (2011) - Freezepop - Harebrained Scheme + + As you can see, Beets has replaced the fields specified by the ``$`` prefix + (e.g. $format, $year) with values for each item in the results. A full + list of fields available for use can be found by running ``beet fields``. If + you'd like beet to use this format as default (without having to use ``-f``) + simply add it to your config file like this:: + + format_item: "[$format] $album ($year) - $artist - $title" + + And yes, the enclosing double-quotes are necessary. + So handy! -Beets also has a ``stats`` command, just in case you want to see how much music +And finally, Beets also has a ``stats`` command, just in case you want to see how much music you have:: $ beet stats From d22a2570081d5cbee9daccb3060b93e5b83d1390 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 1 Mar 2017 20:22:30 -0500 Subject: [PATCH 1755/2280] Main guide: clarify meaning of plain keyword query Fixes #2463. --- docs/guides/main.rst | 4 +++- docs/reference/query.rst | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index ec23e8a8f..4b5381a3a 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -238,7 +238,9 @@ songs. Thus:: $ beet ls album:bird The Mae Shi - Terrorbird - Revelation Six -As you can see, search terms by default search all attributes of songs. (They're +By default, a search term will match any of a handful of :ref:`common +attributes ` of songs. +(They're also implicitly joined by ANDs: a track must match *all* criteria in order to match the query.) To narrow a search term to a particular metadata field, just put the field before the term, separated by a : character. So ``album:bird`` diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 2f3366d4c..b4789aa10 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -6,6 +6,8 @@ searches that select tracks and albums from your library. This page explains the query string syntax, which is meant to vaguely resemble the syntax used by Web search engines. +.. _keywordquery: + Keyword ------- From 212ece8b8b24b8c22418ab45fd2576e5a9af65e8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Mar 2017 10:35:29 -0500 Subject: [PATCH 1756/2280] Docs: Windows Python installer checkbox location See #2462. --- docs/guides/main.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 4b5381a3a..e0e06099c 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -93,9 +93,9 @@ Installing on Windows Installing beets on Windows can be tricky. Following these steps might help you get it right: -1. If you don't have it, `install Python`_ (you want Python 3.6). On the last - screen, the installer gives you the option to "add Python to PATH." Check - this box. If you do that, you can skip the next step. +1. If you don't have it, `install Python`_ (you want Python 3.6). The + installer should give you the option to "add Python to PATH." Check this + box. If you do that, you can skip the next step. 2. If you haven't done so already, set your ``PATH`` environment variable to include Python and its scripts. To do so, you have to get the "Properties" From 697c7c0b1ff3e4b468a70c7e687e1e0855722a2e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Mar 2017 10:37:26 -0500 Subject: [PATCH 1757/2280] Docs: explicitly say what ~ means Again, see #2462. --- docs/guides/main.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index e0e06099c..923f3e806 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -142,8 +142,8 @@ place to start:: Change that first path to a directory where you'd like to keep your music. Then, for ``library``, choose a good place to keep a database file that keeps an index of your music. (The config's format is `YAML`_. You'll want to configure your -text editor to use spaces, not real tabs, for indentation.) - +text editor to use spaces, not real tabs, for indentation. Also, ``~`` means +your home directory in these paths, even on Windows.) The default configuration assumes you want to start a new organized music folder (that ``directory`` above) and that you'll *copy* cleaned-up music into that From a0cbba961f79728a421088b41a0915a600f3c8c3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 2 Mar 2017 10:45:09 -0500 Subject: [PATCH 1758/2280] Add the Kodi docs to the TOC tree --- docs/plugins/index.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 0e851d7da..eaeec02aa 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -66,6 +66,7 @@ like this:: inline ipfs keyfinder + kodiupdate lastgenre lastimport lyrics @@ -148,6 +149,8 @@ Interoperability * :doc:`embyupdate`: Automatically notifies `Emby`_ whenever the beets library changes. * :doc:`importfeeds`: Keep track of imported files via ``.m3u`` playlist file(s) or symlinks. * :doc:`ipfs`: Import libraries from friends and get albums from them via ipfs. +* :doc:`kodiupdate`: Automatically notifies `Kodi`_ whenever the beets library + changes. * :doc:`mpdupdate`: Automatically notifies `MPD`_ whenever the beets library changes. * :doc:`play`: Play beets queries in your music player. @@ -160,6 +163,7 @@ Interoperability .. _Emby: http://emby.media .. _Plex: http://plex.tv +.. _Kodi: http://kodi.tv Miscellaneous ------------- From 791f60b49065dc450e901f62c21a98fb843e7957 Mon Sep 17 00:00:00 2001 From: Mayuresh Kadu Date: Fri, 3 Mar 2017 13:06:09 +0000 Subject: [PATCH 1759/2280] further updates to Main.rst/ "Seeing your music" Revisions to the text explaining "-f" switch, as discussed in PR #2464 of the parent. --- docs/guides/main.rst | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index d221ff810..fff4c6e82 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -264,13 +264,7 @@ The ``beet list`` command has couple of other useful options worth mentioning. As you can see, Beets has replaced the fields specified by the ``$`` prefix (e.g. $format, $year) with values for each item in the results. A full - list of fields available for use can be found by running ``beet fields``. If - you'd like beet to use this format as default (without having to use ``-f``) - simply add it to your config file like this:: - - format_item: "[$format] $album ($year) - $artist - $title" - - And yes, the enclosing double-quotes are necessary. + list of fields available for use can be found by running ``beet fields``. So handy! From 1fbb557c1c7126c8afac95f500dcc6454853f2ee Mon Sep 17 00:00:00 2001 From: Mayuresh Kadu Date: Fri, 3 Mar 2017 13:11:23 +0000 Subject: [PATCH 1760/2280] Further updates to main.rst/ "Seeing your music" Un-indented text explaining "-f" switch. --- docs/guides/main.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index fff4c6e82..36ff43ff3 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -262,9 +262,9 @@ The ``beet list`` command has couple of other useful options worth mentioning. [MP3] For Emma, Forever Ago (2009) - Bon Iver - Flume [AAC] Freezepop Forever (2011) - Freezepop - Harebrained Scheme - As you can see, Beets has replaced the fields specified by the ``$`` prefix - (e.g. $format, $year) with values for each item in the results. A full - list of fields available for use can be found by running ``beet fields``. +As you can see, Beets has replaced the fields specified by the ``$`` prefix (e.g. +$format, $year) with values for each item in the results. A full list of fields +available for use can be found by running ``beet fields``. So handy! From 9e755cf7fe64fce6c978ba80f05cd85dbb97165d Mon Sep 17 00:00:00 2001 From: Mayuresh Kadu Date: Fri, 3 Mar 2017 13:14:24 +0000 Subject: [PATCH 1761/2280] Update main.rst/ Seeing your music Undid adding extra lines to the output. As @sampsyo has rightly pointed out - these would not have appeared in the output. --- docs/guides/main.rst | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 36ff43ff3..57983e222 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -230,14 +230,11 @@ songs. Thus:: The Magnetic Fields - Distortion - Three-Way The Magnetic Fields - Distortion - California Girls The Magnetic Fields - Distortion - Old Fools - $ beet ls hissing gronlandic of Montreal - Hissing Fauna, Are You the Destroyer? - Gronlandic Edit - $ beet ls bird The Knife - The Knife - Bird The Mae Shi - Terrorbird - Revelation Six - $ beet ls album:bird The Mae Shi - Terrorbird - Revelation Six From 4211050e2cf835272de6ab7e6a8f5d744f888fae Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 3 Mar 2017 10:02:57 -0600 Subject: [PATCH 1762/2280] Docs refinements for Kodi plugin #2411 --- docs/plugins/kodiupdate.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/plugins/kodiupdate.rst b/docs/plugins/kodiupdate.rst index 243e384f2..a1ec04775 100644 --- a/docs/plugins/kodiupdate.rst +++ b/docs/plugins/kodiupdate.rst @@ -1,12 +1,12 @@ KodiUpdate Plugin ================= -``kodiupdate`` is a very simple plugin for beets that lets you automatically -update `Kodi`_'s music library whenever you change your beets library. +The ``kodiupdate`` plugin lets you automatically update `Kodi`_'s music +library whenever you change your beets library. To use ``kodiupdate`` plugin, enable it in your configuration (see :ref:`using-plugins`). -Then, you'll probably want to configure the specifics of your Kodi host. +Then, you'll want to configure the specifics of your Kodi host. You can do that using a ``kodi:`` section in your ``config.yaml``, which looks like this:: @@ -16,12 +16,12 @@ which looks like this:: user: kodi pwd: kodi -To use the ``kodiupdate`` plugin you need to install the `requests`_ library with: +To use the ``kodiupdate`` plugin you need to install the `requests`_ library with:: pip install requests -You'll also need to enable jsonrpc in Kodi in order the use the plugin. -(System/Settings/Network/Services > Allow control of Kodi via HTTP) +You'll also need to enable JSON-RPC in Kodi in order the use the plugin. +In Kodi's interface, navigate to System/Settings/Network/Services and choose "Allow control of Kodi via HTTP." With that all in place, you'll see beets send the "update" command to your Kodi host every time you change your beets library. From 38d2aeaed9d0bc30ad103efc7b045c5827f7aa9f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 3 Mar 2017 10:04:46 -0600 Subject: [PATCH 1763/2280] Changelog for Kodi plugin (#2411) --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 60d60bc40..2ceed486d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -32,6 +32,8 @@ New features: links on filesystems that support them. Thanks to :user:`jacobwgillespie`. :bug:`2445` * You can now run beets by typing `python -m beets`. :bug:`2453` +* A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync + with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` Fixes: From a8c46d8b32724d23b6abcc30730f6d54a2238e35 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 3 Mar 2017 10:17:49 -0600 Subject: [PATCH 1764/2280] Brevity/clarity improvements for #2464 --- docs/guides/main.rst | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index c230b662a..f0b3635c2 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -247,27 +247,23 @@ put the field before the term, separated by a : character. So ``album:bird`` only looks for ``bird`` in the "album" field of your songs. (Need to know more? :doc:`/reference/query/` will answer all your questions.) -The ``beet list`` command has couple of other useful options worth mentioning. - -``-a``, which searches for albums instead of songs:: +The ``beet list`` command also has an ``-a`` option, which searches for albums instead of songs:: $ beet ls -a forever Bon Iver - For Emma, Forever Ago Freezepop - Freezepop Forever -``-f``, which lets you specify what gets displayed in the results of a search:: +There's also an ``-f`` option (for *format*) that lets you specify what gets displayed in the results of a search:: $ beet ls -a forever -f "[$format] $album ($year) - $artist - $title" [MP3] For Emma, Forever Ago (2009) - Bon Iver - Flume [AAC] Freezepop Forever (2011) - Freezepop - Harebrained Scheme - -As you can see, Beets has replaced the fields specified by the ``$`` prefix (e.g. -$format, $year) with values for each item in the results. A full list of fields -available for use can be found by running ``beet fields``. - -So handy! -And finally, Beets also has a ``stats`` command, just in case you want to see how much music +In the format option, field references like `$format` and `$year` are filled +in with data from each result. You can see a full list of available fields by +running ``beet fields``. + +Beets also has a ``stats`` command, just in case you want to see how much music you have:: $ beet stats From d356356111977c06e4227011aed919ca4ab2df74 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 3 Mar 2017 11:59:50 -0600 Subject: [PATCH 1765/2280] Fix #2466: GIO returns bytes, so decode them --- beetsplug/thumbnails.py | 8 +++++++- docs/changelog.rst | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 1ea90f01e..838206156 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -289,4 +289,10 @@ class GioURI(URIGetter): raise finally: self.libgio.g_free(uri_ptr) - return uri + + try: + return uri.decode(util._fsencoding()) + except UnicodeDecodeError: + raise RuntimeError( + "Could not decode filename from GIO: {!r}".format(uri) + ) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2ceed486d..7e86755fb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -59,6 +59,8 @@ Fixes: ``copy`` and ``move`` options. :bug:`2444` * :doc:`/plugins/mbsubmit`: The tracks are now sorted. Thanks to :user:`awesomer`. :bug:`2457` +* :doc:`/plugins/thumbnails`: Fix a string-related crash on Python 3. + :bug:`2466` 1.4.3 (January 9, 2017) From 17ad3e83dbe20126ff0048c29e1c1dd245845645 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 3 Mar 2017 12:10:26 -0600 Subject: [PATCH 1766/2280] Test updates for #2466 fix --- test/test_thumbnails.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_thumbnails.py b/test/test_thumbnails.py index d287c073a..dc03f06f7 100644 --- a/test/test_thumbnails.py +++ b/test/test_thumbnails.py @@ -276,12 +276,12 @@ class ThumbnailsTest(unittest.TestCase, TestHelper): if not gio.available: self.skipTest(u"GIO library not found") - self.assertEqual(gio.uri(u"/foo"), b"file:///") # silent fail - self.assertEqual(gio.uri(b"/foo"), b"file:///foo") - self.assertEqual(gio.uri(b"/foo!"), b"file:///foo!") + self.assertEqual(gio.uri(u"/foo"), u"file:///") # silent fail + self.assertEqual(gio.uri(b"/foo"), u"file:///foo") + self.assertEqual(gio.uri(b"/foo!"), u"file:///foo!") self.assertEqual( gio.uri(b'/music/\xec\x8b\xb8\xec\x9d\xb4'), - b'file:///music/%EC%8B%B8%EC%9D%B4') + u'file:///music/%EC%8B%B8%EC%9D%B4') def suite(): From 8d14e1b6df03b69f9be008ea7ffed21576f06170 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 19:07:06 -0500 Subject: [PATCH 1767/2280] smartplaylist: Support overlapping playlist defs See http://discourse.beets.io/t/beets-path-handling-for-delimited-fields/44 --- beetsplug/smartplaylist.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/beetsplug/smartplaylist.py b/beetsplug/smartplaylist.py index 514e74acc..009512c5c 100644 --- a/beetsplug/smartplaylist.py +++ b/beetsplug/smartplaylist.py @@ -172,6 +172,9 @@ class SmartPlaylistPlugin(BeetsPlugin): if relative_to: relative_to = normpath(relative_to) + # Maps playlist filenames to lists of track filenames. + m3us = {} + for playlist in self._matched_playlists: name, (query, q_sort), (album_query, a_q_sort) = playlist self._log.debug(u"Creating playlist {0}", name) @@ -183,7 +186,6 @@ class SmartPlaylistPlugin(BeetsPlugin): for album in lib.albums(album_query, a_q_sort): items.extend(album.items()) - m3us = {} # As we allow tags in the m3u names, we'll need to iterate through # the items and generate the correct m3u file names. for item in items: @@ -196,13 +198,14 @@ class SmartPlaylistPlugin(BeetsPlugin): item_path = os.path.relpath(item.path, relative_to) if item_path not in m3us[m3u_name]: m3us[m3u_name].append(item_path) - # Now iterate through the m3us that we need to generate - for m3u in m3us: - m3u_path = normpath(os.path.join(playlist_dir, - bytestring_path(m3u))) - mkdirall(m3u_path) - with open(syspath(m3u_path), 'wb') as f: - for path in m3us[m3u]: - f.write(path + b'\n') + + # Write all of the accumulated track lists to files. + for m3u in m3us: + m3u_path = normpath(os.path.join(playlist_dir, + bytestring_path(m3u))) + mkdirall(m3u_path) + with open(syspath(m3u_path), 'wb') as f: + for path in m3us[m3u]: + f.write(path + b'\n') self._log.info(u"{0} playlists updated", len(self._matched_playlists)) From ad4cd7a447e5ff8504481e9e7259ae02c39dfb3b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 22:58:00 -0500 Subject: [PATCH 1768/2280] Fix #2469: Beatport track limit It looks like the API uses pagination, and the default page size is 10. An easy fix is to just request lots of tracks per page (here, 100). A nicer thing to do in the future would be to actually traverse multiple pages. --- beetsplug/beatport.py | 3 ++- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index c62abf7ab..8a73efa16 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -161,7 +161,8 @@ class BeatportClient(object): :returns: Tracks in the matching release :rtype: list of :py:class:`BeatportTrack` """ - response = self._get('/catalog/3/tracks', releaseId=beatport_id) + response = self._get('/catalog/3/tracks', releaseId=beatport_id, + perPage=100) return [BeatportTrack(t) for t in response] def get_track(self, beatport_id): diff --git a/docs/changelog.rst b/docs/changelog.rst index 7e86755fb..9ad8b3b4d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -61,6 +61,8 @@ Fixes: :user:`awesomer`. :bug:`2457` * :doc:`/plugins/thumbnails`: Fix a string-related crash on Python 3. :bug:`2466` +* :doc:`/plugins/beatport`: More than just 10 songs are now fetched per album. + :bug:`2469` 1.4.3 (January 9, 2017) From 1fbbcf65fde067bd753907dc18218acc3f7dddee Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:29:09 -0500 Subject: [PATCH 1769/2280] Fix some confusing indentation --- beetsplug/embedart.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 6344dc2b9..f7e92e6f1 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -69,26 +69,26 @@ class EmbedCoverArtPlugin(BeetsPlugin): def _confirmation(items, opts): # Confirm artwork changes to library items. - if not opts.yes: - # Prepare confirmation with user. - print_() + if not opts.yes: + # Prepare confirmation with user. + print_() - fmt = u'$albumartist - $album' - istr = u'album' - if opts.file: - fmt = u'$albumartist - $album - $title' - istr = u'file' - prompt = u'Modify artwork for %i %s%s (y/n)?' % \ - (len(items), istr, 's' if len(items) > 1 else '') + fmt = u'$albumartist - $album' + istr = u'album' + if opts.file: + fmt = u'$albumartist - $album - $title' + istr = u'file' + prompt = u'Modify artwork for %i %s%s (y/n)?' % \ + (len(items), istr, 's' if len(items) > 1 else '') - # Show all the items. - for item in items: - print_(format(item, fmt)) + # Show all the items. + for item in items: + print_(format(item, fmt)) - # Confirm with user. - if not ui.input_yn(prompt, True): - return False - return True + # Confirm with user. + if not ui.input_yn(prompt, True): + return False + return True def embed_func(lib, opts, args): if opts.file: From c8499eb56d55b1f7d24ea26fbcba681ca427b92e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:34:53 -0500 Subject: [PATCH 1770/2280] _confirmation does not need to be a closure --- beetsplug/embedart.py | 50 +++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index f7e92e6f1..658b99599 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -27,6 +27,33 @@ from beets import config from beets import art +def _confirmation(items, opts): + """Show the list of affected objects (items or albums) and confirm + that the user wants to modify their artwork. + """ + # Confirm artwork changes to library items. + if not opts.yes: + # Prepare confirmation with user. + print_() + + fmt = u'$albumartist - $album' + istr = u'album' + if opts.file: + fmt = u'$albumartist - $album - $title' + istr = u'file' + prompt = u'Modify artwork for %i %s%s (y/n)?' % \ + (len(items), istr, 's' if len(items) > 1 else '') + + # Show all the items. + for item in items: + print_(format(item, fmt)) + + # Confirm with user. + if not ui.input_yn(prompt, True): + return False + return True + + class EmbedCoverArtPlugin(BeetsPlugin): """Allows albumart to be embedded into the actual files. """ @@ -67,29 +94,6 @@ class EmbedCoverArtPlugin(BeetsPlugin): compare_threshold = self.config['compare_threshold'].get(int) ifempty = self.config['ifempty'].get(bool) - def _confirmation(items, opts): - # Confirm artwork changes to library items. - if not opts.yes: - # Prepare confirmation with user. - print_() - - fmt = u'$albumartist - $album' - istr = u'album' - if opts.file: - fmt = u'$albumartist - $album - $title' - istr = u'file' - prompt = u'Modify artwork for %i %s%s (y/n)?' % \ - (len(items), istr, 's' if len(items) > 1 else '') - - # Show all the items. - for item in items: - print_(format(item, fmt)) - - # Confirm with user. - if not ui.input_yn(prompt, True): - return False - return True - def embed_func(lib, opts, args): if opts.file: imagepath = normpath(opts.file) From 430595825f624e00cf7cb4a86bd8568fd02257a3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:37:04 -0500 Subject: [PATCH 1771/2280] Rename parameter to be more sensible We don't just take items; they're either items or albums. --- beetsplug/embedart.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 658b99599..c3463c1a6 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -27,7 +27,7 @@ from beets import config from beets import art -def _confirmation(items, opts): +def _confirmation(objs, opts): """Show the list of affected objects (items or albums) and confirm that the user wants to modify their artwork. """ @@ -42,11 +42,11 @@ def _confirmation(items, opts): fmt = u'$albumartist - $album - $title' istr = u'file' prompt = u'Modify artwork for %i %s%s (y/n)?' % \ - (len(items), istr, 's' if len(items) > 1 else '') + (len(objs), istr, 's' if len(objs) > 1 else '') - # Show all the items. - for item in items: - print_(format(item, fmt)) + # Show all the items or albums. + for obj in objs: + print_(format(obj, fmt)) # Confirm with user. if not ui.input_yn(prompt, True): From eddbab63bd5e4efaaeeab42220771a5e9387b1fe Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:37:33 -0500 Subject: [PATCH 1772/2280] Remove extraneous blank line --- beetsplug/embedart.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index c3463c1a6..39cab585e 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -33,9 +33,6 @@ def _confirmation(objs, opts): """ # Confirm artwork changes to library items. if not opts.yes: - # Prepare confirmation with user. - print_() - fmt = u'$albumartist - $album' istr = u'album' if opts.file: From 3a436bb33dc5553c3d447a5d77a650a5b248466a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:38:16 -0500 Subject: [PATCH 1773/2280] Remove explicit format We now use the default formats from the configuration. --- beetsplug/embedart.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 39cab585e..618761e90 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -33,17 +33,15 @@ def _confirmation(objs, opts): """ # Confirm artwork changes to library items. if not opts.yes: - fmt = u'$albumartist - $album' istr = u'album' if opts.file: - fmt = u'$albumartist - $album - $title' istr = u'file' prompt = u'Modify artwork for %i %s%s (y/n)?' % \ (len(objs), istr, 's' if len(objs) > 1 else '') # Show all the items or albums. for obj in objs: - print_(format(obj, fmt)) + print_(format(obj)) # Confirm with user. if not ui.input_yn(prompt, True): From f985970b252346f40dc22fdb6ef678442b966eb0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:42:20 -0500 Subject: [PATCH 1774/2280] Simplify scope of _confirmation and formatting --- beetsplug/embedart.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 618761e90..4f6cf1580 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -27,26 +27,26 @@ from beets import config from beets import art -def _confirmation(objs, opts): +def _confirmation(objs, album): """Show the list of affected objects (items or albums) and confirm that the user wants to modify their artwork. + + `album` is a Boolean indicating whether these are albums (as opposed + to items). """ - # Confirm artwork changes to library items. - if not opts.yes: - istr = u'album' - if opts.file: - istr = u'file' - prompt = u'Modify artwork for %i %s%s (y/n)?' % \ - (len(objs), istr, 's' if len(objs) > 1 else '') + noun = u'album' if album else u'file' + prompt = u'Modify artwork for {} {}{} (y/n)?'.format( + len(objs), + noun, + u's' if len(objs) > 1 else u'' + ) - # Show all the items or albums. - for obj in objs: - print_(format(obj)) + # Show all the items or albums. + for obj in objs: + print_(format(obj)) - # Confirm with user. - if not ui.input_yn(prompt, True): - return False - return True + # Confirm with user. + return ui.input_yn(prompt, True) class EmbedCoverArtPlugin(BeetsPlugin): @@ -100,7 +100,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): items = lib.items(decargs(args)) # Confirm with user. - if not _confirmation(items, opts): + if not opts.yes and not _confirmation(items, not opts.file): return for item in items: @@ -110,7 +110,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): items = lib.albums(decargs(args)) # Confirm with user. - if not _confirmation(items, opts): + if not opts.yes and not _confirmation(items, not opts.file): return for album in items: From f0f55d11ec535ad3159336d19cdd51c937759ca9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:42:38 -0500 Subject: [PATCH 1775/2280] Rename _confirmation to _confirm --- beetsplug/embedart.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 4f6cf1580..3d7f4f993 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -27,7 +27,7 @@ from beets import config from beets import art -def _confirmation(objs, album): +def _confirm(objs, album): """Show the list of affected objects (items or albums) and confirm that the user wants to modify their artwork. @@ -100,20 +100,20 @@ class EmbedCoverArtPlugin(BeetsPlugin): items = lib.items(decargs(args)) # Confirm with user. - if not opts.yes and not _confirmation(items, not opts.file): + if not opts.yes and not _confirm(items, not opts.file): return for item in items: art.embed_item(self._log, item, imagepath, maxwidth, None, compare_threshold, ifempty) else: - items = lib.albums(decargs(args)) + albums = lib.albums(decargs(args)) # Confirm with user. - if not opts.yes and not _confirmation(items, not opts.file): + if not opts.yes and not _confirm(albums, not opts.file): return - for album in items: + for album in albums: art.embed_album(self._log, album, maxwidth, False, compare_threshold, ifempty) self.remove_artfile(album) From 8ce7b49ed812f4fa704f822c90a6f526dbf2d446 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:45:29 -0500 Subject: [PATCH 1776/2280] Default to confirm --- beetsplug/embedart.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 3d7f4f993..51d401af8 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -35,7 +35,7 @@ def _confirm(objs, album): to items). """ noun = u'album' if album else u'file' - prompt = u'Modify artwork for {} {}{} (y/n)?'.format( + prompt = u'Modify artwork for {} {}{} (Y/n)?'.format( len(objs), noun, u's' if len(objs) > 1 else u'' @@ -46,7 +46,7 @@ def _confirm(objs, album): print_(format(obj)) # Confirm with user. - return ui.input_yn(prompt, True) + return ui.input_yn(prompt) class EmbedCoverArtPlugin(BeetsPlugin): From b91185a9ff7cd7aecd65bbda10e7971921f7b2b3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:53:17 -0500 Subject: [PATCH 1777/2280] Docs tweaks for #2422 --- docs/changelog.rst | 5 +++-- docs/plugins/embedart.rst | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index fd37f992e..dd597d933 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,8 +31,9 @@ New features: * A new :ref:`hardlink` config option instructs the importer to create hard links on filesystems that support them. Thanks to :user:`jacobwgillespie`. :bug:`2445` -* :doc:`/plugins/embedart` by default now asks for confirmation before - embedding art into music files. Thanks to :user:`Stunner`. :bug:`1999` +* :doc:`/plugins/embedart`: The explicit ``embedart`` command now asks for + confirmation before embedding art into music files. Thanks to + :user:`Stunner`. :bug:`1999` * You can now run beets by typing `python -m beets`. :bug:`2453` * A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index 717bfb8e2..68ea0f664 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -81,8 +81,8 @@ embedded album art: * ``beet embedart [-f IMAGE] QUERY``: embed images into the every track on the albums matching the query. If the ``-f`` (``--file``) option is given, then use a specific image file from the filesystem; otherwise, each album embeds - its own currently associated album art. Will prompt for confirmation before - making the change unless the ``-y`` (``--yes``) option is specified. + its own currently associated album art. The command prompts for confirmation + before making the change unless you specify the ``-y`` (``--yes``) option. * ``beet extractart [-a] [-n FILE] QUERY``: extracts the images for all albums matching the query. The images are placed inside the album folder. You can From 5a71ce722a672431c035ad3b6c430b97fbaacdc9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 6 Mar 2017 23:55:14 -0500 Subject: [PATCH 1778/2280] Simplify embedart test changes for #2422 Whenever possible, it's nice to avoid using DummyIO---it can make debugging difficult. --- test/test_embedart.py | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index b0e66dddb..ad04c57d7 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -52,8 +52,6 @@ class EmbedartCliTest(_common.TestCase, TestHelper): def setUp(self): super(EmbedartCliTest, self).setUp() - self.io.install() - self.setup_beets() # Converter is threaded self.load_plugins('embedart') @@ -71,8 +69,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data() album = self.add_album_fixture() item = album.items()[0] - self.io.addinput('y') - self.run_command('embedart', '-f', self.small_artpath) + self.run_command('embedart', '-y', '-f', self.small_artpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -82,8 +79,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): item = album.items()[0] album.artpath = self.small_artpath album.store() - self.io.addinput('y') - self.run_command('embedart') + self.run_command('embedart', '-y') mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) @@ -101,8 +97,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): album.store() config['embedart']['remove_art_file'] = True - self.io.addinput('y') - self.run_command('embedart') + self.run_command('embedart', '-y') if os.path.isfile(tmp_path): os.remove(tmp_path) @@ -112,8 +107,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.add_album_fixture() logging.getLogger('beets.embedart').setLevel(logging.DEBUG) with self.assertRaises(ui.UserError): - self.io.addinput('y') - self.run_command('embedart', '-f', '/doesnotexist') + self.run_command('embedart', '-y', '-f', '/doesnotexist') def test_embed_non_image_file(self): album = self.add_album_fixture() @@ -124,8 +118,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): os.close(handle) try: - self.io.addinput('y') - self.run_command('embedart', '-f', tmp_path) + self.run_command('embedart', '-y', '-f', tmp_path) finally: os.remove(tmp_path) @@ -137,11 +130,9 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data(self.abbey_artpath) album = self.add_album_fixture() item = album.items()[0] - self.io.addinput('y') - self.run_command('embedart', '-f', self.abbey_artpath) + self.run_command('embedart', '-y', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 - self.io.addinput('y') - self.run_command('embedart', '-f', self.abbey_differentpath) + self.run_command('embedart', '-y', '-f', self.abbey_differentpath) mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data, @@ -153,8 +144,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self._setup_data(self.abbey_similarpath) album = self.add_album_fixture() item = album.items()[0] - self.io.addinput('y') - self.run_command('embedart', '-f', self.abbey_artpath) + self.run_command('embedart', '-y', '-f', self.abbey_artpath) config['embedart']['compare_threshold'] = 20 self.run_command('embedart', '-y', '-f', self.abbey_similarpath) mediafile = MediaFile(syspath(item.path)) From 4d90c9645c4901835c8585ad0f8fc38345ae44ec Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 7 Mar 2017 22:55:44 -0500 Subject: [PATCH 1779/2280] Changelog for #2468 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index d69012706..f72d22f9a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -34,6 +34,9 @@ New features: * You can now run beets by typing `python -m beets`. :bug:`2453` * A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` +* :doc:`/plugins/smartplaylist`: Different playlist specifications that + generate identically-named playlist files no longer conflict; instead, the + resulting lists of tracks are concatenated. :bug:`2468` Fixes: From f6df3befac07109848594af46459853fd12b51b3 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 8 Mar 2017 19:06:09 -0800 Subject: [PATCH 1780/2280] Added interactive test method for embedart plugin. --- test/test_embedart.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/test_embedart.py b/test/test_embedart.py index ad04c57d7..30e4841ba 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -52,6 +52,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): def setUp(self): super(EmbedartCliTest, self).setUp() + self.io.install() self.setup_beets() # Converter is threaded self.load_plugins('embedart') @@ -65,6 +66,15 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.unload_plugins() self.teardown_beets() + def test_embed_art_from_file_with_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + mediafile = MediaFile(syspath(item.path)) + self.assertEqual(mediafile.images[0].data, self.image_data) + def test_embed_art_from_file(self): self._setup_data() album = self.add_album_fixture() From acbf3b75345e408977c7a7cd54f37bd36fd03254 Mon Sep 17 00:00:00 2001 From: abba23 <628208@gmail.com> Date: Fri, 10 Mar 2017 17:31:23 +0100 Subject: [PATCH 1781/2280] added beets-popularity plugin --- docs/plugins/index.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index eaeec02aa..0b2440aa8 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -240,6 +240,8 @@ Here are a few of the plugins written by the beets community: * `beets-usertag`_ lets you use keywords to tag and organize your music. +* `beets-popularity`_ fetches popularity values from Spotify. + .. _beets-check: https://github.com/geigerzaehler/beets-check .. _copyartifacts: https://github.com/sbarakat/beets-copyartifacts .. _dsedivec: https://github.com/dsedivec/beets-plugins @@ -257,3 +259,5 @@ Here are a few of the plugins written by the beets community: .. _beets-noimport: https://gitlab.com/tiago.dias/beets-noimport .. _whatlastgenre: https://github.com/YetAnotherNerd/whatlastgenre/tree/master/plugin/beets .. _beets-usertag: https://github.com/igordertigor/beets-usertag +.. _beets-popularity: https://github.com/abba23/beets-popularity + From 64d69f0817c0282fa71ee980ce3c6d602ce52730 Mon Sep 17 00:00:00 2001 From: Aaron Date: Fri, 10 Mar 2017 23:30:49 -0800 Subject: [PATCH 1782/2280] =?UTF-8?q?embedart:=20Added=20test=20case=20for?= =?UTF-8?q?=20inputting=20=E2=80=9Cno=E2=80=9D=20option=20interactively.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/test_embedart.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/test/test_embedart.py b/test/test_embedart.py index 30e4841ba..1622fffb4 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -66,7 +66,7 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.unload_plugins() self.teardown_beets() - def test_embed_art_from_file_with_input(self): + def test_embed_art_from_file_with_yes_input(self): self._setup_data() album = self.add_album_fixture() item = album.items()[0] @@ -75,6 +75,16 @@ class EmbedartCliTest(_common.TestCase, TestHelper): mediafile = MediaFile(syspath(item.path)) self.assertEqual(mediafile.images[0].data, self.image_data) + def test_embed_art_from_file_with_no_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('n') + self.run_command('embedart', '-f', self.small_artpath) + mediafile = MediaFile(syspath(item.path)) + # make sure that images array is empty (nothing embedded) + self.assertEqual(len(mediafile.images), 0) + def test_embed_art_from_file(self): self._setup_data() album = self.add_album_fixture() From 71aab6d7432fe18a5f2b4765aad79aea23b6f1e2 Mon Sep 17 00:00:00 2001 From: inytar Date: Thu, 16 Mar 2017 11:19:13 -0400 Subject: [PATCH 1783/2280] Remove check for supported formats in absubmit Also lower the logging to warning if the extractor fails to analyse a file --- beetsplug/absubmit.py | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index e30fe21fa..e935324f3 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -90,10 +90,6 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): self.extractor_sha.update(extractor.read()) self.extractor_sha = self.extractor_sha.hexdigest() - supported_formats = {'mp3', 'ogg', 'oga', 'flac', 'mp4', 'm4a', 'm4r', - 'm4b', 'm4p', 'aac', 'wma', 'asf', 'mpc', 'wv', - 'spx', 'tta', '3g2', 'aif', 'aiff', 'ape'} - base_url = 'https://acousticbrainz.org/api/v1/{mbid}/low-level' def commands(self): @@ -119,11 +115,6 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): self._log.info(u'Not analysing {}, missing ' u'musicbrainz track id.', item) return None - # If file format is not supported skip it. - if item['format'].lower() not in self.supported_formats: - self._log.info(u'Not analysing {}, file not in ' - u'supported format.', item) - return None # Temporary file to save extractor output to, extractor only works # if an output file is given. Here we use a temporary file to copy @@ -136,7 +127,7 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): try: call([self.extractor, util.syspath(item.path), filename]) except ABSubmitError as e: - self._log.error( + self._log.warning( u'Failed to analyse {item} for AcousticBrainz: {error}', item=item, error=e ) From ba78feb9f86fb064da64bb6fb91401bcd4f1e5ff Mon Sep 17 00:00:00 2001 From: inytar Date: Thu, 16 Mar 2017 11:20:21 -0400 Subject: [PATCH 1784/2280] Fix a typo in the absubmit documentation --- docs/plugins/absubmit.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/absubmit.rst b/docs/plugins/absubmit.rst index 665133c64..feebc1642 100644 --- a/docs/plugins/absubmit.rst +++ b/docs/plugins/absubmit.rst @@ -9,7 +9,7 @@ Installation The `absubmit` plugin requires the `streaming_extractor_music`_ program to run. Its source can be found on `GitHub`_, and while it is possible to compile the extractor from source, AcousticBrainz would prefer if you used their binary (see the AcousticBrainz `FAQ`_). -The `absubmit` also plugin requires `requests`_, which you can install using `pip_` by typing:: +The `absubmit` also plugin requires `requests`_, which you can install using `pip`_ by typing:: pip install requests From bbd0b220058c623e6ad10e4cdc1e44d6a8f69ad7 Mon Sep 17 00:00:00 2001 From: abigaildelarosa Date: Fri, 17 Mar 2017 16:38:59 +0100 Subject: [PATCH 1785/2280] change modify paragraph --- docs/reference/cli.rst | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 59e2eeb68..7f70b99a3 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -238,12 +238,7 @@ artist="Tom Tom Club"`` will change the artist for the track "Genius of Love." To remove fields (which is only possible for flexible attributes), follow a field name with an exclamation point: ``field!``. -The ``-a`` switch operates on albums instead of -individual tracks. Items will automatically be moved around when necessary if -they're in your library directory, but you can disable that with ``-M``. Tags -will be written to the files according to the settings you have for imports, -but these can be overridden with ``-w`` (write tags, the default) and ``-W`` -(don't write tags). +The ``-a`` switch operates on albums instead of individual tracks. This is relevant if you are working with any kind of album field in your paths format :doc:`configuration ` in case that you need to change any album field such as year, album, albumartist etc, do not forget to add the command ``-a`` in the query. Otherwise you will be changing the track fields. Keep in mind that the new value will be used to update the path in the library and on the filesystem. Items will automatically be moved around when necessary if they're in your library directory, but you can disable that with ``-M``. Tags will be written to the files according to the settings you have for imports, but these can be overridden with ``-w`` (write tags, the default) and ``-W`` (don't write tags). When you run the ``modify`` command, it prints a list of all affected items in the library and asks for your permission before making any From 0342f730de1bfe6384225d5441098e3b684238f2 Mon Sep 17 00:00:00 2001 From: inytar Date: Fri, 17 Mar 2017 14:22:36 -0400 Subject: [PATCH 1786/2280] Update changelog --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index cb2934874..2df928eba 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -43,6 +43,7 @@ New features: Fixes: +* :doc:`/plugins/absubmit`: Do not filter for supported formats. :bug:`2471` * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` backend. :bug:`2382` From af335868a86fe96a728be9c685f09d3979b1b793 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 18 Mar 2017 14:10:21 -0400 Subject: [PATCH 1787/2280] Writing refinement for #2480 A slightly more nuanced description. Also use two separate paragraphs. --- docs/reference/cli.rst | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 7f70b99a3..403c1e174 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -238,7 +238,18 @@ artist="Tom Tom Club"`` will change the artist for the track "Genius of Love." To remove fields (which is only possible for flexible attributes), follow a field name with an exclamation point: ``field!``. -The ``-a`` switch operates on albums instead of individual tracks. This is relevant if you are working with any kind of album field in your paths format :doc:`configuration ` in case that you need to change any album field such as year, album, albumartist etc, do not forget to add the command ``-a`` in the query. Otherwise you will be changing the track fields. Keep in mind that the new value will be used to update the path in the library and on the filesystem. Items will automatically be moved around when necessary if they're in your library directory, but you can disable that with ``-M``. Tags will be written to the files according to the settings you have for imports, but these can be overridden with ``-w`` (write tags, the default) and ``-W`` (don't write tags). +The ``-a`` switch operates on albums instead of individual tracks. Without +this flag, the command will only change *track-level* data, even if all the +tracks belong to the same album. If you want to change an *album-level* field, +such as ``year`` or ``albumartist``, you'll want to use the ``-a`` flag to +avoid a confusing situation where the data for individual tracks conflicts +with the data for the whole album. + +Items will automatically be moved around when necessary if they're in your +library directory, but you can disable that with ``-M``. Tags will be written +to the files according to the settings you have for imports, but these can be +overridden with ``-w`` (write tags, the default) and ``-W`` (don't write +tags). When you run the ``modify`` command, it prints a list of all affected items in the library and asks for your permission before making any From 339a1ef671fe0fab0068f67ba2d055a21896962b Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Sat, 18 Mar 2017 01:58:38 -0400 Subject: [PATCH 1788/2280] beetsplug: add '-a' to show missing albums to 'missing' plugin Passing -a to 'beet missing' shows albums missing by all artists in the library. Signed-off-by: Quentin Young --- beetsplug/missing.py | 111 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 91 insertions(+), 20 deletions(-) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 24c903cd6..6afe3b37b 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Pedro Silva. +# Copyright 2017, Quentin Young. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -17,6 +18,12 @@ """ from __future__ import division, absolute_import, print_function +import time +import beets +import musicbrainzngs as m +import sys + +from musicbrainzngs.musicbrainz import MusicBrainzError from beets.autotag import hooks from beets.library import Item from beets.plugins import BeetsPlugin @@ -93,6 +100,7 @@ class MissingPlugin(BeetsPlugin): self.config.add({ 'count': False, 'total': False, + 'albums': False, }) self.album_template_fields['missing'] = _missing_count @@ -106,36 +114,99 @@ class MissingPlugin(BeetsPlugin): self._command.parser.add_option( u'-t', u'--total', dest='total', action='store_true', help=u'count total of missing tracks') + self._command.parser.add_option( + u'-a', u'--albums', dest='albums', action='store_true', + help=u'show missing albums for artist instead of tracks') self._command.parser.add_format_option() def commands(self): def _miss(lib, opts, args): self.config.set_args(opts) - count = self.config['count'].get() - total = self.config['total'].get() - fmt = config['format_album' if count else 'format_item'].get() + albms = self.config['albums'].get() - albums = lib.albums(decargs(args)) - if total: - print(sum([_missing_count(a) for a in albums])) - return - - # Default format string for count mode. - if count: - fmt += ': $missing' - - for album in albums: - if count: - if _missing_count(album): - print_(format(album, fmt)) - - else: - for item in self._missing(album): - print_(format(item, fmt)) + helper = self._missing_albums if albms else self._missing_tracks + helper(lib, args) self._command.func = _miss return [self._command] + def _missing_tracks(self, lib, args): + """Logic for determining missing tracks from each album in the library + (the usual case) + """ + albums = lib.albums(decargs(args)) + + count = self.config['count'].get() + total = self.config['total'].get() + fmt = config['format_album' if count else 'format_item'].get() + + if total: + print(sum([_missing_count(a) for a in albums])) + return + + # Default format string for count mode. + if count: + fmt += ': $missing' + + for album in albums: + if count: + if _missing_count(album): + print_(format(album, fmt)) + + else: + for item in self._missing(album): + print_(format(item, fmt)) + + def _missing_albums(self, lib, args): + """Logic for determining missing albums from each artist in the library + (-a case) + """ + albums = lib.albums(decargs(args)) + # build dict mapping artist to list of their albums in library + albums_by_artist = {} + for alb in albums: + artist = (alb['albumartist'], alb['mb_albumartistid']) + artistalbs = albums_by_artist.setdefault(artist, []) + artistalbs.append(alb) + albums_by_artist[artist] = artistalbs + + # build dict mapping artist to list of all albums + m.set_useragent('beets', beets.__version__, 'http://beets.io/') + + for artist, albums in albums_by_artist.items(): + if artist[1] is None or artist[1] == "": + print_(u"[!] No musicbrainz ID for artist {}, skipping." + .format(artist[0]), stream=sys.stderr) + continue + + try: + releases = m.browse_releases(artist=artist[1])['release-list'] + except MusicBrainzError as err: + print_(u"[!] Couldn't fetch info for artist '{}' ({}) - '{}'" + .format(artist[0], artist[1], err), stream=sys.stderr) + continue + + missing = [] + present = [] + for release in releases: + missing.append(release) + for alb in albums: + # compare by title, don't care about specific releases + if alb['album'].lower() == release['title'].lower(): + missing.remove(release) + present.append(release) + break + + missing_titles = {release['title'] for release in missing} + + prefix_miss = "{} - ".format(artist[0]) + + for release in missing_titles: + print_(u"{}{}".format(prefix_miss, release)) + + # respect musicbrainz rate limits + time.sleep(1) + def _missing(self, album): """Query MusicBrainz to determine items missing from `album`. """ From b013abae6bb30710210011503487f4dba300d9a7 Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Sat, 18 Mar 2017 16:15:21 -0400 Subject: [PATCH 1789/2280] beetsplug: cleanup for 'missing -a' code * Use full name for musicbrainzngs import * Use beets internal logging facilities * Match releases by release id * Convert some strings to Unicode * Remove unnecessary MB rate-limiting * Remove unnecessary imports * Follow beets convention for `--album` option * Follow beets convention for imperative docstrings * Simplify method signatures * Use defaultdict(list) where appropriate * Clarify missing MBID log message Signed-off-by: Quentin Young --- beetsplug/missing.py | 76 ++++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 41 deletions(-) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 6afe3b37b..36140d2bf 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -18,12 +18,10 @@ """ from __future__ import division, absolute_import, print_function -import time -import beets -import musicbrainzngs as m -import sys +import musicbrainzngs from musicbrainzngs.musicbrainz import MusicBrainzError +from collections import defaultdict from beets.autotag import hooks from beets.library import Item from beets.plugins import BeetsPlugin @@ -100,7 +98,7 @@ class MissingPlugin(BeetsPlugin): self.config.add({ 'count': False, 'total': False, - 'albums': False, + 'album': False, }) self.album_template_fields['missing'] = _missing_count @@ -115,26 +113,26 @@ class MissingPlugin(BeetsPlugin): u'-t', u'--total', dest='total', action='store_true', help=u'count total of missing tracks') self._command.parser.add_option( - u'-a', u'--albums', dest='albums', action='store_true', + u'-a', u'--album', dest='album', action='store_true', help=u'show missing albums for artist instead of tracks') self._command.parser.add_format_option() def commands(self): def _miss(lib, opts, args): self.config.set_args(opts) - albms = self.config['albums'].get() + albms = self.config['album'].get() helper = self._missing_albums if albms else self._missing_tracks - helper(lib, args) + helper(lib, decargs(args)) self._command.func = _miss return [self._command] - def _missing_tracks(self, lib, args): - """Logic for determining missing tracks from each album in the library - (the usual case) + def _missing_tracks(self, lib, query): + """Print a listing of tracks missing from each album in the library + matching query. """ - albums = lib.albums(decargs(args)) + albums = lib.albums(query) count = self.config['count'].get() total = self.config['total'].get() @@ -157,55 +155,51 @@ class MissingPlugin(BeetsPlugin): for item in self._missing(album): print_(format(item, fmt)) - def _missing_albums(self, lib, args): - """Logic for determining missing albums from each artist in the library - (-a case) + def _missing_albums(self, lib, query): + """Print a listing of albums missing from each artist in the library + matching query. """ - albums = lib.albums(decargs(args)) + albums = lib.albums(query) # build dict mapping artist to list of their albums in library - albums_by_artist = {} + albums_by_artist = defaultdict(list) for alb in albums: artist = (alb['albumartist'], alb['mb_albumartistid']) - artistalbs = albums_by_artist.setdefault(artist, []) - artistalbs.append(alb) - albums_by_artist[artist] = artistalbs + albums_by_artist[artist].append(alb) # build dict mapping artist to list of all albums - m.set_useragent('beets', beets.__version__, 'http://beets.io/') - for artist, albums in albums_by_artist.items(): if artist[1] is None or artist[1] == "": - print_(u"[!] No musicbrainz ID for artist {}, skipping." - .format(artist[0]), stream=sys.stderr) + albs_no_mbid = [u"'" + a['album'] + u"'" for a in albums] + self._log.info( + u"No musicbrainz ID for artist '{}' found in album(s) {}; " + "skipping", artist[0], u", ".join(albs_no_mbid) + ) continue try: - releases = m.browse_releases(artist=artist[1])['release-list'] + resp = musicbrainzngs.browse_release_groups(artist=artist[1]) + release_groups = resp['release-group-list'] except MusicBrainzError as err: - print_(u"[!] Couldn't fetch info for artist '{}' ({}) - '{}'" - .format(artist[0], artist[1], err), stream=sys.stderr) + self._log.info( + u"Couldn't fetch info for artist '{}' ({}) - '{}'", + artist[0], artist[1], err + ) continue missing = [] present = [] - for release in releases: - missing.append(release) + for rg in release_groups: + missing.append(rg) for alb in albums: - # compare by title, don't care about specific releases - if alb['album'].lower() == release['title'].lower(): - missing.remove(release) - present.append(release) + if alb['mb_releasegroupid'] == rg['id']: + missing.remove(rg) + present.append(rg) break - missing_titles = {release['title'] for release in missing} + missing_titles = {rg['title'] for rg in missing} - prefix_miss = "{} - ".format(artist[0]) - - for release in missing_titles: - print_(u"{}{}".format(prefix_miss, release)) - - # respect musicbrainz rate limits - time.sleep(1) + for release_title in missing_titles: + print_(u"{} - {}".format(artist[0], release_title)) def _missing(self, album): """Query MusicBrainz to determine items missing from `album`. From d82ef105329e440be664178ffc10511c65fa3fec Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Sat, 18 Mar 2017 17:11:46 -0400 Subject: [PATCH 1790/2280] docs: add documentation for `missing -a` Signed-off-by: Quentin Young --- docs/plugins/missing.rst | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/plugins/missing.rst b/docs/plugins/missing.rst index aab04e71b..a37e5d732 100644 --- a/docs/plugins/missing.rst +++ b/docs/plugins/missing.rst @@ -11,7 +11,8 @@ Usage Add the ``missing`` plugin to your configuration (see :ref:`using-plugins`). By default, the ``beet missing`` command lists the names of tracks that your -library is missing from each album. +library is missing from each album. It can also list the names of albums that +your library is missing from each artist. You can customize the output format, count the number of missing tracks per album, or total up the number of missing tracks over your whole library, using command-line switches:: @@ -20,9 +21,12 @@ tracks over your whole library, using command-line switches:: print with custom FORMAT -c, --count count missing tracks per album -t, --total count total of missing tracks + -a, --album show missing albums for artist instead of tracks …or by editing corresponding options. +Note that ``-c`` is ignored when used with ``-a``. + Configuration ------------- @@ -60,6 +64,10 @@ List all missing tracks in your collection:: beet missing +List all missing albums in your collection:: + + beet missing -a + List all missing tracks from 2008:: beet missing year:2008 From bf87cab1d8d48a4c55900b313c599c3e3ac502e3 Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Sat, 18 Mar 2017 19:05:46 -0400 Subject: [PATCH 1791/2280] beetsplug: implement `missing -a -t` Produces a count of missing albums without listing them Signed-off-by: Quentin Young --- beetsplug/missing.py | 11 +++++++++++ docs/plugins/missing.rst | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/beetsplug/missing.py b/beetsplug/missing.py index 36140d2bf..8f0790f2b 100644 --- a/beetsplug/missing.py +++ b/beetsplug/missing.py @@ -159,6 +159,8 @@ class MissingPlugin(BeetsPlugin): """Print a listing of albums missing from each artist in the library matching query. """ + total = self.config['total'].get() + albums = lib.albums(query) # build dict mapping artist to list of their albums in library albums_by_artist = defaultdict(list) @@ -166,6 +168,8 @@ class MissingPlugin(BeetsPlugin): artist = (alb['albumartist'], alb['mb_albumartistid']) albums_by_artist[artist].append(alb) + total_missing = 0 + # build dict mapping artist to list of all albums for artist, albums in albums_by_artist.items(): if artist[1] is None or artist[1] == "": @@ -196,11 +200,18 @@ class MissingPlugin(BeetsPlugin): present.append(rg) break + total_missing += len(missing) + if total: + continue + missing_titles = {rg['title'] for rg in missing} for release_title in missing_titles: print_(u"{} - {}".format(artist[0], release_title)) + if total: + print(total_missing) + def _missing(self, album): """Query MusicBrainz to determine items missing from `album`. """ diff --git a/docs/plugins/missing.rst b/docs/plugins/missing.rst index a37e5d732..38a0d5a08 100644 --- a/docs/plugins/missing.rst +++ b/docs/plugins/missing.rst @@ -20,7 +20,7 @@ tracks over your whole library, using command-line switches:: -f FORMAT, --format=FORMAT print with custom FORMAT -c, --count count missing tracks per album - -t, --total count total of missing tracks + -t, --total count total of missing tracks or albums -a, --album show missing albums for artist instead of tracks …or by editing corresponding options. From bbf54b9d61e0db25ee8d402ccf17cc7f5f42e99e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 18 Mar 2017 19:35:36 -0400 Subject: [PATCH 1792/2280] Changelog for #2481 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2df928eba..cb8999726 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -40,6 +40,8 @@ New features: * :doc:`/plugins/smartplaylist`: Different playlist specifications that generate identically-named playlist files no longer conflict; instead, the resulting lists of tracks are concatenated. :bug:`2468` +* :doc:`/plugins/missing`: A new mode lets you see missing albums from artists + you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` Fixes: From aa847e52ac23da72c6f24a347955695a6e834e1a Mon Sep 17 00:00:00 2001 From: Olivier Biesmans Date: Sun, 19 Mar 2017 20:08:39 +0000 Subject: [PATCH 1793/2280] Add reverse proxy support --- beetsplug/web/__init__.py | 39 ++++++++++++++++++++++++++++++ beetsplug/web/static/beets.js | 6 ++--- beetsplug/web/templates/index.html | 2 +- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index bd4677bd8..e49fde046 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -327,6 +327,7 @@ class WebPlugin(BeetsPlugin): 'host': u'127.0.0.1', 'port': 8337, 'cors': '', + 'reverse_proxy': False, 'include_paths': False, }) @@ -358,9 +359,47 @@ class WebPlugin(BeetsPlugin): r"/*": {"origins": self.config['cors'].get(str)} } CORS(app) + + # Allow serving behind a reverse proxy + if self.config['reverse_proxy']: + app.wsgi_app = ReverseProxied(app.wsgi_app) + # Start the web application. app.run(host=self.config['host'].as_str(), port=self.config['port'].get(int), debug=opts.debug, threaded=True) cmd.func = func return [cmd] + +class ReverseProxied(object): + '''Wrap the application in this middleware and configure the + front-end server to add these headers, to let you quietly bind + this to a URL other than / and to an HTTP scheme that is + different than what is used locally. + + In nginx: + location /myprefix { + proxy_pass http://192.168.0.1:5001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /myprefix; + } + + :param app: the WSGI application + ''' + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + script_name = environ.get('HTTP_X_SCRIPT_NAME', '') + if script_name: + environ['SCRIPT_NAME'] = script_name + path_info = environ['PATH_INFO'] + if path_info.startswith(script_name): + environ['PATH_INFO'] = path_info[len(script_name):] + + scheme = environ.get('HTTP_X_SCHEME', '') + if scheme: + environ['wsgi.url_scheme'] = scheme + return self.app(environ, start_response) diff --git a/beetsplug/web/static/beets.js b/beetsplug/web/static/beets.js index 757f2cdab..ec9aae9b3 100644 --- a/beetsplug/web/static/beets.js +++ b/beetsplug/web/static/beets.js @@ -147,7 +147,7 @@ var BeetsRouter = Backbone.Router.extend({ }, itemQuery: function(query) { var queryURL = query.split(/\s+/).map(encodeURIComponent).join('/'); - $.getJSON('/item/query/' + queryURL, function(data) { + $.getJSON('item/query/' + queryURL, function(data) { var models = _.map( data['results'], function(d) { return new Item(d); } @@ -161,7 +161,7 @@ var router = new BeetsRouter(); // Model. var Item = Backbone.Model.extend({ - urlRoot: '/item' + urlRoot: 'item' }); var Items = Backbone.Collection.extend({ model: Item @@ -264,7 +264,7 @@ var AppView = Backbone.View.extend({ $('#extra-detail').empty().append(extraDetailView.render().el); }, playItem: function(item) { - var url = '/item/' + item.get('id') + '/file'; + var url = 'item/' + item.get('id') + '/file'; $('#player audio').attr('src', url); $('#player audio').get(0).play(); diff --git a/beetsplug/web/templates/index.html b/beetsplug/web/templates/index.html index 7c37c82d6..0fdd46d15 100644 --- a/beetsplug/web/templates/index.html +++ b/beetsplug/web/templates/index.html @@ -82,7 +82,7 @@ <% } %>
File
<% if (lyrics) { %>
Lyrics
From 68fa666644cf7fab24e89b5830f172216253a16e Mon Sep 17 00:00:00 2001 From: Olivier Biesmans Date: Sun, 19 Mar 2017 20:45:26 +0000 Subject: [PATCH 1794/2280] Document the `reverse_proxy' option --- docs/changelog.rst | 2 ++ docs/plugins/web.rst | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index cb8999726..b8f0a59ef 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -42,6 +42,8 @@ New features: resulting lists of tracks are concatenated. :bug:`2468` * :doc:`/plugins/missing`: A new mode lets you see missing albums from artists you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` +* :doc:`plugins/web` : Add new `reverse_proxy` config option to allow serving + the web plugins under a reverse proxy. Fixes: diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 9f1bbcd99..91b5457bf 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,6 +63,8 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. +- **reverse_proxy**: Enable reverse proxy suppport (see :ref:`reverse-proxy`, below). + Default: reverse proxy support is disabled. - **include_paths**: If true, includes paths in item objects. Default: false. @@ -111,6 +113,26 @@ For example:: host: 0.0.0.0 cors: 'http://example.com' +.. _reverse-proxy: +Reverse Proxy support. +______________________ + +When the ``web`` plugin server is running behind a reverse proxy, you may want +the application to appear below some path other than / or let the reverse +proxy terminate TLS connections. This option lets you control this by setting +some HTTP Headers. +When ``reverse_proxy`` is enabled, the ``X-Script-Name`` and ``X-Scheme`` HTTP +headers control the ``SCRIPT_NAME`` and the ``wsgi.url_scheme`` environ keys, +respectively. + +``Nginx`` configuration that serves the web plugin under the /beets directory:: + location /beets { + proxy_pass http://127.0.0.1:8080; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /beets; + } JSON API -------- From 18b3e6a9fd4fbdcfaaf4e407099355f55c0095df Mon Sep 17 00:00:00 2001 From: obiesmans Date: Sun, 19 Mar 2017 22:00:01 +0100 Subject: [PATCH 1795/2280] Update changelog.rst --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b8f0a59ef..47cfddfea 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -42,7 +42,7 @@ New features: resulting lists of tracks are concatenated. :bug:`2468` * :doc:`/plugins/missing`: A new mode lets you see missing albums from artists you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` -* :doc:`plugins/web` : Add new `reverse_proxy` config option to allow serving +* :doc:`/plugins/web` : Add new `reverse_proxy` config option to allow serving the web plugins under a reverse proxy. Fixes: From be85825b6033b15e0fd6ebb5e38c42abc0b95117 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Mar 2017 21:20:14 -0400 Subject: [PATCH 1796/2280] Typo and formatting fixes in docs --- docs/plugins/web.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 91b5457bf..74b3e6f6e 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,7 +63,7 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. -- **reverse_proxy**: Enable reverse proxy suppport (see :ref:`reverse-proxy`, below). +- **reverse_proxy**: Enable reverse proxy support (see :ref:`reverse-proxy`, below). Default: reverse proxy support is disabled. - **include_paths**: If true, includes paths in item objects. Default: false. @@ -114,8 +114,9 @@ For example:: cors: 'http://example.com' .. _reverse-proxy: -Reverse Proxy support. -______________________ + +Reverse Proxy Support +--------------------- When the ``web`` plugin server is running behind a reverse proxy, you may want the application to appear below some path other than / or let the reverse @@ -137,7 +138,6 @@ respectively. JSON API -------- - ``GET /item/`` ++++++++++++++ From 095f596e5c7ed6739a8f63abf595490461c01ba3 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Mar 2017 21:25:18 -0400 Subject: [PATCH 1797/2280] Clarity in the reverse_proxy docs --- docs/plugins/web.rst | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 74b3e6f6e..d726911aa 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -118,15 +118,19 @@ For example:: Reverse Proxy Support --------------------- -When the ``web`` plugin server is running behind a reverse proxy, you may want -the application to appear below some path other than / or let the reverse -proxy terminate TLS connections. This option lets you control this by setting -some HTTP Headers. -When ``reverse_proxy`` is enabled, the ``X-Script-Name`` and ``X-Scheme`` HTTP -headers control the ``SCRIPT_NAME`` and the ``wsgi.url_scheme`` environ keys, -respectively. +When the server is running behind a reverse proxy, you can tell the plugin to +respect forwarded headers. Specifically, this can help when you host the +plugin at a base URL other than the root ``/`` or when you use the proxy to +handle secure connections. Enable the ``reverse_proxy`` configuration option +if you do this. + +Technically, this option lets the proxy provide ``X-Script-Name`` and +``X-Scheme`` HTTP headers to control the plugin's the ``SCRIPT_NAME`` and its +``wsgi.url_scheme`` parameter. + +Here's a sample `Nginx`_ configuration that serves the web plugin under the +/beets directory:: -``Nginx`` configuration that serves the web plugin under the /beets directory:: location /beets { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; @@ -135,6 +139,8 @@ respectively. proxy_set_header X-Script-Name /beets; } +.. _Nginx: https://www.nginx.com + JSON API -------- From 9b383f87f456303824f72d571853068ae8e43f55 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Mar 2017 21:27:00 -0400 Subject: [PATCH 1798/2280] Docs: consistent description of a Boolean option --- docs/plugins/web.rst | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index d726911aa..73a2b9147 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,8 +63,9 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. -- **reverse_proxy**: Enable reverse proxy support (see :ref:`reverse-proxy`, below). - Default: reverse proxy support is disabled. +- **reverse_proxy**: If true, enable reverse proxy support (see + :ref:`reverse-proxy`, below). + Default: false. - **include_paths**: If true, includes paths in item objects. Default: false. From cf384109f0c6f0358c05b4d2a68e2c048ea168a8 Mon Sep 17 00:00:00 2001 From: Olivier Biesmans Date: Sun, 19 Mar 2017 21:16:26 +0000 Subject: [PATCH 1799/2280] Make falke8 happy and reference flask doc for the ReverseProxied class --- beetsplug/web/__init__.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index e49fde046..3c18ebd5d 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -371,10 +371,11 @@ class WebPlugin(BeetsPlugin): cmd.func = func return [cmd] + class ReverseProxied(object): - '''Wrap the application in this middleware and configure the - front-end server to add these headers, to let you quietly bind - this to a URL other than / and to an HTTP scheme that is + '''Wrap the application in this middleware and configure the + front-end server to add these headers, to let you quietly bind + this to a URL other than / and to an HTTP scheme that is different than what is used locally. In nginx: @@ -386,6 +387,8 @@ class ReverseProxied(object): proxy_set_header X-Script-Name /myprefix; } + From: http://flask.pocoo.org/snippets/35/ + :param app: the WSGI application ''' def __init__(self, app): From 7cf7bc5ff6bc980b76e1301a94097ae57b4fc27a Mon Sep 17 00:00:00 2001 From: Jan Solanti Date: Mon, 20 Mar 2017 22:03:50 +0200 Subject: [PATCH 1800/2280] Change default aac encoder to FFmpeg's native one FFmpeg's native aac encoder was declared stable in 3.0 (Feb 15. 2016). Support for libfaac was removed some time later: http://git.videolan.org/?p=ffmpeg.git;a=commit;h=dc0f711459e0c682bf9f94ba38d26736e90cff45 --- beetsplug/convert.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index dfdf4e310..8af9a62a1 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -109,8 +109,8 @@ class ConvertPlugin(BeetsPlugin): u'format': u'mp3', u'formats': { u'aac': { - u'command': u'ffmpeg -i $source -y -vn -acodec libfaac ' - u'-aq 100 $dest', + u'command': u'ffmpeg -i $source -y -vn -acodec aac ' + u'-aq 1 $dest', u'extension': u'm4a', }, u'alac': { From 91b65ca5ab8ecdc691454c50d2e5ca74857fc79d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 20 Mar 2017 22:19:10 -0400 Subject: [PATCH 1801/2280] Changelog for #2484 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 47cfddfea..3a5272a91 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -77,6 +77,8 @@ Fixes: * On Python 3, the :ref:`terminal_encoding` setting is respected again for output and printing will no longer crash on systems configured with a limited encoding. +* :doc:`/plugins/convert`: The default configuration uses FFmpeg's built-in + AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` 1.4.3 (January 9, 2017) From 920784a42d438677f6799d30a5bf1a2aae521766 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Thu, 23 Mar 2017 22:46:23 +0100 Subject: [PATCH 1802/2280] Play: handle plural in warning output --- beetsplug/play.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/play.py b/beetsplug/play.py index 636d98d46..9e912dbce 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -163,6 +163,9 @@ class PlayPlugin(BeetsPlugin): # Warn user before playing any huge playlists. if warning_threshold and len(selection) > warning_threshold: + if len(selection) > 1: + item_type += 's' + ui.print_(ui.colorize( 'text_warning', u'You are about to queue {0} {1}.'.format( From 47cc9591275589034205a5c7a29a56c32a544e0c Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Sat, 25 Mar 2017 20:47:07 +0100 Subject: [PATCH 1803/2280] Fix import of multidisc releases with subdirectories Don't stop collapsing paths when iterating over subdirectories of already collapsed paths. Fixes #2493 --- beets/importer.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index 690a499ff..675f2f3f2 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1469,6 +1469,16 @@ MULTIDISC_MARKERS = (br'dis[ck]', br'cd') MULTIDISC_PAT_FMT = br'^(.*%s[\W_]*)\d' +def is_subdir_of_any_in_list(path, dirs): + """Returns True if path os a subdirectory of any directory in dirs + (a list). In other case, returns False. + """ + for d in dirs: + if path.startswith(d + b'/'): + return True + return False + + def albums_in_dir(path): """Recursively searches the given directory and returns an iterable of (paths, items) where paths is a list of directories and items is @@ -1490,7 +1500,8 @@ def albums_in_dir(path): if collapse_paths: if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \ (collapse_pat and - collapse_pat.match(os.path.basename(root))): + collapse_pat.match(os.path.basename(root))) or \ + is_subdir_of_any_in_list(root, collapse_paths): # Still collapsing. collapse_paths.append(root) collapse_items += items From 2fbc7f0e70ed458708c8c5b5425d1f35ddf4ee9b Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sun, 26 Mar 2017 13:40:40 +0300 Subject: [PATCH 1804/2280] Added a terminal bell if interaction from the user is required --- beets/ui/commands.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 8a07f6147..029a6d8f3 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -823,6 +823,8 @@ class TerminalImportSession(importer.ImportSession): Returns a list of `PromptChoice`s. """ # Standard, built-in choices. + #Bell ring to alert the user that he has to interfere with the cmd + print('\a') choices = [ PromptChoice(u's', u'Skip', lambda s, t: importer.action.SKIP), From 9446ec7f469e302e4aa4f07fbc787de6910888c6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 26 Mar 2017 17:16:42 -0400 Subject: [PATCH 1805/2280] Flush the stdout buffer after printing a line Pointed out in #2490, this is a regression introduced by #2398. We need to flush the buffer to faithfully emulate the "real" print() function. --- beets/ui/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index df370b52e..29e228497 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -148,6 +148,7 @@ def print_(*strings, **kwargs): if hasattr(sys.stdout, 'buffer'): out = txt.encode(_out_encoding(), 'replace') sys.stdout.buffer.write(out) + sys.stdout.buffer.flush() else: # In our test harnesses (e.g., DummyOut), sys.stdout.buffer # does not exist. We instead just record the text string. From 5128b9567c052850e68a76f941d0bd0ae0d127b6 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Mon, 27 Mar 2017 01:02:18 +0300 Subject: [PATCH 1806/2280] Added bell when user interaction is needed --- beets/ui/commands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 029a6d8f3..9c6683bfe 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -613,6 +613,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, }) if default is None: require = True + # Bell ring when interaction with the user is needed. + print('\a') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': @@ -823,8 +825,6 @@ class TerminalImportSession(importer.ImportSession): Returns a list of `PromptChoice`s. """ # Standard, built-in choices. - #Bell ring to alert the user that he has to interfere with the cmd - print('\a') choices = [ PromptChoice(u's', u'Skip', lambda s, t: importer.action.SKIP), From 28c423b527abf7c14c78c6bf7e3e0e1537da9b66 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Mon, 27 Mar 2017 01:06:30 +0300 Subject: [PATCH 1807/2280] Added bell when user interaction is needed --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 9c6683bfe..a5b50a704 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -613,7 +613,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, }) if default is None: require = True - # Bell ring when interaction with the user is needed. + # Bell ring when user interaction is needed. print('\a') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) From 35810df9852624640cedafa9ebbf3164088ba8c4 Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Mon, 27 Mar 2017 00:20:44 +0200 Subject: [PATCH 1808/2280] Simplify is_subdir_of_any_in_list and the test that uses it Following the comments from sampsyo in #2494 --- beets/importer.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 675f2f3f2..ce9ebc01c 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1473,10 +1473,8 @@ def is_subdir_of_any_in_list(path, dirs): """Returns True if path os a subdirectory of any directory in dirs (a list). In other case, returns False. """ - for d in dirs: - if path.startswith(d + b'/'): - return True - return False + ancestors = ancestry(path) + return any(d in ancestors for d in dirs) def albums_in_dir(path): @@ -1498,10 +1496,9 @@ def albums_in_dir(path): # and add the current directory. If so, just add the directory # and move on to the next directory. If not, stop collapsing. if collapse_paths: - if (not collapse_pat and collapse_paths[0] in ancestry(root)) or \ + if (is_subdir_of_any_in_list(root, collapse_paths)) or \ (collapse_pat and - collapse_pat.match(os.path.basename(root))) or \ - is_subdir_of_any_in_list(root, collapse_paths): + collapse_pat.match(os.path.basename(root))): # Still collapsing. collapse_paths.append(root) collapse_items += items From c605a918c8168650cbc3a9a6c3a92629bce2a8ec Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Mon, 27 Mar 2017 20:49:28 +0300 Subject: [PATCH 1809/2280] Added an if statement that allows the bell ring according to the user's configuration. --- beets/config_default.yaml | 1 + beets/ui/commands.py | 3 ++- docs/reference/config.rst | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 3b0377966..1c6cb8b33 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -25,6 +25,7 @@ import: pretend: false search_ids: [] duplicate_action: ask + bell: yes clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information", "lost+found"] diff --git a/beets/ui/commands.py b/beets/ui/commands.py index a5b50a704..d925be008 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -614,7 +614,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, if default is None: require = True # Bell ring when user interaction is needed. - print('\a') + if config['import']['bell']: + print('\a') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 094462d2f..84e9bc308 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -576,6 +576,14 @@ skipped; "keep" means keep both old and new items; "remove" means remove old item; "ask" means the user should be prompted for the action each time. The default is ``ask``. +.. _bell: + +bell +~~~~~~~~~~~~~~~~ + +Whether the importer ui should ring a bell when user interaction is needed. + +Default: ``yes``. .. _musicbrainz-config: From 218968235ef75177e31fd16105289256c2c64317 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Tue, 28 Mar 2017 01:09:14 +0300 Subject: [PATCH 1810/2280] small changes for the bell issue --- beets/config_default.yaml | 2 +- beets/ui/commands.py | 2 +- docs/reference/config.rst | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 1c6cb8b33..45f13efef 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -25,7 +25,7 @@ import: pretend: false search_ids: [] duplicate_action: ask - bell: yes + bell: no clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information", "lost+found"] diff --git a/beets/ui/commands.py b/beets/ui/commands.py index d925be008..06ab6f0a5 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -615,7 +615,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, require = True # Bell ring when user interaction is needed. if config['import']['bell']: - print('\a') + ui.print_('\a', end='') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 84e9bc308..6a267d0d6 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -581,9 +581,9 @@ The default is ``ask``. bell ~~~~~~~~~~~~~~~~ -Whether the importer ui should ring a bell when user interaction is needed. +Ring the terminal bell to get your attention when the importer needs your input. -Default: ``yes``. +Default: ``no``. .. _musicbrainz-config: From 473566bf42127f594802b84654cb7d7cb3df789b Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Tue, 28 Mar 2017 00:26:24 +0200 Subject: [PATCH 1811/2280] Added changelog entry for #2494 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3a5272a91..99a85d8a1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -79,6 +79,8 @@ Fixes: limited encoding. * :doc:`/plugins/convert`: The default configuration uses FFmpeg's built-in AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` +* Fix import of multidisc releases with subdirectories, which previously + made each disc be imported separately in different releases. :bug:`2493` 1.4.3 (January 9, 2017) From 70ef6e7df8ed2a5d27392459dde326c128295ce2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 27 Mar 2017 23:23:23 -0400 Subject: [PATCH 1812/2280] Fix heading underline length --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 6a267d0d6..7fb7c96c4 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -579,7 +579,7 @@ The default is ``ask``. .. _bell: bell -~~~~~~~~~~~~~~~~ +~~~~ Ring the terminal bell to get your attention when the importer needs your input. From ffdeb1e20317f2003de999ed6c4538c999bf293a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 27 Mar 2017 23:26:22 -0400 Subject: [PATCH 1813/2280] Changelog/thanks for #2495 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3a5272a91..013e57846 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -44,6 +44,9 @@ New features: you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` * :doc:`/plugins/web` : Add new `reverse_proxy` config option to allow serving the web plugins under a reverse proxy. +* A new :ref:`bell` configuration option under the ``import`` section enables + a terminal bell when input is required. Thanks to :user:`SpirosChadoulos`. + :bug:`2366` :bug:`2495` Fixes: From e9b22cfa3b75c716eae9f74398747fcd856777cf Mon Sep 17 00:00:00 2001 From: David Logie Date: Mon, 3 Apr 2017 13:43:42 +0100 Subject: [PATCH 1814/2280] Use preferred countries when selecting a release event. --- beets/autotag/mb.py | 21 ++++++++++++++++++--- docs/changelog.rst | 2 ++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index a6133adb1..3c5ccee77 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -109,6 +109,22 @@ def _preferred_alias(aliases): return matches[0] +def _preferred_release_event(release): + """Given a release, select and return the user's preferred release + event as a tuple of (country, release-date). Falls back to the + default release event if a preferred event is not found. + + """ + countries = config['match']['preferred']['countries'].as_str_seq() + + for event in release.get('release-event-list', {}): + for country in countries: + if country in event['area']['iso-3166-1-code-list']: + return country, event['date'] + + return release.get('country'), release.get('date') + + def _flatten_artist_credit(credit): """Given a list representing an ``artist-credit`` block, flatten the data into a triple of joined artist name strings: canonical, sort, and @@ -301,7 +317,6 @@ def album_info(release): info.artist = config['va_name'].as_str() info.asin = release.get('asin') info.releasegroup_id = release['release-group']['id'] - info.country = release.get('country') info.albumstatus = release.get('status') # Build up the disambiguation string from the release group and release. @@ -318,8 +333,8 @@ def album_info(release): if reltype: info.albumtype = reltype.lower() - # Release dates. - release_date = release.get('date') + # Release events. + info.country, release_date = _preferred_release_event(release) release_group_date = release['release-group'].get('first-release-date') if not release_date: # Fall back if release-specific date is not available. diff --git a/docs/changelog.rst b/docs/changelog.rst index 37c1ef9fb..ddb6ec603 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -47,6 +47,8 @@ New features: * A new :ref:`bell` configuration option under the ``import`` section enables a terminal bell when input is required. Thanks to :user:`SpirosChadoulos`. :bug:`2366` :bug:`2495` +* Importing a release with multiple release events now selects the + event based on your :ref:`preferred` countries. :bug:`2501` Fixes: From 24e171ce3ec21c794a1a56ff5e9897e809b6c717 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 3 Apr 2017 18:17:26 +0200 Subject: [PATCH 1815/2280] Tiny docstring fix --- beets/autotag/mb.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 3c5ccee77..4bee5b5b0 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -111,9 +111,8 @@ def _preferred_alias(aliases): def _preferred_release_event(release): """Given a release, select and return the user's preferred release - event as a tuple of (country, release-date). Falls back to the + event as a tuple of (country, release_date). Fall back to the default release event if a preferred event is not found. - """ countries = config['match']['preferred']['countries'].as_str_seq() From 45bed808d39fae2845ba4addbd71f31be2e485d4 Mon Sep 17 00:00:00 2001 From: David Logie Date: Mon, 3 Apr 2017 19:48:45 +0100 Subject: [PATCH 1816/2280] Don't fail if there are no areas listed in a release event. --- beets/autotag/mb.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 4bee5b5b0..21dd8a715 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -118,8 +118,11 @@ def _preferred_release_event(release): for event in release.get('release-event-list', {}): for country in countries: - if country in event['area']['iso-3166-1-code-list']: - return country, event['date'] + try: + if country in event['area']['iso-3166-1-code-list']: + return country, event['date'] + except KeyError: + pass return release.get('country'), release.get('date') From 1e4378d636e035c293d76cc436083dd9c9fa087e Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Sat, 21 Jan 2017 11:22:49 +0100 Subject: [PATCH 1817/2280] Run python2 or python3 depending on what's used On a system with dependencies installed for python3 but not for python2, we have to make sure python3 is used everywhere since 'python' might be running the python2 interpreter. This helps with some problems in #2400, but doesn't fix the issue completely. --- test/test_convert.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 2a32e51e7..fe74b0b73 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -15,6 +15,7 @@ from __future__ import division, absolute_import, print_function +import sys import re import os.path import unittest @@ -39,7 +40,7 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') - return u"python '{}' $source $dest {}".format(stub, tag) + return u"python{} '{}' $source $dest {}".format(sys.version_info.major, stub, tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From 42b4e54391e362f4dd144d0ed5bd48f1fcca5d97 Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Sun, 22 Jan 2017 11:45:45 +0100 Subject: [PATCH 1818/2280] Use sys.executable instead of composing the executable name Better use sys.executable than using sys.version_info.major and compose the name of the python executable. --- test/test_convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index fe74b0b73..208bcdb7d 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -40,7 +40,7 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') - return u"python{} '{}' $source $dest {}".format(sys.version_info.major, stub, tag) + return u"{} '{}' $source $dest {}".format(sys.executable, stub, tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From 44ddd2e8f5d2af920865fe3f79856e267e8d071a Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Fri, 27 Jan 2017 11:33:37 +0100 Subject: [PATCH 1819/2280] Shell-escape sys.executable sys.executable needs to be shell-escaped on windows. --- test/test_convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 208bcdb7d..237cafdeb 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -40,7 +40,7 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') - return u"{} '{}' $source $dest {}".format(sys.executable, stub, tag) + return u"'{}' '{}' $source $dest {}".format(sys.executable, stub, tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From fa468ce9d1fa1f57b50627db14387f7ad98de28f Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Wed, 22 Mar 2017 19:44:42 +0100 Subject: [PATCH 1820/2280] Properly quote executable and command line parameter Use shlex.quote (on python3) or pipes.quote (on python2) to properly quote the python executable and parameter instead of using single quotes --- test/test_convert.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 237cafdeb..69a23afd7 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -28,6 +28,15 @@ from beets.mediafile import MediaFile from beets import util +def shell_quote(text): + if sys.version_info[0] < 3: + import pipes + return pipes.quote(text) + else: + import shlex + return shlex.quote(text) + + class TestHelper(helper.TestHelper): def tagged_copy_cmd(self, tag): @@ -40,7 +49,7 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') - return u"'{}' '{}' $source $dest {}".format(sys.executable, stub, tag) + return u"{} {} $source $dest {}".format(shell_quote(sys.executable), shell_quote(stub), tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. From 85e0c0dcee70d4983973485e0fe29f417aea3069 Mon Sep 17 00:00:00 2001 From: Antonio Larrosa Date: Thu, 23 Mar 2017 20:19:50 +0100 Subject: [PATCH 1821/2280] Fixed E501 and E305 PEP8 errors --- test/test_convert.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_convert.py b/test/test_convert.py index 69a23afd7..aa0cd0a34 100644 --- a/test/test_convert.py +++ b/test/test_convert.py @@ -49,7 +49,8 @@ class TestHelper(helper.TestHelper): # A Python script that copies the file and appends a tag. stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') - return u"{} {} $source $dest {}".format(shell_quote(sys.executable), shell_quote(stub), tag) + return u"{} {} $source $dest {}".format(shell_quote(sys.executable), + shell_quote(stub), tag) def assertFileTag(self, path, tag): # noqa """Assert that the path is a file and the files content ends with `tag`. @@ -283,5 +284,6 @@ class NeverConvertLossyFilesTest(unittest.TestCase, TestHelper, def suite(): return unittest.TestLoader().loadTestsFromName(__name__) + if __name__ == '__main__': unittest.main(defaultTest='suite') From 11e3a5a923dfa878af6147cdd758aa38ac3328d5 Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Wed, 12 Apr 2017 00:38:58 +0300 Subject: [PATCH 1822/2280] OperationalError from SQlite that indicates a permissions problem on database file. --- beets/ui/__init__.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 29e228497..d208aa692 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1159,10 +1159,13 @@ def _open_library(config): ) lib.get_item(0) # Test database connection. except (sqlite3.OperationalError, sqlite3.DatabaseError): + message = "" log.debug(u'{}', traceback.format_exc()) - raise UserError(u"database file {0} could not be opened".format( + if e.args[0] == "unable to open database file": + message = "It might be a permissions problem." + raise UserError(u"database file {0} could not be opened.%s".format( util.displayable_path(dbpath) - )) + )%message) log.debug(u'library database: {0}\n' u'library directory: {1}', util.displayable_path(lib.path), From e224621e83d129d69e08029139b9750a624f49df Mon Sep 17 00:00:00 2001 From: Matt Murch Date: Wed, 12 Apr 2017 13:38:03 -0400 Subject: [PATCH 1823/2280] Add default replace for - to _ Also updated changelog and docs. Resolves: #549 --- beets/config_default.yaml | 1 + docs/changelog.rst | 1 + docs/reference/config.rst | 1 + 3 files changed, 3 insertions(+) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 45f13efef..b7e6b1e2b 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -39,6 +39,7 @@ replace: '\.$': _ '\s+$': '' '^\s+': '' + '^-': _ path_sep_replace: _ asciify_paths: false art_filename: cover diff --git a/docs/changelog.rst b/docs/changelog.rst index ddb6ec603..d6d85452c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,6 +52,7 @@ New features: Fixes: +* :doc:`/beets/config_default`: Added default replace for - to _. :bug:`549` * :doc:`/plugins/absubmit`: Do not filter for supported formats. :bug:`2471` * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 7fb7c96c4..82c11238a 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -131,6 +131,7 @@ unexpected behavior on all popular platforms:: '\.$': _ '\s+$': '' '^\s+': '' + '^-': _ These substitutions remove forward and back slashes, leading dots, and control characters—all of which is a good idea on any OS. The fourth line From 6e29514d4c2b9e75d4030088c1ef5db699ae709f Mon Sep 17 00:00:00 2001 From: Matt Murch Date: Wed, 12 Apr 2017 19:04:02 -0400 Subject: [PATCH 1824/2280] Fix Changelog Bug --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index d6d85452c..f153ab410 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,7 +52,7 @@ New features: Fixes: -* :doc:`/beets/config_default`: Added default replace for - to _. :bug:`549` +* :ref:`replace`: Added default replace for - to _. :bug:`549` * :doc:`/plugins/absubmit`: Do not filter for supported formats. :bug:`2471` * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` From 4745c262e238f5da7c28ee1328bf8af41e710a37 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Thu, 13 Apr 2017 12:51:11 +0300 Subject: [PATCH 1825/2280] New export command --- beets/ui/commands.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 06ab6f0a5..1afc7b540 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,7 +1450,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, confirm=False): +def move_items(lib, dest, query, copy, album, pretend, confirm=False, export): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. @@ -1479,17 +1479,20 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False): show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: - if confirm: - objs = ui.input_select_objects( - u'Really %s' % act, objs, - lambda o: show_path_changes( - [(o.path, o.destination(basedir=dest))])) + if export: + util.copy(item.path, item.destination(basedir=dest)) + else: + if confirm: + objs = ui.input_select_objects( + u'Really %s' % act, objs, + lambda o: show_path_changes( + [(o.path, o.destination(basedir=dest))])) - for obj in objs: - log.debug(u'moving: {0}', util.displayable_path(obj.path)) + for obj in objs: + log.debug(u'moving: {0}', util.displayable_path(obj.path)) - obj.move(copy, basedir=dest) - obj.store() + obj.move(copy, basedir=dest) + obj.store() def move_func(lib, opts, args): @@ -1500,7 +1503,7 @@ def move_func(lib, opts, args): raise ui.UserError(u'no such directory: %s' % dest) move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, - opts.timid) + opts.timid, opts.export) move_cmd = ui.Subcommand( @@ -1522,6 +1525,10 @@ move_cmd.parser.add_option( u'-t', u'--timid', dest='timid', action='store_true', help=u'always confirm all actions' ) +move_cmd.parser.add_option( + u'-e', u'--export', default=False, action='store_true', + help=u'copy without changing the database path' +) move_cmd.parser.add_album_option() move_cmd.func = move_func default_commands.append(move_cmd) From 1744ca6e887e54c78b411d8e2584ded3ba2dd688 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 00:40:06 +0100 Subject: [PATCH 1826/2280] raises error when dates passed to query as long numbers --- beets/dbcore/query.py | 2 +- test/test_datequery.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 470ca2ac6..f1d28a7a8 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -561,7 +561,7 @@ class Period(object): date = datetime.strptime(string, date_format) except ValueError: # Parsing failed. - return None + raise InvalidQueryArgumentTypeError(string, datetime) precision = cls.precisions[ordinal] return cls(date, precision) diff --git a/test/test_datequery.py b/test/test_datequery.py index 1e1625db2..0bb1378a3 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -21,7 +21,7 @@ from test import _common from datetime import datetime import unittest import time -from beets.dbcore.query import _parse_periods, DateInterval, DateQuery +from beets.dbcore.query import _parse_periods, DateInterval, DateQuery, InvalidQueryArgumentTypeError def _date(string): @@ -117,7 +117,8 @@ class DateQueryTest(_common.LibTestCase): class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): - DateQuery('added', '1409830085..1412422089') + with self.assertRaises(InvalidQueryArgumentTypeError): + DateQuery('added', '1409830085..1412422089') def test_too_many_components(self): DateQuery('added', '12-34-56-78') From a3251ef7c6d3934eb1b0140f36122eaf59a91a5c Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 01:13:02 +0100 Subject: [PATCH 1827/2280] skips tests for now --- test/test_query.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/test_query.py b/test/test_query.py index 41672ab35..fb8d3ac16 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -890,6 +890,7 @@ class NotQueryTest(DummyDataTestCase): self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) + @unittest.skip # skip until I can figure out what this test is doing def test_type_date(self): q = dbcore.query.DateQuery(u'mtime', u'0.0') not_results = self.lib.items(dbcore.query.NotQuery(q)) @@ -992,7 +993,8 @@ class NotQueryTest(DummyDataTestCase): AttributeError: type object 'NoneQuery' has no attribute 'field' at NoneQuery.match() (due to being @classmethod, and no self?) """ - classes = [(dbcore.query.DateQuery, [u'mtime', u'0.0']), + classes = [#(dbcore.query.DateQuery, [u'mtime', u'0.0']), # skip until I can figure out what this test is doing + # replacing '0.0' with a proper date e.g. '2001-01-01' passes the test (dbcore.query.MatchQuery, [u'artist', u'one']), # (dbcore.query.NoneQuery, ['rg_track_gain']), (dbcore.query.NumericQuery, [u'year', u'2002']), From 3aebb30ad918fdb5d120615828201ce839d85782 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 01:31:46 +0100 Subject: [PATCH 1828/2280] improves the exception details --- beets/dbcore/query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f1d28a7a8..46e7562fd 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -561,7 +561,7 @@ class Period(object): date = datetime.strptime(string, date_format) except ValueError: # Parsing failed. - raise InvalidQueryArgumentTypeError(string, datetime) + raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') precision = cls.precisions[ordinal] return cls(date, precision) From 8e6909bf4b2021e91dba907faa42b0424c49d7bf Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 01:32:18 +0100 Subject: [PATCH 1829/2280] raises error when date string has too many components --- beets/dbcore/query.py | 2 +- test/test_datequery.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 46e7562fd..1169b08d9 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -555,7 +555,7 @@ class Period(object): ordinal = string.count('-') if ordinal >= len(cls.date_formats): # Too many components. - return None + raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') date_format = cls.date_formats[ordinal] try: date = datetime.strptime(string, date_format) diff --git a/test/test_datequery.py b/test/test_datequery.py index 0bb1378a3..7acf192c9 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -121,7 +121,8 @@ class DateQueryConstructTest(unittest.TestCase): DateQuery('added', '1409830085..1412422089') def test_too_many_components(self): - DateQuery('added', '12-34-56-78') + with self.assertRaises(InvalidQueryArgumentTypeError): + DateQuery('added', '12-34-56-78') def suite(): From 1ac38722934d57f49c269c711653ec05369744b6 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 01:40:06 +0100 Subject: [PATCH 1830/2280] updates documentation --- beets/dbcore/query.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 1169b08d9..cf0c13792 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -547,8 +547,9 @@ class Period(object): @classmethod def parse(cls, string): - """Parse a date and return a `Period` object or `None` if the - string is empty. + """Parse a date and return a `Period` object, or `None` if the + string is empty, or raise an InvalidQueryArgumentTypeError if + the string could not be parsed to a date. """ if not string: return None From ed0ea1dee5a8beebbbbdc2b04a7393f938164d09 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 01:49:58 +0100 Subject: [PATCH 1831/2280] tests more invalid date queries --- test/test_datequery.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/test_datequery.py b/test/test_datequery.py index 7acf192c9..97550ace0 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -124,6 +124,21 @@ class DateQueryConstructTest(unittest.TestCase): with self.assertRaises(InvalidQueryArgumentTypeError): DateQuery('added', '12-34-56-78') + def test_invalid_date_query(self): + q_list = [ + '2001-01-0a', + '2001-0a', + '200a', + '2001-01-01..2001-01-0a', + '2001-0a..2001-01', + '200a..2002', + '20aa..', + '..2aa' + ] + for q in q_list: + with self.assertRaises(InvalidQueryArgumentTypeError): + DateQuery('added', q) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From ad87d2af9231c4bd735ba477a621fb51b0b263b3 Mon Sep 17 00:00:00 2001 From: MolarAmbiguity Date: Fri, 14 Apr 2017 12:40:32 +1000 Subject: [PATCH 1832/2280] Add info about overlaying configs --- beets/ui/__init__.py | 9 ++++++++- docs/reference/cli.rst | 5 +++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 29e228497..762a21174 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1122,9 +1122,12 @@ def _configure(options): # special handling lets specified plugins get loaded before we # finish parsing the command line. if getattr(options, 'config', None) is not None: + overlay_path = True config_path = options.config del options.config config.set_file(config_path) + else: + overlay_path = False config.set_args(options) # Configure the logger. @@ -1133,9 +1136,13 @@ def _configure(options): else: log.set_global_level(logging.INFO) + if overlay_path: + log.debug(u'overlaying configuration: {0}', + util.displayable_path(config_path)) + config_path = config.user_config_path() if os.path.isfile(config_path): - log.debug(u'user configuration: {0}', + log.debug(u'base user configuration: {0}', util.displayable_path(config_path)) else: log.debug(u'no user configuration found at {0}', diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 403c1e174..7bdb891c3 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -72,7 +72,7 @@ box. To extract `rar` files, install the `rarfile`_ package and the Optional command flags: * By default, the command copies files your the library directory and - updates the ID3 tags on your music. In order to move the files, instead of + updates the ID3 tags on your music. In order to move the files, instead of copying, use the ``-m`` (move) option. If you'd like to leave your music files untouched, try the ``-C`` (don't copy) and ``-W`` (don't write tags) options. You can also disable this behavior by default in the @@ -409,7 +409,8 @@ import ...``. * ``-v``: verbose mode; prints out a deluge of debugging information. Please use this flag when reporting bugs. You can use it twice, as in ``-vv``, to make beets even more verbose. -* ``-c FILE``: read a specified YAML :doc:`configuration file `. +* ``-c FILE``: read a specified YAML :doc:`configuration file `. any +options set in the specified config will override your normal config. Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. From 94b75e8fb4ab9f96156ae00877eef8fb4c83169e Mon Sep 17 00:00:00 2001 From: MolarAmbiguity Date: Fri, 14 Apr 2017 12:57:42 +1000 Subject: [PATCH 1833/2280] Fix bulleted list --- docs/reference/cli.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 7bdb891c3..58ce8c324 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -410,7 +410,7 @@ import ...``. this flag when reporting bugs. You can use it twice, as in ``-vv``, to make beets even more verbose. * ``-c FILE``: read a specified YAML :doc:`configuration file `. any -options set in the specified config will override your normal config. + options set in the specified config will override your normal config. Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. From 3fd04ad642f42439a24c1693c0b90f9c05e86d37 Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Fri, 14 Apr 2017 09:28:13 +0300 Subject: [PATCH 1834/2280] adding AccessFileError as new class error excpetion --- beets/dbcore/db.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 6b0ed8b43..89b7bd17b 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -32,6 +32,10 @@ from beets.dbcore import types from .query import MatchQuery, NullSort, TrueQuery import six +class AccessFileError(Exception): + """UI exception. Commands should throw this in order to display + nonrecoverable errors to the user. + """ class FormattedMapping(collections.Mapping): """A `dict`-like formatted view of a model. @@ -680,8 +684,11 @@ class Transaction(object): """Execute an SQL statement with substitution values and return the row ID of the last affected row. """ - cursor = self.db._connection().execute(statement, subvals) - return cursor.lastrowid + + cursor = self.db._connection().execute(statement, subvals) + raise AccessFileError("unable to open database file. It might be a permissions problem") + return cursor.lastrowid + def script(self, statements): """Execute a string containing multiple SQL statements.""" From bccfcb6b4f8707741ecef510a091305d915d5a8b Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Fri, 14 Apr 2017 09:33:23 +0300 Subject: [PATCH 1835/2280] handlinig AccessFileError in main --- beets/ui/__init__.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index d208aa692..7720c9358 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -41,6 +41,7 @@ from beets import config from beets.util import confit, as_string from beets.autotag import mb from beets.dbcore import query as db_query +from beets.dbcore import db import six # On Windows platforms, use colorama to support "ANSI" terminal colors. @@ -1159,13 +1160,10 @@ def _open_library(config): ) lib.get_item(0) # Test database connection. except (sqlite3.OperationalError, sqlite3.DatabaseError): - message = "" log.debug(u'{}', traceback.format_exc()) - if e.args[0] == "unable to open database file": - message = "It might be a permissions problem." - raise UserError(u"database file {0} could not be opened.%s".format( + raise UserError(u"database file {0} could not be opened".format( util.displayable_path(dbpath) - )%message) + )) log.debug(u'library database: {0}\n' u'library directory: {1}', util.displayable_path(lib.path), @@ -1250,3 +1248,6 @@ def main(args=None): except KeyboardInterrupt: # Silently ignore ^C except in verbose mode. log.debug(u'{}', traceback.format_exc()) + except db.AccessFileError as exc: + log.error(u'{0}',exc) + sys.exit(1) From cb2f47d8d918ed7845cec899515cde48627e4411 Mon Sep 17 00:00:00 2001 From: Mary Koliopoulou Date: Fri, 14 Apr 2017 09:41:24 +0300 Subject: [PATCH 1836/2280] Update db.py --- beets/dbcore/db.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 89b7bd17b..24ee4a1d7 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -685,9 +685,9 @@ class Transaction(object): the row ID of the last affected row. """ - cursor = self.db._connection().execute(statement, subvals) - raise AccessFileError("unable to open database file. It might be a permissions problem") - return cursor.lastrowid + cursor = self.db._connection().execute(statement, subvals) + raise AccessFileError("unable to open database file. It might be a permissions problem") + return cursor.lastrowid def script(self, statements): From 8f3ca12179acec8e855a31badeb3b55290086db6 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Fri, 14 Apr 2017 12:19:16 +0300 Subject: [PATCH 1837/2280] Put export before confirm --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 1afc7b540..b748c12b2 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,7 +1450,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, confirm=False, export): +def move_items(lib, dest, query, copy, album, pretend, export, confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. From ff4c0abcf132ee21e76789613e4a4f5e98a063f5 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 13:04:45 +0100 Subject: [PATCH 1838/2280] =?UTF-8?q?tests=20=E2=80=98added=E2=80=99=20ins?= =?UTF-8?q?tead=20of=20=E2=80=98mtime=E2=80=99=20,=20and=20uses=20a=20corr?= =?UTF-8?q?ect=20date=20format?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/test_query.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/test_query.py b/test/test_query.py index fb8d3ac16..3216c6f12 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -890,11 +890,11 @@ class NotQueryTest(DummyDataTestCase): self.assert_items_matched(not_results, [u'beets 4 eva']) self.assertNegationProperties(q) - @unittest.skip # skip until I can figure out what this test is doing def test_type_date(self): - q = dbcore.query.DateQuery(u'mtime', u'0.0') + q = dbcore.query.DateQuery(u'added', u'2000-01-01') not_results = self.lib.items(dbcore.query.NotQuery(q)) - self.assert_items_matched(not_results, []) + # query date is in the past, thus the 'not' results should contain all items + self.assert_items_matched(not_results, [u'foo bar', u'baz qux', u'beets 4 eva']) self.assertNegationProperties(q) def test_type_false(self): @@ -993,8 +993,7 @@ class NotQueryTest(DummyDataTestCase): AttributeError: type object 'NoneQuery' has no attribute 'field' at NoneQuery.match() (due to being @classmethod, and no self?) """ - classes = [#(dbcore.query.DateQuery, [u'mtime', u'0.0']), # skip until I can figure out what this test is doing - # replacing '0.0' with a proper date e.g. '2001-01-01' passes the test + classes = [(dbcore.query.DateQuery, [u'added', u'2001-01-01']), (dbcore.query.MatchQuery, [u'artist', u'one']), # (dbcore.query.NoneQuery, ['rg_track_gain']), (dbcore.query.NumericQuery, [u'year', u'2002']), From c7801d4cc0e9729b0d741384373c47671203ee2a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 14 Apr 2017 09:31:30 -0400 Subject: [PATCH 1839/2280] Attempted fix for #2515 (convert on Windows) On Python 3, this tries to pass through the Unicode filename representation for paths to the Windows API. --- beetsplug/convert.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 8af9a62a1..ec4d7c62e 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -24,6 +24,7 @@ import tempfile import shlex import six from string import Template +import platform from beets import ui, util, plugins, config from beets.plugins import BeetsPlugin @@ -183,12 +184,22 @@ class ConvertPlugin(BeetsPlugin): if not quiet and not pretend: self._log.info(u'Encoding {0}', util.displayable_path(source)) - # Substitute $source and $dest in the argument list. + # On Python 3, we need to construct the command to invoke as a + # Unicode string. On Unix, this is a little unfortunate---the OS is + # expecting bytes---so we use surrogate escaping and decode with the + # argument encoding, which is the same encoding that will then be + # *reversed* to recover the same bytes before invoking the OS. On + # Windows, we want to preserve the Unicode filename "as is." if not six.PY2: command = command.decode(util.arg_encoding(), 'surrogateescape') - source = source.decode(util.arg_encoding(), 'surrogateescape') - dest = dest.decode(util.arg_encoding(), 'surrogateescape') + if platform.system() == 'Windows': + source = source.decode(util._fsencoding()) + dest = dest.decode(util._fsencoding()) + else: + source = source.decode(util.arg_encoding(), 'surrogateescape') + dest = dest.decode(util.arg_encoding(), 'surrogateescape') + # Substitute $source and $dest in the argument list. args = shlex.split(command) encode_cmd = [] for i, arg in enumerate(args): From d466f8802c94404a9256ebf55308db83d43fcf42 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 14:45:51 +0100 Subject: [PATCH 1840/2280] passes flake8 --- test/test_datequery.py | 3 ++- test/test_query.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index 97550ace0..e81544aaa 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -21,7 +21,8 @@ from test import _common from datetime import datetime import unittest import time -from beets.dbcore.query import _parse_periods, DateInterval, DateQuery, InvalidQueryArgumentTypeError +from beets.dbcore.query import _parse_periods, DateInterval, DateQuery,\ + InvalidQueryArgumentTypeError def _date(string): diff --git a/test/test_query.py b/test/test_query.py index 3216c6f12..3538c15a8 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -893,8 +893,10 @@ class NotQueryTest(DummyDataTestCase): def test_type_date(self): q = dbcore.query.DateQuery(u'added', u'2000-01-01') not_results = self.lib.items(dbcore.query.NotQuery(q)) - # query date is in the past, thus the 'not' results should contain all items - self.assert_items_matched(not_results, [u'foo bar', u'baz qux', u'beets 4 eva']) + # query date is in the past, thus the 'not' results should contain all + # items + self.assert_items_matched(not_results, [u'foo bar', u'baz qux', + u'beets 4 eva']) self.assertNegationProperties(q) def test_type_false(self): From 6515f9c55a45ff870375bae112624c23201d1373 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 14 Apr 2017 15:25:03 +0100 Subject: [PATCH 1841/2280] changes date validation method to try each format until a match is found --- beets/dbcore/query.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index cf0c13792..1c5c58e53 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -533,8 +533,8 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day') - date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') + precisions = ('day', 'month', 'year') + date_formats = ('%Y-%m-%d', '%Y-%m', '%Y') def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -553,17 +553,19 @@ class Period(object): """ if not string: return None - ordinal = string.count('-') - if ordinal >= len(cls.date_formats): - # Too many components. - raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') - date_format = cls.date_formats[ordinal] - try: - date = datetime.strptime(string, date_format) - except ValueError: - # Parsing failed. - raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') - precision = cls.precisions[ordinal] + count = 0 + date = None + for date_format in cls.date_formats: + try: + date = datetime.strptime(string, date_format) + break + except ValueError: + # Parsing failed. + count += 1 + if date is None: + raise InvalidQueryArgumentTypeError(string, + 'a valid datetime string') + precision = cls.precisions[count] return cls(date, precision) def open_right_endpoint(self): From cf744eb1f7519ba75f3b85d6abc45e188f2a5f91 Mon Sep 17 00:00:00 2001 From: Mary Koliopoulou Date: Fri, 14 Apr 2017 19:42:23 +0300 Subject: [PATCH 1842/2280] Update db.py --- beets/dbcore/db.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 24ee4a1d7..df42ab05f 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -684,17 +684,17 @@ class Transaction(object): """Execute an SQL statement with substitution values and return the row ID of the last affected row. """ - - cursor = self.db._connection().execute(statement, subvals) - raise AccessFileError("unable to open database file. It might be a permissions problem") - return cursor.lastrowid + try: + cursor = self.db._connection().execute(statement, subvals) + return cursor.lastrowid + except sqlite3.OperationalError as e: + raise AccessFileError("unable to open database file. It might be a permissions problem") def script(self, statements): """Execute a string containing multiple SQL statements.""" self.db._connection().executescript(statements) - class Database(object): """A container for Model objects that wraps an SQLite database as the backend. From d4413a2bc4e028034a2886d5cda8b432f7bcf0d5 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sat, 15 Apr 2017 00:54:09 +0300 Subject: [PATCH 1843/2280] obj instead of item --- beets/ui/commands.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index b748c12b2..eec478ea6 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1480,7 +1480,8 @@ def move_items(lib, dest, query, copy, album, pretend, export, confirm=False): for obj in objs]) else: if export: - util.copy(item.path, item.destination(basedir=dest)) + for obj in objs: + util.copy(obj.path, obj.destination(basedir=dest)) else: if confirm: objs = ui.input_select_objects( From a526eb7222826fbdb15b0d3288de7b73ec8a0853 Mon Sep 17 00:00:00 2001 From: MolarAmbiguity Date: Sat, 15 Apr 2017 09:23:35 +1000 Subject: [PATCH 1844/2280] Implement feedback from sampsyo --- beets/ui/__init__.py | 11 +++++------ docs/reference/cli.rst | 7 +++++-- testconfig.yaml | 10 ++++++++++ 3 files changed, 20 insertions(+), 8 deletions(-) create mode 100644 testconfig.yaml diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 762a21174..75bce9e7a 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1122,12 +1122,11 @@ def _configure(options): # special handling lets specified plugins get loaded before we # finish parsing the command line. if getattr(options, 'config', None) is not None: - overlay_path = True - config_path = options.config + overlay_path = options.config del options.config - config.set_file(config_path) + config.set_file(overlay_path) else: - overlay_path = False + overlay_path = None config.set_args(options) # Configure the logger. @@ -1138,11 +1137,11 @@ def _configure(options): if overlay_path: log.debug(u'overlaying configuration: {0}', - util.displayable_path(config_path)) + util.displayable_path(overlay_path)) config_path = config.user_config_path() if os.path.isfile(config_path): - log.debug(u'base user configuration: {0}', + log.debug(u'user configuration: {0}', util.displayable_path(config_path)) else: log.debug(u'no user configuration found at {0}', diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 58ce8c324..37fc31767 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -409,8 +409,11 @@ import ...``. * ``-v``: verbose mode; prints out a deluge of debugging information. Please use this flag when reporting bugs. You can use it twice, as in ``-vv``, to make beets even more verbose. -* ``-c FILE``: read a specified YAML :doc:`configuration file `. any - options set in the specified config will override your normal config. +* ``-c FILE``: read a specified YAML :doc:`configuration file `. This + configuration works as an overlay: rather than replacing your normal + configuration options entirely, the two are merged. Any individual options set + in this config file will override your base configuration. + Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. diff --git a/testconfig.yaml b/testconfig.yaml new file mode 100644 index 000000000..bd864107f --- /dev/null +++ b/testconfig.yaml @@ -0,0 +1,10 @@ +directory: /home/jack/Music/ +library: /home/jack/Music/library.blb +import: + move: yes +paths: + default: $albumartist/$album%aunique{}/$disc-$track $title + singleton: $albumartist/$title + +ui: + color: no From d3664ad5db742a64d19b21d00e05f8e3f1ab598e Mon Sep 17 00:00:00 2001 From: Jakub Wilk Date: Sat, 15 Apr 2017 14:44:19 +0200 Subject: [PATCH 1845/2280] Fix misuse of flags in re.sub() calls The 4th argument of re.sub() is maximum number of substitutions, not flags. --- beetsplug/beatport.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/beatport.py b/beetsplug/beatport.py index 8a73efa16..fc412d998 100644 --- a/beetsplug/beatport.py +++ b/beetsplug/beatport.py @@ -394,10 +394,10 @@ class BeatportPlugin(BeetsPlugin): # cause a query to return no results, even if they match the artist or # album title. Use `re.UNICODE` flag to avoid stripping non-english # word characters. - query = re.sub(r'\W+', ' ', query, re.UNICODE) + query = re.sub(r'\W+', ' ', query, flags=re.UNICODE) # Strip medium information from query, Things like "CD1" and "disk 1" # can also negate an otherwise positive result. - query = re.sub(r'\b(CD|disc)\s*\d+', '', query, re.I) + query = re.sub(r'\b(CD|disc)\s*\d+', '', query, flags=re.I) albums = [self._get_album_info(x) for x in self.client.search(query)] return albums From e709ae6dd58e57c498075cfb5b8752dcb8e5dbf9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 15 Apr 2017 11:13:47 -0400 Subject: [PATCH 1846/2280] Changelog for #2516 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index ddb6ec603..7dbe02314 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -770,6 +770,8 @@ Fixes: does not exist, beets creates an empty file before editing it. This fixes an error on OS X, where the ``open`` command does not work with non-existent files. :bug:`1480` +* :doc:`/plugins/convert`: Fix a problem with filename encoding on Windows + under Python 3. :bug:`2515` :bug:`2516` .. _Python bug: http://bugs.python.org/issue16512 .. _ipfs: http://ipfs.io From fb7296711cd0d7fb6365b1ba5df3089b2eb02024 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 15 Apr 2017 11:27:19 -0400 Subject: [PATCH 1847/2280] Fix Windows encoding in convert stub (#2516) --- test/rsrc/convert_stub.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/test/rsrc/convert_stub.py b/test/rsrc/convert_stub.py index f32bce09a..cb42692d7 100755 --- a/test/rsrc/convert_stub.py +++ b/test/rsrc/convert_stub.py @@ -28,12 +28,9 @@ def convert(in_file, out_file, tag): if not isinstance(tag, bytes): tag = tag.encode('utf-8') - # On Windows, use Unicode paths. (The test harness gives them to us - # as UTF-8 bytes.) - if platform.system() == 'Windows': - if not PY2: - in_file = in_file.encode(arg_encoding()) - out_file = out_file.encode(arg_encoding()) + # On Windows, use Unicode paths. On Python 3, we get the actual, + # Unicode filenames. On Python 2, we get them as UTF-8 byes. + if platform.system() == 'Windows' and PY2: in_file = in_file.decode('utf-8') out_file = out_file.decode('utf-8') From 419d9a066776952d850464b8ead6b49d740098d4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 15 Apr 2017 11:52:09 -0400 Subject: [PATCH 1848/2280] Remove an accidentally-committed config --- testconfig.yaml | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 testconfig.yaml diff --git a/testconfig.yaml b/testconfig.yaml deleted file mode 100644 index bd864107f..000000000 --- a/testconfig.yaml +++ /dev/null @@ -1,10 +0,0 @@ -directory: /home/jack/Music/ -library: /home/jack/Music/library.blb -import: - move: yes -paths: - default: $albumartist/$album%aunique{}/$disc-$track $title - singleton: $albumartist/$title - -ui: - color: no From 8e58a61eb4a5a1fa26371263552d8a3c6bc8ed38 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 15 Apr 2017 15:34:09 -0400 Subject: [PATCH 1849/2280] Remove one blank line --- docs/reference/cli.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 37fc31767..43c217942 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -414,7 +414,6 @@ import ...``. configuration options entirely, the two are merged. Any individual options set in this config file will override your base configuration. - Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. From 346ecbc6d45e14dbe203556ef0d7a7a42a3983e6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 15 Apr 2017 15:43:26 -0400 Subject: [PATCH 1850/2280] Slightly more verbose config overlay description --- docs/reference/cli.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 43c217942..b4c7b9e1b 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -412,7 +412,8 @@ import ...``. * ``-c FILE``: read a specified YAML :doc:`configuration file `. This configuration works as an overlay: rather than replacing your normal configuration options entirely, the two are merged. Any individual options set - in this config file will override your base configuration. + in this config file will override the corresponding settings in your base + configuration. Beets also uses the ``BEETSDIR`` environment variable to look for configuration and data. From f7a58447f0230e83b76f68c5423e20708830ba93 Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Sun, 16 Apr 2017 15:15:45 +0300 Subject: [PATCH 1851/2280] Change the error name to DBAccessError --- beets/ui/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 7720c9358..ecd8f01f1 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1248,6 +1248,6 @@ def main(args=None): except KeyboardInterrupt: # Silently ignore ^C except in verbose mode. log.debug(u'{}', traceback.format_exc()) - except db.AccessFileError as exc: - log.error(u'{0}',exc) + except db.DBAccessError as exc: + log.error(u'{0}', exc) sys.exit(1) From 0492741bf7013219cc4eca9813b4c46859b839f5 Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Sun, 16 Apr 2017 15:18:40 +0300 Subject: [PATCH 1852/2280] Error check with if statemetnt --- beets/dbcore/db.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index df42ab05f..bfc870b38 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -32,11 +32,15 @@ from beets.dbcore import types from .query import MatchQuery, NullSort, TrueQuery import six -class AccessFileError(Exception): - """UI exception. Commands should throw this in order to display - nonrecoverable errors to the user. + +class DBAccessError(Exception): + """The SQLite database became inaccessible. + This can happen when trying to read or write the + database when, for example, the database file is deleted or otherwise disappears. + There is probably no way to recover from this error. """ + class FormattedMapping(collections.Mapping): """A `dict`-like formatted view of a model. @@ -688,13 +692,16 @@ class Transaction(object): cursor = self.db._connection().execute(statement, subvals) return cursor.lastrowid except sqlite3.OperationalError as e: - raise AccessFileError("unable to open database file. It might be a permissions problem") - + if e.args[0] in ('unable to open database file', + 'attempt to write a readonly database file'): + raise DBAccessError("Unable to open database file." \ + "It might be a permissions problem.") def script(self, statements): """Execute a string containing multiple SQL statements.""" self.db._connection().executescript(statements) + class Database(object): """A container for Model objects that wraps an SQLite database as the backend. From a99b7e9e40864d1b7e5b2b6b4d7955e8e7683a28 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sun, 16 Apr 2017 15:53:11 +0300 Subject: [PATCH 1853/2280] Provided default value for export. --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index eec478ea6..befbd1a45 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,7 +1450,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, export, confirm=False): +def move_items(lib, dest, query, copy, album, pretend, export=False, confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. From 512031a0998025e96c83fc4e841354d5e6cbf0c4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Apr 2017 08:57:52 -0400 Subject: [PATCH 1854/2280] Revise changelog for #2509 --- docs/changelog.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5fc981f9e..274f36665 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,7 +52,8 @@ New features: Fixes: -* :ref:`replace`: Added default replace for - to _. :bug:`549` +* In the :ref:`replace` configuration option, we now replace a leading hyphen + (-) with an underscore. :bug:`549` :bug:`2509` * :doc:`/plugins/absubmit`: Do not filter for supported formats. :bug:`2471` * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` From e756f988454a8c3c2a3fbdad76a8592a71aea24a Mon Sep 17 00:00:00 2001 From: Mary011196 Date: Sun, 16 Apr 2017 17:24:48 +0300 Subject: [PATCH 1855/2280] Correcting the mistakes that Travis CI showed me --- beets/dbcore/db.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index bfc870b38..c9f1f72a9 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -36,7 +36,8 @@ import six class DBAccessError(Exception): """The SQLite database became inaccessible. This can happen when trying to read or write the - database when, for example, the database file is deleted or otherwise disappears. + database when, for example, the database file + is deleted or otherwise disappears. There is probably no way to recover from this error. """ @@ -692,10 +693,10 @@ class Transaction(object): cursor = self.db._connection().execute(statement, subvals) return cursor.lastrowid except sqlite3.OperationalError as e: - if e.args[0] in ('unable to open database file', - 'attempt to write a readonly database file'): - raise DBAccessError("Unable to open database file." \ - "It might be a permissions problem.") + if e.args[0] in ("attempt to write a readonly database", + "unable to open database file"): + raise DBAccessError('Unable to open database file.' + 'It might be a permissions problem') def script(self, statements): """Execute a string containing multiple SQL statements.""" From 621427fa636050bfd96b3e388ab24aff8a061c79 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 18 Apr 2017 10:31:09 -0400 Subject: [PATCH 1856/2280] Reformat a docstring --- beets/dbcore/db.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index c9f1f72a9..058b52ff5 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -35,10 +35,10 @@ import six class DBAccessError(Exception): """The SQLite database became inaccessible. - This can happen when trying to read or write the - database when, for example, the database file - is deleted or otherwise disappears. - There is probably no way to recover from this error. + + This can happen when trying to read or write the database when, for + example, the database file is deleted or otherwise disappears. There + is probably no way to recover from this error. """ From 19e09585d8fc43cf59433af5ed8229acccaf8f12 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 18 Apr 2017 10:32:44 -0400 Subject: [PATCH 1857/2280] Re-raise other errors And re-use the SQLite error string instead of a hand-written one for now. --- beets/dbcore/db.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 058b52ff5..ef7231a76 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -693,10 +693,14 @@ class Transaction(object): cursor = self.db._connection().execute(statement, subvals) return cursor.lastrowid except sqlite3.OperationalError as e: + # In two specific cases, SQLite reports an error while accessing + # the underlying database file. We surface these exceptions as + # DBAccessError so the application can abort. if e.args[0] in ("attempt to write a readonly database", "unable to open database file"): - raise DBAccessError('Unable to open database file.' - 'It might be a permissions problem') + raise DBAccessError(e.args[0]) + else: + raise def script(self, statements): """Execute a string containing multiple SQL statements.""" From 906bd97d46f2535c271923ea879f9d1a45f46176 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 18 Apr 2017 17:57:13 -0400 Subject: [PATCH 1858/2280] Hint about database access errors --- beets/ui/__init__.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index ecd8f01f1..39d3d52ac 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1249,5 +1249,9 @@ def main(args=None): # Silently ignore ^C except in verbose mode. log.debug(u'{}', traceback.format_exc()) except db.DBAccessError as exc: - log.error(u'{0}', exc) + log.error( + u'database access error: {0}\n' + u'the library file might have a permissions problem', + exc + ) sys.exit(1) From 7eaaa995668064aad334b75ba16456df9e532556 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 18 Apr 2017 17:59:12 -0400 Subject: [PATCH 1859/2280] Changelog entry for #2508 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 37c1ef9fb..14e0f98fc 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -84,6 +84,8 @@ Fixes: AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` * Fix import of multidisc releases with subdirectories, which previously made each disc be imported separately in different releases. :bug:`2493` +* When the SQLite database stops being accessible, we now print a friendly + error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` 1.4.3 (January 9, 2017) From ffcaf3384548ab95275c5489bb8dbf1631dd0687 Mon Sep 17 00:00:00 2001 From: xarph Date: Tue, 18 Apr 2017 15:30:24 -0700 Subject: [PATCH 1860/2280] add -f argument to play command --- beetsplug/play.py | 7 ++++++- docs/changelog.rst | 3 +++ docs/plugins/play.rst | 3 +++ test/test_play.py | 14 ++++++++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 9e912dbce..409e0c4ab 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -81,6 +81,11 @@ class PlayPlugin(BeetsPlugin): action='store', help=u'add additional arguments to the command', ) + play_command.parser.add_option( + u'-f', u'--force', + action="store_true", + help=u'disable the warning threshold', + ) play_command.func = self._play_command return [play_command] @@ -125,7 +130,7 @@ class PlayPlugin(BeetsPlugin): # Check if the selection exceeds configured threshold. If True, # cancel, otherwise proceed with play command. - if not self._exceeds_threshold(selection, command_str, open_args, + if opts.force or not self._exceeds_threshold(selection, command_str, open_args, item_type): play(command_str, selection, paths, open_args, self._log, item_type) diff --git a/docs/changelog.rst b/docs/changelog.rst index ddb6ec603..cd539d0cf 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -49,6 +49,9 @@ New features: :bug:`2366` :bug:`2495` * Importing a release with multiple release events now selects the event based on your :ref:`preferred` countries. :bug:`2501` +* :doc:`/plugins/play`: A new ``-f`` or ``--force`` parameter lets you skip + the warning message if you enqueue more items than the warning threshold + usually allows. Fixes: diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 9b9110bde..71baa0388 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -95,6 +95,9 @@ example:: indicates that you need to insert extra arguments before specifying the playlist. +The ``--force`` (or ``-f``) flag to the ``play`` command will skip the warning +message if you choose to play more items than the **warning_threshold** value. + Note on the Leakage of the Generated Playlists ---------------------------------------------- diff --git a/test/test_play.py b/test/test_play.py index 86fef99a9..685632b40 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -115,6 +115,20 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_not_called() + def test_force_warning_threshold_bypass(self, open_mock): + self.config['play']['warning_threshold'] = 1 + self.other_item = self.add_item(title='another NiceTitle') + + expected_playlist = u'{0}\n{1}'.format( + self.item.path.decode('utf-8'), + self.other_item.path.decode('utf-8')) + + with control_stdin("a"): + self.run_and_assert( + open_mock, + [u'-f', u'NiceTitle'], + expected_playlist=expected_playlist) + def test_command_failed(self, open_mock): open_mock.side_effect = OSError(u"some reason") From 53618258faec970a0005b640d6811ad0aa04684a Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Wed, 19 Apr 2017 11:31:08 +0300 Subject: [PATCH 1861/2280] added 1 line before for loop --- beets/ui/commands.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index befbd1a45..26ed4836b 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1480,6 +1480,10 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, confirm=Fal for obj in objs]) else: if export: + objs = ui.input_select_objects( + u'Really %s' % act, objs, + lambda o: show_path_changes( + [(o.path, o.destination(basedir=dest))])) for obj in objs: util.copy(obj.path, obj.destination(basedir=dest)) else: From 70183070b2d622278e1d29e542f903ca1a8bd026 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Wed, 19 Apr 2017 12:35:07 +0300 Subject: [PATCH 1862/2280] deleted else --- beets/ui/commands.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 06ab6f0a5..88d9ccaf1 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,7 +1450,7 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, confirm=False): +def move_items(lib, dest, query, copy, album, pretend, export=False, confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. @@ -1479,6 +1479,9 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False): show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: + if export: + for obj in objs: + util.copy(obj.path, obj.destination(basedir=dest)) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, @@ -1500,7 +1503,7 @@ def move_func(lib, opts, args): raise ui.UserError(u'no such directory: %s' % dest) move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, - opts.timid) + opts.timid, opts.export) move_cmd = ui.Subcommand( @@ -1522,6 +1525,10 @@ move_cmd.parser.add_option( u'-t', u'--timid', dest='timid', action='store_true', help=u'always confirm all actions' ) +move_cmd.parser.add_option( + u'-e', u'--export', default=False, action='store_true', + help=u'copy without changing the database path' +) move_cmd.parser.add_album_option() move_cmd.func = move_func default_commands.append(move_cmd) From de57602e3451021a43bece47f1d45b5b7d15bd96 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Wed, 19 Apr 2017 12:54:03 +0300 Subject: [PATCH 1863/2280] fixed certain errors --- beets/ui/commands.py | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 368dd1eb4..88d9ccaf1 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1480,30 +1480,19 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, confirm=Fal for obj in objs]) else: if export: -<<<<<<< HEAD for obj in objs: util.copy(obj.path, obj.destination(basedir=dest)) if confirm: -======= ->>>>>>> 53618258faec970a0005b640d6811ad0aa04684a objs = ui.input_select_objects( u'Really %s' % act, objs, lambda o: show_path_changes( [(o.path, o.destination(basedir=dest))])) - for obj in objs: - util.copy(obj.path, obj.destination(basedir=dest)) - else: - if confirm: - objs = ui.input_select_objects( - u'Really %s' % act, objs, - lambda o: show_path_changes( - [(o.path, o.destination(basedir=dest))])) - for obj in objs: - log.debug(u'moving: {0}', util.displayable_path(obj.path)) + for obj in objs: + log.debug(u'moving: {0}', util.displayable_path(obj.path)) - obj.move(copy, basedir=dest) - obj.store() + obj.move(copy, basedir=dest) + obj.store() def move_func(lib, opts, args): From 60318f1e02a248802a9ccbc2463c783111736ca3 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Wed, 19 Apr 2017 13:07:04 +0300 Subject: [PATCH 1864/2280] fixed line length --- beets/ui/commands.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 88d9ccaf1..36876d229 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,7 +1450,8 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, export=False, confirm=False): +def move_items(lib, dest, query, copy, album, pretend, export=False, + confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. From 18c512893eeb2cb9d734ca1c5b3e4df5fba1a1ba Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 19 Apr 2017 14:10:04 +0100 Subject: [PATCH 1865/2280] more flake8 updates --- beets/dbcore/query.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index cf0c13792..aa8aa4af8 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -556,13 +556,15 @@ class Period(object): ordinal = string.count('-') if ordinal >= len(cls.date_formats): # Too many components. - raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') + raise InvalidQueryArgumentTypeError(string, + 'a valid datetime string') date_format = cls.date_formats[ordinal] try: date = datetime.strptime(string, date_format) except ValueError: # Parsing failed. - raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') + raise InvalidQueryArgumentTypeError(string, + 'a valid datetime string') precision = cls.precisions[ordinal] return cls(date, precision) From 29b57fb5a7c2f5d960f9345475bd1a1cbf8730cb Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 19 Apr 2017 11:36:58 -0400 Subject: [PATCH 1866/2280] Changelog for #2517 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 274f36665..5330869ee 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -88,6 +88,8 @@ Fixes: AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` * Fix import of multidisc releases with subdirectories, which previously made each disc be imported separately in different releases. :bug:`2493` +* Invalid date queries now print an error message instead of being silently + ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` 1.4.3 (January 9, 2017) From 02aa6191c1af4fd39a1d5f31de6ef27ade3aa9f6 Mon Sep 17 00:00:00 2001 From: xarph Date: Wed, 19 Apr 2017 10:51:44 -0700 Subject: [PATCH 1867/2280] rename --force to --yes in play plugin fix some pep8 goo --- beetsplug/play.py | 8 ++++---- docs/changelog.rst | 2 +- docs/plugins/play.rst | 5 +++-- test/test_play.py | 4 ++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 409e0c4ab..8477acbfc 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -82,9 +82,9 @@ class PlayPlugin(BeetsPlugin): help=u'add additional arguments to the command', ) play_command.parser.add_option( - u'-f', u'--force', + u'-y', u'--yes', action="store_true", - help=u'disable the warning threshold', + help=u'skip the warning threshold', ) play_command.func = self._play_command return [play_command] @@ -130,8 +130,8 @@ class PlayPlugin(BeetsPlugin): # Check if the selection exceeds configured threshold. If True, # cancel, otherwise proceed with play command. - if opts.force or not self._exceeds_threshold(selection, command_str, open_args, - item_type): + if opts.yes or not self._exceeds_threshold( + selection, command_str, open_args, item_type): play(command_str, selection, paths, open_args, self._log, item_type) diff --git a/docs/changelog.rst b/docs/changelog.rst index cd539d0cf..7fa0dbcbb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -49,7 +49,7 @@ New features: :bug:`2366` :bug:`2495` * Importing a release with multiple release events now selects the event based on your :ref:`preferred` countries. :bug:`2501` -* :doc:`/plugins/play`: A new ``-f`` or ``--force`` parameter lets you skip +* :doc:`/plugins/play`: A new ``-y`` or ``--yes`` parameter lets you skip the warning message if you enqueue more items than the warning threshold usually allows. diff --git a/docs/plugins/play.rst b/docs/plugins/play.rst index 71baa0388..3a08a4239 100644 --- a/docs/plugins/play.rst +++ b/docs/plugins/play.rst @@ -95,8 +95,9 @@ example:: indicates that you need to insert extra arguments before specifying the playlist. -The ``--force`` (or ``-f``) flag to the ``play`` command will skip the warning -message if you choose to play more items than the **warning_threshold** value. +The ``--yes`` (or ``-y``) flag to the ``play`` command will skip the warning +message if you choose to play more items than the **warning_threshold** +value usually allows. Note on the Leakage of the Generated Playlists ---------------------------------------------- diff --git a/test/test_play.py b/test/test_play.py index 685632b40..9721143cc 100644 --- a/test/test_play.py +++ b/test/test_play.py @@ -115,7 +115,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): open_mock.assert_not_called() - def test_force_warning_threshold_bypass(self, open_mock): + def test_skip_warning_threshold_bypass(self, open_mock): self.config['play']['warning_threshold'] = 1 self.other_item = self.add_item(title='another NiceTitle') @@ -126,7 +126,7 @@ class PlayPluginTest(unittest.TestCase, TestHelper): with control_stdin("a"): self.run_and_assert( open_mock, - [u'-f', u'NiceTitle'], + [u'-y', u'NiceTitle'], expected_playlist=expected_playlist) def test_command_failed(self, open_mock): From 9d42728f7fdb05a00c59df561d3eb67a2dc2cf06 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 19 Apr 2017 19:07:29 -0400 Subject: [PATCH 1868/2280] ftintitle: Clarify control flow Assigning to this variable made it hard to tell what the function was actually returning. --- beetsplug/ftintitle.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index db450d9c8..3b1caffe6 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -49,13 +49,11 @@ def find_feat_part(artist, albumartist): """Attempt to find featured artists in the item's artist fields and return the results. Returns None if no featured artist found. """ - feat_part = None - # Look for the album artist in the artist field. If it's not # present, give up. albumartist_split = artist.split(albumartist, 1) if len(albumartist_split) <= 1: - return feat_part + return None # If the last element of the split (the right-hand side of the # album artist) is nonempty, then it probably contains the @@ -63,15 +61,16 @@ def find_feat_part(artist, albumartist): elif albumartist_split[-1] != '': # Extract the featured artist from the right-hand side. _, feat_part = split_on_feat(albumartist_split[-1]) + return feat_part # Otherwise, if there's nothing on the right-hand side, look for a # featuring artist on the left-hand side. else: lhs, rhs = split_on_feat(albumartist_split[0]) if lhs: - feat_part = lhs + return lhs - return feat_part + return None class FtInTitlePlugin(plugins.BeetsPlugin): From fae8fcc932ffbb22f30d334cbe35d3b0850679b5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 19 Apr 2017 19:08:15 -0400 Subject: [PATCH 1869/2280] ftintitle: Clarify indexing This can only be a two-element array, so just use the index 1. This matches better with the comments, that say "right-hand side" instead of "the last value in the list." --- beetsplug/ftintitle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 3b1caffe6..1060a2dd8 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -58,9 +58,9 @@ def find_feat_part(artist, albumartist): # If the last element of the split (the right-hand side of the # album artist) is nonempty, then it probably contains the # featured artist. - elif albumartist_split[-1] != '': + elif albumartist_split[1] != '': # Extract the featured artist from the right-hand side. - _, feat_part = split_on_feat(albumartist_split[-1]) + _, feat_part = split_on_feat(albumartist_split[1]) return feat_part # Otherwise, if there's nothing on the right-hand side, look for a From 713c00aea75fb14ae00d4a41c4d17d3b79bba062 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 20 Apr 2017 13:20:22 +0100 Subject: [PATCH 1870/2280] reverts order of precisions from broadest to narrowest --- beets/dbcore/query.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 1c5c58e53..0ed5f8935 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -533,8 +533,8 @@ class Period(object): instants of time during January 2014. """ - precisions = ('day', 'month', 'year') - date_formats = ('%Y-%m-%d', '%Y-%m', '%Y') + precisions = ('year', 'month', 'day') + date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and From 85adbd138336826b7250640f369698e099fd4ae1 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 20 Apr 2017 13:36:31 +0100 Subject: [PATCH 1871/2280] =?UTF-8?q?gives=20variable=20the=20better=20nam?= =?UTF-8?q?e=20of=20=E2=80=98ordinal=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beets/dbcore/query.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 0ed5f8935..13aca762d 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -553,7 +553,7 @@ class Period(object): """ if not string: return None - count = 0 + ordinal = 0 date = None for date_format in cls.date_formats: try: @@ -561,11 +561,11 @@ class Period(object): break except ValueError: # Parsing failed. - count += 1 + ordinal += 1 if date is None: raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') - precision = cls.precisions[count] + precision = cls.precisions[ordinal] return cls(date, precision) def open_right_endpoint(self): From 4dbc4134b315650786d5667991e5e0198100eaff Mon Sep 17 00:00:00 2001 From: discopatrick Date: Fri, 21 Apr 2017 12:55:44 +0100 Subject: [PATCH 1872/2280] consolidates the declaration and incrementing of `ordinal` into one line --- beets/dbcore/query.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 13aca762d..8ce4dac41 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -553,15 +553,14 @@ class Period(object): """ if not string: return None - ordinal = 0 date = None - for date_format in cls.date_formats: + for ordinal, date_format in enumerate(cls.date_formats): try: date = datetime.strptime(string, date_format) break except ValueError: # Parsing failed. - ordinal += 1 + pass if date is None: raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') From 7a3c78621514fcd643b967c6f78a554eec0ee72f Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 22 Apr 2017 15:01:31 +0200 Subject: [PATCH 1873/2280] command-output: Wire subproc stdin to /dev/null This should fix 2488, where beet convert would prevent further inputs. --- beets/util/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index f6cd488d6..5db205c02 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -801,6 +801,7 @@ def command_output(cmd, shell=False): cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, close_fds=platform.system() != 'Windows', shell=shell ) From 7a08e4a978e0dcc52bb84d92dcf795c761959f48 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 22 Apr 2017 15:07:28 +0200 Subject: [PATCH 1874/2280] Changelog for 2524 --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index bae5c1e49..5c0d15e0f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -52,6 +52,11 @@ New features: * :doc:`/plugins/play`: A new ``-y`` or ``--yes`` parameter lets you skip the warning message if you enqueue more items than the warning threshold usually allows. +* Fix a bug where commands which forked subprocesses would sometimes prevent + further inputs. This bug mainly affected :doc:`/plugins/convert`. + Thanks to :user:`jansol`. + :bug:`2488` + :bug:`2524` Fixes: From b38f34b2c06255f1c51e8714c8af6962e297a3c5 Mon Sep 17 00:00:00 2001 From: "nath@home" Date: Sat, 22 Apr 2017 15:52:09 +0200 Subject: [PATCH 1875/2280] command_output: insure py2/3 compat This should make #2524 pass --- beets/util/__init__.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 5db205c02..ee06df0bf 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -797,11 +797,16 @@ def command_output(cmd, shell=False): """ cmd = convert_command_args(cmd) + try: # python >= 3.3 + devnull = subprocess.DEVNULL + except AttributeError: + devnull = open(os.devnull, 'r+b') + proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - stdin=subprocess.DEVNULL, + stdin=devnull, close_fds=platform.system() != 'Windows', shell=shell ) From 58417526cb1f871b5a1dcf0a7e03c46cf3064eca Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 20 Apr 2017 14:28:36 +0100 Subject: [PATCH 1876/2280] Rename `InvalidQueryArgumentTypeError` to `InvalidQueryArgumentValueError` The way we use `InvalidQueryArgumentTypeError` is more akin to a `ValueError` than a `TypeError`. For example, we try to parse a string as an int, float, or date, but the parsing fails - there was nothing wrong with the type of the variable (string), but its contents were not parseable into the type we wanted - there was a problem with the value of the string. --- beets/dbcore/query.py | 24 ++++++++++++------------ beets/library.py | 2 +- test/test_datequery.py | 8 ++++---- test/test_query.py | 6 +++--- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index aa8aa4af8..a6040c7d1 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -47,7 +47,7 @@ class InvalidQueryError(ParsingError): super(InvalidQueryError, self).__init__(message) -class InvalidQueryArgumentTypeError(ParsingError): +class InvalidQueryArgumentValueError(ParsingError): """Represent a query argument that could not be converted as expected. It exists to be caught in upper stack levels so a meaningful (i.e. with the @@ -57,7 +57,7 @@ class InvalidQueryArgumentTypeError(ParsingError): message = u"'{0}' is not {1}".format(what, expected) if detail: message = u"{0}: {1}".format(message, detail) - super(InvalidQueryArgumentTypeError, self).__init__(message) + super(InvalidQueryArgumentValueError, self).__init__(message) class Query(object): @@ -211,9 +211,9 @@ class RegexpQuery(StringFieldQuery): self.pattern = re.compile(self.pattern) except re.error as exc: # Invalid regular expression. - raise InvalidQueryArgumentTypeError(pattern, - u"a regular expression", - format(exc)) + raise InvalidQueryArgumentValueError(pattern, + u"a regular expression", + format(exc)) @staticmethod def _normalize(s): @@ -285,7 +285,7 @@ class NumericQuery(FieldQuery): try: return float(s) except ValueError: - raise InvalidQueryArgumentTypeError(s, u"an int or a float") + raise InvalidQueryArgumentValueError(s, u"an int or a float") def __init__(self, field, pattern, fast=True): super(NumericQuery, self).__init__(field, pattern, fast) @@ -548,7 +548,7 @@ class Period(object): @classmethod def parse(cls, string): """Parse a date and return a `Period` object, or `None` if the - string is empty, or raise an InvalidQueryArgumentTypeError if + string is empty, or raise an InvalidQueryArgumentValueError if the string could not be parsed to a date. """ if not string: @@ -556,15 +556,15 @@ class Period(object): ordinal = string.count('-') if ordinal >= len(cls.date_formats): # Too many components. - raise InvalidQueryArgumentTypeError(string, - 'a valid datetime string') + raise InvalidQueryArgumentValueError(string, + 'a valid datetime string') date_format = cls.date_formats[ordinal] try: date = datetime.strptime(string, date_format) except ValueError: # Parsing failed. - raise InvalidQueryArgumentTypeError(string, - 'a valid datetime string') + raise InvalidQueryArgumentValueError(string, + 'a valid datetime string') precision = cls.precisions[ordinal] return cls(date, precision) @@ -686,7 +686,7 @@ class DurationQuery(NumericQuery): try: return float(s) except ValueError: - raise InvalidQueryArgumentTypeError( + raise InvalidQueryArgumentValueError( s, u"a M:SS string or a float") diff --git a/beets/library.py b/beets/library.py index b263ecd64..56fd8f65b 100644 --- a/beets/library.py +++ b/beets/library.py @@ -1306,7 +1306,7 @@ class Library(dbcore.Database): query, parsed_sort = parse_query_string(query, model_cls) elif isinstance(query, (list, tuple)): query, parsed_sort = parse_query_parts(query, model_cls) - except dbcore.query.InvalidQueryArgumentTypeError as exc: + except dbcore.query.InvalidQueryArgumentValueError as exc: raise dbcore.InvalidQueryError(query, exc) # Any non-null sort specified by the parsed query overrides the diff --git a/test/test_datequery.py b/test/test_datequery.py index e81544aaa..8ca5680c6 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -22,7 +22,7 @@ from datetime import datetime import unittest import time from beets.dbcore.query import _parse_periods, DateInterval, DateQuery,\ - InvalidQueryArgumentTypeError + InvalidQueryArgumentValueError def _date(string): @@ -118,11 +118,11 @@ class DateQueryTest(_common.LibTestCase): class DateQueryConstructTest(unittest.TestCase): def test_long_numbers(self): - with self.assertRaises(InvalidQueryArgumentTypeError): + with self.assertRaises(InvalidQueryArgumentValueError): DateQuery('added', '1409830085..1412422089') def test_too_many_components(self): - with self.assertRaises(InvalidQueryArgumentTypeError): + with self.assertRaises(InvalidQueryArgumentValueError): DateQuery('added', '12-34-56-78') def test_invalid_date_query(self): @@ -137,7 +137,7 @@ class DateQueryConstructTest(unittest.TestCase): '..2aa' ] for q in q_list: - with self.assertRaises(InvalidQueryArgumentTypeError): + with self.assertRaises(InvalidQueryArgumentValueError): DateQuery('added', q) diff --git a/test/test_query.py b/test/test_query.py index 3538c15a8..61df3ca10 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -30,7 +30,7 @@ import beets.library from beets import dbcore from beets.dbcore import types from beets.dbcore.query import (NoneQuery, ParsingError, - InvalidQueryArgumentTypeError) + InvalidQueryArgumentValueError) from beets.library import Library, Item from beets import util import platform @@ -301,11 +301,11 @@ class GetTest(DummyDataTestCase): self.assertFalse(results) def test_invalid_query(self): - with self.assertRaises(InvalidQueryArgumentTypeError) as raised: + with self.assertRaises(InvalidQueryArgumentValueError) as raised: dbcore.query.NumericQuery('year', u'199a') self.assertIn(u'not an int', six.text_type(raised.exception)) - with self.assertRaises(InvalidQueryArgumentTypeError) as raised: + with self.assertRaises(InvalidQueryArgumentValueError) as raised: dbcore.query.RegexpQuery('year', u'199(') exception_text = six.text_type(raised.exception) self.assertIn(u'not a regular expression', exception_text) From 63cd799e8d4e7ecb43878562d4ff2007931b6282 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Sat, 22 Apr 2017 00:56:52 +0100 Subject: [PATCH 1877/2280] Raise the correct error type The incorrect error type was reintroduced in the previous merge commit. --- beets/dbcore/query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index c1150c9c4..558a434bc 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -562,7 +562,7 @@ class Period(object): # Parsing failed. pass if date is None: - raise InvalidQueryArgumentTypeError(string, + raise InvalidQueryArgumentValueError(string, 'a valid datetime string') precision = cls.precisions[ordinal] return cls(date, precision) From d24b373c8715d54e12b54334ce062a4b2bc44287 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Sat, 22 Apr 2017 01:11:48 +0100 Subject: [PATCH 1878/2280] Adjust indentation to pass flake8 tests --- beets/dbcore/query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 558a434bc..e532ed419 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -563,7 +563,7 @@ class Period(object): pass if date is None: raise InvalidQueryArgumentValueError(string, - 'a valid datetime string') + 'a valid datetime string') precision = cls.precisions[ordinal] return cls(date, precision) From 95a868bb502be301a89d8f4452089c3a30d09dc2 Mon Sep 17 00:00:00 2001 From: Jakub Wilk Date: Sun, 23 Apr 2017 23:28:32 +0200 Subject: [PATCH 1879/2280] Don't hardcode errno constant The value of ENOENT is architecture-dependent, so don't assume it's always 2. --- beetsplug/absubmit.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index e935324f3..3d21c469c 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -18,6 +18,7 @@ from __future__ import division, absolute_import, print_function +import errno import hashlib import json import os @@ -142,8 +143,8 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): try: os.remove(filename) except OSError as e: - # errno 2 means file does not exist, just ignore this error. - if e.errno != 2: + # ENOENT means file does not exist, just ignore this error. + if e.errno != errno.ENOENT: raise def _submit_data(self, item, data): From 61b832990f522af5581e43d2b9b83988228ef8a4 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Tue, 25 Apr 2017 01:05:46 +0100 Subject: [PATCH 1880/2280] =?UTF-8?q?Add=20a=20date=20query=20precision=20?= =?UTF-8?q?of=20=E2=80=98hour=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beets/dbcore/query.py | 6 ++++-- test/test_datequery.py | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 8ce4dac41..764ed0402 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -533,8 +533,8 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day') - date_formats = ('%Y', '%Y-%m', '%Y-%m-%d') + precisions = ('year', 'month', 'day', 'hour') + date_formats = ('%Y', '%Y-%m', '%Y-%m-%d', '%Y-%m-%dT%H') def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -582,6 +582,8 @@ class Period(object): return date.replace(year=date.year + 1, month=1) elif 'day' == precision: return date + timedelta(days=1) + elif 'hour' == precision: + return date + timedelta(hours=1) else: raise ValueError(u'unhandled precision {0}'.format(precision)) diff --git a/test/test_datequery.py b/test/test_datequery.py index e81544aaa..d670d329b 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -58,6 +58,10 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('1999-12..2000-02', '1999-11-30T23:59:59') self.assertExcludes('1999-12..2000-02', '2000-03-01T00:00:00') + def test_hour_precision_intervals(self): + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T12:30:00') + def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) From 5f2c47ec187eedb1d251e3b7f6b2d3a97c1f47f5 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Tue, 25 Apr 2017 01:16:50 +0100 Subject: [PATCH 1881/2280] Test further hour precision intervals --- test/test_datequery.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/test_datequery.py b/test/test_datequery.py index d670d329b..12ce224c4 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -59,8 +59,20 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('1999-12..2000-02', '2000-03-01T00:00:00') def test_hour_precision_intervals(self): + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T11:59:59') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T12:00:00') self.assertContains('2000-01-01T12..2000-01-01T13', '2000-01-01T12:30:00') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T13:30:00') + self.assertContains('2000-01-01T12..2000-01-01T13', + '2000-01-01T13:59:59') + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T14:00:00') + self.assertExcludes('2000-01-01T12..2000-01-01T13', + '2000-01-01T14:30:00') def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) From ba324df0d1f17e4ffb7de97a580a0fe33610097b Mon Sep 17 00:00:00 2001 From: discopatrick Date: Tue, 25 Apr 2017 01:37:57 +0100 Subject: [PATCH 1882/2280] =?UTF-8?q?Add=20a=20date=20query=20precision=20?= =?UTF-8?q?of=20=E2=80=98minute=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beets/dbcore/query.py | 6 ++++-- test/test_datequery.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 764ed0402..da466a6ba 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -533,8 +533,8 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day', 'hour') - date_formats = ('%Y', '%Y-%m', '%Y-%m-%d', '%Y-%m-%dT%H') + precisions = ('year', 'month', 'day', 'hour', 'minute') + date_formats = ('%Y', '%Y-%m', '%Y-%m-%d', '%Y-%m-%dT%H', '%Y-%m-%dT%H:%M') def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -584,6 +584,8 @@ class Period(object): return date + timedelta(days=1) elif 'hour' == precision: return date + timedelta(hours=1) + elif 'minute' == precision: + return date + timedelta(minutes=1) else: raise ValueError(u'unhandled precision {0}'.format(precision)) diff --git a/test/test_datequery.py b/test/test_datequery.py index 12ce224c4..ea1974c41 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -74,6 +74,18 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12..2000-01-01T13', '2000-01-01T14:30:00') + def test_minute_precision_intervals(self): + self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:29:59') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:30:00') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:30:30') + self.assertContains('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:30:59') + self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', + '2000-01-01T12:31:00') + def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) From b8e1c5675e21a6605c5770ae46f38057b8b54701 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Tue, 25 Apr 2017 02:25:50 +0100 Subject: [PATCH 1883/2280] Fix tests --- test/test_datequery.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index ea1974c41..b1398201c 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -82,9 +82,9 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:30:30') self.assertContains('2000-01-01T12:30..2000-01-01T12:31', - '2000-01-01T12:30:59') + '2000-01-01T12:31:59') self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', - '2000-01-01T12:31:00') + '2000-01-01T12:32:00') def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) From 05f0072363ede939ca023ba6f1ad7ab2afde5105 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 26 Apr 2017 23:46:17 +0100 Subject: [PATCH 1884/2280] Update docstring --- beets/dbcore/query.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index da466a6ba..7b0728408 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -538,7 +538,8 @@ class Period(object): def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and - precision (a string, one of "year", "month", or "day"). + precision (a string, one of "year", "month", "day", "hour", "minute", or + "second"). """ if precision not in Period.precisions: raise ValueError(u'Invalid precision {0}'.format(precision)) From 6a71504545c154cc453b7f24f9b0328a140163fa Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 26 Apr 2017 23:53:51 +0100 Subject: [PATCH 1885/2280] Allow multiple date formats for each precision We want to allow datetime queries to be entered in multiple formats, e.g. with a 'T' or a space separator between date and time. This commit sets up that possibility, albeit with an additional dummy format for the time being. --- beets/dbcore/query.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 7b0728408..3014e73a5 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -534,7 +534,7 @@ class Period(object): """ precisions = ('year', 'month', 'day', 'hour', 'minute') - date_formats = ('%Y', '%Y-%m', '%Y-%m-%d', '%Y-%m-%dT%H', '%Y-%m-%dT%H:%M') + date_formats = (('%Y',), ('%Y-%m',), ('%Y-%m-%d',), ('%Y-%m-%dT%H', 'dummy-format'), ('%Y-%m-%dT%H:%M',)) def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -555,13 +555,19 @@ class Period(object): if not string: return None date = None + found = False for ordinal, date_format in enumerate(cls.date_formats): - try: - date = datetime.strptime(string, date_format) + if found is True: + ordinal -= 1 break - except ValueError: - # Parsing failed. - pass + for format_option in date_format: + try: + date = datetime.strptime(string, format_option) + found = True + break + except ValueError: + # Parsing failed. + pass if date is None: raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') From c3771f722ce08972cd73f7b34f96e075de98ad77 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 00:04:46 +0100 Subject: [PATCH 1886/2280] Allow hour precision queries to use space separator --- beets/dbcore/query.py | 2 +- test/test_datequery.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 3014e73a5..4c109c5b8 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -534,7 +534,7 @@ class Period(object): """ precisions = ('year', 'month', 'day', 'hour', 'minute') - date_formats = (('%Y',), ('%Y-%m',), ('%Y-%m-%d',), ('%Y-%m-%dT%H', 'dummy-format'), ('%Y-%m-%dT%H:%M',)) + date_formats = (('%Y',), ('%Y-%m',), ('%Y-%m-%d',), ('%Y-%m-%dT%H', '%Y-%m-%d %H'), ('%Y-%m-%dT%H:%M',)) def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and diff --git a/test/test_datequery.py b/test/test_datequery.py index b1398201c..743688b4d 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -59,6 +59,7 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('1999-12..2000-02', '2000-03-01T00:00:00') def test_hour_precision_intervals(self): + # test with 'T' separator self.assertExcludes('2000-01-01T12..2000-01-01T13', '2000-01-01T11:59:59') self.assertContains('2000-01-01T12..2000-01-01T13', @@ -74,6 +75,12 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12..2000-01-01T13', '2000-01-01T14:30:00') + # test with ' ' (space) separator + self.assertExcludes('2000-01-01 12..2000-01-01 13', + '2000-01-01T11:59:59') + self.assertContains('2000-01-01 12..2000-01-01 13', + '2000-01-01T12:00:00') + def test_minute_precision_intervals(self): self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:29:59') From 04e2975ee954e0117a7b79628809cc3ea0676ea0 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 26 Apr 2017 23:21:47 +0100 Subject: [PATCH 1887/2280] Separate date formats onto individual lines --- beets/dbcore/query.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 4c109c5b8..949908bc2 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -534,7 +534,13 @@ class Period(object): """ precisions = ('year', 'month', 'day', 'hour', 'minute') - date_formats = (('%Y',), ('%Y-%m',), ('%Y-%m-%d',), ('%Y-%m-%dT%H', '%Y-%m-%d %H'), ('%Y-%m-%dT%H:%M',)) + date_formats = ( + ('%Y',), # year + ('%Y-%m',), # month + ('%Y-%m-%d',), # day + ('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour + ('%Y-%m-%dT%H:%M',) # minute + ) def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and From c10eb8f69dbde91d947b25d16c8596efee06d13a Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 26 Apr 2017 23:23:21 +0100 Subject: [PATCH 1888/2280] Keep docstring line <= 79 characters --- beets/dbcore/query.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 949908bc2..e7001dcb2 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -544,8 +544,8 @@ class Period(object): def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and - precision (a string, one of "year", "month", "day", "hour", "minute", or - "second"). + precision (a string, one of "year", "month", "day", "hour", "minute", + or "second"). """ if precision not in Period.precisions: raise ValueError(u'Invalid precision {0}'.format(precision)) From 02bd19fb328a433165b25d29268f14b7d7f5996d Mon Sep 17 00:00:00 2001 From: discopatrick Date: Wed, 26 Apr 2017 23:33:53 +0100 Subject: [PATCH 1889/2280] Allow minute precision queries to use space separator --- beets/dbcore/query.py | 2 +- test/test_datequery.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index e7001dcb2..f9090e76b 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -539,7 +539,7 @@ class Period(object): ('%Y-%m',), # month ('%Y-%m-%d',), # day ('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour - ('%Y-%m-%dT%H:%M',) # minute + ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M') # minute ) def __init__(self, date, precision): diff --git a/test/test_datequery.py b/test/test_datequery.py index 743688b4d..14156febc 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -93,6 +93,12 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:32:00') + # test with ' ' (space) separator + self.assertExcludes('2000-01-01 12:30..2000-01-01 12:31', + '2000-01-01T12:29:59') + self.assertContains('2000-01-01 12:30..2000-01-01 12:31', + '2000-01-01T12:30:00') + def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) From 24890c77f1fe3228950fb92a943f6266c07ddaaa Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 00:24:17 +0100 Subject: [PATCH 1890/2280] =?UTF-8?q?Add=20a=20date=20query=20precision=20?= =?UTF-8?q?of=20=E2=80=98second=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- beets/dbcore/query.py | 7 +++++-- test/test_datequery.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index f9090e76b..3e6ff270d 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -533,13 +533,14 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day', 'hour', 'minute') + precisions = ('year', 'month', 'day', 'hour', 'minute', 'second') date_formats = ( ('%Y',), # year ('%Y-%m',), # month ('%Y-%m-%d',), # day ('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour - ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M') # minute + ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute + ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second ) def __init__(self, date, precision): @@ -599,6 +600,8 @@ class Period(object): return date + timedelta(hours=1) elif 'minute' == precision: return date + timedelta(minutes=1) + elif 'second' == precision: + return date + timedelta(seconds=1) else: raise ValueError(u'unhandled precision {0}'.format(precision)) diff --git a/test/test_datequery.py b/test/test_datequery.py index 14156febc..99381be19 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -99,6 +99,22 @@ class DateIntervalTest(unittest.TestCase): self.assertContains('2000-01-01 12:30..2000-01-01 12:31', '2000-01-01T12:30:00') + def test_second_precision_intervals(self): + self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:49') + self.assertContains('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:50') + self.assertContains('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:55') + self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', + '2000-01-01T12:30:56') + + # test with ' ' (space) separator + self.assertExcludes('2000-01-01 12:30:50..2000-01-01 12:30:55', + '2000-01-01T12:30:49') + self.assertContains('2000-01-01 12:30:50..2000-01-01 12:30:55', + '2000-01-01T12:30:50') + def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) From 1ab913b200c8510e9f58a2b310819810b16df2c5 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 11:28:10 +0100 Subject: [PATCH 1891/2280] Test each valid datetime separator --- test/test_datequery.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/test_datequery.py b/test/test_datequery.py index 99381be19..c15b08cbd 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -197,6 +197,21 @@ class DateQueryConstructTest(unittest.TestCase): with self.assertRaises(InvalidQueryArgumentTypeError): DateQuery('added', q) + def test_datetime_T_separator(self): + date_query = DateQuery('added', '2000-01-01T12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + + def test_datetime_t_separator(self): + date_query = DateQuery('added', '2000-01-01t12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + + def test_datetime_space_separator(self): + date_query = DateQuery('added', '2000-01-01 12') + self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) + self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 5a3b74f681b0278e11c1d3174f5dac18dcc7806e Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 11:29:45 +0100 Subject: [PATCH 1892/2280] Test an invalid datetime separator raises error --- test/test_datequery.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_datequery.py b/test/test_datequery.py index c15b08cbd..c702c70e5 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -212,6 +212,10 @@ class DateQueryConstructTest(unittest.TestCase): self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) + def test_datetime_invalid_separator(self): + with self.assertRaises(InvalidQueryArgumentTypeError): + DateQuery('added', '2000-01-01x12') + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 6e6dd76513d11c90732d8156b72a9894e793f543 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 11:36:03 +0100 Subject: [PATCH 1893/2280] Remove space separator tests from test_x_precision_intervals tests This is not the correct place for space separator tests. Each test should test one thing only. Space separator tests are now in a separate test case. --- test/test_datequery.py | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index c702c70e5..d2223a8d7 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -75,12 +75,6 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12..2000-01-01T13', '2000-01-01T14:30:00') - # test with ' ' (space) separator - self.assertExcludes('2000-01-01 12..2000-01-01 13', - '2000-01-01T11:59:59') - self.assertContains('2000-01-01 12..2000-01-01 13', - '2000-01-01T12:00:00') - def test_minute_precision_intervals(self): self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:29:59') @@ -93,12 +87,6 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:32:00') - # test with ' ' (space) separator - self.assertExcludes('2000-01-01 12:30..2000-01-01 12:31', - '2000-01-01T12:29:59') - self.assertContains('2000-01-01 12:30..2000-01-01 12:31', - '2000-01-01T12:30:00') - def test_second_precision_intervals(self): self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', '2000-01-01T12:30:49') @@ -109,12 +97,6 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12:30:50..2000-01-01T12:30:55', '2000-01-01T12:30:56') - # test with ' ' (space) separator - self.assertExcludes('2000-01-01 12:30:50..2000-01-01 12:30:55', - '2000-01-01T12:30:49') - self.assertContains('2000-01-01 12:30:50..2000-01-01 12:30:55', - '2000-01-01T12:30:50') - def test_unbounded_endpoints(self): self.assertContains('..', date=datetime.max) self.assertContains('..', date=datetime.min) From 50a2e37a4d8033e6340942f1d59322660eebcd59 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 27 Apr 2017 15:58:08 +0100 Subject: [PATCH 1894/2280] Keep function names lowercase to pass flake8 tests --- test/test_datequery.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index d2223a8d7..b8bb10925 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -179,12 +179,12 @@ class DateQueryConstructTest(unittest.TestCase): with self.assertRaises(InvalidQueryArgumentTypeError): DateQuery('added', q) - def test_datetime_T_separator(self): + def test_datetime_uppercase_t_separator(self): date_query = DateQuery('added', '2000-01-01T12') self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) - def test_datetime_t_separator(self): + def test_datetime_lowercase_t_separator(self): date_query = DateQuery('added', '2000-01-01t12') self.assertEqual(date_query.interval.start, datetime(2000, 1, 1, 12)) self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) From c51ecd46e3b7b97ea87d88ed6c041683cbc14eda Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 12:10:02 +0200 Subject: [PATCH 1895/2280] add composer_sort tag# --- beets/autotag/__init__.py | 6 +++++ beets/autotag/hooks.py | 6 +++-- beets/autotag/mb.py | 4 ++++ beets/library.py | 1 + beets/mediafile.py | 16 +++++++++++++ test/_common.py | 1 + test/test_mediafile.py | 48 ++++++++++++++++++++------------------- 7 files changed, 57 insertions(+), 25 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 822bb60ef..a820535cb 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -49,8 +49,12 @@ def apply_item_metadata(item, track_info): item.lyricist = track_info.lyricist if track_info.composer is not None: item.composer = track_info.composer + if track_info.composer_sort is not None: + item.composer_sort = track_info.composer_sort if track_info.arranger is not None: item.arranger = track_info.arranger + + # At the moment, the other metadata is left intact (including album # and track number). Perhaps these should be emptied? @@ -155,6 +159,8 @@ def apply_metadata(album_info, mapping): item.lyricist = track_info.lyricist if track_info.composer is not None: item.composer = track_info.composer + if track_info.composer_sort is not None: + item.composer_sort = track_info.composer_sort if track_info.arranger is not None: item.arranger = track_info.arranger diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 3c403fcf4..0c3f78ad3 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -144,6 +144,7 @@ class TrackInfo(object): - ``data_url``: The data source release URL. - ``lyricist``: individual track lyricist name - ``composer``: individual track composer name + - ``composer_sort``: individual track composer sort name - ``arranger`: individual track arranger name - ``track_alt``: alternative track number (tape, vinyl, etc.) @@ -155,8 +156,8 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None, lyricist=None, composer=None, arranger=None, - track_alt=None): + media=None, lyricist=None, composer=None, composer_sort=None, + arranger=None, track_alt=None): self.title = title self.track_id = track_id self.artist = artist @@ -174,6 +175,7 @@ class TrackInfo(object): self.data_url = data_url self.lyricist = lyricist self.composer = composer + self.composer_sort = composer_sort self.arranger = arranger self.track_alt = track_alt diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 21dd8a715..e0c217513 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -207,6 +207,7 @@ def track_info(recording, index=None, medium=None, medium_index=None, lyricist = [] composer = [] + composer_sort = [] for work_relation in recording.get('work-relation-list', ()): if work_relation['type'] != 'performance': continue @@ -218,12 +219,15 @@ def track_info(recording, index=None, medium=None, medium_index=None, lyricist.append(artist_relation['artist']['name']) elif type == 'composer': composer.append(artist_relation['artist']['name']) + composer_sort.append(artist_relation['artist']['sort-name']) if lyricist: info.lyricist = u', '.join(lyricist) if composer: info.composer = u', '.join(composer) + info.composer_sort = u', '.join(composer_sort) arranger = [] + arranger_sort = [] for artist_relation in recording.get('artist-relation-list', ()): if 'type' in artist_relation: type = artist_relation['type'] diff --git a/beets/library.py b/beets/library.py index b263ecd64..094a85d6b 100644 --- a/beets/library.py +++ b/beets/library.py @@ -417,6 +417,7 @@ class Item(LibModel): 'genre': types.STRING, 'lyricist': types.STRING, 'composer': types.STRING, + 'composer_sort': types.STRING, 'arranger': types.STRING, 'grouping': types.STRING, 'year': types.PaddedInt(4), diff --git a/beets/mediafile.py b/beets/mediafile.py index 13f1b2dfb..fd94587a8 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1632,12 +1632,28 @@ class MediaFile(object): StorageStyle('LYRICIST'), ASFStorageStyle('WM/Writer'), ) + composer = MediaField( MP3StorageStyle('TCOM'), MP4StorageStyle('\xa9wrt'), StorageStyle('COMPOSER'), ASFStorageStyle('WM/Composer'), ) + + composer_sort = MediaField( + MP3StorageStyle('TSOC'), + MP4StorageStyle('soco'), + StorageStyle('COMPOSERSORT'), + ASFStorageStyle('WM/Composersort'), + ) + + arranger = MediaField( + MP3PeopleStorageStyle('TIPL', involvement='arranger'), + MP4StorageStyle('----:com.apple.iTunes:Arranger'), + StorageStyle('ARRANGER'), + ASFStorageStyle('beets/Arranger'), + ) + arranger = MediaField( MP3PeopleStorageStyle('TIPL', involvement='arranger'), MP4StorageStyle('----:com.apple.iTunes:Arranger'), diff --git a/test/_common.py b/test/_common.py index f3213ec31..221903f68 100644 --- a/test/_common.py +++ b/test/_common.py @@ -68,6 +68,7 @@ def item(lib=None): genre=u'the genre', lyricist=u'the lyricist', composer=u'the composer', + composer_sort=u'the sortname of the composer', arranger=u'the arranger', grouping=u'the grouping', year=1, diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 63df38b8e..f11e060df 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -318,29 +318,30 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, """ full_initial_tags = { - 'title': u'full', - 'artist': u'the artist', - 'album': u'the album', - 'genre': u'the genre', - 'composer': u'the composer', - 'grouping': u'the grouping', - 'year': 2001, - 'month': None, - 'day': None, - 'date': datetime.date(2001, 1, 1), - 'track': 2, - 'tracktotal': 3, - 'disc': 4, - 'disctotal': 5, - 'lyrics': u'the lyrics', - 'comments': u'the comments', - 'bpm': 6, - 'comp': True, - 'mb_trackid': '8b882575-08a5-4452-a7a7-cbb8a1531f9e', - 'mb_albumid': '9e873859-8aa4-4790-b985-5a953e8ef628', - 'mb_artistid': '7cf0ea9d-86b9-4dad-ba9e-2355a64899ea', - 'art': None, - 'label': u'the label', + 'title': u'full', + 'artist': u'the artist', + 'album': u'the album', + 'genre': u'the genre', + 'composer': u'the composer', + 'composer_sort' :u'the sortname of the composer', + 'grouping': u'the grouping', + 'year': 2001, + 'month': None, + 'day': None, + 'date': datetime.date(2001, 1, 1), + 'track': 2, + 'tracktotal': 3, + 'disc': 4, + 'disctotal': 5, + 'lyrics': u'the lyrics', + 'comments': u'the comments', + 'bpm': 6, + 'comp': True, + 'mb_trackid': '8b882575-08a5-4452-a7a7-cbb8a1531f9e', + 'mb_albumid': '9e873859-8aa4-4790-b985-5a953e8ef628', + 'mb_artistid': '7cf0ea9d-86b9-4dad-ba9e-2355a64899ea', + 'art': None, + 'label': u'the label', } tag_fields = [ @@ -350,6 +351,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'genre', 'lyricist', 'composer', + 'composer_sort', 'arranger', 'grouping', 'year', From e3c37981bba0ff3ee8e697188bedd706a4e091e3 Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 12:13:27 +0200 Subject: [PATCH 1896/2280] little indentation stuff --- test/test_mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index f11e060df..aa7d6341e 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -323,7 +323,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'album': u'the album', 'genre': u'the genre', 'composer': u'the composer', - 'composer_sort' :u'the sortname of the composer', + 'composer_sort': u'the sortname of the composer', 'grouping': u'the grouping', 'year': 2001, 'month': None, From 075e2432bfd5b7bbd386b642f128c318054c821a Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 12:15:37 +0200 Subject: [PATCH 1897/2280] deleted one duplicate block --- beets/autotag/mb.py | 1 - beets/mediafile.py | 7 ------- 2 files changed, 8 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index e0c217513..c2172d0ac 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -227,7 +227,6 @@ def track_info(recording, index=None, medium=None, medium_index=None, info.composer_sort = u', '.join(composer_sort) arranger = [] - arranger_sort = [] for artist_relation in recording.get('artist-relation-list', ()): if 'type' in artist_relation: type = artist_relation['type'] diff --git a/beets/mediafile.py b/beets/mediafile.py index fd94587a8..c04cdb67b 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1647,13 +1647,6 @@ class MediaFile(object): ASFStorageStyle('WM/Composersort'), ) - arranger = MediaField( - MP3PeopleStorageStyle('TIPL', involvement='arranger'), - MP4StorageStyle('----:com.apple.iTunes:Arranger'), - StorageStyle('ARRANGER'), - ASFStorageStyle('beets/Arranger'), - ) - arranger = MediaField( MP3PeopleStorageStyle('TIPL', involvement='arranger'), MP4StorageStyle('----:com.apple.iTunes:Arranger'), From 2a418a6350c9266181c715fd0f9dd8077f9fd1c0 Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 12:29:44 +0200 Subject: [PATCH 1898/2280] ASFStorageStyle corrected --- beets/mediafile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index c04cdb67b..e5e7af3ec 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1644,7 +1644,7 @@ class MediaFile(object): MP3StorageStyle('TSOC'), MP4StorageStyle('soco'), StorageStyle('COMPOSERSORT'), - ASFStorageStyle('WM/Composersort'), + ASFStorageStyle('WM/Composersortorder'), ) arranger = MediaField( From d4ff82e46fef897dde4aee6ebe8781f563a6f39c Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 12:45:31 +0200 Subject: [PATCH 1899/2280] adding image stuff for composer_sort --- test/test_mediafile.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index aa7d6341e..179999dc6 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -141,6 +141,12 @@ class ImageStructureTestMixin(ArtTestMixin): type=ImageType.composer) mediafile.images += [image] mediafile.save() + + image = Image(data=self.png_data, desc=u'the sortname of the composer', + type=ImageType.composer_sort) + mediafile.images += [image] + mediafile.save() + mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) @@ -150,6 +156,12 @@ class ImageStructureTestMixin(ArtTestMixin): self.assertExtendedImageAttributes( image, desc=u'the composer', type=ImageType.composer ) + + images = (i for i in mediafile.images if i.desc == u'the sortname of the composer') + image = next(images, None) + self.assertExtendedImageAttributes( + image, desc=u'the sortname of the composer', type=ImageType.composer_sort + ) def test_delete_image_structures(self): mediafile = self._mediafile_fixture('image') @@ -193,6 +205,11 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): type=ImageType.composer) mediafile.images += [image] mediafile.save() + + image = Image(data=self.tiff_data, desc=u'the sortname of the composer', + type=ImageType.composer_sort) + mediafile.images += [image] + mediafile.save() mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) @@ -202,6 +219,11 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): mediafile.images))[0] self.assertExtendedImageAttributes( image, desc=u'the composer', type=ImageType.composer) + + image = list(filter(lambda i: i.mime_type == 'image/tiff', + mediafile.images))[0] + self.assertExtendedImageAttributes( + image, desc=u'the sortname of the composer', type=ImageType.composer_sort) class LazySaveTestMixin(object): From 4a17da8e10c64ad889bfa42a0941ae2c95c29443 Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 13:41:54 +0200 Subject: [PATCH 1900/2280] requested changes: where there is no artist_sort, there is no need for composer_sort; cleaning up whitespaces. --- beets/autotag/__init__.py | 2 -- beets/autotag/hooks.py | 2 +- beets/mediafile.py | 4 ---- test/test_mediafile.py | 24 ------------------------ 4 files changed, 1 insertion(+), 31 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index a820535cb..4c5f09eb4 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -53,8 +53,6 @@ def apply_item_metadata(item, track_info): item.composer_sort = track_info.composer_sort if track_info.arranger is not None: item.arranger = track_info.arranger - - # At the moment, the other metadata is left intact (including album # and track number). Perhaps these should be emptied? diff --git a/beets/autotag/hooks.py b/beets/autotag/hooks.py index 0c3f78ad3..053d050c6 100644 --- a/beets/autotag/hooks.py +++ b/beets/autotag/hooks.py @@ -156,7 +156,7 @@ class TrackInfo(object): length=None, index=None, medium=None, medium_index=None, medium_total=None, artist_sort=None, disctitle=None, artist_credit=None, data_source=None, data_url=None, - media=None, lyricist=None, composer=None, composer_sort=None, + media=None, lyricist=None, composer=None, composer_sort=None, arranger=None, track_alt=None): self.title = title self.track_id = track_id diff --git a/beets/mediafile.py b/beets/mediafile.py index e5e7af3ec..9f37b70d5 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1632,28 +1632,24 @@ class MediaFile(object): StorageStyle('LYRICIST'), ASFStorageStyle('WM/Writer'), ) - composer = MediaField( MP3StorageStyle('TCOM'), MP4StorageStyle('\xa9wrt'), StorageStyle('COMPOSER'), ASFStorageStyle('WM/Composer'), ) - composer_sort = MediaField( MP3StorageStyle('TSOC'), MP4StorageStyle('soco'), StorageStyle('COMPOSERSORT'), ASFStorageStyle('WM/Composersortorder'), ) - arranger = MediaField( MP3PeopleStorageStyle('TIPL', involvement='arranger'), MP4StorageStyle('----:com.apple.iTunes:Arranger'), StorageStyle('ARRANGER'), ASFStorageStyle('beets/Arranger'), ) - grouping = MediaField( MP3StorageStyle('TIT1'), MP4StorageStyle('\xa9grp'), diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 179999dc6..961d3d3bd 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -141,12 +141,6 @@ class ImageStructureTestMixin(ArtTestMixin): type=ImageType.composer) mediafile.images += [image] mediafile.save() - - image = Image(data=self.png_data, desc=u'the sortname of the composer', - type=ImageType.composer_sort) - mediafile.images += [image] - mediafile.save() - mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) @@ -156,12 +150,6 @@ class ImageStructureTestMixin(ArtTestMixin): self.assertExtendedImageAttributes( image, desc=u'the composer', type=ImageType.composer ) - - images = (i for i in mediafile.images if i.desc == u'the sortname of the composer') - image = next(images, None) - self.assertExtendedImageAttributes( - image, desc=u'the sortname of the composer', type=ImageType.composer_sort - ) def test_delete_image_structures(self): mediafile = self._mediafile_fixture('image') @@ -205,11 +193,6 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): type=ImageType.composer) mediafile.images += [image] mediafile.save() - - image = Image(data=self.tiff_data, desc=u'the sortname of the composer', - type=ImageType.composer_sort) - mediafile.images += [image] - mediafile.save() mediafile = MediaFile(mediafile.path) self.assertEqual(len(mediafile.images), 3) @@ -219,11 +202,6 @@ class ExtendedImageStructureTestMixin(ImageStructureTestMixin): mediafile.images))[0] self.assertExtendedImageAttributes( image, desc=u'the composer', type=ImageType.composer) - - image = list(filter(lambda i: i.mime_type == 'image/tiff', - mediafile.images))[0] - self.assertExtendedImageAttributes( - image, desc=u'the sortname of the composer', type=ImageType.composer_sort) class LazySaveTestMixin(object): @@ -345,7 +323,6 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'album': u'the album', 'genre': u'the genre', 'composer': u'the composer', - 'composer_sort': u'the sortname of the composer', 'grouping': u'the grouping', 'year': 2001, 'month': None, @@ -373,7 +350,6 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'genre', 'lyricist', 'composer', - 'composer_sort', 'arranger', 'grouping', 'year', From 23f172d03d838d1119df09927e14d9f13cc14e59 Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 28 Apr 2017 13:49:50 +0200 Subject: [PATCH 1901/2280] if there is no artist_sort, there should not be a composer_sort. --- test/_common.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/_common.py b/test/_common.py index 221903f68..f3213ec31 100644 --- a/test/_common.py +++ b/test/_common.py @@ -68,7 +68,6 @@ def item(lib=None): genre=u'the genre', lyricist=u'the lyricist', composer=u'the composer', - composer_sort=u'the sortname of the composer', arranger=u'the arranger', grouping=u'the grouping', year=1, From ac06be1a5a6c584c18d4e6695657d1ac84b05651 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Tue, 26 Apr 2016 22:32:31 +0100 Subject: [PATCH 1902/2280] Add flake8 check for blind excepts Add flake8 check for blind excepts using flake8-blind-except (B901). --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index 43bff8014..8c3731f5d 100644 --- a/tox.ini +++ b/tox.ini @@ -30,6 +30,7 @@ deps = flake8 flake8-coding flake8-future-import + flake8-blind-except pep8-naming files = beets beetsplug beet test setup.py docs From bb5629ea1d3664594855064e15255b45faa6b13d Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 26 Apr 2016 00:14:35 +0200 Subject: [PATCH 1903/2280] Remove untyped except statements --- beets/mediafile.py | 2 +- beets/plugins.py | 2 +- beets/util/functemplate.py | 2 +- beets/util/pipeline.py | 8 ++++---- beetsplug/duplicates.py | 2 +- beetsplug/thumbnails.py | 4 ---- 6 files changed, 8 insertions(+), 12 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 13f1b2dfb..bd9b11969 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1317,7 +1317,7 @@ class DateField(MediaField): for item in items: try: items_.append(int(item)) - except: + except (TypeError, ValueError): items_.append(None) return items_ diff --git a/beets/plugins.py b/beets/plugins.py index 2ecdb8472..d62f3c011 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -264,7 +264,7 @@ def load_plugins(names=()): and obj != BeetsPlugin and obj not in _classes: _classes.add(obj) - except: + except Exception: log.warning( u'** error loading plugin {}:\n{}', name, diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 51716552c..58b0416a1 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -570,7 +570,7 @@ class Template(object): """ try: res = self.compiled(values, functions) - except: # Handle any exceptions thrown by compiled version. + except Exception: # Handle any exceptions thrown by compiled version. res = self.interpret(values, functions) return res diff --git a/beets/util/pipeline.py b/beets/util/pipeline.py index 367e5d980..39bc7152e 100644 --- a/beets/util/pipeline.py +++ b/beets/util/pipeline.py @@ -270,7 +270,7 @@ class FirstPipelineThread(PipelineThread): return self.out_queue.put(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -318,7 +318,7 @@ class MiddlePipelineThread(PipelineThread): return self.out_queue.put(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -357,7 +357,7 @@ class LastPipelineThread(PipelineThread): # Send to consumer. self.coro.send(msg) - except: + except BaseException: self.abort_all(sys.exc_info()) return @@ -425,7 +425,7 @@ class Pipeline(object): while threads[-1].is_alive(): threads[-1].join(1) - except: + except BaseException: # Stop all the threads immediately. for thread in threads: thread.abort() diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 93d53c58a..2f6bba3e6 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -185,7 +185,7 @@ class DuplicatesPlugin(BeetsPlugin): if tag: try: k, v = tag.split('=') - except: + except Exception: raise UserError( u"{}: can't parse k=v tag: {}".format(PLUGIN, tag) ) diff --git a/beetsplug/thumbnails.py b/beetsplug/thumbnails.py index 838206156..04845e880 100644 --- a/beetsplug/thumbnails.py +++ b/beetsplug/thumbnails.py @@ -274,8 +274,6 @@ class GioURI(URIGetter): try: uri_ptr = self.libgio.g_file_get_uri(g_file_ptr) - except: - raise finally: self.libgio.g_object_unref(g_file_ptr) if not uri_ptr: @@ -285,8 +283,6 @@ class GioURI(URIGetter): try: uri = copy_c_string(uri_ptr) - except: - raise finally: self.libgio.g_free(uri_ptr) From 287e077709c4ef20a6d02126c2a0a13bb908b2b7 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 28 Apr 2016 19:27:02 +0200 Subject: [PATCH 1904/2280] Remove blind excepts from bluelet.py --- beets/util/bluelet.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/util/bluelet.py b/beets/util/bluelet.py index 48dd7bd94..0da17559b 100644 --- a/beets/util/bluelet.py +++ b/beets/util/bluelet.py @@ -269,7 +269,7 @@ def run(root_coro): except StopIteration: # Thread is done. complete_thread(coro, None) - except: + except BaseException: # Thread raised some other exception. del threads[coro] raise ThreadException(coro, sys.exc_info()) @@ -366,7 +366,7 @@ def run(root_coro): exit_te = te break - except: + except BaseException: # For instance, KeyboardInterrupt during select(). Raise # into root thread and terminate others. threads = {root_coro: ExceptionEvent(sys.exc_info())} From f622e42a88c7a5b9c92d29a2e0a587b335462839 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Thu, 28 Apr 2016 23:42:40 +0100 Subject: [PATCH 1905/2280] Replace blind excepts with generic Exception excepts in tests --- test/test_logging.py | 2 +- test/test_mediafile.py | 2 +- test/test_replaygain.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_logging.py b/test/test_logging.py index a6b02a572..826b2447b 100644 --- a/test/test_logging.py +++ b/test/test_logging.py @@ -257,7 +257,7 @@ class ConcurrentEventsTest(TestCase, helper.TestHelper): t2.join(.1) self.assertFalse(t2.is_alive()) - except: + except Exception: print(u"Alive threads:", threading.enumerate()) if dp.lock1.locked(): print(u"Releasing lock1 after exception in test") diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 63df38b8e..820bdb412 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -913,7 +913,7 @@ class AIFFTest(ReadWriteTestBase, unittest.TestCase): # remove this once we require a version that includes the feature. try: import mutagen.dsf # noqa -except: +except ImportError: HAVE_DSF = False else: HAVE_DSF = True diff --git a/test/test_replaygain.py b/test/test_replaygain.py index 6ea21ecb6..6ddee54da 100644 --- a/test/test_replaygain.py +++ b/test/test_replaygain.py @@ -52,14 +52,14 @@ class ReplayGainCliTestBase(TestHelper): try: self.load_plugins('replaygain') - except: + except Exception: import sys # store exception info so an error in teardown does not swallow it exc_info = sys.exc_info() try: self.teardown_beets() self.unload_plugins() - except: + except Exception: # if load_plugins() failed then setup is incomplete and # teardown operations may fail. In particular # {Item,Album} # may not have the _original_types attribute in unload_plugins From 813b078d026f37268e89cd6bb782a2a42e7d32e3 Mon Sep 17 00:00:00 2001 From: dosoe Date: Sat, 29 Apr 2017 18:47:03 +0200 Subject: [PATCH 1906/2280] added composer_sort on test_mediafile.py since there is artist_sort --- test/test_mediafile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 961d3d3bd..580584791 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -350,6 +350,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'genre', 'lyricist', 'composer', + 'composer_sort', 'arranger', 'grouping', 'year', From e9c3d69e5991b8f45c6602dc6e0584522b7b3961 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 29 Apr 2017 18:29:36 -0400 Subject: [PATCH 1907/2280] Fix a typo --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 06ab6f0a5..90896a357 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -84,7 +84,7 @@ def _do_query(lib, query, album, also_items=True): def _print_keys(query): """Given a SQLite query result, print the `key` field of each - returned row, with identation of 2 spaces. + returned row, with indentation of 2 spaces. """ for row in query: print_(u' ' * 2 + row['key']) From dd7b129e217ab39717f662c43fc7a8ea347ffb8c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 29 Apr 2017 18:29:47 -0400 Subject: [PATCH 1908/2280] Turn off unnecessary execute bit --- beets/ui/commands.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 beets/ui/commands.py diff --git a/beets/ui/commands.py b/beets/ui/commands.py old mode 100755 new mode 100644 From 8e78cfdac7cbb4f5bc6a23a40c11295783e88f71 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 29 Apr 2017 21:13:34 -0400 Subject: [PATCH 1909/2280] Always pass unicode to print_ Introduced in #2495. --- beets/ui/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 90896a357..995ff87e9 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -615,7 +615,7 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None, require = True # Bell ring when user interaction is needed. if config['import']['bell']: - ui.print_('\a', end='') + ui.print_(u'\a', end=u'') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': From bab99f546f420d893581003fc5286ac35df70bdc Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sun, 30 Apr 2017 15:02:50 +0300 Subject: [PATCH 1910/2280] Added a test for the new export feature --- test/test_ui.py | 77 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/test/test_ui.py b/test/test_ui.py index c519e66fb..f31e677c3 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -476,6 +476,83 @@ class MoveTest(_common.TestCase): self.i.load() self.assertIn(b'srcfile', self.i.path) +class ExportTest(_common.TestCase): + def setUp(self): + super(MoveTest, self).setUp() + + self.io.install() + + self.libdir = os.path.join(self.temp_dir, b'testlibdir') + os.mkdir(self.libdir) + + self.itempath = os.path.join(self.libdir, b'srcfile') + shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.itempath) + + # Add a file to the library but don't copy it in yet. + self.lib = library.Library(':memory:', self.libdir) + self.i = library.Item.from_path(self.itempath) + self.lib.add(self.i) + self.album = self.lib.add_album([self.i]) + + # Alternate destination directory. + self.otherdir = os.path.join(self.temp_dir, b'testotherdir') + + def _move(self, query=(), dest=None, copy=False, album=False, + pretend=False, export=True): + commands.move_items(self.lib, dest, query, copy, album, pretend, export) + + def test_move_item(self): + self._move() + self.i.load() + self.assertTrue(b'testlibdir' in self.i.path) + self.assertExists(self.i.path) + self.assertNotExists(self.itempath) + + def test_copy_item(self): + self._move(copy=True) + self.i.load() + self.assertTrue(b'testlibdir' in self.i.path) + self.assertExists(self.i.path) + self.assertExists(self.itempath) + + def test_move_album(self): + self._move(album=True) + self.i.load() + self.assertTrue(b'testlibdir' in self.i.path) + self.assertExists(self.i.path) + self.assertNotExists(self.itempath) + + def test_copy_album(self): + self._move(copy=True, album=True) + self.i.load() + self.assertTrue(b'testlibdir' in self.i.path) + self.assertExists(self.i.path) + self.assertExists(self.itempath) + + def test_move_item_custom_dir(self): + self._move(dest=self.otherdir) + self.i.load() + self.assertTrue(b'testotherdir' in self.i.path) + self.assertExists(self.i.path) + self.assertNotExists(self.itempath) + + def test_move_album_custom_dir(self): + self._move(dest=self.otherdir, album=True) + self.i.load() + self.assertTrue(b'testotherdir' in self.i.path) + self.assertExists(self.i.path) + self.assertNotExists(self.itempath) + + def test_pretend_move_item(self): + self._move(dest=self.otherdir, pretend=True) + self.i.load() + self.assertIn(b'srcfile', self.i.path) + + def test_pretend_move_album(self): + self._move(album=True, pretend=True) + self.i.load() + self.assertIn(b'srcfile', self.i.path) + class UpdateTest(_common.TestCase): def setUp(self): From a88192240e0d9ad37424cd74242ce25eb3d3b477 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sun, 30 Apr 2017 15:14:17 +0300 Subject: [PATCH 1911/2280] ExportTest correction --- test/test_ui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_ui.py b/test/test_ui.py index f31e677c3..fd65ab0a6 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -478,7 +478,7 @@ class MoveTest(_common.TestCase): class ExportTest(_common.TestCase): def setUp(self): - super(MoveTest, self).setUp() + super(ExportTest, self).setUp() self.io.install() From 2bf58a61c31ebec6b0dfc0ea212fc22f3da3614b Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Sun, 30 Apr 2017 23:14:23 +0200 Subject: [PATCH 1912/2280] Decode string with Unicode escape --- beetsplug/lyrics.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 6714b2fee..14ca6a4b5 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -21,6 +21,7 @@ from __future__ import absolute_import, division, print_function import difflib import itertools import json +import struct import re import requests import unicodedata @@ -77,6 +78,11 @@ USER_AGENT = 'beets/{}'.format(beets.__version__) # Utilities. +def unichar(i): + try: + return six.unichr(i) + except ValueError: + return struct.pack('i', i).decode('utf-32') def unescape(text): """Resolve &#xxx; HTML entities (and some others).""" @@ -86,7 +92,7 @@ def unescape(text): def replchar(m): num = m.group(1) - return six.unichr(int(num)) + return unichar(int(num)) out = re.sub(u"&#(\d+);", replchar, out) return out From 1c0b79590e53335ee7c82241b6e92d8ab9472f40 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Mon, 1 May 2017 03:05:48 +0100 Subject: [PATCH 1913/2280] Refactor date-finding loop into an inner function This is an attempt to make this code more robust and more readable. --- beets/dbcore/query.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 3e6ff270d..89ee7aef7 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -559,22 +559,21 @@ class Period(object): string is empty, or raise an InvalidQueryArgumentTypeError if the string could not be parsed to a date. """ + + def find_date_and_format(string): + for ord, format in enumerate(cls.date_formats): + for format_option in format: + try: + date = datetime.strptime(string, format_option) + return date, ord + except ValueError: + # Parsing failed. + pass + return (None, None) + if not string: return None - date = None - found = False - for ordinal, date_format in enumerate(cls.date_formats): - if found is True: - ordinal -= 1 - break - for format_option in date_format: - try: - date = datetime.strptime(string, format_option) - found = True - break - except ValueError: - # Parsing failed. - pass + date, ordinal = find_date_and_format(string) if date is None: raise InvalidQueryArgumentTypeError(string, 'a valid datetime string') From a165d6c00bf022345852e20ccc6624fd3d5da04d Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Mon, 1 May 2017 23:40:09 +0200 Subject: [PATCH 1914/2280] Fix MusiXmatch text extraction markers --- beetsplug/lyrics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 14ca6a4b5..ad2d278b5 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -263,8 +263,8 @@ class MusiXmatch(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_between(html, - '"body":', '"language":') + lyrics = extract_text_between(html, '

', + '

') return lyrics.strip(',"').replace('\\n', '\n') From f8862ac0ea8d3a055a5ebfc0abda0c2b28773947 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 00:52:07 +0200 Subject: [PATCH 1915/2280] Sort imports --- test/test_lyrics.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 13ba07fdf..eb9d17dec 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -15,21 +15,25 @@ """Tests for the 'lyrics' plugin.""" -from __future__ import division, absolute_import, print_function +from __future__ import absolute_import, division, print_function import os -import sys import re +import six +import sys import unittest +from mock import patch from test import _common -from mock import MagicMock + +from beets import logging +from beets.library import Item +from beets.util import bytestring_path, confit from beetsplug import lyrics -from beets.library import Item -from beets.util import confit, bytestring_path -from beets import logging -import six + +from mock import MagicMock + log = logging.getLogger('beets.test_lyrics') raw_backend = lyrics.Backend({}, log) From 4e0527f07d5cdfa623216caa21904d74fdd289dd Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 00:54:58 +0200 Subject: [PATCH 1916/2280] Docstrings style --- test/test_lyrics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index eb9d17dec..d8b9e672e 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -42,7 +42,7 @@ google = lyrics.Google(MagicMock(), log) class LyricsPluginTest(unittest.TestCase): def setUp(self): - """Set up configuration""" + """Set up configuration.""" lyrics.LyricsPlugin() def test_search_artist(self): @@ -317,7 +317,7 @@ class LyricsGooglePluginTest(unittest.TestCase): title=u'Beets song', path=u'/lyrics/beetssong') def setUp(self): - """Set up configuration""" + """Set up configuration.""" try: __import__('bs4') except ImportError: From a85dcd88c4898c067982e7a87f7234be99aa9f5d Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 00:56:56 +0200 Subject: [PATCH 1917/2280] Store whole expected lyrics, not just keywords, but randomized --- test/rsrc/lyricstext.yaml | 87 ++++++++++++++++++++++----------------- test/test_lyrics.py | 10 +++-- 2 files changed, 55 insertions(+), 42 deletions(-) diff --git a/test/rsrc/lyricstext.yaml b/test/rsrc/lyricstext.yaml index 814c207df..7ae1a70e7 100644 --- a/test/rsrc/lyricstext.yaml +++ b/test/rsrc/lyricstext.yaml @@ -1,45 +1,56 @@ -Beets_song: - - geeks - - bouquet - - panacea +# Song used by LyricsGooglePluginMachineryTest -Amsterdam: - - oriflammes - - fortune - - batave - - pissent - -Lady_Madonna: - - heaven - - tuesday - - thursday - -Jazz_n_blues: - - parkway - - balance - - impatient - - shoes - -Hey_it_s_ok: - - swear - - forgive - - drink - - found - -City_of_dreams: - - groves - - landmarks - - twilight - - freeways - -Black_magic_woman: - - devil - - magic - - spell - - heart +Beets_song: | + beets is the media library management system for obsessive-compulsive music geeks the purpose of + beets is to get your music collection right once and for all it catalogs your collection + automatically improving its metadata as it goes it then provides a bouquet of tools for + manipulating and accessing your music here's an example of beets' brainy tag corrector doing its + because beets is designed as a library it can do almost anything you can imagine for your + music collection via plugins beets becomes a panacea missing_texts: | Lyricsmania staff is working hard for you to add $TITLE lyrics as soon as they'll be released by $ARTIST, check back soon! In case you have the lyrics to $TITLE and want to send them to us, fill out the following form. + +# Songs lyrics used to test the different sources present in the google custom search engine. +# Text is randomized for copyright infringement reason. + +Amsterdam: | + coup corps coeur invitent mains comme trop morue le hantent mais la dames joli revenir aux + mangent croquer pleine plantent rire de sortent pleins fortune d'amsterdam bruit ruisselants + large poissons braguette leur putains blanches jusque pissent dans soleils dansent et port + bien vertu nez sur chaleur femmes rotant dorment marins boivent bu les que d'un qui je + une cou hambourg plus ils dents ou tournent or berges d'ailleurs tout ciel haubans ce son lueurs + en lune ont mouchent leurs long frottant jusqu'en vous regard montrent langueurs chantent + tordent pleure donnent drames mornes des panse pour un sent encore referment nappes au meurent + geste quand puis alors frites grosses batave expire naissent reboivent oriflammes grave riant a + enfin rance fier y bouffer s'entendre se mieux + +Lady_Madonna: | + feed his money tuesday manage didn't head feet see arrives at in madonna rest morning children + wonder how make thursday your to sunday music papers come tie you has was is listen suitcase + ends friday run that needed breast they child baby mending on lady learned a nun like did wednesday + bed think without afternoon night meet the playing lying + +Jazz_n_blues: | + all shoes money through follow blow til father to his hit jazz kiss now cool bar cause 50 night + heading i'll says yeah cash forgot blues out what for ways away fingers waiting got ever bold + screen sixty throw wait on about last compton days o pick love wall had within jeans jd next + miss standing from it's two long fight extravagant tell today more buy shopping that didn't + what's but russian up can parkway balance my and gone am it as at in check if bags when cross + machine take you drinks coke june wrong coming fancy's i n' impatient so the main's spend + that's + +Hey_it_s_ok: | + and forget be when please it against fighting mama cause ! again what said + things papa hey to much lovers way wet was too do drink and i who forgive + hey fourteen please know not wanted had myself ok friends bed times looked + swear act found the my mean + +Black_magic_woman: | + blind heart sticks just don't into back alone see need yes your out devil make that to black got + you might me woman turning spell stop baby with 'round a on stone messin' magic i of + tricks up leave turn bad so pick she's my can't + diff --git a/test/test_lyrics.py b/test/test_lyrics.py index d8b9e672e..d36499d16 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -221,10 +221,12 @@ class MockFetchUrl(object): def is_lyrics_content_ok(title, text): - """Compare lyrics text to expected lyrics for given title""" - - keywords = LYRICS_TEXTS[google.slugify(title)] - return all(x in text.lower() for x in keywords) + """Compare lyrics text to expected lyrics for given title.""" + if not text: + return + keywords = set(LYRICS_TEXTS[google.slugify(title)].split()) + words = set(x.strip(".?, ") for x in text.lower().split()) + return keywords <= words LYRICS_ROOT_DIR = os.path.join(_common.RSRC, b'lyrics') LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, b'lyricstext.yaml')) From d88cabc8464ab338b143e336afcf03ace2303266 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 01:03:26 +0200 Subject: [PATCH 1918/2280] Divide LyricsGooglePluginTest into two classes. Move existing tests into LyricsGooglePluginMachineryTest. Create LyricsPluginSourcesTest class to check fetching of each source. Some code was supposed to do that until now but was never executed as we exited early at the "if not check_lyrics_fetched():" check. --- test/test_lyrics.py | 227 +++++++++++++++++++------------------------- 1 file changed, 100 insertions(+), 127 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index d36499d16..b6abf8d9e 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -198,15 +198,6 @@ def url_to_filename(url): return fn -def check_lyrics_fetched(): - """Return True if lyrics_download_samples.py has been runned and lyrics - pages are present in resources directory""" - lyrics_dirs = len([d for d in os.listdir(LYRICS_ROOT_DIR) if - os.path.isdir(os.path.join(LYRICS_ROOT_DIR, d))]) - # example.com is the only lyrics dir added to repo - return lyrics_dirs > 1 - - class MockFetchUrl(object): def __init__(self, pathval='fetched_path'): self.pathval = pathval @@ -230,94 +221,9 @@ def is_lyrics_content_ok(title, text): LYRICS_ROOT_DIR = os.path.join(_common.RSRC, b'lyrics') LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, b'lyricstext.yaml')) -DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') - -DEFAULT_SOURCES = [ - dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', - path=u'The_Beatles:Lady_Madonna'), - dict(artist=u'Santana', title=u'Black magic woman', - url='http://www.lyrics.com/', - path=u'black-magic-woman-lyrics-santana.html'), - dict(DEFAULT_SONG, url='https://www.musixmatch.com/', - path=u'lyrics/The-Beatles/Lady-Madonna'), -] - -# Every source entered in default beets google custom search engine -# must be listed below. -# Use default query when possible, or override artist and title fields -# if website don't have lyrics for default query. -GOOGLE_SOURCES = [ - dict(DEFAULT_SONG, - url=u'http://www.absolutelyrics.com', - path=u'/lyrics/view/the_beatles/lady_madonna'), - dict(DEFAULT_SONG, - url=u'http://www.azlyrics.com', - path=u'/lyrics/beatles/ladymadonna.html'), - dict(DEFAULT_SONG, - url=u'http://www.chartlyrics.com', - path=u'/_LsLsZ7P4EK-F-LD4dJgDQ/Lady+Madonna.aspx'), - dict(DEFAULT_SONG, - url=u'http://www.elyricsworld.com', - path=u'/lady_madonna_lyrics_beatles.html'), - dict(url=u'http://www.lacoccinelle.net', - artist=u'Jacques Brel', title=u"Amsterdam", - path=u'/paroles-officielles/275679.html'), - dict(DEFAULT_SONG, - url=u'http://letras.mus.br/', path=u'the-beatles/275/'), - dict(DEFAULT_SONG, - url='http://www.lyricsmania.com/', - path='lady_madonna_lyrics_the_beatles.html'), - dict(artist=u'Santana', title=u'Black magic woman', - url='http://www.lyrics.com/', - path=u'black-magic-woman-lyrics-santana.html'), - dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', - path=u'The_Beatles:Lady_Madonna'), - dict(DEFAULT_SONG, - url=u'http://www.lyrics.net', path=u'/lyric/19110224'), - dict(DEFAULT_SONG, - url=u'http://www.lyricsmode.com', - path=u'/lyrics/b/beatles/lady_madonna.html'), - dict(url=u'http://www.lyricsontop.com', - artist=u'Amy Winehouse', title=u"Jazz'n'blues", - path=u'/amy-winehouse-songs/jazz-n-blues-lyrics.html'), - dict(DEFAULT_SONG, - url='http://www.metrolyrics.com/', - path='lady-madonna-lyrics-beatles.html'), - dict(url='http://www.musica.com/', path='letras.asp?letra=2738', - artist=u'Santana', title=u'Black magic woman'), - dict(DEFAULT_SONG, - url=u'http://www.onelyrics.net/', - artist=u'Ben & Ellen Harper', title=u'City of dreams', - path='ben-ellen-harper-city-of-dreams-lyrics'), - dict(url=u'http://www.paroles.net/', - artist=u'Lilly Wood & the prick', title=u"Hey it's ok", - path=u'lilly-wood-the-prick/paroles-hey-it-s-ok'), - dict(DEFAULT_SONG, - url='http://www.releaselyrics.com', - path=u'/346e/the-beatles-lady-madonna-(love-version)/'), - dict(DEFAULT_SONG, - url=u'http://www.smartlyrics.com', - path=u'/Song18148-The-Beatles-Lady-Madonna-lyrics.aspx'), - dict(DEFAULT_SONG, - url='http://www.songlyrics.com', - path=u'/the-beatles/lady-madonna-lyrics'), - dict(DEFAULT_SONG, - url=u'http://www.stlyrics.com', - path=u'/songs/r/richiehavens48961/ladymadonna2069109.html'), - dict(DEFAULT_SONG, - url=u'http://www.sweetslyrics.com', - path=u'/761696.The%20Beatles%20-%20Lady%20Madonna.html') -] -class LyricsGooglePluginTest(unittest.TestCase): - """Test scraping heuristics on a fake html page. - Or run lyrics_download_samples.py first to check that beets google - custom search engine sources are correctly scraped. - """ - source = dict(url=u'http://www.example.com', artist=u'John Doe', - title=u'Beets song', path=u'/lyrics/beetssong') - +class LyricsGoogleBaseTest(unittest.TestCase): def setUp(self): """Set up configuration.""" try: @@ -326,44 +232,112 @@ class LyricsGooglePluginTest(unittest.TestCase): self.skipTest('Beautiful Soup 4 not available') if sys.version_info[:3] < (2, 7, 3): self.skipTest("Python's built-in HTML parser is not good enough") - lyrics.LyricsPlugin() - raw_backend.fetch_url = MockFetchUrl() - def test_mocked_source_ok(self): - """Test that lyrics of the mocked page are correctly scraped""" - url = self.source['url'] + self.source['path'] - if os.path.isfile(url_to_filename(url)): - res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url)) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(self.source['title'], res), - url) + +class LyricsPluginSourcesTest(LyricsGoogleBaseTest): + """Check that beets google custom search engine sources are correctly scraped. + """ + + DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') + + DEFAULT_SOURCES = [ + dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), + # dict(artist=u'Santana', title=u'Black magic woman', backend=lyrics.MusiXmatch), + # dict(DEFAULT_SONG, backend=lyrics.Genius), + ] + + GOOGLE_SOURCES = [ + dict(DEFAULT_SONG, + url=u'http://www.absolutelyrics.com', + path=u'/lyrics/view/the_beatles/lady_madonna'), + dict(DEFAULT_SONG, + url=u'http://www.azlyrics.com', + path=u'/lyrics/beatles/ladymadonna.html'), + dict(DEFAULT_SONG, + url=u'http://www.chartlyrics.com', + path=u'/_LsLsZ7P4EK-F-LD4dJgDQ/Lady+Madonna.aspx'), + dict(DEFAULT_SONG, + url=u'http://www.elyricsworld.com', + path=u'/lady_madonna_lyrics_beatles.html'), + dict(url=u'http://www.lacoccinelle.net', + artist=u'Jacques Brel', title=u"Amsterdam", + path=u'/paroles-officielles/275679.html'), + dict(DEFAULT_SONG, + url=u'http://letras.mus.br/', path=u'the-beatles/275/'), + dict(DEFAULT_SONG, + url='http://www.lyricsmania.com/', + path='lady_madonna_lyrics_the_beatles.html'), + dict(DEFAULT_SONG, url=u'http://lyrics.wikia.com/', + path=u'The_Beatles:Lady_Madonna'), + dict(DEFAULT_SONG, + url=u'http://www.lyricsmode.com', + path=u'/lyrics/b/beatles/lady_madonna.html'), + dict(url=u'http://www.lyricsontop.com', + artist=u'Amy Winehouse', title=u"Jazz'n'blues", + path=u'/amy-winehouse-songs/jazz-n-blues-lyrics.html'), + dict(DEFAULT_SONG, + url='http://www.metrolyrics.com/', + path='lady-madonna-lyrics-beatles.html'), + dict(url='http://www.musica.com/', path='letras.asp?letra=2738', + artist=u'Santana', title=u'Black magic woman'), + dict(url=u'http://www.paroles.net/', + artist=u'Lilly Wood & the prick', title=u"Hey it's ok", + path=u'lilly-wood-the-prick/paroles-hey-it-s-ok'), + dict(DEFAULT_SONG, + url='http://www.songlyrics.com', + path=u'/the-beatles/lady-madonna-lyrics'), + dict(DEFAULT_SONG, + url=u'http://www.sweetslyrics.com', + path=u'/761696.The%20Beatles%20-%20Lady%20Madonna.html') + ] + + def setUp(self): + LyricsGoogleBaseTest.setUp(self) + self.plugin = lyrics.LyricsPlugin() + + def test_backend_sources_ok(self): + """Test default backends with songs known to exist in respective databases. + """ + errors = [] + for s in self.DEFAULT_SOURCES: + res = s['backend'](self.plugin.config, self.plugin._log).fetch(s['artist'], s['title']) + if not is_lyrics_content_ok(s['title'], res): + errors.append(s['backend'].__name__) + self.assertFalse(errors) def test_google_sources_ok(self): """Test if lyrics present on websites registered in beets google custom search engine are correctly scraped.""" - if not check_lyrics_fetched(): - self.skipTest("Run lyrics_download_samples.py script first.") - for s in GOOGLE_SOURCES: + for s in self.GOOGLE_SOURCES: url = s['url'] + s['path'] - if os.path.isfile(url_to_filename(url)): - res = lyrics.scrape_lyrics_from_html( - raw_backend.fetch_url(url)) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(s['title'], res), url) + res = lyrics.scrape_lyrics_from_html( + raw_backend.fetch_url(url)) + self.assertTrue(google.is_lyrics(res), url) + self.assertTrue(is_lyrics_content_ok(s['title'], res), url) - def test_default_ok(self): - """Test default engines with the default query""" - if not check_lyrics_fetched(): - self.skipTest("Run lyrics_download_samples.py script first.") - for (source, s) in zip([lyrics.LyricsWiki, - lyrics.LyricsCom, - lyrics.MusiXmatch], DEFAULT_SOURCES): - url = s['url'] + s['path'] - if os.path.isfile(url_to_filename(url)): - res = source({}, log).fetch(s['artist'], s['title']) - self.assertTrue(google.is_lyrics(res), url) - self.assertTrue(is_lyrics_content_ok(s['title'], res), url) +class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): + """Test scraping heuristics on a fake html page. + """ + source = dict(url=u'http://www.example.com', artist=u'John Doe', + title=u'Beets song', path=u'/lyrics/beetssong') + + def setUp(self): + """Set up configuration""" + LyricsGoogleBaseTest.setUp(self) + self.plugin = lyrics.LyricsPlugin() + + + @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) + def test_mocked_source_ok(self): + """Test that lyrics of the mocked page are correctly scraped""" + url = self.source['url'] + self.source['path'] + res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url)) + self.assertTrue(google.is_lyrics(res), url) + self.assertTrue(is_lyrics_content_ok(self.source['title'], res), + url) + + @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) def test_is_page_candidate_exact_match(self): """Test matching html page title with song infos -- when song infos are present in the title.""" @@ -373,8 +347,7 @@ class LyricsGooglePluginTest(unittest.TestCase): html = raw_backend.fetch_url(url) soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) - self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), + self.assertEqual(google.is_page_candidate(url, soup.title.string, s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): From fa9262d61b65b5023b3be6bd68bd04c434cb3b5c Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 01:05:18 +0200 Subject: [PATCH 1919/2280] Disable tests that do real requests to lyrics sites by default. Set BEETS_TEST_LYRICS_SOURCES environment variable to '1' to not skip the tests. --- test/test_lyrics.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index b6abf8d9e..9ed0eb4b4 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -295,6 +295,8 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): LyricsGoogleBaseTest.setUp(self) self.plugin = lyrics.LyricsPlugin() + @unittest.skipUnless(os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1', + 'lyrics sources testing not enabled') def test_backend_sources_ok(self): """Test default backends with songs known to exist in respective databases. """ @@ -305,6 +307,8 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): errors.append(s['backend'].__name__) self.assertFalse(errors) + @unittest.skipUnless(os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1', + 'lyrics sources testing not enabled') def test_google_sources_ok(self): """Test if lyrics present on websites registered in beets google custom search engine are correctly scraped.""" From 3e3ad6974cc58d4b9b2f55f83bd01403339eb65a Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 07:30:40 +0200 Subject: [PATCH 1920/2280] Fix PEP8 --- beetsplug/lyrics.py | 13 +++++++++---- test/test_lyrics.py | 11 +++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index ad2d278b5..9a60df119 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -84,6 +84,7 @@ def unichar(i): except ValueError: return struct.pack('i', i).decode('utf-32') + def unescape(text): """Resolve &#xxx; HTML entities (and some others).""" if isinstance(text, bytes): @@ -110,7 +111,6 @@ def extract_text_in(html, starttag): """Extract the text from a
tag in the HTML starting with ``starttag``. Returns None if parsing fails. """ - # Strip off the leading text before opening tag. try: _, html = html.split(starttag, 1) @@ -151,10 +151,10 @@ def search_pairs(item): and featured artists from the strings and add them as candidates. The method also tries to split multiple titles separated with `/`. """ - def generate_alternatives(string, patterns): """Generate string alternatives by extracting first matching group for - each given pattern.""" + each given pattern. + """ alternatives = [string] for pattern in patterns: match = re.search(pattern, string, re.IGNORECASE) @@ -270,6 +270,7 @@ class MusiXmatch(SymbolsReplaced): 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'].as_str() @@ -361,6 +362,7 @@ class Genius(Backend): class LyricsWiki(SymbolsReplaced): """Fetch lyrics from LyricsWiki.""" + URL_PATTERN = 'http://lyrics.wikia.com/%s:%s' def fetch(self, artist, title): @@ -381,6 +383,7 @@ class LyricsWiki(SymbolsReplaced): class LyricsCom(Backend): """Fetch lyrics from Lyrics.com.""" + URL_PATTERN = 'http://www.lyrics.com/%s-lyrics-%s.html' NOT_FOUND = ( 'Sorry, we do not have the lyric', @@ -484,6 +487,7 @@ def scrape_lyrics_from_html(html): 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'].as_str() @@ -719,7 +723,8 @@ class LyricsPlugin(plugins.BeetsPlugin): def fetch_item_lyrics(self, lib, item, write, force): """Fetch and store lyrics for a single item. If ``write``, then the - lyrics will also be written to the file itself.""" + lyrics will also be written to the file itself. + """ # Skip if the item already has lyrics. if not force and item.lyrics: self._log.info(u'lyrics already present: {0}', item) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 9ed0eb4b4..0dbf658fe 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -311,7 +311,8 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): 'lyrics sources testing not enabled') def test_google_sources_ok(self): """Test if lyrics present on websites registered in beets google custom - search engine are correctly scraped.""" + search engine are correctly scraped. + """ for s in self.GOOGLE_SOURCES: url = s['url'] + s['path'] res = lyrics.scrape_lyrics_from_html( @@ -323,6 +324,7 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): """Test scraping heuristics on a fake html page. """ + source = dict(url=u'http://www.example.com', artist=u'John Doe', title=u'Beets song', path=u'/lyrics/beetssong') @@ -330,7 +332,6 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): """Set up configuration""" LyricsGoogleBaseTest.setUp(self) self.plugin = lyrics.LyricsPlugin() - @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) def test_mocked_source_ok(self): @@ -344,7 +345,8 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl()) def test_is_page_candidate_exact_match(self): """Test matching html page title with song infos -- when song infos are - present in the title.""" + present in the title. + """ from bs4 import SoupStrainer, BeautifulSoup s = self.source url = six.text_type(s['url'] + s['path']) @@ -356,7 +358,8 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are - not present in the title.""" + not present in the title. + """ s = self.source url = s['url'] + s['path'] url_title = u'example.com | Beats song by John doe' From 11eb90c7588f1d4ef688af1396f01b114f7ba833 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 07:46:36 +0200 Subject: [PATCH 1921/2280] Fix PEP8 --- beetsplug/lyrics.py | 3 ++- test/test_lyrics.py | 19 ++++++++++++------- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 9a60df119..5cf93471c 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -263,7 +263,8 @@ class MusiXmatch(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_between(html, '

', + lyrics = extract_text_between(html, + '

', '

') return lyrics.strip(',"').replace('\\n', '\n') diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 0dbf658fe..42969e3ea 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -235,14 +235,16 @@ class LyricsGoogleBaseTest(unittest.TestCase): class LyricsPluginSourcesTest(LyricsGoogleBaseTest): - """Check that beets google custom search engine sources are correctly scraped. + """Check that beets google custom search engine sources are correctly + scraped. """ DEFAULT_SONG = dict(artist=u'The Beatles', title=u'Lady Madonna') DEFAULT_SOURCES = [ dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), - # dict(artist=u'Santana', title=u'Black magic woman', backend=lyrics.MusiXmatch), + # dict(artist=u'Santana', title=u'Black magic woman', + # backend=lyrics.MusiXmatch), # dict(DEFAULT_SONG, backend=lyrics.Genius), ] @@ -295,19 +297,22 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): LyricsGoogleBaseTest.setUp(self) self.plugin = lyrics.LyricsPlugin() - @unittest.skipUnless(os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1', + @unittest.skipUnless(os.environ.get( + 'BEETS_TEST_LYRICS_SOURCES', '0') == '1', 'lyrics sources testing not enabled') def test_backend_sources_ok(self): """Test default backends with songs known to exist in respective databases. """ errors = [] for s in self.DEFAULT_SOURCES: - res = s['backend'](self.plugin.config, self.plugin._log).fetch(s['artist'], s['title']) + res = s['backend'](self.plugin.config, self.plugin._log).fetch( + s['artist'], s['title']) if not is_lyrics_content_ok(s['title'], res): errors.append(s['backend'].__name__) self.assertFalse(errors) - @unittest.skipUnless(os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1', + @unittest.skipUnless(os.environ.get( + 'BEETS_TEST_LYRICS_SOURCES', '0') == '1', 'lyrics sources testing not enabled') def test_google_sources_ok(self): """Test if lyrics present on websites registered in beets google custom @@ -353,8 +358,8 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): html = raw_backend.fetch_url(url) soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) - self.assertEqual(google.is_page_candidate(url, soup.title.string, s['title'], s['artist']), - True, url) + self.assertEqual(google.is_page_candidate(url, soup.title.string, + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are From 3e38a33c4a2730d83a5c9d43cdc5c9de6644b552 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 23:37:20 +0200 Subject: [PATCH 1922/2280] Fix PEP8 --- beetsplug/lyrics.py | 2 +- test/test_lyrics.py | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 5cf93471c..f75b157c7 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -52,7 +52,6 @@ except ImportError: from beets import plugins from beets import ui -import beets DIV_RE = re.compile(r'<(/?)div>?', re.I) @@ -260,6 +259,7 @@ class MusiXmatch(SymbolsReplaced): def fetch(self, artist, title): url = self.build_url(artist, title) + html = self.fetch_url(url) if not html: return diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 42969e3ea..8dc3e24f0 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -41,6 +41,7 @@ google = lyrics.Google(MagicMock(), log) class LyricsPluginTest(unittest.TestCase): + def setUp(self): """Set up configuration.""" lyrics.LyricsPlugin() @@ -199,6 +200,7 @@ def url_to_filename(url): class MockFetchUrl(object): + def __init__(self, pathval='fetched_path'): self.pathval = pathval self.fetched = None @@ -224,6 +226,7 @@ LYRICS_TEXTS = confit.load_yaml(os.path.join(_common.RSRC, b'lyricstext.yaml')) class LyricsGoogleBaseTest(unittest.TestCase): + def setUp(self): """Set up configuration.""" try: @@ -244,7 +247,7 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): DEFAULT_SOURCES = [ dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), # dict(artist=u'Santana', title=u'Black magic woman', - # backend=lyrics.MusiXmatch), + # backend=lyrics.MusiXmatch), # dict(DEFAULT_SONG, backend=lyrics.Genius), ] @@ -359,7 +362,7 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), True, url) + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are @@ -371,11 +374,11 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): # very small diffs (typo) are ok eg 'beats' vs 'beets' with same artist self.assertEqual(google.is_page_candidate(url, url_title, s['title'], - s['artist']), True, url) + s['artist']), True, url) # reject different title url_title = u'example.com | seets bong lyrics by John doe' self.assertEqual(google.is_page_candidate(url, url_title, s['title'], - s['artist']), False, url) + s['artist']), False, url) def test_is_page_candidate_special_chars(self): """Ensure that `is_page_candidate` doesn't crash when the artist From 07af27e44b9c923e23673f46aa3de683b34d15ae Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Tue, 2 May 2017 23:40:25 +0200 Subject: [PATCH 1923/2280] Lyrics are last paragraph with class 'mxm-lyrics__content' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove ‘data-reactid’ from marker. --- beetsplug/lyrics.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f75b157c7..39e1502ed 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -263,9 +263,8 @@ class MusiXmatch(SymbolsReplaced): html = self.fetch_url(url) if not html: return - lyrics = extract_text_between(html, - '

', - '

') + html_part = html.split('

Date: Tue, 2 May 2017 23:48:20 +0200 Subject: [PATCH 1924/2280] Restore beets module import --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 39e1502ed..cdaf102e3 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -52,7 +52,7 @@ except ImportError: from beets import plugins from beets import ui - +import beets DIV_RE = re.compile(r'<(/?)div>?', re.I) COMMENT_RE = re.compile(r'', re.S) From b3fbdbae5a76980f2d022539af88f44b41fc9597 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 00:02:09 +0200 Subject: [PATCH 1925/2280] Fix flake8 --- test/test_lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 8dc3e24f0..3b260c482 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -362,7 +362,7 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), True, url) + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are From f53ab801b83d2d24444e3ae7de1bb11dfbe55dbe Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 00:11:26 +0200 Subject: [PATCH 1926/2280] Add indent --- test/test_lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index 3b260c482..e2e5958b1 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -362,7 +362,7 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), True, url) + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are From 49e548bdbc9501a4f635a9f5dbc822adfc91f6a7 Mon Sep 17 00:00:00 2001 From: Wolf Date: Tue, 2 May 2017 22:36:26 -0400 Subject: [PATCH 1927/2280] Remove mention of python-itunes The plugin is inactive and has been broken for months: https://github.com/beetbox/beets/issues/2371 Fixes https://github.com/beetbox/beets/issues/1610 --- docs/plugins/fetchart.rst | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index ee0014072..82085ca61 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -49,7 +49,7 @@ file. The available options are: (``enforce_ratio: 0.5%``). Default: ``no``. - **sources**: List of sources to search for images. An asterisk `*` expands to all available sources. - Default: ``filesystem coverart itunes amazon albumart``, i.e., everything but + Default: ``filesystem coverart amazon albumart``, i.e., everything but ``wikipedia``, ``google`` and ``fanarttv``. Enable those sources for more matches at the cost of some speed. They are searched in the given order, thus in the default config, no remote (Web) art source are queried if @@ -82,13 +82,13 @@ or `Pillow`_. .. _ImageMagick: http://www.imagemagick.org/ Here's an example that makes plugin select only images that contain *front* or -*back* keywords in their filenames and prioritizes the iTunes source over +*back* keywords in their filenames and prioritizes the Amazon source over others:: fetchart: cautious: true cover_names: front back - sources: itunes * + sources: amazon * Manually Fetching Album Art @@ -128,7 +128,7 @@ Album Art Sources ----------------- By default, this plugin searches for art in the local filesystem as well as on -the Cover Art Archive, the iTunes Store, Amazon, and AlbumArt.org, in that +the Cover Art Archive, Amazon, and AlbumArt.org, in that order. You can reorder the sources or remove some to speed up the process using the ``sources`` configuration option. @@ -146,18 +146,9 @@ described above. For "as-is" imports (and non-autotagged imports using the iTunes Store '''''''''''' -To use the iTunes Store as an art source, install the `python-itunes`_ -library. You can do this using `pip`_, like so:: +There is currently `no plugin`_ to use the iTunes Store as an art source. - $ pip install https://github.com/ocelma/python-itunes/archive/master.zip - -(There's currently `a problem`_ that prevents a plain ``pip install -python-itunes`` from working.) -Once the library is installed, the plugin will use it to search automatically. - -.. _a problem: https://github.com/ocelma/python-itunes/issues/9 -.. _python-itunes: https://github.com/ocelma/python-itunes -.. _pip: http://www.pip-installer.org/ +.. _no plugin: https://github.com/beetbox/beets/issues/2371 Google custom search '''''''''''''''''''' From 471d46d67e770ab06ab4f573cc9c2745b3a63a76 Mon Sep 17 00:00:00 2001 From: Mark Stenglein Date: Tue, 2 May 2017 23:41:31 -0400 Subject: [PATCH 1928/2280] web: __init__: _rep: Filter all bytes for serializer This commit fixes issue #2532 by filtering out any byte values added by any other extensions and decoding them to strings for the JSON serializer. It does not remove any of the keys, instead opting to just convert them. Signed-off-by: Mark Stenglein --- beetsplug/web/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 3c18ebd5d..1bea628f8 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -42,6 +42,10 @@ def _rep(obj, expand=False): else: del out['path'] + # Filter all bytes attributes and convert them to strings + for key in filter(lambda key: isinstance(out[key], bytes), out): + out[key] = out[key].decode('utf-8') + # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. try: From 8b4b64d7343e7341f077d67afbc5ab660b7e0c58 Mon Sep 17 00:00:00 2001 From: Wolf Date: Wed, 3 May 2017 00:48:52 -0400 Subject: [PATCH 1929/2280] Changelog for #2540 --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5c0d15e0f..fbcf33c13 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -100,6 +100,11 @@ Fixes: ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` * When the SQLite database stops being accessible, we now print a friendly error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` +* :doc:`plugins/fetchart`'s iTunes Store artwork lookup no longer recommended + in documentation, as the unmaintained `python-itunes`_ is broken. Want + to adopt it? :bug:`2371` :bug:`1610` + +.. _python-itunes: https://github.com/ocelma/python-itunes 1.4.3 (January 9, 2017) From 8f32bfed82ef7fcf8a3fd88ffe305230bc37d711 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 07:42:50 +0200 Subject: [PATCH 1930/2280] Reactivate test of LyricsCom and MusiXmatch sources --- test/test_lyrics.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index e2e5958b1..a96551e75 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -246,9 +246,10 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): DEFAULT_SOURCES = [ dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), - # dict(artist=u'Santana', title=u'Black magic woman', - # backend=lyrics.MusiXmatch), - # dict(DEFAULT_SONG, backend=lyrics.Genius), + dict(DEFAULT_SONG, backend=lyrics.LyricsCom), + dict(artist=u'Santana', title=u'Black magic woman', + backend=lyrics.MusiXmatch), + dict(DEFAULT_SONG, backend=lyrics.Genius), ] GOOGLE_SOURCES = [ @@ -361,8 +362,9 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): html = raw_backend.fetch_url(url) soup = BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('title')) - self.assertEqual(google.is_page_candidate(url, soup.title.string, - s['title'], s['artist']), True, url) + self.assertEqual( + google.is_page_candidate(url, soup.title.string, + s['title'], s['artist']), True, url) def test_is_page_candidate_fuzzy_match(self): """Test matching html page title with song infos -- when song infos are From e7ea7ab5f22342136b2a8f038bbbac19a0c66555 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 20:04:02 +0200 Subject: [PATCH 1931/2280] Update fetchart.rst --- docs/plugins/fetchart.rst | 7 ------- 1 file changed, 7 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 82085ca61..97e88c03c 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -143,13 +143,6 @@ When you choose to apply changes during an import, beets will search for art as described above. For "as-is" imports (and non-autotagged imports using the ``-A`` flag), beets only looks for art on the local filesystem. -iTunes Store -'''''''''''' - -There is currently `no plugin`_ to use the iTunes Store as an art source. - -.. _no plugin: https://github.com/beetbox/beets/issues/2371 - Google custom search '''''''''''''''''''' From 9394e0ac63786b7f0296eb39d0885960e677ff23 Mon Sep 17 00:00:00 2001 From: Mark Stenglein Date: Wed, 3 May 2017 16:34:30 -0400 Subject: [PATCH 1932/2280] web: __init__: _rep: change to base64 encoding As suggested, this commit adds base64 encoding for the bytes encoding. Signed-off-by: Mark Stenglein --- beetsplug/web/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 1bea628f8..2afef7786 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -25,6 +25,7 @@ from flask import g from werkzeug.routing import BaseConverter, PathConverter import os import json +import base64 # Utilities. @@ -44,7 +45,7 @@ def _rep(obj, expand=False): # Filter all bytes attributes and convert them to strings for key in filter(lambda key: isinstance(out[key], bytes), out): - out[key] = out[key].decode('utf-8') + out[key] = base64.b64encode(out[key]).decode('ascii') # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. From 22f07b91e93267520870f55114841c886c7d057d Mon Sep 17 00:00:00 2001 From: Mark Stenglein Date: Wed, 3 May 2017 16:36:40 -0400 Subject: [PATCH 1933/2280] web: __init__: _rep: Make the looping more pythonic As suggested, changes around the for loop to make it a bit more pythonic by using an if loop inside a normal for loop. Signed-off-by: Mark Stenglein --- beetsplug/web/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 2afef7786..c154b0cf4 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -44,7 +44,8 @@ def _rep(obj, expand=False): del out['path'] # Filter all bytes attributes and convert them to strings - for key in filter(lambda key: isinstance(out[key], bytes), out): + for key, value in out.items(): + if isinstance(out[key], bytes): out[key] = base64.b64encode(out[key]).decode('ascii') # Get the size (in bytes) of the backing file. This is useful From 409f0709706db987f647d271e49144bae6ec852e Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 22:54:09 +0200 Subject: [PATCH 1934/2280] Remove lyrics.com source --- beetsplug/lyrics.py | 36 +----------------------------------- docs/plugins/lyrics.rst | 5 ++--- test/test_lyrics.py | 1 - 3 files changed, 3 insertions(+), 39 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index cdaf102e3..113bed104 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -381,39 +381,6 @@ class LyricsWiki(SymbolsReplaced): return lyrics -class LyricsCom(Backend): - """Fetch lyrics from Lyrics.com.""" - - URL_PATTERN = 'http://www.lyrics.com/%s-lyrics-%s.html' - NOT_FOUND = ( - 'Sorry, we do not have the lyric', - 'Submit Lyrics', - ) - - @classmethod - def _encode(cls, s): - s = re.sub(r'[^\w\s-]', '', s) - s = re.sub(r'\s+', '-', s) - return super(LyricsCom, cls)._encode(s).lower() - - def fetch(self, artist, title): - url = self.build_url(artist, title) - html = self.fetch_url(url) - if not html: - return - lyrics = extract_text_between(html, '

', '
') - if not lyrics: - return - for not_found_str in self.NOT_FOUND: - if not_found_str in lyrics: - return - - parts = lyrics.split('\n---\nLyrics powered by', 1) - if parts: - return parts[0] - - def remove_credits(text): """Remove first/last line of text if it contains the word 'lyrics' eg 'Lyrics by songsdatabase.com' @@ -605,11 +572,10 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'lyrics.com', 'musixmatch'] + SOURCES = ['google', 'lyricwiki', 'musixmatch'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, - 'lyrics.com': LyricsCom, 'musixmatch': MusiXmatch, 'genius': Genius, } diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 7263304f2..d7c268c7e 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -2,11 +2,10 @@ Lyrics Plugin ============= The ``lyrics`` plugin fetches and stores song lyrics from databases on the Web. -Namely, the current version of the plugin uses `Lyric Wiki`_, `Lyrics.com`_, +Namely, the current version of the plugin uses `Lyric Wiki`_, `Musixmatch`_, `Genius.com`_, and, optionally, the Google custom search API. .. _Lyric Wiki: http://lyrics.wikia.com/ -.. _Lyrics.com: http://www.lyrics.com/ .. _Musixmatch: https://www.musixmatch.com/ .. _Genius.com: http://genius.com/ @@ -60,7 +59,7 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki lyrics.com musixmatch``, i.e., all the + Default: ``google lyricwiki musixmatch``, i.e., all the sources except for `genius`. The `google` source will be automatically deactivated if no ``google_API_key`` is setup. diff --git a/test/test_lyrics.py b/test/test_lyrics.py index a96551e75..e811da8d7 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -246,7 +246,6 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest): DEFAULT_SOURCES = [ dict(DEFAULT_SONG, backend=lyrics.LyricsWiki), - dict(DEFAULT_SONG, backend=lyrics.LyricsCom), dict(artist=u'Santana', title=u'Black magic woman', backend=lyrics.MusiXmatch), dict(DEFAULT_SONG, backend=lyrics.Genius), From 6fa1651d99294378f0590deabf35e3ece524c197 Mon Sep 17 00:00:00 2001 From: Fabrice Laporte Date: Wed, 3 May 2017 23:06:43 +0200 Subject: [PATCH 1935/2280] Update changelog --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index fbcf33c13..1014bfd1b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -103,6 +103,7 @@ Fixes: * :doc:`plugins/fetchart`'s iTunes Store artwork lookup no longer recommended in documentation, as the unmaintained `python-itunes`_ is broken. Want to adopt it? :bug:`2371` :bug:`1610` +* :doc:`/plugins/lyrics`: drop Lyrics.com backend (don't work anymore) .. _python-itunes: https://github.com/ocelma/python-itunes From b57c49d7386e9e55ddf0495f034b93cb2da55588 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 May 2017 09:29:27 -0400 Subject: [PATCH 1936/2280] Add a period to a comment, simplify one expression w.r.t. #2542 --- beetsplug/web/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index c154b0cf4..290f25b48 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -43,10 +43,10 @@ def _rep(obj, expand=False): else: del out['path'] - # Filter all bytes attributes and convert them to strings + # Filter all bytes attributes and convert them to strings. for key, value in out.items(): if isinstance(out[key], bytes): - out[key] = base64.b64encode(out[key]).decode('ascii') + out[key] = base64.b64encode(value).decode('ascii') # Get the size (in bytes) of the backing file. This is useful # for the Tomahawk resolver API. From 376c31a2a41e0c71eefec14a8729c666d642420c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 May 2017 09:30:54 -0400 Subject: [PATCH 1937/2280] Changelog for #2542, which fixes #2532 --- docs/changelog.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index fbcf33c13..e5701cfaf 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -100,9 +100,11 @@ Fixes: ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` * When the SQLite database stops being accessible, we now print a friendly error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` -* :doc:`plugins/fetchart`'s iTunes Store artwork lookup no longer recommended +* :doc:`/plugins/fetchart`'s iTunes Store artwork lookup no longer recommended in documentation, as the unmaintained `python-itunes`_ is broken. Want to adopt it? :bug:`2371` :bug:`1610` +* :doc:`/plugins/web`: Avoid a crash when sending binary data, such as + Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` .. _python-itunes: https://github.com/ocelma/python-itunes From 6ab7ad22de68f5ce8f09fc671bcc117830698cc9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 May 2017 09:35:19 -0400 Subject: [PATCH 1938/2280] Improve changelog for #2549, which fixes #2548 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5c0915c3b..b3aba9511 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -106,6 +106,9 @@ Fixes: * :doc:`/plugins/web`: Avoid a crash when sending binary data, such as Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` * :doc:`/plugins/lyrics`: drop Lyrics.com backend (don't work anymore) +* :doc:`/plugins/lyrics`: The Lyrics.com backend has been removed. (It stopped + working because of changes to the site's URL structure.) + :bug:`2548` :bug:`2549` .. _python-itunes: https://github.com/ocelma/python-itunes From fc560ac1cb7163cd2a5a9f64b7a00585caa8eb44 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 4 May 2017 09:41:20 -0400 Subject: [PATCH 1939/2280] Rearrange changelog for feature removal c.f. #2540 and #2549 --- docs/changelog.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b3aba9511..bf0d7d254 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -100,15 +100,17 @@ Fixes: ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` * When the SQLite database stops being accessible, we now print a friendly error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` -* :doc:`/plugins/fetchart`'s iTunes Store artwork lookup no longer recommended - in documentation, as the unmaintained `python-itunes`_ is broken. Want - to adopt it? :bug:`2371` :bug:`1610` * :doc:`/plugins/web`: Avoid a crash when sending binary data, such as Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` -* :doc:`/plugins/lyrics`: drop Lyrics.com backend (don't work anymore) + +Two plugins had backends removed due to bitrot: + * :doc:`/plugins/lyrics`: The Lyrics.com backend has been removed. (It stopped working because of changes to the site's URL structure.) :bug:`2548` :bug:`2549` +* :doc:`/plugins/fetchart`: The documentation no longer recommends iTunes + Store artwork lookup because the unmaintained `python-itunes`_ is broken. + Want to adopt it? :bug:`2371` :bug:`1610` .. _python-itunes: https://github.com/ocelma/python-itunes From 90c30d8564b7b31427f33c83b3933921329ec497 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Thu, 4 May 2017 19:08:23 +0300 Subject: [PATCH 1940/2280] Added an if album: statement --- beets/ui/commands.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 36876d229..840aa0a93 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1481,8 +1481,12 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, for obj in objs]) else: if export: - for obj in objs: - util.copy(obj.path, obj.destination(basedir=dest)) + if album: + util.copy([(item.path, item.destination(basedir=dest)) + for obj in objs for item in obj.items()]) + else: + util.copy([(obj.path, obj.destination(basedir=dest)) + for obj in objs]) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, From 167ae91b8d94fc252c9238c6a35f1083b09f2303 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Fri, 5 May 2017 00:36:36 +0300 Subject: [PATCH 1941/2280] Changes at line 1486 --- beets/ui/commands.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 840aa0a93..7e2095dd1 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1482,11 +1482,12 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, else: if export: if album: - util.copy([(item.path, item.destination(basedir=dest)) - for obj in objs for item in obj.items()]) + for obj in objs: + for item in obj.items(): + util.copy(item.path, item.destination(basedir=dest)) else: - util.copy([(obj.path, obj.destination(basedir=dest)) - for obj in objs]) + for item in objs: + util.copy(item.path, item.destination(basedir=dest)) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, From 09ea5448f1aab3bc662127cfb6e5e38eac3c7798 Mon Sep 17 00:00:00 2001 From: "Shen-Ta Hsieh(BestSteve)" Date: Sat, 6 May 2017 02:52:55 +0800 Subject: [PATCH 1942/2280] Recompress png file (#2552) Signed-off-by: Shen-Ta Hsieh --- docs/plugins/beetsweb.png | Bin 36607 -> 33782 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/docs/plugins/beetsweb.png b/docs/plugins/beetsweb.png index c335104eb86d66e48cda9a311ce8793eaeadf259..dcb5aae17a25a50eb44c9fcbdfd6360280c25a2d 100644 GIT binary patch literal 33782 zcmeAS@N?(olHy`uVBq!ia0y~yU{YgXU@YQbW?*3W_WU6S0|V2?0G|+7uaw$JErnj) zXEW-j?c8^8{np((_Z^u#e*q^0gNBBNpSOpAfPj^iRZvh+QBjeEgv8aWS5KclbL`mB zU%!6E$H)Kw|Nrm5e}De`{r&sTuV24@{P_9(`}eP3zkdGw<->;$pFVwh_wL=BH*a3O zdiC({Sew{G2< z)vJ~-U%qg`f*CWWPo6xvf5L>$j*fy0Yj1bGd2ssuvm4*v-~0al`R}i9|NZ>*|L=Ej zSpNU^_y61P|6YFlap&=?JC9%Aee(Ljvp4sjzkm4h!;{w^pT7Na=i#%3m(V7V}7uR)7i%rcdOAG2O4CzdFXpPmb^ykTRVo6qG2;pJ~ zHfE1?*C~py?5a#%)R{V?I%wC@ou*CEQ;P#nYhsvAB45Mv`m0s{KliHYzSv>2V9%$CQ;)7Y zp0ie*ZW;I;UlFQNOl+P~p%KU}Au6Q5E!b;_hAEpjvUSAR8|q`<{KPkGHV!B)v5 zQE6$_Gf(h6{u2C8r`1uiJ@=ZHgDUnQ;jdG1pTO)*A^W5*Z+3vtnEct zPyN(M;@!QKDgWKiQ0-?MBOh3JN94O^J*|;@crLM`L7I`Va^Ib{MuVPxqGEvux_(S) z3^Whg6xwj!`DdQ+18WJv3%OnAUww>puF=|MJKy|d`q@v04eL&der|PA%>V6j(`=?v zjLxJNE1Il?HqTLR={TY$r$7Dl@r#=`#VuUBcJJD?Gv>6W-sZ1jGsxB!Aj5&x(C+xY6Him+3GqDr^CZuqvG z+d-Q0-bN?aa^AcAR(j3$g@2FU^l3PtwsXDSx;uvpAG6=Nw|>$D{gqM&^ltMX;y9#b z(;UtEQ=}l|Kj-t)Cob&Y@4jP-gJk`jOG1Yxbmw2!ncx0Fu#fBBd~f^EUB7Q@bpFWe zlok-V^0c^%et#(6a6rP=f=m3k(T(Pe&gYHJTT4=E_whV@ zoWpMRh=bFF)9>FCnS1!0hhQ#C_Z> zKXq1{a^W(bIsY<0 z&YZvPwQ{`v%O54r4?JAY|3*}Jf83;d+94YE?MnDRIqul2EB}6d-ah-d#)Ko~(vQ4( z_whV_Eb!p|ms0Les(U6ISl(9Y3~}>*d5cAab4%y7b-o{#dsf=Adv8vCyE^c#<_YHT z$7>3lnYedIh0o{_FExxxl+AsiQeyb{-OnG2ZTo(IJ^s>GclU1lT~>R)FOIF%oxY5} z=KJw4@7CANSlCyyGdWA;fIR=S6RH85Yg!G<>vzfX@_s6nuoqZ!dU_v!`mB}>?A0}O zRZ}}>Y$?n&VqSH}e{$l4+{xTLI)~3s&utIU61ASDU%>mwdx5W6gyZZ6aiyiwQ?nF) z9bm~V3OsRXfAzIJpAVhZuiLWv``+jAbr1jAD`oHBv+C*3_tE@nOD^(utz`8My{-B|{LP1gtttnNit28bah}-b=_wWbIcN5P`x`E( zai?;ex^h!ec+xEgU0Hz+^Ar5~CYQE#PFZ@*Hhcd~{?KlkS+=e}>JWp8b0 zJhR>YEytb3fjI%b_vJ;8nLk`U^V!cQPl~xe?esYqTo>V*JNwM1JJ0LS^8UA-MbPUi$t_WYD4a3nF7qZ;gNZK<(hNb$?5y z9}+(xnb~)d<^GlZ_IexQ*x%P{$G3lqy~6UN?MI!`vCj9$_mpg#;JNg2RB{o|ts}L| zN;hR!ocZ_J+U$;LbhMs_y7l_&x1Llj|NLgLu<%>|$-du~dmfkhVDsVblLdL*#c_$44DlPUch$Vl`+08N@#}`SmA836lB$*6 zo-5Q@W%}~St#j|@y*szn^X^KUbYU%uHl zS8YmvIPcTy?GI-!@DF_w*ka>lXfm_yr^Mk$4EK!-GbW#r5j?t}(Jb+z#vJ+HOv?bP zaH$Dw3GX^3Ur+U7K6GSH#uc^39v{7k9R++({`$|ZTyabAu!G5#fX~v~qondVbgz8* z|9|ltN1kI3qT__Ky^W`RyYuPS;Vc)H(~~?)!eRxl<|cMO(OQ-#&(44S!!GqwRlP@% zc3gtn9#!4=-%^${G5p`B+TOBTmsM|nEXZ2^_x;W5j!YjK?#q2zn|0c4SKq#)pZ6a= zuC`y^e%-IL_h0<4+s(Gj-iL2yb-Bjkx!?bga z74-S$le6e*N+-)Z<&tTu3THRR8=Wb4D&F|+<7YwpprBQG>ZvUrD|kxh%#7b@YP9rQ z$e$TM66@@~|G8>0W1juG)H5{|mY+>Oc5iv`{J<2$&zn2>C&&N)m#f=-#Y$c+NUb}p zH1L{p!sCt(pQ*=QMOc((&A;8zTX`(dNoZf}j&F@;j(eZ|+|$!FU0pM+1JUw?&vtFOkg=>MNyehyS-sy^}M zSwx1vNS58Hslmdr(?0)9*%ig4Yb%)Z{pa19)c5BkhDFhz9k(M+$_4hV7kW7}S87d~`>fdW5i?iKXMO#< zV8YAN%cr-%KsRoj|-SH5Ys8}sogcfx8V?I`QRCJ)s&~G;Q9HWiT}cW z?pGz?Rs&x;(C;)&~eY6GOyEd5!;s-Hd+~-R;f@~ zm=QILUwpp0#Pe_dMZdN``#srizx~mZLH{jXH(jxheBr+(NAazatkLS{&Ww>2^!XhJJbR$dY$&VwmLL>zejn*#I6ZT*M!F_ukyP! zwfb+_=Q;ZqT--Uyetu2VVY9a!3cDjW@A8^l>S3_4V_KQ734>?Y*Eym&dFxhHJzd!7 zEaZ1;%{y!D!m}G%v^&1+YCn2G$>KQ^bBf*%-j;|HhyT?4WK?D1ZM9VYC!eHuV(N## zDYt(X-_gkSVm)wVQr!!`SL>{=im>Z?-exe5op9>XQf_hno?{zsewK_^vzW*j-}duv zM3&37-v`$;8LAyyc-?nlFJs`=dIc7nW~u(N@@O?rgp+$^JeIEQT64(9_u7#Yd6&g&W;*Q*iU<^Mjq;aDevqI(kIO~iz&&=KfM?;3 zOCI`fy>;lHbKn10uU}7Je{avT+Y{y$tM%D;9xBOW`eUBBThd1=J?xy57N^*otB-bw ziSAJFWszcTaQ*m$Va>_Jl__4T5t9@CP4`>CIrCDF)@S=~j}>!3_;!4=?{&p(bEoE9p4epWGp`PVsr-zB6<8$RFhTS>OJ8Lq_uL#TC&iWm+ua3@IVA92G*AmgF4G3)>`Y z{Pc~{lLZfs-uuelFK@r&Rx6WISzBrhdvgQ(fm^1Qhjy&lr7I^Y_{+sWWFoKYN}Zel zkwlZfH6}@4=N&5Epr+ZsA>@h8h41gmr0pZk*Y9wdX4YH(uz#;PUvAN3^W5JlZ!i5UPCq5CU-$J&;<=|Rx0^rh z7u@kH-&cgqy(Lj+LAv+~!D%1#8r4I@z9!~gvS<{I(P{5H^k3n}-})nkYs)V@6T6eE z*O>U?$DRWlWljf6%@u0;nZB^4!swOSveuIsuM1 zqqkqwN_X#zoU}XOTWRL9{LjaP!}iV%G}c)t|D)@$;Hzsw%DXqk`7Ca{ZG6sPZj_Qv z;Q9|9Yk19DL#u1PUfTKj`RVC(ySF_Le!g9uyS}2wb!XvmtErE==TB~R@Bg$etorl; zVf9rtg@#jS3EwC*HZ@cKAbfUX$X|owPp7vfZCuF3&;CBq?}63)!ryo1e3zV;{;yi9 zVtV~7;eYubYuPQHCnfzfxfwoRizPkQ##(RJE?3hg#fos})mt9AHoQw(+tNK>$8*7ZoHE)`*JpJm-F2dcPH&ucQKbJUuC)c@-q#C#wRB{ zL}nDs%m2P6Zcjzst5f^eu8qBKeAsG+P0^HM!y`gDEF8)oR(x>!xb*yqLxZVrd8?JUI&i;>l$MW;T&xP^N{3adJpMQ0J-724B@wHFxSr^@(#&f>v z1*cp$%(S&?-1}ZzwEz5y?_Y2GXWewo*VnP#5wY&em&?z0Jz$GTX!-TPXvU9|;{N&ePU+41Y z+)n&*VXl8|SC{T#jjbt4bGv^2zE*zyE6;4flLwEy*jRqy?yNg9o!=~PFWNRccFUVi zRVAU;lLuSQyxZC5`TWt+`ai$xw1MRotv4$Yd#uh zeR92J(OA-@cx1-gscE;@r18DJ-*xc%XXmYN?Y1i2>*ZGOKy zcv`ol`-_&&7YmQc9Iv*?sZUCqe4wn#R_FaUj@Z3U8<$@{+Ps(b&d;3P+lwc+mzVFb zkl9i-^KoVW>cz(|w`CrE{4A2^IM=*=dE)MyJr`e-)PKKz_ksBj(me0YQGEPNGHTNu zwe{_3lYRHr=Du0R=i{9#*YnZ&Xj%F;^+hMtn)U9jD?c(fxA)7F%g?KJ&nkW6(Ia`7 zaecVV)yIi%GQ>(_uRi~^_n@FMm%eXEX?^zj>Mm0r=lrGQz4fC}u_I%ysM6<@_ftY zJj|kTvEi-B1^c8V77r7ik}s@5{B9H5=luUwwK=-|t)DZeMPiMi+|jP4kZ)`LzP69s zvyJQT<6B>a#pd3a=)0`@{nN7Nb~BZJ-#c^no6Aq;B}>nHm6`3d{~Y`7dTvVL`?b~e z|9O5Eyw~NQue;~#hkNnU@BQ47viJLkm96Z4(KhGnzufg~vflUM-1cA&J?oF3)Oq@C zf>OE8Dk?8~9a>(Tmvqx$mDAx1z0FI!`=yrMGC5SIMk#kMt7We11usncCOBsmhPH3KTf3OVCi_P3YXxdhY9vNbRRzcLeJ9 z&u*WQwE5Ua`-nOFvZrL9Uy*xay};3wDiYf@nI+S{rq&K=&!-;8S}SYU}c!2HfQ-dZBD(5+M%}?HJ;e6H6dh7l4vorJNTbf_EymMz_%ik*A`FbTscgNH(t3JrXx9*Bw z`Sx$zKMsp9vf5{9dF)qQ=Zm({ojy{5`(>-g#T|!;{#uY!vr=y(izZ=jRK}Ltnk?KNd_a zX#H?0djEkv4&UDYZTj#hC2sz zHl9>d5o_{1p2gp>BWA|@tOEy%?R{)6PxLLaIbD!j)bUi|+T#40YS~N4U6CJIr~4RZ zN}Wn*u{$owCso{7;1SN&e#Yg{73VE-nO`|NG>;y1@xJ-E#rOof#`ysq^WG>)oKRybIUAX2_p@HS$3HH%Y?FZC8oM2JgT{r$PoXzB+k8TC8wDGgJUAopK(27bTV-6 zoqct}-l&mHc@ZG1H2Tgffw@EGQDHObuv7q>@qwf62j>+NZ|BjrreOhEzR!uS&+ zhuhk$r2?f^U3N{=Smge8gGH@MS3`5>T>+WXOSZoaYd-iQH~R9-lnK8&w(;+2Gf?F9 zJZy11r8P}>`d_Obt@ig7 z+{C}J?)}M0t*UR_`P3da9Ih%qFXF#u`u@2t%nuE=_Am>7Iw$8cL8Ot>?f8+>t_dIC zPw5i9J8vy8nPh%A|FU z6<-XsC(A7D)cm9RW5)cb<19KKyq|Y1zU-m=pyAE-g%-}%{yJA@r1gqSSkmRY*)F&6 z4gd6g*%FbLC*KiMo72qs_r65S=8PkU>JIa``<#8x-y*WcJ0zH=ca|WF7q_Xe4t-sYQiTFO}_C^5b1j6z}W(Czpu^PR;c( z*>X9fUDaJ_+MI(MGF#@H*ZA1M(we;ZLEyHx7EcV0vRq0r7M$iP}G^^E)Z?XJ~v_I=7fzy8hL z;ItFJXH1#k!xd3fkP^SuAWCgc>(tbL`q{=#pCbd;O#60uXR6$c2NLW3BXyEi_RI=p z>z=ma=NrSOR&NcnSQb&4gqikfhOHN!TaG5VUOU^B{Zu4Fvse1E!qUjMKe%;D+WCbU z#3CHIqJ13;>4Vt*`AUj1?|XXD1#Z-4bNcy5vuc3x;`ykmx! zMCXbOHQ^a)Du#_h%N`V+G7;XC!gqMPDl5kdGquc{c^v(z2afm2E>M}waa;MY`_d_I zwrDO)=j0U;_6%0EOiWt4Nl}H}Cxt<6op%|t$L^DBI+po1xEVI4AK7C(*&{FG&9*HZ z>e9j$jKYn}_rGe)zqT%RSINge`Rl_yUaw!cb>g2>5q~8X-7*k9ajo-boQ}G9dTwy| znjUMTpKo|Jik(T>dL*JZr8jbg!H&O|S9*26@m?~2wZUXz@0BIBvo_4gi4n{87ZPK$ zfAdbi@%%mK$zjtiqP2dhe3V@FpnUST$i^qNOp$AZDt1dx3=4Tr;nQ zevxbLT^AYAt~QC^-AYQ7@$FB^x`zyj-TM|)A8Nl^wZTVX-@>q%Yfs*rspM~;K2u@} zU%7YctOSnV$u3pLw%x7EzLue!!!7)?tw3LU;e=H@EL&FSbT)TA;?DFkSfI7fV9|44 zSJMi2mrCcTsNj`TGNKBTbQ&jbEUD6&D(PIJ>N+jt)#4fDdA`|`Dvw_?G3s2kGO)`t zWa%;&r=Y3-wQd?b`G1S+K|`mTVW7`04@SZ0y3N(jyC(_l@=Oc5`sQM(=nRKLZ;J2N zeg1m={=ceoXKy*NbhI)rx-QUsSTjnk?2_5zNoEFp7YpxcJYZhi&%S)wS;b|1Hv+8g zN~YCjtTrtx{OR+$wUOEM_TRTn3-``3xNWlV(T$6Jfoc~IS>y?5O}_F>WZTWcxHZk; z75@&%cYN6Av4dTC`=-uK3vU`M5|s$JGU2?r!pg+|4H92YXK_qD*ugaUy!ZjhI9eho#}iz(&g5&_NlpO<*TzmC z-$@cb`4zno?f1w z;_1g~uY1k+p6Hz@@!P?pTb8L%#$)lJ2=o1d%gt{tKX^DRzxj53UAFoD>hu#~&%=!4 z7Faf0{MXp}uHow`wZHdon)AOok*m;g?~vtP$3_p{gfx*I-}g^g9kBj;qQa?Vm%G;~ zO27E=U3bNlL*XAkq#XONpL1wwsOFK(<;-WTgL;x5Z(N?fJLb*Li>oi4WBl=@$ou2V zhnfePf6TB+7drISHiIi}QkZdNMnWI=*1h+WlG1m)X*?;DzEZ%Ip>R=b{pa$fm&`x? zvwryYSI<7nkNQ8K{n_#O+y3?Mx4hVUa;kez^elg`_Qlc1YM(vHyIy|d;()fyaQbrjK$G{Ut8+~c9^Ds{e9q=qN3o+ruu@C!xt(uTbY^Ninrgf^;>U~) z)7O9h`<3^Q`hqPHnLEEK^c?@TSLKVNLB^a-8!o;6ofmkXGh_Sf&&{s`+qUc7F(_se zGgMVPUtPhcxk7Z(T=mL7>p#DD^QlSQw`|Y13I9zuc{DoPy*YJ!*W2|I{{5fMd{L>} zd;6-?kGIw?oVHZd#&tzezX3TSGzvljnKOFRsMyL^GT~;bDV#z zQS)9?^wQ9={9r?pW!`z|uYY<of8~=!LQ_w9o5@WMI#Uw5`f8NvX13|8^I9GjIZvM*Y!|c!PN0tke@6)XjUA=xvTAby|iR*c{opZO$xz?E2ENo zwxf%Rq;m=IX4x{Pwb~nP`BV%l&(F+H{}i?58_#$9^GEXjrqAuAb#s6E=+tNn%LkgC zI?dbf`H1~|*jm%Qj@$1^t+o546uA4~>kVzT%_mI6JaQTuT@8zm74{Ts*nVAo&u8sj ziy5i8&$4$MEQ>Sy;qs;X>eTaAl?ETe?Q)p^^qrr0E&WcM!j-!Z=+r**O9u2p;3 zLt8&qH$Hzhb-RDJv_8ues{*$LC*9`Vn6G?%O5)SIYod4WWA_j74d#A&_M)5X^{Kt9 z*1zOpROOu`l5xmBFz3!6funY+(q>M~4G#O3Oo-Fee0?bFpK#l+FtauB`!@#Mb4aYX zTjex0k2hFh!q=Yy0k0a=RxQgs^~`z2)8N(1)_H}NhOS+;I_LE?6V+MX3)a8p4PCu< z-HNqWL)S`(zW=wce!ld#?|*-9bL&3dRavuMqfaY&72C8Kd%r!MUDNTjoY_leUFW*j zub#CpIC*hp@cx8|qfd`NP^+6C>>>Ko<;APRoKJLO55G~KtnR;ed4R9Jlk!3pr|mf! zH&;ZNBpaN5=kB|FMO$Hdu%uV%n^%lW&;ED*f4Ssvz{Aa*HWG~6V{+`B=B)AF^QH7} ztx6Y1?Y76#M+*Id?tWN&Ilzm>w_@e>KgOk(nM;(D95XLpTfgq4`S**wtCd|$loxDa z^etgd<~5lZFrTrhWnDD?#0xgNwx8g?x_auZ^qpA;k8ZddJKwiw(ZzX79t$Ncm(t6ty|qQ@ z>VerMhiCN_Oq_b;qCivg*KbEn54H#}n`HjX2`&*oQMkuEYmRMkSyYDAG#!kUu@>(?KzYqq|x5i24hkG5uL$yz#Qr;g5Aqn=9n*T)Z_Y z`R@^@s1n2L`t!~{SasK3jd#*-4&HTVhk(}N%;V3493XL^PaU2VJ8r4LEw(%WZ5*_%OKl0Zv7q6mok5an0HbIc?9L zsp+S@&g7Ii@p}yigRg|c8ulc6%jymB_ivcK4qVf3oId}+`#U<<(r?VERVp&t88Tn7 zJj}lPR+|gOGbk?^>L$A!1JpUF+N36hw` z_*?qe)&B-xuA6ne%hhK3VX>gOzimpg98;v4k4r@F8B=D)>zavEQ+YRt#om7PaMCtW zp(|V!eXE^jGtN_(ku_}=0jSpf8s%u zT3f%s_l6%Hb_$0*)hs_KR@E=>{gA2X+BM0@MJ>nqyv?K)OLnaEne01vvyY1Y9+6i$ z8JmP3xAGjH* z`~JJ|`np~6XTQtGhyTB6-EDGntwc{-_=N1V44pJSP6IOQ!tK z)aTRgUajQT_$|Bmja%*UN$yLn*Xgal)3ABZrmjx?FM^Lv)aEU_)EKl(Lx@!>rf1@{ z8I#{tZ!3T9TOJe5yY6sS*YwvLtoGNHufMGr>=gQ{^P=d~o&)l{Cz!(1mMvFX<~cdx zAKRRS!dwRLs1@o7I%bBZEOMOC0(V@9Et2`%|_GMklbDtKnkVF5li{jk} z|CK-etm$h|p1|UJy!?-#Z^5n|Q*_0|Kg6q>zAWFNs^V#=v)3c$*UY0_9g+@xK7J3b z9@)BA&{s?>{JOcB@zG9mz)(uKuGg{Mm{TfWfaMaTQy>ymeR`ZoP+{rYz9 z?%i*7E=s=nV)jhDDPnTma@i;*&lUEc)wyS$=9rwobU^TYsmyV+IW1}joi>!_7a!Yt zRwvOicJV^di$=GeWMt_M51_nfYFc z0q688zq+!jE*(X8jcf;h`}TjHy#b-2eWsDJKNd|mp_n^eXqG~PlJ)QN<|;f+4c?D? zB3_#sURrncou!Y!S-pEn%Dz!cJPpl_ZC_UNO>bGQd$s3ZcYq7yB)QC{H*3njE>V5= zQGMRezgcTIr|kIh)7X5jgXzyF3zze6+wgzl#$x_I2U-es)#}zKS2WLxd3W7q%H(6u zR;Y#eIC-DZ(O|mbtP#L+Vv|x<%;crL%Tx^bcAY)=>|^?VzYL`f{PXVq{o|Wa^yb>H zv*-U+e7k8cQT_j>>K%z-ue*Ms-$LXk8Ei#>(#Fq6h zsQu*fG$84)>aL@Y3nTiJgeT3pkg{2iLx(N*=^yR=$7aPOiO2o!ytte5u2t`0YyJ4W zA70H*zEh#K_uF07W#0{^Uu}4^`L=hv=}b4nhtvM3x1VU}=<)JdB=e}n>B)>j0j4_d zCF`ZdcSsuw38;E{giLn(#QH71?A&JUt}QPgzx$|c^Zb>g&+IdiCpUQB5G^hCJ0|6D z<^cDBVwG#xttn_9zU)N zr+Ut>onxUe?M7H$>8%gSNvX51x6LoUxlFg>(5cDdRUBng^FMcO%FPj9n6&v}zpKvH zpa|UwGTKgy#Debb`g8H+jD%~UmCDeJc)}CH_TiXQ)icsr>zGg5(4EJr1tFa<-H6K;WX3CCbxOuD*~vJ^M%@+wNmM zmLF6dT58v4ESY$r8e!+q)i~ z56YRS)TO!5bWQjF*+*Q~-xex6d$oGY@AOkI(|u-bvTQA7=oYs32?#&BcFo=T3rh1f zPM-hjC@cHj_elHK$=`j2Bq#H}e&{n{rh%%VS%=2{iC5KGCNrwIMA7Zy6lk;!5 z=0d}rLECKY7{YXXT#ml_?xNBy)Yd8H5zE%Pb@3Zdx3j;_SDy-+yJ+dUu7iSE(Z_y< zdhXKj-2Wi|T!Hd(S0-uI^2F9j5vzAEs}>fXoVp|bz?=t@`Z=WUJ7n1|pR+VC;e%^k z*`=1w&aBOe)gpaI7uu=y(6SnF~S<5Z2RIgvP=ppCERSEmH-CKY5$dhKx84CK&DLePp-(SDH zS4eoWctSFp+EU3jhd6VgBTp8uj zqM8dHH#a8+WxN*^bq%}Fcvo2}s6}~}!NesJpS@;GtY;IRt&y$r>y`GYpL2el|77cy za6qTUpz@&O@|l~AxZen0i9N(`oe+NWh}p%q&h&d`f6w-DTCB{uyEXlLWxi|IW}CAD zshN2$(?iMygx9cDJXmd({?2ayqRR02%Bb}kt+G7lT>~#fPPl1kn9rjT%zpWrS3&ID zkId1VE1OR;sdb%N@Zr$HTOtQ1&)L`#W*8n(5q+>_rtT?&$O$(M1V0Ch8O)s7TbXv; zhsJ%r4*~!km zS>)2f1Xl0R4O?~F#Df-Zn7XOqAYX)WgqC|@0yv&I9G1H(4sv%8sfgsm=h8w+uFHQkpHdU!ZWEpVg{X& zpWdzFpQg1r`H(ETOZTdcPi|+~X#NPV`}}05to1GFj3Zsvt2lHSgt{EH*Iis{vMu49 z-D&e|11z3VH{Of6Y{pd(?yG=h3`vlTC#gal}WgUNaG~km(Octzg#&z+p%EQ=cQj)>Ya`Dxhr*C zYu=vpie~;>bMCR`vLtM>`L>s(^W?Fc28Ama9PK`8@BZsFB`N6R`4Sd2KKIqy=dN%C z7XGaWy_p-LY z7#zVMEWhT@zA&keu7YZ20-H1}SI%fl{mbCr70_^IwU+6RmKomH%l>;RJ3NiJ8fnCC zq`GHA=cc4ZzgC?RP}^qUvw%^}X7=qF1u=$mUZ|8a^*ma$Z%6;@D%0uf-g>NFf7P^} zo%cJl@cUm+K9}y@b^1t3lEk)sjjOMu{$LK^%~`+xD+|+sCF$*zCDy#`cP=(_8U_4n zKC{Zz&-9F^;YSI>_h-dsZdEP$nY1v{cEamDi?H-g@cE7Fuas9>R>oYlTPPpj!`{h%ObV*6aa3# zW50bj_7?EmoX@(~m(%>|^n0gxImG-T48OPvEt)ao#)6k^{yXcoM0HromqZ+3UoOAr z#LD~kJm&6rdX-u1o4x7lxog_8^_$O4IR5^7`IEVC9$PSnu$`}sap>_p z_hVam#+i7Z?(D_KX5V0uSRo{%vT1&(lJ?pi=Qgt4V+id%eJ}QFOHrxCG{c44p3Pko z#>lVxh-W(cMSal?0piW>Oz#gpN!|KOpp2_s+fqU9iFr#8m-|!O4Uak$eCGYKko~wc z=GFI~^BSgyNqyeAXLbIQvg)~-kMoRMbrm#Y*^bY=YF_+%&$%+;$$s+BRnMj6xcKHZ zWpmgkJhqwk%WGoWl!TxbF0K<(9Ag*6Oe?#;l+&+BUU)Y5!bc5vvcAqUaZ1r#6kPpc z$>k$0Z5EvS{Fi^f5V+hS`kQx-yMUVQtb0C(k2%CtJu7#ad!}c4vrzlJsQJ&#+^y90 zV)o4VXv(`=ax(8v=Uws>GgxMnWWULt$0(|tWgz(U?eiNmEnH5!+v)i{eq?%V$s*mE zstXdl3!cteUm3prLCZD4HBpal7o1(0GiA~nk*T>etIz#@vhb~~Q>gD*R{0r^*vg_= z5|gIS_@MCf$kNykYC^(yXHWTQeQ|=dPV3#8=N|IU)pRQl8yg&S3~cTUU6aPjdT(3F zG&P?B;iKxN3mzWxHavPt&?xLS9CB$=1_rO+9?Bi7KQft`}ZA!{^!p&BUYGI%d-}r)DquCP~(o0Rsok7dtdVG z4^`$X6F29{2s_S5F;o*){uh0`YHzgk3(acb!%Oo|9RB8@{B4)7kHwOV@M0eyyFFh1 zUwgxSe5x8e>yEI^{lBA%*Yo(dC|Il z!sWHKN8ayUxUlY=uV3v)S>Bf$OlM_!Br&B2``o>^gXz~yK4#$@2H~ooYb^W4zMr@E zQSdrrvR=SSDUJ+ z|7x3CYLz^xV&ggK@`dM!&+Cefck7v^ zFZ$zez^Kl~W>};seal${&sdna_hc5A9v5+y2X6w^$La;*9Ef{iB66dnY8@rb`IUA zGF=jrvt90n$*vKyd!YDg&cgOb2OrihW}3?GVym>pJ#<;*#U(mS>X&&d1ai-&I_j-j z{LD(N!(i4jMI~2VHQwd*KU3{x?f$%8Zyzk4cQO4tmssoFL;3r^Cb-VL)V{ER**bZV z&(+zXxh989`=?wr-rFg1Ows3?{GXr8=hrL!l705dggJEHWyRcwzJC8Ns+Q|a@%ca3 zzhnCPn4M1;FM1}wJT;X|#&ufsn!6?k_`hFC)eb+Fpn1wH|Lz8-1YH^7*#g?;`FBtJ zlALkl_mNq?%v|%CZyw#H`+9nNr0s)QtV?7x(q~zmJkO%7%RF_q<(1Iag?<~8_S(qZ z*K&(xI=C`q56A6o4JYrLU8?jb*)uD=!IN**jsnHKhXOBtIjvv7J(d4o!=rw0yM--@ zOn)ceU-*CWS0gdge_kc8Ua#wto-+5?QmOT&_b%UQxO!htVNZ)eFW6f znXLhb3?}~K^IqTeX`5Tjn-udsCl%)`p7`&{;?J8i3^ocpujbO`p6vRs^!2svceh?P z;Cb`KY9j~R+(mz+o~Fj?oZBqFM0n*VYY!h6W3zMSP5Q2-XBd6N3=S?04w#a5TvadK zXU8Fx?fxCx&Xs+u?2 zoxW1NVAi}tk2XkLv1XjCwqe4ANf9~6#E+|}>3sWZqIc!cf`dnntW59WJW;Kpd||7B z&yQ|dtCV$nb$$MQo@OiFT|F;h(p7DlhciMi5Yu&E~3xz3M$6WTZ z>no_TpIk0l;?^I$DBM1>Bsyu4&q0@sjyvb?`12_@X;J0Y|1Cmy)ul~l zOs{O`6lyO2r?RQIH@V`1;G(BcRs)W{y>p*w4L|<0C|I$O%LCNJcINoVwFc{ry@Z>3BKcUASozE>i z{i2(4oBbQb`Co77Z%Lf_$!*89{&y#oPrO{-rY8MQNBOebEayd{la)Tt+x3$9kRj(~ zV>>Z5eVJgxN)PtpUjhr>u!{LSn<)~?$Y}8V_55bX(208!0s$YUD{g(CTXC=XAum3k`h^=gwYXF6C)D}XE>L5x+?(^`actX`V?md1 zw4E0{IKyVi9#^5s(%*7~g{{+7zgPU5@o$dB#C@;7*B;DX($K6^ykztFEAN+Iyb$pH z{QdoJSMA7qey2shK)iT*`u)GUz6EWDvclGT8H#g0nDSUTw%wIG#3C)GHbeZ0RribS zIxTazcXe)GCdO5t>#%y|*CSW2OJz@fwYyYT;Dbs{jh}fZ14H5S^X1Hq4r|k^rL6u$ zynMVUvf+Y@ziA04o6W7V&8Y&{Zl9@h*bqKB>i*(v!MDDBUOsukUl}J$*L0pfTluth zl2L@NVWP6a;jr<((Y3yO`S+D;Q&Qw-?U)rDRB}*O zZf5+uoe{}b-)Sc~XL+q{4*y`aBgFYZi6irC=8w5qQy-KE6pHnCrA;`ZHD@0GkNXKm zubw>Hzr?y^lb-JT8SJSWORc4L7Tr3mFB{R5=P;q9ZPT%ZvY(w+=bv6KEdEe;PE-T0 zmBGT_?^oXB{}IUeYxk{!brliP>rNa=`Nc2)>S)6ZzXQiyHw2%(vj2j0+PvoSRXIz~ z83aA4+12P=>+HMq=*`=&6z9G36>!<(`%Q1lWcio6kNghwZtpK<{uTA^!{@C}}}t)PEVYzMuJGJFokhx&wmmufCC6Ui?@-d$EZar*7$JCy||w_ay&p7i$R-6)R9Wyg-(OHNvp-E&e<V~J}`=cIi*3O5Yc|7;rkSZ`Yc30=gSGyype}A`kj^&-zt}DzV z53q!no;h7IV@85@OXsl}36=}i@2vExnjHQ&}Gc%e_n!ftB>ko%T+Tr^LdX?|W zEm5AE{Z7W+Ucp5Ep3N=m1^i2{?N&B_@#pDzi++PfWyzxTT1(D}&gjwQHR+q^Cm?+O zYD~CdZ^Z+RGaoi_$=0z6IPTvNo0O!wtyb=QTls|P25ROXrIwxzU-8-2q^8jRLC5+D z$4VAA$GsBlKIwEJ^1j3UTK|ejPw9*0B@EYhbu@SiE53+1|4vuM>Z|Ber9j4@wLhoq z6yIjI`LO@D|2w~w_NMILGyVSjrH+Ff=)SqFXKHKGf?Frbu`Sk39h1VCW#yY4?G+HP6Of5ZW zyJGD5ZL#-b+=}OmrI-HL`Ge=*mAm(AYggV|yYu3Q>o4!0)NQsl-d!u5YQJD%{)7Gp z#V#spNtJ)vo_eRBs4kSATG`Bb-=n-mQNY8Rdn_E}?RyVL0B zrp#=!3oVR>`952xc1@@%I&34y-4W=rKGl9fsYgnZQqtpT5l_=s>8>&NUUSnT-(Y6! z9pS6W?OOl21lRE|Z zGYTCzG?sSoZ`V!u6fdw^-r$qr!+Y-|HfMic)aaLx^YPoNpN*Z>cBl6@ot$)I>Bf!T zxi4$0`x?*GZb;ugg%0Sw1i zyFd86ao6sfk*|8ci(QSl+rQzXT!N8)Bd^VpxMyapZYy?wj&@D{eo0} zmVVB5&#YEQtC<~BYTeatJ~^{EI&$B#qEk-eO#o+rIOIdQjLNe%)h^OL7Fx*B{+!f2gihjhp?{o==|^ zb)Cw}yxk{abl?|JN&@G|$qK_qVdn{x*}nXYGCB|NKrD_d*%_h1r}d>)X%v8M!4Z99??)fyt9cA-&u|i_O?B_M2qSxTbYxRlSn%@>}&! zUTpj>W4kB0QDuUsHuK*rd)S!P_f~R>OE7C~ae4P_BGc0-t5fMok0dl#-ro>zcCzr0 zgGk&n7F*+)UU{b(PR~*A4qRe%sQI6v&^gVb))MZ@IU!~h$w8@d)1uaXUv{%5bxVWL zH9pVD*Pc8nNVsSzFUhgIE0HbJAj?;MiJ?XHgi9IKlg$^KPu}#}kkMk^{y&S)i`H=X z_)H5s#VruGQe%PZ_LmRwyF^4`(Xt}JNsP<+y;2m|7~?e( zd~1ztzNhE*9zFGIdcms)cP=VsBy$Kq@hknhvVW6=r-Nz=v-`!X;#Utc|8*&Ra4$#w z?JwEMr87iCeTqCkh8bk)8J&?0pJMPea_jedEvlcJ4_!a9s?KlYzg31W+N8ufA4I60 zwD`?e;U&Y87ka<3WTG?om*%%AfBH^p`OM3mcyfk>)}@=$8(P|rFiPnyKHOmZHC;Qd zIzHf2nT5gi7>VTThYKA}ul#i;kk{btEG_A&?;ad{`fy%2bCS@S%!eJR-mM_V>`#lz zebwUpGyTc2C~3*WqL7;%vTpGPflD(RDz`5!^9f6ObobMa9?q$&`r~5PNlrfe)9|cJ zzKq+f&FlQX*J;f-^5=Z>;r<4d8t#_Pm6BIG4$fp&U+nARrZvMR$@u;Q8-uFl_g_W! zpX~FzC@Z{3dBxMk&96&x8+1E=y@;E_&ijUu?Va5Ep9=fz zrgQGL)NMCuHSAT?KD%_j*ZfP~7C$t7gBLL_v7FjjFLBvs>chfiX^STK7k?7rt*iMj zTIO>t$*66SVMUDh!LyIGc(3OCD0u&J(U-o`rqlzHc#C`ZY2EN zlDtW1@_)y~J8V-nByZvq{%?}I{$r-f#eZ>I*MQ=;WqJP^*~wF9{P?*4lCa(Tz-~~0 z8`T%szMHY;z>~=pKW_Zmm%NE-^8Gipks%`2zm-R<`D$BxIpk_Xv5>j}*SQ7X?{T;t zI8#1v`DI?C6$@(xV!Q)ZUOiO;TENBwXg2Y{&%<7FZA!Xe}AX%RJPA4{;$3K#bn<@Pa@<_eg0S7X?XYY z2@iv4?+HGAr*xj(Sf;>sG<(I@bd^6ou`{Qh)IBZCt-e)T`uVGhj%ohx@1uFmTn(2l z>a){`zie7J!(!*&9h>fVpDC6!n7P(5>*%SLUhfz#%SrulAs!{Hw=5U=KlyVjE+XPb zoqWMknR<>ZCH+E0d|_`BkE*oE>if)@;NG;ipv!drch+Z>7j3hR6E1yyJ^%l|_4R+h zp4ZB=+xqpyF0Pk#8oyonZ!Yor_VBp;->#7F*%AAvRJGb3kYJgamv6`A7_EBGr!VgO zuRYriuXVio*J+#1?vt;de0IC`bepW*mot^~j!iiK)+E8mJNVg|P`wS098=f5ObB~? zXI|RwOS=mnv&~G9bdx_F31>G-!U*4(TOzD`y z=T$VPGV$_ciJ4F5U4J{r^X7R;fs;!$cbDul%dfd*b1Gop?xU+0oo+ap!)wqOBa^Gw zx@O5d?U&IW`|osdUGLE5y6RN6#9rxJ$*26Ftge=2Ob5O^`FG@3gL0aK*JQm#J^X6# zmZsl4H?8fMO~=WVdFvjETZVI7w2QsTf4e7MLu!Y(x}y{OXN3h`pLewLO_rYWx_Fyr zGw+NOYP@P{2N)k+JsB>UecqDm?KUax+k3zA81uhPx0d=gsbsd$y%m14mdz@*H)6B2 z7}Qt36Unt=Hq{1IX!a!vWMl> z6aL>jJy~M<&(EQeEt}-0f3!9_7(RKT%B<%{Y(ny8w6=SHkgJ>H2YVBn%`S zc9*{nbn}|<{N}kT&soOP0}iU~5Zd)&{mn}Xp6q@RZA;!6?N-V*m{@REo#p!Drjwug zgq&E#ZFW{N|J1oYZ>h=WJ+@w_>T0=Hw``i8n)40nu!{O|v zW>xk_b@`8c+chS+zp-oJH2I^z?P(CW`F8uCx)Q6FP4|B!t@~Qud-%w1o}fA@pLK#h z@3`LXU!HL2%$D_sH06vFj2td~+y46EXSReOBbCtlFP|UOtr4vDTzO3;plIpZd8;q; z#im(wXvnB(_>1utv|A)@vSFHByQY72-q(!NtS;@Jx$IIKJVoEnm55eMx%s1@Awfxi zv7+$p{);OO4i(hjpMyNbo_quD2}= zMZ*0juLV`7u8f^z;qznixwBJRxu2i+@8nmzVWY#WyrOHfCySb2>3o5=%Aw{B4GBf; z29b$R4L-^w|1Bwflyj-RnRWT$7Kcr{uf8@;FydZ3|E`UMcZN~;lf^bawX?~^)_Qx6Ifk#Vf}i~r1+EP^W*01)nxei zDwp-WsppIHWfu}Q%T$(D?_Kbrpt&SKBkX!??xY;A_seoN$<)s=__*#(N;0qC^IgU) z9NpXYUU;ayceBou({F_KZn^%W&-rzJ<|H=Zd^h&p&6U}^e%zd9v!;Ae;-QG@3Hwi) zCm2a@&TLhBl{k5;y{lO73&FdIzpg*6m|vp6b@Swz`A$>w@4Q|8WVwJI!%L~g1wYG# z-g1X!?p<7$@z>Vs@R8_-C;*G6&ck2+dze7ML(Wwo!- zsu1CN3AeYlHW^=Izx=4M>J`rb}FlkrO*3YhIsIoXxh3_=XkJNib5JR( z^n{=bmjV~X*dG3OB>w2B1vBng9G2r<5T3q%ubP2jLQz*Q=cI|gB`=$Qi3OKW`s=&u z-eI;yu>m`el%=Y3F3_C%=G!#C9WUN&z0Rh_=5wUKXaCcR!e}JqKobiXYHAA@pYJbsjY~9}(#aW^36WThBTkc(N{}dd}Tx zdIGt*_3FEIugkj2Cm8uLFJ@9R;}j~k-hM%oMe^J0T^qm8=%^7o8dp6xA?d&owae%K z|Ms{0E1CRv!9KR1h9N6ix*dYPF{y2p@;TBF%XOHA~u6Pw;1lv-V>z%$vsjB_cUaIV9(pPG)EQ|CJc1vNUK`uD8Bqvh7S zlB|y9v-t%1XsZ4BbF%E^fmc`iPGmLB-!r4`^9_TY9?Qd~IBuypyll?x!2ex0vQy5z zyjU%GV};h$_(O(##tBLPTpxaW+v+~&!Fl;}M^2WmIJTh}-5mn~$sSSN&8j+x_{CkamZ_Vq^>rQ2VTJZGjhH1QOpOkLWdKV${c8AgW`PR$I zr?rIz+-*3i${z3s;JwpXJ|C zVN<%i^xmJhZ+TaQfa;G0g1ez=;a$j%!K)l)If;`jKd-(@c^t#Um?*4N55aUX5ALol=%)2zr?kRVl zT=cQ)Mz-HquG>c!e_z$HW!bu0SERn|V!nPe;>6L!Ah}(9MvJ-oven91PfqmMaOmRW zC(SZysSC41%oB{VgMIESE4Y&K?_z)4`bMu4I*Oh9{y)^WQPAOv*tDZjXTQ-mskMUU zf?uCMdt!Xvj!pV=aK`gyMWsFODu3wx7GD2*Rmo&(7I?61W8JE8b6BNI*=by%I$rVX&nIp0?Ofwhk z;_iEXhWXG%=Hs!tulov*KT+cmI%u_{U-hsdpYe_Cjl$~|>g)2B2&KAho1}D2@~_(_ z8FL?|MtO*u zZ`Wo|e(B{^f70goCVkcXR2(^x>#y%z)$Z&&1|KV~KhM9NrhE2{&b?{#=b!g#U#BD& zaUi9Gy}K**_-?+wYA>VnBHN!o&!4>@`SlL11f^G-&71d5+u5aa`Qw}T(24Vpcda=c z@zkBWr)g^M*HfR4^@wWUTX=o_oD*q>wuy@SXk?s!&SL!Q?PQk8-|yG|_c(aNIN_1h z%e2}%g-f^%Hp(a-H*0G1Kj3oZu|f0RWs&l-!HG)$n*KeMy<+t8j@h|nVT*+qihl8( zh(A7y{k5M#-bp^sReq}uY|g29W6Bcu@rA7ov;Uhc77d$w6Xmz_xF3GPb+uBXYSVO? z^&wNtm_!Qh+*!3RXof_7;{Ok))^Kae1+``fX7!r(-Jo1&?=VeG`&NY_E{*dzoHQ z@!*%=HtQ|Z?|xl%{bqCGLyj2&^Nu~bQ__=fwX!&o!L#(+Ghg2_&r3n;bx-8PT$p@0 zXMODS%PQVN{zsO1Ei3tO!!1Qtt>;5%?py{RzkofKzr5a5#P;8wtGE5Q%!2vZ!Z4+BKMSQhQXi49ZcOvSYFwjdCwzL&*<*`VlLme3~O!PUsYNr$4jzL z3cNa5&~uzeZ%x{Ctsm0@*DsCJew#S0|6-nfcaqP#)k_?U|2t~OxrAK%<@{3FTDPgb87$dLkS6|Z3Fuc^UT=u@v-jvXJ!|_-@n^F ziGg!s)!OAvk=y1P8gpM-7ulxY?UKWHE_ri%_~gsqSL+-Oy4%@)-O@+KE9;f2%C>+@ zQ(C=OZCIjF=>Avn$oc0ByTeNtw+V)Z{#`Sph{I*Uq<7tGl!nJ(=1ZGzpMhldM< zvIlWu)==gf+zI#3A=6eb2 zbGaTlg)U9cuKTCBUnOXLpysBv3m3TL=-LQMSLEDc-gsgw+oLFECU5h@OOMJq-rslV zZLW($#o2_UC+30kycUUxmh0L7ciyz7eWkym_Fg|pPM&YGWY!7a^_f;VUn6iq@G_-2 z9lW}q1l{_K^dAV#o$SkSw4rliwJx8x!wd-n!7av-YxMNZ!~5pu`CipB)teK=gE{->tD*tQQlIY-yRH^M}&7@~kglrNI^>A7+{r$}wAAi|gW{(T; z3}`sh;Q2~xo#ZWx{)~***M282eLMS}dPG)W(n7AUH(0E)4(3jNxomaeT-H>prJw_WeLBgVg#cg7r}|IgCx-Os&W zG$Ew6{!)&eH8nF&pT3cZJ2=C^n4m~6xBvu@Lq zYiDQQPhR8it?z#ckCJ)C|q`Z8rvd{y0gvM*MEL*Uhph>!RmIm ziPxq*eUek~V&yAV@3)CAIwdRGY@cx6c+=I;8M6Jx{`tHzH!hg?Z@Q{GiGR)MN1Afe z*Tt{)GCq`YXW^t-m(~f?9Vl(*b3D0m;mU(=^K!TXAD-(F`{Zn);3u8UFPjx~SA}WE zI@S*hZ`g}J;l1`pBCo?E|A}DZoXqN}B8-g7R0OhOUrC*L{HRgo#N{gw4)Si=(e+?! zSD>Il#(@?Nm+9&qRz`{E>{<`(inVpJHF1jitsEsjW7-s7F=KtPOr5PA5ib^a9ANu4 zYfY{d`@+`Xv)eA;6P)xdT){xrepg6&+=VUa4JT)qGn}-0@%YD%8S>K1X~$|C7bjfO zf3Fd~`jAuI9J9aaVPY#D#p&I*`|#4s>B?{QCtS(5P0i2ua@pxHP0~B>+ z_E;;fYgyowak#Mg;kAg2b&s|^Rb*C^dah!>KY_oNW!<)@S@~}g-J`11{^?wCX3gyV zB~doT*r(=U^Gp_RT_v$qZbBO}4PG*bujGG`@crJNV_t86t5+=L@$yUNUgduvd>*4( zjQsL0?dK}&*A-s%Pbn6-R+BEVyVKd@@7*sCMJ_V*t9krm4bQ$+zebil>Ynr+_PGbv zsC@a<;lPvq$mbbjuKcI!E7BL{oVDt{@x_ZzxQyMv@P72<476FHU1-x`*J#u@Sn)UwkXABOWzhlj4Xdk{{bqUAwi>EH-PD}XS z=Qw}Dugg>J3LKam=NR{Hosf+CFZUf=_;jtD7QX%$q^q=HQA?lZyv43eYP{=u&apc) zPJe!*FJLO)atsuS7nxut4F183Nj_|IQ*9=5DM^{Am|Q_zy= zVlOWh#@P)g-_=}*wD1Wsneio<^=YGYL;OkZHEI`x)mHA0>yv0YDO&daNAv18X~&xt z=c|2HPiVTTvbbp#Bd^*k;{+uorotDcfj$cxu2<|Tz4H1>qEm6+fLg5$2Nlxso)-+`T*JygJAGCW!}^4I=#})lX@1 z=xsV#!J;;g?@f$|;EN)6C)T|Ur_ZKx@ILlhs&}j8&-F!#O`q3rNSK^cv;NFo(2`nv z!aHAWhKjjQAiwLUt+#on%*zcG625a(V_MW+kL}w6`cx8x`HwV2@2ssqswaQv1;_5w z{ipbTS2nO8Ha_&k&pA1n?+|;fx96Gj!L7+0^8$4KMkI7iY)P0u;g_(1WPAxvT*HYO z$)~cM@~#E$@8Dp0^x|!lxF!?Zfj4{)%NXwRma(sUe6MG*;Ea-_%QFqaCNKZIzW3(V z?His;EZW&pm0^;3_TpLT?>SvFB9$Yus&<*`GT!DBZLTq0sGC`1@5ZG#-?85&Eu`Vt z<(z0cZN=>~?;mPK#Fh3ND|;*zewNQpV*VSNI78vi zi@t5M6yi#rO6n?IINW}1PU5rq?-F+#?D%D}+n0IY)v#}xEE(>c>01I6|Fh;v8YL`x z9-lqI<&mk^mTzjIOEi~k-KG6rG$*_3SKxgi9n&SzkDu|YCro~MjNQz#@c5i(uF})* zYq*%nK3Mkk*SBv9ZL9A8{_xjqhpl;=h4J@*yga?QRSOvn_xB54dw%fTD7VQ&L zWauzkrKCE4*3|zW1uGmM>AxtPtaxv|>6-8D;=iKrFYj<*JpAR3QwCexgmu1W?|l0> z(d@wS&2`a^(U+%*-IqF3sDFH|ttE$qNy4Jp|FY!Fd~HK|P79h}Tws5D3Qyjy-A=6r z!uF>p*_SWe|NOW>_1_ey`~F8=f6sdT{bGO%!v*J1iCs!@H7>@YYG3|+={VrAVnIe% zWr_FI)27UOll)W?E;Mv{Zsxe};=kpaNT#p{0pJI}?BM zrbzERE8?u_FL0;;r~00 z46!(cH;mxl*pYb?XC~u9ckr*p--cKt(sy`tx2L zpOh+Bua6J7_AZrRk=OZDU%GMkn{=M){cB9K)-+ANrmy)yD8%HUd;a;28+t}gjm;-0IGCX=^5By#OBY?ym$k{emz>$bcjQr; z(yK@g@wI`)vn(?AC-qn;Uj8GsEZ_6g=BLiD52Vh{EcN{Ps+dvoq6s}8c;7F^OZ`gLL3tQ8qX znxbpIPrPr%{<8U7LG1+~9?aeJuJxfND$3_n1ytc5Oz;>CV`rj<l2Yo%L=nn%kD-y;3zed42*v@5hwvrE^Xn^Dq#ad~~_Q>?z;= zmOC8YqaJ^5?w|4nPk*00c`{#C?bROBpG$RWZGZl>SLN+voV@6}!yC)<_g<^a5Mfk% ze&EN>BVEz!=O`9Mw5o>imT_!aD#|Nwp=*(O@@tgY)^DqS?5-1;|7ex=nPyYrS#~dK zU;g^`r>V*{(k;K$|r=9A++91e?XTFhQjXaDo- zhwGE?FZx{kr#5`O4O<+~j6cC)ldtt{s(jv6WZ|R3q$bWVxpMF9=nst79zD^#qW5+q z3;(=pmYH8(SNnu-lU=p^PNa-ljQkgcNmEa7rT$OlcTCx)>0~#B)$mNHQ)`CC^G!2X zt&Q;5mDy#{_Csy|l$?I`*OwV4M{ilgAb)tf+WvqI8*0|s{4|Oy)mt9dDH$hvJGA_| z_j7(GwKXqe0RI z%a<1}7K?cpIrr|8|L-DoC9dUmWrvk*)|OIzDgEFl?0e5y35q4mYD*7a`sZIKWmO?{+GEv~?h+3c;oRI6)6e<0a^5ZdK0(1@ zvG1QPSNk#z951`<`5nJ8@K!O4&xR>B|IX>1W%b#@{QAT7uPbVQ>jr%OyZz(yHSP;o zU!C41z|441M&i05M^!*K-^1cx>yt04Twm%QDfvOk&EozNohRScy;zbMFS>Ny^~b-L zg&o<_(tc9&0<(JEX|~ncT`^ZJ^b}?=7+4qKMB4zyVPJF&UH z-M7+)v&Ex$-XCe(J2#eA-uJ)ey-$7e|4ucwoWjE_GNFE+TICmyJq*^|cZ_L9MQFd; zEA<%0$tmll*M&Jvv17VqbLVQdaEbbPL#3e0xj*t$l-OKb@B9pSbeQGR+^x$GDBV6^ zu`Mp|d*>0aGWSJ!Pv;11IWTGAO$+-&Y^7Sa0!-@_(wP7B?DF_wt1#n=-&B6x>n_gK zD>4@apKP2IgGszc(W&nm&utIBO6rnUQ&mvbN6p;_7JWj~y%4+KCnwRF}10={a}FaecaJUbCU#wdLV+U<-k|-6lOpphHhYV-;AJM2yJ}XfDZZI<#lLvg>bz5H&sV;5 zsC+&9csy_L^AF->Tk;l)>HBaU3@p`seWQ{s-B*PmOOeXW|~`g z=tdkhD4F0RPwh(@NbNmDSrhW7<2+YPXblocQ}uFktEF zg%8cPO*4M;zKLtDj0;PGyp)*SwRX9{oqZDyo>7@K?Sz5g6(hyglLLES4#hcyD@XF!SJ}HqZF-iwpACS3XFY`913Q z1o>SH&Be>apN2X3n;p3N|I*qCd`}Ht-i{VgS@xyVX!(TSm$x`gSMU)qkE;5$aQkfD zA7E}c;HZnL|-X1IX5&#(0x_Z?k+idpul^S;tb z*7-&UTDG-W+l99+`)A%bM@`B{;L+DI_s9n+k!=%xFBa4bzI{JdM8(-A)uJxLk+m;6;J#L#AVP?Fum;Y#-ufV&V zeRpMFYJ67uQIcNG*nV=c-nIA97bDL&|9HW1C~?!7UkSX@@|Ka?oLIj1GOGP4xK#Em zk;B}&=Z4)^w!3QoBMlDPW}Im7+>~o7YtFk_8JSrOz;MJ7Jet}^I%X%fR z^qtH8eP1m0mV^6`im3Po#sfqSge}3NmfMs3lWSR4hUrj&g@>Xk+ zBD0!)`pWk$uCCb!%T}L0({;2$dY|ffmpth{RvVvf$6GiZ8s!D6o_JfIlD0bSwC{{w zQ>W?=HNQD^GG>{D4>rcw9bl0-boj%hbw=Ac-bsJ`^jpWyEwSm#qqP+dv1Q9jE^HTK zzt7?GCvir_E&;V~=K`74Hj9Y9U0$y9MSVu0|9iidZi9 zY767qY2PDoYgL7x+5Nb-?;EpJZ^w3&x41Gt3~+GY(e(L!dJV_NCN`fqHKw`UU7P+j zCmg-{qW{pR%eNAxTIykiyJTs|bkahE@AY-)_z<(ubd;N8Ns%4Q$G z==)2$x8-GzU1)f|G$H9gib<}X&$`&n=ME++g?8V`{^dS5dV3IuTF|Yv>+R<|#Rj*% z&D@^1usI<~nLo#%fyK&xd-0EiqMR8YY~1v=_lw(^pP%V2-=x`g{v`8f7moP_rS36b z1r48F*3&XQyq&ZC>%*``kG^#(e)pcqIQjP;ulIkOWz?$PnKn*}_E%Hi&pex9>dPxz zr>MsZEqu$J$+uQ5&M!}Tn#uL|cJBQ%WSG^IO8iBB6uTdN+}U+aAop&lykPP#)n8^C zR&?2YDM~w#^4woR>(-gc^R7I||9^Ss^_(vcpLIVxKKcH&^VOg3KK~lLBKzAG^~v#k zi!ZlbZHd|0ZriHmAavlc`tb(OrWuUFu^}M`mVEpJ(s?BR$hS{_%gaKR1zvAp4&bzi zyC5JZ@so|a^V8q$Qg?Yz_cKmD($*;;nk#5vxc+6@{{C}&(}G_lBp%Aozpj;_F|*{A zRQkdhC)7m^7+X#--_88t@`Ht&|Gi`8fhVPwvkPWK%-X&DS={2otIs4hb@e(3_{Pq5 z{=y`yR-oEH<-McDk5?zRFM7WEI)fUU&kms#5xz#+U+-i$Me-Y**s``IyzTtrmD!mW z4Iau#9NqRMzvlA8dz-%8Xz*-0{DkNEv;|>zGu398#LSvi-7Ar;v2W|=uKy>?LpWYZ z*|HbUs5zc^$X3RGOL7mBLFdV1f@T*JlT!Ive2zrl*tPlM&g%(kHcuNinnkW(Amkf6 zTP5j@4TGBN!;g~x{dXkgR1^uh3m=*|!zSl|N?_um?yjJ>503fnyY)sUbk?M5-m=#p zAD?f}|9Gn8)h*pu2Q)%U_}M-3zVg|;|8TO7N7}&igZ>e(B^PEER$2QduQ|G4-OJFx z&V7fJOoN%+|4JHMG!D^N;cEQ2WX2w$ZpO*tVvjG|E?XWwyU_2^;UfWjN6RG?kA1h< z@?v34aN5pgoqufgOD;5YdL({6)w?2FbHj}i4^ z=}rIoOQkDUZ%YVke$}J+iT!iRwicclHo09g)|}CMByY?s&7S=7s8Nxo@ftO~34JHZ zzOSAaS}Af(@@CT)uLImuO-&zMD*bikwW!T+xB1u2eV_P;#O(93dt{Oz^fz1P#*E2# zO~kkE@TvT^_I_>oV*6)nUx%&QcZ!=cvZjAxoj({s>|D}a_l+#_Y3C_|6vdl zoTsjm^ml^UhicnB*AG{!UYis)D^!SOy{3lCzZj>}{aPFxGK@YIFBUKg+xk3zCC7H# zR-x5+ZRX0_m0j9hnrkB@Z-`u!Po2JoC+v!Ugo3|x%zBg4iyCe-Lfc&TR%_j zhyY*wmJ7GHO1v>GNR*w>XnXvZt@(|J6GxkWhA234Gc2*#yLBz|1hWD&(*=y3cC$)( zdE6LQNlz}FXut01@%bq?jV&4|@R4>=+ z-|A~ZI+|=gM{Zx?OLMd_Q0kCB!DX~L_Z~~6&dY?b$4&F*q*cHDHAgKnf9>LHUwCqy zEJcLaETuPgzhK%t&2d$18vlx^Ti0FGJDETC#?o0!SobJi4f*4H=7drOy`qR#K`@W3k#svhPfacRjLpru zhZ1bgPkSnS-Xkq{Fd9va*4Lm+x;&TU3~s6-m!r- z;Xy%4g!~F6h7I|K)4v^l^>95)+PVvqoHm<%h_sGo6juCXUR1;`6Fx_ezeJQZ)2)80 z>h)dK4$m)08|-vA>HA~1q3}h~a(S;y4Tgy~%Z{DVu?f8WZ+X-dr))1avxPEQJFj0p z>QSY==Q+oT1AGzQQerX5-m-UZ3@Ycdf6ioV_{lQaI_tpi zzOQ||wya+A&}HQ`ea+`_9Gh)^@3r3}czZ*S8N?5Jif762w;|C38&kYhb z{V?JG{JXGQjG^PjqaLm`ymma*g*CaWclhtOI&h%LF8u)i#dRGgAto6))eWV-$j}_Jr5j_QSoU>Op+7OJ@6!^hbJfKePq=Z zJyyRXH(BPY#bockx54>BZuxJqHEN~mr&2CnNZ7P}$2|MLW}#w@>yITiHJ4tOzoB1$ zzOLN*TeYx;T_4}ByOJeruAjK%IX^u-`J?W^6b^aT&*Ou2L@;cP@moRV|e0=MA+v1R0>aKQy#aEm;Cu(If2L&i2Z8ShK`s8vP=D%Ij7AO%j&r5(s7P2)}ghHQ*zm^&(_b% zre9rd=YB+2HgT@I-GVbFuS8`ggk>hyH7ieKaNzhUIxkT~{?);W>PyZ>)rnQ=-ar1a zON7zYK|YfqFWsYjVym&3$;H3bjKVIQUAe~_I-OP|?2i5(IWu*_wqEzu-$PqAe~X=` z!MSk3*4FJ^Tf-t0O;}FNn%DTYjLpP4S}blxf@73#OUaAe^(U`X-;!bSc~IqeyCg@P zL6w#F-@PY7yOZ6O4g^_;PU(Kcv07&T`jVc-pJW8LAL!?{|0|&M?S^#Sl=|S7>k7_uS>2SI({z4g?CZ6Q3LEaK&v|>t?BI?yg&*amz*NN`Cf9=5DVt&&LH(O43UAz9|%J~UBF)QBt@_v3C zey`}`sS{tFGWz}Jo5nujcP+VFap|J3_iELS^hKI%E{01*wV7uh`t9QUe%r^@y4S=H zZP>QL^Of$Ec{5XYUDQ4k=`T5P68qztEW;maU7pup@`Sg_Xv_-H@ZXx0nsE3?W>xL4 zwI?U{obqrM=D!+sV|rKA=G{9^=vck9|9bU6%V*9w;VBYtOy79BOWwYzqPaef@$ln+ z*Ihdqg>Q;$@Zk7;mq5moic9ZCH6%LXpDdg&tdvH%zoV z^+z>yNr^T042Nz0#`DvwmfYLYVAualx|wZ--lB`c%1<$ED{j516!ZBkMe05haVeHrY{g zZ|!lL^}XMmS?#xaSz7)YrmLZX1`opp1m71n=#rw`>dYApC$)N(T)(4oN%YGH z{qidfDqT{tY%AjCUT|W`uUeeSu$4)3SvQ;E^vTnHeX0C!V4Tpj-`?QZKPT@tp*Y`F z3&W)p)E*Z#an;3Z9{sY(;A5KHuZwCrp0n#}G6KHt3jN<^rm?efL;VWBKX+J!7rs98{ia&Gy$Wbh7t_=YJQUY4BXJZt)fS^te;5A7oQE&Ix}S|RKbUevbm_O{O6Qp7 zb^O$p{qo_)J~f9W8#%W-nJmbE-`DoFeZu59CRHKRZ)t2{`0to@faS>c!d2HJPQOjM zta$G=culeX6uk#0nwBojhS#G2jTZPF_KaCYy}+m#38@0ZvF zX4PvME@$?;&T(i@O;pbPh>RsdDG@zAzrRO$thBD2kZ(0lS~QC1f&DR_86lh6@~RH2 z-JViBr>pG3uYgGx*WOe(vZ-9mD1p^6&RL@3<{vc&<|!R7lk)P{B{gu~zPss}PRmb* z$r)Si`Gj{du~$uy4~#RN5whug)J5aAg?9f#FEJhYVBfJj?ZA@lSId_kJy(A})t=MC z=AZv2#Ws`KI>+_*Ze3qs-H|;h!Z(e7^6onJc;64&$~EhKmioGf|L$%&S!(vrte-6= zQTOws5S0X`ke`YM)-9V)&OYAN#CP1trA+li)+R}VlR^eF_bWWyFL3&@j8D@ZwONG+ zSXMI~WD%NJ5n{LRFz*bV^>8?lW7=gg~y)uB%5jihn#hVf8)1LpM`8 zm$60!HW|!465%T(qc+LM$!DTg?20R)OsbYX(^{fq3|@Z!!7$nNuJwo8kDiwm&Ulek z&!lE?R%PSAdt6RF3Otin3(lCMtu#YNG^!!DVLIdFBb#R?eo_;;elb15K z+BbE|D_Lf*S-Oyi<)@|KljXTq|6a2Q7Z)7a`$Q$z>TkETm$UK(rX1EiLOg2uYOk`K z)chZ->^;I8$D}59fJL#6gMZ(9hkpO?-^w$5ddy7Bp3OOUvZT=B#QDHhu_wP@$2X!pTNm`{ycxXN_m{5-AoIi@R@Tru0hpr*m0mh-)RO$&GMZ)59{t@b&( zvw9cqJ9di8(BOr$QLq2a`GO_)dR=7X4_x*4x6(e(p?kok@g!T5r`s)t+{~+UoAC_pXIW%yTKrAB9VWB-Brj;A+yHuE2mk=@?M)M z*?!_%b-a^y$8)J|kXQ1#wmy39PridH8~Zop%n6o#xh7F=-OL}e@2wE^ykW7|*XqN% z$40SBKj+NYePy1GVSG!jm-T^{dU z$ULRxZS0d(6Zq~NSh(a!ec+Bt1_3W!OJyIP89JT6mQ3E@9&wbVN~-;&!d|`G5&r3u zxucYC`&IKUzy00J`&7+_DS8(-8@pXPXPo3ZPuncP$k^xF#cW|-HEtmxHI)|q&pYOv z&bgv@wM3+F#)o5#eBOUubvbV{FVN6fxO@Gqpcr|J%yrN8Y=w^rmZiIY({3`*TX-TDJ41i!Sot+Us$sZOMe&pCUW8E_$%KP3Xu?XG|7j zRx>`F^7hpk(U%n$1m~9sy_@al-#vG=x`U`=&^nQVMNzqYTo(ft8ExA8{o(K2eJdvJ zdfnQ3R(sR@@4m-1bB^i%+x7W1`(#V+53Ar%t3f>sGl;{CVVt zfulma@%CvmuTEUF_+Om$j5SZYJ1u6}@CrBYeHOCbF!8aS@9IY{E9?Rtbtoi7yYwYy;C9~CCcgWlecHeGYl)GT_QF8Xo+{i zWb12hcRBW4-*s>5#$w*jrG-E4_I{f`C(rBsVjeF4?9XCOAIoQdwdH(Uvv|+v{i$nb zetI7k(BJTB>ghs76Ti3(e-iVm%F=>bW3_G6xMNfELbw>(H+>WfZZc19)0*|=^64LY zwtt(mX19BEPOQ5Q17B37KaW@8q|U;S8P!2W5tfnl3k_XkyDC%bx~3(oF?6OoOqjWN z`I%pbcWo@4yiqT-n8l@F&z3cZ*34j3@!Ykv=k)f4b_>1*8?&Fe|NGkE4Vg|Xvlgvc zG_hjFo*xWG2{qGJ@7%DsXVI?s(w@m{4(E0+X_>uw{j551CI&`Emqnea&#vrUvv@*j zS;_bJ_ttGcz|8#a;_-c(SI=6rdex}|J67zy*w9dazw;r9j^XkU4&+nhzxcuOC z>bjr*|9;x&e_p-rnBcb3TZPi9LD!(a+B>IXU_B=Pz<{ za!N`{k&%(9sj1P?(NA8ye){%HSXkJ`jT=9F_>h&A_4x5)H8r*S&)?6OG2PkO`TY6w z2M->6`SFLgw)XDbdu(iMUcPuyu^?m#HZQi_j=Z+mWZru3({ri+Apc@$=ogcXuAYGBh;&`t|FpSFi5hzyIgY z-;*a#-o1PG(xppJpFVx`=+U)n*PcIr9v>h7>({Saw{G2e{QB>|fB*jdXJBBs`{eci z|Noy)>0igdz#vr;r}Wxc6-C8|(GCp) z3XD!1=Ra@>%sW`o*n9Rg|GNA9J*j6c{A3=p*|Quw@tC2r^E1P7w;LW^1uCZ}>GE*g z+_-jns>MlBw?}X zi>G_-Twn7si~V%IjLQCxb)Tf$C*PMSQB*$pzBb@zuk*>}k$h>-i(mhFYXA4q^wPZT zyQlwG{QB*ay2sOL0qZ~bd$jT-t(bkys5Ee1+$o2>CQCM&D|kLp|I{+)hlt~+>ehya zKXLPRn!D6JzVNBqead?|$GY_sdaZx>wM_;&;5*~f-R%?J^G&;N9Z|PlVXff-+eLrk zGFy4o;~RQz$0o4N2-$sf)_W}tjTcRur|jao<$NflMxwOeW$(NBvqHXq?AQJI?zlqy z*WlP``=amPy}R~0bHbPZf4bw#R^8D$6L$6Ww5P65BJb?g5?Rc2$l&;<4yBp9C-OHg zkmJw}dKMY7S4--Vn9&0FqM2H!d>4oQN#(wnWRbdfVN#2i>O}pbj*~4hu4$niHCI1; z3O(en6)zyC68|;f(_QD2<^6v9W@M!NT*W@+eO zVd36&to1HY53-gh+S=Ogop*Bc{Mv6fZzf5!e5+bi_xJVvf4{CLzH)onYH#rMj()2D z`4yikU4HKEy#Fr$jik~2dB0OXe7^Vp@znd5UrbgueG!`1;wjnjn(^+VS>KQU|50$h z{r|_~m09KrELooK^J-t;w13li`*VAGe8}#v5&05j@3-%7-f;i#w)oGE3Ey>)t`m0`sT1Ju(zn{z~xEgM~6$^ZNrlpM2-hkH5dW{5bnwt-bS3 zOiH=_)@5bYq1Dsx-FfkJb=yS!ot1W;AO5cXVzYYQy?Teb{*ZkSL|i63y2P&;uR0}T zLe15LpSFxYf9XxP(N}W1clU7_lh3O!AqSf5|NXO{Q1|~hYlwo#-6!e)Kl97i{dg$< z@AFMo6NmNTu77`(|L1;LzMuE?yMqq4d*$us@h_13AgOZ6jb-Jy-{J=ZS_?2S92 z^Y8Uxh5g@4fDPWu>d{d{}T`@`6R`+xKN3U2-O_B*Dj_u7AeC z3!kc;o_yyBm#wL1tox^NubzMJ{&^FsC70GLJmdW2JIl%UoGolmx?K;QZf^=)enOc+ z&2MVg0hTi&wcBrhI{shiMgPP+DYe;uXa8UFW%f-e#W&aguXosgt<&|#jg`L>FEjdF zn;IV#vF250TtQ)CV*jZ<{~mo_UZtFVmnVA4{22wW@9|vCSW@=CdEIw;_5IdMZJad2 zPtCQ}l0UHI?#k=dbKm(2&3IF6eegu-uIaYFrMo8I|MTpoZ{CB~W#7!a6Be~>$W!Sk zm}I=^gW@AWe!rgUuQgYjupOFvw@T>l+ULQn9Fjju_DCouPwEXmkzVp?xAW8FmaO+# zW!-;HEV=UHYP8ShZBMM9pEK9F5h3yS&>z=_wv(SrKY3_-_wcE5HoeQ5ocuBS|Lyy9 z@^3l&{rwf(zZ~=y)zogNvDIYx>+$I&E6Yj#b=w7gR_$3P7thsjWNA)A)^Y>KSG2BAV-34GjEd(J-`7X{JSX^szl&$;`Niy?zwE41NZx!(ssF>*Ur+3~CNoXy z$(Vd!nbF5=;;Zi~r`d9I{5&lGkKuT_`AUxYry2}?$_gBEc`7q)*WATR-??|xmN3nb zd2`YIT}N#F+e_)<-{H{^qNoX?D zIdo)&yxWv~j``=!xvnK%@-mk2UCKN2_yo?{s)o)uc}e-*e|JW-yFQDNjE_p%xFh6t z`ZBB9cQ4vz=&n@!ZWy(3arf6=yU77R_dP8BY`dpsxxS+76hbO7C~eqXKre{9KKfp9}w}acXnA%YIV)l6C7D=1+4EpLl<7cU5tJ z*6&Y`rha@F+goM3&9PT&dEM_zAydykU3Yum#vRdn7+&6#+_5k4^mpFc|9{O`}9l485bs%t&0Eux8C9Tcl)~k zRjrrL#P?QR-!DAl&u=}cw(E~)@!WdCkTIE6RU&QKo+m0{%g@VLurn>){_2RvW|bQ{ zy=Lu8487|VB|oj%Q?uFRicM2ZQIpHFcPEs~7YW_S{kiXCPROb9jqhsTe13ZWOhNvw zk2RT(xX&+NGjEbtmwJJ(-~9>V23u-A3w%1d$Y?hE{r>@WU##1w+xw`G@48}dU-jGUaPFGu|2~&PEc>qAom`%OYwteBLmrO5 zGc4xK`eDqubZG*gD$hig-zt3f1NJOD=)6>Pg=fe2nXD}Q)82ERI=nJ0>xt&W1%`7@ zpOW^9uKjhQjV*QK`RzJOuWWaTi;H?89l6iHNOIw)v&tvF^X?0e&tSSQpsKu6-Sgyc zH{JU(I`&KcJj{y{RO3~(^<7lc(z$yj=jZ%S7GEz;^j2E@b)Q;X!sMHen>U;|@j`C? z@jEOvz8-daqmoUgDaf;3e0|tv7E|12_P=ruFTITHG3(Cp-J|m=i|f%em)~ca3TCPA zl+fDdc_ORiQ>FZTnae*ys;2H{e|O*gUW&=guLVU_XKc0hM!pYQS;Oe5@xboW*~OFd zpFN%YX4VmRAFhg*fBE(IcdlPK-=|La0L$?g!7_FWtvGx_aNV-aO7YA~#l$7k8fF=+xqbQ86Gg^76^fnh*VI0JHqBn9`7_JyVUozQ<#vje z@*1a}SF-#()cND0@1Mh`zu)n%o4kDMR?+vY!42Fgk2q@sH1vdobnZL9Zss`dedLwG zr`b(U%sD^VF5dk=%(#QEDIxog`y?p&dj!m` z^h^^!#KPSw!ZU3KH}_d*{l;mb+KM{PuZ}A`$x>BR3F0`OlcD%o)T3stTw_L=Z&P%K zz|+Ya1b+I;DNb~$(_S0ozoBNm)@x2Y~gy-wCnZ%kLp)PF<&{N{_v!-T$D3Y z^By@v8;f&~CAC_X6?EQn)U-L=$t5W9L8$(6!nuH-dX9Cgk3W^_tvUbqDZifj`HUyd zj1_Iu?*H2G$@cK+=gl!|4}M}#zoN3B%c-}>e5Ih8p7=CLO>>)_EjmXhYZuJl6V3DR z=1a#z;zyoMDr!yfb>&yRuR3qZr|4McQ`2KyJ8G`4c(Pm0WncD$Ki33)3JI>euv#W; zpZBbV%fHrritSgsZ@T4=gD%@7ff+A2y&JALTRGb}o%_DDuQ@)+Pm&A! zcizGI*}Aa*dp>#I<(I#yWzfk{T&dy1@`>e4?7=88pRD2ldzM8_T%kTUL{ipOt1Mku z7MR?2qiKumv$cksBe(Q+UcRjIr^W1gPM*+N)})!9Jndlz7c32v-uPAJnq>Z_iBpag zEV{NS#4g{L?Md}J<@>@a^EdRV?BCis-M_bM;gjl?eT^FPw|liDXvMFYvFw2&!^xeR zD^4FNPxr7tcA4vku)>PGsRlnH?X8@lG-XQ5<_A-MDSxm(6wqk8 z{#oN9Za)o~iJi}S?30UAQ*(1ub>*0^`1~`R6EIOAE;9P0JX@fu+R7;^tEO%W_3~@1 zn043VleYVW`!ZVdpUXSetyKwL`A4Del;bCD=O^9bobMJnJapp;wijG@RowA4_lgsj zRxNXIToduBVqb^DCyvyKJt3=RU6JDFsyX1z;dA8`S840%NlNBfJ&RRRn^=pTiY$Yk z>`I(rvdCiQ9>wzpj{OeHI#yh~em)_~@5JNz5f)m(JkF_C=Lj7%_UL2aWtz;T@L@@Y zRj%`dyLKTN%XJpA2<=o@s_hz{D?KU7OGt*pQDx_)H_yWB9)9_I>_TcnEdRE1E45qf zO@3~;S;|_yt7XE&r}ht~+CHeg6W=8e{9w(OTXOTFLNwWe-UlR4c{~z7|%S%9AuX)d|y$J?ax9)n?#*w!^>{?RWgn;V->Q6KB^WO{2 znR`k}fcfWc6W)F6^g5b1FiqXJeB&BEN%a@|RK$WE=h`iL5V&IVq8Q&*yA~-eU1=OJ zaqir!Nxh}JPQ||BIu&|oHGcrRl8;x6mviZLftk}!>ZCfiluwm>x^B`WArFZ_>4X=n zRx{tZ{xNCyD$@fjMP66VR>nSQ%DKASu0z+Z)L`2I?t7fO^lu(X+GHxmdi6l_p(U~N znM`|2)x0yGe9l<^+U(jjsnFD#vbS0fG&L1Py=VMnVG!PYIPg&cgU_obQ`w6rdf&e4 zD(ieFJhgUi-+?0!1GKYmSGP``|MuCG-EVkz?rZpTUD3zm-Pty)jG0ku-oF2DX>6@- zUHt#{&oalGyoGFkVFOO5Ue*Q|xVrpQHAJm2tZM`}sdZq+OLPwpSe zem8AeV4CTzwnNv}eX3rmd*RXBRc|JlIL10$3NyYSGg(4$N|*%ah2<6=y;DyFRqgiZ z72EOj`u=~9y4UM#RR4VS)^mcQ3`fw0M=~#z4Kkg!`>f5;3+Oz}b@$ydJ<-B4%aquX zzcJy9wKmj*TwOPLwV~{RB`X|U!$h38LqGnFUAnSyZ%&?y=dE6wVAr(^*9gDcQuW$6 zoo{J+*7Y?%Kd6R+m=a-Mh#;{D!OeR<^Z2OTSwQd&FAEOcN3Hyzzo3dH>Fm*O!*Q zzoB6p*>U?uuK}Z;LY0EUMh2g#i@K{PTrcCy_6ey9oxa(o=|^>{Sj?Lx`BzTX?rjte zvyD}&Y~}eJto?bH$BO9d0hO;;3D3HCZFZu`Y`s`#)~-pRAyNx6a(#YeUp}`)-fD^M z=jG{fmGke}ivNw78oS2%-^!NwYj@7Zd^u;f@5ayNBK>iF*H)Ql=Q|zJoNenoZ$i#TX56qodu)S#aMa7a(cGVo zn8v(&$FVagF6za*huJC{@;sLIYrNxK)55L8S^QgQ!z)2G&MI@x{$0XiY_%(Htqy;$ z_Tbf4x$VXWn@U%OO+T=iw~Ujqn>q2(CWRcYCsXs(=k9!aW%t=r(Q7t|FOT1?D{V;&^hwiPX~O8U z=52A@%x!6B7rxp5_v_5`y02cV<{o;IF?;LL^M*^>NeNH5B&B|9KI$uD_H+J!1&u`HW%Ko41=Bf9)D~Mv(s=`@hXM zziNKhYjv&tJ@@dr!!8k47uS~OY2|&_^!|D`WvQ6u*Dnq{dWWOJcv|l-4ri2(Y&h<} z@%=}Y6C9Q%oPKLuw?90-VRhn#&mpmUrOIx1tk(RJ#x%KYN|7_GOmLR>hHoh%YGP|V zDqZ;Pz1JO=`FJ<{`@X}5^3%+{FJ4HmzOLV5=_sGip zPEY^kuCde1A4R5SXiQX`q2aURPiu);p3MwDWNBjOkQ(yy?cHf1E4b?C zoPN0F=9fOF*{0d=%z8de4T;W;neNP6n)805XqfRtog4dE!}pwd9ldi+(SMC0Kq3EkG@;3_SWPVI{xO#JvFLUSeHTS-iRhK(w%{+VWY0ma)>)W}#w%c?< z`LC=zE6?k{Z|}LAq1WEM)ydd+h<|VRnz;OG@5WVorDje2<`*EnG-~(S*!OuG7nynT zygzmMon|iMpPN>1V5Jv|})(ak*F;%$q~G+$o~zkQl(LFB5u?{+)#Hts&GXFkJW zc14s&QnlkegHq8`W{*PrlT%h+&NS1=j-Ko19_SL+dU<8Ji;IM^U#WHMR4?IzmompV zHXA&@+G=p{)HRh0mXiX%A3Ahs!M2$2!-w>impET7trlVs+4Ri%O>0`IuAH~d1Se*L zK<5_L#7n;Jm9bmn<95r4mHDqcelc-*VEg2oHg|WiEtP3VT6B1i@7<|IXAUM6YD}GQ z;rgr(D>=Ui$bK!2`@3nHN>-jil1`tEaD+(ANA2@9bwy{}G9A?C|GZkqCS7(x%`{T` zhWDFmIqweWeEa40)+@mKc2S4fPpceu>!q`9OMi|$bIIr3-Wl8BvA*0hs7oN{xPU;C9Cabx@U3x(VTMN`kz6sso8U1b`s zAD5G->dwwTnJemc(bCC#gmbjg^IcsV*DbD_f9^@P>T@=k3%MM@vrhi@PLFG5zMPp- zq-ro@@w;aq^Pd~`cNmzlE;k7^voJZKDx6r9b8E}d`shE~GcViKr`caKIOOtMaf__{ zCicy7cV@oS{ZMwj;CB3FBZkQ?WkF}FbAHWJjxL^bujcUoM|0*p$4o|vBe-L;eX^_G*Ty+pqqDK+I$VPtqx zbnTm!p5P&K!P_c^=Tp{%gfyqV_Ky>rch+TkTJ&b6@=lezvZ8|tsa3^oSspMb!`^oZIA+dWqPjMBySbWh_ zGC7yJ^yj;bou@Zz{^^RIp`WnMfg|I=`56xmnY*lTd7{>1WYQ3|Fqlnff@5&fo~qYQ z6Hixsz0{hv!twEb1|JhC-j%t=wXT=5e0E5Qik61HJe>F~Z1Tb8#c$;%%dGd&T%6y2 z+^ zmc0qzIOlrSS0$f&cW0bU-TR~L(!{fKuD(lO^!eF7=LDg%%a}th@o&hK`Tj2Z=KD?D z!EXg79Bbr#oEmm!{hY0zEz;jkd)wFlbWNeC_cPz7vc}uOpBY7R>VsT(FW=m`-Qw_q zt%ehqFF5yVr_0V`8&`@XFlA_5RT6n~r}0D1I>86b2?7a|RM>OxUYN#O@In1#@#85g zc_b7=d!}cW=xSa~3!IU1)l~2D%&xAr-*%)fjoL4tkiqNhJy+jO2#%<;&FLG!ZK z2DoR~oc+|sR@ox;SJkO2jNPH(fXj4;Pb)c?a|13e37ajO_&`NJ(_5&AfxR~{jc51w z$T(KHZXGdMeqr8gW!bK*d}mk9wrOkG&|;99&AIQD;gwwmJFYTRMP%mWE`3~~y7m;? z%o!IR2G%(rEC1-=x9-~Nr)&Gd8aTU5qm)W?&9sBRA2YuEuk6{GnKISq7H01EdU`=Y z#h_CC_NhHz%kE5Uo^y8I)_)ldFZ)^A%{k?Ol_tu&dR~M8qs3n}JV&rY#X`3B? zwsCoHCAVK4-y%Ndnrr!2jKZ`d_$_^smTt0CT5mR0IAIeX*NK<@K|wPdj31^ebz2G@ zf5SRsf}8tn75l5NwBER^eaQMH!IXJc(HoyFn=14Vw0tX3c)9Y#oh2L>^d6cWnJa>%9quBVh_BSRynti3;H_pb7jFN$Wa ztCtiF^K*MCE21XlZEWIkc2ksvl#WzOC$mzI+lpLq`wfpYGD}5OW2Wv-c@TD8Y^7|4 z*@=fz1sizUW4&bbR23M4qYM^mKiagWNxo;|#Kl%?4yqQrdL$-oFZx|?n)`94Y4)YH z|D4a~9Dc~Q;vIi^n)Bg9s;`y~b^843*6@1OMc=?wAb zUz{1(pXp6!G zu+<21hPx#srCZ&vdzQ~I*>ujg8`9w?l-X{zTs?L+Zk~B|rPcQ7v0C-_wtt)3BJoYZ z{C950s`hxP&2wYhYwxiJPkF=6(C@kN@9pJ3CO_Y_ba!L^Q?a`#2LdlOmCjCzyZCEo z`NBY^R3Ub?_Nmqa(&0;Dtchkx~`AMMR^O#48n8-KRptAAs`W9hn5$MP8)4#WJufiubrWDZg$JOzM~RfW1D-IJb$Hhglkgd z6SnrKxk}}4eKP{gX2^W{#Fmkk(#K}uJS97_Ddt|n#FN>wMiWhbw9P!Aa>~hirDkG7 zfBrtkDJ>T#a66($sm^bBB z@4E+YBJIM{H}S72oj&bzwQ%oIU7!E^RZq>yTW)_-Ie15EREWWxzY7Z%dF?F!ym|Gh ztXVRNLMs?5rkQ4K4ZM71m2qSWU%%Vq;MXSW!WJK6uN9gZoO_9}ywf=-eV2ySedpw^ zMW(uw8U2D5EeaAk6jboQDS4vgM0e%=e^aOUsqO!mDv}|z_*{n5j2S%=S1%|mJ{x2Z zImPR=z`+Y1rWqw1!o71OH2I!x7uRQf5oURZ?S}4CH`$Z6hddIJwu|b``F!kl{`r|j zt0qrtmG|YgmP}C3>-#LsKd(ij+P+h5BhM`b3D23#%l|pZH3->@dlqo`vOiZ(pLFN_ z^UY~3dp1u?rJH;_KJ_FJIFB`2F*lYH!B% z6^r@5wO`t^ZxWa2PE9UhPgapIhup1ZnLSza*L$X|F)+7`N#p)8D`lQgNB-BJQ4b>o zR|Inj%T7@2;-572#9|Ij?;l=law`mW+Bl^@?4Quo&Z%ZrP4_t^2t*v*|hu?x8twfH(fW)w`PF@D);g=&+uNed%~3ce#hlAe!lWi`=g$2cWTMwoh@9ZE-yWL z8GTBeW}FF<77XNeYYq%BnZY&PlGjVg7*lqlxsl$M2vY@P5?AlGS0ZaF6+VKC(5yQnvpZgzq{aJiIZ^sjU zZ=uW6R|hAFc3)Lqs~KfkGj%4@)$~i9rfHWngfkk>iHI&-$mzqjn5{=ld8P6XcR7y) zg9$voY;v_WJ{;j8%}{wEDP{>hpPZ9Fb!Fhw#<<}7BPS!7_W z_G03Sr9x-?FST60b%ABdzO)%!6RxG^&In@v+HcWZ_3*H%i@C(g+-wswcTK^L76E@Y z=9N#=n1t7O|M2e6@@I5n7U|QhSj6a*P`Oh=O!TUcLAsNKgOjI@r{5)2m#eQd{2XS* zWC}{Fv=l-Brr*{wVaEN0pM49TOwU;4A$a)_@45*NCqIiGxgJ^RWjTMDjjC6s$%IvGOHLg2 zm=JN*g#W?B*F0PNPCBkgZ0TGk8EkI;x@YUDz~HqPQ!>c1X5YKc zNPqpNO-AcCX{=wNvEHbEo>q5*f|CAvv-KS=3%7I3J;C{Zs|iEWN0&RUQ%`g%K4_9L zQ0wm({bA5-6Bi-ZsZyx0-^im*Ro{Nmq-6_tvYytTbYl5*3$CA2o314MJkjgf-Skvk z@aNQ~KVDUu6&trsH4)|rw_|dB(Q}q9>ML9GMH3nSgtl!do6HWe1ere;>5XdkbAB89 z=0nyAf9LZlAN-Oh9+8;M>2YG?&YK==-;c-%R+ci@%eqWlbJEkjnDdp}!dD`5r827m z|2^;vQ@GJ2H?O>7Py37Qk!;V+Saz!x9B($3@~iXsb?}p}^GW$hwHZIf+SNQ}wcaz+ z%;|Og5Hvlt;OEQ?)5}@Lp54wX(z-8R@sZ2?l+w+=<6ww)!lgSpYs3{-M|5eOY!cli z*7iR%%&dEL*oj5L4WeuRrcH{8=?^-hZ+-ANr!3p4X7x!jeGjtM9X-BbQ)C2JaA!Zi ze&?z6DxX@{c&=IyYIydK)wE}hr*mih)INAxW#%=m?dm$M3qQTwG&kYrR>e=u+9e0% zb@p3kaQZvcJ>BqWw(HLW!67OqmcMRx`RRH{Xu-1uqE0hb1?kl5^ewt@)Tzeq?4IT+ z1rr0R3ZBSck78o&SgEsUdZgzn?ki$D*G4hR&8{pfddS8ktYcDT%a-_4fRXR-$DQnl zT-fZQr96z*h(^vjYOL?!aq4-5wvkydL+dGZ$&fys_#GaH|2{SM7I1$W?)7x?@BC-p z5{p@WwkiCa+Wh2tU(`O9fTlmsE}mG=J57JeqC|_ITLf1AdDig9Yh_Ij$3*{T7Y{Rb zJ&6z}!2?HHdevEI(3Vq@J`E@h83OOo+c%kbNr;% z8GrcG$YIpsWc9U1OL6Tv6~(y%i=~^?JBm|&E>nCm+f6aP=iL zlvXG=a9+DozCHa#?d0|S2ddwnKK=dR$)(-m`WFvBSn)nDc1OYM-QEZ1Ex5obwVB0~ z)xgp9?-~J zYwv0E{5z8>@|@Rg&yQ2<MV!+5+@bTKk2)%6E-&e)2>&5OWczJ27{=WN)g|T}~ zOa1uDADl>^u2=W#>s^2Qy$zmCFE4$a*|lrh_h;I#tiJp4_UB; zSqBGowp&ODSve-p5l|D?i`l_)OC|fSReSRNx38zK`@iEvpwjJH=9u!%*Ux%aKeUW- zJG_1S^XXwB7G`&M6@GN$h}~nUIs5UV=Z6&wUoD-m%`h!aQ8?k)WItMuaMzbb15 zsuG)ynf*N<|0iBtzvkOb)eCC(^yWO3w|)KV&*PMR^^exf-t+pv#O9QXcfOTdb=W^{ zm7bv1p?7D-lC8`>9}1o%72H|+zUi0@qmN!q z+23ET4V_c7H9tr1ocbp5-269NZhE=~T|d=o8dkqN>s{TsSC>NzBQ{@eez{rNSkp(M zf%BP0=dOP-RoCu34?BPIWCZuRlQZ``-z8x6`d9k(<4m>3{`+1~V46`=_V?LW?vEQ+ zs63N@_RIKP=FT0gZ>Htsoew=YbxT=auXoH|o8FUA2hVxFy|ue4z-@av+ZIm`&--z+ z<{G|!cJ}8j+t1UMA63oxzF>LU`Rz@~_ud)?nwsaw&Ho|&i$9U+Y4K;{2G48Xeym*2 zWFdBIhsxxOA&>i`r})Nxd$L`_r?1#7JGS*<>v{uUf!O_YP;{pz4f&Ty?b)cX}R<$Bc7FYe|AV- zeq^@f*3O=*#ancHz1J->zUPu!vD-ZPTK~e-KYuT6^Lt-?{vcz5kW9I7_1@t5*5}qF z}xjd^R&V_*XLQhzU;X&?vGy0u^6$Kuye0i zum7pqJ@xk1t+%qj7hjup*P6|?D!7yLw~Sm;9#7Zllsn-EcI@2zN8tM}w^uVubM4;m z`26F7fy&<#^BX=?q~H1fx5MCI(N5X@0pZf3?}GAYef`?&KVLg^_UvhAy7x;K)PCLL zmptdRoqY5Q<7l<_5+Mh+zdxsMI^&u>d;6#LPRaR4&RqFfb2=?{cWrs>XYMy=3cl3v zE_`V6#n4X8CI3P_qm<3vxe62OTxQ%kdc4hb*Eh}If8WaI-%s7YtFV2qTkQ7t8{(U@ z*uli9g_El%@=ZY(!so^*D>4f*`~qjmMXoAxn(yv}mIfBXJtvi+g+h2|Efdlc00 zyYM}p`;N&cv|8i!AnGVMim}WSv>^Sw*{m(=%{*d|t+j~2W&0c*~cR8`)*W+6(A6*hZ)iP+> z#2s^=TwNX@ZQMBFVS-RbV^i0Mm&*fs?(n*vxPE;fn^JqBACu1pSGnuQ_T0Gkf#c!J z)$8~F>iTocT+wG;=c^~xtGbR~j}K^8K6oNrScGSCHe*lEbhh+>!-unl1y!9GYq|c< zKlJ~{G6tWD+fR<~o@96Svd_W@PN&X>iJVNonhrdXTJOu0l_Ilu&4bmbM-z*bZ25F+7PSX!@}=WL)=RwLX!2a^>A=~v zWa^5zr~-e>pBH2nJ}C+6`Lg1GN#>GmolB;OeEr#abont+(dAmN+M76E2{CvE3+viE zuUPahuYu!W$L+f}Zd|>m(dv1;VUfWe6aAF@8qt0o}^&ii(g z)w`$M*|9)QVQN>xlIn_l z+}boXXF}fgTdTCEtlV;Up#ftmlP})_7M@zs+I3R9Jr4HrYbjj0*C(-3Tl;km{{a`l z>{Xk2nL2GZ?A-mJewIVi?3u-N`?qgi61K?KM9iJl)w93L?EID|x47qJF@*?ZdrcS9W~AVUqVd`(})NdsOQ~qZ^0k z-1V0~@=w6^^O1#1E(c{B%$&trb)<8BP(}%l74J4n-+g(ui(1UiM`UfeF)xp6*Ga!6 z)24~#GpPNXnz!42$Hiw7nm!Uah2P#-^fbI&9&<)`t?!$@wBC~`2CruAe$c65ETAox znB+2J%dEL~ZQtF~V^m4nXnR(qs+&PjdcxLO?Vj$n3l~OpO*(e>d*0a-(+;#eoT0j1 z?JaZeq!}OXdT%W7dA?)Gr!DGRc|R4uOAC(8UwU};y3!ktb0hp(53x+;bo9Jg(ZJ!_ z+LFVfbm8OHo7Su|wuol0sq0+$>z?=Wvd7ECTxa~)IrYsh)y)iQx0jz#+x)WnhJEp! z-8r`>XRq49vrH&Izx#H|rBG+(*IlBCNfR409~FN~n0&cU;h>Vr(rbt8<7))jWEu~( zHmTN|Xg!esUEh52wW_j`(2O~gel8W|JL?s5<{5*Jgx=4yYh^b2D!gKtQonWw!5g7hd2;*r8~jWLjedL@)Bo8v^e?IXzOOmhWOj9f zZ*|je+k>}SKC@&`R?8^vFk+k%Ap7uZk>{}vud|}(vh|BI-v)F%2nfHq(879ll&xG% z>z%07<;)Y}s^{$L@(#*=>;I-<$z8tx9x>eshqQu9%{&E-Uf;a&PIK7GTPde09R5Pf=TsvL=?AwtKw^EY%%&ZFa z_fI^$=k&8hPCqBu_O)@=#r@EH`LZA`Iq`490$-VogWo2Yv6paG)+TN*s=oPjV=3#z zjQMW^uQ^NEo9+Mok@?PCBkz-TWnIq8Bo`=8=$U$eh5J<3ra#}*TmQ5$=@k_J7n3mW z%$<70^0Sq6+1%K9eFitT3j5xuYdCtQ+xo`gllgMIzbDQOIh-nUGve@9d)3EkG5I?z z@)kMH_%UaJ&jBOHDHGVcyJy#$^w!Lp%c>fc_Iy*--`>{FMt4) zx|(a=hr$!}lY0(HS-H;nv2%$pZ|k{FcT}3EdH0-ElxpkD(I}OEy_4tXu0Jo@>^5ZH zuUq8qw`B2#Iq|_dJ%`w~a5j1_KkH^<81mEXTpzPXwf|3khp+Mp!F_K`-YFO)D*R*E zEh*w{zgg(^JY7>IpKoWn?f<#($9g9k1=O!sN2!P(6~c#WT1*kbRQdr?d7C}vEa8CdYiKGtBRzwOe^E4Ysf z?@ZZsu$Mv{;Pec zfue_G{Ob~tg{OD6HFnPRjykaE`@4;&Pv88)oYM1AK~_dE@spXE)x|d#SFHSKedDp@ zlhoshdfC^7@4eySoZR?v&x?GP84P}#zNy9VYOnP&%X~cR_Kqdb>@s3`YMFc{@vOY@ zF?G@6Ltd{J3150N%Xp{l0rsBd^ESDqC-Hv#V4%p%e9(Bi#7PIC!@TpBKjoKfp4D*D zqM>uXqC;b_ee(Cm7DDd)k9JJ5$a3GgusTQl*ax+QPazjQ3?3d+_dSrZ!PKlke#Q^h zxeurFL|zVGt-Pm4t+@N|_m}T_LS_68wCI)V2#776a`2#~l8=h1_?q0s>{Bxl>DQEBY=+tm* zH;S`XD>Pyh7E}w%-@SX|(R%qA54vT`g3Qv@4`-ER@UE(Sdns5|)%)4T+bw176HUAs zmc*`qqO$*}UXB~zk;o&0M(oP3ZNKFToo!b+f6q!SU54eLOVZI&9^N?%+aInl*7$R> zxpVDO&$NwGN`AVxa4ID|<6gg2aL1EL^XF@HZ{KKQ9CxpRBj90~#e&GJ!f@xQ>bqB4 zTHSo$Jm;3!_ebZP*>9}16xek2{2MmbExihS&SgFaRrO{j2hL^j_g?kLef?^Yuc6Lg zSlL8E4?ezSWBpTLy2>j5FC{jT4T=UIGiCVN&jhB)bE;WfG%jbovUKk4eVcp#2&lcE z_;W*D+Vyi)dU-}>_Qo7Kf9`NGEqQC5&A^yBr}y@`YwM3JShL+MYv$gif-Gw9Cr!8> zZ++yg<)`NxSNN$IybKV@@|$ZV+P&YWv?A@r>^`a1MFwV}LaSa}6L|KhZyTR$cFwX6 zp;m8?*!auWKBgQv688Lnezld(uZams?0Y}5U3rzb&i?1x@S;uks#^Vo;ur-sEbiR& zS>UskbX;x1+haM45*zNGFDTsn{7J*p+b0V>H^*PjyI;vMW4pX>`=@^EPiEK8uMu}P zxW4i3i;^pEgs%(8+&}wF%ZkZYaKVz$x>aeCyZ3w5a9#?OuWczhZ@*^6t+R6BB|I0t zt;&+GGMMOI7jf~U%7G=f!V(r581}PFuDc-K{z7{HlIi!KecR)s!`-LB#MEBCY4Uf` z;+Rj}>z}FY-J{xmQ*?gc>vfDgOEgbbH2!Ui>>b(p(V?!=^R}&8wXN~bERV9{GL`BGLxzW3r{+s+R^4N1W7Alx zzV_564d06wud}T=z-X|NaowL;d*5uEwVXrEBC~4JxgE1>=bw{bP|UI6vax#m!}|h{ zuWa40`@%Gp{Xe|;&gmpvC~2HL*PAI?#YSD5LAYALCyc@8M551OmfKU!-r9ZJAl9() zcgC#6MrOem1J`S0^69S&f1;m!-=BR(h-K;0jWbJb20!Zi-njkQshDpC(RErZu`4(4$<1hBJ@wBc?d)@b;AGX8>lAFZP270%ZAu>J?@NomrhGf# z_V)Gq%$G8+_!)#c-EVw<{Zs82zdNJaB{z1dEgSiSbBxx#N&6mu^8Jcivh||g%4_${ zmPm=dJ#FLl8|Gd&Vy^3a&{O5*ImF`Izbf`kV#bD|*Po>o-u;|$wqdJ5f$yo9Lv?4* zdDdqoGzGu@UcEZEI&J^r)G|lw&D?G4;SQq!A~Zb%-?p3M_8 zW&iWDy(^cTIoWgT$<2h8ADliHT5S2Oo*pgVWSMuy+=@jbA$h@1#^p~RigMp*4tN}0 ze6VmwwfSy??U{kkUVq%UQgF$;jTdiPO_)D_zfM}FRA&0OjnRIgeyM_Lr_)!cZIBTfw>a-%-7m0d=IirSf9Jk2v^bwzG2_j8 z$KoZ&wixVPmL~ilRsXl6ulv-jZ^s^oMqTc)OFHEDRQKND+#BasT+8!WeMwKzz%rt_ ztkX=&#=ke0sg$FN;knhjq|4tLB%5j_Wv2H=dv_;#+e)l7%(pYVpnQx7S%b z3EUpBqU?Z=Xy%j!FLl=iewjG$+?mpDG1Hi|`|q7+{OHSBd%k^I#%!@_s}sDsPD+}yGfa4HflTk6?Z1CUdRy>_``Vq# zxsShUFX+1b z;rJt)?TLv+B8i)lqyNobpAxq7*~Z_2v$vF9`JHs2K9%vvH^CVRlNZg{J?FrZa=qRA z@BLwFZ%^OW)5)&3%-4?ZYyQ67^4HF(vwt6d67|^8;O03wml-+B zx1GFg`ugIXU-OQ>zqcX!@YoztbVf|NHM>t z_C~sWQSuGVmyZS1e*C>4u=azAuIc;W6W1K8o0j{y?)8_ueNA`&uRlE@KM&o}KFi6@ zZpHSgdtKf4OFcdYiR`axy*`O*wWbB;Oihlx0!S0^aQ99$oCVb}Bc zH(L)%3a^QuF>fyK+~?b>e0-CBy7-^gc;g@Wi9c=St-r}0vmbcm#3vl%u>aVy@2#-f zG>>I-S>pJTc4@!9sk@Z-jdf<%0g)-{$!Z5P5}nMLAKEv*eBNQHW%D&|cJ7L<6orEx zqB>`jS7c~icqMyPCvyGSwEye}p9nsaz5ZHy*`_zs9)I<}6SE`m;E_|RXZM!A|77kk zUH|^>LW|0S+x5S8+TJ^Pzuvw=PW$jt-5sTWKLnWOwA&co+^)}S&wui~?#^2N7Dm_B z^!x1UJkz(<{tR!gpEvQ}{Gv(8?zPc%S#`CyCz~f1Z84|}-gNr=za8c`fB5v7xCY$M z-}t65QEpBAt%r#(KRsMfFvs-6(eJY@_43RlSBfS})N_P8+*4_qoWRyM|F!>mM)fD} z{#X9GZ2vOmMjv0Rli>%JbE{=_eV*Bte|~2Aty@3u&W>|(ebJ}iomtY_k@fIf?gh0& zE)j`e`5q|9B|hTkQ{Q~+My|#4iMF$(HfQb8Vi`vVgH9L=&Oq&|Haor>v zz4*Bi4{dxNaO!{FaVBYph}y@@82`(n_L94v@4377To&i`-4^MLK7BpnH)Op(&P|wh z;J||ey`^Mhz#Y)cp#|IBwmp!V~kU>9(=1f^D7K>38qO?syli_z>wRvE9|pJZZuQ-??Q`3a)g@*P48m?geqk+d z8&f{&{C2#SqsV_^a`ee!--q{K2h1oCnPWXI%e76{GUikF5!RVC>M_h)eZQ??GqjZ7 z^wIvQdZ=2$r-Z}Vb#iKdS=6j=v`*Xk=6gb`+IiO*DMvP(Kf227;T5j9+<+MuKBPKX zlr$(g3g%q=+GzGucH^Qjo8NW@M>e0&-o|{` zQSY6u*|Qgm?izlK-)PMHMM}eGN5+RKPTzw6*xxN@R8RQCVbHjW`RIox!r~+6Iy)hK+ABe>$;@xATi^KE-NU7K z!_4x4oa#en#@k^gi619_i(J2WUSrg~B*V`&($aC8=cg*W zn#~!dELKNW&aszFJhZ1Ts^P*X=RHPDiN>>M^9p{xvHr$mp|-g!YR5Hw{x}*a-ZqX) ze*R~P^<dfxt>w2m5_VYs!i$Qgu#SHr28@RjKE+miEC29p@r}z5h18wJHSF4S zSa@CvOlGYYQG4^5x8+)D_pO#$8ze7msy*;VNK!17pIg}aOVN#N>#}8k*W7Y>c=@T_ zAFeg~wq4`+x$DD~ZGGyg2k-lH2`~4VJO9ls_HSxi^;l+aAKYsMk6drQl;W@Kvu(0r=_2N)1R)Ob-r$ClxBnhA zh&)-h)rMDU#gCOrGw!L%irG6JxE=BT^upk+wso(T%t_qJ`I5iY_pehxjJ>iC+lkx% z&0OPa|2jmAX0)za^{bDumC1IJCc8_##)Q^$Ixkj~%SOu0i@L#3X1o7EzmBBJogH!k zjW#Ol)y37cZ_e=ivwYd(a-kUs{^~!!R$RKgb9eGGn}_GV*T_EnwSMuE<)3Xi_q*-O zJkR{#-Q4$l>iZ@7w{eDjNIVkjQ*)#I!r5tM9hEbVF#9}8Q$Cz(lyCoY?T-php9{{3 zOvhJBZ@qoSouPm3;Ejr#`7UCfp7;j=l@mNxttd8xS%ThnK4F;MYVdEWF3?BX8IH5xy6ax}^Pbb5UCp7dr$6>Ou=Yzb^UtRhdvE_*_3h|n(Yj17uF2nj-@3Kx z%Ig98!LDdUZEf>(1YG=h6*C zCm*a@elR2Bv4ZtHM*)uT;5X0LH#Www&G4A($9#RdhtMDAgr><+)7z!PH+v_~PL7j| zIDf8RH?qNaIs1pj%)tew57=+jzPTtV&~^Ep^{cDyH)eJ_L}!SuJh6eN?$yaRb(`ci zlxgkumFBEG*-)J`b34Dm$&2zQ}d2bZFn|4{wV88_r zi@o)Kuu7B|_NTbbGMO{^T*%^Go*mD^83k25xBnEKUK+s1$;|s;z1x=wGH)AM>@SOR zvK@S~1SU0qHJ=4x_A8u91ZFJoZ|Q70@Fe5i)L-+qt`EpHQs2Ay-u7Qp zw<*lnb5w5qs}t>P?K(ep8~xt;m^qr)bHCFUAAR@KiX}e z*p_?iKtsOK4ONcGTi-7Ut&B_H7dw;6|ETIfuIcNW{I70L+n9fa-zQ_T`qqnu=aTbd zlcp~Vb=~wv_r-<0YmXl7*WMkGQ4)7&Cgv4 z6neVms&4a&1Bu`IrDr^Fs5;KD@7~+&?A7aqu6^R2;2e5&>euy4<6mYAZ%fS0R^C%m zyI{k=eilbF=GrHVHy)aFQ2X`rCF$wIm4E%&)C6PNf) zQd#oehGN@ig)EZ=pL4|AwAK9l@QOpbQoP-=>&$&pYFGL8UHNwGm*vY%YxS;8wnL4p6bwGziptq0_Ivl6t@<~f8gKF8t~h9~mk{)JpV2x`)2ta0IddJZ zUMs)pe{+4=hR?~-E8NNxe!jVXj_j&0{ulQAv&;F)Gx?po-{S4QIn&Cr zHeZ`6%Cchbg3E6t`3)?&zZ|~lFUI}lWSjAP2L?{%J_g-5ov;52zWs?m_vwt{7v{5B zht=yPW!y6Z?)A63@eA+YzvOCkY*<_M{OO)6HlMj+!I$9l`qdvv!-|iRdCb?|@h`vL z(0rhA`Tpk-_LgEFCCF|dppP!GPn-{Yu?N;aJ^k9w*?6F*a*lodr1q2imNzX_HnzQPmucxpRzE+_re5w+-$6>}C{vYS{p7F^t&j@&y{G2gU+Hao19Qz;qYpv@4eOcvv zXXfYhpB=*XITnm-)ctkrHa|SVdE$3Fue6_x_0N-S{(dsmIV=^qGJjRvttH!e)$|Yd za?hBf!1C*X$$=+dZf?HNm!W7@EoG+h-0q%|g|8rJMImfmFfd*)HgzY9A5wRxUf_wd>r zyTV6?hf;2___(nP&r>n5G_Jj>ZsW7*xA~mk6(479K2fN2yev%nm;ao_Hvgq(US2Mr zw5-;qHq`H{VS>&7<_)&rXBI!_HfUkI0G2Nk3njp5bShT&(V&VQD=_PJQm|hLbN6 zismh!%%Z05&t$c1uJvE$w@2s9-uFWwqs>{J)4lKQjpK{{tE~4mn`2#nt^P%c*F4TO{+X)VA7YW$ z^|N=LaejVe&AY|P*;}F}F%~2-oE22^yU@|UZ0*c4zSKFtGY-$1Jb%s4%j((Z7*0Pj z?H5*CuAX3IHDivw`h}OF^6Ra9{p1_pKYn?|@bBW{`Tqas6#4w0@xA`Y@8$mDGtSTb zm+{M8-uF1qxr+?57OOl`PFPyG?w5qEyyE4TFBLc<&(Hn$NB+OHIpgGuhn^HOs?B$f ztvxsYLBXtF7o87X>}A#db-wo8@AHbrN7$4+vi|vOS`g{Q_hkN)QmLPI>{j0;>Xt9} zKaeuTK$5%U-RI-XQ;LNRBxQa4{(oJ3+<*T6sRy2{x5@Y?nEnrB!NDhY;*T5q9!S}8 z>&a(B*LqRW)90(jGMLmBH=jKIc+Ni)#>s&Pp2VO3lUsB7Bj=1BCbj)i^|u>-uCK?KzS!cQrkl(Y~j-Q(s8IRx!S)X2!}Xe;0OCuBe`I<8}U;`VW_12kz!r zDSG&!%FW;#l6#I%+EH6&e|^TS^9E)5E3?mKZ??VSp2L2y<;_*|tSc-Q?q1i;87H@! zb4}{oaLBDu<|bF-Pl)hW^#KbXD6*E#cD#gPG-z58c(@x1-STSwg_&$NX=csu;?@ zO?LTOeEVkg{g{1~6E+uD-#9#{T>m%Qk<_ag zEUmsqwxbzGe6u-yCfUrZ=@Mo*@_K#Kw++86@3@9^S1)Wfd&u`-+sTvbH)ry%^K;tA z{d$himD?93zy2||cfWCSz4HA3J51_gts0lzw$YHSTUb+HJ@=9|vo|nI_PHQ< zVMohG>CM|GFFN-3v}bio^^vz{eCix;c*&Yq&-$BwF8k=MR0e~Krxq#a3mlPoo^!|R z+YjYKDGSmWt&PpL2JCCLyYI%ZE5`EtW}L6L zf#1vhs@k7x>9-^DDnA`BYoBrG2w%aES*goiHobAW%>Cxl99#DrKY2Ib`0<7LP4>#y zg|E#L-)~=H9zW~oIsW!*ss20%I!{*#OV3rAE+$}NZuj|O!ll5iJ#(joEnTrb^4Pw~ zFSWy_e5n4hurkoe?5%M5x7Pt0G7pcp%JNS8@N(Ll8#A8qy!oqs=!ul{|GKQJlmDw8 zKfc)a595pt(QJP%YQElbrmQUOoY%J(h3^ip{CJ#y!|C;#KC&~1oo1XCyCp|#_gZ-q z534-Bb_2!h^ENU>&2!)4E5d!_Z|Kj2{kFU(H##@9`t?l zNwSai$IQw{_q(irzs z&p6q=*|SFPrp}iahgezECU2Tqmob@d!$+OG>@yy1SKfqeaJn?9zoy}F<{qe!h2_ zTjC~`#7~VozRzb-%dy$Ex>ner(qx9r@wIQar#PQbX*hYTMDOvZ)|d-w#@8PEZ7q{i ztrkz6d^hv5eabOUFptq?lV4gFjP$3`+r;8A(ksAKW`Mi^+Yjo)5HTR&ocD->U^Yb?3PMk%Dph9 z>tx2EcQ z$?Z)ixyrOQ+JWVV0i zESBH6{PH&G0LH9^Y47{WFO{<=7%hn3ZCLKG+vS29gRuO&ui;y#i+;O3KX(;8LBhH4 z!nKgSN8jbYp6Qbq^gjCZKK_?p&jfFaS+1BRc-;3!>(0>RiU%n@{OiA7W)}W*?7Dw_ zPy7d#qbw3^dt>X4%=2@Pev)PO?^@}!yEXw^=iXA=!I*M?>en}aR`1A+*W2oQW36d* z|AzDDlYR!?Fk@f#yC-$~*U*W3{|iNSn%!h~^Q?_NE>Xv5am_vPZ%J~F+nr6f{K}TO ziT`ypQO;ZJ+x}!j`(ciJ=97^#c3k@3v5oUe`D&v#pS-*Iu9s`1yfza3YG-M|ZY5G> znRiP)enzyD)6{^sqMY%1Hll*w_g`)iP1@CZ;W6*6-~G>4&c0~A?f5J8GQQdi=10D! z{IefB#}rG4^TmR)6>3oN@B})J?M* zmi-H`@OY+X*wkxeSp7D$x$}DPMZ;U3y(fKJuO3v>QQ1Ey}lM5XX*da<-|A}cEb;Rv z*4Yv%264>?{r?=}&ndrsccbCkchls1w~4M)FFKjLLRv&Jb<5&t;WV|!eoUH4R{I25 z&LnH^mRoMV@Swx7cdss&?!RBWYSrq$k7hnli)|{i^_$B3_2c)N^Op19KX0D=d8Xac z>}t=+MwNO`H2jJ+`GP0?S#u-1aE6Y}3=NrCQzn^PiL!63W2ugu%hmq*Yh?Un=lQcv zq^o@Xmi792#i5mxllv#6J#DLb_HM_fW|Q~L&4%l)Tq=1Ix$*iVgUAeniBs8}g!`i7Qw0MzY_{4@|ohy<~Ip zkC_`lMidx4bc)@na+5v(_9M0#GGSKRCOdyPwf63*jX6ag?{4uuXHffDvCyH_)8nSE z$EUzEPE!t4glm4WWmK7Oqx~&PMva?CO;Ixb|9!iEzxZ2B!e?+S6_jb3Q!>%}VG*O6 ztd`FW*6E85vj|+;D0otB!a=u$PdQ-U>&&>|Iq~fi`+xsFuKM-)9oOWg(ak4~#AOe> zFh~@C!eM`Ot}Bpo*UUY3-jE*&f}BzGzxiOQ*_wE zXC9B*wENTN+sE%awZA>$yT8M;tn~(l@1mG4O)%qMCe(70Yf?gSO7yaWM-u%$X^OrM zt~vELJBU>-g!$Dx(Q4f{{NBsiE`JZd#lu}*SNc=`&CVuhc|V`buG*V zUU*x*&3(T8R>JW@-8BVQzdrx&eQI;k`oLd-McuhSQVKo4Pq?q2wEU5K+1}}gRIE3y zob{Hyy(=MtkN2$VU7=i!U$${ym4v>$y}IOrbouJ6|WY^IR>EfCtY??lk=IlPf7%d<*PwQMkva`y; zRlJqwjwdoo09ek@{-cG<^PJ=IBnTG_Ij6F=-KI&A&qd`Y}Uu=G8-9L`Vd-I<4D3ksRd z_ROC9h4ZKIyW@$U4hJOnZ~gnwe*dz$r#>gF|0umS&+f(dia$XSw;aX3-jDK=vQ16N zHc#6m;G469-?8a_%F8h6PZtapFD+Njonhdx*t2ZW?lzT@pB&NCe@#D## zKTb2*CM14gafc26%C{dA9^H(4#K*n+M1B3o?XKJ2YRt}HM+a%V~7li!bap4@!OH_i6=$%VFl{MqTqqW`=NN`CkK&UL?LpHlqk zxBq{T*~tPuwO%3q9Urf*s^wg=p==v}^UTsMHXp*wZoWCA+U}Yu?wP&ns06A(f@y0dd9^)+B4I4T5Zc`jjJsp7Z^86 zHn|wSOP+b(D&t3WMn-AfROe}P)o11{Ja|Uxp6Sz@iS~+i3Uyw3I=8>g%$$Dl@RI9B z(j8y*BXYZof3y~f&u!dpvVGQx`JQ3?XRS6|j+`=CtjX?pkUxW3<%vmc`s-@LtV{eY zJN?;(EB;>hpZ34@X5I4-QOmzP_{%?i>EgVTTerFGsrZ?ZIwAb~-%D2%%-+ngcsu2n zo|E%-i6`r~tUcTM?%@%QaBwrF_0f409qo5zYv*&nzwY&V{BS|k3@ zeCx{&ts~DC+n7xk^9_5iv)N2DR@>~&B7={GlPCW^!6t5guC{n#kBQy4meXfe?cXq8 zyyB0NSK>T9MsK0ZAHQ%-tc`jmo+&YJGpOL6HT%MzVrIQNJEyKYs&c-($7{Xp!7XL- zb#D|^zkM@PJ95prGAD*b?d^rv79Nl7E^&t2{T626QEd|y*?pqOE;MgZuB-SFJ@M%+jN+=_l0)vbXl2VPs?L40xRGn4>h}_t z!%G$<-)1{7Q8wXF?)GK#Z7M&N%sBVp{=Q&0qbj*_51I7!x*zVam~JVVvEYkT=(S4; zN$oe1Zbq#?=;EIkzFgB)_0lqzO8$#M5f!qVbZ0k7PWYoB4>~-6(7#h(WKKrT( zx6dC}pN?EN6VK+=;%D2Z+D36{pJtShpZ+BvELuiQpUbBx;;Q`BideINWVcIE8$}b7 z+)N{kRV3WcXwFmGq;Y40ub85b(628dWzut%88sArwxw_KV_SKp)Ii~!W@gvnC#{L= zSAG?_lQ-+MlZWM^XKG7kuUvbuy?DOfk!_t5glZjfZZ$A!oNRq+8PiuMcVK#qUwYZ& zGrz=J_Ld!8yY5~gulVg-e$}F(RlRkqva*%!M3S->I^`TM=MBsHthi$9GK+OLMV@{$ z&A9aF(#7!LI=jD|92|u+bnb{I`Tg(dSRwi9+|!@plTuyvgXjB&b!iLjad>0;w_5S8 z&ot#r*;6L4sjpO;t#_o&yXn{4o-`$6Mb*V>vu%z)Dw0vtm#KbhnNv7JCt=2lEyk5m zC6!yMOP8LXX>XGLWSi~9l)uSVe{F+m6TZlD7nYSZx(m;pZ*e+%Ds%Cr+l!uDv#``^ zytpHGp?V{y{>8U~+Bts~h0l<+UUcAm)#1gKod13}M9namxyRGi`S&?R-nHMSg$JfB z-(R$OVaui~N=4ao)DF0{2bymTVVA4=7U*5JNb_=V`0qsN0z0A5Bl_QD*Us6=rBkI^ zx9HNz^JRwv-k<#PG`2kHzis$p*{W=|?*UV{sJTyEo!Yxp zY+`gb$A*iNyWJT0q}G_Mo|U^PDWtTTL)Y`x!Mb&4OBd~$%WeP za8;<5bnZU6NbL3z*GU&oy1!do!~Ej;3a5<+s$1ALU6yX=jJ|FuBQ^g{yU&(u)_de#qyS2 z_onuL=L_yU{(Jj7k5kTxlip9h;H!CIlgaO@b!{jkwS#?o#l28?gutpao1-0_|i$&iiv54*yO`b0amQv13x>M zJdxaR@H;1eu=qjQXHD|E6ABIB_+jVJc^wLaw7PZzz$K_>i zdCX$Xdgji>X#BG&-EyUH-g6bt)L9edm-_ziRH@21S(zBHV&j#`HtO^K8hcuJ?YB31 z%s=bpQv>aQV?mDlEebcqKY3ZpKIaOjW0r>A7g?1bFM7^JRpd-E<`X_XE%A+dx`TJ!$+=ZE&c||t`Sae4p)S1TfZeh=sY2K6ep4yk>z5Ups<$TXnPW$l( zEP;PuPBUi{hTW zM|L*BS)w3cg^(88@E`< z#Lav3>}tr5x~#6~4@sWwjB4$B@3lQ*imxtAv@s7{?CJD=X>@nzs`b~lGLs@B?cndojP6apKt* z#_NZzWv}M0-ne&%!xt9Yl{3puxOW@*N8DYiIkze6>+v~vvrazTo$*tgXZbTnt4lUd z(pRyy+Ff0k{k%3zFyq`|lh*jSMTd@v%{k?_xw`4kF_H907PYe(*QZq11#?o!zM9IZnN-FQkMOpYQN2jY4Wj5P&B%^%0!>%+kDdK zMWNYJ1#jM^3B@5hO=BB;IWLNcSs9r7rfSYy>vXr!`j_atGttJc_of{M792F!JCapi*a=vjMw>DFA;@*$| zmK`Q>=lnJWFTbQvW;H=gIx#3l<4EG6qRCITRe2;X^e$MlMZrfX=kgtA>#zyVW>eC4 z@0^iw=O~BwTKB2Zzum5}-q^zUQE<`|tF&_h3nZ6qkc_+GS@_m1bbm5``$@*=`1=`V zPgZ=tc!vL&@=u|jfHh|Y5;oo06RIIhL?lEd9< zYhT2_9g|WH9NoP7q+*m-#Wk0GYWr1LJB)ckq-RMznD~)#qhtNqWh)M4Yi#*;x8s>y zmcrW7(EaiCNe4az?GK5}T6O1EN4Rjp;W@6Bbw~OAW!~0*fAzNcX>_iHy;k|$`(2y= z^?m>UFL0MhJ(sp0&pbI98JoMh54~+~f195A+q&{aC7X8hqqCEBcQGoMeoCHHbE)8V ze3+y5zjJlwvr8VY-x8WtSD#q;>XCbd;EF>Z-X;9}nVLO!(tUm3IX_OXDrw-af9+EH z>%c{^haz``_w^e2F1D{a_<$*1@!2xLE6aAaXR(;)S$Uszh%@HeaPh1C;i|-jXPdq- zZqnLs`u@`V_%D}wfBs(hSU&pfSFTlW(gQaC`n)>3q)Pkhqkg|VhnM~OE2+hF^K;?T z8NQFQ{rSBndDt?$zMc0xz+i_%Vv>N*Ba^0CyG+D=qb@(WnYIBGQL`9kpEG_qgN^O! z;s=lVeB>3{(?mmNg*m@57w`*knsw5{ebtXeJ%9cjo3y{<(UyNLE4mJFxE}c7v(5Of z>xKW1*9+8J|9dIRHuYi-&_oy8k z>nC>+o}R-lttWdop3Hw&Tj?xU9W$fgRBvZzB7dL$IX|BHvp+6MUAlFgw!TNDaT zxartxCH=|GIHf40Do{ZY$$;ljT>WwF}R$E?Py(Mq^nk}~$ac_LF;K)Xsn=6-fFfL6pExPot zd4f=NiO+(!ImWwH{AOOY+oF9ab++-Yp1pg+z5Sg&W_((caHy_!K8xD4q;Bc`f3CfH zV_{wB_i~oi(ZkW%JB+GMuGUyv{%%3nBaTmJr*!2mF*LE;$!?i>{JfH=uiNsbXr^ti zzb>@TVE)R!*TH&u;<3DWiSkkz=`q_n^QGN3oDSZV_loU$quQwkti9NwwA zzBc;nenwsW@X*k`kGLP4G!0#U^3?3m>c>VF=ULTM-%n;rHLtXnP7F$N{*}3JQ-4Zm z*m~!p88=^*2u!Lel-10%+86b7N#Mo3_QIP)S7z*U!JMyrh6IV}|r=o)>S(zrKgO`fRWZ&VY}W!hbMOaoF6!5> zOV{Jq-Lek*dTZyZ?bH9P7I*S}u`)r4>(Un4GK16q*JybDIkPM=%F-jeEaTyPjShR> z89T}+3qNT%oRd12ucf)hHB;kwjSBPP&UACWna)KF#gnaKKAl~-tk%LPXk`Z5j1mQ( zDP_i=P8<`_J7pKLxjrN@>E*JPMLmJR)7CYL9Qu;X`^At)ZM{w`SN*IhOV_VinHBZx z*6dJUe^z1p`{h$b!#||Evnjo=-I40%VPGOF_tJdb^H1gLFGW{xoYwSSTC#&xe|tK^ zu|wH0c)fBAzJ+zxo$ax&XHzEtx*lTXBX2Bmy=|EN$jZ1ed-_m_47NW6YKfg-|MS)Hi*~m^v^O- zw>tc&bcvawy=wdi>DNq)%MWoc`Sd3XJ%@MCUHOLJnykN@oQgn6e~wyp3YBmnL9hC6zhk7)i^Y1Rehtg+0$=R z3^WD)PMI`CqHZjy!O}!9cu4!our@?dA6m)NaXun|JG-h`jTpd_6v4i z`C_nVu-9_H;=gSKK+zxaleT_srnCJ%>a1JzsI!_W)kgua~W4GqhOVFHc)@x`5Ac zw|!KU&Krf+OMkz1>rG0_*Y(^GzihHQr{BW1P@Y|1Wk2q#>g>;);S$!ca|LIq-?b;M zJYNjYS#a7PzqHZla$2_7?||gSA2XwbU-lj8__+Ok-S4yJ_pjOA@3A{{_(JfZl-#me z9il=jPfXQ6(6sMadGXr0TUFNI-rcN|^)i;v;#2SphhXbV%ciH_GTm*Twdhiw*Cz7` zhpeY0*54?fpt7S~e6p3rhD)35EEd0eqtt#!xcg=9Mjl}|-QcwooY?v#g?+d)i!ygH zuGqIkef8-|Em7Y5>wg?mRZqRiUsk)~Uu}ZI7AB`%iKloHjoyE|Vz5$M_oYaY?%mhI zM`fem#=UpE^ussvg^o-wrkdyy*zLvn!<{vY*-Arg|&Z^Sno4kC9kyh8I!~ar@6F$A0wx`Pb z`(7CijmmchOZZC}gv)h3H{DNrS3iHt3eB9y=G~iLd72+Mvh3F1trwPeyuJC~^^@wx z#HaO(f?Tt_%5Q{QOZzOjB2=cyH~IKYwf&cTT&=6}f9_Iid!Dq%bnQfWx4i6G!WF*R zF~x^i92oT{=4`ls-g8r`x>ajuNK5C{zp^QF;yla@EiOdqW!&PBXgc_z^~#YAQFp=* zEc1Jpd&J0bPQ~e0)AZJ#ej_61@M!hnBdZU#_@8|(vM)-m{baHjbJns&XDyBg9Zd6E zCLP`GWVC(DD))=KW@x;cb?tLc_}*pT0w%8W+8bH9_tcIa8CGF^E!F{KmfOu6*!qp;If=W>4@Inwz+? zBS%kt{=`XnYegK5fIV$u5HKl(nAgz z-#QHYvX54EznEK@pfvC3rM-baKI{qBjI*n(yBT%+J z-@7a2X8*E}ke;&cb$G_d2PegDwTN+5v3)db{`xL)t4P42ueBSL@7Y(?-K^Vj!xjLkji^Xk@(N!KS_ z_%^SId2y%5$=nG`E-YLBuGRR~*@c!r)g1peuPShR^>NEwjai;cUT%40r+ic8mEpq| zzxJ_i`XQce;Q8fXG}E2h_fOj>n) z!g;Yn8BN(XHx8M$SvROK@b9gZn{ni3wjrbN*^rP{&-?E(-kL6%y@&no>C@|Xy*O9$ z>Q=An`V(A-PiJ>sOVa;t#Uk|XX}H8)-48`FY8&N!FNADyZS8y-qWN=nV72a%#3aFn z^7l#B*{i;>@mw)YS;(^CtjYlv1()bO?2;#6dr!Y`;Id18-{B{&Cw(=1*8E+1dFyq9 z%Bh+@89ojI5-YOJC&URfa+iQMw_xcV$VQt_nWeQz<(j{=pH>uQX z=9)%j+EFPtvX`vubwA7!y{Gf;rTrWI*rQLMx@6&#B%}6PV!KP2%uTVD&fNPYZ%t1{ zL^D@v-uN~)(>(|7ZB#51zGZ)wD+we#DD@eYVWPCrMmQ zFgVaJb8nUF3kk`oQ!;O5pNNRwRg!;MYMXKMF1P7LAGGdXjQSB5|EsK@|G0I<=JH;l zcF#5I1&RY(pGs{%>)^epXY0+C*=}O9H?r<-otIYKSaCI8=ders)5j8zbKAb%a=w|} zzwIpZWOt*-vo9)n<-HYr-+5T2ZQILf6BdP=KAz35d)fQvm)%XpGyb$b*O2|Q@~{gZ z3zL0|iCEC}V*zVZ{eI1|Id8fnyv=^$&O{|&o_Tlt&;EE;cxSh*(B37|Q}X0mcjrv1 z=bLPQ<431hx{TUoA)ZPzrN7C_zVrTGuYb0fxpC&tvvWGn+gw!X=yCayoi**pZ1s(6 zF554*IsaZz`h?#};gImJ8!qIFueGUK>?e|D{PXbK1pzMWe>^rY+}Ha!+})jRU+s#P zTZ^A;HkSW;&RS!c@p0Q&{v|ut9preG=Kq@c`WzMajR)skPkQZaY?rTV`DSTqole1u zrP9KV>P? zToq-rg+@XfuClXCsa=xUzg0cz%&ik~)*i2F>IyT2GoSHKa!Q{d_IY8Li8jL#tG(7! z@4kJ;{Etyurs4wIh4*(Ir5@@noO12a3$^+ePuu&BWw71Q4VuvrVI|St`OSWRzkv78 zBBwQess?)}Kj_&z$?V_U*v7Z!#z#(lycntb{9H)7@qd}MnQf%%`B?Zv z&9(E?vMnnTjOQA~b_6|G{>{34;&~6LNv}Ciw&%F$GCWzy_&_V@M)#iZFIB>SPRz3t zn4*&S!^BPa>J$Ald;T;fo_D=t*)z9q`?V?8_bRY*&13dSd0N4@u}nL*n!|IlkJ62D0dfV?V{MG&+$11S`ukefQFZEL64cAU~ovZu$_=fGJ%Kw@k zU5x+0k^cB|>SCtbmA;LHHr`?+faRVz<)?M;@})XTJT;%^dB z^QtzJkrBG#_vw?X9@j?Q=M(q-`Mq|XWpKp5SCxMX!>_jPy}IP%>=2#LvyGN|W-%t* zwat3Ve(`WL%Z!z2A-@#rJMT@6=`=`Gt9O1Kyx`&2tDf_&2$|oz7?UPzlKW2V&&NA1 zzx(UCkNUp26T$GZYqr0B+5wGi^CHp}!?doH>AZTuk-Sn;^hU_@fY-O$LMAO*CVb<$ z$?Jm;c4(e2OJl#ea?ASrIo5ez8|SWUWp432`by{fOxu*^)rY2-8njy3TycH+YTBfU zZ!5!pJ+)*%($xQ6+VW?3(m}0{ho?u*ls{R*Ri43^AZyCta(k&-14qj=D=8V3D)Ev{ zrB}|$2tAw|;q;30({1DS&E_`}8y-IljN0z->4>`(+l&BTTS?)zyDQFI+sMkq?68n^ z^E9hee$9>Y#xhGQx}F6j+-5fX6Z3oPYCB%F>X2==?0X|$yQ-I@u3q>(av}%&+#4&G z1kQM~aM?50BYi7^tcr}T{0N-2Y|W3eHJ7umUt>$mVXkyt*njYea@3jQTnx7b)Yw(} ze@uPZP-1U-ew)(dm#V$%N*{HsXsgN%{Jw5(@G@qB3SGcW(uD#tC-i$8+c9W-&h4Eg|quU#)e~jfAFk zowv3*I!#(|H`IBqt1mmtS>_3LkM$Th6O^7za#EakDC_@6KH-xew7i(PltdHRj~q*pMBkIE962ln|Gcps|O=hiF zwz+JJ&GFM6Jr393P09Bbu2y@#PEqWAp31dQ`9(&(A-tTIe8Zkyw_GC5U^c_^rK@tjO4(z*)yk>1x-Xph4}4ZRtjpuvH zjEPKEGN@?HOTKwiYV)#Nopb(V z25-51YNw6-l={El*G_eOA#InLJwjs)PoCa|ISTZX};IB=djD~`T0vX2Ohb^BsiZh z({tI9&MDCvC2w8{E_6S)&Qj#YvZ5D1S*BYRo(h!xV*gK$^<3bOwRW@DwCGd_pWKle z#NT%~gS}u{4O6nf61Pb0llg*b7WTK_78!Mt68|ZlWjNm^oC}^$@XVY^Ur6T-c@x`#>8w=-Wf z_bvV=Rr4cY##wR8Me>`qH-zr$lV7W!pWRt;?eXV(`ug|vAI{0Dj{aG>dh~=d3-Iu&XL*cAhRgmxp=KW*1biH zOZU#{otc`quJo~b^7@5JK~B#P$!t9$aG$00<`z@&-0-c;OQrHw3C*rEna(6#?Y1R8 z{>jA<7Qba{Q~oy0Y~Q5(V!D@>d(h02I{yM<9^5?8@`*D}X3C!#D0%CdfG* z7A{Ww`Juack~qIwQG(t%q2+(2dH#!W1e+gw`ZGhn@YI)Xj>#8zq-G}_XnPlJ=lx5# z{iHv;n&Q*bvmbYe9&a%-Jk6>mDWrD%xMaYC`Pm09JO4{9oUvzu!A)PQM3&1Nn?$m{ zOJ1k)w7}_tWB8GDi|WF&%!w5&N9;;ftlSgr*eK{l8Tdq_BOR zdUSu<>SqmwGyY6TR4U$ittv)~FYuynhnm4BTZP5NGyZZYxD>AOE7B~S@#je5qL3L} zG8xB2f~45$(+_2A>MzlLd`j-p&hts_5}WNlb|yT!ZeCh+q+{Mp;T8XWda-=vuB(?( zJI}86+oSmUFQK%z*S7K|7S$X&t|=?csBFH&Uw=yA^4rJTJ2gCVgiWOF57$5KX|kKQ zb#61WE@$yw@%EGb%#+voR@w?!PWa8U^Yu29(nvR29I9hn;B_5bm6wYq)pgX-(+ zx&JMdWBqg1W2u~NN7em5S3)yx89kU&YT9of`ZE3d*R2*mEqvxN`}B#b_s8feOUKM% z6aEwBd?M;p(C*shJhAJX`+0@)c`t5zrYIt#zeue z*n~{E^iotMZF<5UeZI-^>}u!M&GC8PTbx{dB5{s&^2H^kd$-O$w=WO@e-g5ZGMP=5dc4xT_z?OYWe$mo%c&^IyTQ3#fZ!LT?JKydvo7;)f z2}_?$F)8E?mtXpLrrjk;E#*>Yxfe+ZC+0?^71mFmT{=(f&qcp>^BsRZPt5uDquDvy zWA1^h-&}K@UB%4%&*j~V(Y7j8FS+E`Zl9563QB4g2AWFSg61SncD|$L<(h4p+fW|6 z;h{AA!K8x=B6HpWK zw&QWF+qq=+!6hAg0y)#U9tO?bF1D9pd&Zg*7Cva0=bId>^1nKYx8m*; zjihU<4=uU*dhV%nTb%Pg-909>{d~FQ>`KOC3_j}^ecD22)KsZG3-3t(cZG54o@F+U zc|yFx9b6ofFHQ23(8~AcWcJCsY~=9lrFi2>$4eF0V-%{IYO>~S_UKjHcSl6x#6HYKF;YrUOszUJ|L; z{$W=$kDB0idp6+{X=0O~l^H7?TYPXySo=ve6T#el>#G=->0gnYBF?9FUZ#w{@nreV zuDB&s+&8fws!Gr z1>?QTMSnW3K71+sbY@;qgH)__?S$DCq520*F3J}h{8U@E_~e%P)2q`iF6r>PePDW; z4!`@131{ow_v*;J^m*cP=ih?t#AwAg^Nl7Jt>G70b@oa2C-tHO;a(@C<(-1{`%2{2 z1n*@?W>uRmpcY)NZ!qJI#C#d&y=W3x$GYgx6Ij2tBF3 zxQ~B-$)_KNA+yYb`kz*R>A8_!@O!sqMO8t;hm!3rwigV%k1Vndhn)ab`gI_^ka{&I!o22Xg( zx{|!Nrd`6EZ+}Njl&fiJFA9DW6u|W4!lu0$+wFH<+$pg4guaI7qK2cjlN3B3uK2A| zcktY`^GuV2H}Xzi^DnsE@9l|Wo07Kjb%ag#pB_Cq)Ykkk=eA}g*3So8Zhn91T6J(? zkiYqGO{x?Tk`VYoqY(DRlebnTR82Nn4n7^@~E28A?p2rhs-jR~o z^1Uh}bo#0j%QX6;%UPmUom#ix!R@os{LP+U#ALLhpFD}L$h%!KqbKfFZ|RH!(R=}O zg^y0`;>wOw+x{%#9N!c+Vd2Eri(KE8wrOh|*;ZLO?Y&`wko1$y@?2`u^=nohQd#C^ z#iMrT$&6&>605bZb#?E{t7Iy+c)qT3;(rq6+wzvh3=Bd&Z$zOII%XVLq{$&$os5W$vku5AJi@o-KIKshHv7|0}`VDT=pe<6vn(gc;|_3nZct) zwY-&#{e9j$F@iBU+dwPrBa}Lb{ zO;Jl#5w$N5D*Cpj^9v_>GmGpD+_L9fqtNx^*Q2X4CbvDR;QC!KBc|yJ%kjhC_boP% z?6;heqaTy zU-#+Lzt_s2*S^d!UfsXt(fjZEZ#H$Qx1Q|fwg|1iYjEM>a^Ixv))~e+LYq^i?*^%+ zL^v<2Qr}hG_UD6WlHIOX`TuhNt=b>acGC9Na|xpxGnzZsOsxxi*8H-HuQ<1AzejUK8|S$z*|mNlY|`30JrzvcJ0?DD*H%8s-|VSt8B!^=JW-`Eox_nicVrA+e#|g9 z`TgMUHuJp8XZ}>Iy^x=!P_uf{ysd%V`(LcG|EFWhyv5aqAz4E0zJE>Y!6(%!hhEkC zy*bbl9CiLz+LA>f6L=+a_!Bpl)|&2K{$lsckS!(6|z89h3Rtsv)$X1ubuw?!+-ye_WwV-bP0l+XkKT83M- From f5b23fffd4494d1d799eaaef7fad4e4c0b926d50 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sat, 6 May 2017 15:03:42 +0300 Subject: [PATCH 1943/2280] Replaced all AssertNotExists with AssertExists --- test/test_ui.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index fd65ab0a6..0f5ad5d67 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -506,7 +506,7 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertExists(self.itempath) def test_copy_item(self): self._move(copy=True) @@ -520,7 +520,7 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertExists(self.itempath) def test_copy_album(self): self._move(copy=True, album=True) @@ -534,14 +534,14 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertExists(self.itempath) def test_move_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertExists(self.itempath) def test_pretend_move_item(self): self._move(dest=self.otherdir, pretend=True) From 0dc948d9d34cb81e63543767a088f41b50182899 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Thu, 11 May 2017 12:11:21 +0300 Subject: [PATCH 1944/2280] Made sure that the destination directory will exist --- beets/ui/commands.py | 9 +++++++-- test/test_ui.py | 2 ++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 7e2095dd1..db34ed872 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1481,13 +1481,18 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, for obj in objs]) else: if export: + if album: for obj in objs: for item in obj.items(): + # Create necessary ancestry for the copy. + util.mkdirall(item.destination(basedir=dest)) util.copy(item.path, item.destination(basedir=dest)) else: - for item in objs: - util.copy(item.path, item.destination(basedir=dest)) + for obj in objs: + # Create necessary ancestry for the copy. + util.mkdirall(obj.destination(basedir=dest)) + util.copy(obj.path, obj.destination(basedir=dest)) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, diff --git a/test/test_ui.py b/test/test_ui.py index 0f5ad5d67..33266d379 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -543,6 +543,8 @@ class ExportTest(_common.TestCase): self.assertExists(self.i.path) self.assertExists(self.itempath) + + def test_pretend_move_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() From 51835e762ffe10b279d7a49e459327acdc502630 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Thu, 11 May 2017 12:30:21 +0300 Subject: [PATCH 1945/2280] Minor fixes to move tests --- test/test_ui.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index 33266d379..f017d8210 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -506,7 +506,7 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) - self.assertExists(self.itempath) + self.assertNotExists(self.itempath) def test_copy_item(self): self._move(copy=True) @@ -520,7 +520,7 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) - self.assertExists(self.itempath) + self.assertNotExists(self.itempath) def test_copy_album(self): self._move(copy=True, album=True) @@ -534,14 +534,14 @@ class ExportTest(_common.TestCase): self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) - self.assertExists(self.itempath) + self.assertNotExists(self.itempath) def test_move_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) - self.assertExists(self.itempath) + self.assertNotExists(self.itempath) From c4ef23d9f716d889206391bdd3811c59467f1192 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Thu, 11 May 2017 12:45:03 +0300 Subject: [PATCH 1946/2280] Minor Flake fixes --- test/test_ui.py | 72 ++++++++++++++++++++++++------------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index f017d8210..92a4d4ddb 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -156,7 +156,6 @@ class RemoveTest(_common.TestCase): class ModifyTest(unittest.TestCase, TestHelper): - def setUp(self): self.setup_beets() self.album = self.add_album_fixture() @@ -347,7 +346,6 @@ class ModifyTest(unittest.TestCase, TestHelper): class WriteTest(unittest.TestCase, TestHelper): - def setUp(self): self.setup_beets() @@ -476,6 +474,7 @@ class MoveTest(_common.TestCase): self.i.load() self.assertIn(b'srcfile', self.i.path) + class ExportTest(_common.TestCase): def setUp(self): super(ExportTest, self).setUp() @@ -499,7 +498,8 @@ class ExportTest(_common.TestCase): def _move(self, query=(), dest=None, copy=False, album=False, pretend=False, export=True): - commands.move_items(self.lib, dest, query, copy, album, pretend, export) + commands.move_items(self.lib, dest, query, copy, album, + pretend, export) def test_move_item(self): self._move() @@ -543,8 +543,6 @@ class ExportTest(_common.TestCase): self.assertExists(self.i.path) self.assertNotExists(self.itempath) - - def test_pretend_move_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() @@ -901,37 +899,37 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') -# @unittest.skip('Difficult to implement with optparse') -# def test_multiple_cli_config_files(self): -# cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') -# cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') -# -# with open(cli_config_path_1, 'w') as file: -# file.write('first: value') -# -# with open(cli_config_path_2, 'w') as file: -# file.write('second: value') -# -# self.run_command('--config', cli_config_path_1, -# '--config', cli_config_path_2, 'test', lib=None) -# self.assertEqual(config['first'].get(), 'value') -# self.assertEqual(config['second'].get(), 'value') -# -# @unittest.skip('Difficult to implement with optparse') -# def test_multiple_cli_config_overwrite(self): -# cli_config_path = os.path.join(self.temp_dir, b'config.yaml') -# cli_overwrite_config_path = os.path.join(self.temp_dir, -# b'overwrite_config.yaml') -# -# with open(cli_config_path, 'w') as file: -# file.write('anoption: value') -# -# with open(cli_overwrite_config_path, 'w') as file: -# file.write('anoption: overwrite') -# -# self.run_command('--config', cli_config_path, -# '--config', cli_overwrite_config_path, 'test') -# self.assertEqual(config['anoption'].get(), 'cli overwrite') + # @unittest.skip('Difficult to implement with optparse') + # def test_multiple_cli_config_files(self): + # cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') + # cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') + # + # with open(cli_config_path_1, 'w') as file: + # file.write('first: value') + # + # with open(cli_config_path_2, 'w') as file: + # file.write('second: value') + # + # self.run_command('--config', cli_config_path_1, + # '--config', cli_config_path_2, 'test', lib=None) + # self.assertEqual(config['first'].get(), 'value') + # self.assertEqual(config['second'].get(), 'value') + # + # @unittest.skip('Difficult to implement with optparse') + # def test_multiple_cli_config_overwrite(self): + # cli_config_path = os.path.join(self.temp_dir, b'config.yaml') + # cli_overwrite_config_path = os.path.join(self.temp_dir, + # b'overwrite_config.yaml') + # + # with open(cli_config_path, 'w') as file: + # file.write('anoption: value') + # + # with open(cli_overwrite_config_path, 'w') as file: + # file.write('anoption: overwrite') + # + # self.run_command('--config', cli_config_path, + # '--config', cli_overwrite_config_path, 'test') + # self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_paths_resolve_relative_to_user_dir(self): cli_config_path = os.path.join(self.temp_dir, b'config.yaml') @@ -1271,6 +1269,7 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): """Test CommonOptionsParser and formatting LibModel formatting on 'list' command. """ + def setUp(self): self.setup_beets() self.lib = library.Library(':memory:') @@ -1467,5 +1466,6 @@ class EncodingTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) + if __name__ == '__main__': unittest.main(defaultTest='suite') From e4441437f5ab4c9ecb1f8976aaa6ac122c9a46e2 Mon Sep 17 00:00:00 2001 From: dosoe Date: Fri, 12 May 2017 11:36:30 +0200 Subject: [PATCH 1947/2280] Corrected line length --- beets/autotag/mb.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index c2172d0ac..9da709160 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -219,7 +219,8 @@ def track_info(recording, index=None, medium=None, medium_index=None, lyricist.append(artist_relation['artist']['name']) elif type == 'composer': composer.append(artist_relation['artist']['name']) - composer_sort.append(artist_relation['artist']['sort-name']) + composer_sort.append( + artist_relation['artist']['sort-name']) if lyricist: info.lyricist = u', '.join(lyricist) if composer: From 8f62e8bc684a9f943baa1db4eaac1b5b43a09ec2 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Fri, 12 May 2017 14:49:03 +0300 Subject: [PATCH 1948/2280] Requested changes done --- beets/ui/commands.py | 16 ++++---- test/test_ui.py | 93 +++++++++++++++++--------------------------- 2 files changed, 45 insertions(+), 64 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index db34ed872..b7792d0cf 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1447,6 +1447,12 @@ modify_cmd.parser.add_option( modify_cmd.func = modify_func default_commands.append(modify_cmd) +#export(file) function copies a file without modifying the database. + +def export(file): + # Create necessary ancestry for the copy. + util.mkdirall(file.destination(basedir=dest)) + util.copy(file.path, file.destination(basedir=dest)) # move: Move/copy files to the library or a new base directory. @@ -1480,19 +1486,15 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: + #Copying files without modifying the database. if export: - if album: for obj in objs: for item in obj.items(): - # Create necessary ancestry for the copy. - util.mkdirall(item.destination(basedir=dest)) - util.copy(item.path, item.destination(basedir=dest)) + export(item) else: for obj in objs: - # Create necessary ancestry for the copy. - util.mkdirall(obj.destination(basedir=dest)) - util.copy(obj.path, obj.destination(basedir=dest)) + export(obj) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, diff --git a/test/test_ui.py b/test/test_ui.py index 92a4d4ddb..f34cf72cb 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -501,54 +501,33 @@ class ExportTest(_common.TestCase): commands.move_items(self.lib, dest, query, copy, album, pretend, export) - def test_move_item(self): + def test_export_item(self): self._move() self.i.load() self.assertTrue(b'testlibdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) - def test_copy_item(self): - self._move(copy=True) - self.i.load() - self.assertTrue(b'testlibdir' in self.i.path) - self.assertExists(self.i.path) - self.assertExists(self.itempath) - - def test_move_album(self): - self._move(album=True) - self.i.load() - self.assertTrue(b'testlibdir' in self.i.path) - self.assertExists(self.i.path) - self.assertNotExists(self.itempath) - - def test_copy_album(self): - self._move(copy=True, album=True) - self.i.load() - self.assertTrue(b'testlibdir' in self.i.path) - self.assertExists(self.i.path) - self.assertExists(self.itempath) - - def test_move_item_custom_dir(self): + def test_export_item_custom_dir(self): self._move(dest=self.otherdir) self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) - def test_move_album_custom_dir(self): + def test_export_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() self.assertTrue(b'testotherdir' in self.i.path) self.assertExists(self.i.path) self.assertNotExists(self.itempath) - def test_pretend_move_item(self): + def test_pretend_export_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() self.assertIn(b'srcfile', self.i.path) - def test_pretend_move_album(self): + def test_pretend_export_album(self): self._move(album=True, pretend=True) self.i.load() self.assertIn(b'srcfile', self.i.path) @@ -899,37 +878,37 @@ class ConfigTest(unittest.TestCase, TestHelper, _common.Assertions): self.run_command('--config', cli_config_path, 'test', lib=None) self.assertEqual(config['anoption'].get(), 'cli overwrite') - # @unittest.skip('Difficult to implement with optparse') - # def test_multiple_cli_config_files(self): - # cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') - # cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') - # - # with open(cli_config_path_1, 'w') as file: - # file.write('first: value') - # - # with open(cli_config_path_2, 'w') as file: - # file.write('second: value') - # - # self.run_command('--config', cli_config_path_1, - # '--config', cli_config_path_2, 'test', lib=None) - # self.assertEqual(config['first'].get(), 'value') - # self.assertEqual(config['second'].get(), 'value') - # - # @unittest.skip('Difficult to implement with optparse') - # def test_multiple_cli_config_overwrite(self): - # cli_config_path = os.path.join(self.temp_dir, b'config.yaml') - # cli_overwrite_config_path = os.path.join(self.temp_dir, - # b'overwrite_config.yaml') - # - # with open(cli_config_path, 'w') as file: - # file.write('anoption: value') - # - # with open(cli_overwrite_config_path, 'w') as file: - # file.write('anoption: overwrite') - # - # self.run_command('--config', cli_config_path, - # '--config', cli_overwrite_config_path, 'test') - # self.assertEqual(config['anoption'].get(), 'cli overwrite') +# @unittest.skip('Difficult to implement with optparse') +# def test_multiple_cli_config_files(self): +# cli_config_path_1 = os.path.join(self.temp_dir, b'config.yaml') +# cli_config_path_2 = os.path.join(self.temp_dir, b'config_2.yaml') +# +# with open(cli_config_path_1, 'w') as file: +# file.write('first: value') +# +# with open(cli_config_path_2, 'w') as file: +# file.write('second: value') +# +# self.run_command('--config', cli_config_path_1, +# '--config', cli_config_path_2, 'test', lib=None) +# self.assertEqual(config['first'].get(), 'value') +# self.assertEqual(config['second'].get(), 'value') +# +# @unittest.skip('Difficult to implement with optparse') +# def test_multiple_cli_config_overwrite(self): +# cli_config_path = os.path.join(self.temp_dir, b'config.yaml') +# cli_overwrite_config_path = os.path.join(self.temp_dir, +# b'overwrite_config.yaml') +# +# with open(cli_config_path, 'w') as file: +# file.write('anoption: value') +# +# with open(cli_overwrite_config_path, 'w') as file: +# file.write('anoption: overwrite') +# +# self.run_command('--config', cli_config_path, +# '--config', cli_overwrite_config_path, 'test') +# self.assertEqual(config['anoption'].get(), 'cli overwrite') def test_cli_config_paths_resolve_relative_to_user_dir(self): cli_config_path = os.path.join(self.temp_dir, b'config.yaml') From 169cf596b0f98edcddcc7a9fda791721d3c37f45 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Fri, 12 May 2017 15:08:06 +0300 Subject: [PATCH 1949/2280] Fixed bool variable error --- beets/ui/commands.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index b7792d0cf..64f3229d5 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1447,13 +1447,6 @@ modify_cmd.parser.add_option( modify_cmd.func = modify_func default_commands.append(modify_cmd) -#export(file) function copies a file without modifying the database. - -def export(file): - # Create necessary ancestry for the copy. - util.mkdirall(file.destination(basedir=dest)) - util.copy(file.path, file.destination(basedir=dest)) - # move: Move/copy files to the library or a new base directory. def move_items(lib, dest, query, copy, album, pretend, export=False, @@ -1488,6 +1481,12 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, else: #Copying files without modifying the database. if export: + # export(file) function copies a file without modifying the database. + + def export(file): + # Create necessary ancestry for the copy. + util.mkdirall(file.destination(basedir=dest)) + util.copy(file.path, file.destination(basedir=dest)) if album: for obj in objs: for item in obj.items(): From 7c9198934488c6b5b9ee7e11a3e1275d901c3a8a Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Fri, 12 May 2017 15:25:36 +0300 Subject: [PATCH 1950/2280] Minor flake fixes --- beets/ui/commands.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 64f3229d5..7ffa90b11 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1447,6 +1447,7 @@ modify_cmd.parser.add_option( modify_cmd.func = modify_func default_commands.append(modify_cmd) + # move: Move/copy files to the library or a new base directory. def move_items(lib, dest, query, copy, album, pretend, export=False, @@ -1479,9 +1480,10 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: - #Copying files without modifying the database. + # Copying files without modifying the database. if export: - # export(file) function copies a file without modifying the database. + # export(file) function copies a file without modifying + # the database. def export(file): # Create necessary ancestry for the copy. @@ -1490,7 +1492,7 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, if album: for obj in objs: for item in obj.items(): - export(item) + export(item) else: for obj in objs: export(obj) From 9ccaad27d3f59cda60fcffb5dc0223cd9e10ae95 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 12 May 2017 10:42:50 -0400 Subject: [PATCH 1951/2280] Undo some noisy whitespace changes --- beets/mediafile.py | 1 + test/test_mediafile.py | 46 +++++++++++++++++++++--------------------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 234e0daba..9242ab1f1 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -1650,6 +1650,7 @@ class MediaFile(object): StorageStyle('ARRANGER'), ASFStorageStyle('beets/Arranger'), ) + grouping = MediaField( MP3StorageStyle('TIT1'), MP4StorageStyle('\xa9grp'), diff --git a/test/test_mediafile.py b/test/test_mediafile.py index f1066c56f..18dcc11a3 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -318,29 +318,29 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, """ full_initial_tags = { - 'title': u'full', - 'artist': u'the artist', - 'album': u'the album', - 'genre': u'the genre', - 'composer': u'the composer', - 'grouping': u'the grouping', - 'year': 2001, - 'month': None, - 'day': None, - 'date': datetime.date(2001, 1, 1), - 'track': 2, - 'tracktotal': 3, - 'disc': 4, - 'disctotal': 5, - 'lyrics': u'the lyrics', - 'comments': u'the comments', - 'bpm': 6, - 'comp': True, - 'mb_trackid': '8b882575-08a5-4452-a7a7-cbb8a1531f9e', - 'mb_albumid': '9e873859-8aa4-4790-b985-5a953e8ef628', - 'mb_artistid': '7cf0ea9d-86b9-4dad-ba9e-2355a64899ea', - 'art': None, - 'label': u'the label', + 'title': u'full', + 'artist': u'the artist', + 'album': u'the album', + 'genre': u'the genre', + 'composer': u'the composer', + 'grouping': u'the grouping', + 'year': 2001, + 'month': None, + 'day': None, + 'date': datetime.date(2001, 1, 1), + 'track': 2, + 'tracktotal': 3, + 'disc': 4, + 'disctotal': 5, + 'lyrics': u'the lyrics', + 'comments': u'the comments', + 'bpm': 6, + 'comp': True, + 'mb_trackid': '8b882575-08a5-4452-a7a7-cbb8a1531f9e', + 'mb_albumid': '9e873859-8aa4-4790-b985-5a953e8ef628', + 'mb_artistid': '7cf0ea9d-86b9-4dad-ba9e-2355a64899ea', + 'art': None, + 'label': u'the label', } tag_fields = [ From 5eca5181065d462e1a8adb1bb1cc7099e65f0e65 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 12 May 2017 12:41:51 -0400 Subject: [PATCH 1952/2280] Changelog for #2529, which fixes #2519 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index bf0d7d254..7edd51cc2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -57,6 +57,10 @@ New features: Thanks to :user:`jansol`. :bug:`2488` :bug:`2524` +* A new field, ``composer_sort``, is now supported and fetched from + MusicBrainz. + Thanks to :user:`dosoe`. + :bug:`2519` :bug:`2529` Fixes: From 3c852d3539aafa2c9ad76a72ac88416379110139 Mon Sep 17 00:00:00 2001 From: SpirosChadoulos Date: Sat, 13 May 2017 12:26:31 +0300 Subject: [PATCH 1953/2280] docs --- docs/reference/cli.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 403c1e174..7baa25f05 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -72,7 +72,7 @@ box. To extract `rar` files, install the `rarfile`_ package and the Optional command flags: * By default, the command copies files your the library directory and - updates the ID3 tags on your music. In order to move the files, instead of + updates the ID3 tags on your music. In order to move the files, instead of copying, use the ``-m`` (move) option. If you'd like to leave your music files untouched, try the ``-C`` (don't copy) and ``-W`` (don't write tags) options. You can also disable this behavior by default in the @@ -275,6 +275,7 @@ query are renamed into your library directory structure. By specifying a destination directory with ``-d`` manually, you can move items matching a query anywhere in your filesystem. The ``-c`` option copies files instead of moving them. As with other commands, the ``-a`` option matches albums instead of items. +The ``-e`` flag (for "export") copies files without changing the database. To perform a "dry run", just use the ``-p`` (for "pretend") flag. This will show you a list of files that would be moved but won't actually change anything From 9840964f51fed3b3d0dcc1db9c76f90be4c05e73 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 16 May 2017 14:00:10 -0400 Subject: [PATCH 1954/2280] Fix #2562: avoid crash with newlines in templates Turns out! The $ character in Python regexes also matches before the last newline at the end of a string, not just at the end of a string. The \Z entity does what we really want: the *real* end of the string. --- beets/util/functemplate.py | 9 ++++++--- docs/changelog.rst | 1 + test/test_template.py | 5 +++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/beets/util/functemplate.py b/beets/util/functemplate.py index 58b0416a1..0e13db4a0 100644 --- a/beets/util/functemplate.py +++ b/beets/util/functemplate.py @@ -325,7 +325,7 @@ class Parser(object): # Common parsing resources. special_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_OPEN, GROUP_CLOSE, ESCAPE_CHAR) - special_char_re = re.compile(r'[%s]|$' % + special_char_re = re.compile(r'[%s]|\Z' % u''.join(re.escape(c) for c in special_chars)) escapable_chars = (SYMBOL_DELIM, FUNC_DELIM, GROUP_CLOSE, ARG_SEP) terminator_chars = (GROUP_CLOSE,) @@ -343,8 +343,11 @@ class Parser(object): if self.in_argument: extra_special_chars = (ARG_SEP,) special_char_re = re.compile( - r'[%s]|$' % u''.join(re.escape(c) for c in - self.special_chars + extra_special_chars)) + r'[%s]|\Z' % u''.join( + re.escape(c) for c in + self.special_chars + extra_special_chars + ) + ) text_parts = [] diff --git a/docs/changelog.rst b/docs/changelog.rst index 7edd51cc2..9caca1280 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -106,6 +106,7 @@ Fixes: error message. Thanks to :user:`Mary011196`. :bug:`1676` :bug:`2508` * :doc:`/plugins/web`: Avoid a crash when sending binary data, such as Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` +* Fix a hang when parsing templates that end in newlines. :bug:`2562` Two plugins had backends removed due to bitrot: diff --git a/test/test_template.py b/test/test_template.py index 1cbe9be0c..288bc2314 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -227,6 +227,11 @@ class ParseTest(unittest.TestCase): self.assertEqual(parts[2], u',') self._assert_symbol(parts[3], u"bar") + def test_newline_at_end(self): + parts = list(_normparse(u'foo\n')) + self.assertEqual(len(parts), 1) + self.assertEqual(parts[0], u'foo\n') + class EvalTest(unittest.TestCase): def _eval(self, template): From 060041a69e4646b87dec85e0125f6d8a41648152 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 17 May 2017 10:19:18 -0400 Subject: [PATCH 1955/2280] Load YAML as binary data This lets the YAML library itself deal with the encoding (mostly), which should address #2456 and #2565, which have to do with `open` giving us a system-specific encoding by default on Python 3 on Windows when the files should have been written using UTF-8 per the YAML standard. --- beets/util/confit.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 373e05ffc..73ae97abc 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -668,7 +668,7 @@ def load_yaml(filename): parsed, a ConfigReadError is raised. """ try: - with open(filename, 'r') as f: + with open(filename, 'rb') as f: return yaml.load(f, Loader=Loader) except (IOError, yaml.error.YAMLError) as exc: raise ConfigReadError(filename, exc) @@ -908,9 +908,10 @@ class Configuration(RootView): default_source = source break if default_source and default_source.filename: - with open(default_source.filename, 'r') as fp: + with open(default_source.filename, 'rb') as fp: default_data = fp.read() - yaml_out = restore_yaml_comments(yaml_out, default_data) + yaml_out = restore_yaml_comments(yaml_out, + default_data.decode('utf8')) return yaml_out From 35dd6fdf217aca5f2685df9a379ff79f238d396e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 17 May 2017 10:22:44 -0400 Subject: [PATCH 1956/2280] Changelog for #2566 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 9caca1280..caea9c6a4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -107,6 +107,8 @@ Fixes: * :doc:`/plugins/web`: Avoid a crash when sending binary data, such as Chromaprint fingerprints, in music attributes. :bug:`2542` :bug:`2532` * Fix a hang when parsing templates that end in newlines. :bug:`2562` +* Fix a crash when reading non-ASCII characters in configuration files on + Windows under Python 3. :bug:`2456` :bug:`2565` :bug:`2566` Two plugins had backends removed due to bitrot: From 9fe171c5cedd1a2abd96679d89ffc159239b1985 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= Date: Wed, 17 May 2017 21:37:38 +0200 Subject: [PATCH 1957/2280] properly safe cast unicode as int --- beets/mediafile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index 9242ab1f1..50c2cb76b 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -154,10 +154,12 @@ def _safe_cast(out_type, val): return int(val) else: # Process any other type as a string. - if not isinstance(val, six.string_types): + if isinstance(val, bytes): + val = val.decode('utf-8', 'ignore') + elif not isinstance(val, six.string_types): val = six.text_type(val) # Get a number from the front of the string. - val = re.match(r'[0-9]*', val.strip()).group(0) + val = re.match(r'[\+-]?[0-9]*', val.strip()).group(0) if not val: return 0 else: From ddfe44266b3e2588a11884f1d3b3ba530c3800d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= Date: Wed, 17 May 2017 21:41:12 +0200 Subject: [PATCH 1958/2280] r128 gain tags in mediafile test --- test/test_mediafile.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/test_mediafile.py b/test/test_mediafile.py index 18dcc11a3..5a004b7e8 100644 --- a/test/test_mediafile.py +++ b/test/test_mediafile.py @@ -374,6 +374,8 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, 'rg_track_gain', 'rg_album_peak', 'rg_album_gain', + 'r128_track_gain', + 'r128_album_gain', 'albumartist', 'mb_albumartistid', 'artist_sort', @@ -672,6 +674,9 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin, if key.startswith('rg_'): # ReplayGain is float tags[key] = 1.0 + elif key.startswith('r128_'): + # R128 is int + tags[key] = -1 else: tags[key] = 'value\u2010%s' % key From 2685f133152c6b059ab116560c5ee357c6550404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= Date: Sat, 13 May 2017 19:50:43 +0200 Subject: [PATCH 1959/2280] replaygain: support r128 --- beets/library.py | 4 ++ beets/mediafile.py | 32 +++++++++++++++ beetsplug/replaygain.py | 86 +++++++++++++++++++++++++++++++++++++---- 3 files changed, 114 insertions(+), 8 deletions(-) diff --git a/beets/library.py b/beets/library.py index 4b2b194fc..991de59e8 100644 --- a/beets/library.py +++ b/beets/library.py @@ -454,6 +454,8 @@ class Item(LibModel): 'rg_track_peak': types.NULL_FLOAT, 'rg_album_gain': types.NULL_FLOAT, 'rg_album_peak': types.NULL_FLOAT, + 'r128_track_gain': types.PaddedInt(6), + 'r128_album_gain': types.PaddedInt(6), 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), @@ -898,6 +900,7 @@ class Album(LibModel): 'albumdisambig': types.STRING, 'rg_album_gain': types.NULL_FLOAT, 'rg_album_peak': types.NULL_FLOAT, + 'r128_album_gain': types.PaddedInt(6), 'original_year': types.PaddedInt(4), 'original_month': types.PaddedInt(2), 'original_day': types.PaddedInt(2), @@ -941,6 +944,7 @@ class Album(LibModel): 'albumdisambig', 'rg_album_gain', 'rg_album_peak', + 'r128_album_gain', 'original_year', 'original_month', 'original_day', diff --git a/beets/mediafile.py b/beets/mediafile.py index 50c2cb76b..d928e05c4 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -2007,6 +2007,38 @@ class MediaFile(object): out_type=float, ) + # EBU R128 fields. + r128_track_gain = MediaField( + MP3DescStorageStyle( + u'R128_TRACK_GAIN' + ), + MP4StorageStyle( + '----:com.apple.iTunes:R128_TRACK_GAIN' + ), + StorageStyle( + u'R128_TRACK_GAIN' + ), + ASFStorageStyle( + u'R128_TRACK_GAIN' + ), + out_type=int, + ) + r128_album_gain = MediaField( + MP3DescStorageStyle( + u'R128_ALBUM_GAIN' + ), + MP4StorageStyle( + '----:com.apple.iTunes:R128_ALBUM_GAIN' + ), + StorageStyle( + u'R128_ALBUM_GAIN' + ), + ASFStorageStyle( + u'R128_ALBUM_GAIN' + ), + out_type=int, + ) + initial_key = MediaField( MP3StorageStyle('TKEY'), MP4StorageStyle('----:com.apple.iTunes:initialkey'), diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 4cf7da7c5..69fa8d6c1 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -805,6 +805,7 @@ class ReplayGainPlugin(BeetsPlugin): 'auto': True, 'backend': u'command', 'targetlevel': 89, + 'r128': ['Opus'], }) self.overwrite = self.config['overwrite'].get(bool) @@ -822,6 +823,9 @@ class ReplayGainPlugin(BeetsPlugin): if self.config['auto']: self.import_stages = [self.imported] + # Formats to use R128. + self.r128_whitelist = self.config['r128'].as_str_seq() + try: self.backend_instance = self.backends[backend_name]( self.config, self._log @@ -830,9 +834,19 @@ class ReplayGainPlugin(BeetsPlugin): raise ui.UserError( u'replaygain initialization failed: {0}'.format(e)) + self.r128_backend_instance = '' + + def should_use_r128(self, item): + """Checks the plugin setting to decide whether the calculation + should be done using the EBU R128 standard and use R128_ tags instead. + """ + return item.format in self.r128_whitelist + def track_requires_gain(self, item): return self.overwrite or \ - (not item.rg_track_gain or not item.rg_track_peak) + (self.should_use_r128(item) and not item.r128_track_gain) or \ + (not self.should_use_r128(item) and + (not item.rg_track_gain or not item.rg_track_peak)) def album_requires_gain(self, album): # Skip calculating gain only when *all* files don't need @@ -840,8 +854,12 @@ class ReplayGainPlugin(BeetsPlugin): # needs recalculation, we still get an accurate album gain # value. return self.overwrite or \ - any([not item.rg_album_gain or not item.rg_album_peak - for item in album.items()]) + any([self.should_use_r128(item) and + (not item.r128_item_gain or not item.r128_album_gain) + for item in album.items()]) or \ + any([not self.should_use_r128(item) and + (not item.rg_album_gain or not item.rg_album_peak) + for item in album.items()]) def store_track_gain(self, item, track_gain): item.rg_track_gain = track_gain.gain @@ -851,6 +869,12 @@ class ReplayGainPlugin(BeetsPlugin): self._log.debug(u'applied track gain {0}, peak {1}', item.rg_track_gain, item.rg_track_peak) + def store_track_r128_gain(self, item, track_gain): + item.r128_track_gain = int(round(track_gain.gain * pow(2, 8))) + item.store() + + self._log.debug(u'applied track gain {0}', item.r128_track_gain) + def store_album_gain(self, album, album_gain): album.rg_album_gain = album_gain.gain album.rg_album_peak = album_gain.peak @@ -859,6 +883,12 @@ class ReplayGainPlugin(BeetsPlugin): self._log.debug(u'applied album gain {0}, peak {1}', album.rg_album_gain, album.rg_album_peak) + def store_album_r128_gain(self, album, album_gain): + album.r128_album_gain = int(round(album_gain.gain * pow(2, 8))) + album.store() + + self._log.debug(u'applied album gain {0}', album.r128_album_gain) + def handle_album(self, album, write): """Compute album and track replay gain store it in all of the album's items. @@ -873,17 +903,35 @@ class ReplayGainPlugin(BeetsPlugin): self._log.info(u'analyzing {0}', album) + if (any([self.should_use_r128(item) for item in album.items()]) and + all(([self.should_use_r128(item) for item in album.items()]))): + raise ReplayGainError( + u"Mix of ReplayGain and EBU R128 detected" + u"for some tracks in album {0}".format(album) + ) + + if any([self.should_use_r128(item) for item in album.items()]): + if self.r128_backend_instance == '': + self.init_r128_backend() + backend_instance = self.r128_backend_instance + store_track_gain = self.store_track_r128_gain + store_album_gain = self.store_album_r128_gain + else: + backend_instance = self.backend_instance + store_track_gain = self.store_track_gain + store_album_gain = self.store_album_gain + try: - album_gain = self.backend_instance.compute_album_gain(album) + album_gain = backend_instance.compute_album_gain(album) if len(album_gain.track_gains) != len(album.items()): raise ReplayGainError( u"ReplayGain backend failed " u"for some tracks in album {0}".format(album) ) - self.store_album_gain(album, album_gain.album_gain) + store_album_gain(album, album_gain.album_gain) for item, track_gain in zip(album.items(), album_gain.track_gains): - self.store_track_gain(item, track_gain) + store_track_gain(item, track_gain) if write: item.try_write() except ReplayGainError as e: @@ -905,14 +953,23 @@ class ReplayGainPlugin(BeetsPlugin): self._log.info(u'analyzing {0}', item) + if self.should_use_r128(item): + if self.r128_backend_instance == '': + self.init_r128_backend() + backend_instance = self.r128_backend_instance + store_track_gain = self.store_track_r128_gain + else: + backend_instance = self.backend_instance + store_track_gain = self.store_track_gain + try: - track_gains = self.backend_instance.compute_track_gain([item]) + track_gains = backend_instance.compute_track_gain([item]) if len(track_gains) != 1: raise ReplayGainError( u"ReplayGain backend failed for track {0}".format(item) ) - self.store_track_gain(item, track_gains[0]) + store_track_gain(item, track_gains[0]) if write: item.try_write() except ReplayGainError as e: @@ -921,6 +978,19 @@ class ReplayGainPlugin(BeetsPlugin): raise ui.UserError( u"Fatal replay gain error: {0}".format(e)) + def init_r128_backend(self): + backend_name = 'bs1770gain' + + try: + self.r128_backend_instance = self.backends[backend_name]( + self.config, self._log + ) + except (ReplayGainError, FatalReplayGainError) as e: + raise ui.UserError( + u'replaygain initialization failed: {0}'.format(e)) + + self.r128_backend_instance.method = '--ebu' + def imported(self, session, task): """Add replay gain info to items or albums of ``task``. """ From 8168a88a7f6e401c7a982567f44d7e55e41f09d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= Date: Wed, 17 May 2017 21:58:41 +0200 Subject: [PATCH 1960/2280] update replaygain docs with info about r128 --- docs/plugins/replaygain.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plugins/replaygain.rst b/docs/plugins/replaygain.rst index 6f119e2b0..838a2ea2b 100644 --- a/docs/plugins/replaygain.rst +++ b/docs/plugins/replaygain.rst @@ -108,6 +108,10 @@ configuration file. The available options are: Default: ``no``. - **targetlevel**: A number of decibels for the target loudness level. Default: 89. +- **r128**: A space separated list of formats that will use ``R128_`` tags with + integer values instead of the common ``REPLAYGAIN_`` tags with floating point + values. Requires the "bs1770gain" backend. + Default: ``Opus``. These options only work with the "command" backend: From a93414dc9d3f801126e9d4bb47a35429aad9f1e0 Mon Sep 17 00:00:00 2001 From: Scott Leggett Date: Thu, 25 May 2017 22:38:57 +1000 Subject: [PATCH 1961/2280] Document gapless mp3 encoding. --- docs/plugins/convert.rst | 49 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index b8069506d..99ce0de15 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -140,3 +140,52 @@ and the given command is used for all conversions. convert: command: ffmpeg -i $source -y -vn -aq 2 $dest extension: mp3 + + +Gapless MP3 encoding +```````````````````` + +Due to limitations in the ``ffmpeg`` encoder, by default the ``convert`` plugin +does not produce MP3s with accurate length tags (it does not write a LAME MP3 +info tag). This means that the MP3s are not "`gapless`_", and can result in +noticeable gaps between tracks during playback. + +.. _gapless: http://wiki.hydrogenaud.io/index.php?title=Gapless_playback + +To work around this problem, you must use the `LAME`_ MP3 encoder, which will +produce MP3s with accurate length tags. + +.. _LAME: http://lame.sourceforge.net/ + +To do this on Linux, you need to install ``lame``, create a script (e.g. +``/home/user/.config/beets/mp3.sh``) with the following contents, and make it +executable. + +:: + + #!/bin/sh + /usr/bin/ffmpeg -i "$1" -f wav - | /usr/bin/lame -V 2 --noreplaygain - "$2" + +Then configure the ``convert`` plugin to use the script. + +:: + + convert: + command: /home/user/.config/beets/mp3.sh $source $dest + extension: mp3 + +.. note:: + + In the script above, ``ffmpeg`` output format ``wav`` is used to produce an + accurate length header to pass to ``lame``. + + ``--noreplaygain`` configures ``lame`` not to do ReplayGain analysis and + tagging itself, because it can only do a track level analysis. Instead, you + can use the beets ``replaygain`` plugin to analyse and add both Album and + Track ReplayGain tags. + + See the ``lame`` `documentation`_ and the `HydrogenAudio wiki`_ for other + ``lame`` configuration options, and a thorough discussion of MP3 encoding. + +.. _documentation: http://lame.sourceforge.net/using.php +.. _HydrogenAudio wiki: http://wiki.hydrogenaud.io/index.php?title=LAME From 348e04464a3faf267b80c5678012c0d5388a9025 Mon Sep 17 00:00:00 2001 From: Scott Leggett Date: Fri, 26 May 2017 07:26:07 +1000 Subject: [PATCH 1962/2280] Remove absolute paths from sample script. --- docs/plugins/convert.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 99ce0de15..89f114a11 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -164,7 +164,7 @@ executable. :: #!/bin/sh - /usr/bin/ffmpeg -i "$1" -f wav - | /usr/bin/lame -V 2 --noreplaygain - "$2" + ffmpeg -i "$1" -f wav - | lame -V 2 --noreplaygain - "$2" Then configure the ``convert`` plugin to use the script. From 1da972f4bb28569b1bed4676cb4302aabe5baf8d Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Tue, 30 May 2017 16:15:28 +0200 Subject: [PATCH 1963/2280] implemented `set_field` cli parsing --- beets/config_default.yaml | 3 ++- beets/ui/__init__.py | 18 ++++++++++++++++++ beets/ui/commands.py | 6 ++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index b7e6b1e2b..439a93f55 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -25,7 +25,8 @@ import: pretend: false search_ids: [] duplicate_action: ask - bell: no + bell: no + set_fields: {} clutter: ["Thumbs.DB", ".DS_Store"] ignore: [".*", "*~", "System Volume Information", "lost+found"] diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 60652fa08..0a215535b 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1060,6 +1060,24 @@ class SubcommandsOptionParser(CommonOptionsParser): suboptions, subargs = subcommand.parse_args(args) return subcommand, suboptions, subargs + @staticmethod + def _store_dict(option, opt_str, value, parser): + """Custom action callback to parse options which have ``key=value`` + pairs as values. All such pairs passed for this option are + aggregated into a dictionary. + """ + dest = option.dest + option_values = getattr(parser.values, dest, None) + + if option_values is None: + # This is the first supplied ``key=value`` pair of option. + # Initialize empty dictionary and get a reference to it. + setattr(parser.values, dest, dict()) + option_values = getattr(parser.values, dest) + + key, value = value.split('=') + option_values[key] = value + optparse.Option.ALWAYS_TYPED_ACTIONS += ('callback',) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 995ff87e9..39e2bcb45 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -40,6 +40,7 @@ from beets import config from beets import logging from beets.util.confit import _package_path import six +from . import SubcommandsOptionParser VARIOUS_ARTISTS = u'Various Artists' PromptChoice = namedtuple('PromptChoice', ['short', 'long', 'callback']) @@ -1017,6 +1018,11 @@ import_cmd.parser.add_option( metavar='ID', help=u'restrict matching to a specific metadata backend ID' ) +import_cmd.parser.add_option( + u'--set-field', dest='set_fields', action='callback', callback=SubcommandsOptionParser._store_dict, + metavar='FIELD=VALUE', + help=u'set the given fields to the supplied values after importing' +) import_cmd.func = import_func default_commands.append(import_cmd) From 569098a31804a72529e25d3a3a47cd9df7d1bb51 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Tue, 30 May 2017 16:56:33 +0200 Subject: [PATCH 1964/2280] store_dict parser action now stores unicode, and implementend set_fields functionality in importer --- beets/importer.py | 28 +++++++++++++++++++++++++++- beets/ui/__init__.py | 2 +- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index ce9ebc01c..801e0cdca 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -419,7 +419,7 @@ class ImportTask(BaseImportTask): from the `candidates` list. * `find_duplicates()` Returns a list of albums from `lib` with the - same artist and album name as the task. + same artist and album name as the task. * `apply_metadata()` Sets the attributes of the items from the task's `match` attribute. @@ -429,6 +429,9 @@ class ImportTask(BaseImportTask): * `manipulate_files()` Copy, move, and write files depending on the session configuration. + * `set_fields()` Sets the fields given at CLI or configuration to + the specified values. + * `finalize()` Update the import progress and cleanup the file system. """ @@ -529,6 +532,14 @@ class ImportTask(BaseImportTask): util.remove(item.path) util.prune_dirs(os.path.dirname(item.path), lib.directory) + def set_fields(self): + set_fields_dict = config['import']['set_fields'] + for field in set_fields_dict.keys(): + print(type(set_fields_dict[field].get())) + value = set_fields_dict[field].get() + log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) + self.album[field] = value + self.album.store() def finalize(self, session): """Save progress, clean up files, and emit plugin event. @@ -877,6 +888,16 @@ class SingletonImportTask(ImportTask): def reload(self): self.item.load() + def set_fields(self): + """Similar to ``ImportTask.set_fields``, but for singleton items. + """ + set_fields_dict = config['import']['set_fields'] + for field in set_fields_dict.keys(): + value = set_fields_dict[field].get() + log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) + self.item[field] = value + self.item.store() + # FIXME The inheritance relationships are inverted. This is why there # are so many methods which pass. More responsibility should be delegated to @@ -1385,6 +1406,11 @@ def apply_choice(session, task): task.add(session.lib) + # If ``set_fields`` is set, set those fields to the + # configured values. + if config['import']['set_fields']: + task.set_fields() + @pipeline.mutator_stage def plugin_stage(session, func, task): diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 0a215535b..7091dbbaf 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1075,7 +1075,7 @@ class SubcommandsOptionParser(CommonOptionsParser): setattr(parser.values, dest, dict()) option_values = getattr(parser.values, dest) - key, value = value.split('=') + key, value = map(lambda s: util.text_string(s), value.split('=')) option_values[key] = value From 91722aea36753de6658a03451e9e9b742a7cae41 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Tue, 30 May 2017 21:29:49 +0200 Subject: [PATCH 1965/2280] added documentation --- beets/importer.py | 12 +++++++++--- beets/ui/commands.py | 5 +++-- docs/changelog.rst | 5 +++++ docs/reference/cli.rst | 11 +++++++++++ docs/reference/config.rst | 20 ++++++++++++++++++++ 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 801e0cdca..247b46968 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -532,12 +532,15 @@ class ImportTask(BaseImportTask): util.remove(item.path) util.prune_dirs(os.path.dirname(item.path), lib.directory) + def set_fields(self): set_fields_dict = config['import']['set_fields'] for field in set_fields_dict.keys(): - print(type(set_fields_dict[field].get())) value = set_fields_dict[field].get() - log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) + log.debug(u'Set field {1}={2} for {0}', + displayable_path(self.paths), + field, + value) self.album[field] = value self.album.store() @@ -894,7 +897,10 @@ class SingletonImportTask(ImportTask): set_fields_dict = config['import']['set_fields'] for field in set_fields_dict.keys(): value = set_fields_dict[field].get() - log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) + log.debug(u'Set field {1}={2} for {0}', + displayable_path(self.paths), + field, + value) self.item[field] = value self.item.store() diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 39e2bcb45..240c776ee 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1019,9 +1019,10 @@ import_cmd.parser.add_option( help=u'restrict matching to a specific metadata backend ID' ) import_cmd.parser.add_option( - u'--set-field', dest='set_fields', action='callback', callback=SubcommandsOptionParser._store_dict, + u'--set-field', dest='set_fields', action='callback', + callback=SubcommandsOptionParser._store_dict, metavar='FIELD=VALUE', - help=u'set the given fields to the supplied values after importing' + help=u'set the given fields to the supplied values' ) import_cmd.func = import_func default_commands.append(import_cmd) diff --git a/docs/changelog.rst b/docs/changelog.rst index caea9c6a4..0da327ac4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -61,6 +61,11 @@ New features: MusicBrainz. Thanks to :user:`dosoe`. :bug:`2519` :bug:`2529` +* It is now possible to set fields to certain values during import, using + either the `importer.set_fields` dictionary in the config file, or by + passing one or more `--set-field field=value` options on the command-line. + :bug: `1881` + Fixes: diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index b4c7b9e1b..b9f29c9c9 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -138,6 +138,17 @@ Optional command flags: searching for other candidates by using the ``--search-id SEARCH_ID`` option. Multiple IDs can be specified by simply repeating the option several times. +* You can supply ``--set-field`` options with ``field=value`` pairs to assign to + those fields the specified values on import, in addition to such field/value + pairs defined in the ``importer.set_fields`` dictionary in the configuration + file. Make sure to use an option per field/value pair, like so: + :: + + beet import --set-field genre="Alternative Rock" --set-field mood="emotional" + + Note that values for the fields specified on the command-line override the + ones defined for those fields in the configuration file. + .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 .. only:: html diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 82c11238a..1018b9bb4 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -586,6 +586,26 @@ Ring the terminal bell to get your attention when the importer needs your input. Default: ``no``. +.. _set_fields: + +set_fields +~~~~~~~~~~ + +A dictionary of field/value pairs, each one used to set a field to the +corresponding value during import. + +Example: :: + + set_fields: + genre: 'To Listen' + collection: 'Unordered' + +Note that field/value pairs supplied via ``--set-field`` options on the +command-line are processed in addition to those specified here. Those values +override the ones defined here in the case of fields with the same name. + +Default: ``{}`` (empty). + .. _musicbrainz-config: MusicBrainz Options From b5a8891872d7e4b386a1cf9d381cde5706482503 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Wed, 31 May 2017 08:17:59 +0200 Subject: [PATCH 1966/2280] implemented error handling for invalid, non-key/value cli argumnets --- beets/ui/__init__.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 7091dbbaf..2cea00be7 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1075,7 +1075,15 @@ class SubcommandsOptionParser(CommonOptionsParser): setattr(parser.values, dest, dict()) option_values = getattr(parser.values, dest) - key, value = map(lambda s: util.text_string(s), value.split('=')) + try: + key, value = map(lambda s: util.text_string(s), value.split('=')) + if not (key and value): + raise ValueError + except ValueError: + raise UserError( + "supplied argument `{0}' is not of the form `key=value'" + .format(value)) + option_values[key] = value From c64878179eb007174203897050d485fb7549b215 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Thu, 1 Jun 2017 11:57:24 +0200 Subject: [PATCH 1967/2280] finished tests for set_fields on importer --- test/test_importer.py | 64 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/test/test_importer.py b/test/test_importer.py index 26dec3de8..cbfbda778 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -543,6 +543,38 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.assertEqual(len(self.lib.items()), 2) self.assertEqual(len(self.lib.albums()), 2) + def test_set_fields(self): + genre = u"\U0001F3B7 Jazz" + collection = u"To Listen" + + config['import']['set_fields'] = { + u'collection': collection, + u'genre': genre + } + + # As-is item import. + self.assertEqual(self.lib.albums().get(), None) + self.importer.add_choice(importer.action.ASIS) + self.importer.run() + + for item in self.lib.items(): + item.load() # TODO: Not sure this is necessary. + self.assertEqual(item.genre, genre) + self.assertEqual(item.collection, collection) + # Remove item from library to test again with APPLY choice. + item.remove() + + # Autotagged. + self.assertEqual(self.lib.albums().get(), None) + self.importer.clear_choices() + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + + for item in self.lib.items(): + item.load() + self.assertEqual(item.genre, genre) + self.assertEqual(item.collection, collection) + class ImportTest(_common.TestCase, ImportHelper): """Test APPLY, ASIS and SKIP choices. @@ -672,6 +704,38 @@ class ImportTest(_common.TestCase, ImportHelper): with self.assertRaises(AttributeError): self.lib.items().get().data_source + def test_set_fields(self): + genre = u"\U0001F3B7 Jazz" + collection = u"To Listen" + + config['import']['set_fields'] = { + u'collection': collection, + u'genre': genre + } + + # As-is album import. + self.assertEqual(self.lib.albums().get(), None) + self.importer.add_choice(importer.action.ASIS) + self.importer.run() + + for album in self.lib.albums(): + album.load() # TODO: Not sure this is necessary. + self.assertEqual(album.genre, genre) + self.assertEqual(album.collection, collection) + # Remove album from library to test again with APPLY choice. + album.remove() + + # Autotagged. + self.assertEqual(self.lib.albums().get(), None) + self.importer.clear_choices() + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + + for album in self.lib.albums(): + album.load() + self.assertEqual(album.genre, genre) + self.assertEqual(album.collection, collection) + class ImportTracksTest(_common.TestCase, ImportHelper): """Test TRACKS and APPLY choice. From e1101d4e95664ef593135b16c846886cb55532c8 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 1 Jun 2017 12:33:23 +0100 Subject: [PATCH 1968/2280] Update assertion with correct error name --- test/test_datequery.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index 6cd97fd30..71daa42e4 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -195,7 +195,7 @@ class DateQueryConstructTest(unittest.TestCase): self.assertEqual(date_query.interval.end, datetime(2000, 1, 1, 13)) def test_datetime_invalid_separator(self): - with self.assertRaises(InvalidQueryArgumentTypeError): + with self.assertRaises(InvalidQueryArgumentValueError): DateQuery('added', '2000-01-01x12') From 95eeec937c7466987cd53e39207d4fff41fc0332 Mon Sep 17 00:00:00 2001 From: discopatrick Date: Thu, 1 Jun 2017 13:11:40 +0100 Subject: [PATCH 1969/2280] Add docs for datetime queries --- docs/reference/query.rst | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index b4789aa10..70988f026 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -188,6 +188,33 @@ Find all items with a file modification time between 2008-12-01 and $ beet ls 'mtime:2008-12-01..2008-12-02' +You can also add an optional time value to date queries, specifying hours, +minutes, and seconds. + +Times are separated from dates by a space, an uppercase 'T' or a lowercase +'t', for example: ``2008-12-01T23:59:59``. If you specify a time, then the +date must contain a year, month, and day. The minutes and seconds are +optional. + +Here is an example that finds all items added on 2008-12-01 at or after 22:00 +but before 23:00:: + + $ beet ls 'added:2008-12-01T22' + +Find all items added on or after 2008-12-01 22:45:: + + $ beet ls 'added:2008-12-01T22:45..' + +Find all items added on 2008-12-01, at or after 22:45:20 but before 22:45:41:: + + $ beet ls 'added:2008-12-01T22:45:20..2008-12-01T22:45:40' + +Examples of each time format:: + + $ beet ls 'added:2008-12-01T22:45:20' + $ beet ls 'added:2008-12-01t22:45:20' + $ beet ls 'added:2008-12-01 22:45:20' + .. _not_query: Query Term Negation From ee46a5150f4d97f03eaef509d098f739f3ae88ce Mon Sep 17 00:00:00 2001 From: Jakub Turski Date: Fri, 2 Jun 2017 15:48:05 +0100 Subject: [PATCH 1970/2280] Don't crash if non-canonical genre and prefer_specific: yes. Also, add a test for this. --- beetsplug/lastgenre/__init__.py | 1 + test/test_lastgenre.py | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/beetsplug/lastgenre/__init__.py b/beetsplug/lastgenre/__init__.py index 2756f452c..4374310ba 100644 --- a/beetsplug/lastgenre/__init__.py +++ b/beetsplug/lastgenre/__init__.py @@ -174,6 +174,7 @@ class LastGenrePlugin(plugins.BeetsPlugin): genre tree. """ depth_tag_pairs = [(self._get_depth(t), t) for t in tags] + depth_tag_pairs = [e for e in depth_tag_pairs if e[0] is not None] depth_tag_pairs.sort(reverse=True) return [p[1] for p in depth_tag_pairs] diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index f57471f1c..db2ea903e 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -213,6 +213,17 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): self.assertEqual(res, (config['lastgenre']['fallback'].get(), u'fallback')) + def test_sort_by_depth(self): + self._setup_config(canonical=True,count=99) + # Normal case. + tags = ('electronic', 'ambient', 'post-rock', 'downtempo') + res = self.plugin._sort_by_depth(tags) + self.assertEqual(res, ['post-rock', 'downtempo', 'ambient', 'electronic']) + # Non-canonical tag ('chillout') present. + tags = ('electronic', 'ambient', 'chillout') + res = self.plugin._sort_by_depth(tags) + self.assertEqual(res, ['ambient', 'electronic']) + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From a43f5fdace8631b836998a040a25acd27731f565 Mon Sep 17 00:00:00 2001 From: Jakub Turski Date: Fri, 2 Jun 2017 15:50:58 +0100 Subject: [PATCH 1971/2280] Remove unnecessary test setup parameter. --- test/test_lastgenre.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index db2ea903e..d8ba60cf9 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -214,7 +214,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): u'fallback')) def test_sort_by_depth(self): - self._setup_config(canonical=True,count=99) + self._setup_config(canonical=True) # Normal case. tags = ('electronic', 'ambient', 'post-rock', 'downtempo') res = self.plugin._sort_by_depth(tags) From 0e7a0a62d43c23cb27b08c79246cffaa82a8f0a1 Mon Sep 17 00:00:00 2001 From: Jakub Turski Date: Fri, 2 Jun 2017 16:04:05 +0100 Subject: [PATCH 1972/2280] Fix excessive line length. --- test/test_lastgenre.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index d8ba60cf9..18cb81a0a 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -218,7 +218,8 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): # Normal case. tags = ('electronic', 'ambient', 'post-rock', 'downtempo') res = self.plugin._sort_by_depth(tags) - self.assertEqual(res, ['post-rock', 'downtempo', 'ambient', 'electronic']) + self.assertEqual( + res, ['post-rock', 'downtempo', 'ambient', 'electronic']) # Non-canonical tag ('chillout') present. tags = ('electronic', 'ambient', 'chillout') res = self.plugin._sort_by_depth(tags) From f6830b4bc3dafcef2f71a92904213e0905e02ae7 Mon Sep 17 00:00:00 2001 From: Jakub Turski Date: Fri, 2 Jun 2017 16:27:49 +0100 Subject: [PATCH 1973/2280] Here, flake8, be happy. --- test/test_lastgenre.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_lastgenre.py b/test/test_lastgenre.py index 18cb81a0a..a70c65ca1 100644 --- a/test/test_lastgenre.py +++ b/test/test_lastgenre.py @@ -219,7 +219,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper): tags = ('electronic', 'ambient', 'post-rock', 'downtempo') res = self.plugin._sort_by_depth(tags) self.assertEqual( - res, ['post-rock', 'downtempo', 'ambient', 'electronic']) + res, ['post-rock', 'downtempo', 'ambient', 'electronic']) # Non-canonical tag ('chillout') present. tags = ('electronic', 'ambient', 'chillout') res = self.plugin._sort_by_depth(tags) From b1d8321e40d334db82af6b209efdc0c23327b657 Mon Sep 17 00:00:00 2001 From: tigranl Date: Thu, 15 Dec 2016 18:46:37 +0300 Subject: [PATCH 1974/2280] Add Google Music plugin --- beetsplug/gmusic.py | 90 +++++++++++++++++++++++++++++++++++++++++ docs/plugins/gmusic.rst | 38 +++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 beetsplug/gmusic.py create mode 100644 docs/plugins/gmusic.rst diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py new file mode 100644 index 000000000..b2d9a2f48 --- /dev/null +++ b/beetsplug/gmusic.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2017, Tigran Kostandyan. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Uploads files to Google Play Music""" + +from __future__ import print_function +import os.path + +from beets.plugins import BeetsPlugin +from beets import ui +from beets import config +from beets.ui import Subcommand +from gmusicapi import Musicmanager, Mobileclient +import gmusicapi.clients + + +# Checks for OAuth2 credentials, if they don't exist - performs authorization +m = Musicmanager() +if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH): + m.login() +else: + m.perform_oauth() + + +class Gmusic(BeetsPlugin): + def __init__(self): + super(Gmusic, self).__init__() + + def commands(self): + gupload = Subcommand('gmusic-upload', + help=u'upload your tracks to Google Play Music') + + search = Subcommand('gmusic-songs', + help=u'list of songs in Google Play Music library' + ) + search.parser.add_option('-t', '--track', dest='track', + action='store_true', + help='Search by track name') + search.parser.add_option('-a', '--artist', dest='artist', + action='store_true', + help='Search by artist') + gupload.func = self.upload + search.func = self.search + return [gupload, search] + + def upload(self, lib, opts, args): + items = lib.items(ui.decargs(args)) + files = [x.path.decode('utf-8') for x in items] + ui.print_('Uploading your files...') + m.upload(filepaths=files) + ui.print_('Your files were successfully added to library') + + def search(self, lib, opts, args): + email = config['gmusic']['email'].as_str() + password = config['gmusic']['password'].as_str() + # Since Musicmanager doesn't support library management + # we need to use mobileclient interface + mobile = Mobileclient() + try: + mobile.login(email, password, Mobileclient.FROM_MAC_ADDRESS) + files = mobile.get_all_songs() + except: + ui.print_('Error occured. Please check your email and password') + if not args: + for i, file in enumerate(files, start=1): + print(i, ui.colorize('blue', file['artist']), + file['title'], ui.colorize('red', file['album'])) + else: + if opts.track: + print(*self.match(files, args, 'title')) + else: + print(*self.match(files, args, 'artist')) + + @staticmethod + def match(files, args, search_by): + for file in files: + if ' '.join(args) in file[search_by]: + return file['artist'], file['title'], file['album'] diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst new file mode 100644 index 000000000..0fd3c579b --- /dev/null +++ b/docs/plugins/gmusic.rst @@ -0,0 +1,38 @@ +Gmusic Plugin +============= + +This plugin allows you to manage your Google Play Music library with beets. + +Usage +----- + +To use the ``gmusic`` plugin, enable it in your configuration file. + +Then, add your Google email and password to configuration file under a ``gmusic`` section, if you want to be able to search for songs in your library:: + + gmusic: + email: email + password: password + +It's not necessary if you only upload files. + +Now if you want to upload your tracks use ``gmusic-upload`` command:: + + beet gmusic-upload [ARGS...] + +If no arguments are provided, it will upload your entire beet collection. + +In case you want to search for songs in your Google Music library just use:: + + beet gmusic-songs [OPTS...] [ARGS...] + + Options: + -a, --artist search by artist name + -t, --track search by track + +For example:: + + beet gmusic-songs -a John Frusciante + beet gmusic-songs -t Black Hole Sun + +If you want a list of all songs simply leave it without arguments and options. \ No newline at end of file From 291b287f562b8d268a5495ffb9bc3dcae7c0429d Mon Sep 17 00:00:00 2001 From: discopatrick Date: Mon, 5 Jun 2017 16:31:37 +0100 Subject: [PATCH 1975/2280] Add a test for a non-range date query --- test/test_datequery.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/test_datequery.py b/test/test_datequery.py index 71daa42e4..ba8857084 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -75,6 +75,12 @@ class DateIntervalTest(unittest.TestCase): self.assertExcludes('2000-01-01T12..2000-01-01T13', '2000-01-01T14:30:00') + # test non-range query + self.assertContains('2008-12-01T22', + '2008-12-01T22:30:00') + self.assertExcludes('2008-12-01T22', + '2008-12-01T23:30:00') + def test_minute_precision_intervals(self): self.assertExcludes('2000-01-01T12:30..2000-01-01T12:31', '2000-01-01T12:29:59') From a559e6e14e439f28f8c44815c0b99525f3cb92c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 16:25:36 -0400 Subject: [PATCH 1976/2280] Edit the changelog for release --- docs/changelog.rst | 59 +++++++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index caea9c6a4..25f25eb86 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,39 +4,50 @@ Changelog 1.4.4 (in development) ---------------------- -New features: +This release built up a longer-than-normal list of nifty new features. We now +support DSF audio files and the importer can hard-link your files, for +example. + +Here's a full list of new features: * Added support for DSF files, once a future version of Mutagen is released that supports them. Thanks to :user:`docbobo`. :bug:`459` :bug:`2379` +* A new :ref:`hardlink` config option instructs the importer to create hard + links on filesystems that support them. Thanks to :user:`jacobwgillespie`. + :bug:`2445` +* A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync + with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` +* A new :ref:`bell` configuration option under the ``import`` section enables + a terminal bell when input is required. Thanks to :user:`SpirosChadoulos`. + :bug:`2366` :bug:`2495` +* A new field, ``composer_sort``, is now supported and fetched from + MusicBrainz. + Thanks to :user:`dosoe`. + :bug:`2519` :bug:`2529` * The MusicBrainz backend and :doc:`/plugins/discogs` now both provide a new attribute called ``track_alt`` that stores more nuanced, possibly non-numeric track index data. For example, some vinyl or tape media will report the side of the record using a letter instead of a number in that field. :bug:`1831` :bug:`2363` -* The :doc:`/plugins/web` has a new endpoint, ``/item/path/foo``, which will +* :doc:`/plugins/web`: Added a new endpoint, ``/item/path/foo``, which will return the item info for the file at the given path, or 404. -* The :doc:`/plugins/web` also has a new config option, ``include_paths``, +* :doc:`/plugins/web`: Added a new config option, ``include_paths``, which will cause paths to be included in item API responses if set to true. * The ``%aunique`` template function for :ref:`aunique` now takes a third - argument that specifies which brackets to use around the disambiguator + argument that specifies which brackets to use around the disambiguator value. The argument can be any two characters that represent the left and right brackets. It defaults to `[]` and can also be blank to turn off bracketing. :bug:`2397` :bug:`2399` * Added a ``--move`` or ``-m`` option to the importer so that the files can be - moved to the library instead of being copied or added "in place". + moved to the library instead of being copied or added "in place." :bug:`2252` :bug:`2429` * :doc:`/plugins/badfiles`: Added a ``--verbose`` or ``-v`` option. Results are now displayed only for corrupted files by default and for all the files when the verbose option is set. :bug:`1654` :bug:`2434` -* A new :ref:`hardlink` config option instructs the importer to create hard - links on filesystems that support them. Thanks to :user:`jacobwgillespie`. - :bug:`2445` * :doc:`/plugins/embedart`: The explicit ``embedart`` command now asks for confirmation before embedding art into music files. Thanks to :user:`Stunner`. :bug:`1999` * You can now run beets by typing `python -m beets`. :bug:`2453` -* A new :doc:`/plugins/kodiupdate` lets you keep your Kodi library in sync - with beets. Thanks to :user:`Pauligrinder`. :bug:`2411` * :doc:`/plugins/smartplaylist`: Different playlist specifications that generate identically-named playlist files no longer conflict; instead, the resulting lists of tracks are concatenated. :bug:`2468` @@ -44,9 +55,6 @@ New features: you have in your library. Thanks to :user:`qlyoung`. :bug:`2481` * :doc:`/plugins/web` : Add new `reverse_proxy` config option to allow serving the web plugins under a reverse proxy. -* A new :ref:`bell` configuration option under the ``import`` section enables - a terminal bell when input is required. Thanks to :user:`SpirosChadoulos`. - :bug:`2366` :bug:`2495` * Importing a release with multiple release events now selects the event based on your :ref:`preferred` countries. :bug:`2501` * :doc:`/plugins/play`: A new ``-y`` or ``--yes`` parameter lets you skip @@ -57,28 +65,25 @@ New features: Thanks to :user:`jansol`. :bug:`2488` :bug:`2524` -* A new field, ``composer_sort``, is now supported and fetched from - MusicBrainz. - Thanks to :user:`dosoe`. - :bug:`2519` :bug:`2529` -Fixes: +There are also quite a few fixes: * In the :ref:`replace` configuration option, we now replace a leading hyphen (-) with an underscore. :bug:`549` :bug:`2509` -* :doc:`/plugins/absubmit`: Do not filter for supported formats. :bug:`2471` +* :doc:`/plugins/absubmit`: We no longer filter audio files for specific + formats---we will attempt the submission process for all formats. :bug:`2471` * :doc:`/plugins/mpdupdate`: Fix Python 3 compatibility. :bug:`2381` * :doc:`/plugins/replaygain`: Fix Python 3 compatibility in the ``bs1770gain`` backend. :bug:`2382` -* :doc:`/plugins/bpd`: Report playback times as integer. :bug:`2394` +* :doc:`/plugins/bpd`: Report playback times as integers. :bug:`2394` * :doc:`/plugins/mpdstats`: Fix Python 3 compatibility. The plugin also now requires version 0.4.2 or later of the ``python-mpd2`` library. :bug:`2405` -* :doc:`/plugins/mpdstats`: Improve handling of mpd status queries. +* :doc:`/plugins/mpdstats`: Improve handling of MPD status queries. * :doc:`/plugins/badfiles`: Fix Python 3 compatibility. * Fix some cases where album-level ReplayGain/SoundCheck metadata would be written to files incorrectly. :bug:`2426` -* :doc:`/plugins/badfiles`: The command no longer bails out if validator - command is not found or exists with an error. :bug:`2430` :bug:`2433` +* :doc:`/plugins/badfiles`: The command no longer bails out if the validator + command is not found or exits with an error. :bug:`2430` :bug:`2433` * :doc:`/plugins/lyrics`: The Google search backend no longer crashes when the server responds with an error. :bug:`2437` * :doc:`/plugins/discogs`: You can now authenticate with Discogs using a @@ -87,7 +92,7 @@ Fixes: Thanks to :user:`Lompik`. :bug:`2443` :bug:`2448` * :doc:`/plugins/duplicates`: Fix Python 3 compatibility when using the ``copy`` and ``move`` options. :bug:`2444` -* :doc:`/plugins/mbsubmit`: The tracks are now sorted. Thanks to +* :doc:`/plugins/mbsubmit`: The tracks are now sorted properly. Thanks to :user:`awesomer`. :bug:`2457` * :doc:`/plugins/thumbnails`: Fix a string-related crash on Python 3. :bug:`2466` @@ -98,8 +103,8 @@ Fixes: limited encoding. * :doc:`/plugins/convert`: The default configuration uses FFmpeg's built-in AAC codec instead of faac. Thanks to :user:`jansol`. :bug:`2484` -* Fix import of multidisc releases with subdirectories, which previously - made each disc be imported separately in different releases. :bug:`2493` +* Fix the importer's detection of multi-disc albums when other subdirectories + are present. :bug:`2493` * Invalid date queries now print an error message instead of being silently ignored. Thanks to :user:`discopatrick`. :bug:`2513` :bug:`2517` * When the SQLite database stops being accessible, we now print a friendly @@ -110,7 +115,7 @@ Fixes: * Fix a crash when reading non-ASCII characters in configuration files on Windows under Python 3. :bug:`2456` :bug:`2565` :bug:`2566` -Two plugins had backends removed due to bitrot: +We removed backends from two metadata plugins because of bitrot: * :doc:`/plugins/lyrics`: The Lyrics.com backend has been removed. (It stopped working because of changes to the site's URL structure.) From 9727ca72c946c44fbb7e8c8798b832eccb9b11d7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 16:28:17 -0400 Subject: [PATCH 1977/2280] Add date to the changelog --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 25f25eb86..7016fe854 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.4 (in development) ----------------------- +1.4.4 (June 10, 2017) +--------------------- This release built up a longer-than-normal list of nifty new features. We now support DSF audio files and the importer can hard-link your files, for From 8842bd3ecc9855faed1f2ba86239a27835a9e402 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 16:28:50 -0400 Subject: [PATCH 1978/2280] Version bump: 1.4.5 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index 964d2592c..cab256032 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.4' +__version__ = u'1.4.5' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 7016fe854..d253f6d06 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.5 (in development) +---------------------- + +Changelog goes here! + + 1.4.4 (June 10, 2017) --------------------- diff --git a/docs/conf.py b/docs/conf.py index 9573b2fba..cd55e57a5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.4' +release = '1.4.5' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 148643837..9fdbf63ca 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.4', + version='1.4.5', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 29d6c27d02e000888a747e8bdcab03a7418f5137 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:03:01 -0400 Subject: [PATCH 1979/2280] Fix some spurious whitespace changes --- test/test_ui.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index f34cf72cb..c67c9cb55 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -156,6 +156,7 @@ class RemoveTest(_common.TestCase): class ModifyTest(unittest.TestCase, TestHelper): + def setUp(self): self.setup_beets() self.album = self.add_album_fixture() @@ -346,6 +347,7 @@ class ModifyTest(unittest.TestCase, TestHelper): class WriteTest(unittest.TestCase, TestHelper): + def setUp(self): self.setup_beets() @@ -1248,7 +1250,6 @@ class CommonOptionsParserCliTest(unittest.TestCase, TestHelper): """Test CommonOptionsParser and formatting LibModel formatting on 'list' command. """ - def setUp(self): self.setup_beets() self.lib = library.Library(':memory:') @@ -1445,6 +1446,5 @@ class EncodingTest(_common.TestCase): def suite(): return unittest.TestLoader().loadTestsFromName(__name__) - if __name__ == '__main__': unittest.main(defaultTest='suite') From b25eb87f6091d5c0fad0babf4efb6a15087958a5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:05:17 -0400 Subject: [PATCH 1980/2280] Remove unnecessary output capture --- test/test_ui.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index c67c9cb55..0fbec0bde 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -481,8 +481,6 @@ class ExportTest(_common.TestCase): def setUp(self): super(ExportTest, self).setUp() - self.io.install() - self.libdir = os.path.join(self.temp_dir, b'testlibdir') os.mkdir(self.libdir) From 231528784d32927a72afce2116b6f07baba07ee6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:15:02 -0400 Subject: [PATCH 1981/2280] Simplify implementation of export behavior --- beets/ui/commands.py | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 7ffa90b11..df23f5887 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1464,6 +1464,7 @@ def move_items(lib, dest, query, copy, album, pretend, export=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)] + copy = copy or export # Exporting always copies. action = u'Copying' if copy else u'Moving' act = u'copy' if copy else u'move' entity = u'album' if album else u'item' @@ -1480,22 +1481,6 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: - # Copying files without modifying the database. - if export: - # export(file) function copies a file without modifying - # the database. - - def export(file): - # Create necessary ancestry for the copy. - util.mkdirall(file.destination(basedir=dest)) - util.copy(file.path, file.destination(basedir=dest)) - if album: - for obj in objs: - for item in obj.items(): - export(item) - else: - for obj in objs: - export(obj) if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, @@ -1505,8 +1490,12 @@ def move_items(lib, dest, query, copy, album, pretend, export=False, for obj in objs: log.debug(u'moving: {0}', util.displayable_path(obj.path)) - obj.move(copy, basedir=dest) - obj.store() + if export: + # Copy without affecting the database. + obj.move(True, basedir=dest, store=False) + else: + # Ordinary move/copy: store the new path. + obj.move(copy, basedir=dest) def move_func(lib, opts, args): From 714560aace0bb53af3b594fc1ee43c4f0bed2e11 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:19:27 -0400 Subject: [PATCH 1982/2280] Fix parameter order and binding The calls didn't match up with the parameter order. --- beets/ui/commands.py | 4 ++-- test/test_ui.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index df23f5887..d95a126d1 100755 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1450,8 +1450,8 @@ default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. -def move_items(lib, dest, query, copy, album, pretend, export=False, - confirm=False): +def move_items(lib, dest, query, copy, album, pretend, confirm=False, + export=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. diff --git a/test/test_ui.py b/test/test_ui.py index 0fbec0bde..a24a635f3 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -499,7 +499,7 @@ class ExportTest(_common.TestCase): def _move(self, query=(), dest=None, copy=False, album=False, pretend=False, export=True): commands.move_items(self.lib, dest, query, copy, album, - pretend, export) + pretend, export=export) def test_export_item(self): self._move() From 730c84e5e575488afb6a0b042582737f3fc2b2ea Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:24:45 -0400 Subject: [PATCH 1983/2280] Correct tests for export mode The old tests were wrong but the incorrectness was hidden by the incorrect parameter passing fixed in the previous commit. Now we actually test that the item's path did not change. --- test/test_ui.py | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index a24a635f3..ed31570e4 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -501,36 +501,23 @@ class ExportTest(_common.TestCase): commands.move_items(self.lib, dest, query, copy, album, pretend, export=export) - def test_export_item(self): - self._move() - self.i.load() - self.assertTrue(b'testlibdir' in self.i.path) - self.assertExists(self.i.path) - self.assertNotExists(self.itempath) - def test_export_item_custom_dir(self): self._move(dest=self.otherdir) self.i.load() - self.assertTrue(b'testotherdir' in self.i.path) - self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertEqual(self.i.path, self.itempath) + self.assertExists(self.otherdir) def test_export_album_custom_dir(self): self._move(dest=self.otherdir, album=True) self.i.load() - self.assertTrue(b'testotherdir' in self.i.path) - self.assertExists(self.i.path) - self.assertNotExists(self.itempath) + self.assertEqual(self.i.path, self.itempath) + self.assertExists(self.otherdir) def test_pretend_export_item(self): self._move(dest=self.otherdir, pretend=True) self.i.load() self.assertIn(b'srcfile', self.i.path) - - def test_pretend_export_album(self): - self._move(album=True, pretend=True) - self.i.load() - self.assertIn(b'srcfile', self.i.path) + self.assertNotExists(self.otherdir) class UpdateTest(_common.TestCase): From ca4f96e33c0f13e1a17edfc96e94293d78ed8144 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:26:41 -0400 Subject: [PATCH 1984/2280] Consolidate export tests into MoveTest Just one new flag. --- test/test_ui.py | 36 ++++++------------------------------ 1 file changed, 6 insertions(+), 30 deletions(-) diff --git a/test/test_ui.py b/test/test_ui.py index ed31570e4..04c033f51 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -421,8 +421,9 @@ class MoveTest(_common.TestCase): self.otherdir = os.path.join(self.temp_dir, b'testotherdir') def _move(self, query=(), dest=None, copy=False, album=False, - pretend=False): - commands.move_items(self.lib, dest, query, copy, album, pretend) + pretend=False, export=False): + commands.move_items(self.lib, dest, query, copy, album, pretend, + export=export) def test_move_item(self): self._move() @@ -476,45 +477,20 @@ class MoveTest(_common.TestCase): self.i.load() self.assertIn(b'srcfile', self.i.path) - -class ExportTest(_common.TestCase): - def setUp(self): - super(ExportTest, self).setUp() - - self.libdir = os.path.join(self.temp_dir, b'testlibdir') - os.mkdir(self.libdir) - - self.itempath = os.path.join(self.libdir, b'srcfile') - shutil.copy(os.path.join(_common.RSRC, b'full.mp3'), self.itempath) - - # Add a file to the library but don't copy it in yet. - self.lib = library.Library(':memory:', self.libdir) - self.i = library.Item.from_path(self.itempath) - self.lib.add(self.i) - self.album = self.lib.add_album([self.i]) - - # Alternate destination directory. - self.otherdir = os.path.join(self.temp_dir, b'testotherdir') - - def _move(self, query=(), dest=None, copy=False, album=False, - pretend=False, export=True): - commands.move_items(self.lib, dest, query, copy, album, - pretend, export=export) - def test_export_item_custom_dir(self): - self._move(dest=self.otherdir) + self._move(dest=self.otherdir, export=True) self.i.load() self.assertEqual(self.i.path, self.itempath) self.assertExists(self.otherdir) def test_export_album_custom_dir(self): - self._move(dest=self.otherdir, album=True) + self._move(dest=self.otherdir, album=True, export=True) self.i.load() self.assertEqual(self.i.path, self.itempath) self.assertExists(self.otherdir) def test_pretend_export_item(self): - self._move(dest=self.otherdir, pretend=True) + self._move(dest=self.otherdir, pretend=True, export=True) self.i.load() self.assertIn(b'srcfile', self.i.path) self.assertNotExists(self.otherdir) From 7cacae5c982046d33703923e33d53d92dd36d0c4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:35:09 -0400 Subject: [PATCH 1985/2280] Changelog for #2560 (fixes #2557) --- docs/changelog.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index d253f6d06..e8424f60a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,12 @@ Changelog 1.4.5 (in development) ---------------------- -Changelog goes here! +Features: + +* :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from + classic ReplayGain data for formats that need it (namely, Ogg Opus). A new + `r128` configuration option enables this behavior for specific formats. + Thanks to :user:`autrimpo`. :bug:`2557` :bug:`2560` 1.4.4 (June 10, 2017) From f6dc98121741a5bbc7acfcf56608c997e5c2eecc Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:42:18 -0400 Subject: [PATCH 1986/2280] Edit docs from #2576 for brevity Fixes #1741. --- docs/plugins/convert.rst | 45 +++++++++++----------------------------- 1 file changed, 12 insertions(+), 33 deletions(-) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 89f114a11..59036a38b 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -145,47 +145,26 @@ and the given command is used for all conversions. Gapless MP3 encoding ```````````````````` -Due to limitations in the ``ffmpeg`` encoder, by default the ``convert`` plugin -does not produce MP3s with accurate length tags (it does not write a LAME MP3 -info tag). This means that the MP3s are not "`gapless`_", and can result in -noticeable gaps between tracks during playback. - -.. _gapless: http://wiki.hydrogenaud.io/index.php?title=Gapless_playback - -To work around this problem, you must use the `LAME`_ MP3 encoder, which will -produce MP3s with accurate length tags. - -.. _LAME: http://lame.sourceforge.net/ - -To do this on Linux, you need to install ``lame``, create a script (e.g. -``/home/user/.config/beets/mp3.sh``) with the following contents, and make it -executable. - -:: +While FFmpeg cannot produce "`gapless`_" MP3s by itself, you can create them +by using `LAME`_ directly. Use a shell script like this to pipe the output of +FFmpeg into the LAME tool:: #!/bin/sh ffmpeg -i "$1" -f wav - | lame -V 2 --noreplaygain - "$2" -Then configure the ``convert`` plugin to use the script. - -:: +Then configure the ``convert`` plugin to use the script:: convert: - command: /home/user/.config/beets/mp3.sh $source $dest + command: /path/to/script.sh $source $dest extension: mp3 -.. note:: - - In the script above, ``ffmpeg`` output format ``wav`` is used to produce an - accurate length header to pass to ``lame``. - - ``--noreplaygain`` configures ``lame`` not to do ReplayGain analysis and - tagging itself, because it can only do a track level analysis. Instead, you - can use the beets ``replaygain`` plugin to analyse and add both Album and - Track ReplayGain tags. - - See the ``lame`` `documentation`_ and the `HydrogenAudio wiki`_ for other - ``lame`` configuration options, and a thorough discussion of MP3 encoding. +This strategy configures FFmpeg to produce a WAV file with an accurate length +header for LAME to use. Using ``--noreplaygain`` disables gain analysis; you +can use the :doc:`/plugins/replaygain` to do this analysis. See the LAME +`documentation`_ and the `HydrogenAudio wiki`_ for other LAME configuration +options and a thorough discussion of MP3 encoding. .. _documentation: http://lame.sourceforge.net/using.php .. _HydrogenAudio wiki: http://wiki.hydrogenaud.io/index.php?title=LAME +.. _gapless: http://wiki.hydrogenaud.io/index.php?title=Gapless_playback +.. _LAME: http://lame.sourceforge.net/ From 1af3729b4e4263c9a1e0d045ef635f935e9d93d1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:48:07 -0400 Subject: [PATCH 1987/2280] Changelog for #2583 --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e8424f60a..0aaf5f409 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -11,6 +11,12 @@ Features: `r128` configuration option enables this behavior for specific formats. Thanks to :user:`autrimpo`. :bug:`2557` :bug:`2560` +Fixes: + +* :doc:`/plugins/lastgenre`: Fix a crash when using the `prefer_specific` and + `canonical` options together. Thanks to :user:`yacoob`. :bug:`2459` + :bug:`2583` + 1.4.4 (June 10, 2017) --------------------- From f4d33686aea17fbc4dc08459bf1bc18eeb2b874b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:52:52 -0400 Subject: [PATCH 1988/2280] Some more clarity in comments for #2294 --- beets/autotag/mb.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 8676126e9..5c484d2b3 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -333,20 +333,23 @@ def album_info(release): disambig.append(release.get('disambiguation')) info.albumdisambig = u', '.join(disambig) - # Retrieves the Release type. - # Considers all other release types(including primary and secondary) (new) - # and logs them. + # Get the "classic" Release type. This data comes from a legacy API + # feature before MusicBrainz supported multiple release types. if 'type' in release['release-group']: reltype = release['release-group']['type'] if reltype: info.albumtype = reltype.lower() + + # Log the new-style "primary" and "secondary" release types. + # Eventually, we'd like to actually store this data, but we just log + # it for now to help understand the differences. if 'primary-type' in release['release-group']: rel_primarytype = release['release-group']['primary-type'] if rel_primarytype: - log.debug('Primary Type (new data): ' + rel_primarytype.lower()) + log.debug('primary MB release type: ' + rel_primarytype.lower()) if 'secondary-type-list' in release['release-group']: if release['release-group']['secondary-type-list']: - log.debug('Secondary Type(s) (new data): ' + ', '.join( + log.debug('secondary MB release type(s): ' + ', '.join( [secondarytype.lower() for secondarytype in release['release-group']['secondary-type-list']])) From d645c03ded42ce4b69057d717a9da7fd3871b75d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 20:59:02 -0400 Subject: [PATCH 1989/2280] Changelog for #2528 (fixes #2506) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0aaf5f409..9089058d2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,9 @@ Changelog Features: +* :ref:`Date queries ` can now include times, so you can filter + your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` + :bug:`2528` * :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from classic ReplayGain data for formats that need it (namely, Ogg Opus). A new `r128` configuration option enables this behavior for specific formats. From 0a731484e2a2a4401d59d9d25308f2b67cfcc351 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 10 Jun 2017 21:00:49 -0400 Subject: [PATCH 1990/2280] Slight refinements to time query docs --- docs/reference/query.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 70988f026..112c1966d 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -201,15 +201,17 @@ but before 23:00:: $ beet ls 'added:2008-12-01T22' -Find all items added on or after 2008-12-01 22:45:: +To find all items added on or after 2008-12-01 at 22:45:: $ beet ls 'added:2008-12-01T22:45..' -Find all items added on 2008-12-01, at or after 22:45:20 but before 22:45:41:: +To find all items added on 2008-12-01, at or after 22:45:20 but before +22:45:41:: $ beet ls 'added:2008-12-01T22:45:20..2008-12-01T22:45:40' -Examples of each time format:: +Here are example of the three ways to separate dates from times. All of these +queries do the same thing:: $ beet ls 'added:2008-12-01T22:45:20' $ beet ls 'added:2008-12-01t22:45:20' From f65653a843f45ece2f64c51cf5c347bf1a7c3604 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 11 Jun 2017 12:22:49 -0400 Subject: [PATCH 1991/2280] Changelog for #2510 (fixes #435) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 9089058d2..d50c25800 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,9 @@ Features: classic ReplayGain data for formats that need it (namely, Ogg Opus). A new `r128` configuration option enables this behavior for specific formats. Thanks to :user:`autrimpo`. :bug:`2557` :bug:`2560` +* The :ref:`move-cmd` command gained a new ``--export`` flag, which copies + files to an external location without changing their location in the library + database. Thanks to :user:`SpirosChadoulos`. :bug:`435` :bug:`2510` Fixes: From 28ba733ebe11034d0421aed503e7337695e4c0e7 Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Sun, 11 Jun 2017 22:27:44 +0300 Subject: [PATCH 1992/2280] Add custom exception and mark fields as redacted. Remove Musicmanager global variable. Update gmusic.rst --- beetsplug/gmusic.py | 36 +++++++++++++++++++----------------- docs/plugins/gmusic.rst | 16 +++++++++++++--- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py index b2d9a2f48..57c2a3464 100644 --- a/beetsplug/gmusic.py +++ b/beetsplug/gmusic.py @@ -23,20 +23,19 @@ from beets import ui from beets import config from beets.ui import Subcommand from gmusicapi import Musicmanager, Mobileclient +from gmusicapi.exceptions import NotLoggedIn import gmusicapi.clients -# Checks for OAuth2 credentials, if they don't exist - performs authorization -m = Musicmanager() -if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH): - m.login() -else: - m.perform_oauth() - - class Gmusic(BeetsPlugin): def __init__(self): super(Gmusic, self).__init__() + # Checks for OAuth2 credentials, if they don't exist - performs authorization + self.m = Musicmanager() + if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH): + self.m.login() + else: + self.m.perform_oauth() def commands(self): gupload = Subcommand('gmusic-upload', @@ -59,19 +58,22 @@ class Gmusic(BeetsPlugin): items = lib.items(ui.decargs(args)) files = [x.path.decode('utf-8') for x in items] ui.print_('Uploading your files...') - m.upload(filepaths=files) + self.m.upload(filepaths=files) ui.print_('Your files were successfully added to library') def search(self, lib, opts, args): - email = config['gmusic']['email'].as_str() - password = config['gmusic']['password'].as_str() + password = config['gmusic']['password'] + email = config['gmusic']['email'] + password.redact = True + email.redact = True # Since Musicmanager doesn't support library management # we need to use mobileclient interface mobile = Mobileclient() try: - mobile.login(email, password, Mobileclient.FROM_MAC_ADDRESS) + mobile.login(email.as_str(), password.as_str(), + Mobileclient.FROM_MAC_ADDRESS) files = mobile.get_all_songs() - except: + except NotLoggedIn: ui.print_('Error occured. Please check your email and password') if not args: for i, file in enumerate(files, start=1): @@ -79,12 +81,12 @@ class Gmusic(BeetsPlugin): file['title'], ui.colorize('red', file['album'])) else: if opts.track: - print(*self.match(files, args, 'title')) + self.match(files, args, 'title') else: - print(*self.match(files, args, 'artist')) + self.match(files, args, 'artist') @staticmethod def match(files, args, search_by): for file in files: - if ' '.join(args) in file[search_by]: - return file['artist'], file['title'], file['album'] + if ' '.join(ui.decargs(args)) in file[search_by]: + print(file['artist'], file['title'], file['album']) diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst index 0fd3c579b..e9d81b659 100644 --- a/docs/plugins/gmusic.rst +++ b/docs/plugins/gmusic.rst @@ -3,20 +3,30 @@ Gmusic Plugin This plugin allows you to manage your Google Play Music library with beets. + +Installation +------------ + +The plugin requires `gmusic`_. You can install it using `pip`:: + + pip install gmusicapi + +.. _gmusic: https://github.com/simon-weber/gmusicapi/ + Usage ----- To use the ``gmusic`` plugin, enable it in your configuration file. -Then, add your Google email and password to configuration file under a ``gmusic`` section, if you want to be able to search for songs in your library:: +Then, add your Google email and password to configuration file under a ``gmusic`` section, if you want to be able to search for songs in your library. +It's not necessary if you only upload files. :: gmusic: email: email password: password -It's not necessary if you only upload files. -Now if you want to upload your tracks use ``gmusic-upload`` command:: +If you want to upload your tracks use ``gmusic-upload`` command:: beet gmusic-upload [ARGS...] From 06f86c82e54728884b8c69a2ca31585616f85bdc Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Sun, 11 Jun 2017 22:36:09 +0300 Subject: [PATCH 1993/2280] PEP8 --- beetsplug/gmusic.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py index 57c2a3464..545d5cae4 100644 --- a/beetsplug/gmusic.py +++ b/beetsplug/gmusic.py @@ -30,7 +30,8 @@ import gmusicapi.clients class Gmusic(BeetsPlugin): def __init__(self): super(Gmusic, self).__init__() - # Checks for OAuth2 credentials, if they don't exist - performs authorization + # Checks for OAuth2 credentials, + # if they don't exist - performs authorization self.m = Musicmanager() if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH): self.m.login() From 52d5d2310b74d562faeca653b3d1e146d8df6b97 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Mon, 12 Jun 2017 16:46:09 +0200 Subject: [PATCH 1994/2280] refactoring according to feedback in pull request --- beets/ui/__init__.py | 53 ++++++++++++++++++++------------------- beets/ui/commands.py | 6 ++--- docs/changelog.rst | 2 +- docs/reference/cli.rst | 7 +++--- docs/reference/config.rst | 2 +- 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 2cea00be7..8b0d57106 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -769,6 +769,33 @@ def show_path_changes(path_changes): pad = max_width - len(source) log.info(u'{0} {1} -> {2}', source, ' ' * pad, dest) +# Helper functions for option parsing. + +def _store_dict(option, opt_str, value, parser): + """Custom action callback to parse options which have ``key=value`` + pairs as values. All such pairs passed for this option are + aggregated into a dictionary. + """ + dest = option.dest + option_values = getattr(parser.values, dest, None) + + if option_values is None: + # This is the first supplied ``key=value`` pair of option. + # Initialize empty dictionary and get a reference to it. + setattr(parser.values, dest, dict()) + option_values = getattr(parser.values, dest) + + try: + key, value = map(lambda s: util.text_string(s), value.split('=')) + if not (key and value): + raise ValueError + except ValueError: + raise UserError( + "supplied argument `{0}' is not of the form `key=value'" + .format(value)) + + option_values[key] = value + class CommonOptionsParser(optparse.OptionParser, object): """Offers a simple way to add common formatting options. @@ -1060,32 +1087,6 @@ class SubcommandsOptionParser(CommonOptionsParser): suboptions, subargs = subcommand.parse_args(args) return subcommand, suboptions, subargs - @staticmethod - def _store_dict(option, opt_str, value, parser): - """Custom action callback to parse options which have ``key=value`` - pairs as values. All such pairs passed for this option are - aggregated into a dictionary. - """ - dest = option.dest - option_values = getattr(parser.values, dest, None) - - if option_values is None: - # This is the first supplied ``key=value`` pair of option. - # Initialize empty dictionary and get a reference to it. - setattr(parser.values, dest, dict()) - option_values = getattr(parser.values, dest) - - try: - key, value = map(lambda s: util.text_string(s), value.split('=')) - if not (key and value): - raise ValueError - except ValueError: - raise UserError( - "supplied argument `{0}' is not of the form `key=value'" - .format(value)) - - option_values[key] = value - optparse.Option.ALWAYS_TYPED_ACTIONS += ('callback',) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 240c776ee..0003efc5d 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -40,7 +40,7 @@ from beets import config from beets import logging from beets.util.confit import _package_path import six -from . import SubcommandsOptionParser +from . import _store_dict VARIOUS_ARTISTS = u'Various Artists' PromptChoice = namedtuple('PromptChoice', ['short', 'long', 'callback']) @@ -1019,8 +1019,8 @@ import_cmd.parser.add_option( help=u'restrict matching to a specific metadata backend ID' ) import_cmd.parser.add_option( - u'--set-field', dest='set_fields', action='callback', - callback=SubcommandsOptionParser._store_dict, + u'--set', dest='set_fields', action='callback', + callback=_store_dict, metavar='FIELD=VALUE', help=u'set the given fields to the supplied values' ) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0da327ac4..6fcdb5792 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -63,7 +63,7 @@ New features: :bug:`2519` :bug:`2529` * It is now possible to set fields to certain values during import, using either the `importer.set_fields` dictionary in the config file, or by - passing one or more `--set-field field=value` options on the command-line. + passing one or more `--set field=value` options on the command-line. :bug: `1881` diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index b9f29c9c9..38d4f40ca 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -138,13 +138,12 @@ Optional command flags: searching for other candidates by using the ``--search-id SEARCH_ID`` option. Multiple IDs can be specified by simply repeating the option several times. -* You can supply ``--set-field`` options with ``field=value`` pairs to assign to +* You can supply ``--set`` options with ``field=value`` pairs to assign to those fields the specified values on import, in addition to such field/value pairs defined in the ``importer.set_fields`` dictionary in the configuration - file. Make sure to use an option per field/value pair, like so: - :: + file. Make sure to use an option per field/value pair, like so:: - beet import --set-field genre="Alternative Rock" --set-field mood="emotional" + beet import --set genre="Alternative Rock" --set mood="emotional" Note that values for the fields specified on the command-line override the ones defined for those fields in the configuration file. diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 1018b9bb4..bcd30169b 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -600,7 +600,7 @@ Example: :: genre: 'To Listen' collection: 'Unordered' -Note that field/value pairs supplied via ``--set-field`` options on the +Note that field/value pairs supplied via ``--set`` options on the command-line are processed in addition to those specified here. Those values override the ones defined here in the case of fields with the same name. From 53d0421d4350c6fb6771cb0a0a808289cb9e58a0 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Mon, 12 Jun 2017 16:51:22 +0200 Subject: [PATCH 1995/2280] added docstring for set_fields methods --- beets/importer.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index 247b46968..6ceb4f831 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -534,6 +534,9 @@ class ImportTask(BaseImportTask): lib.directory) def set_fields(self): + """Sets the fields given at CLI or configuration to the specified + values. + """ set_fields_dict = config['import']['set_fields'] for field in set_fields_dict.keys(): value = set_fields_dict[field].get() @@ -892,7 +895,8 @@ class SingletonImportTask(ImportTask): self.item.load() def set_fields(self): - """Similar to ``ImportTask.set_fields``, but for singleton items. + """Sets the fields given at CLI or configuration to the specified + values. """ set_fields_dict = config['import']['set_fields'] for field in set_fields_dict.keys(): From 24658989daa80f0c714c84d3a8d6af7d42e5e607 Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Mon, 12 Jun 2017 17:02:41 +0200 Subject: [PATCH 1996/2280] refactoring according to suggestions in pull request --- beets/importer.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 6ceb4f831..d36a5a0a0 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -537,15 +537,14 @@ class ImportTask(BaseImportTask): """Sets the fields given at CLI or configuration to the specified values. """ - set_fields_dict = config['import']['set_fields'] - for field in set_fields_dict.keys(): - value = set_fields_dict[field].get() + for field, view in config['import']['set_fields'].items(): + value = view.get() log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) self.album[field] = value - self.album.store() + self.album.store() def finalize(self, session): """Save progress, clean up files, and emit plugin event. @@ -898,15 +897,14 @@ class SingletonImportTask(ImportTask): """Sets the fields given at CLI or configuration to the specified values. """ - set_fields_dict = config['import']['set_fields'] - for field in set_fields_dict.keys(): - value = set_fields_dict[field].get() + for field, view in config['import']['set_fields'].items(): + value = view.get() log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) self.item[field] = value - self.item.store() + self.item.store() # FIXME The inheritance relationships are inverted. This is why there @@ -1418,6 +1416,9 @@ def apply_choice(session, task): # If ``set_fields`` is set, set those fields to the # configured values. + # NOTE: This cannot be done before the ``task.add()`` call above, + # because then the ``ImportTask`` won't have an `album` for which + # it can set the fields. if config['import']['set_fields']: task.set_fields() From 8555481482c20cb356c35654e00e93a87634fe08 Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Tue, 13 Jun 2017 01:41:06 +0300 Subject: [PATCH 1997/2280] Update index.rst --- docs/plugins/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index e0f9521e2..20b8c9440 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -168,6 +168,7 @@ Miscellaneous * :doc:`duplicates`: List duplicate tracks or albums. * :doc:`export`: Export data from queries to a format. * :doc:`fuzzy`: Search albums and tracks with fuzzy string matching. +* :doc:`gmusic`: Search and upload files to Google Play Music. * :doc:`hook`: Run a command when an event is emitted by beets. * :doc:`ihate`: Automatically skip albums and tracks during the import process. * :doc:`info`: Print music files' tags to the console. From 2d7962c552eef30527ec52fcd858fcaff2484847 Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Tue, 13 Jun 2017 02:48:43 +0300 Subject: [PATCH 1998/2280] Update toctree --- docs/plugins/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index 20b8c9440..504d4a132 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -57,6 +57,7 @@ like this:: ftintitle fuzzy freedesktop + gmusic hook ihate importadded From 762f9ca054782f368051347967878c89995182ad Mon Sep 17 00:00:00 2001 From: Bart Kleijngeld Date: Tue, 13 Jun 2017 14:33:08 +0200 Subject: [PATCH 1999/2280] revised to fix flake8 warnings --- beets/ui/__init__.py | 1 + test/test_importer.py | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 8b0d57106..d014cc5d0 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -771,6 +771,7 @@ def show_path_changes(path_changes): # Helper functions for option parsing. + def _store_dict(option, opt_str, value, parser): """Custom action callback to parse options which have ``key=value`` pairs as values. All such pairs passed for this option are diff --git a/test/test_importer.py b/test/test_importer.py index cbfbda778..1e0dd1fb9 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -558,7 +558,7 @@ class ImportSingletonTest(_common.TestCase, ImportHelper): self.importer.run() for item in self.lib.items(): - item.load() # TODO: Not sure this is necessary. + item.load() # TODO: Not sure this is necessary. self.assertEqual(item.genre, genre) self.assertEqual(item.collection, collection) # Remove item from library to test again with APPLY choice. @@ -719,7 +719,7 @@ class ImportTest(_common.TestCase, ImportHelper): self.importer.run() for album in self.lib.albums(): - album.load() # TODO: Not sure this is necessary. + album.load() # TODO: Not sure this is necessary. self.assertEqual(album.genre, genre) self.assertEqual(album.collection, collection) # Remove album from library to test again with APPLY choice. From 719b699d009442281fa01c32092ef3b45935395f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 13 Jun 2017 09:19:56 -0400 Subject: [PATCH 2000/2280] Teensy whitespace fix --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index d014cc5d0..6ba80d22f 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -769,8 +769,8 @@ def show_path_changes(path_changes): pad = max_width - len(source) log.info(u'{0} {1} -> {2}', source, ' ' * pad, dest) -# Helper functions for option parsing. +# Helper functions for option parsing. def _store_dict(option, opt_str, value, parser): """Custom action callback to parse options which have ``key=value`` From 3f684455d265e00a739c8e396d9b593d2867f966 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 13 Jun 2017 09:20:21 -0400 Subject: [PATCH 2001/2280] Move changelog entry to the right position --- docs/changelog.rst | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ff5f7330f..5b42be08d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,10 @@ Changelog Features: +* It is now possible to set fields to certain values during import, using + either the `importer.set_fields` dictionary in the config file, or by + passing one or more `--set field=value` options on the command-line. + :bug: `1881` * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` @@ -88,14 +92,6 @@ Here's a full list of new features: Thanks to :user:`jansol`. :bug:`2488` :bug:`2524` -* A new field, ``composer_sort``, is now supported and fetched from - MusicBrainz. - Thanks to :user:`dosoe`. - :bug:`2519` :bug:`2529` -* It is now possible to set fields to certain values during import, using - either the `importer.set_fields` dictionary in the config file, or by - passing one or more `--set field=value` options on the command-line. - :bug: `1881` There are also quite a few fixes: From 71d6dc354453c04bee50fcfd30c79c63d969e217 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 13 Jun 2017 09:27:42 -0400 Subject: [PATCH 2002/2280] Docs refinements for #2581 --- docs/changelog.rst | 8 ++++---- docs/reference/cli.rst | 11 ++++------- docs/reference/config.rst | 11 ++++------- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5b42be08d..fb4f0837a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,10 +6,10 @@ Changelog Features: -* It is now possible to set fields to certain values during import, using - either the `importer.set_fields` dictionary in the config file, or by - passing one or more `--set field=value` options on the command-line. - :bug: `1881` +* You can now set fields to certain values during :ref:`import-cmd`, using + either a ``--set field=value`` command-line flag or a new :ref:`set_fields` + configuration option under the `importer` section. + Thanks to :user:`bartkl`. :bug: `1881` :bug:`2581` * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index c5ea5b349..3e668f013 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -138,16 +138,13 @@ Optional command flags: searching for other candidates by using the ``--search-id SEARCH_ID`` option. Multiple IDs can be specified by simply repeating the option several times. -* You can supply ``--set`` options with ``field=value`` pairs to assign to - those fields the specified values on import, in addition to such field/value - pairs defined in the ``importer.set_fields`` dictionary in the configuration - file. Make sure to use an option per field/value pair, like so:: +* You can supply ``--set field=value`` to assign `field` to `value` on import. + These assignments will merge with (and possibly override) the + :ref:`set_fields` configuration dictionary. You can use the option multiple + times on the command line, like so:: beet import --set genre="Alternative Rock" --set mood="emotional" - Note that values for the fields specified on the command-line override the - ones defined for those fields in the configuration file. - .. _rarfile: https://pypi.python.org/pypi/rarfile/2.2 .. only:: html diff --git a/docs/reference/config.rst b/docs/reference/config.rst index bcd30169b..9faddd2d2 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -591,18 +591,15 @@ Default: ``no``. set_fields ~~~~~~~~~~ -A dictionary of field/value pairs, each one used to set a field to the -corresponding value during import. - -Example: :: +A dictionary indicating fields to set to values for newly imported music. +Here's an example:: set_fields: genre: 'To Listen' collection: 'Unordered' -Note that field/value pairs supplied via ``--set`` options on the -command-line are processed in addition to those specified here. Those values -override the ones defined here in the case of fields with the same name. +Other field/value pairs supplied via the ``--set`` option on the command-line +override any settings here for fields with the same name. Default: ``{}`` (empty). From 1f2b8cef971292c2caf2249e4494e8aa4f8e9e5a Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 14 Jun 2017 19:05:38 -0400 Subject: [PATCH 2003/2280] Tiny code and docs fixes for gmusic (#2586) --- beetsplug/gmusic.py | 9 +++++--- docs/plugins/gmusic.rst | 47 +++++++++++++++++++++-------------------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py index 545d5cae4..f935fce08 100644 --- a/beetsplug/gmusic.py +++ b/beetsplug/gmusic.py @@ -13,7 +13,7 @@ # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -"""Uploads files to Google Play Music""" +"""Upload files to Google Play Music and list songs in its library.""" from __future__ import print_function import os.path @@ -41,6 +41,7 @@ class Gmusic(BeetsPlugin): def commands(self): gupload = Subcommand('gmusic-upload', help=u'upload your tracks to Google Play Music') + gupload.func = self.upload search = Subcommand('gmusic-songs', help=u'list of songs in Google Play Music library' @@ -51,7 +52,6 @@ class Gmusic(BeetsPlugin): search.parser.add_option('-a', '--artist', dest='artist', action='store_true', help='Search by artist') - gupload.func = self.upload search.func = self.search return [gupload, search] @@ -75,7 +75,10 @@ class Gmusic(BeetsPlugin): Mobileclient.FROM_MAC_ADDRESS) files = mobile.get_all_songs() except NotLoggedIn: - ui.print_('Error occured. Please check your email and password') + ui.print_( + 'Authentication error. Please check your email and password.' + ) + return if not args: for i, file in enumerate(files, start=1): print(i, ui.colorize('blue', file['artist']), diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst index e9d81b659..4941033a3 100644 --- a/docs/plugins/gmusic.rst +++ b/docs/plugins/gmusic.rst @@ -1,48 +1,49 @@ Gmusic Plugin ============= -This plugin allows you to manage your Google Play Music library with beets. +The ``gmusic`` plugin lets you upload songs to Google Play Music and query +songs in your library. Installation ------------ -The plugin requires `gmusic`_. You can install it using `pip`:: +The plugin requires `gmusicapi`_. You can install it using `pip`:: pip install gmusicapi -.. _gmusic: https://github.com/simon-weber/gmusicapi/ +.. _gmusicapi: https://github.com/simon-weber/gmusicapi/ + +Then, you can enable the ``gmusic`` plugin in your configuration (see +:ref:`using-plugins`). + Usage ----- -To use the ``gmusic`` plugin, enable it in your configuration file. +To upload tracks to Google Play Music, use the ``gmusic-upload`` command:: -Then, add your Google email and password to configuration file under a ``gmusic`` section, if you want to be able to search for songs in your library. -It's not necessary if you only upload files. :: + beet gmusic-upload [QUERY] + +If you don't include a query, the plugin will upload your entire collection. + +To query the songs in your collection, you will need to add your Google +credentials to your beets configuration file. Put your Google username and +password under a section called ``gmusic``, like so:: gmusic: - email: email - password: password + email: user@example.com + password: seekrit +Then, use the ``gmusic-songs`` command to list music:: -If you want to upload your tracks use ``gmusic-upload`` command:: + beet gmusic-songs [-at] [ARGS] - beet gmusic-upload [ARGS...] - -If no arguments are provided, it will upload your entire beet collection. - -In case you want to search for songs in your Google Music library just use:: - - beet gmusic-songs [OPTS...] [ARGS...] - - Options: - -a, --artist search by artist name - -t, --track search by track - -For example:: +Use the ``-a`` option to search by artist and ``-t`` to search by track. For +example:: beet gmusic-songs -a John Frusciante beet gmusic-songs -t Black Hole Sun -If you want a list of all songs simply leave it without arguments and options. \ No newline at end of file +For a list of all songs in your library, run ``beet gmusic-songs`` without any +arguments. From 97cedce0f8c71e9d10b9ebe69bfed4155dfce5ad Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 14 Jun 2017 19:07:34 -0400 Subject: [PATCH 2004/2280] Changelog for #2586 (fixes #2553) --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index fb4f0837a..c727d284d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,8 @@ Features: * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` +* A new :ref:`/plugins/gmusic` lets you interact with your Google Play Music + library. Thanks to :user:`tigranl`. :bug:`2553` :bug:`2586` * :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from classic ReplayGain data for formats that need it (namely, Ogg Opus). A new `r128` configuration option enables this behavior for specific formats. From ace5656e369b8e6b5e948d3ad5ce4191380409d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 14 Jun 2017 19:08:27 -0400 Subject: [PATCH 2005/2280] Complete set of __future__ imports --- beetsplug/gmusic.py | 2 +- test/rsrc/unicode’d.mp3 | Bin 12820 -> 12820 bytes 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py index f935fce08..67752ba27 100644 --- a/beetsplug/gmusic.py +++ b/beetsplug/gmusic.py @@ -15,7 +15,7 @@ """Upload files to Google Play Music and list songs in its library.""" -from __future__ import print_function +from __future__ import absolute_import, division, print_function import os.path from beets.plugins import BeetsPlugin diff --git a/test/rsrc/unicode’d.mp3 b/test/rsrc/unicode’d.mp3 index 663f43910b83fd13227fc0abcbbab1e87576cdaa..ebc75ce31cfdd6bcea3ed250b2af79b3141c09ea 100644 GIT binary patch delta 68 zcmbP|G9_ih3`Qei1_tIJLnDiLM<1t9-*|UNPd^3&hLDJe2nGfQxMWC>qq8?ua`Obn L61L5D9M?1fS?v*o delta 20 ccmbP|G9_ih493lu7<1Sru~==k Date: Wed, 14 Jun 2017 19:09:38 -0400 Subject: [PATCH 2006/2280] ReST syntax fix --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index c727d284d..299d380f9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,7 +13,7 @@ Features: * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` -* A new :ref:`/plugins/gmusic` lets you interact with your Google Play Music +* A new :doc:`/plugins/gmusic` lets you interact with your Google Play Music library. Thanks to :user:`tigranl`. :bug:`2553` :bug:`2586` * :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from classic ReplayGain data for formats that need it (namely, Ogg Opus). A new From 92c118f4a85823c3a90ef414b5c05f63656e355f Mon Sep 17 00:00:00 2001 From: euri10 Date: Thu, 15 Jun 2017 09:11:28 +0200 Subject: [PATCH 2007/2280] Corrected some flake8 errors --- beets/dbcore/query.py | 49 ++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index e90077c5f..d669b34c4 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -40,6 +40,7 @@ class InvalidQueryError(ParsingError): The query should be a unicode string or a list, which will be space-joined. """ + def __init__(self, query, explanation): if isinstance(query, list): query = " ".join(query) @@ -53,6 +54,7 @@ class InvalidQueryArgumentValueError(ParsingError): It exists to be caught in upper stack levels so a meaningful (i.e. with the query) InvalidQueryError can be raised. """ + def __init__(self, what, expected, detail=None): message = u"'{0}' is not {1}".format(what, expected) if detail: @@ -63,6 +65,7 @@ class InvalidQueryArgumentValueError(ParsingError): class Query(object): """An abstract class representing a query into the item database. """ + def clause(self): """Generate an SQLite expression implementing the query. @@ -95,6 +98,7 @@ class FieldQuery(Query): string. Subclasses may also provide `col_clause` to implement the same matching functionality in SQLite. """ + def __init__(self, field, pattern, fast=True): self.field = field self.pattern = pattern @@ -126,7 +130,7 @@ class FieldQuery(Query): def __eq__(self, other): return super(FieldQuery, self).__eq__(other) and \ - self.field == other.field and self.pattern == other.pattern + self.field == other.field and self.pattern == other.pattern def __hash__(self): return hash((self.field, hash(self.pattern))) @@ -134,6 +138,7 @@ class FieldQuery(Query): class MatchQuery(FieldQuery): """A query that looks for exact matches in an item field.""" + def col_clause(self): return self.field + " = ?", [self.pattern] @@ -143,7 +148,6 @@ class MatchQuery(FieldQuery): class NoneQuery(FieldQuery): - def __init__(self, field, fast=True): super(NoneQuery, self).__init__(field, None, fast) @@ -165,6 +169,7 @@ class StringFieldQuery(FieldQuery): """A FieldQuery that converts values to strings before matching them. """ + @classmethod def value_match(cls, pattern, value): """Determine whether the value matches the pattern. The value @@ -182,11 +187,12 @@ class StringFieldQuery(FieldQuery): class SubstringQuery(StringFieldQuery): """A query that matches a substring in a specific item field.""" + def col_clause(self): pattern = (self.pattern - .replace('\\', '\\\\') - .replace('%', '\\%') - .replace('_', '\\_')) + .replace('\\', '\\\\') + .replace('%', '\\%') + .replace('_', '\\_')) search = '%' + pattern + '%' clause = self.field + " like ? escape '\\'" subvals = [search] @@ -204,6 +210,7 @@ class RegexpQuery(StringFieldQuery): Raises InvalidQueryError when the pattern is not a valid regular expression. """ + def __init__(self, field, pattern, fast=True): super(RegexpQuery, self).__init__(field, pattern, fast) pattern = self._normalize(pattern) @@ -231,6 +238,7 @@ class BooleanQuery(MatchQuery): """Matches a boolean field. Pattern should either be a boolean or a string reflecting a boolean. """ + def __init__(self, field, pattern, fast=True): super(BooleanQuery, self).__init__(field, pattern, fast) if isinstance(pattern, six.string_types): @@ -244,6 +252,7 @@ class BytesQuery(MatchQuery): `unicode` equivalently in Python 2. Always use this query instead of `MatchQuery` when matching on BLOB values. """ + def __init__(self, field, pattern): super(BytesQuery, self).__init__(field, pattern) @@ -270,6 +279,7 @@ class NumericQuery(FieldQuery): Raises InvalidQueryError when the pattern does not represent an int or a float. """ + def _convert(self, s): """Convert a string to a numeric type (float or int). @@ -337,6 +347,7 @@ class CollectionQuery(Query): """An abstract query class that aggregates other queries. Can be indexed like a list to access the sub-queries. """ + def __init__(self, subqueries=()): self.subqueries = subqueries @@ -375,7 +386,7 @@ class CollectionQuery(Query): def __eq__(self, other): return super(CollectionQuery, self).__eq__(other) and \ - self.subqueries == other.subqueries + self.subqueries == other.subqueries def __hash__(self): """Since subqueries are mutable, this object should not be hashable. @@ -389,6 +400,7 @@ class AnyFieldQuery(CollectionQuery): any field. The individual field query class is provided to the constructor. """ + def __init__(self, pattern, fields, cls): self.pattern = pattern self.fields = fields @@ -414,7 +426,7 @@ class AnyFieldQuery(CollectionQuery): def __eq__(self, other): return super(AnyFieldQuery, self).__eq__(other) and \ - self.query_class == other.query_class + self.query_class == other.query_class def __hash__(self): return hash((self.pattern, tuple(self.fields), self.query_class)) @@ -424,6 +436,7 @@ class MutableCollectionQuery(CollectionQuery): """A collection query whose subqueries may be modified after the query is initialized. """ + def __setitem__(self, key, value): self.subqueries[key] = value @@ -433,6 +446,7 @@ class MutableCollectionQuery(CollectionQuery): class AndQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('and') @@ -442,6 +456,7 @@ class AndQuery(MutableCollectionQuery): class OrQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('or') @@ -453,6 +468,7 @@ class NotQuery(Query): """A query that matches the negation of its `subquery`, as a shorcut for performing `not(subquery)` without using regular expressions. """ + def __init__(self, subquery): self.subquery = subquery @@ -473,7 +489,7 @@ class NotQuery(Query): def __eq__(self, other): return super(NotQuery, self).__eq__(other) and \ - self.subquery == other.subquery + self.subquery == other.subquery def __hash__(self): return hash(('not', hash(self.subquery))) @@ -481,6 +497,7 @@ class NotQuery(Query): class TrueQuery(Query): """A query that always matches.""" + def clause(self): return '1', () @@ -490,6 +507,7 @@ class TrueQuery(Query): class FalseQuery(Query): """A query that never matches.""" + def clause(self): return '0', () @@ -533,7 +551,6 @@ class Period(object): instants of time during January 2014. """ - precisions = ('year', 'month', 'day', 'hour', 'minute', 'second') date_formats = ( ('%Y',), # year @@ -545,7 +562,6 @@ class Period(object): ) relative = {'y': 365, 'm': 30, 'w': 7, 'd': 1} - def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and precision (a string, one of "year", "month", "day", "hour", "minute", @@ -599,7 +615,8 @@ class Period(object): timespan = match_dq.group('timespan') multiplier = -1 if sign == '-' else 1 days = cls.relative[timespan] - date = datetime.now() + multiplier * timedelta(days=int(quantity) * days) + date = datetime.now() + multiplier * timedelta( + days=int(quantity) * days) string = date.strftime(cls.date_formats[5][0]) date, ordinal = find_date_and_format(string) @@ -838,13 +855,14 @@ class MultipleSort(Sort): def __eq__(self, other): return super(MultipleSort, self).__eq__(other) and \ - self.sorts == other.sorts + self.sorts == other.sorts class FieldSort(Sort): """An abstract sort criterion that orders by a specific field (of any kind). """ + def __init__(self, field, ascending=True, case_insensitive=True): self.field = field self.ascending = ascending @@ -875,13 +893,14 @@ class FieldSort(Sort): def __eq__(self, other): return super(FieldSort, self).__eq__(other) and \ - self.field == other.field and \ - self.ascending == other.ascending + self.field == other.field and \ + self.ascending == other.ascending class FixedFieldSort(FieldSort): """Sort object to sort on a fixed field. """ + def order_clause(self): order = "ASC" if self.ascending else "DESC" if self.case_insensitive: @@ -898,12 +917,14 @@ class SlowFieldSort(FieldSort): """A sort criterion by some model field other than a fixed field: i.e., a computed or flexible field. """ + def is_slow(self): return True class NullSort(Sort): """No sorting. Leave results unsorted.""" + def sort(self, items): return items From 527d0a88f4221663a31b433ef98c52cb4c46b022 Mon Sep 17 00:00:00 2001 From: euri10 Date: Thu, 15 Jun 2017 09:31:41 +0200 Subject: [PATCH 2008/2280] Corrected some flake8 errors --- beets/dbcore/query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index d669b34c4..169697b12 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -130,7 +130,7 @@ class FieldQuery(Query): def __eq__(self, other): return super(FieldQuery, self).__eq__(other) and \ - self.field == other.field and self.pattern == other.pattern + self.field == other.field and self.pattern == other.pattern def __hash__(self): return hash((self.field, hash(self.pattern))) From ae3f9bf9b6c162a7f9386eab45219d4c442f7e48 Mon Sep 17 00:00:00 2001 From: euri10 Date: Thu, 15 Jun 2017 09:59:53 +0200 Subject: [PATCH 2009/2280] Corrected some flake8 errors, overindentation and pycharm reformat don't seem to play well --- beets/dbcore/query.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 169697b12..14117f9af 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -386,7 +386,7 @@ class CollectionQuery(Query): def __eq__(self, other): return super(CollectionQuery, self).__eq__(other) and \ - self.subqueries == other.subqueries + self.subqueries == other.subqueries def __hash__(self): """Since subqueries are mutable, this object should not be hashable. @@ -426,7 +426,7 @@ class AnyFieldQuery(CollectionQuery): def __eq__(self, other): return super(AnyFieldQuery, self).__eq__(other) and \ - self.query_class == other.query_class + self.query_class == other.query_class def __hash__(self): return hash((self.pattern, tuple(self.fields), self.query_class)) @@ -489,7 +489,7 @@ class NotQuery(Query): def __eq__(self, other): return super(NotQuery, self).__eq__(other) and \ - self.subquery == other.subquery + self.subquery == other.subquery def __hash__(self): return hash(('not', hash(self.subquery))) @@ -855,7 +855,7 @@ class MultipleSort(Sort): def __eq__(self, other): return super(MultipleSort, self).__eq__(other) and \ - self.sorts == other.sorts + self.sorts == other.sorts class FieldSort(Sort): @@ -893,8 +893,8 @@ class FieldSort(Sort): def __eq__(self, other): return super(FieldSort, self).__eq__(other) and \ - self.field == other.field and \ - self.ascending == other.ascending + self.field == other.field and \ + self.ascending == other.ascending class FixedFieldSort(FieldSort): From bc8a8ecf5f819facc8dbe088a3829ebd6acfb1e2 Mon Sep 17 00:00:00 2001 From: robot3498712 Date: Thu, 15 Jun 2017 12:49:00 +0200 Subject: [PATCH 2010/2280] fix /issues/2592: web: Use Unicode paths to send files on Windows under Python 2 --- beetsplug/web/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 290f25b48..14e338ba6 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -217,12 +217,13 @@ def all_items(): @app.route('/item//file') def item_file(item_id): item = g.lib.get_item(item_id) + item_path = util.syspath(item.path) if os.name == 'nt' else util.py3_path(item.path) response = flask.send_file( - util.py3_path(item.path), + item_path, as_attachment=True, attachment_filename=os.path.basename(util.py3_path(item.path)), ) - response.headers['Content-Length'] = os.path.getsize(item.path) + response.headers['Content-Length'] = os.path.getsize(item_path) return response From cafbb2438e90727ae48c00324cda5f8309ab544c Mon Sep 17 00:00:00 2001 From: robot3498712 Date: Thu, 15 Jun 2017 13:27:28 +0200 Subject: [PATCH 2011/2280] fixed failing test - line too long --- beetsplug/web/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 14e338ba6..00718dbfb 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -217,7 +217,8 @@ def all_items(): @app.route('/item//file') def item_file(item_id): item = g.lib.get_item(item_id) - item_path = util.syspath(item.path) if os.name == 'nt' else util.py3_path(item.path) + item_path = util.syspath(item.path) if (os.name == 'nt') else ( + util.py3_path(item.path)) response = flask.send_file( item_path, as_attachment=True, From f36c70c754b7bd8c2616f0e37ff4853961deb991 Mon Sep 17 00:00:00 2001 From: Aran Cox Date: Thu, 15 Jun 2017 09:00:59 -0500 Subject: [PATCH 2012/2280] do not quote the value in xml, use quoteattr to add quotes as needed --- beetsplug/metasync/amarok.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index aaa1ee91e..caaea72dc 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -21,7 +21,7 @@ from __future__ import division, absolute_import, print_function from os.path import basename from datetime import datetime from time import mktime -from xml.sax.saxutils import escape +from xml.sax.saxutils import quoteattr from beets.util import displayable_path from beets.dbcore import types @@ -51,7 +51,7 @@ class Amarok(MetaSource): queryXML = u' \ \ - \ + \ \ ' @@ -71,7 +71,7 @@ class Amarok(MetaSource): # for the patch relative to the mount point. But the full path is part # of the result set. So query for the filename and then try to match # the correct item from the results we get back - results = self.collection.Query(self.queryXML % escape(basename(path))) + results = self.collection.Query(self.queryXML % quoteattr(basename(path))) for result in results: if result['xesam:url'] != path: continue From c840fea1254325940bc4e48c1c8e82a5f9678f0d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 17:49:59 -0400 Subject: [PATCH 2013/2280] Changelog for #2593 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 299d380f9..b3bee8a44 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,6 +28,8 @@ Fixes: * :doc:`/plugins/lastgenre`: Fix a crash when using the `prefer_specific` and `canonical` options together. Thanks to :user:`yacoob`. :bug:`2459` :bug:`2583` +* :doc:`/plugins/web`: Fix a crash on Windows under Python 2 when serving + non-ASCII filenames. Thanks to :user:`robot3498712`. :bug:`2592` :bug:`2593` 1.4.4 (June 10, 2017) From 009c6a4f6d76496109ab9b9751ff22864cf612cd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 17:51:14 -0400 Subject: [PATCH 2014/2280] Slightly clearer layout for #2593, and comments --- beetsplug/web/__init__.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 00718dbfb..635c2f5a8 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -217,8 +217,14 @@ def all_items(): @app.route('/item//file') def item_file(item_id): item = g.lib.get_item(item_id) - item_path = util.syspath(item.path) if (os.name == 'nt') else ( - util.py3_path(item.path)) + + # On Windows under Python 2, Flask wants a Unicode path. On Python 3, it + # *always* wants a Unicode path. + if os.name == 'nt': + item_path = util.syspath(item.path) + else: + item_path = util.py3_path(item.path) + response = flask.send_file( item_path, as_attachment=True, From 2144882290111b908293fceb542fe3047ce62de5 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 17:59:40 -0400 Subject: [PATCH 2015/2280] Correct some PEP8 post-docstring whitespace To better match #2597 for a cleaner diff. --- beets/dbcore/query.py | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 51790b9fa..31756aeac 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -40,6 +40,7 @@ class InvalidQueryError(ParsingError): The query should be a unicode string or a list, which will be space-joined. """ + def __init__(self, query, explanation): if isinstance(query, list): query = " ".join(query) @@ -53,6 +54,7 @@ class InvalidQueryArgumentValueError(ParsingError): It exists to be caught in upper stack levels so a meaningful (i.e. with the query) InvalidQueryError can be raised. """ + def __init__(self, what, expected, detail=None): message = u"'{0}' is not {1}".format(what, expected) if detail: @@ -63,6 +65,7 @@ class InvalidQueryArgumentValueError(ParsingError): class Query(object): """An abstract class representing a query into the item database. """ + def clause(self): """Generate an SQLite expression implementing the query. @@ -95,6 +98,7 @@ class FieldQuery(Query): string. Subclasses may also provide `col_clause` to implement the same matching functionality in SQLite. """ + def __init__(self, field, pattern, fast=True): self.field = field self.pattern = pattern @@ -134,6 +138,7 @@ class FieldQuery(Query): class MatchQuery(FieldQuery): """A query that looks for exact matches in an item field.""" + def col_clause(self): return self.field + " = ?", [self.pattern] @@ -143,6 +148,7 @@ class MatchQuery(FieldQuery): class NoneQuery(FieldQuery): + """A query that checks whether a field is null.""" def __init__(self, field, fast=True): super(NoneQuery, self).__init__(field, None, fast) @@ -165,6 +171,7 @@ class StringFieldQuery(FieldQuery): """A FieldQuery that converts values to strings before matching them. """ + @classmethod def value_match(cls, pattern, value): """Determine whether the value matches the pattern. The value @@ -182,11 +189,12 @@ class StringFieldQuery(FieldQuery): class SubstringQuery(StringFieldQuery): """A query that matches a substring in a specific item field.""" + def col_clause(self): pattern = (self.pattern - .replace('\\', '\\\\') - .replace('%', '\\%') - .replace('_', '\\_')) + .replace('\\', '\\\\') + .replace('%', '\\%') + .replace('_', '\\_')) search = '%' + pattern + '%' clause = self.field + " like ? escape '\\'" subvals = [search] @@ -204,6 +212,7 @@ class RegexpQuery(StringFieldQuery): Raises InvalidQueryError when the pattern is not a valid regular expression. """ + def __init__(self, field, pattern, fast=True): super(RegexpQuery, self).__init__(field, pattern, fast) pattern = self._normalize(pattern) @@ -231,6 +240,7 @@ class BooleanQuery(MatchQuery): """Matches a boolean field. Pattern should either be a boolean or a string reflecting a boolean. """ + def __init__(self, field, pattern, fast=True): super(BooleanQuery, self).__init__(field, pattern, fast) if isinstance(pattern, six.string_types): @@ -244,6 +254,7 @@ class BytesQuery(MatchQuery): `unicode` equivalently in Python 2. Always use this query instead of `MatchQuery` when matching on BLOB values. """ + def __init__(self, field, pattern): super(BytesQuery, self).__init__(field, pattern) @@ -270,6 +281,7 @@ class NumericQuery(FieldQuery): Raises InvalidQueryError when the pattern does not represent an int or a float. """ + def _convert(self, s): """Convert a string to a numeric type (float or int). @@ -337,6 +349,7 @@ class CollectionQuery(Query): """An abstract query class that aggregates other queries. Can be indexed like a list to access the sub-queries. """ + def __init__(self, subqueries=()): self.subqueries = subqueries @@ -389,6 +402,7 @@ class AnyFieldQuery(CollectionQuery): any field. The individual field query class is provided to the constructor. """ + def __init__(self, pattern, fields, cls): self.pattern = pattern self.fields = fields @@ -424,6 +438,7 @@ class MutableCollectionQuery(CollectionQuery): """A collection query whose subqueries may be modified after the query is initialized. """ + def __setitem__(self, key, value): self.subqueries[key] = value @@ -433,6 +448,7 @@ class MutableCollectionQuery(CollectionQuery): class AndQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('and') @@ -442,6 +458,7 @@ class AndQuery(MutableCollectionQuery): class OrQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" + def clause(self): return self.clause_with_joiner('or') @@ -453,6 +470,7 @@ class NotQuery(Query): """A query that matches the negation of its `subquery`, as a shorcut for performing `not(subquery)` without using regular expressions. """ + def __init__(self, subquery): self.subquery = subquery @@ -481,6 +499,7 @@ class NotQuery(Query): class TrueQuery(Query): """A query that always matches.""" + def clause(self): return '1', () @@ -490,6 +509,7 @@ class TrueQuery(Query): class FalseQuery(Query): """A query that never matches.""" + def clause(self): return '0', () From 949d7fbca5c0620b392e9473fcb4a1df1cdf55ab Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 18:05:47 -0400 Subject: [PATCH 2016/2280] More docstring whitespace --- beets/dbcore/query.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 31756aeac..4d94f4e35 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -667,6 +667,7 @@ class DateQuery(FieldQuery): The value of a date field can be matched against a date interval by using an ellipsis interval syntax similar to that of NumericQuery. """ + def __init__(self, field, pattern, fast=True): super(DateQuery, self).__init__(field, pattern, fast) start, end = _parse_periods(pattern) @@ -710,6 +711,7 @@ class DurationQuery(NumericQuery): Raises InvalidQueryError when the pattern does not represent an int, float or M:SS time interval. """ + def _convert(self, s): """Convert a M:SS or numeric string to a float. @@ -832,6 +834,7 @@ class FieldSort(Sort): """An abstract sort criterion that orders by a specific field (of any kind). """ + def __init__(self, field, ascending=True, case_insensitive=True): self.field = field self.ascending = ascending @@ -869,6 +872,7 @@ class FieldSort(Sort): class FixedFieldSort(FieldSort): """Sort object to sort on a fixed field. """ + def order_clause(self): order = "ASC" if self.ascending else "DESC" if self.case_insensitive: @@ -885,12 +889,14 @@ class SlowFieldSort(FieldSort): """A sort criterion by some model field other than a fixed field: i.e., a computed or flexible field. """ + def is_slow(self): return True class NullSort(Sort): """No sorting. Leave results unsorted.""" + def sort(self, items): return items From 8a6c8cde6a6221274c74722a47b26d4ae70f6cb0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 18:10:55 -0400 Subject: [PATCH 2017/2280] Simplify the docs a bit for relative dates --- beets/dbcore/query.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 39ff0dc77..2feec08ab 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -577,20 +577,19 @@ class Period(object): @classmethod def parse(cls, string): """Parse a date and return a `Period` object or `None` if the - string is empty. - Depending on the string, the date can be absolute or - relative. - An absolute date has to be like one of the date_formats '%Y' or '%Y-%m' - or '%Y-%m-%d' - A relative date consists of three parts: - - a ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` - sign will add a time quantity to the current date while the ``-`` sign - will do the opposite - - a number follows and indicates the amount to add or substract - - a final letter ends and represents the amount in either days, weeks, - months or years (``d``, ``w``, ``m`` or ``y``) - Please note that this relative calculation makes the assumption of 30 - days per month and 365 days per year. + string is empty, or raise an InvalidQueryArgumentValueError if + the string cannot be parsed to a date. + + The date may be absolute or relative. Absolute dates look like + `YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative + dates have three parts: + + - Optionally, a ``+`` or ``-`` sign indicating the future or the + past. The default is the future. + - A number: how much to add or subtract. + - A letter indicating the unit: days, weeks, months or years + (``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days + and a "year" is exactly 365 days. """ def find_date_and_format(string): From 130c581c282942e01c0ae4c50cc82d2ff070414e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 18:15:51 -0400 Subject: [PATCH 2018/2280] Some formatting cleanup for relative dates --- beets/dbcore/query.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 2feec08ab..5ef440b5e 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -563,6 +563,8 @@ class Period(object): ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second ) relative = {'y': 365, 'm': 30, 'w': 7, 'd': 1} + relative_re = '(?P[+|-]?)(?P[0-9]+)' + \ + '(?P[y|m|w|d])' def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and @@ -606,24 +608,26 @@ class Period(object): if not string: return None - pattern_dq = '(?P[+|-]?)(?P[0-9]+)(?P[y|m|w|d])' # noqa: E501 - match_dq = re.match(pattern_dq, string) - # test if the string matches the relative date pattern, add the parsed - # quantity to now in that case - if match_dq is not None: + # Check for a relative date. + match_dq = re.match(cls.relative_re, string) + if match_dq: sign = match_dq.group('sign') quantity = match_dq.group('quantity') timespan = match_dq.group('timespan') + + # Add or subtract the given amount of time from the current + # date. multiplier = -1 if sign == '-' else 1 days = cls.relative[timespan] - date = datetime.now() + multiplier * timedelta( - days=int(quantity) * days) + date = datetime.now() + \ + timedelta(days=int(quantity) * days) * multiplier string = date.strftime(cls.date_formats[5][0]) + # Check for an absolute date. date, ordinal = find_date_and_format(string) if date is None: raise InvalidQueryArgumentValueError(string, - 'a valid datetime string') + 'a valid date/time string') precision = cls.precisions[ordinal] return cls(date, precision) From 8ba0060f4472a77d1368555b6f01f4a2152a3a9e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 20:46:54 -0400 Subject: [PATCH 2019/2280] Wrap a long line --- beetsplug/metasync/amarok.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/metasync/amarok.py b/beetsplug/metasync/amarok.py index caaea72dc..0622fc17a 100644 --- a/beetsplug/metasync/amarok.py +++ b/beetsplug/metasync/amarok.py @@ -71,7 +71,9 @@ class Amarok(MetaSource): # for the patch relative to the mount point. But the full path is part # of the result set. So query for the filename and then try to match # the correct item from the results we get back - results = self.collection.Query(self.queryXML % quoteattr(basename(path))) + results = self.collection.Query( + self.queryXML % quoteattr(basename(path)) + ) for result in results: if result['xesam:url'] != path: continue From 63692ff9a4ba0225372b5e7dd6bb7aa2f8cbc06f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 15 Jun 2017 21:04:16 -0400 Subject: [PATCH 2020/2280] Changelog for #2596 (fixes #2595) --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index b3bee8a44..01cc27cc5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -30,6 +30,8 @@ Fixes: :bug:`2583` * :doc:`/plugins/web`: Fix a crash on Windows under Python 2 when serving non-ASCII filenames. Thanks to :user:`robot3498712`. :bug:`2592` :bug:`2593` +* :doc:`/plugins/metasync`: Fix a crash in the Amarok backend when filenames + contain quotes. Thanks to :user:`aranc23`. :bug:`2595` :bug:`2596` 1.4.4 (June 10, 2017) From 93f064f505837333f2090338df20f6430bc5ab01 Mon Sep 17 00:00:00 2001 From: euri10 Date: Fri, 16 Jun 2017 09:14:40 +0200 Subject: [PATCH 2021/2280] Renamed relative to relative_units Changed the return in case of a relative date, by default precision is to the second, aka 5 Removed old 'relative' precision that indeed isn't necessary anymore Corrected doc according to current relative date format, no more @ --- beets/dbcore/query.py | 8 +++----- docs/reference/query.rst | 3 +-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index 5ef440b5e..fbe6626c7 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -562,7 +562,7 @@ class Period(object): ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second ) - relative = {'y': 365, 'm': 30, 'w': 7, 'd': 1} + relative_units = {'y': 365, 'm': 30, 'w': 7, 'd': 1} relative_re = '(?P[+|-]?)(?P[0-9]+)' + \ '(?P[y|m|w|d])' @@ -618,10 +618,10 @@ class Period(object): # Add or subtract the given amount of time from the current # date. multiplier = -1 if sign == '-' else 1 - days = cls.relative[timespan] + days = cls.relative_units[timespan] date = datetime.now() + \ timedelta(days=int(quantity) * days) * multiplier - string = date.strftime(cls.date_formats[5][0]) + return cls(date, cls.precisions[5]) # Check for an absolute date. date, ordinal = find_date_and_format(string) @@ -637,8 +637,6 @@ class Period(object): """ precision = self.precision date = self.date - if 'relative' == self.precision: - return date if 'year' == self.precision: return date.replace(year=date.year + 1, month=1) elif 'month' == precision: diff --git a/docs/reference/query.rst b/docs/reference/query.rst index fa1286c8c..bb14f3cd2 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -165,8 +165,7 @@ and day are optional. If you leave out the day, for example, you will get matches for the whole month. You can also use relative dates to the current time. -A relative date begins with an ``@``. -It looks like ``@-3w``, ``@2m`` or ``@-4d`` which means the date 3 weeks ago, +It looks like ``-3w``, ``2m`` or ``-4d`` which means the date 3 weeks ago, the date 2 months from now and the date 4 days ago. A relative date consists of three parts: - ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will From 690ed731d83e393a93d5dea1e892d79a7c557578 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Jun 2017 11:07:24 -0400 Subject: [PATCH 2022/2280] Move the relative date docs downward It's important to introduce the .. syntax before we get here. --- docs/reference/query.rst | 44 ++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index bb14f3cd2..4eba910ca 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -164,28 +164,6 @@ Dates are written separated by hyphens, like ``year-month-day``, but the month and day are optional. If you leave out the day, for example, you will get matches for the whole month. -You can also use relative dates to the current time. -It looks like ``-3w``, ``2m`` or ``-4d`` which means the date 3 weeks ago, -the date 2 months from now and the date 4 days ago. -A relative date consists of three parts: -- ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will -add a time quantity to the current date while the ``-`` sign will do the -opposite -- a number follows and indicates the amount to add or substract -- a final letter ends and represents the amount in either days, weeks, months or -years (``d``, ``w``, ``m`` or ``y``) - -Please note that this relative calculation makes the assumption of 30 days per -month and 365 days per year. - -Here is an example that finds all the albums added between now and last week:: - - $ beet ls -a 'added:-1w..' - -Find all items added in a 2 weeks period 4 weeks ago:: - - $ beet ls -a 'added:-6w..-4w' - Date *intervals*, like the numeric intervals described above, are separated by two dots (``..``). You can specify a start, an end, or both. @@ -239,6 +217,28 @@ queries do the same thing:: $ beet ls 'added:2008-12-01t22:45:20' $ beet ls 'added:2008-12-01 22:45:20' +You can also use relative dates to the current time. +It looks like ``-3w``, ``2m`` or ``-4d`` which means the date 3 weeks ago, +the date 2 months from now and the date 4 days ago. +A relative date consists of three parts: +- ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will +add a time quantity to the current date while the ``-`` sign will do the +opposite +- a number follows and indicates the amount to add or substract +- a final letter ends and represents the amount in either days, weeks, months or +years (``d``, ``w``, ``m`` or ``y``) + +Please note that this relative calculation makes the assumption of 30 days per +month and 365 days per year. + +Here is an example that finds all the albums added between now and last week:: + + $ beet ls -a 'added:-1w..' + +Find all items added in a 2 weeks period 4 weeks ago:: + + $ beet ls -a 'added:-6w..-4w' + .. _not_query: Query Term Negation From b1b4272501a9e5c0fb4f89fed831b69fa1f77d29 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Jun 2017 11:11:12 -0400 Subject: [PATCH 2023/2280] Refinements to the relative date docs --- docs/reference/query.rst | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/docs/reference/query.rst b/docs/reference/query.rst index 4eba910ca..d103d9aec 100644 --- a/docs/reference/query.rst +++ b/docs/reference/query.rst @@ -217,27 +217,24 @@ queries do the same thing:: $ beet ls 'added:2008-12-01t22:45:20' $ beet ls 'added:2008-12-01 22:45:20' -You can also use relative dates to the current time. -It looks like ``-3w``, ``2m`` or ``-4d`` which means the date 3 weeks ago, -the date 2 months from now and the date 4 days ago. -A relative date consists of three parts: -- ``+`` or ``-`` sign is optional and defaults to ``+``. The ``+`` sign will -add a time quantity to the current date while the ``-`` sign will do the -opposite -- a number follows and indicates the amount to add or substract -- a final letter ends and represents the amount in either days, weeks, months or -years (``d``, ``w``, ``m`` or ``y``) +You can also use *relative* dates. For example, ``-3w`` means three weeks ago, +and ``+4d`` means four days in the future. A relative date has three parts: -Please note that this relative calculation makes the assumption of 30 days per -month and 365 days per year. +- Either ``+`` or ``-``, to indicate the past or the future. The sign is + optional; if you leave this off, it defaults to the future. +- A number. +- A letter indicating the unit: ``d``, ``w``, ``m`` or ``y``, meaning days, + weeks, months or years. (A "month" is always 30 days and a "year" is always + 365 days.) -Here is an example that finds all the albums added between now and last week:: +Here's an example that finds all the albums added since last week:: $ beet ls -a 'added:-1w..' -Find all items added in a 2 weeks period 4 weeks ago:: +And here's an example that lists items added in a two-week period starting +four weeks ago:: - $ beet ls -a 'added:-6w..-4w' + $ beet ls 'added:-6w..-4w' .. _not_query: From a52d3d532ad01f7f7d5798baa0688b7b14576d6c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 16 Jun 2017 11:13:01 -0400 Subject: [PATCH 2024/2280] Changelog for relative dates (#2418, #2598) --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 01cc27cc5..d692c4bf8 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,9 @@ Features: * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` +* :ref:`Date queries ` can also be *relative*. You can say + ``added:-1w..`` to match music added in the last week, for example. Thanks + to :user:`euri10`. :bug:`2598` * A new :doc:`/plugins/gmusic` lets you interact with your Google Play Music library. Thanks to :user:`tigranl`. :bug:`2553` :bug:`2586` * :doc:`/plugins/replaygain`: We now keep R128 data in separate tags from From 732f0174c83bbc6e5b7b53436a186b011123af8d Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Jun 2017 12:41:46 -0400 Subject: [PATCH 2025/2280] Expand error message for FileTypeError (#2599) ...when Mutagen doesn't recognize the type at all. --- beets/mediafile.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index d928e05c4..b4c62612f 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -96,7 +96,7 @@ class FileTypeError(UnreadableFileError): """ def __init__(self, path, mutagen_type=None): if mutagen_type is None: - msg = repr(path) + msg = u'{0!r}: not in a recognized format'.format(path) else: msg = u'{0}: of mutagen type {1}'.format(repr(path), mutagen_type) Exception.__init__(self, msg) diff --git a/docs/changelog.rst b/docs/changelog.rst index d692c4bf8..3de6792ed 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -35,6 +35,8 @@ Fixes: non-ASCII filenames. Thanks to :user:`robot3498712`. :bug:`2592` :bug:`2593` * :doc:`/plugins/metasync`: Fix a crash in the Amarok backend when filenames contain quotes. Thanks to :user:`aranc23`. :bug:`2595` :bug:`2596` +* More informative error messages are displayed when the file format is not + recognized. :bug:`2599` 1.4.4 (June 10, 2017) From d2106454c47cd3b5972d347d9a1e176f5420e9d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 17 Jun 2017 12:43:25 -0400 Subject: [PATCH 2026/2280] Fix path in read errors while writing (#2599) --- beets/library.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 991de59e8..0a64516ad 100644 --- a/beets/library.py +++ b/beets/library.py @@ -615,7 +615,7 @@ class Item(LibModel): mediafile = MediaFile(syspath(path), id3v23=beets.config['id3v23'].get(bool)) except UnreadableFileError as exc: - raise ReadError(self.path, exc) + raise ReadError(path, exc) # Write the tags to the file. mediafile.update(item_tags) From 3bea8761114fe1704f543e51d6e259a68f8fd88f Mon Sep 17 00:00:00 2001 From: masi Date: Sat, 17 Jun 2017 23:20:46 +0200 Subject: [PATCH 2027/2280] Fix #1918: ValueError on trying to import --- beetsplug/importadded.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/importadded.py b/beetsplug/importadded.py index c1838884b..36407b14c 100644 --- a/beetsplug/importadded.py +++ b/beetsplug/importadded.py @@ -30,8 +30,8 @@ class ImportAddedPlugin(BeetsPlugin): self.item_mtime = dict() register = self.register_listener - register('import_task_start', self.check_config) - register('import_task_start', self.record_if_inplace) + register('import_task_created', self.check_config) + register('import_task_created', self.record_if_inplace) register('import_task_files', self.record_reimported) register('before_item_moved', self.record_import_mtime) register('item_copied', self.record_import_mtime) From 2cd3e13aa74c7f45c455a4d83a8892d7cf84c55c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 14:47:11 -0400 Subject: [PATCH 2028/2280] Spruce up changelog for release --- docs/changelog.rst | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3de6792ed..55b6f0c78 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,12 +4,17 @@ Changelog 1.4.5 (in development) ---------------------- -Features: +Version 1.4.5 adds some oft-requested features. When you're importing files, +you can now manually set fields on the new music. Date queries have gotten +much more powerful: you can write precise queries down to the second, and we +now have *relative* queries like ``-1w``, which means *one week ago*. + +Here are the new features: * You can now set fields to certain values during :ref:`import-cmd`, using either a ``--set field=value`` command-line flag or a new :ref:`set_fields` configuration option under the `importer` section. - Thanks to :user:`bartkl`. :bug: `1881` :bug:`2581` + Thanks to :user:`bartkl`. :bug:`1881` :bug:`2581` * :ref:`Date queries ` can now include times, so you can filter your music down to the second. Thanks to :user:`discopatrick`. :bug:`2506` :bug:`2528` @@ -23,10 +28,10 @@ Features: `r128` configuration option enables this behavior for specific formats. Thanks to :user:`autrimpo`. :bug:`2557` :bug:`2560` * The :ref:`move-cmd` command gained a new ``--export`` flag, which copies - files to an external location without changing their location in the library + files to an external location without changing their paths in the library database. Thanks to :user:`SpirosChadoulos`. :bug:`435` :bug:`2510` -Fixes: +There are also some bug fixes: * :doc:`/plugins/lastgenre`: Fix a crash when using the `prefer_specific` and `canonical` options together. Thanks to :user:`yacoob`. :bug:`2459` From 4917bd30f7a8ca1cd35eeddfab2a018c7102d5bf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 14:48:48 -0400 Subject: [PATCH 2029/2280] Add date to changelog --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 55b6f0c78..4e281a8df 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.5 (in development) ----------------------- +1.4.5 (June 20, 2017) +--------------------- Version 1.4.5 adds some oft-requested features. When you're importing files, you can now manually set fields on the new music. Date queries have gotten From 7e8056b0e8652a6235d8e2e054c0c41eae71bff0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 14:49:19 -0400 Subject: [PATCH 2030/2280] Version bump: 1.4.6 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index cab256032..ba2faec94 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.5' +__version__ = u'1.4.6' __author__ = u'Adrian Sampson ' diff --git a/docs/changelog.rst b/docs/changelog.rst index 4e281a8df..bd34271da 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.6 (in development) +---------------------- + +Changelog goes here! + + 1.4.5 (June 20, 2017) --------------------- diff --git a/docs/conf.py b/docs/conf.py index cd55e57a5..9bfab940a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.5' +release = '1.4.6' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 9fdbf63ca..06d35ae4a 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.5', + version='1.4.6', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From b575a1ef75b3b1204482ae4e143686598180c639 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 15:50:37 -0400 Subject: [PATCH 2031/2280] Always use specific null values for fixed fields This came out of an attempt to address the mysterious testing problems from PR #2563 and turned into a big old debacle. As it turns out, the problem came from calling Item.from_path and getting None for fields that weren't filled out by the MediaFile data. Everywhere else, we fill out these fixed attributes with the special null value for the field's type, so it's actually pretty confusing that these could mysteriously become None. I think it will be saner all around if we enforce this universally. There were two possible fixes: one in __getitem__ to check for missing values and one that set all the missing values in the constructor. I opted for the former because it has a smaller footprint, but the latter might have slightly better performance (depending on the ratio of constructions to lookups). --- beets/dbcore/db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index ef7231a76..a714d9492 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -236,7 +236,7 @@ class Model(object): if key in getters: # Computed. return getters[key](self) elif key in self._fields: # Fixed. - return self._values_fixed.get(key) + return self._values_fixed.get(key, self._type(key).null) elif key in self._values_flex: # Flexible. return self._values_flex[key] else: From 2a9be17cf689db03523207197ad3228164a983d2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 15:56:33 -0400 Subject: [PATCH 2032/2280] Fix some brittle query tests These were written to incidentally depend on Nones; the behavior they're actually testing doesn't really have anything to say about None-ness. --- test/test_dbcore.py | 2 +- test/test_query.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_dbcore.py b/test/test_dbcore.py index d070e257e..d2d97d4b3 100644 --- a/test/test_dbcore.py +++ b/test/test_dbcore.py @@ -320,7 +320,7 @@ class ModelTest(unittest.TestCase): def test_items(self): model = TestModel1(self.db) model.id = 5 - self.assertEqual({('id', 5), ('field_one', None)}, + self.assertEqual({('id', 5), ('field_one', 0)}, set(model.items())) def test_delete_internal_field(self): diff --git a/test/test_query.py b/test/test_query.py index 61df3ca10..c0ab2a171 100644 --- a/test/test_query.py +++ b/test/test_query.py @@ -79,10 +79,10 @@ class AnyFieldQueryTest(_common.LibTestCase): class AssertsMixin(object): def assert_items_matched(self, results, titles): - self.assertEqual([i.title for i in results], titles) + self.assertEqual(set([i.title for i in results]), set(titles)) def assert_albums_matched(self, results, albums): - self.assertEqual([a.album for a in results], albums) + self.assertEqual(set([a.album for a in results]), set(albums)) # A test case class providing a library with some dummy data and some From 41bd6f9a973d86d8c8339dfb9bd305e335e6fa2f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 16:04:25 -0400 Subject: [PATCH 2033/2280] Explicitly let artpath be missing We really want `Album.artpath` to be None sometimes, and this was relying on some accidental dbcore behavior before. Now, we explicitly mark the field as nullable: it may be a path, or it may be None to indicate that there is no art. --- beets/library.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/beets/library.py b/beets/library.py index 0a64516ad..748f532a5 100644 --- a/beets/library.py +++ b/beets/library.py @@ -144,10 +144,27 @@ class DateType(types.Float): class PathType(types.Type): + """A dbcore type for filesystem paths. These are represented as + `bytes` objects, in keeping with the Unix filesystem abstraction. + """ + sql = u'BLOB' query = PathQuery model_type = bytes + def __init__(self, nullable=False): + """Create a path type object. `nullable` controls whether the + type may be missing, i.e., None. + """ + self.nullable = nullable + + @property + def null(self): + if self.nullable: + return None + else: + return b'' + def format(self, value): return util.displayable_path(value) @@ -873,7 +890,7 @@ class Album(LibModel): _always_dirty = True _fields = { 'id': types.PRIMARY_ID, - 'artpath': PathType(), + 'artpath': PathType(True), 'added': DateType(), 'albumartist': types.STRING, From 8085d1318bcbbd867d951cc23866c35822559325 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 16:19:31 -0400 Subject: [PATCH 2034/2280] Fix ipfs test to sort items in order --- test/test_ipfs.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_ipfs.py b/test/test_ipfs.py index 9c523d6e5..d670bfc25 100644 --- a/test/test_ipfs.py +++ b/test/test_ipfs.py @@ -67,17 +67,17 @@ class IPFSPluginTest(unittest.TestCase, TestHelper): def mk_test_album(self): items = [_common.item() for _ in range(3)] items[0].title = 'foo bar' - items[0].artist = 'one' + items[0].artist = '1one' items[0].album = 'baz' items[0].year = 2001 items[0].comp = True items[1].title = 'baz qux' - items[1].artist = 'two' + items[1].artist = '2two' items[1].album = 'baz' items[1].year = 2002 items[1].comp = True items[2].title = 'beets 4 eva' - items[2].artist = 'three' + items[2].artist = '3three' items[2].album = 'foo' items[2].year = 2003 items[2].comp = False From 336fdba9edb39974dcde7be7c314c473c462e0ef Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Tue, 20 Jun 2017 16:31:00 -0400 Subject: [PATCH 2035/2280] Musical key field may be None Fixes a `modify` test, of all things. --- beets/library.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beets/library.py b/beets/library.py index 748f532a5..f294e6d4f 100644 --- a/beets/library.py +++ b/beets/library.py @@ -205,6 +205,8 @@ class MusicalKey(types.String): r'bb': 'a#', } + null = None + def parse(self, key): key = key.lower() for flat, sharp in self.ENHARMONIC.items(): From 6185c6ad4ba689ed438c2075699eb12b24ef5daf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 21 Jun 2017 10:28:43 -0400 Subject: [PATCH 2036/2280] Changelog for #2605 --- docs/changelog.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index bd34271da..e3aac2381 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,13 @@ Changelog Changelog goes here! +For developers: + +* Fixed fields in Album and Item objects are now more strict about translating + missing values into type-specific null-like values. This should help in + cases where a string field is unexpectedly `None` sometimes instead of just + showing up as an empty string. :bug:`2605` + 1.4.5 (June 20, 2017) --------------------- From 70a2ad354bfd39387fab8cd14337861c8acd7d47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= Date: Tue, 4 Jul 2017 15:53:02 +0200 Subject: [PATCH 2037/2280] fixes issue #2615 --- beetsplug/replaygain.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 69fa8d6c1..8b4172a5a 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -855,7 +855,7 @@ class ReplayGainPlugin(BeetsPlugin): # value. return self.overwrite or \ any([self.should_use_r128(item) and - (not item.r128_item_gain or not item.r128_album_gain) + (not item.r128_track_gain or not item.r128_album_gain) for item in album.items()]) or \ any([not self.should_use_r128(item) and (not item.rg_album_gain or not item.rg_album_peak) @@ -903,11 +903,11 @@ class ReplayGainPlugin(BeetsPlugin): self._log.info(u'analyzing {0}', album) - if (any([self.should_use_r128(item) for item in album.items()]) and + if (any([self.should_use_r128(item) for item in album.items()]) and not all(([self.should_use_r128(item) for item in album.items()]))): raise ReplayGainError( u"Mix of ReplayGain and EBU R128 detected" - u"for some tracks in album {0}".format(album) + u" for some tracks in album {0}".format(album) ) if any([self.should_use_r128(item) for item in album.items()]): From e742f8694c3057c1fea053aafdbc7455f6867995 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Thu, 6 Jul 2017 23:20:40 -0400 Subject: [PATCH 2038/2280] Changelog for #2623 (fixes #2615) --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e3aac2381..35785cc3c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,11 @@ Changelog Changelog goes here! +Fixes: + +* :doc:`/plugins/replaygain`: Fix a regression in the previous release related + to the new R128 tags. :bug:`2615` :bug:`2623` + For developers: * Fixed fields in Album and Item objects are now more strict about translating From c5502fb4d1ac4ba723e7c330d34b6030afcf0310 Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Wed, 12 Jul 2017 11:57:41 +0200 Subject: [PATCH 2039/2280] Do not warn about a BrokenPipeError we do consider For some reason Python always warns about a BrokenPipeError on stderr even if it is caught. Fixes #2622 --- beets/ui/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/ui/__init__.py b/beets/ui/__init__.py index 6ba80d22f..af2b79a19 100644 --- a/beets/ui/__init__.py +++ b/beets/ui/__init__.py @@ -1276,7 +1276,7 @@ def main(args=None): except IOError as exc: if exc.errno == errno.EPIPE: # "Broken pipe". End silently. - pass + sys.stderr.close() else: raise except KeyboardInterrupt: From 9f3e5b28b4d3cbacc5d9f08647ef20d3bbca5084 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Fri, 14 Jul 2017 15:31:17 -0400 Subject: [PATCH 2040/2280] output lyrics in HTML, allow skipping the idea here is to format the lyrics output a little better so that it can (for example) be shown as a web page or an ebook. the new skip option allows for faster generation of the output in the (most common) case where not all lyrics are available. --- beetsplug/lyrics.py | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 113bed104..f90159708 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -595,6 +595,7 @@ class LyricsPlugin(plugins.BeetsPlugin): "76V-uFL5jks5dNvcGCdarqFjDhP9c", 'fallback': None, 'force': False, + 'skip': False, 'sources': self.SOURCES, }) self.config['bing_client_secret'].redact = True @@ -663,18 +664,33 @@ class LyricsPlugin(plugins.BeetsPlugin): action='store_true', default=False, help=u'always re-download lyrics', ) + cmd.parser.add_option( + u'-s', u'--skip', dest='skip_fetched', + action='store_true', default=False, + help=u'skip already fetched lyrics', + ) def func(lib, opts, args): # The "write to files" option corresponds to the # import_write config value. write = ui.should_write() + artist = '' + album = '' for item in lib.items(ui.decargs(args)): - self.fetch_item_lyrics( - lib, item, write, - opts.force_refetch or self.config['force'], - ) + if not opts.skip_fetched and not self.config['skip']: + self.fetch_item_lyrics( + lib, item, write, + opts.force_refetch or self.config['force'], + ) if opts.printlyr and item.lyrics: - ui.print_(item.lyrics) + if artist != item.artist: + artist = item.artist + ui.print_('

' + artist + '

') + if album != item.album: + album = item.album + ui.print_('

' + artist + '

') + ui.print_('

' + item.title + '

') + ui.print_('
' + item.lyrics + '
') cmd.func = func return [cmd] From 0fbfa1feae1397affc388743d56c49879970f502 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Fri, 14 Jul 2017 17:34:51 -0400 Subject: [PATCH 2041/2280] render RST instead of HTML ReStructuredText has the advantage over HTML that it can be rendered easily to multiple formats (HTML, ePUB, PDF) and it supports indexes. the output needs to be fed into a file and integrated into an existing Sphinx document, of course. --- beetsplug/lyrics.py | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f90159708..3c0afab46 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -659,6 +659,11 @@ class LyricsPlugin(plugins.BeetsPlugin): action='store_true', default=False, help=u'print lyrics to console', ) + cmd.parser.add_option( + u'-r', u'--print-rst', dest='printrst', + action='store_true', default=False, + help=u'print lyrics to console as RST text', + ) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', action='store_true', default=False, @@ -682,15 +687,27 @@ class LyricsPlugin(plugins.BeetsPlugin): lib, item, write, opts.force_refetch or self.config['force'], ) - if opts.printlyr and item.lyrics: - if artist != item.artist: - artist = item.artist - ui.print_('

' + artist + '

') - if album != item.album: - album = item.album - ui.print_('

' + artist + '

') - ui.print_('

' + item.title + '

') - ui.print_('
' + item.lyrics + '
') + if item.lyrics: + if opts.printlyr: + ui.print_(item.lyrics) + if opts.printrst: + if artist != item.artist: + artist = item.artist + ui.print_(artist) + ui.print_(u'=' * len(artist)) + ui.print_() + if album != item.album: + album = item.album + ui.print_(album) + ui.print_(u'-' * len(album)) + ui.print_() + title_str = u':index:`' + item.title + u'`' + ui.print_(title_str) + ui.print_(u'~' * len(title_str)) + ui.print_() + # turn lyrics into a line block + ui.print_(u'| ' + item.lyrics.replace(u'\n', u'\n| ')) + ui.print_() cmd.func = func return [cmd] From 2fa46a750735f82350037ce21b48665f7b63fe71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Fri, 14 Jul 2017 17:43:37 -0400 Subject: [PATCH 2042/2280] add documentation for new lyrics flags --- docs/plugins/lyrics.rst | 49 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index d7c268c7e..454f16d57 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -84,10 +84,55 @@ lyrics will be added to the beets database and, if ``import.write`` is on, embedded into files' metadata. The ``-p`` option to the ``lyrics`` command makes it print lyrics out to the -console so you can view the fetched (or previously-stored) lyrics. +console so you can view the fetched (or previously-stored) lyrics. The +``-r`` option similarly shows all lyrics as an RST (ReStructuredText) +document. That document, in turn, can be parsed by tools like Sphinx +to generate HTML, ePUB or PDF formatted documents. Use, for example, +the following ``conf.py``:: + + # -*- coding: utf-8 -*- + master_doc = 'index' + project = u'Lyrics' + copyright = u'none' + author = u'Various Authors' + latex_documents = [ + (master_doc, 'Lyrics.tex', project, + author, 'manual'), + ] + epub_title = project + epub_author = author + epub_publisher = author + epub_copyright = copyright + epub_exclude_files = ['search.html'] + epub_tocdepth = 1 + epub_tocdup = False + +Then the output can be written to ``index.rst``. An alternative is to +use the following ``index.rst`` file, which will also generate an +index of song titles:: + + Lyrics + ====== + + * :ref:`Song index ` + * :ref:`search` + + Artist index: + + .. toctree:: + :maxdepth: 1 + + artists + +Then the correct format can be generated with one of:: + + sphinx-build -b epub3 . _build/epub + sphinx-build -b latex . _build/latex + sphinx-build -b html . _build/html The ``-f`` option forces the command to fetch lyrics, even for tracks that -already have lyrics. +already have lyrics. Inversely, the ``-s`` option skips lyrics that +are not locally available, to dump lyrics faster. .. _activate-google-custom-search: From 63aa3b316514062a53dec185f06c1c4201eb16cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 00:50:52 -0400 Subject: [PATCH 2043/2280] write to separate rst files this makes the ePUB easier to parse by e-readers, because they do not need to load one giant HTML file, but one per author. it also makes sphinx rendering more efficient and interactive --- beetsplug/lyrics.py | 58 +++++++++++++++++++++++++++++------------ docs/plugins/lyrics.rst | 5 ++-- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 3c0afab46..42ddef025 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -22,12 +22,15 @@ import difflib import itertools import json import struct +import os.path import re import requests import unicodedata +from unidecode import unidecode import warnings import six from six.moves import urllib +import sys try: from bs4 import SoupStrainer, BeautifulSoup @@ -660,9 +663,9 @@ class LyricsPlugin(plugins.BeetsPlugin): help=u'print lyrics to console', ) cmd.parser.add_option( - u'-r', u'--print-rst', dest='printrst', - action='store_true', default=False, - help=u'print lyrics to console as RST text', + u'-r', u'--write-rst', dest='writerst', + action='store', default='.', + help=u'write lyrics to given directory as RST files', ) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', @@ -679,8 +682,9 @@ class LyricsPlugin(plugins.BeetsPlugin): # The "write to files" option corresponds to the # import_write config value. write = ui.should_write() - artist = '' - album = '' + artist = u'Unknown artist' + album = False + output = sys.stdout for item in lib.items(ui.decargs(args)): if not opts.skip_fetched and not self.config['skip']: self.fetch_item_lyrics( @@ -690,24 +694,44 @@ class LyricsPlugin(plugins.BeetsPlugin): if item.lyrics: if opts.printlyr: ui.print_(item.lyrics) - if opts.printrst: + if opts.writerst: if artist != item.artist: artist = item.artist - ui.print_(artist) - ui.print_(u'=' * len(artist)) - ui.print_() + if output != sys.stdout: + output.close() + slug = re.sub(r'\W+', '-', + unidecode(artist).lower()) + path = os.path.join(opts.writerst, slug + u'.rst') + output = open(path, 'w') + output.write(artist.encode('utf-8')) + output.write(u'\n') + output.write(u'=' * len(artist)) + output.write(u'\n') + output.write(u''' +.. contents:: + :local: +''') + output.write(u'\n') if album != item.album: album = item.album - ui.print_(album) - ui.print_(u'-' * len(album)) - ui.print_() + output.write(album.encode('utf-8')) + output.write(u'\n') + output.write(u'-' * len(album)) + output.write(u'\n') + output.write(u'\n') title_str = u':index:`' + item.title + u'`' - ui.print_(title_str) - ui.print_(u'~' * len(title_str)) - ui.print_() + output.write(title_str.encode('utf-8')) + output.write(u'\n') + output.write(u'~' * len(title_str)) + output.write(u'\n') + output.write(u'\n') # turn lyrics into a line block - ui.print_(u'| ' + item.lyrics.replace(u'\n', u'\n| ')) - ui.print_() + block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') + output.write(block.encode('utf-8')) + output.write(u'\n') + output.write(u'\n') + if opts.writerst: + output.close() cmd.func = func return [cmd] diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 454f16d57..2fe7422f9 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -85,8 +85,9 @@ embedded into files' metadata. The ``-p`` option to the ``lyrics`` command makes it print lyrics out to the console so you can view the fetched (or previously-stored) lyrics. The -``-r`` option similarly shows all lyrics as an RST (ReStructuredText) -document. That document, in turn, can be parsed by tools like Sphinx +``-r directory`` option similarly shows all lyrics as an RST (ReStructuredText) +document structure located in ``directory`` (which defaults to the +current directory). That document, in turn, can be parsed by tools like Sphinx to generate HTML, ePUB or PDF formatted documents. Use, for example, the following ``conf.py``:: From 469c03a7bfc43957d5e4f768fbc363f06ec04240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 01:13:18 -0400 Subject: [PATCH 2044/2280] deal properly with empty album titles --- beetsplug/lyrics.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 42ddef025..17c226589 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -713,10 +713,12 @@ class LyricsPlugin(plugins.BeetsPlugin): ''') output.write(u'\n') if album != item.album: - album = item.album - output.write(album.encode('utf-8')) + tmpalbum = album = item.album + if album == '': + tmpalbum = 'Unknown album' + output.write(tmpalbum.encode('utf-8')) output.write(u'\n') - output.write(u'-' * len(album)) + output.write(u'-' * len(tmpalbum)) output.write(u'\n') output.write(u'\n') title_str = u':index:`' + item.title + u'`' From ac32ae574cb789aa17f2abf243946d7165b489b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 09:21:54 -0400 Subject: [PATCH 2045/2280] optimize: write only 3 times per file this makes the code more readable and reduces the number of syscalls to write files --- beetsplug/lyrics.py | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 17c226589..959506e99 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -703,35 +703,27 @@ class LyricsPlugin(plugins.BeetsPlugin): unidecode(artist).lower()) path = os.path.join(opts.writerst, slug + u'.rst') output = open(path, 'w') - output.write(artist.encode('utf-8')) - output.write(u'\n') - output.write(u'=' * len(artist)) - output.write(u'\n') - output.write(u''' + rst = u'''%s +%s + .. contents:: :local: -''') - output.write(u'\n') + +''' % (artist, u'=' * len(artist)) + output.write(rst.encode('utf-8')) if album != item.album: tmpalbum = album = item.album if album == '': - tmpalbum = 'Unknown album' - output.write(tmpalbum.encode('utf-8')) - output.write(u'\n') - output.write(u'-' * len(tmpalbum)) - output.write(u'\n') - output.write(u'\n') - title_str = u':index:`' + item.title + u'`' - output.write(title_str.encode('utf-8')) - output.write(u'\n') - output.write(u'~' * len(title_str)) - output.write(u'\n') - output.write(u'\n') - # turn lyrics into a line block + tmpalbum = u'Unknown album' + rst = u"%s\n%s\n\n" % (tmpalbum, + u'-' * len(tmpalbum)) + output.write(rst.encode('utf-8')) + title_str = u":index:`%s`" % item.title block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') - output.write(block.encode('utf-8')) - output.write(u'\n') - output.write(u'\n') + rst = u"%s\n%s\n\n%s\n" % (title_str, + u'~' * len(title_str), + block) + output.write(rst.encode('utf-8')) if opts.writerst: output.close() From 32de4148bc4509c37315a10046edc0cc36e10fd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 09:30:14 -0400 Subject: [PATCH 2046/2280] use glob patterns correctly in index --- docs/plugins/lyrics.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 2fe7422f9..f7f9c2189 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -122,8 +122,9 @@ index of song titles:: .. toctree:: :maxdepth: 1 + :glob: - artists + artists/* Then the correct format can be generated with one of:: From d330353e1c1d5cdc261b5ed2be286c7500bf087d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 14:19:25 -0400 Subject: [PATCH 2047/2280] rename the skip option to local skip was a misnomer: we actually skip "unfetched" lyrics. this means it's somewhat of a double-negative and really confusing. --local is clearer, although less in opposition with --force --- beetsplug/lyrics.py | 8 ++++---- docs/plugins/lyrics.rst | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 959506e99..38c0f73fb 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -598,7 +598,7 @@ class LyricsPlugin(plugins.BeetsPlugin): "76V-uFL5jks5dNvcGCdarqFjDhP9c", 'fallback': None, 'force': False, - 'skip': False, + 'local': False, 'sources': self.SOURCES, }) self.config['bing_client_secret'].redact = True @@ -673,9 +673,9 @@ class LyricsPlugin(plugins.BeetsPlugin): help=u'always re-download lyrics', ) cmd.parser.add_option( - u'-s', u'--skip', dest='skip_fetched', + u'-l', u'--local', dest='local_only', action='store_true', default=False, - help=u'skip already fetched lyrics', + help=u'do not fetch missing lyrics', ) def func(lib, opts, args): @@ -686,7 +686,7 @@ class LyricsPlugin(plugins.BeetsPlugin): album = False output = sys.stdout for item in lib.items(ui.decargs(args)): - if not opts.skip_fetched and not self.config['skip']: + if not opts.local_only and not self.config['local']: self.fetch_item_lyrics( lib, item, write, opts.force_refetch or self.config['force'], diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index f7f9c2189..5682ddbc0 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -133,8 +133,9 @@ Then the correct format can be generated with one of:: sphinx-build -b html . _build/html The ``-f`` option forces the command to fetch lyrics, even for tracks that -already have lyrics. Inversely, the ``-s`` option skips lyrics that -are not locally available, to dump lyrics faster. +already have lyrics. Inversely, the ``-l`` option restricts operations +to lyrics that are locally available, to show lyrics faster without +retrying them over the network all the time. .. _activate-google-custom-search: From 91de8aac84eb3058cf44d7e5b3f86970adc28a0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 14:46:26 -0400 Subject: [PATCH 2048/2280] move rst writer to a different function this simplifies and clarifies the code, although we need to call the writerst function twice to wrap up at the end of the loop --- beetsplug/lyrics.py | 78 ++++++++++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 33 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 38c0f73fb..f32e34bfd 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -19,6 +19,7 @@ from __future__ import absolute_import, division, print_function import difflib +import errno import itertools import json import struct @@ -30,7 +31,6 @@ from unidecode import unidecode import warnings import six from six.moves import urllib -import sys try: from bs4 import SoupStrainer, BeautifulSoup @@ -605,6 +605,14 @@ class LyricsPlugin(plugins.BeetsPlugin): self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True self.config['genius_api_key'].redact = True + # state information for the RST writer + # the current artist + self.artist = u'Unknown artist' + # the current album, False means no album yet + self.album = False + # the current rst file content. None means the file is not + # open yet. + self.rst = None available_sources = list(self.SOURCES) sources = plugins.sanitize_choices( @@ -682,9 +690,6 @@ class LyricsPlugin(plugins.BeetsPlugin): # The "write to files" option corresponds to the # import_write config value. write = ui.should_write() - artist = u'Unknown artist' - album = False - output = sys.stdout for item in lib.items(ui.decargs(args)): if not opts.local_only and not self.config['local']: self.fetch_item_lyrics( @@ -695,40 +700,47 @@ class LyricsPlugin(plugins.BeetsPlugin): if opts.printlyr: ui.print_(item.lyrics) if opts.writerst: - if artist != item.artist: - artist = item.artist - if output != sys.stdout: - output.close() - slug = re.sub(r'\W+', '-', - unidecode(artist).lower()) - path = os.path.join(opts.writerst, slug + u'.rst') - output = open(path, 'w') - rst = u'''%s + self.writerst(opts.writerst, item) + if opts.writerst: + # flush last artist + self.writerst(opts.writerst, None) + cmd.func = func + return [cmd] + + def writerst(self, directory, item): + """Write the item to an RST file + + this will keep state (in the `rst` variable) in order to avoid + writing continuously to the same files + """ + if item is None or self.artist != item.artist: + if self.rst is not None: + slug = re.sub(r'\W+', '-', unidecode(self.artist).lower()) + path = os.path.join(directory, 'artists', slug + u'.rst') + with open(path, 'w') as output: + output.write(self.rst.encode('utf-8')) + self.rst = None + if item is None: + return + self.artist = item.artist + self.rst = u'''%s %s .. contents:: :local: -''' % (artist, u'=' * len(artist)) - output.write(rst.encode('utf-8')) - if album != item.album: - tmpalbum = album = item.album - if album == '': - tmpalbum = u'Unknown album' - rst = u"%s\n%s\n\n" % (tmpalbum, - u'-' * len(tmpalbum)) - output.write(rst.encode('utf-8')) - title_str = u":index:`%s`" % item.title - block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') - rst = u"%s\n%s\n\n%s\n" % (title_str, - u'~' * len(title_str), - block) - output.write(rst.encode('utf-8')) - if opts.writerst: - output.close() - - cmd.func = func - return [cmd] +''' % (self.artist, u'=' * len(self.artist)) + if self.album != item.album: + tmpalbum = self.album = item.album + if self.album == '': + tmpalbum = u'Unknown album' + self.rst += u"%s\n%s\n\n" % (tmpalbum, + u'-' * len(tmpalbum)) + title_str = u":index:`%s`" % item.title + block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') + self.rst += u"%s\n%s\n\n%s\n" % (title_str, + u'~' * len(title_str), + block) def imported(self, session, task): """Import hook for fetching lyrics automatically. From e6adb5e7da94fa3ff3175c2a00fbf6bbe67153ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 14:47:36 -0400 Subject: [PATCH 2049/2280] cosmetic: do not use needless heredoc --- beetsplug/lyrics.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f32e34bfd..a1af67363 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -723,13 +723,8 @@ class LyricsPlugin(plugins.BeetsPlugin): if item is None: return self.artist = item.artist - self.rst = u'''%s -%s - -.. contents:: - :local: - -''' % (self.artist, u'=' * len(self.artist)) + self.rst = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ + % (self.artist, u'=' * len(self.artist)) if self.album != item.album: tmpalbum = self.album = item.album if self.album == '': From f6674287589c489417a0bc99306b12f735cab89c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 15:43:13 -0400 Subject: [PATCH 2050/2280] write sphinx base files we write the artists files in a subdirectory, to avoid infinite recursions or flooding the current directory needlessly. this way, the user has a good base structure and can just chain the command into sphinx to continue building the next format, after possible tweaks. --- beetsplug/lyrics.py | 60 +++++++++++++++++++++++++++++++++ docs/plugins/lyrics.rst | 75 +++++++++++++++-------------------------- 2 files changed, 88 insertions(+), 47 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index a1af67363..29bab25a6 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -690,6 +690,8 @@ class LyricsPlugin(plugins.BeetsPlugin): # The "write to files" option corresponds to the # import_write config value. write = ui.should_write() + if opts.writerst: + self.writerst_indexes(opts.writerst) for item in lib.items(ui.decargs(args)): if not opts.local_only and not self.config['local']: self.fetch_item_lyrics( @@ -704,6 +706,13 @@ class LyricsPlugin(plugins.BeetsPlugin): if opts.writerst: # flush last artist self.writerst(opts.writerst, None) + ui.print_(u'RST files generated. to build, use one of:') + ui.print_(u' sphinx-build -b html %s _build/html' + % opts.writerst) + ui.print_(u' sphinx-build -b epub %s _build/epub' + % opts.writerst) + ui.print_(u' sphinx-build -b latex %s _build/latex && make -C _build/latex all-pdf' + % opts.writerst) cmd.func = func return [cmd] @@ -737,6 +746,57 @@ class LyricsPlugin(plugins.BeetsPlugin): u'~' * len(title_str), block) + def writerst_indexes(self, directory): + """Write conf.py and index.rst files necessary for Sphinx + + We write minimal configurations that are necessary for Sphinx + to operate. We do not overwrite existing files so that + customizations are respected.""" + try: + os.makedirs(os.path.join(directory, 'artists')) + except OSError as e: + if e.errno == errno.EEXIST: + pass + else: + raise + indexfile = os.path.join(directory, 'index.rst') + if not os.path.exists(indexfile): + with open(indexfile, 'w') as output: + output.write(u'''Lyrics +====== + +* :ref:`Song index ` +* :ref:`search` + +Artist index: + +.. toctree:: + :maxdepth: 1 + :glob: + + artists/* +''') + conffile = os.path.join(directory, 'conf.py') + if not os.path.exists(conffile): + with open(conffile, 'w') as output: + output.write(u'''# -*- coding: utf-8 -*- +master_doc = 'index' +project = u'Lyrics' +copyright = u'none' +author = u'Various Authors' +latex_documents = [ + (master_doc, 'Lyrics.tex', project, + author, 'manual'), +] +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright +epub_exclude_files = ['search.html'] +epub_tocdepth = 1 +epub_tocdup = False +''') + def imported(self, session, task): """Import hook for fetching lyrics automatically. """ diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 5682ddbc0..0c6d68546 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -84,59 +84,40 @@ lyrics will be added to the beets database and, if ``import.write`` is on, embedded into files' metadata. The ``-p`` option to the ``lyrics`` command makes it print lyrics out to the -console so you can view the fetched (or previously-stored) lyrics. The -``-r directory`` option similarly shows all lyrics as an RST (ReStructuredText) -document structure located in ``directory`` (which defaults to the -current directory). That document, in turn, can be parsed by tools like Sphinx -to generate HTML, ePUB or PDF formatted documents. Use, for example, -the following ``conf.py``:: - - # -*- coding: utf-8 -*- - master_doc = 'index' - project = u'Lyrics' - copyright = u'none' - author = u'Various Authors' - latex_documents = [ - (master_doc, 'Lyrics.tex', project, - author, 'manual'), - ] - epub_title = project - epub_author = author - epub_publisher = author - epub_copyright = copyright - epub_exclude_files = ['search.html'] - epub_tocdepth = 1 - epub_tocdup = False - -Then the output can be written to ``index.rst``. An alternative is to -use the following ``index.rst`` file, which will also generate an -index of song titles:: - - Lyrics - ====== - - * :ref:`Song index ` - * :ref:`search` - - Artist index: - - .. toctree:: - :maxdepth: 1 - :glob: - - artists/* - -Then the correct format can be generated with one of:: - - sphinx-build -b epub3 . _build/epub - sphinx-build -b latex . _build/latex - sphinx-build -b html . _build/html +console so you can view the fetched (or previously-stored) lyrics. The ``-f`` option forces the command to fetch lyrics, even for tracks that already have lyrics. Inversely, the ``-l`` option restricts operations to lyrics that are locally available, to show lyrics faster without retrying them over the network all the time. +Rendering lyrics into other formats +----------------------------------- + +The ``-r directory`` option similarly renders all lyrics as an RST +(ReStructuredText) document structure located in ``directory`` (which +defaults to the current directory). That directory, in turn, can be +parsed by tools like Sphinx to generate HTML, ePUB or PDF formatted +documents. A minimal ``conf.py`` and ``index.rst`` files are created +the first time the command is ran, to provide templates that can be +modified. They are not overwritten on subsequent runs. + +Sphinx supports various `builders +`_, but here are a +few suggestions. + + * build a HTML version:: + + sphinx-build -b html . _build/html + + * build an ePUB3 formatted file, usable on ebook-readers:: + + sphinx-build -b epub3 . _build/epub + + * build a PDF file, which incidentally also builds a LaTeX file:: + + sphinx-build -b latex %s _build/latex && make -C _build/latex all-pdf + .. _activate-google-custom-search: Activate Google custom search From 0bcd16f1ab04cd77319ad5f2eb1f44308f674cd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 16:21:41 -0400 Subject: [PATCH 2051/2280] deal with encoding issues in python3 when we encode explicitly, we return bytes, so open files as binary --- beetsplug/lyrics.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 29bab25a6..c36839b29 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -726,7 +726,7 @@ class LyricsPlugin(plugins.BeetsPlugin): if self.rst is not None: slug = re.sub(r'\W+', '-', unidecode(self.artist).lower()) path = os.path.join(directory, 'artists', slug + u'.rst') - with open(path, 'w') as output: + with open(path, 'wb') as output: output.write(self.rst.encode('utf-8')) self.rst = None if item is None: @@ -761,7 +761,7 @@ class LyricsPlugin(plugins.BeetsPlugin): raise indexfile = os.path.join(directory, 'index.rst') if not os.path.exists(indexfile): - with open(indexfile, 'w') as output: + with open(indexfile, 'wb') as output: output.write(u'''Lyrics ====== @@ -778,7 +778,7 @@ Artist index: ''') conffile = os.path.join(directory, 'conf.py') if not os.path.exists(conffile): - with open(conffile, 'w') as output: + with open(conffile, 'wb') as output: output.write(u'''# -*- coding: utf-8 -*- master_doc = 'index' project = u'Lyrics' From 5d8c15980ef5fa854ab17dba5ab83489d640bead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Sat, 15 Jul 2017 16:24:07 -0400 Subject: [PATCH 2052/2280] fix flake8 warning --- beetsplug/lyrics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index c36839b29..73e7e11b1 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -711,7 +711,8 @@ class LyricsPlugin(plugins.BeetsPlugin): % opts.writerst) ui.print_(u' sphinx-build -b epub %s _build/epub' % opts.writerst) - ui.print_(u' sphinx-build -b latex %s _build/latex && make -C _build/latex all-pdf' + ui.print_((u' sphinx-build -b latex %s _build/latex ' + u'&& make -C _build/latex all-pdf') % opts.writerst) cmd.func = func return [cmd] From c655a13c4103308dea3ae936198c21ddb733d502 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Jul 2017 10:02:14 -0400 Subject: [PATCH 2053/2280] Use title case in docs --- docs/plugins/lyrics.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 0c6d68546..872c95b5c 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -91,7 +91,7 @@ already have lyrics. Inversely, the ``-l`` option restricts operations to lyrics that are locally available, to show lyrics faster without retrying them over the network all the time. -Rendering lyrics into other formats +Rendering Lyrics into Other Formats ----------------------------------- The ``-r directory`` option similarly renders all lyrics as an RST @@ -120,7 +120,7 @@ few suggestions. .. _activate-google-custom-search: -Activate Google custom search +Activate Google Custom Search ------------------------------ Using the Google backend requires `BeautifulSoup`_, which you can install From d44eda56c50d1cbe6ad70406717ab3c44e4e80d0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Jul 2017 10:07:32 -0400 Subject: [PATCH 2054/2280] Docs refinements for lyrics ReST output --- docs/plugins/lyrics.rst | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 872c95b5c..85e3021f9 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -88,33 +88,37 @@ console so you can view the fetched (or previously-stored) lyrics. The ``-f`` option forces the command to fetch lyrics, even for tracks that already have lyrics. Inversely, the ``-l`` option restricts operations -to lyrics that are locally available, to show lyrics faster without -retrying them over the network all the time. +to lyrics that are locally available, which show lyrics faster without using +the network at all. Rendering Lyrics into Other Formats ----------------------------------- -The ``-r directory`` option similarly renders all lyrics as an RST -(ReStructuredText) document structure located in ``directory`` (which -defaults to the current directory). That directory, in turn, can be -parsed by tools like Sphinx to generate HTML, ePUB or PDF formatted -documents. A minimal ``conf.py`` and ``index.rst`` files are created -the first time the command is ran, to provide templates that can be -modified. They are not overwritten on subsequent runs. +The ``-r directory`` option renders all lyrics as `reStructuredText`_ (ReST) +documents in ``directory`` (by default, the current directory). That +directory, in turn, can be parsed by tools like `Sphinx`_ to generate HTML, +ePUB, or PDF documents. + +A minimal ``conf.py`` and ``index.rst`` files are created the first time the +command is run. They are not overwritten on subsequent runs, so you can safely +modify these files to customize the output. + +.. _Sphinx: http://www.sphinx-doc.org/ +.. _reStructuredText: http://docutils.sourceforge.net/rst.html Sphinx supports various `builders `_, but here are a few suggestions. - * build a HTML version:: + * Build an HTML version:: sphinx-build -b html . _build/html - * build an ePUB3 formatted file, usable on ebook-readers:: + * Build an ePUB3 formatted file, usable on ebook readers:: - sphinx-build -b epub3 . _build/epub + sphinx-build -b epub3 . _build/epub - * build a PDF file, which incidentally also builds a LaTeX file:: + * Build a PDF file, which incidentally also builds a LaTeX file:: sphinx-build -b latex %s _build/latex && make -C _build/latex all-pdf From 813cf97686bcaebce2ee5c68f99681713cd039c9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Jul 2017 10:10:41 -0400 Subject: [PATCH 2055/2280] Better metavariable for lyrics --help output --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 73e7e11b1..7fb13150b 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -672,7 +672,7 @@ class LyricsPlugin(plugins.BeetsPlugin): ) cmd.parser.add_option( u'-r', u'--write-rst', dest='writerst', - action='store', default='.', + action='store', default='.', metavar='directory', help=u'write lyrics to given directory as RST files', ) cmd.parser.add_option( From 9de94378b91fb619206ab5356ea080965233ba6b Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Jul 2017 10:14:49 -0400 Subject: [PATCH 2056/2280] An even shorter metavariable --- beetsplug/lyrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7fb13150b..841847c8c 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -672,7 +672,7 @@ class LyricsPlugin(plugins.BeetsPlugin): ) cmd.parser.add_option( u'-r', u'--write-rst', dest='writerst', - action='store', default='.', metavar='directory', + action='store', default='.', metavar='dir', help=u'write lyrics to given directory as RST files', ) cmd.parser.add_option( From cf75b1548e48f91cabceadd7c3faa8eab589e30f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 16 Jul 2017 10:15:45 -0400 Subject: [PATCH 2057/2280] Changelog entry for #2628 --- docs/changelog.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 35785cc3c..e30080f49 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,11 @@ Changelog 1.4.6 (in development) ---------------------- -Changelog goes here! +New features: + +* :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files + for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. + :bug:`2628` Fixes: From 8da5c0f8717c334434845e7c06779aff8341c11c Mon Sep 17 00:00:00 2001 From: "nathdwek@laptop" Date: Mon, 17 Jul 2017 12:14:12 +0200 Subject: [PATCH 2058/2280] Changelog for #2623 --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 35785cc3c..281f6a32e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,11 @@ Changelog goes here! Fixes: +* Prevent Python from warning about a ``BrokenPipeError`` being ignored even + though we do take it into account. This was an issue when using beets in + simple shell scripts. + Thanks to :user:`Azphreal`. + :bug:`2622` :bug:`2631` * :doc:`/plugins/replaygain`: Fix a regression in the previous release related to the new R128 tags. :bug:`2615` :bug:`2623` From 7e0a48a46d7fe7b3d920db3f7e52cd9ca4978ea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 08:49:40 -0400 Subject: [PATCH 2059/2280] s/rest/rest/ --- beetsplug/lyrics.py | 60 ++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 841847c8c..9dba98a39 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -605,14 +605,14 @@ class LyricsPlugin(plugins.BeetsPlugin): self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True self.config['genius_api_key'].redact = True - # state information for the RST writer + # state information for the ReST writer # the current artist self.artist = u'Unknown artist' # the current album, False means no album yet self.album = False - # the current rst file content. None means the file is not + # the current rest file content. None means the file is not # open yet. - self.rst = None + self.rest = None available_sources = list(self.SOURCES) sources = plugins.sanitize_choices( @@ -671,9 +671,9 @@ class LyricsPlugin(plugins.BeetsPlugin): help=u'print lyrics to console', ) cmd.parser.add_option( - u'-r', u'--write-rst', dest='writerst', + u'-r', u'--write-rest', dest='writerest', action='store', default='.', metavar='dir', - help=u'write lyrics to given directory as RST files', + help=u'write lyrics to given directory as ReST files', ) cmd.parser.add_option( u'-f', u'--force', dest='force_refetch', @@ -690,8 +690,8 @@ class LyricsPlugin(plugins.BeetsPlugin): # The "write to files" option corresponds to the # import_write config value. write = ui.should_write() - if opts.writerst: - self.writerst_indexes(opts.writerst) + if opts.writerest: + self.writerest_indexes(opts.writerest) for item in lib.items(ui.decargs(args)): if not opts.local_only and not self.config['local']: self.fetch_item_lyrics( @@ -701,53 +701,53 @@ class LyricsPlugin(plugins.BeetsPlugin): if item.lyrics: if opts.printlyr: ui.print_(item.lyrics) - if opts.writerst: - self.writerst(opts.writerst, item) - if opts.writerst: + if opts.writerest: + self.writerest(opts.writerest, item) + if opts.writerest: # flush last artist - self.writerst(opts.writerst, None) - ui.print_(u'RST files generated. to build, use one of:') + self.writerest(opts.writerest, None) + ui.print_(u'ReST files generated. to build, use one of:') ui.print_(u' sphinx-build -b html %s _build/html' - % opts.writerst) + % opts.writerest) ui.print_(u' sphinx-build -b epub %s _build/epub' - % opts.writerst) + % opts.writerest) ui.print_((u' sphinx-build -b latex %s _build/latex ' u'&& make -C _build/latex all-pdf') - % opts.writerst) + % opts.writerest) cmd.func = func return [cmd] - def writerst(self, directory, item): - """Write the item to an RST file + def writerest(self, directory, item): + """Write the item to an ReST file - this will keep state (in the `rst` variable) in order to avoid - writing continuously to the same files + This will keep state (in the `rest` variable) in order to avoid + writing continuously to the same files. """ if item is None or self.artist != item.artist: - if self.rst is not None: + if self.rest is not None: slug = re.sub(r'\W+', '-', unidecode(self.artist).lower()) path = os.path.join(directory, 'artists', slug + u'.rst') with open(path, 'wb') as output: - output.write(self.rst.encode('utf-8')) - self.rst = None + output.write(self.rest.encode('utf-8')) + self.rest = None if item is None: return self.artist = item.artist - self.rst = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ - % (self.artist, u'=' * len(self.artist)) + self.rest = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ + % (self.artist, u'=' * len(self.artist)) if self.album != item.album: tmpalbum = self.album = item.album if self.album == '': tmpalbum = u'Unknown album' - self.rst += u"%s\n%s\n\n" % (tmpalbum, - u'-' * len(tmpalbum)) + self.rest += u"%s\n%s\n\n" % (tmpalbum, + u'-' * len(tmpalbum)) title_str = u":index:`%s`" % item.title block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') - self.rst += u"%s\n%s\n\n%s\n" % (title_str, - u'~' * len(title_str), - block) + self.rest += u"%s\n%s\n\n%s\n" % (title_str, + u'~' * len(title_str), + block) - def writerst_indexes(self, directory): + def writerest_indexes(self, directory): """Write conf.py and index.rst files necessary for Sphinx We write minimal configurations that are necessary for Sphinx From 6d58110bd2e46b32f36ddbcd588ef137f8915274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 08:50:19 -0400 Subject: [PATCH 2060/2280] move heredocs to top-level globals --- beetsplug/lyrics.py | 68 ++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 31 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 9dba98a39..07e865c91 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -77,6 +77,41 @@ URL_CHARACTERS = { } USER_AGENT = 'beets/{}'.format(beets.__version__) +# the content for the base index.rst generated +REST_INDEX_TEMPLATE = u'''Lyrics +====== + +* :ref:`Song index ` +* :ref:`search` + +Artist index: + +.. toctree:: + :maxdepth: 1 + :glob: + + artists/* +''' + +# the content for the base conf.py generated +REST_CONF_TEMPLATE = u'''# -*- coding: utf-8 -*- +master_doc = 'index' +project = u'Lyrics' +copyright = u'none' +author = u'Various Authors' +latex_documents = [ + (master_doc, 'Lyrics.tex', project, + author, 'manual'), +] +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright +epub_exclude_files = ['search.html'] +epub_tocdepth = 1 +epub_tocdup = False +''' + # Utilities. @@ -763,40 +798,11 @@ class LyricsPlugin(plugins.BeetsPlugin): indexfile = os.path.join(directory, 'index.rst') if not os.path.exists(indexfile): with open(indexfile, 'wb') as output: - output.write(u'''Lyrics -====== - -* :ref:`Song index ` -* :ref:`search` - -Artist index: - -.. toctree:: - :maxdepth: 1 - :glob: - - artists/* -''') + output.write(REST_INDEX_TEMPLATE) conffile = os.path.join(directory, 'conf.py') if not os.path.exists(conffile): with open(conffile, 'wb') as output: - output.write(u'''# -*- coding: utf-8 -*- -master_doc = 'index' -project = u'Lyrics' -copyright = u'none' -author = u'Various Authors' -latex_documents = [ - (master_doc, 'Lyrics.tex', project, - author, 'manual'), -] -epub_title = project -epub_author = author -epub_publisher = author -epub_copyright = copyright -epub_exclude_files = ['search.html'] -epub_tocdepth = 1 -epub_tocdup = False -''') + output.write(REST_CONF_TEMPLATE) def imported(self, session, task): """Import hook for fetching lyrics automatically. From b6e42ee2e886da109cbc1262e8558ab61966082b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 08:55:07 -0400 Subject: [PATCH 2061/2280] fix another unicode error the unicode strings are not binary - rely on Python to do the right thing here instead of encoding a string we know is already properly encoded --- beetsplug/lyrics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 07e865c91..e19014d11 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -797,11 +797,11 @@ class LyricsPlugin(plugins.BeetsPlugin): raise indexfile = os.path.join(directory, 'index.rst') if not os.path.exists(indexfile): - with open(indexfile, 'wb') as output: + with open(indexfile, 'w') as output: output.write(REST_INDEX_TEMPLATE) conffile = os.path.join(directory, 'conf.py') if not os.path.exists(conffile): - with open(conffile, 'wb') as output: + with open(conffile, 'w') as output: output.write(REST_CONF_TEMPLATE) def imported(self, session, task): From 93966ed4ee134cc7f727636ea4e5203e230b1e38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 09:00:22 -0400 Subject: [PATCH 2062/2280] strip whitespace in titles this would cause problems with songs that had trailing spaces with the index directive --- beetsplug/lyrics.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index e19014d11..7c81d3a81 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -760,7 +760,8 @@ class LyricsPlugin(plugins.BeetsPlugin): """ if item is None or self.artist != item.artist: if self.rest is not None: - slug = re.sub(r'\W+', '-', unidecode(self.artist).lower()) + slug = re.sub(r'\W+', '-', + unidecode(self.artist.strip()).lower()) path = os.path.join(directory, 'artists', slug + u'.rst') with open(path, 'wb') as output: output.write(self.rest.encode('utf-8')) @@ -769,14 +770,15 @@ class LyricsPlugin(plugins.BeetsPlugin): return self.artist = item.artist self.rest = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ - % (self.artist, u'=' * len(self.artist)) + % (self.artist.strip(), + u'=' * len(self.artist.strip())) if self.album != item.album: tmpalbum = self.album = item.album if self.album == '': tmpalbum = u'Unknown album' - self.rest += u"%s\n%s\n\n" % (tmpalbum, - u'-' * len(tmpalbum)) - title_str = u":index:`%s`" % item.title + self.rest += u"%s\n%s\n\n" % (tmpalbum.strip(), + u'-' * len(tmpalbum.strip())) + title_str = u":index:`%s`" % item.title.strip() block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') self.rest += u"%s\n%s\n\n%s\n" % (title_str, u'~' * len(title_str), From b303d5beb082bff851759bbe79c3ab5337e4cfa4 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 17 Jul 2017 10:59:04 -0400 Subject: [PATCH 2063/2280] Slightly more complete sentences in comments --- beetsplug/lyrics.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7c81d3a81..57265a469 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -77,7 +77,7 @@ URL_CHARACTERS = { } USER_AGENT = 'beets/{}'.format(beets.__version__) -# the content for the base index.rst generated +# The content for the base index.rst generated in ReST mode. REST_INDEX_TEMPLATE = u'''Lyrics ====== @@ -93,7 +93,7 @@ Artist index: artists/* ''' -# the content for the base conf.py generated +# The content for the base conf.py generated. REST_CONF_TEMPLATE = u'''# -*- coding: utf-8 -*- master_doc = 'index' project = u'Lyrics' @@ -640,12 +640,13 @@ class LyricsPlugin(plugins.BeetsPlugin): self.config['google_API_key'].redact = True self.config['google_engine_ID'].redact = True self.config['genius_api_key'].redact = True - # state information for the ReST writer - # the current artist + + # State information for the ReST writer. + # First, the current artist we're writing. self.artist = u'Unknown artist' - # the current album, False means no album yet + # The current album: False means no album yet. self.album = False - # the current rest file content. None means the file is not + # The current rest file content. None means the file is not # open yet. self.rest = None From 36f84bfedd137f16ce6263f6b57c9f89e70be7b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 11:44:06 -0400 Subject: [PATCH 2064/2280] add missing trailing newline after lyrics block this would yield a warning for every song --- beetsplug/lyrics.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 57265a469..f2a59c5b5 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -781,9 +781,9 @@ class LyricsPlugin(plugins.BeetsPlugin): u'-' * len(tmpalbum.strip())) title_str = u":index:`%s`" % item.title.strip() block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') - self.rest += u"%s\n%s\n\n%s\n" % (title_str, - u'~' * len(title_str), - block) + self.rest += u"%s\n%s\n\n%s\n\n" % (title_str, + u'~' * len(title_str), + block) def writerest_indexes(self, directory): """Write conf.py and index.rst files necessary for Sphinx From 9894e8752ba375a8f1734099e85dde48536222f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 11:49:35 -0400 Subject: [PATCH 2065/2280] ignore trailing/leading whitespace when comparing artists --- beetsplug/lyrics.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index f2a59c5b5..acd1ab99d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -759,7 +759,7 @@ class LyricsPlugin(plugins.BeetsPlugin): This will keep state (in the `rest` variable) in order to avoid writing continuously to the same files. """ - if item is None or self.artist != item.artist: + if item is None or self.artist != item.artist.strip(): if self.rest is not None: slug = re.sub(r'\W+', '-', unidecode(self.artist.strip()).lower()) @@ -769,10 +769,10 @@ class LyricsPlugin(plugins.BeetsPlugin): self.rest = None if item is None: return - self.artist = item.artist + self.artist = item.artist.strip() self.rest = u"%s\n%s\n\n.. contents::\n :local:\n\n" \ - % (self.artist.strip(), - u'=' * len(self.artist.strip())) + % (self.artist, + u'=' * len(self.artist)) if self.album != item.album: tmpalbum = self.album = item.album if self.album == '': From 9c36a41ea8630bc0e1339c8b41b3877b125c95f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 11:50:15 -0400 Subject: [PATCH 2066/2280] slight refactoring: strip album only once --- beetsplug/lyrics.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index acd1ab99d..1d6d31814 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -774,11 +774,10 @@ class LyricsPlugin(plugins.BeetsPlugin): % (self.artist, u'=' * len(self.artist)) if self.album != item.album: - tmpalbum = self.album = item.album + tmpalbum = self.album = item.album.strip() if self.album == '': tmpalbum = u'Unknown album' - self.rest += u"%s\n%s\n\n" % (tmpalbum.strip(), - u'-' * len(tmpalbum.strip())) + self.rest += u"%s\n%s\n\n" % (tmpalbum, u'-' * len(tmpalbum)) title_str = u":index:`%s`" % item.title.strip() block = u'| ' + item.lyrics.replace(u'\n', u'\n| ') self.rest += u"%s\n%s\n\n%s\n\n" % (title_str, From 458f3636f4ef4fdb9627359c504aab9b35b93515 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 11:59:12 -0400 Subject: [PATCH 2067/2280] compare artists based on the slug this is necessary because otherwise artists with different string representations but the same slug would overwrite one another this outlines more clearly the code duplication between the rst code and the slugify function, something which can be fixed later. --- beetsplug/lyrics.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 1d6d31814..27b05f542 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -759,11 +759,22 @@ class LyricsPlugin(plugins.BeetsPlugin): This will keep state (in the `rest` variable) in order to avoid writing continuously to the same files. """ - if item is None or self.artist != item.artist.strip(): + def slug(text): + """Make a URL-safe, human-readable version of the given text + + This will do the following: + + 1. decode unicode characters into ASCII + 2. shift everything to lowercase + 3. strip whitespace + 4. replace other non-word characters with dashes + """ + return re.sub(r'\W+', '-', unidecode(text).lower().strip()) + + if item is None or slug(self.artist) != slug(item.artist): if self.rest is not None: - slug = re.sub(r'\W+', '-', - unidecode(self.artist.strip()).lower()) - path = os.path.join(directory, 'artists', slug + u'.rst') + path = os.path.join(directory, 'artists', + slug(self.artist) + u'.rst') with open(path, 'wb') as output: output.write(self.rest.encode('utf-8')) self.rest = None From 5e8d17a4fcd735075d526ffd07e4d47677908285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Mon, 17 Jul 2017 12:21:55 -0400 Subject: [PATCH 2068/2280] lyrics: detect MusixMatch blocking we just look for the bad string in the HTML. this has the downside that we may consider songs that have those exact lyrics (you never know, really) may trigger this warning as well and we would fail to fetch those songs. we also fail if lyrics contain another magic string that seems to come up when you do fill in the CAPTCHA after being blocked. --- beetsplug/lyrics.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 57265a469..cc8de9f1d 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -301,9 +301,19 @@ class MusiXmatch(SymbolsReplaced): html = self.fetch_url(url) if not html: return + if "We detected that your IP is blocked" in html: + self._log.warning(u'we are blocked at MusixMatch: url %s failed' + % url) + return html_part = html.split('

Date: Tue, 18 Jul 2017 16:12:39 -0400 Subject: [PATCH 2069/2280] move slug utility function to top-level it's a generic utility function that can be reused, there's nothing class-specific about it. --- beetsplug/lyrics.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 27b05f542..95c3d6ad6 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -227,6 +227,19 @@ def search_pairs(item): return itertools.product(artists, multi_titles) +def slug(text): + """Make a URL-safe, human-readable version of the given text + + This will do the following: + + 1. decode unicode characters into ASCII + 2. shift everything to lowercase + 3. strip whitespace + 4. replace other non-word characters with dashes + """ + return re.sub(r'\W+', '-', unidecode(text).lower().strip()) + + class Backend(object): def __init__(self, config, log): self._log = log @@ -759,17 +772,6 @@ class LyricsPlugin(plugins.BeetsPlugin): This will keep state (in the `rest` variable) in order to avoid writing continuously to the same files. """ - def slug(text): - """Make a URL-safe, human-readable version of the given text - - This will do the following: - - 1. decode unicode characters into ASCII - 2. shift everything to lowercase - 3. strip whitespace - 4. replace other non-word characters with dashes - """ - return re.sub(r'\W+', '-', unidecode(text).lower().strip()) if item is None or slug(self.artist) != slug(item.artist): if self.rest is not None: From b4b547309332451c18accec3e69164d261ff3a33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Tue, 18 Jul 2017 16:14:10 -0400 Subject: [PATCH 2070/2280] add pointer to slugify in slug --- beetsplug/lyrics.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 95c3d6ad6..84f1bf6c0 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -236,6 +236,10 @@ def slug(text): 2. shift everything to lowercase 3. strip whitespace 4. replace other non-word characters with dashes + + This somewhat duplicates the :func:`Google.slugify` function but + slugify is not as generic as this one, which can be reused + elsewhere. """ return re.sub(r'\W+', '-', unidecode(text).lower().strip()) From 914dba4152ec689851e3f7c80b84348adebd0cc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Tue, 18 Jul 2017 16:32:47 -0400 Subject: [PATCH 2071/2280] add tests for slug function, failing --- test/test_lyrics.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/test_lyrics.py b/test/test_lyrics.py index e811da8d7..398314ba6 100644 --- a/test/test_lyrics.py +++ b/test/test_lyrics.py @@ -393,6 +393,26 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest): google.is_page_candidate(url, url_title, s['title'], u'Sunn O)))') +class SlugTests(unittest.TestCase): + + def test_slug(self): + # plain ascii passthrough + text = u"test" + self.assertEqual(lyrics.slug(text), 'test') + # german unicode and capitals + text = u"Mørdag" + self.assertEqual(lyrics.slug(text), 'mordag') + # more accents and quotes + text = u"l'été c'est fait pour jouer" + self.assertEqual(lyrics.slug(text), 'l-ete-c-est-fait-pour-jouer') + # accents, parens and spaces + text = u"\xe7afe au lait (boisson)" + self.assertEqual(lyrics.slug(text), 'cafe-au-lait-boisson') + text = u"Multiple spaces -- and symbols! -- merged" + self.assertEqual(lyrics.slug(text), + 'multiple-spaces-and-symbols-merged') + + def suite(): return unittest.TestLoader().loadTestsFromName(__name__) From 5ef68783a84d9045ce4e1f4fe95c68ce184a4d21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Tue, 18 Jul 2017 16:33:22 -0400 Subject: [PATCH 2072/2280] strip trailing and leading extra dashes those are introduced if non-word characters are found, and are ugly --- beetsplug/lyrics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 84f1bf6c0..8bd96c7cf 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -236,12 +236,13 @@ def slug(text): 2. shift everything to lowercase 3. strip whitespace 4. replace other non-word characters with dashes + 5. strip extra dashes This somewhat duplicates the :func:`Google.slugify` function but slugify is not as generic as this one, which can be reused elsewhere. """ - return re.sub(r'\W+', '-', unidecode(text).lower().strip()) + return re.sub(r'\W+', '-', unidecode(text).lower().strip()).strip('-') class Backend(object): From a17974a1523e8cc3998be77b9384a062d3c4bd85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antoine=20Beaupr=C3=A9?= Date: Tue, 18 Jul 2017 16:36:40 -0400 Subject: [PATCH 2073/2280] add changelog entry for #2634 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e30080f49..d94260906 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -14,6 +14,9 @@ Fixes: * :doc:`/plugins/replaygain`: Fix a regression in the previous release related to the new R128 tags. :bug:`2615` :bug:`2623` +* :doc:`/plugins/lyrics`: The MusixMatch backend now detect and warns + the user when blocked on the server. Thanks to + :user:`anarcat`. :bug:`2634` :bug:`2632` For developers: From 9e2a71eec39fcc58c6bf5aeb15e96af8be5edaff Mon Sep 17 00:00:00 2001 From: plittlefield Date: Fri, 11 Aug 2017 16:12:29 +0100 Subject: [PATCH 2074/2280] Update zero.rst --- docs/plugins/zero.rst | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 20e1fa171..355ad3234 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -50,3 +50,20 @@ Manually Triggering Zero You can also type ``beet zero [QUERY]`` to manually invoke the plugin on music in your library. + +A Note About Fields +------------------- + +If you wish to store embedded cover artwork metadata in the file, you must +use the field ``images``. This is a special field and is not shown by +issuing the command ``beet fields``. + +For example:: + + zero: + keep_fields: title artist album year track genre images + +This will result in the following metadata field in an MP3 file:: + + APIC (Attached picture): ()[, 3]: image/jpeg, 88742 bytes + From 598c965b0f64a0e42bd4faf7c0e2540ac91b16c8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 11 Aug 2017 14:35:22 -0400 Subject: [PATCH 2075/2280] Simplify text for #2653 --- docs/plugins/zero.rst | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/plugins/zero.rst b/docs/plugins/zero.rst index 355ad3234..3ef241c87 100644 --- a/docs/plugins/zero.rst +++ b/docs/plugins/zero.rst @@ -51,19 +51,12 @@ Manually Triggering Zero You can also type ``beet zero [QUERY]`` to manually invoke the plugin on music in your library. -A Note About Fields -------------------- +Preserving Album Art +-------------------- -If you wish to store embedded cover artwork metadata in the file, you must -use the field ``images``. This is a special field and is not shown by -issuing the command ``beet fields``. - -For example:: +If you use the ``keep_fields`` option, the plugin will remove embedded album +art from files' tags unless you tell it not to. To keep the album art, include +the special field ``images`` in the list. For example:: zero: keep_fields: title artist album year track genre images - -This will result in the following metadata field in an MP3 file:: - - APIC (Attached picture): ()[, 3]: image/jpeg, 88742 bytes - From f909f092fc848d2dbd66edb890442c53792dc56b Mon Sep 17 00:00:00 2001 From: David Logie Date: Fri, 10 Mar 2017 18:50:42 +0000 Subject: [PATCH 2076/2280] Fix importfeeds plugin on Python 3. --- beetsplug/importfeeds.py | 38 +++++++++----------------------------- 1 file changed, 9 insertions(+), 29 deletions(-) diff --git a/beetsplug/importfeeds.py b/beetsplug/importfeeds.py index 18f63a2bd..35ae28835 100644 --- a/beetsplug/importfeeds.py +++ b/beetsplug/importfeeds.py @@ -30,20 +30,6 @@ from beets import config M3U_DEFAULT_NAME = 'imported.m3u' -def _get_feeds_dir(lib): - """Given a Library object, return the path to the feeds directory to be - used (either in the library directory or an explicitly configured - path). Ensures that the directory exists. - """ - # Inside library directory. - dirpath = lib.directory - - # Ensure directory exists. - if not os.path.exists(syspath(dirpath)): - os.makedirs(syspath(dirpath)) - return dirpath - - def _build_m3u_filename(basename): """Builds unique m3u filename by appending given basename to current date.""" @@ -78,30 +64,28 @@ class ImportFeedsPlugin(BeetsPlugin): 'absolute_path': False, }) - feeds_dir = self.config['dir'].get() - if feeds_dir: - feeds_dir = os.path.expanduser(bytestring_path(feeds_dir)) - self.config['dir'] = feeds_dir - if not os.path.exists(syspath(feeds_dir)): - os.makedirs(syspath(feeds_dir)) - relative_to = self.config['relative_to'].get() if relative_to: self.config['relative_to'] = normpath(relative_to) else: - self.config['relative_to'] = feeds_dir + self.config['relative_to'] = self.get_feeds_dir() - self.register_listener('library_opened', self.library_opened) self.register_listener('album_imported', self.album_imported) self.register_listener('item_imported', self.item_imported) + def get_feeds_dir(self): + feeds_dir = self.config['dir'].get() + if feeds_dir: + return os.path.expanduser(bytestring_path(feeds_dir)) + return config['directory'].as_filename() + def _record_items(self, lib, basename, items): """Records relative paths to the given items for each feed format """ - feedsdir = bytestring_path(self.config['dir'].as_filename()) + feedsdir = bytestring_path(self.get_feeds_dir()) formats = self.config['formats'].as_str_seq() relative_to = self.config['relative_to'].get() \ - or self.config['dir'].as_filename() + or self.get_feeds_dir() relative_to = bytestring_path(relative_to) paths = [] @@ -138,10 +122,6 @@ class ImportFeedsPlugin(BeetsPlugin): for path in paths: self._log.info(u" {0}", path) - def library_opened(self, lib): - if self.config['dir'].get() is None: - self.config['dir'] = _get_feeds_dir(lib) - def album_imported(self, lib, album): self._record_items(lib, album.album, album.items()) From c89186afacff0f34d7d5f8ca7cd83575e0d4f6cd Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 20 Aug 2017 12:52:54 -0400 Subject: [PATCH 2077/2280] Changelog for #2467/#2658 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f3e673497..020626e4c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -22,6 +22,8 @@ Fixes: * :doc:`/plugins/lyrics`: The MusixMatch backend now detect and warns the user when blocked on the server. Thanks to :user:`anarcat`. :bug:`2634` :bug:`2632` +* :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain + configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` For developers: From 51961bbba25cc520bd85c60ce3ab80263776378f Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 20 Aug 2017 13:03:40 -0400 Subject: [PATCH 2078/2280] gmusic: Use Unicode literals (#2660) --- beetsplug/gmusic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/gmusic.py b/beetsplug/gmusic.py index 67752ba27..259d2725a 100644 --- a/beetsplug/gmusic.py +++ b/beetsplug/gmusic.py @@ -58,9 +58,9 @@ class Gmusic(BeetsPlugin): def upload(self, lib, opts, args): items = lib.items(ui.decargs(args)) files = [x.path.decode('utf-8') for x in items] - ui.print_('Uploading your files...') + ui.print_(u'Uploading your files...') self.m.upload(filepaths=files) - ui.print_('Your files were successfully added to library') + ui.print_(u'Your files were successfully added to library') def search(self, lib, opts, args): password = config['gmusic']['password'] @@ -76,7 +76,7 @@ class Gmusic(BeetsPlugin): files = mobile.get_all_songs() except NotLoggedIn: ui.print_( - 'Authentication error. Please check your email and password.' + u'Authentication error. Please check your email and password.' ) return if not args: From 7eb9913391413cee5fd28fd407d5385cac8d6d5b Mon Sep 17 00:00:00 2001 From: Nate Bogdanowicz Date: Sun, 20 Aug 2017 13:14:48 -0700 Subject: [PATCH 2079/2280] Fix kodi url --- beetsplug/kodiupdate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py index 78f120d89..4713151b3 100644 --- a/beetsplug/kodiupdate.py +++ b/beetsplug/kodiupdate.py @@ -33,7 +33,7 @@ from beets.plugins import BeetsPlugin def update_kodi(host, port, user, password): """Sends request to the Kodi api to start a library refresh. """ - url = "http://{0}:{1}/jsonrpc/".format(host, port) + url = "http://{0}:{1}/jsonrpc".format(host, port) """Content-Type: application/json is mandatory according to the kodi jsonrpc documentation""" From f5dbb7b0c5406857b67099f8511a5231b423ff6b Mon Sep 17 00:00:00 2001 From: Nate Bogdanowicz Date: Sun, 20 Aug 2017 14:46:15 -0700 Subject: [PATCH 2080/2280] Make error handling and logging more detailed --- beetsplug/kodiupdate.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/beetsplug/kodiupdate.py b/beetsplug/kodiupdate.py index 4713151b3..ce5cb478c 100644 --- a/beetsplug/kodiupdate.py +++ b/beetsplug/kodiupdate.py @@ -28,6 +28,7 @@ from __future__ import division, absolute_import, print_function import requests from beets import config from beets.plugins import BeetsPlugin +import six def update_kodi(host, port, user, password): @@ -72,16 +73,26 @@ class KodiUpdate(BeetsPlugin): def update(self, lib): """When the client exists try to send refresh request to Kodi server. """ - self._log.info(u'Updating Kodi library...') + self._log.info(u'Requesting a Kodi library update...') # Try to send update request. try: - update_kodi( + r = update_kodi( config['kodi']['host'].get(), config['kodi']['port'].get(), config['kodi']['user'].get(), config['kodi']['pwd'].get()) - self._log.info(u'... started.') + r.raise_for_status() - except requests.exceptions.RequestException: - self._log.warning(u'Update failed.') + except requests.exceptions.RequestException as e: + self._log.warning(u'Kodi update failed: {0}', + six.text_type(e)) + return + + json = r.json() + if json.get('result') != 'OK': + self._log.warning(u'Kodi update failed: JSON response was {0!r}', + json) + return + + self._log.info(u'Kodi update triggered') From df479d686d8a4dadbe4b2577ac18c1e0c7ab7d05 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Sun, 20 Aug 2017 15:47:19 +0200 Subject: [PATCH 2081/2280] Fix the edit plugin displaying bogus data or even crashing on re-imports --- beetsplug/edit.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 1411c0401..8feb28f27 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -365,9 +365,12 @@ class EditPlugin(plugins.BeetsPlugin): """Callback for invoking the functionality during an interactive import session on the *original* item tags. """ - # Assign temporary ids to the Items. - for i, obj in enumerate(task.items): - obj.id = i + 1 + # Assign negative temporary ids to Items that are not in the database + # yet. By using negative values, no clash with items in the database + # can occur. + for i, obj in enumerate(task.items, start=1): + if not obj._db: + obj.id = -i # Present the YAML to the user and let her change it. fields = self._get_fields(album=False, extra=[]) @@ -375,7 +378,8 @@ class EditPlugin(plugins.BeetsPlugin): # Remove temporary ids. for obj in task.items: - obj.id = None + if not obj._db: + obj.id = None # Save the new data. if success: From 109b547f7a85f5403a63d63d18d8bcb4ca815dc8 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Mon, 21 Aug 2017 00:29:57 +0200 Subject: [PATCH 2082/2280] Changelog entry for the edit plugin bugfix --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 020626e4c..c04d7367f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ Fixes: :user:`anarcat`. :bug:`2634` :bug:`2632` * :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` +* :doc: `/plugins/edit`: Fix a bug when editing items during a ``-L`` + re-import. Previously, diffs against against unrelated items could be + shown or beets could crash with a traceback. :bug:`2659` For developers: From bfdcbe2aac9ef3debdcde835a725e0b6ee5b94d2 Mon Sep 17 00:00:00 2001 From: Tigran Kostandyan Date: Mon, 21 Aug 2017 11:38:11 +0300 Subject: [PATCH 2083/2280] Update gmusic.rst --- docs/plugins/gmusic.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst index 4941033a3..595c67177 100644 --- a/docs/plugins/gmusic.rst +++ b/docs/plugins/gmusic.rst @@ -35,10 +35,14 @@ password under a section called ``gmusic``, like so:: email: user@example.com password: seekrit +If you are using two-factor authentication you need to provide an app password (visit `settings` page to set up). + Then, use the ``gmusic-songs`` command to list music:: beet gmusic-songs [-at] [ARGS] +.. _settings: https://github.com/beetbox/beets/issues/2660 + Use the ``-a`` option to search by artist and ``-t`` to search by track. For example:: From 2b31b493a6c5618d8e18df245bb6a5843eaf39c1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 21 Aug 2017 14:29:34 -0400 Subject: [PATCH 2084/2280] Refine docs for #2663 --- docs/plugins/gmusic.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/gmusic.rst b/docs/plugins/gmusic.rst index 595c67177..d0ba96671 100644 --- a/docs/plugins/gmusic.rst +++ b/docs/plugins/gmusic.rst @@ -35,14 +35,14 @@ password under a section called ``gmusic``, like so:: email: user@example.com password: seekrit -If you are using two-factor authentication you need to provide an app password (visit `settings` page to set up). +If you have enabled two-factor authentication in your Google account, you will +need to set up and use an *application-specific password*. You can obtain one +from your Google security settings page. Then, use the ``gmusic-songs`` command to list music:: beet gmusic-songs [-at] [ARGS] -.. _settings: https://github.com/beetbox/beets/issues/2660 - Use the ``-a`` option to search by artist and ``-t`` to search by track. For example:: From e983929e52f3ce4e61c19ead2b07238cbaddfe36 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 21 Aug 2017 14:30:12 -0400 Subject: [PATCH 2085/2280] Fix a ReST syntax error --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index c04d7367f..c71eec055 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,7 +24,7 @@ Fixes: :user:`anarcat`. :bug:`2634` :bug:`2632` * :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` -* :doc: `/plugins/edit`: Fix a bug when editing items during a ``-L`` +* :doc:`/plugins/edit`: Fix a bug when editing items during a ``-L`` re-import. Previously, diffs against against unrelated items could be shown or beets could crash with a traceback. :bug:`2659` From 9d01ba0af2f3015083281169681b963943ff5290 Mon Sep 17 00:00:00 2001 From: Nate Bogdanowicz Date: Tue, 22 Aug 2017 09:56:57 -0700 Subject: [PATCH 2086/2280] Add changelog entry for #2662 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 020626e4c..3e44484ed 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,8 @@ Fixes: :user:`anarcat`. :bug:`2634` :bug:`2632` * :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` +* :doc:`/plugins/kodiupdate`: Fix server URL and add better error reporting. + :bug:`2662` For developers: From 7d4627bb8f592459e13e6999eb435970d78f73ed Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Aug 2017 22:57:10 +0200 Subject: [PATCH 2087/2280] Ensure mtime is non-zero for Items in test fixtures. mtime == 0 is the "this Item contains newer metadata than the file's tags" marker. Setting this to something else than 0 emulates the state of Items freshly read from the database. Breaks 4 of the edit plugin tests. --- test/_common.py | 1 + test/helper.py | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/test/_common.py b/test/_common.py index f3213ec31..fc7b650b3 100644 --- a/test/_common.py +++ b/test/_common.py @@ -90,6 +90,7 @@ def item(lib=None): mb_artistid='someID-3', mb_albumartistid='someID-4', album_id=None, + mtime=12345, ) if lib: lib.add(i) diff --git a/test/helper.py b/test/helper.py index 795fd2ac0..5af742e12 100644 --- a/test/helper.py +++ b/test/helper.py @@ -315,6 +315,8 @@ class TestHelper(object): item = Item(**values_) if 'path' not in values: item['path'] = 'audio.' + item['format'].lower() + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 return item def add_item(self, **values): @@ -365,6 +367,8 @@ class TestHelper(object): item = Item.from_path(path) item.album = u'\u00e4lbum {0}'.format(i) # Check unicode paths item.title = u't\u00eftle {0}'.format(i) + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 item.add(self.lib) item.move(copy=True) item.store() @@ -380,6 +384,8 @@ class TestHelper(object): item = Item.from_path(path) item.album = u'\u00e4lbum' # Check unicode paths item.title = u't\u00eftle {0}'.format(i) + # mtime needs to be set last since other assignments reset it. + item.mtime = 12345 item.add(self.lib) item.move(copy=True) item.store() From 18c82cab5f35194cc0037e940c1f873e04c3271f Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Aug 2017 23:17:39 +0200 Subject: [PATCH 2088/2280] test_edit: Add a comment explaining why I didn't change the writing behaviour I was midway through writing a test when realizing that it's best the way it is... --- test/test_edit.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_edit.py b/test/test_edit.py index 2900d092a..9486e8485 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -217,6 +217,9 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): ['a']) self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar') + # Even though a flexible attribute was written (which is not directly + # written to the tags), write should still be called since templates + # might use it. self.assertCounts(mock_write, write_call_count=1, title_starts_with=u't\u00eftle') From c811102eb2d1b2bd06bde8f3a89a42d0ecbefbdd Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Aug 2017 23:22:58 +0200 Subject: [PATCH 2089/2280] test_edit: Expect mtime to change, unbreaks the multiple-item tests. --- test/test_edit.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 9486e8485..8953ea2f1 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -162,7 +162,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\u00eftle') self.assertItemFieldsModified(self.album.items(), self.items_orig, - ['title']) + ['title', 'mtime']) def test_single_title_edit_apply(self, mock_write): """Edit title for one item in the library, then apply changes.""" @@ -202,7 +202,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertItemFieldsModified(self.album.items(), self.items_orig, - ['album']) + ['album', 'mtime']) # Ensure album is *not* modified. self.album.load() self.assertEqual(self.album.album, u'\u00e4lbum') @@ -235,7 +235,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.album, u'modified \u00e4lbum') self.assertItemFieldsModified(self.album.items(), self.items_orig, - ['album']) + ['album', 'mtime']) def test_a_albumartist_edit_apply(self, mock_write): """Album query (-a), edit albumartist field, apply changes.""" @@ -249,7 +249,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT) self.assertEqual(self.album.albumartist, u'the modified album artist') self.assertItemFieldsModified(self.album.items(), self.items_orig, - ['albumartist']) + ['albumartist', 'mtime']) def test_malformed_yaml(self, mock_write): """Edit the yaml file incorrectly (resulting in a malformed yaml From b903b44a0c733227cd284ce631231a0caa62d47e Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Aug 2017 23:31:40 +0200 Subject: [PATCH 2090/2280] test_edit: Fix test that intended to change one item but affected two. This didn't manifest as a testing failure since the plugin (mostly silently) drops id changes. --- test/test_edit.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/test_edit.py b/test/test_edit.py index 8953ea2f1..0a6a286f5 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -210,13 +210,14 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin): def test_single_edit_add_field(self, mock_write): """Edit the yaml file appending an extra field to the first item, then apply changes.""" - # Append "foo: bar" to item with id == 1. - self.run_mocked_command({'replacements': {u"id: 1": - u"id: 1\nfoo: bar"}}, + # Append "foo: bar" to item with id == 2. ("id: 1" would match both + # "id: 1" and "id: 10") + self.run_mocked_command({'replacements': {u"id: 2": + u"id: 2\nfoo: bar"}}, # Apply changes. ['a']) - self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar') + self.assertEqual(self.lib.items(u'id:2')[0].foo, 'bar') # Even though a flexible attribute was written (which is not directly # written to the tags), write should still be called since templates # might use it. From c4fb2d195550a13d3ef69fd47c5851a2fb6a4dca Mon Sep 17 00:00:00 2001 From: wordofglass Date: Tue, 22 Aug 2017 18:21:47 +0200 Subject: [PATCH 2091/2280] Item: Do not reset the mtime in __setitem__ unless the value actually changes Unbreaks the remaining edit plugin tests. --- beets/dbcore/db.py | 15 ++++++++++++--- beets/library.py | 6 +++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index a714d9492..82371fb17 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -242,8 +242,9 @@ class Model(object): else: raise KeyError(key) - def __setitem__(self, key, value): - """Assign the value for a field. + def _setitem(self, key, value): + """Assign the value for a field, return whether new and old value + differ. """ # Choose where to place the value. if key in self._fields: @@ -257,9 +258,17 @@ class Model(object): # Assign value and possibly mark as dirty. old_value = source.get(key) source[key] = value - if self._always_dirty or old_value != value: + changed = old_value != value + if self._always_dirty or changed: self._dirty.add(key) + return changed + + def __setitem__(self, key, value): + """Assign the value for a field. + """ + self._setitem(key, value) + def __delitem__(self, key): """Remove a flexible attribute from the model. """ diff --git a/beets/library.py b/beets/library.py index f294e6d4f..988628a5c 100644 --- a/beets/library.py +++ b/beets/library.py @@ -547,10 +547,10 @@ class Item(LibModel): elif isinstance(value, BLOB_TYPE): value = bytes(value) - if key in MediaFile.fields(): - self.mtime = 0 # Reset mtime on dirty. + changed = super(Item, self)._setitem(key, value) - super(Item, self).__setitem__(key, value) + if changed and key in MediaFile.fields(): + self.mtime = 0 # Reset mtime on dirty. def update(self, values): """Set all key/value pairs in the mapping. If mtime is From 989845199bfa4139374c8e93f13feb590243dd45 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 24 Aug 2017 13:07:20 +0200 Subject: [PATCH 2092/2280] edit: Correctly reset the old object, do not reload it from the tags Previously, if continuing to edit (i.e. invoking the $EDITOR) multiple times in one invocation of EditPlugin.edit_objects, the plugin would reload the old state from the file tags. The initial 'old state' is usually only loaded from the database, though. As a consequence, if database and tags were not in sync, the diffs from first and all subsequent edits could differ unexpectedly. --- beetsplug/edit.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 8feb28f27..eba2db659 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -302,9 +302,14 @@ class EditPlugin(plugins.BeetsPlugin): elif choice == u'c': # Cancel. return False elif choice == u'e': # Keep editing. - # Reset the temporary changes to the objects. + # Reset the temporary changes to the objects. I we have a + # deepcopy from above, use that, else reload from the + # database. + objs = [(old_obj or obj) + for old_obj, obj in zip(objs_old, objs)] for obj in objs: - obj.read() + if obj._db: + obj.load() continue # Remove the temporary file before returning. From 33f7e679432f4d31f2dcfbbd604e3544977c2d1c Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 24 Aug 2017 13:15:15 +0200 Subject: [PATCH 2093/2280] edit: Fix a regression from #2659 when re-tagging albums --- beetsplug/edit.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index eba2db659..7b59546cc 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -283,7 +283,7 @@ class EditPlugin(plugins.BeetsPlugin): # Show the changes. # If the objects are not on the DB yet, we need a copy of their # original state for show_model_changes. - objs_old = [deepcopy(obj) if not obj._db else None + objs_old = [deepcopy(obj) if obj.id < 0 else None for obj in objs] self.apply_data(objs, old_data, new_data) changed = False @@ -308,7 +308,7 @@ class EditPlugin(plugins.BeetsPlugin): objs = [(old_obj or obj) for old_obj, obj in zip(objs_old, objs)] for obj in objs: - if obj._db: + if not obj.id < 0: obj.load() continue @@ -374,7 +374,8 @@ class EditPlugin(plugins.BeetsPlugin): # yet. By using negative values, no clash with items in the database # can occur. for i, obj in enumerate(task.items, start=1): - if not obj._db: + # The importer may set the id to None when re-importing albums. + if not obj._db or obj.id is None: obj.id = -i # Present the YAML to the user and let her change it. @@ -383,7 +384,7 @@ class EditPlugin(plugins.BeetsPlugin): # Remove temporary ids. for obj in task.items: - if not obj._db: + if obj.id < 0: obj.id = None # Save the new data. From a9a2276774bbc88f354c126d1397c31c90a93435 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 24 Aug 2017 14:42:04 +0200 Subject: [PATCH 2094/2280] Implement beets.dbcore.db.Model.copy() --- beets/dbcore/db.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index a714d9492..073b228c9 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -217,6 +217,18 @@ class Model(object): if need_id and not self.id: raise ValueError(u'{0} has no id'.format(type(self).__name__)) + def copy(self): + """Create a semi-deep copy of the item. In particular, the _db object + is not duplicated. A simple copy.deepcopy wouldn't work due to the + sqlite objects in _db. + """ + new = self.__class__() + new._db = self._db + new._values_fixed = self._values_fixed.copy() + new._values_flex = self._values_flex.copy() + new._dirty = self._dirty.copy() + return new + # Essential field accessors. @classmethod From 352d99cccdbb6b53b051d5642ae64cdf965599d1 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 24 Aug 2017 14:43:56 +0200 Subject: [PATCH 2095/2280] edit: Do not deepcopy objects, finally fixes the regression from #2659 Deepcopying fails if a database is attached as Model._db since the sqlite connection objects it contains are non-copyable --- beetsplug/edit.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 7b59546cc..5e0559bbf 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -23,7 +23,6 @@ from beets import ui from beets.dbcore import types from beets.importer import action from beets.ui.commands import _do_query, PromptChoice -from copy import deepcopy import codecs import subprocess import yaml @@ -283,7 +282,7 @@ class EditPlugin(plugins.BeetsPlugin): # Show the changes. # If the objects are not on the DB yet, we need a copy of their # original state for show_model_changes. - objs_old = [deepcopy(obj) if obj.id < 0 else None + objs_old = [obj.copy() if obj.id < 0 else None for obj in objs] self.apply_data(objs, old_data, new_data) changed = False From 5f21bd3ccd232014cd604062071eb40bc442d1b1 Mon Sep 17 00:00:00 2001 From: wordofglass Date: Thu, 24 Aug 2017 14:52:41 +0200 Subject: [PATCH 2096/2280] test_edit: Add a test for retagging. --- test/test_edit.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/test/test_edit.py b/test/test_edit.py index 2900d092a..b4eea4abb 100644 --- a/test/test_edit.py +++ b/test/test_edit.py @@ -22,6 +22,7 @@ from test import _common from test.helper import TestHelper, control_stdin from test.test_ui_importer import TerminalImportSessionSetup from test.test_importer import ImportHelper, AutotagStub +from beets.dbcore.query import TrueQuery from beets.library import Item from beetsplug.edit import EditPlugin @@ -359,6 +360,34 @@ class EditDuringImporterTest(TerminalImportSessionSetup, unittest.TestCase, # Ensure album is fetched from a candidate. self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + def test_edit_retag_apply(self): + """Import the album using a candidate, then retag and edit and apply + changes. + """ + self._setup_import_session() + self.run_mocked_interpreter({}, + # 1, Apply changes. + ['1', 'a']) + + # Retag and edit track titles. On retag, the importer will reset items + # ids but not the db connections. + self.importer.paths = [] + self.importer.query = TrueQuery() + self.run_mocked_interpreter({'replacements': {u'Applied Title': + u'Edited Title'}}, + # eDit, Apply changes. + ['d', 'a']) + + # Check that 'title' field is modified, and other fields come from + # the candidate. + self.assertTrue(all('Edited Title ' in i.title + for i in self.lib.items())) + self.assertTrue(all('match ' in i.mb_trackid + for i in self.lib.items())) + + # Ensure album is fetched from a candidate. + self.assertIn('albumid', self.lib.albums()[0].mb_albumid) + def test_edit_discard_candidate(self): """Edit the album field for all items in the library, discard changes, using a candidate. From 024689e781113259d9d6397d42dcd2aa2ed5f04a Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 25 Aug 2017 15:34:16 +0200 Subject: [PATCH 2097/2280] Changelog entry for the mtime fixes --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index c71eec055..6190022ed 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,10 @@ Fixes: * :doc:`/plugins/edit`: Fix a bug when editing items during a ``-L`` re-import. Previously, diffs against against unrelated items could be shown or beets could crash with a traceback. :bug:`2659` +* Fixed a problem where "no-op" modifications would reset files' mtimes, + resulting in unnecessary writes. This most prominently affected the + :doc:`/plugins/edit` when saving the text file without making changes to some + music. For developers: From 7f12cc0c8813c56baa576d5e82fd7471b0a0e45d Mon Sep 17 00:00:00 2001 From: wordofglass Date: Fri, 25 Aug 2017 15:47:07 +0200 Subject: [PATCH 2098/2280] edit, Model.copy: documentation improvements --- beets/dbcore/db.py | 9 ++++++--- beetsplug/edit.py | 3 +-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 073b228c9..a45e6dc3d 100755 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -218,9 +218,12 @@ class Model(object): raise ValueError(u'{0} has no id'.format(type(self).__name__)) def copy(self): - """Create a semi-deep copy of the item. In particular, the _db object - is not duplicated. A simple copy.deepcopy wouldn't work due to the - sqlite objects in _db. + """Create a copy of the model object. + + The field values and other state is duplicated, but the new copy + remains associated with the same database as the old object. + (A simple `copy.deepcopy` will not work because it would try to + duplicate the SQLite connection.) """ new = self.__class__() new._db = self._db diff --git a/beetsplug/edit.py b/beetsplug/edit.py index 5e0559bbf..631a1b584 100644 --- a/beetsplug/edit.py +++ b/beetsplug/edit.py @@ -302,8 +302,7 @@ class EditPlugin(plugins.BeetsPlugin): return False elif choice == u'e': # Keep editing. # Reset the temporary changes to the objects. I we have a - # deepcopy from above, use that, else reload from the - # database. + # copy from above, use that, else reload from the database. objs = [(old_obj or obj) for old_obj, obj in zip(objs_old, objs)] for obj in objs: From 015aee366288466d0a59892bf5046144a19e0890 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 26 Aug 2017 11:18:27 -0400 Subject: [PATCH 2099/2280] Fix #2671: missing syspath on acoustid call --- beetsplug/chroma.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/chroma.py b/beetsplug/chroma.py index cd0a77593..574729560 100644 --- a/beetsplug/chroma.py +++ b/beetsplug/chroma.py @@ -295,7 +295,7 @@ def fingerprint_item(log, item, write=False): log.info(u'{0}: fingerprinting', util.displayable_path(item.path)) try: - _, fp = acoustid.fingerprint_file(item.path) + _, fp = acoustid.fingerprint_file(util.syspath(item.path)) item.acoustid_fingerprint = fp if write: log.info(u'{0}: writing fingerprint', diff --git a/docs/changelog.rst b/docs/changelog.rst index 5e0391f22..2e4f1be54 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -33,6 +33,8 @@ Fixes: resulting in unnecessary writes. This most prominently affected the :doc:`/plugins/edit` when saving the text file without making changes to some music. :bug:`2667` +* :doc:`/plugins/chroma`: Fix a crash when running the ``submit`` command on + Python 3 on Windows with non-ASCII filenames. :bug:`2671` For developers: From 34246a00e7be8da59ed4e0d659f7b980a5da7910 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 27 Aug 2017 10:20:36 -0400 Subject: [PATCH 2100/2280] Fix #2673: JSON file encoding in absubmit First, it's best to open the file as binary so the JSON module itself can figure out how to decode it (it will just use UTF-8). Then, we can use `load` instead of `loads` to avoid needing to read the file explicitly ourselves. --- beetsplug/absubmit.py | 4 ++-- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/absubmit.py b/beetsplug/absubmit.py index 3d21c469c..0c288b9d8 100644 --- a/beetsplug/absubmit.py +++ b/beetsplug/absubmit.py @@ -133,8 +133,8 @@ class AcousticBrainzSubmitPlugin(plugins.BeetsPlugin): item=item, error=e ) return None - with open(filename) as tmp_file: - analysis = json.loads(tmp_file.read()) + with open(filename, 'rb') as tmp_file: + analysis = json.load(tmp_file) # Add the hash to the output. analysis['metadata']['version']['essentia_build_sha'] = \ self.extractor_sha diff --git a/docs/changelog.rst b/docs/changelog.rst index 2e4f1be54..413cf0df0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -35,6 +35,8 @@ Fixes: music. :bug:`2667` * :doc:`/plugins/chroma`: Fix a crash when running the ``submit`` command on Python 3 on Windows with non-ASCII filenames. :bug:`2671` +* :doc:`/plugins/absubmit`: Fix an occasional crash on Python 3 when the AB + analysis tool produced non-ASCII metadata. :bug:`2673` For developers: From b2fd274e2cde0471002d1e16b2eb761a1dfef48e Mon Sep 17 00:00:00 2001 From: euri10 Date: Tue, 5 Sep 2017 16:34:26 +0200 Subject: [PATCH 2101/2280] Added a missing switch to the fetchart command so that only missing albums are displayed --- beetsplug/fetchart.py | 18 +++++++++++++----- docs/plugins/fetchart.rst | 11 +++++++++++ test/test_art.py | 3 ++- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 91b77c0a4..6fc7ad433 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -824,9 +824,15 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): action='store_true', default=False, help=u're-download art when already present' ) + cmd.parser.add_option( + u'-m', u'--missing', dest='missing', + action='store_true', default=False, + help=u'shows only missing art' + ) def func(lib, opts, args): - self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force) + self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force, + opts.missing) cmd.func = func return [cmd] @@ -866,13 +872,16 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): return out - def batch_fetch_art(self, lib, albums, force): + def batch_fetch_art(self, lib, albums, force, missing): """Fetch album art for each of the albums. This implements the manual fetchart CLI command. """ for album in albums: if album.artpath and not force and os.path.isfile(album.artpath): - message = ui.colorize('text_highlight_minor', u'has album art') + if not missing: + message = ui.colorize('text_highlight_minor', + u'has album art') + self._log.info(u'{0}: {1}', album, message) else: # In ordinary invocations, look for images on the # filesystem. When forcing, however, always go to the Web @@ -885,5 +894,4 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): message = ui.colorize('text_success', u'found album art') else: message = ui.colorize('text_error', u'no art found') - - self._log.info(u'{0}: {1}', album, message) + self._log.info(u'{0}: {1}', album, message) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 97e88c03c..4ca289799 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -106,6 +106,17 @@ be processed; otherwise, the command processes every album in your library. .. _image-resizing: +Display Only Missing Album Art +------------------------------ + +Use the ``fetchart`` command with the ``-m`` switch in order to display only missing +art:: + + $ beet fetchart [-m] [query] + +By default the command will display all results, the ``-m`` or ``--missing`` +switch will only display results for those album arts that still miss. + Image Resizing -------------- diff --git a/test/test_art.py b/test/test_art.py index 6b0e5bbc5..df70dd56a 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -518,7 +518,8 @@ class ArtImporterTest(UseThePlugin): # message " has album art". self._fetch_art(True) util.remove(self.album.artpath) - self.plugin.batch_fetch_art(self.lib, self.lib.albums(), force=False) + self.plugin.batch_fetch_art(self.lib, self.lib.albums(), force=False, + missing=False) self.assertExists(self.album.artpath) From 25fb2453b4e86af8107b1c3a689dfa19496304d6 Mon Sep 17 00:00:00 2001 From: euri10 Date: Tue, 5 Sep 2017 18:27:47 +0200 Subject: [PATCH 2102/2280] Modified the name of the fetchart plugin switch from missing to quiet --- beetsplug/fetchart.py | 10 +++++----- docs/changelog.rst | 3 +++ docs/plugins/fetchart.rst | 8 ++++---- test/test_art.py | 2 +- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 6fc7ad433..a1153bd69 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -825,14 +825,14 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): help=u're-download art when already present' ) cmd.parser.add_option( - u'-m', u'--missing', dest='missing', + u'-q', u'--quiet', dest='quiet', action='store_true', default=False, - help=u'shows only missing art' + help=u'shows only quiet art' ) def func(lib, opts, args): self.batch_fetch_art(lib, lib.albums(ui.decargs(args)), opts.force, - opts.missing) + opts.quiet) cmd.func = func return [cmd] @@ -872,13 +872,13 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): return out - def batch_fetch_art(self, lib, albums, force, missing): + def batch_fetch_art(self, lib, albums, force, quiet): """Fetch album art for each of the albums. This implements the manual fetchart CLI command. """ for album in albums: if album.artpath and not force and os.path.isfile(album.artpath): - if not missing: + if not quiet: message = ui.colorize('text_highlight_minor', u'has album art') self._log.info(u'{0}: {1}', album, message) diff --git a/docs/changelog.rst b/docs/changelog.rst index 413cf0df0..1bf02a83e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,6 +9,9 @@ New features: * :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. :bug:`2628` +* :doc:`/plugins/fetchart`: The plugin has now a quiet switch that will only + display missing album arts. Thanks to :user:`euri10`. + :bug:`2683` Fixes: diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 4ca289799..82918e051 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -109,13 +109,13 @@ be processed; otherwise, the command processes every album in your library. Display Only Missing Album Art ------------------------------ -Use the ``fetchart`` command with the ``-m`` switch in order to display only missing +Use the ``fetchart`` command with the ``-q`` switch in order to display only missing art:: - $ beet fetchart [-m] [query] + $ beet fetchart [-q] [query] -By default the command will display all results, the ``-m`` or ``--missing`` -switch will only display results for those album arts that still miss. +By default the command will display all results, the ``-q`` or ``--quiet`` +switch will only display results for album arts that are still missing. Image Resizing -------------- diff --git a/test/test_art.py b/test/test_art.py index df70dd56a..a95cd4c95 100644 --- a/test/test_art.py +++ b/test/test_art.py @@ -519,7 +519,7 @@ class ArtImporterTest(UseThePlugin): self._fetch_art(True) util.remove(self.album.artpath) self.plugin.batch_fetch_art(self.lib, self.lib.albums(), force=False, - missing=False) + quiet=False) self.assertExists(self.album.artpath) From 46f7ce78f138b60a81b5dff295e21ac7bbd3bf2a Mon Sep 17 00:00:00 2001 From: David Logie Date: Sat, 9 Sep 2017 18:59:22 +0100 Subject: [PATCH 2103/2280] mbcollection: Support specifiying collection ID. --- beetsplug/mbcollection.py | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 99cb30d15..9c13b66fd 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -60,10 +60,33 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): config['musicbrainz']['user'].as_str(), config['musicbrainz']['pass'].as_str(), ) - self.config.add({'auto': False}) + self.config.add({ + 'auto': False, + 'collection': u'', + }) if self.config['auto']: self.import_stages = [self.imported] + def _get_collection(self): + collections = mb_call(musicbrainzngs.get_collections) + if not collections['collection-list']: + raise ui.UserError(u'no collections exist for user') + + # Get all collection IDs, avoiding event collections + collection_ids = [x['id'] for x in collections['collection-list']] + if not collection_ids: + raise ui.UserError(u'No collection found.') + + # Check that the collection exists so we can present a nice error + collection = self.config['collection'].as_str() + if collection: + if collection not in collection_ids: + raise ui.UserError(u'invalid collection ID: {0}'.format(collection)) + return collection + + # No specified collection. Just return the first collection ID + return collection_ids[0] + def commands(self): mbupdate = Subcommand('mbupdate', help=u'Update MusicBrainz collection') @@ -82,19 +105,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): def update_album_list(self, album_list): """Update the MusicBrainz collection from a list of Beets albums """ - # Get the available collections. - collections = mb_call(musicbrainzngs.get_collections) - if not collections['collection-list']: - raise ui.UserError(u'no collections exist for user') - - # Get the first release collection. MusicBrainz also has event - # collections, so we need to avoid adding to those. - for collection in collections['collection-list']: - if 'release-count' in collection: - collection_id = collection['id'] - break - else: - raise ui.UserError(u'No collection found.') + collection_id = self._get_collection() # Get a list of all the album IDs. album_ids = [] From 7db09c6abae9482acea0e8b2d6284943c2bbfe22 Mon Sep 17 00:00:00 2001 From: David Logie Date: Sat, 9 Sep 2017 19:13:44 +0100 Subject: [PATCH 2104/2280] Silence pep8 warning. --- beetsplug/mbcollection.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 9c13b66fd..bd6e84188 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -81,7 +81,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): collection = self.config['collection'].as_str() if collection: if collection not in collection_ids: - raise ui.UserError(u'invalid collection ID: {0}'.format(collection)) + raise ui.UserError(u'invalid collection ID: {}' + .format(collection)) return collection # No specified collection. Just return the first collection ID From 8eb233331c1f518c43046f7904ad47a59839d5b5 Mon Sep 17 00:00:00 2001 From: David Logie Date: Sat, 9 Sep 2017 21:38:33 +0100 Subject: [PATCH 2105/2280] Update changelog/docs for new ``mbcollection.collection`` option. --- docs/changelog.rst | 3 +++ docs/plugins/mbcollection.rst | 2 ++ 2 files changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 1bf02a83e..1c86011fd 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,9 @@ New features: * :doc:`/plugins/fetchart`: The plugin has now a quiet switch that will only display missing album arts. Thanks to :user:`euri10`. :bug:`2683` +* :doc:`/plugins/mbcollection`: The plugin now supports a custom MusicBrainz + collection via the ``collection`` configuration option. + :bug:`2685` Fixes: diff --git a/docs/plugins/mbcollection.rst b/docs/plugins/mbcollection.rst index df9a5ddc8..f48996164 100644 --- a/docs/plugins/mbcollection.rst +++ b/docs/plugins/mbcollection.rst @@ -29,3 +29,5 @@ configuration file. There is one option available: - **auto**: Automatically amend your MusicBrainz collection whenever you import a new album. Default: ``no``. +- **collection**: Which MusicBrainz collection to update. + Default: ``None``. From b3761396638f5b0da1e3111dd450d40d0d86a464 Mon Sep 17 00:00:00 2001 From: zigarrre Date: Mon, 11 Sep 2017 16:35:26 +0200 Subject: [PATCH 2106/2280] Refactored move functions for clarity according to #2682 The move functions in library.py and manipule_files in importer.py where changed to use a single parameter for the file operation instead of multiple boolean flags. A typo in the documentation of the Album.move and Item.move functions confusing True and False when describing the store parameter was fixed as well. --- beets/importer.py | 38 +++++++++---- beets/library.py | 118 +++++++++++++++++++++------------------- beets/ui/commands.py | 11 +++- beets/util/__init__.py | 10 ++++ beetsplug/duplicates.py | 8 +-- docs/changelog.rst | 3 + test/helper.py | 7 ++- test/test_files.py | 35 ++++++------ test/test_ui.py | 6 +- 9 files changed, 138 insertions(+), 98 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index d36a5a0a0..e7d8b40bc 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -37,7 +37,7 @@ from beets import dbcore from beets import plugins from beets import util from beets import config -from beets.util import pipeline, sorted_walk, ancestry +from beets.util import pipeline, sorted_walk, ancestry, MoveOperation from beets.util import syspath, normpath, displayable_path from enum import Enum from beets import mediafile @@ -675,20 +675,28 @@ class ImportTask(BaseImportTask): for item in self.items: item.update(changes) - def manipulate_files(self, move=False, copy=False, write=False, - link=False, hardlink=False, session=None): + def manipulate_files(self, operation=None, write=False, session=None): + """ Copy, move, link or hardlink (depending on `operation`) the files + as well as write metadata. + + `operation` should be an instance of `util.MoveOperation`. + + If `write` is `True` metadata is written to the files. + """ + items = self.imported_items() # Save the original paths of all items for deletion and pruning # in the next step (finalization). self.old_paths = [item.path for item in items] for item in items: - if move or copy or link or hardlink: + if operation is not None: # In copy and link modes, treat re-imports specially: # move in-library files. (Out-of-library files are # copied/moved as usual). old_path = item.path - if (copy or link or hardlink) and self.replaced_items[item] \ - and session.lib.directory in util.ancestry(old_path): + if (operation != MoveOperation.MOVE + and self.replaced_items[item] + and session.lib.directory in util.ancestry(old_path)): item.move() # We moved the item, so remove the # now-nonexistent file from old_paths. @@ -696,7 +704,7 @@ class ImportTask(BaseImportTask): else: # A normal import. Just copy files and keep track of # old paths. - item.move(copy, link, hardlink) + item.move(operation) if write and (self.apply or self.choice_flag == action.RETAG): item.try_write() @@ -1450,12 +1458,20 @@ def manipulate_files(session, task): if task.should_remove_duplicates: task.remove_duplicates(session.lib) + if session.config['move']: + operation = MoveOperation.MOVE + elif session.config['copy']: + operation = MoveOperation.COPY + elif session.config['link']: + operation = MoveOperation.LINK + elif session.config['hardlink']: + operation = MoveOperation.HARDLINK + else: + operation = None + task.manipulate_files( - move=session.config['move'], - copy=session.config['copy'], + operation, write=session.config['write'], - link=session.config['link'], - hardlink=session.config['hardlink'], session=session, ) diff --git a/beets/library.py b/beets/library.py index 988628a5c..dd9081d10 100644 --- a/beets/library.py +++ b/beets/library.py @@ -28,7 +28,8 @@ from beets import logging from beets.mediafile import MediaFile, UnreadableFileError from beets import plugins from beets import util -from beets.util import bytestring_path, syspath, normpath, samefile +from beets.util import bytestring_path, syspath, normpath, samefile, \ + MoveOperation from beets.util.functemplate import Template from beets import dbcore from beets.dbcore import types @@ -685,31 +686,34 @@ class Item(LibModel): # Files themselves. - def move_file(self, dest, copy=False, link=False, hardlink=False): - """Moves or copies the item's file, updating the path value if - the move succeeds. If a file exists at ``dest``, then it is - slightly modified to be unique. + def move_file(self, dest, operation=MoveOperation.MOVE): + """Move, copy, link or hardlink the item's depending on `operation`, + updating the path value if the move succeeds. + + If a file exists at `dest`, then it is slightly modified to be unique. + + `operation` should be an instance of `util.MoveOperation`. """ if not util.samefile(self.path, dest): dest = util.unique_path(dest) - if copy: - util.copy(self.path, dest) - plugins.send("item_copied", item=self, source=self.path, - destination=dest) - elif link: - util.link(self.path, dest) - plugins.send("item_linked", item=self, source=self.path, - destination=dest) - elif hardlink: - util.hardlink(self.path, dest) - plugins.send("item_hardlinked", item=self, source=self.path, - destination=dest) - else: + if operation == MoveOperation.MOVE: plugins.send("before_item_moved", item=self, source=self.path, destination=dest) util.move(self.path, dest) plugins.send("item_moved", item=self, source=self.path, destination=dest) + elif operation == MoveOperation.COPY: + util.copy(self.path, dest) + plugins.send("item_copied", item=self, source=self.path, + destination=dest) + elif operation == MoveOperation.LINK: + util.link(self.path, dest) + plugins.send("item_linked", item=self, source=self.path, + destination=dest) + elif operation == MoveOperation.HARDLINK: + util.hardlink(self.path, dest) + plugins.send("item_hardlinked", item=self, source=self.path, + destination=dest) # Either copying or moving succeeded, so update the stored path. self.path = dest @@ -756,29 +760,26 @@ class Item(LibModel): self._db._memotable = {} - def move(self, copy=False, link=False, hardlink=False, basedir=None, + def move(self, operation=MoveOperation.MOVE, basedir=None, with_album=True, store=True): """Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item's path field is updated to reflect the new location. - If `copy` is true, moving the file is copied rather than moved. - Similarly, `link` creates a symlink instead, and `hardlink` - creates a hardlink. + Instead of moving the item it can also be copied, linked or hardlinked + depending on `operation` which should be an instance of + `util.MoveOperation`. - basedir overrides the library base directory for the - destination. + `basedir` overrides the library base directory for the destination. - If the item is in an album, the album is given an opportunity to - move its art. (This can be disabled by passing - with_album=False.) + If the item is in an album and `with_album` is `True`, the album is + given an opportunity to move its art. By default, the item is stored to the database if it is in the database, so any dirty fields prior to the move() call will be written - as a side effect. You probably want to call save() to commit the DB - transaction. If `store` is true however, the item won't be stored, and - you'll have to manually store it after invoking this method. + as a side effect. If `store` is `False` however, the item won't be stored, + and you'll have to manually store it after invoking this method. """ self._check_db() dest = self.destination(basedir=basedir) @@ -788,7 +789,7 @@ class Item(LibModel): # Perform the move and store the change. old_path = self.path - self.move_file(dest, copy, link, hardlink) + self.move_file(dest, operation) if store: self.store() @@ -796,12 +797,12 @@ class Item(LibModel): if with_album: album = self.get_album() if album: - album.move_art(copy) + album.move_art(operation) if store: album.store() # Prune vacated directory. - if not copy: + if operation == MoveOperation.MOVE: util.prune_dirs(os.path.dirname(old_path), self._db.directory) # Templating. @@ -1008,9 +1009,12 @@ class Album(LibModel): for item in self.items(): item.remove(delete, False) - def move_art(self, copy=False, link=False, hardlink=False): - """Move or copy any existing album art so that it remains in the - same directory as the items. + def move_art(self, operation=MoveOperation.MOVE): + """Move, copy, link or hardlink (depending on `operation`) any + existing album art so that it remains in the same directory as + the items. + + `operation` should be an instance of `util.MoveOperation`. """ old_art = self.artpath if not old_art: @@ -1024,29 +1028,29 @@ class Album(LibModel): log.debug(u'moving album art {0} to {1}', util.displayable_path(old_art), util.displayable_path(new_art)) - if copy: - util.copy(old_art, new_art) - elif link: - util.link(old_art, new_art) - elif hardlink: - util.hardlink(old_art, new_art) - else: + if operation == MoveOperation.MOVE: util.move(old_art, new_art) + util.prune_dirs(os.path.dirname(old_art), self._db.directory) + elif operation == MoveOperation.COPY: + util.copy(old_art, new_art) + elif operation == MoveOperation.LINK: + util.link(old_art, new_art) + elif operation == MoveOperation.HARDLINK: + util.hardlink(old_art, new_art) self.artpath = new_art - # Prune old path when moving. - if not copy: - util.prune_dirs(os.path.dirname(old_art), - self._db.directory) + def move(self, operation=MoveOperation.MOVE, basedir=None, store=True): + """Move, copy, link or hardlink (depending on `operation`) + all items to their destination. Any album art moves along with them. - def move(self, copy=False, link=False, hardlink=False, basedir=None, - store=True): - """Moves (or copies) all items to their destination. Any album - art moves along with them. basedir overrides the library base - directory for the destination. By default, the album is stored to the - database, persisting any modifications to its metadata. If `store` is - true however, the album is not stored automatically, and you'll have - to manually store it after invoking this method. + `basedir` overrides the library base directory for the destination. + + `operation` should be an instance of `util.MoveOperation`. + + By default, the album is stored to the database, persisting any + modifications to its metadata. If `store` is `False` however, + the album is not stored automatically, and you'll have to manually + store it after invoking this method. """ basedir = basedir or self._db.directory @@ -1058,11 +1062,11 @@ class Album(LibModel): # Move items. items = list(self.items()) for item in items: - item.move(copy, link, hardlink, basedir=basedir, with_album=False, + item.move(operation, basedir=basedir, with_album=False, store=store) # Move art. - self.move_art(copy, link, hardlink) + self.move_art(operation) if store: self.store() diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 4171ae3b1..a4b433925 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -34,7 +34,8 @@ from beets.autotag import hooks from beets import plugins from beets import importer from beets import util -from beets.util import syspath, normpath, ancestry, displayable_path +from beets.util import syspath, normpath, ancestry, displayable_path, \ + MoveOperation from beets import library from beets import config from beets import logging @@ -1499,10 +1500,14 @@ def move_items(lib, dest, query, copy, album, pretend, confirm=False, if export: # Copy without affecting the database. - obj.move(True, basedir=dest, store=False) + obj.move(operation=MoveOperation.COPY, basedir=dest, + store=False) else: # Ordinary move/copy: store the new path. - obj.move(copy, basedir=dest) + if copy: + obj.move(operation=MoveOperation.COPY, basedir=dest) + else: + obj.move(operation=MoveOperation.MOVE, basedir=dest) def move_func(lib, opts, args): diff --git a/beets/util/__init__.py b/beets/util/__init__.py index ee06df0bf..6673c61e3 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -31,6 +31,7 @@ import shlex from beets.util import hidden import six from unidecode import unidecode +from enum import Enum MAX_FILENAME_LENGTH = 200 @@ -124,6 +125,15 @@ class FilesystemError(HumanReadableException): return u'{0} {1}'.format(self._reasonstr(), clause) +class MoveOperation(Enum): + """Represents the file operations that e.g. various move functions can carry out. + """ + MOVE = 0 + COPY = 1 + LINK = 2 + HARDLINK = 3 + + def normpath(path): """Provide the canonical form of the path suitable for storing in the database. diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 2f6bba3e6..f63a7be20 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -22,7 +22,7 @@ import shlex from beets.plugins import BeetsPlugin from beets.ui import decargs, print_, Subcommand, UserError from beets.util import command_output, displayable_path, subprocess, \ - bytestring_path + bytestring_path, MoveOperation from beets.library import Item, Album import six @@ -175,10 +175,10 @@ class DuplicatesPlugin(BeetsPlugin): """ print_(format(item, fmt)) if copy: - item.move(basedir=copy, copy=True) + item.move(basedir=copy, operation=MoveOperation.COPY) item.store() if move: - item.move(basedir=move, copy=False) + item.move(basedir=move) item.store() if delete: item.remove(delete=True) @@ -312,7 +312,7 @@ class DuplicatesPlugin(BeetsPlugin): objs[0], displayable_path(o.path), displayable_path(missing.destination())) - missing.move(copy=True) + missing.move(operation=MoveOperation.COPY) return objs def _merge(self, objs): diff --git a/docs/changelog.rst b/docs/changelog.rst index 1c86011fd..f8b8ad1cd 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -50,6 +50,9 @@ For developers: missing values into type-specific null-like values. This should help in cases where a string field is unexpectedly `None` sometimes instead of just showing up as an empty string. :bug:`2605` +* Refactored the move functions in library.py and the `manipulate_files` function + in importer.py to use a single parameter describing the file operation instead + of multiple boolean flags. :bug:`2682` 1.4.5 (June 20, 2017) diff --git a/test/helper.py b/test/helper.py index 5af742e12..ebf039fca 100644 --- a/test/helper.py +++ b/test/helper.py @@ -52,6 +52,7 @@ from beets import importer from beets.autotag.hooks import AlbumInfo, TrackInfo from beets.mediafile import MediaFile, Image from beets import util +from beets.util import MoveOperation # TODO Move AutotagMock here from test import _common @@ -349,7 +350,7 @@ class TestHelper(object): item['path'] = os.path.join(_common.RSRC, util.bytestring_path('min.' + extension)) item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() return item @@ -370,7 +371,7 @@ class TestHelper(object): # mtime needs to be set last since other assignments reset it. item.mtime = 12345 item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() items.append(item) return items @@ -387,7 +388,7 @@ class TestHelper(object): # mtime needs to be set last since other assignments reset it. item.mtime = 12345 item.add(self.lib) - item.move(copy=True) + item.move(operation=MoveOperation.COPY) item.store() items.append(item) return self.lib.add_album(items) diff --git a/test/test_files.py b/test/test_files.py index 834d3391c..ff055ac6f 100644 --- a/test/test_files.py +++ b/test/test_files.py @@ -27,6 +27,7 @@ from test import _common from test._common import item, touch import beets.library from beets import util +from beets.util import MoveOperation class MoveTest(_common.TestCase): @@ -78,11 +79,11 @@ class MoveTest(_common.TestCase): self.assertNotExists(os.path.dirname(old_path)) def test_copy_arrives(self): - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertExists(self.dest) def test_copy_does_not_depart(self): - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertExists(self.path) def test_move_changes_path(self): @@ -92,13 +93,13 @@ class MoveTest(_common.TestCase): def test_copy_already_at_destination(self): self.i.move() old_path = self.i.path - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertEqual(self.i.path, old_path) def test_move_already_at_destination(self): self.i.move() old_path = self.i.path - self.i.move(copy=False) + self.i.move() self.assertEqual(self.i.path, old_path) def test_read_only_file_copied_writable(self): @@ -106,7 +107,7 @@ class MoveTest(_common.TestCase): os.chmod(self.path, 0o444) try: - self.i.move(copy=True) + self.i.move(operation=MoveOperation.COPY) self.assertTrue(os.access(self.i.path, os.W_OK)) finally: # Make everything writable so it can be cleaned up. @@ -126,24 +127,24 @@ class MoveTest(_common.TestCase): @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_arrives(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) self.assertExists(self.dest) self.assertTrue(os.path.islink(self.dest)) self.assertEqual(os.readlink(self.dest), self.path) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_does_not_depart(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) self.assertExists(self.path) @unittest.skipUnless(_common.HAVE_SYMLINK, "need symlinks") def test_link_changes_path(self): - self.i.move(link=True) + self.i.move(operation=MoveOperation.LINK) self.assertEqual(self.i.path, util.normpath(self.dest)) @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") def test_hardlink_arrives(self): - self.i.move(hardlink=True) + self.i.move(operation=MoveOperation.HARDLINK) self.assertExists(self.dest) s1 = os.stat(self.path) s2 = os.stat(self.dest) @@ -154,12 +155,12 @@ class MoveTest(_common.TestCase): @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") def test_hardlink_does_not_depart(self): - self.i.move(hardlink=True) + self.i.move(operation=MoveOperation.HARDLINK) self.assertExists(self.path) @unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks") def test_hardlink_changes_path(self): - self.i.move(hardlink=True) + self.i.move(operation=MoveOperation.HARDLINK) self.assertEqual(self.i.path, util.normpath(self.dest)) @@ -236,7 +237,7 @@ class AlbumFileTest(_common.TestCase): def test_albuminfo_move_copies_file(self): oldpath = self.i.path self.ai.album = u'newAlbumName' - self.ai.move(True) + self.ai.move(operation=MoveOperation.COPY) self.ai.store() self.i.load() @@ -311,7 +312,7 @@ class ArtFileTest(_common.TestCase): i2.path = self.i.path i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) self.assertEqual(ai.artpath, None) ai.set_art(newart) @@ -327,7 +328,7 @@ class ArtFileTest(_common.TestCase): i2.path = self.i.path i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) ai.set_art(newart) # Set the art again. @@ -341,7 +342,7 @@ class ArtFileTest(_common.TestCase): i2.path = self.i.path i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) # Copy the art to the destination. artdest = ai.art_destination(newart) @@ -358,7 +359,7 @@ class ArtFileTest(_common.TestCase): i2.path = self.i.path i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) # Make a file at the destination. artdest = ai.art_destination(newart) @@ -382,7 +383,7 @@ class ArtFileTest(_common.TestCase): i2.path = self.i.path i2.artist = u'someArtist' ai = self.lib.add_album((i2,)) - i2.move(True) + i2.move(operation=MoveOperation.COPY) ai.set_art(newart) mode = stat.S_IMODE(os.stat(ai.artpath).st_mode) diff --git a/test/test_ui.py b/test/test_ui.py index 04c033f51..77804d3d2 100644 --- a/test/test_ui.py +++ b/test/test_ui.py @@ -40,7 +40,7 @@ from beets import config from beets import plugins from beets.util.confit import ConfigError from beets import util -from beets.util import syspath +from beets.util import syspath, MoveOperation class ListTest(unittest.TestCase): @@ -126,7 +126,7 @@ class RemoveTest(_common.TestCase): item_path = os.path.join(_common.RSRC, b'full.mp3') self.i = library.Item.from_path(item_path) self.lib.add(self.i) - self.i.move(True) + self.i.move(operation=MoveOperation.COPY) def test_remove_items_no_delete(self): self.io.addinput('y') @@ -509,7 +509,7 @@ class UpdateTest(_common.TestCase): item_path = os.path.join(_common.RSRC, b'full.mp3') self.i = library.Item.from_path(item_path) self.lib.add(self.i) - self.i.move(True) + self.i.move(operation=MoveOperation.COPY) self.album = self.lib.add_album([self.i]) # Album art. From edd2d42cd0cbc10e66567fa8c7bdef62fc770862 Mon Sep 17 00:00:00 2001 From: zigarrre Date: Mon, 11 Sep 2017 17:29:57 +0200 Subject: [PATCH 2107/2280] Shortened two lines that where to long. --- beets/library.py | 5 +++-- beets/util/__init__.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/beets/library.py b/beets/library.py index dd9081d10..597cfe625 100644 --- a/beets/library.py +++ b/beets/library.py @@ -778,8 +778,9 @@ class Item(LibModel): By default, the item is stored to the database if it is in the database, so any dirty fields prior to the move() call will be written - as a side effect. If `store` is `False` however, the item won't be stored, - and you'll have to manually store it after invoking this method. + as a side effect. + If `store` is `False` however, the item won't be stored and you'll + have to manually store it after invoking this method. """ self._check_db() dest = self.destination(basedir=basedir) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index 6673c61e3..db341a646 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -126,7 +126,7 @@ class FilesystemError(HumanReadableException): class MoveOperation(Enum): - """Represents the file operations that e.g. various move functions can carry out. + """The file operations that e.g. various move functions can carry out. """ MOVE = 0 COPY = 1 From e30513db9bd2743820f4ccfadd46fb29d0b054e3 Mon Sep 17 00:00:00 2001 From: zigarrre Date: Tue, 12 Sep 2017 18:19:18 +0200 Subject: [PATCH 2108/2280] Added the default ignore list of flake8 This fixes the W503 warnings and possibly other, unwanted errors and warnings in the future. --- setup.cfg | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.cfg b/setup.cfg index 913880415..a40d74964 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,8 +5,8 @@ logging-clear-handlers=1 [flake8] min-version=2.7 accept-encodings=utf-8 -# Default pyflakes errors we ignore: -# - E241: missing whitespace after ',' (used to align visually) +# Errors we ignore: +# - E121,E123,E126,E226,E24,E704,W503,W504 flake8 default ignores (have to be listed here to not be overridden) # - E221: multiple spaces before operator (used to align visually) # - E731: do not assign a lambda expression, use a def # - F405 object may be undefined, or defined from star imports @@ -19,4 +19,4 @@ accept-encodings=utf-8 # - FI53: `__future__` import "print_function" present # - FI14: `__future__` import "unicode_literals" missing # - FI15: `__future__` import "generator_stop" missing -ignore=E305,C901,E241,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 +ignore=E121,E123,E126,E226,E24,E704,W503,W504,E305,C901,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 From 61b02466510148ce1a9a2550183a1e575fbbb845 Mon Sep 17 00:00:00 2001 From: David Logie Date: Sat, 9 Sep 2017 22:20:41 +0100 Subject: [PATCH 2109/2280] mbcollection: Add support from removing albums. Add a new ``mbcollection.remove`` configuration option (default: None) and a new ``-r`` (``--remove``) flag which removes albums from collections that are no longer present in the beets database. The ``-r`` flag takes precedence over the ``remove`` configuration option. --- beetsplug/mbcollection.py | 50 ++++++++++++++++++++++++++++++++--- docs/changelog.rst | 2 ++ docs/plugins/mbcollection.rst | 9 +++++++ 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index bd6e84188..2f2f2a80c 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -24,6 +24,7 @@ import musicbrainzngs import re SUBMISSION_CHUNK_SIZE = 200 +FETCH_CHUNK_SIZE = 100 UUID_REGEX = r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$' @@ -63,6 +64,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): self.config.add({ 'auto': False, 'collection': u'', + 'remove': False, }) if self.config['auto']: self.import_stages = [self.imported] @@ -88,22 +90,62 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): # No specified collection. Just return the first collection ID return collection_ids[0] + def _get_albums_in_collection(self, id): + def _fetch(offset): + res = mb_call( + musicbrainzngs.get_releases_in_collection, + id, + limit=FETCH_CHUNK_SIZE, + offset=offset + )['collection'] + return [x['id'] for x in res['release-list']], res['release-count'] + + offset = 0 + albums_in_collection, release_count = _fetch(offset) + for i in range(0, release_count, FETCH_CHUNK_SIZE): + offset += FETCH_CHUNK_SIZE + albums_in_collection += _fetch(offset)[0] + + return albums_in_collection + def commands(self): mbupdate = Subcommand('mbupdate', help=u'Update MusicBrainz collection') + mbupdate.parser.add_option('-r', '--remove', + action='store_true', default=None, + dest='remove_missing', + help='Remove albums not in beets library') mbupdate.func = self.update_collection return [mbupdate] + def remove_missing(self, collection_id, lib_albums): + lib_ids = set([x.mb_albumid for x in lib_albums]) + albums_in_collection = self._get_albums_in_collection(collection_id) + remove_me = list(lib_ids - set(albums_in_collection)) + for i in range(0, len(remove_me), FETCH_CHUNK_SIZE): + chunk = remove_me[i:i + FETCH_CHUNK_SIZE] + mb_call( + musicbrainzngs.remove_releases_from_collection, + collection_id, chunk + ) + def update_collection(self, lib, opts, args): - self.update_album_list(lib.albums()) + # If the ``-r`` option is not given then fall back to the + # config defaults. + if opts.remove_missing is None: + remove_missing = self.config['remove'].get(bool) + else: + remove_missing = opts.remove_missing + + self.update_album_list(lib, lib.albums(), remove_missing) def imported(self, session, task): """Add each imported album to the collection. """ if task.is_album: - self.update_album_list([task.album]) + self.update_album_list(session.lib, [task.album]) - def update_album_list(self, album_list): + def update_album_list(self, lib, album_list, remove_missing=False): """Update the MusicBrainz collection from a list of Beets albums """ collection_id = self._get_collection() @@ -123,4 +165,6 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): u'Updating MusicBrainz collection {0}...', collection_id ) submit_albums(collection_id, album_ids) + if remove_missing: + self.remove_missing(collection_id, lib.albums()) self._log.info(u'...MusicBrainz collection updated.') diff --git a/docs/changelog.rst b/docs/changelog.rst index f8b8ad1cd..3574060d2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,8 @@ New features: * :doc:`/plugins/mbcollection`: The plugin now supports a custom MusicBrainz collection via the ``collection`` configuration option. :bug:`2685` +* :doc:`/plugins/mbcollection`: The plugin now supports removing albums + from collections that are longer in the beets library. Fixes: diff --git a/docs/plugins/mbcollection.rst b/docs/plugins/mbcollection.rst index f48996164..803d34904 100644 --- a/docs/plugins/mbcollection.rst +++ b/docs/plugins/mbcollection.rst @@ -20,6 +20,12 @@ command automatically adds all of your albums to the first collection it finds. If you don't have a MusicBrainz collection yet, you may need to add one to your profile first. +The command has one command-line option: + +* To remove albums from the collection which are no longer present in + the beets database, use the ``-r`` (``--remove``) flag. + + Configuration ------------- @@ -31,3 +37,6 @@ configuration file. There is one option available: Default: ``no``. - **collection**: Which MusicBrainz collection to update. Default: ``None``. +- **remove**: Remove albums from collections which are no longer + present in the beets database. + Default: ``None``. From bed003f97bc1ebcf85854bb1ea431294f4ecf20c Mon Sep 17 00:00:00 2001 From: David Logie Date: Mon, 18 Sep 2017 18:19:51 +0100 Subject: [PATCH 2110/2280] Use the built-in method of overriding config with cli options. --- beetsplug/mbcollection.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index 2f2f2a80c..bd081c3e2 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -112,8 +112,9 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): mbupdate = Subcommand('mbupdate', help=u'Update MusicBrainz collection') mbupdate.parser.add_option('-r', '--remove', - action='store_true', default=None, - dest='remove_missing', + action='store_true', + default=False, + dest='remove', help='Remove albums not in beets library') mbupdate.func = self.update_collection return [mbupdate] @@ -130,13 +131,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): ) def update_collection(self, lib, opts, args): - # If the ``-r`` option is not given then fall back to the - # config defaults. - if opts.remove_missing is None: - remove_missing = self.config['remove'].get(bool) - else: - remove_missing = opts.remove_missing - + self.config.set_args(opts) + remove_missing = self.config['remove'].get(bool) self.update_album_list(lib, lib.albums(), remove_missing) def imported(self, session, task): From 114a6f80da4d0c71f556dbeb602ba27238dd3acb Mon Sep 17 00:00:00 2001 From: Jonas Wagner Date: Fri, 22 Sep 2017 13:44:59 +0200 Subject: [PATCH 2111/2280] Fix the --key option in the `duplicates` plugin. During a refactoring, the "dest='keys'" parameter was lost. This caused the option to not have any effect. --- beetsplug/duplicates.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index f63a7be20..2584e6628 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -81,7 +81,7 @@ class DuplicatesPlugin(BeetsPlugin): help=u'report duplicates only if all attributes are set', ) self._command.parser.add_option( - u'-k', u'--key', + u'-k', u'--key', dest='keys', action='append', metavar='KEY', help=u'report duplicates based on keys (use multiple times)', ) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3574060d2..860f58256 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -45,6 +45,8 @@ Fixes: Python 3 on Windows with non-ASCII filenames. :bug:`2671` * :doc:`/plugins/absubmit`: Fix an occasional crash on Python 3 when the AB analysis tool produced non-ASCII metadata. :bug:`2673` +* :doc:`/plugins/duplicates`: Fix the `--key` command line option, which was + ignored. For developers: From d7abf0b8e132dcb3d0be62e521c0198c1cfa4b84 Mon Sep 17 00:00:00 2001 From: Jonas Wagner Date: Fri, 22 Sep 2017 15:00:59 +0200 Subject: [PATCH 2112/2280] Update GStreamer installation instructions for Mac OS X. --- docs/plugins/bpd.rst | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/plugins/bpd.rst b/docs/plugins/bpd.rst index 9c55594a7..fc22846de 100644 --- a/docs/plugins/bpd.rst +++ b/docs/plugins/bpd.rst @@ -16,10 +16,8 @@ Dependencies Before you can use BPD, you'll need the media library called GStreamer (along with its Python bindings) on your system. -* On Mac OS X, you can use `Homebrew`_. Run ``brew install gstreamer`` and then - ``brew install pygobject3``. - -.. _homebrew-versions: https://github.com/Homebrew/homebrew-versions +* On Mac OS X, you can use `Homebrew`_. Run ``brew install gstreamer + gst-plugins-base pygobject3``. * On Linux, you need to install GStreamer 1.0 and the GObject bindings for python. Under Ubuntu, they are called `python-gi` and `gstreamer1.0`. From 77e8f21094672f9d2297fab3b12f1bbb3c251b40 Mon Sep 17 00:00:00 2001 From: j000 Date: Tue, 26 Sep 2017 03:20:00 +0200 Subject: [PATCH 2113/2280] [Play plugin]Respect relative paths when using albums --- beetsplug/play.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index 8477acbfc..b540d7b9b 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -116,9 +116,10 @@ class PlayPlugin(BeetsPlugin): else: selection = lib.items(ui.decargs(args)) paths = [item.path for item in selection] - if relative_to: - paths = [relpath(path, relative_to) for path in paths] item_type = 'track' + + if relative_to: + paths = [relpath(path, relative_to) for path in paths] if not selection: ui.print_(ui.colorize('text_warning', From 5a82c7ead1fd1adc20d4ecaf3ae88578c982ee89 Mon Sep 17 00:00:00 2001 From: j000 Date: Wed, 27 Sep 2017 23:31:35 +0200 Subject: [PATCH 2114/2280] Remove whitespaces from empty line --- beetsplug/play.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/play.py b/beetsplug/play.py index b540d7b9b..4d32a3576 100644 --- a/beetsplug/play.py +++ b/beetsplug/play.py @@ -117,7 +117,7 @@ class PlayPlugin(BeetsPlugin): selection = lib.items(ui.decargs(args)) paths = [item.path for item in selection] item_type = 'track' - + if relative_to: paths = [relpath(path, relative_to) for path in paths] From e08f28d8656e01552e05bcf222834982dd8d0665 Mon Sep 17 00:00:00 2001 From: "nath@dp7510" Date: Mon, 2 Oct 2017 09:15:25 +0200 Subject: [PATCH 2115/2280] Changelog for #2702 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 860f58256..19789b957 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -20,6 +20,10 @@ New features: Fixes: +* :doc:`/plugins/play`: When ``relative_to`` is set, correctly emit relative paths + even when querying for albums rather than tracks. + Thanks to :user:`j000`. + :bug:`2702` * Prevent Python from warning about a ``BrokenPipeError`` being ignored even though we do take it into account. This was an issue when using beets in simple shell scripts. From eb338d208be0698de95c35f7d19fd95b9e91a9f7 Mon Sep 17 00:00:00 2001 From: gdtwst Date: Wed, 4 Oct 2017 16:35:22 +0700 Subject: [PATCH 2116/2280] Register song changes when switching from song to stream URL --- beetsplug/mpdstats.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index bcc3da808..11fb44e4d 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -256,10 +256,6 @@ class MPDStats(object): if not path: return - if is_url(path): - self._log.info(u'playing stream {0}', displayable_path(path)) - return - played, duration = map(int, status['time'].split(':', 1)) remaining = duration - played @@ -276,6 +272,11 @@ class MPDStats(object): if diff <= self.time_threshold: return + if is_url(path): + self._log.info(u'playing stream {0}', displayable_path(path)) + self.now_playing = None + return + self._log.info(u'playing {0}', displayable_path(path)) self.now_playing = { From c2770a5f6b2d3e4aa90d48a5d50a88f62473ab07 Mon Sep 17 00:00:00 2001 From: gdtwst Date: Wed, 4 Oct 2017 19:10:59 +0700 Subject: [PATCH 2117/2280] Enable play counts for repeated plays of the same song. --- beetsplug/mpdstats.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index 11fb44e4d..df016c77e 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -271,6 +271,9 @@ class MPDStats(object): if diff <= self.time_threshold: return + + if self.now_playing['path'] == path and played == 0: + self.handle_song_change(self.now_playing) if is_url(path): self._log.info(u'playing stream {0}', displayable_path(path)) From bd6645d1351a87740cd5797178ec54a945816630 Mon Sep 17 00:00:00 2001 From: Heinz Wiesinger Date: Fri, 28 Jul 2017 21:06:25 +0200 Subject: [PATCH 2118/2280] Fix album replaygain calculation with gstreamer backend. Fixes #2636 --- beetsplug/replaygain.py | 4 ++++ docs/changelog.rst | 2 ++ 2 files changed, 6 insertions(+) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 8b4172a5a..a70f9384b 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -606,6 +606,10 @@ class GStreamerBackend(Backend): self._decbin.sync_state_with_parent() self._decbin.get_state(self.Gst.CLOCK_TIME_NONE) + self._decbin.link(self._conv) + self._pipe.set_state(self.Gst.State.READY) + self._pipe.set_state(self.Gst.State.PLAYING) + return True def _set_next_file(self): diff --git a/docs/changelog.rst b/docs/changelog.rst index 19789b957..20026b3b9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -51,6 +51,8 @@ Fixes: analysis tool produced non-ASCII metadata. :bug:`2673` * :doc:`/plugins/duplicates`: Fix the `--key` command line option, which was ignored. +* :doc:`/plugins/replaygain`: Fix album replaygain calculation with the + gstreamer backend. :bug:`2636` For developers: From e5afc5e0b3c77570369a8e2940b1cdd68092ca23 Mon Sep 17 00:00:00 2001 From: gdtwst Date: Sat, 7 Oct 2017 19:00:08 +0700 Subject: [PATCH 2119/2280] Remove whitespaces from empty line --- beetsplug/mpdstats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/mpdstats.py b/beetsplug/mpdstats.py index df016c77e..e5e82d480 100644 --- a/beetsplug/mpdstats.py +++ b/beetsplug/mpdstats.py @@ -271,7 +271,7 @@ class MPDStats(object): if diff <= self.time_threshold: return - + if self.now_playing['path'] == path and played == 0: self.handle_song_change(self.now_playing) From dd32128fd5e7973b6d43e5d41ad3c8e3d982bac2 Mon Sep 17 00:00:00 2001 From: gdtwst Date: Sat, 7 Oct 2017 20:04:37 +0700 Subject: [PATCH 2120/2280] Changelog for #2707 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 19789b957..8779a9e2e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -17,6 +17,8 @@ New features: :bug:`2685` * :doc:`/plugins/mbcollection`: The plugin now supports removing albums from collections that are longer in the beets library. +* :doc:`/plugins/mpdstats`: The plugin now updates song stats when MPD switches + from a song to a stream and when it plays the same song consecutively. Fixes: From e370286c2f0a263ddd5eae163a905de88127473c Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 7 Oct 2017 12:07:57 -0400 Subject: [PATCH 2121/2280] Add bug reference --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 46f3c07a9..16de3486c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -19,6 +19,7 @@ New features: from collections that are longer in the beets library. * :doc:`/plugins/mpdstats`: The plugin now updates song stats when MPD switches from a song to a stream and when it plays the same song consecutively. + :bug:`2707` Fixes: From fdeef05cc95b881edd08ddf74b2037f03c5e5417 Mon Sep 17 00:00:00 2001 From: konman2 Date: Sat, 7 Oct 2017 20:42:01 -0700 Subject: [PATCH 2122/2280] clearart asks for permission before deleting embedded albumart --- beetsplug/embedart.py | 8 +++++++- docs/plugins/embedart.rst | 3 ++- test/test_embedart.py | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 51d401af8..65aa53433 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -163,8 +163,14 @@ class EmbedCoverArtPlugin(BeetsPlugin): 'clearart', help=u'remove images from file metadata', ) - + clear_cmd.parser.add_option( + u"-y", u"--yes", action="store_true", help=u"skip confirmation" + ) def clear_func(lib, opts, args): + items = lib.items(decargs(args)) + # Confirm with user. + if not opts.yes and not _confirm(items, False): + return art.clear(self._log, lib, decargs(args)) clear_cmd.func = clear_func diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index 68ea0f664..c31284a54 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -99,4 +99,5 @@ embedded album art: automatically. * ``beet clearart QUERY``: removes all embedded images from all items matching - the query. (Use with caution!) + the query. (Use with caution!) The command prompts for confirmation before + making the change unless you specify the ``-y`` (``--yes``) option. \ No newline at end of file diff --git a/test/test_embedart.py b/test/test_embedart.py index 1622fffb4..7023d7cbe 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -195,6 +195,30 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.assertExists(os.path.join(albumpath, b'extracted.jpg')) + def test_clear_art_with_yes_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + self.io.addinput('y') + self.run_command('clearart') + mediafile = MediaFile(syspath(item.path)) + #print(mediafile.images[0].data == self.image_data) + self.assertEqual(len(mediafile.images), 0) + + def test_clear_art_with_no_input(self): + self._setup_data() + album = self.add_album_fixture() + item = album.items()[0] + self.io.addinput('y') + self.run_command('embedart', '-f', self.small_artpath) + self.io.addinput('n') + self.run_command('clearart') + mediafile = MediaFile(syspath(item.path)) + #print(mediafile.images[0].data == self.image_data) + self.assertEqual(mediafile.images[0].data, self.image_data) + @patch('beets.art.subprocess') @patch('beets.art.extract') From 578143ae124d4fa5f7f09188e16f5dcda094a78d Mon Sep 17 00:00:00 2001 From: konman2 Date: Sat, 7 Oct 2017 21:28:33 -0700 Subject: [PATCH 2123/2280] updated to pass pep8 checks --- beetsplug/embedart.py | 1 + test/test_embedart.py | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/embedart.py b/beetsplug/embedart.py index 65aa53433..afe8f86fa 100644 --- a/beetsplug/embedart.py +++ b/beetsplug/embedart.py @@ -166,6 +166,7 @@ class EmbedCoverArtPlugin(BeetsPlugin): clear_cmd.parser.add_option( u"-y", u"--yes", action="store_true", help=u"skip confirmation" ) + def clear_func(lib, opts, args): items = lib.items(decargs(args)) # Confirm with user. diff --git a/test/test_embedart.py b/test/test_embedart.py index 7023d7cbe..049e4694d 100644 --- a/test/test_embedart.py +++ b/test/test_embedart.py @@ -204,9 +204,8 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.io.addinput('y') self.run_command('clearart') mediafile = MediaFile(syspath(item.path)) - #print(mediafile.images[0].data == self.image_data) self.assertEqual(len(mediafile.images), 0) - + def test_clear_art_with_no_input(self): self._setup_data() album = self.add_album_fixture() @@ -216,7 +215,6 @@ class EmbedartCliTest(_common.TestCase, TestHelper): self.io.addinput('n') self.run_command('clearart') mediafile = MediaFile(syspath(item.path)) - #print(mediafile.images[0].data == self.image_data) self.assertEqual(mediafile.images[0].data, self.image_data) From 1b35a5df0db707150e4a790ec2e3dfc8f4f2357b Mon Sep 17 00:00:00 2001 From: Lucas Magno Date: Sun, 8 Oct 2017 09:13:51 -0300 Subject: [PATCH 2124/2280] Fetch lyrics from Genius through scraper --- beetsplug/lyrics.py | 113 +++++++++++++------------------------------- 1 file changed, 33 insertions(+), 80 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index d7fca27c2..025a1374c 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -335,8 +335,11 @@ class MusiXmatch(SymbolsReplaced): class Genius(Backend): - """Fetch lyrics from Genius via genius-api.""" - + """Fetch lyrics from Genius via genius-api. + Simply adapted from https://bigishdata.com/2016/09/27/getting-song-lyrics-from-geniuss-api-scraping/""" + + base_url = "https://api.genius.com" + def __init__(self, config, log): super(Genius, self).__init__(config, log) self.api_key = config['genius_api_key'].as_str() @@ -345,85 +348,35 @@ class Genius(Backend): 'User-Agent': USER_AGENT, } - def search_genius(self, artist, title): - query = u"%s %s" % (artist, title) - url = u'https://api.genius.com/search?q=%s' \ - % (urllib.parse.quote(query.encode('utf-8'))) - - self._log.debug(u'genius: requesting search {}', url) - try: - req = requests.get( - url, - headers=self.headers, - allow_redirects=True - ) - req.raise_for_status() - except requests.RequestException as exc: - self._log.debug(u'genius: request error: {}', exc) - return None - - try: - return req.json() - except ValueError: - self._log.debug(u'genius: invalid response: {}', req.text) - return None - - def get_lyrics(self, link): - url = u'http://genius-api.com/api/lyricsInfo' - - self._log.debug(u'genius: requesting lyrics for link {}', link) - try: - req = requests.post( - url, - data={'link': link}, - headers=self.headers, - allow_redirects=True - ) - req.raise_for_status() - except requests.RequestException as exc: - self._log.debug(u'genius: request error: {}', exc) - return None - - try: - return req.json() - except ValueError: - self._log.debug(u'genius: invalid response: {}', req.text) - return None - - def build_lyric_string(self, lyrics): - if 'lyrics' not in lyrics: - return - sections = lyrics['lyrics']['sections'] - - lyrics_list = [] - for section in sections: - lyrics_list.append(section['name']) - lyrics_list.append('\n') - for verse in section['verses']: - if 'content' in verse: - lyrics_list.append(verse['content']) - - return ''.join(lyrics_list) + def lyrics_from_song_api_path(self, song_api_path): + song_url = self.base_url + song_api_path + response = requests.get(song_url, headers=self.headers) + json = response.json() + path = json["response"]["song"]["path"] + #gotta go regular html scraping... come on Genius + page_url = "https://genius.com" + path + page = requests.get(page_url) + html = BeautifulSoup(page.text, "html.parser") + #remove script tags that they put in the middle of the lyrics + [h.extract() for h in html('script')] + #at least Genius is nice and has a tag called 'lyrics'! + lyrics = html.find("div", class_="lyrics").get_text() #updated css where the lyrics are based in HTML + return lyrics def fetch(self, artist, title): - search_data = self.search_genius(artist, title) - if not search_data: - return - - if not search_data['meta']['status'] == 200: - return - else: - records = search_data['response']['hits'] - if not records: - return - - record_url = records[0]['result']['url'] - lyric_data = self.get_lyrics(record_url) - if not lyric_data: - return - lyrics = self.build_lyric_string(lyric_data) - - return lyrics + search_url = self.base_url + "/search" + data = {'q': title} + response = requests.get(search_url, data=data, headers=self.headers) + json = response.json() + + song_info = None + for hit in json["response"]["hits"]: + if hit["result"]["primary_artist"]["name"] == artist: + song_info = hit + break + if song_info: + song_api_path = song_info["result"]["api_path"] + return self.lyrics_from_song_api_path(song_api_path) class LyricsWiki(SymbolsReplaced): @@ -638,7 +591,7 @@ class Google(Backend): class LyricsPlugin(plugins.BeetsPlugin): - SOURCES = ['google', 'lyricwiki', 'musixmatch'] + SOURCES = ['google', 'lyricwiki', 'musixmatch', 'genius'] SOURCE_BACKENDS = { 'google': Google, 'lyricwiki': LyricsWiki, From 75c668b7d9b546cc722575429557210d476258a8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 8 Oct 2017 13:17:21 -0400 Subject: [PATCH 2125/2280] Remove a needless warning from docs (#2708) No need for caution anymore! :scream: With confirmation, we don't need this warning. --- docs/plugins/embedart.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/embedart.rst b/docs/plugins/embedart.rst index c31284a54..2a34a59e8 100644 --- a/docs/plugins/embedart.rst +++ b/docs/plugins/embedart.rst @@ -99,5 +99,5 @@ embedded album art: automatically. * ``beet clearart QUERY``: removes all embedded images from all items matching - the query. (Use with caution!) The command prompts for confirmation before - making the change unless you specify the ``-y`` (``--yes``) option. \ No newline at end of file + the query. The command prompts for confirmation before making the change + unless you specify the ``-y`` (``--yes``) option. From 1cff500b4b2b54bf6e171a9edf5e3b7a6a10ed34 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 8 Oct 2017 13:18:50 -0400 Subject: [PATCH 2126/2280] Changelog for #2708 (fixes #2427) --- docs/changelog.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 16de3486c..0346b48a4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -17,9 +17,13 @@ New features: :bug:`2685` * :doc:`/plugins/mbcollection`: The plugin now supports removing albums from collections that are longer in the beets library. -* :doc:`/plugins/mpdstats`: The plugin now updates song stats when MPD switches +* :doc:`/plugins/mpdstats`: The plugin now updates song stats when MPD switches from a song to a stream and when it plays the same song consecutively. :bug:`2707` +* :doc:`/plugins/fetchart`: The ``clearart`` command now asks for confirmation + before touching your files. + Thanks to :user:`konman2`. + :bug:`2708` :bug:`2427` Fixes: From fc2d379fb529000f825017e635a0baf0e86a1242 Mon Sep 17 00:00:00 2001 From: Lucas Magno Date: Mon, 9 Oct 2017 06:22:42 -0300 Subject: [PATCH 2127/2280] Comply with PEP8 --- beetsplug/lyrics.py | 67 +++++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 29 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 025a1374c..1987b67e7 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -336,10 +336,13 @@ class MusiXmatch(SymbolsReplaced): class Genius(Backend): """Fetch lyrics from Genius via genius-api. - Simply adapted from https://bigishdata.com/2016/09/27/getting-song-lyrics-from-geniuss-api-scraping/""" - + + Simply adapted from + bigishdata.com/2016/09/27/getting-song-lyrics-from-geniuss-api-scraping/ + """ + base_url = "https://api.genius.com" - + def __init__(self, config, log): super(Genius, self).__init__(config, log) self.api_key = config['genius_api_key'].as_str() @@ -349,34 +352,40 @@ class Genius(Backend): } def lyrics_from_song_api_path(self, song_api_path): - song_url = self.base_url + song_api_path - response = requests.get(song_url, headers=self.headers) - json = response.json() - path = json["response"]["song"]["path"] - #gotta go regular html scraping... come on Genius - page_url = "https://genius.com" + path - page = requests.get(page_url) - html = BeautifulSoup(page.text, "html.parser") - #remove script tags that they put in the middle of the lyrics - [h.extract() for h in html('script')] - #at least Genius is nice and has a tag called 'lyrics'! - lyrics = html.find("div", class_="lyrics").get_text() #updated css where the lyrics are based in HTML - return lyrics + song_url = self.base_url + song_api_path + response = requests.get(song_url, headers=self.headers) + json = response.json() + path = json["response"]["song"]["path"] + + # Gotta go regular html scraping... come on Genius. + page_url = "https://genius.com" + path + page = requests.get(page_url) + html = BeautifulSoup(page.text, "html.parser") + + # Remove script tags that they put in the middle of the lyrics. + [h.extract() for h in html('script')] + + # At least Genius is nice and has a tag called 'lyrics'! + # Updated css where the lyrics are based in HTML. + lyrics = html.find("div", class_="lyrics").get_text() + + return lyrics def fetch(self, artist, title): - search_url = self.base_url + "/search" - data = {'q': title} - response = requests.get(search_url, data=data, headers=self.headers) - json = response.json() - - song_info = None - for hit in json["response"]["hits"]: - if hit["result"]["primary_artist"]["name"] == artist: - song_info = hit - break - if song_info: - song_api_path = song_info["result"]["api_path"] - return self.lyrics_from_song_api_path(song_api_path) + search_url = self.base_url + "/search" + data = {'q': title} + response = requests.get(search_url, data=data, headers=self.headers) + json = response.json() + + song_info = None + for hit in json["response"]["hits"]: + if hit["result"]["primary_artist"]["name"] == artist: + song_info = hit + break + + if song_info: + song_api_path = song_info["result"]["api_path"] + return self.lyrics_from_song_api_path(song_api_path) class LyricsWiki(SymbolsReplaced): From db71710feae981525da6dc1e6f98667e6d85c080 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 9 Oct 2017 18:52:46 -0400 Subject: [PATCH 2128/2280] Changelog entry for #2709 Closes #2545. Closes #2246. --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0346b48a4..3e167b6c2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ New features: before touching your files. Thanks to :user:`konman2`. :bug:`2708` :bug:`2427` +* :doc:`/plugins/lyrics`: The Genius backend should work again. + Thanks to :user:`lmagno`. + :bug:`2709` Fixes: From 14476e2f8a4148a66dfe9f627c97dabd8ea31833 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Fri, 20 Oct 2017 14:49:53 -0400 Subject: [PATCH 2129/2280] scrub: Handle MutagenError (fix #2716) In older versions of Mutagen, an IOError indicated things like permissions errors. Now, a custom MutagenError is raised. Now we handle both. --- beetsplug/scrub.py | 3 ++- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/scrub.py b/beetsplug/scrub.py index b652fa2f5..be6e7fd1f 100644 --- a/beetsplug/scrub.py +++ b/beetsplug/scrub.py @@ -24,6 +24,7 @@ from beets import ui from beets import util from beets import config from beets import mediafile +import mutagen _MUTAGEN_FORMATS = { 'asf': 'ASF', @@ -106,7 +107,7 @@ class ScrubPlugin(BeetsPlugin): for tag in f.keys(): del f[tag] f.save() - except IOError as exc: + except (IOError, mutagen.MutagenError) as exc: self._log.error(u'could not scrub {0}: {1}', util.displayable_path(path), exc) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3e167b6c2..07d2dff74 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -63,6 +63,8 @@ Fixes: ignored. * :doc:`/plugins/replaygain`: Fix album replaygain calculation with the gstreamer backend. :bug:`2636` +* :doc:`/plugins/scrub`: Handle errors when manipulating files using newer + versions of Mutagen. :bug:`2716` For developers: From 7c9ce0da7a25b85846674c27f3618689cf9c2ba2 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 29 Oct 2017 16:29:06 -0400 Subject: [PATCH 2130/2280] Ignore yet another new flake8 error As described in PyCQA/pycodestyle#598, pycodestyle has exposed a new error for "ambiguous variable names." I really wish this project were less eager to add new warnings of questionable value that are enabled by default... --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index a40d74964..be2dbe543 100644 --- a/setup.cfg +++ b/setup.cfg @@ -19,4 +19,5 @@ accept-encodings=utf-8 # - FI53: `__future__` import "print_function" present # - FI14: `__future__` import "unicode_literals" missing # - FI15: `__future__` import "generator_stop" missing -ignore=E121,E123,E126,E226,E24,E704,W503,W504,E305,C901,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15 +# - E741: ambiguous variable name +ignore=E121,E123,E126,E226,E24,E704,W503,W504,E305,C901,E221,E731,F405,FI50,FI51,FI12,FI53,FI14,FI15,E741 From d64842ce5bf2ddec57078ca4d7345809b9693200 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 29 Oct 2017 22:23:47 -0400 Subject: [PATCH 2131/2280] Travis: more specific Python 2.7 release number Failures were cropping up due to a combination of a Travis problem where the Python version was reverted to Python 2.7.6: https://github.com/travis-ci/travis-ci/issues/8097 And a pylast update that called a function only available on Python 2.7.9 and above, discussed here: https://github.com/pylast/pylast/issues/201 I hope this fixes it... --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9a6236bed..13a23e8ff 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,7 @@ env: matrix: include: - - python: 2.7 + - python: 2.7.13 env: {TOX_ENV: py27-cov, COVERAGE: 1} - python: 2.7_with_system_site_packages env: {TOX_ENV: py27-test} @@ -25,7 +25,7 @@ matrix: # - env: {TOX_ENV: pypy-test} - python: 3.4 env: {TOX_ENV: py34-flake8} - - python: 2.7 + - python: 2.7.13 env: {TOX_ENV: docs} # Non-Python dependencies. addons: From 0c03d7e1a342305e464f6a367add3f3ab96b9059 Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 30 Oct 2017 08:41:49 +0200 Subject: [PATCH 2132/2280] Use 2.7.13 instead of 2.7_with_system_site_packages --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 13a23e8ff..2f15baf7e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ matrix: include: - python: 2.7.13 env: {TOX_ENV: py27-cov, COVERAGE: 1} - - python: 2.7_with_system_site_packages + - python: 2.7.13 env: {TOX_ENV: py27-test} - python: 3.4 env: {TOX_ENV: py34-test} From 5348d5ddc095d34ced2888d070d99476c3901f31 Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 30 Oct 2017 08:57:00 +0200 Subject: [PATCH 2133/2280] Update classifiers --- setup.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup.py b/setup.py index 06d35ae4a..24c571039 100755 --- a/setup.py +++ b/setup.py @@ -135,10 +135,13 @@ setup( 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Environment :: Web Environment', + 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: Implementation :: CPython', ], ) From 70f0bc5b6c8b2d0899ec1fe82f4879faebcd9cba Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Tue, 31 Oct 2017 11:28:44 +0530 Subject: [PATCH 2134/2280] Implement album merging for duplicates Fixes #112 --- beets/importer.py | 31 ++++++++++++++++++++++++++++++- beets/ui/commands.py | 4 +++- test/helper.py | 4 +++- test/test_importer.py | 6 ++++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index e7d8b40bc..b9c00c8c7 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -443,6 +443,7 @@ class ImportTask(BaseImportTask): self.candidates = [] self.rec = None self.should_remove_duplicates = False + self.should_merge_duplicates = False self.is_album = True self.search_ids = [] # user-supplied candidate IDs. @@ -1037,6 +1038,10 @@ class ArchiveImportTask(SentinelImportTask): self.extracted = True self.toppath = extract_to +class MergedImportTask(ImportTask): + def __init__(self, toppath, paths, items): + super(MergedImportTask, self).__init__(toppath, paths, items) + class ImportTaskFactory(object): """Generate album and singleton import tasks for all media files @@ -1352,7 +1357,27 @@ def user_query(session, task): ]) return pipeline.multiple(ipl.pull()) - resolve_duplicates(session, task) + if type(task) != MergedImportTask: + resolve_duplicates(session, task) + if task.should_merge_duplicates: + duplicate_items = task.duplicate_items(session.lib) + for item in duplicate_items: + item.id = None + item.album_id = None + + duplicate_paths = [item.path for item in duplicate_items] + + merged_task = MergedImportTask(None, + task.paths + duplicate_paths, + task.items + duplicate_items) + + ipl = pipeline.Pipeline([ + iter([merged_task]), + lookup_candidates(session), + user_query(session) + ]) + return pipeline.multiple(ipl.pull()) + apply_choice(session, task) return task @@ -1373,6 +1398,7 @@ def resolve_duplicates(session, task): u'skip': u's', u'keep': u'k', u'remove': u'r', + u'merge': u'm', u'ask': u'a', }) log.debug(u'default action for duplicates: {0}', duplicate_action) @@ -1386,6 +1412,9 @@ def resolve_duplicates(session, task): elif duplicate_action == u'r': # Remove old. task.should_remove_duplicates = True + elif duplicate_action == u'm': + # Merge duplicates together + task.should_merge_duplicates = True else: # No default action set; ask the session. session.resolve_duplicate(task, found_duplicates) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index a4b433925..c8beb11e2 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -791,7 +791,7 @@ class TerminalImportSession(importer.ImportSession): )) sel = ui.input_options( - (u'Skip new', u'Keep both', u'Remove old') + (u'Skip new', u'Keep both', u'Remove old', u'Merge all') ) if sel == u's': @@ -803,6 +803,8 @@ class TerminalImportSession(importer.ImportSession): elif sel == u'r': # Remove old. task.should_remove_duplicates = True + elif sel == u'm': + task.should_merge_duplicates = True else: assert False diff --git a/test/helper.py b/test/helper.py index ebf039fca..5b3bec8b5 100644 --- a/test/helper.py +++ b/test/helper.py @@ -535,7 +535,7 @@ class TestImportSession(importer.ImportSession): choose_item = choose_match - Resolution = Enum('Resolution', 'REMOVE SKIP KEEPBOTH') + Resolution = Enum('Resolution', 'REMOVE SKIP KEEPBOTH MERGE') default_resolution = 'REMOVE' @@ -553,6 +553,8 @@ class TestImportSession(importer.ImportSession): task.set_choice(importer.action.SKIP) elif res == self.Resolution.REMOVE: task.should_remove_duplicates = True + elif res == self.Resolution.MERGE: + task.should_merge_duplicates = True def generate_album_info(album_id, track_ids): diff --git a/test/test_importer.py b/test/test_importer.py index 1e0dd1fb9..c6b021f33 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -1248,6 +1248,12 @@ class ImportDuplicateAlbumTest(unittest.TestCase, TestHelper, item = self.lib.items().get() self.assertEqual(item.title, u't\xeftle 0') + def test_merge_duplicate_album(self): + self.importer.default_resolution = self.importer.Resolution.MERGE + self.importer.run() + + self.assertEqual(len(self.lib.albums()), 1) + def test_twice_in_import_dir(self): self.skipTest('write me') From 28fef2e77a9d58d1961a4f8f9eb1232996ccaf2a Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Wed, 1 Nov 2017 02:24:19 +0530 Subject: [PATCH 2135/2280] Fix flake8 errors --- beets/importer.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index b9c00c8c7..8541a2f95 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1038,6 +1038,7 @@ class ArchiveImportTask(SentinelImportTask): self.extracted = True self.toppath = extract_to + class MergedImportTask(ImportTask): def __init__(self, toppath, paths, items): super(MergedImportTask, self).__init__(toppath, paths, items) @@ -1367,9 +1368,8 @@ def user_query(session, task): duplicate_paths = [item.path for item in duplicate_items] - merged_task = MergedImportTask(None, - task.paths + duplicate_paths, - task.items + duplicate_items) + merged_task = MergedImportTask(None, task.paths + duplicate_paths, + task.items + duplicate_items) ipl = pipeline.Pipeline([ iter([merged_task]), From abefae12a01ccf0f6a2a82fbc2be11e97ffd075b Mon Sep 17 00:00:00 2001 From: translit <4024096+translit@users.noreply.github.com> Date: Wed, 1 Nov 2017 08:06:30 +0100 Subject: [PATCH 2136/2280] Update fetchart.rst --- docs/plugins/fetchart.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 82918e051..e375f9f57 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -66,7 +66,7 @@ file. The available options are: flexible tag named ``art_source``. See below for the rationale behind this. Default: ``no``. -Note: ``minwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ +Note: ``maxwidth`` and ``enforce_ratio`` options require either `ImageMagick`_ or `Pillow`_. .. note:: From 7ea3192db74c64587bf88b8bd80b3167df166e13 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 1 Nov 2017 18:57:43 -0400 Subject: [PATCH 2137/2280] Mention backups in the main guide --- docs/guides/main.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index f0b3635c2..02296be51 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -182,6 +182,11 @@ here, including the directory and file naming scheme. See Importing Your Library ---------------------- +The next step is to import your music files into the beets library database. +Because this can involve moving files around, data loss is always a +possibility, so now would be a good time to make sure you have a recent backup +of all your music. We'll wait. + There are two good ways to bring your existing library into beets. You can either: (a) quickly bring all your files with all their current metadata into beets' database, or (b) use beets' highly-refined autotagger to find canonical From 0d8d1c3aee6059cf0085ef955100f29130b3fda0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Wed, 1 Nov 2017 19:13:42 -0400 Subject: [PATCH 2138/2280] Modify task recommendation and candidates This way, subsequent candidates can be exposed to plugins instead of just used locally to interact with the user. --- beets/ui/commands.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index a4b433925..133057b05 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -691,7 +691,6 @@ class TerminalImportSession(importer.ImportSession): return action # Loop until we have a choice. - candidates, rec = task.candidates, task.rec while True: # Ask for a choice from the user. The result of # `choose_candidate` may be an `importer.action`, an @@ -699,8 +698,8 @@ class TerminalImportSession(importer.ImportSession): # `PromptChoice`. choices = self._get_choices(task) choice = choose_candidate( - candidates, False, rec, task.cur_artist, task.cur_album, - itemcount=len(task.items), choices=choices + task.candidates, False, task.rec, task.cur_artist, + task.cur_album, itemcount=len(task.items), choices=choices ) # Basic choices that require no more action here. @@ -716,8 +715,8 @@ class TerminalImportSession(importer.ImportSession): return post_choice elif isinstance(post_choice, autotag.Proposal): # Use the new candidates and continue around the loop. - candidates = post_choice.candidates - rec = post_choice.recommendation + task.candidates = post_choice.candidates + task.rec = post_choice.recommendation # Otherwise, we have a specific match selection. else: From 4d4fb504d538bcbfb7e4dbefd5efa42bedcdf8cd Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Sat, 4 Nov 2017 01:33:19 +0530 Subject: [PATCH 2139/2280] Change to subset check for finding duplicates also implement repeating code as helper functions --- beets/importer.py | 87 +++++++++++++++++++++++------------------------ 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 8541a2f95..94594a2a2 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -633,10 +633,11 @@ class ImportTask(BaseImportTask): )) for album in lib.albums(duplicate_query): - # Check whether the album is identical in contents, in which - # case it is not a duplicate (will be replaced). + # Check whether the album paths are all present in the task + # i.e. album is being completely re-imported by the task, + # in which case it is not a duplicate (will be replaced). album_paths = set(i.path for i in album.items()) - if album_paths != task_paths: + if not (album_paths <= task_paths): duplicates.append(album) return duplicates @@ -1039,11 +1040,6 @@ class ArchiveImportTask(SentinelImportTask): self.toppath = extract_to -class MergedImportTask(ImportTask): - def __init__(self, toppath, paths, items): - super(MergedImportTask, self).__init__(toppath, paths, items) - - class ImportTaskFactory(object): """Generate album and singleton import tasks for all media files indicated by a path. @@ -1231,6 +1227,27 @@ class ImportTaskFactory(object): displayable_path(path), exc) +# Pipeline utilities + +def _freshen_items(items): + # Clear IDs from re-tagged items so they appear "fresh" when + # we add them back to the library. + for item in items: + item.id = None + item.album_id = None + + +def _extend_pipeline(tasks, *stages): + # Return pipeline extension for stages with list of tasks + if type(tasks) == list: + task_iter = iter(tasks) + else: + task_iter = tasks + + ipl = pipeline.Pipeline([task_iter] + list(stages)) + return pipeline.multiple(ipl.pull()) + + # Full-album pipeline stages. def read_tasks(session): @@ -1276,12 +1293,7 @@ def query_tasks(session): log.debug(u'yielding album {0}: {1} - {2}', album.id, album.albumartist, album.album) items = list(album.items()) - - # Clear IDs from re-tagged items so they appear "fresh" when - # we add them back to the library. - for item in items: - item.id = None - item.album_id = None + _freshen_items(items) task = ImportTask(None, [album.item_dir()], items) for task in task.handle_created(session): @@ -1341,42 +1353,29 @@ def user_query(session, task): yield new_task yield SentinelImportTask(task.toppath, task.paths) - ipl = pipeline.Pipeline([ - emitter(task), - lookup_candidates(session), - user_query(session), - ]) - return pipeline.multiple(ipl.pull()) + return _extend_pipeline(emitter(task), + lookup_candidates(session), + user_query(session)) # As albums: group items by albums and create task for each album if task.choice_flag is action.ALBUMS: - ipl = pipeline.Pipeline([ - iter([task]), - group_albums(session), - lookup_candidates(session), - user_query(session) - ]) - return pipeline.multiple(ipl.pull()) + return _extend_pipeline([task], + group_albums(session), + lookup_candidates(session), + user_query(session)) - if type(task) != MergedImportTask: - resolve_duplicates(session, task) - if task.should_merge_duplicates: - duplicate_items = task.duplicate_items(session.lib) - for item in duplicate_items: - item.id = None - item.album_id = None + resolve_duplicates(session, task) + if task.should_merge_duplicates: + duplicate_items = task.duplicate_items(session.lib) + _freshen_items(duplicate_items) + duplicate_paths = [item.path for item in duplicate_items] - duplicate_paths = [item.path for item in duplicate_items] + merged_task = ImportTask(None, task.paths + duplicate_paths, + task.items + duplicate_items) - merged_task = MergedImportTask(None, task.paths + duplicate_paths, - task.items + duplicate_items) - - ipl = pipeline.Pipeline([ - iter([merged_task]), - lookup_candidates(session), - user_query(session) - ]) - return pipeline.multiple(ipl.pull()) + return _extend_pipeline([merged_task], + lookup_candidates(session), + user_query(session)) apply_choice(session, task) return task From 1646da4d9c1d7353d3f7126efdfdbe85bc8d00ac Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Sat, 4 Nov 2017 03:08:53 +0530 Subject: [PATCH 2140/2280] Add comments and explain merge feature in config docs and guide --- beets/importer.py | 5 +++++ docs/guides/tagger.rst | 16 ++++++++++++---- docs/reference/config.rst | 11 ++++++----- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 94594a2a2..4af276abe 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -1365,8 +1365,13 @@ def user_query(session, task): user_query(session)) resolve_duplicates(session, task) + if task.should_merge_duplicates: + # Create a new task for tagging the current items + # and duplicates together duplicate_items = task.duplicate_items(session.lib) + + # duplicates would be reimported so make them look "fresh" _freshen_items(duplicate_items) duplicate_paths = [item.path for item in duplicate_items] diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index 4c9df42f8..db11dbcc6 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -234,17 +234,25 @@ If beets finds an album or item in your library that seems to be the same as the one you're importing, you may see a prompt like this:: This album is already in the library! - [S]kip new, Keep both, Remove old? + [S]kip new, Keep both, Remove old, Merge all? Beets wants to keep you safe from duplicates, which can be a real pain, so you -have three choices in this situation. You can skip importing the new music, +have four choices in this situation. You can skip importing the new music, choosing to keep the stuff you already have in your library; you can keep both -the old and the new music; or you can remove the existing music and choose the -new stuff. If you choose that last "trump" option, any duplicates will be +the old and the new music; you can remove the existing music and choose the +new stuff; or you can merge the newly imported album and existing duplicate +into one single album. +If you choose that "remove" option, any duplicates will be removed from your library database---and, if the corresponding files are located inside of your beets library directory, the files themselves will be deleted as well. +If you choose "merge", beets will try re-importing the existing and new tracks +as one bundle so they will get tagged together appropriately. +This is particularly helpful when you are importing extra tracks +of an album in your library with missing tracks, so beets will ask you the same +questions as it would if you were importing all tracks at once. + If you choose to keep two identically-named albums, beets can avoid storing both in the same directory. See :ref:`aunique` for details. diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 9faddd2d2..ce45a94ee 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -571,11 +571,12 @@ Default: ``yes``. duplicate_action ~~~~~~~~~~~~~~~~ -Either ``skip``, ``keep``, ``remove``, or ``ask``. Controls how duplicates -are treated in import task. "skip" means that new item(album or track) will be -skipped; "keep" means keep both old and new items; "remove" means remove old -item; "ask" means the user should be prompted for the action each time. -The default is ``ask``. +Either ``skip``, ``keep``, ``remove``, ``merge`` or ``ask``. +Controls how duplicates are treated in import task. +"skip" means that new item(album or track) will be skipped; +"keep" means keep both old and new items; "remove" means remove old +item; "merge" means merge into one album; "ask" means the user +should be prompted for the action each time. The default is ``ask``. .. _bell: From 83f2e4493680b1bfe3430298d8bd6e6e441a5e14 Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Sun, 5 Nov 2017 06:20:48 +0530 Subject: [PATCH 2141/2280] Mark merged items in session for future tasks --- beets/importer.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/beets/importer.py b/beets/importer.py index 4af276abe..7e5191399 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -188,6 +188,8 @@ class ImportSession(object): self.paths = paths self.query = query self._is_resuming = dict() + self._merged_items = set() + self._merged_dirs = set() # Normalize the paths. if self.paths: @@ -350,6 +352,24 @@ class ImportSession(object): self._history_dirs = history_get() return self._history_dirs + def already_merged(self, paths): + """Returns true if all the paths being imported were part of a merge + during previous tasks. + """ + for path in paths: + if path not in self._merged_items \ + and path not in self._merged_dirs: + return False + return True + + def mark_merged(self, paths): + """Mark paths and directories as merged for future reimport tasks. + """ + self._merged_items.update(paths) + dirs = set([os.path.dirname(path) if os.path.isfile(path) else path + for path in paths]) + self._merged_dirs.update(dirs) + def is_resuming(self, toppath): """Return `True` if user wants to resume import of this path. @@ -1339,6 +1359,9 @@ def user_query(session, task): if task.skip: return task + if session.already_merged(task.paths): + return pipeline.BUBBLE + # Ask the user for a choice. task.choose_match(session) plugins.send('import_task_choice', session=session, task=task) @@ -1371,10 +1394,13 @@ def user_query(session, task): # and duplicates together duplicate_items = task.duplicate_items(session.lib) - # duplicates would be reimported so make them look "fresh" + # Duplicates would be reimported so make them look "fresh" _freshen_items(duplicate_items) duplicate_paths = [item.path for item in duplicate_items] + # Record merged paths in the session so they are not reimported + session.mark_merged(duplicate_paths) + merged_task = ImportTask(None, task.paths + duplicate_paths, task.items + duplicate_items) From a6215f30a72976e8db2bd422e4ab842f85c9daaf Mon Sep 17 00:00:00 2001 From: Meet Udeshi Date: Sun, 5 Nov 2017 12:35:32 +0530 Subject: [PATCH 2142/2280] flake8 fixes --- beets/importer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index 7e5191399..e91b35656 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -358,7 +358,7 @@ class ImportSession(object): """ for path in paths: if path not in self._merged_items \ - and path not in self._merged_dirs: + and path not in self._merged_dirs: return False return True @@ -367,7 +367,7 @@ class ImportSession(object): """ self._merged_items.update(paths) dirs = set([os.path.dirname(path) if os.path.isfile(path) else path - for path in paths]) + for path in paths]) self._merged_dirs.update(dirs) def is_resuming(self, toppath): From 54297dbab43616e961fe9d4016f134d9928ef821 Mon Sep 17 00:00:00 2001 From: test Date: Sun, 5 Nov 2017 12:04:40 +0100 Subject: [PATCH 2143/2280] Tentative fix for issue 2734: also check for RETAG --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index a1153bd69..f0fef164e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -783,7 +783,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if task.choice_flag == importer.action.ASIS: # For as-is imports, don't search Web sources for art. local = True - elif task.choice_flag == importer.action.APPLY: + elif task.choice_flag in (importer.action.APPLY, importer.action.RETAG): # Search everywhere for art. local = False else: From 8544b3a830c3054a5e4d64ebba113a215aa308d4 Mon Sep 17 00:00:00 2001 From: test Date: Fri, 10 Nov 2017 13:46:26 +0100 Subject: [PATCH 2144/2280] Fix long line and add changelog entry --- beetsplug/fetchart.py | 3 ++- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index f0fef164e..5fed59484 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -783,7 +783,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if task.choice_flag == importer.action.ASIS: # For as-is imports, don't search Web sources for art. local = True - elif task.choice_flag in (importer.action.APPLY, importer.action.RETAG): + elif task.choice_flag in (importer.action.APPLY, + importer.action.RETAG): # Search everywhere for art. local = False else: diff --git a/docs/changelog.rst b/docs/changelog.rst index 07d2dff74..4eeadb2f6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -65,6 +65,8 @@ Fixes: gstreamer backend. :bug:`2636` * :doc:`/plugins/scrub`: Handle errors when manipulating files using newer versions of Mutagen. :bug:`2716` +* :doc:`/plugins/fetchart`: Fix: don't skip running the fetchart plugin during import, when the + "Edit Candidates" option is used. :bug:`2734` For developers: From 842f6afd7f91c34c1a0a25c92d4602c9dd34c9e0 Mon Sep 17 00:00:00 2001 From: test Date: Fri, 10 Nov 2017 14:04:16 +0100 Subject: [PATCH 2145/2280] Fix indentation --- beetsplug/fetchart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 5fed59484..8bee6e804 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -784,7 +784,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): # For as-is imports, don't search Web sources for art. local = True elif task.choice_flag in (importer.action.APPLY, - importer.action.RETAG): + importer.action.RETAG): # Search everywhere for art. local = False else: From 0c20147e142187429a7ad4038b8b539d1599e760 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 11 Nov 2017 11:05:43 -0500 Subject: [PATCH 2146/2280] Changelog for #2725 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4eeadb2f6..0cbfa27bd 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,10 @@ Changelog New features: +* When the importer finds duplicate albums, you can now merge all the tracks + together and try importing them as a single album. + Thanks to :user:`udiboy1209`. + :bug:`112` :bug:`2725` * :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. :bug:`2628` From 9657cf612e1ef16cb1e8090d6394f43153709be7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 11 Nov 2017 11:07:40 -0500 Subject: [PATCH 2147/2280] Revise importer guide text about merging --- docs/guides/tagger.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/guides/tagger.rst b/docs/guides/tagger.rst index db11dbcc6..b70857ca5 100644 --- a/docs/guides/tagger.rst +++ b/docs/guides/tagger.rst @@ -240,18 +240,18 @@ Beets wants to keep you safe from duplicates, which can be a real pain, so you have four choices in this situation. You can skip importing the new music, choosing to keep the stuff you already have in your library; you can keep both the old and the new music; you can remove the existing music and choose the -new stuff; or you can merge the newly imported album and existing duplicate -into one single album. +new stuff; or you can merge all the new and old tracks into a single album. If you choose that "remove" option, any duplicates will be removed from your library database---and, if the corresponding files are located inside of your beets library directory, the files themselves will be deleted as well. If you choose "merge", beets will try re-importing the existing and new tracks -as one bundle so they will get tagged together appropriately. -This is particularly helpful when you are importing extra tracks -of an album in your library with missing tracks, so beets will ask you the same -questions as it would if you were importing all tracks at once. +as one bundle together. +This is particularly helpful when you have an album that's missing some tracks +and then want to import the remaining songs. +The importer will ask you the same questions as it would if you were importing +all tracks at once. If you choose to keep two identically-named albums, beets can avoid storing both in the same directory. See :ref:`aunique` for details. From c10e62f2123246c6c55a19815f1960632fa781a1 Mon Sep 17 00:00:00 2001 From: David Logie Date: Mon, 13 Nov 2017 15:48:17 +0000 Subject: [PATCH 2148/2280] mbcollection: Fix default 'remove' value. If the default is not None the value cannot be overriden by the user's config.yaml. --- beetsplug/mbcollection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index bd081c3e2..c01d544a4 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -113,7 +113,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): help=u'Update MusicBrainz collection') mbupdate.parser.add_option('-r', '--remove', action='store_true', - default=False, + default=None, dest='remove', help='Remove albums not in beets library') mbupdate.func = self.update_collection From c40ea4f22a5cd3adebcb579a5366ac73263cbca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Reu=C3=9Fe?= Date: Sat, 18 Nov 2017 20:32:07 +0100 Subject: [PATCH 2149/2280] mediafile._safe_cast: be safer when converting to int MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The regex «[\+-]?[0-9]*» possibly matches a single minus/plus, which would then be passed on to int(), raising a ValueError from within _safe_cast. The test suite covered this for float, but not for int. We now make sure we actually have a number after the sign by using a Kleene plus. --- beets/mediafile.py | 7 ++----- docs/changelog.rst | 2 ++ test/test_mediafile_edge.py | 3 +++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/beets/mediafile.py b/beets/mediafile.py index b4c62612f..34ad49af7 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -159,11 +159,8 @@ def _safe_cast(out_type, val): elif not isinstance(val, six.string_types): val = six.text_type(val) # Get a number from the front of the string. - val = re.match(r'[\+-]?[0-9]*', val.strip()).group(0) - if not val: - return 0 - else: - return int(val) + match = re.match(r'[\+-]?[0-9]+', val.strip()) + return int(match.group(0)) if match else 0 elif out_type == bool: try: diff --git a/docs/changelog.rst b/docs/changelog.rst index 0cbfa27bd..0918a4967 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -71,6 +71,8 @@ Fixes: versions of Mutagen. :bug:`2716` * :doc:`/plugins/fetchart`: Fix: don't skip running the fetchart plugin during import, when the "Edit Candidates" option is used. :bug:`2734` +* Fix a crash when numeric metadata fields contain just a minus or plus sign + with no following numbers. For developers: diff --git a/test/test_mediafile_edge.py b/test/test_mediafile_edge.py index 657ca455d..8bf9e1916 100644 --- a/test/test_mediafile_edge.py +++ b/test/test_mediafile_edge.py @@ -105,6 +105,9 @@ class InvalidValueToleranceTest(unittest.TestCase): def test_safe_cast_string_to_int(self): self.assertEqual(_sc(int, u'something'), 0) + def test_safe_cast_string_to_int_with_no_numbers(self): + self.assertEqual(_sc(int, u'-'), 0) + def test_safe_cast_int_string_to_int(self): self.assertEqual(_sc(int, u'20'), 20) From 16592445b0f5ca7132a0ddef9e5c872ff9c17b92 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sun, 19 Nov 2017 10:51:32 -0500 Subject: [PATCH 2150/2280] Link to bug for #2741 --- docs/changelog.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 0918a4967..d20bc86f6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -72,7 +72,7 @@ Fixes: * :doc:`/plugins/fetchart`: Fix: don't skip running the fetchart plugin during import, when the "Edit Candidates" option is used. :bug:`2734` * Fix a crash when numeric metadata fields contain just a minus or plus sign - with no following numbers. + with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` For developers: From 585d4ba89d19da669def0cef38a94065158fd2b7 Mon Sep 17 00:00:00 2001 From: Barry Broderick Date: Mon, 20 Nov 2017 09:56:40 -0500 Subject: [PATCH 2151/2280] attempted fix for #2740 --- beetsplug/hook.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 833f0feaa..dac38be44 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -68,6 +68,8 @@ class CodingFormatter(string.Formatter): converted = converted.decode(self._coding) except UnicodeEncodeError: pass + except AttributeError: + converted = value return converted From a7818027ab83d98ba7a613d74c40455797c235c6 Mon Sep 17 00:00:00 2001 From: Barry Broderick Date: Mon, 20 Nov 2017 23:08:59 -0500 Subject: [PATCH 2152/2280] replaced the exception test in convert_field with an isinstance test --- beetsplug/hook.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index dac38be44..4f33906a4 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -64,13 +64,9 @@ class CodingFormatter(string.Formatter): converted = super(CodingFormatter, self).convert_field(value, conversion) - try: - converted = converted.decode(self._coding) - except UnicodeEncodeError: - pass - except AttributeError: - converted = value - + if isinstance(converted, bytes): + return converted.decode(self._coding) + return converted From 530beb6312795367a126b7bf15a03c38108b87b6 Mon Sep 17 00:00:00 2001 From: Barry Broderick Date: Wed, 22 Nov 2017 10:10:28 -0500 Subject: [PATCH 2153/2280] removed whitespaces from empty line --- beetsplug/hook.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/hook.py b/beetsplug/hook.py index 4f33906a4..b6270fd50 100644 --- a/beetsplug/hook.py +++ b/beetsplug/hook.py @@ -66,7 +66,7 @@ class CodingFormatter(string.Formatter): if isinstance(converted, bytes): return converted.decode(self._coding) - + return converted From 481378638242cf3137abadb097803de49fa86bcc Mon Sep 17 00:00:00 2001 From: Barry Broderick Date: Wed, 22 Nov 2017 10:21:00 -0500 Subject: [PATCH 2154/2280] updated changelog to include fix for #2740 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index d20bc86f6..fe19403f0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -34,6 +34,10 @@ New features: Fixes: +* :doc:`/plugins/hook`: Fixed a problem whereby accessing non-string properties of + objects such as item or album (e.g. item.track) would cause a crash. + Thanks to :user:`broddo`. + :bug:`2740` * :doc:`/plugins/play`: When ``relative_to`` is set, correctly emit relative paths even when querying for albums rather than tracks. Thanks to :user:`j000`. From 31d8d1f089b8a1323bf0d1fec3eb9266e758c2ff Mon Sep 17 00:00:00 2001 From: Joshua Strobl Date: Sat, 25 Nov 2017 18:19:26 +0200 Subject: [PATCH 2155/2280] Add Solus as an OS where beets is available. --- docs/guides/main.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index f0b3635c2..63e0f49c5 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -43,6 +43,8 @@ Beets works on `Python 2.7`_ and Python 3.4 or later. * On **Fedora** 22 or later, there is a `DNF package`_ (or three):: $ sudo dnf install beets beets-plugins beets-doc + +* On **Solus**, run ``eopkg install beets``. * On **NixOS**, run ``nix-env -i beets``. From f007468da3e3525efae0fad9cb0a1c5e1452bfa1 Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 25 Nov 2017 17:56:42 -0500 Subject: [PATCH 2156/2280] Mention file modification --- docs/guides/main.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guides/main.rst b/docs/guides/main.rst index 02296be51..f310e7d33 100644 --- a/docs/guides/main.rst +++ b/docs/guides/main.rst @@ -183,9 +183,9 @@ Importing Your Library ---------------------- The next step is to import your music files into the beets library database. -Because this can involve moving files around, data loss is always a -possibility, so now would be a good time to make sure you have a recent backup -of all your music. We'll wait. +Because this can involve modifying files and moving them around, data loss is +always a possibility, so now would be a good time to make sure you have a +recent backup of all your music. We'll wait. There are two good ways to bring your existing library into beets. You can either: (a) quickly bring all your files with all their current metadata into From 325ae6f0eea3c69a8f7a0cd394375eeb8a7d4928 Mon Sep 17 00:00:00 2001 From: Owen Parry Date: Mon, 27 Nov 2017 07:55:38 -0800 Subject: [PATCH 2157/2280] Add tags configuration to acousticbrainz plugin --- beetsplug/acousticbrainz.py | 18 +++++++++++++----- docs/plugins/acousticbrainz.rst | 4 +++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 4291d9117..cee765bbb 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -110,6 +110,7 @@ class AcousticPlugin(plugins.BeetsPlugin): self.config.add({ 'auto': True, 'force': False, + 'tags': [] }) if self.config['auto']: @@ -164,6 +165,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def _fetch_info(self, items, write, force): """Fetch additional information from AcousticBrainz for the `item`s. """ + tags = self.config['tags'].get() for item in items: # If we're not forcing re-downloading for all tracks, check # whether the data is already present. We use one @@ -183,11 +185,17 @@ class AcousticPlugin(plugins.BeetsPlugin): data = self._get_data(item.mb_trackid) if data: for attr, val in self._map_data_to_scheme(data, ABSCHEME): - self._log.debug(u'attribute {} of {} set to {}', - attr, - item, - val) - setattr(item, attr, val) + if not tags or attr in tags: + self._log.debug(u'attribute {} of {} set to {}', + attr, + item, + val) + setattr(item, attr, val) + else: + self._log.debug(u'skipping attribute {} of {} (value {}) due to config', + attr, + item, + val) item.store() if write: item.try_write() diff --git a/docs/plugins/acousticbrainz.rst b/docs/plugins/acousticbrainz.rst index bf2102790..5bd514c64 100644 --- a/docs/plugins/acousticbrainz.rst +++ b/docs/plugins/acousticbrainz.rst @@ -54,10 +54,12 @@ Configuration ------------- To configure the plugin, make a ``acousticbrainz:`` section in your -configuration file. There is one option: +configuration file. There are three options: - **auto**: Enable AcousticBrainz during ``beet import``. Default: ``yes``. - **force**: Download AcousticBrainz data even for tracks that already have it. Default: ``no``. +- **tags**: Which tags from the list above to set on your files. + Default: [] (all) From eaa84178f71427901c6d5b22e16fa70b953446c3 Mon Sep 17 00:00:00 2001 From: Owen Parry Date: Mon, 27 Nov 2017 09:11:53 -0800 Subject: [PATCH 2158/2280] split long line --- beetsplug/acousticbrainz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index cee765bbb..982f7829c 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -192,7 +192,8 @@ class AcousticPlugin(plugins.BeetsPlugin): val) setattr(item, attr, val) else: - self._log.debug(u'skipping attribute {} of {} (value {}) due to config', + self._log.debug(u'skipping attribute {} of {} (value {})' + u' due to config', attr, item, val) From a2393e48f250719e435901966b170bc819880fa9 Mon Sep 17 00:00:00 2001 From: Owen Parry Date: Mon, 27 Nov 2017 09:15:03 -0800 Subject: [PATCH 2159/2280] add changelog entry for acousticbrainz 'tag' option --- docs/changelog.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index fe19403f0..e3518cba6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -28,9 +28,9 @@ New features: before touching your files. Thanks to :user:`konman2`. :bug:`2708` :bug:`2427` -* :doc:`/plugins/lyrics`: The Genius backend should work again. - Thanks to :user:`lmagno`. - :bug:`2709` +* :doc:`/plugins/acousticbrainz`: The plugin can now be configured to write only + a specific list of tags. + Thanks to :user:`woparry`. Fixes: From 7265077e75e7f8c5ebb3bb42b3f85c5868ff43e0 Mon Sep 17 00:00:00 2001 From: Aaron Jubbal Date: Wed, 29 Nov 2017 16:13:38 -0800 Subject: [PATCH 2160/2280] `dont_convert` option implemented. Local testing indicates success. --- beetsplug/convert.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index ec4d7c62e..639741dc3 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -31,6 +31,8 @@ from beets.plugins import BeetsPlugin from beets.util.confit import ConfigTypeError from beets import art from beets.util.artresizer import ArtResizer +from beets.library import parse_query_string +from beets.library import Item _fs_lock = threading.Lock() _temp_files = [] # Keep track of temporary transcoded files for deletion. @@ -92,6 +94,12 @@ def should_transcode(item, fmt): """Determine whether the item should be transcoded as part of conversion (i.e., its bitrate is high or it has the wrong format). """ + dont_convert_queries = config['convert']['dont_convert'].as_str_seq() + if dont_convert_queries: + for query_string in dont_convert_queries: + query, _ = parse_query_string(query_string, Item) + if query.match(item): + return False if config['convert']['never_convert_lossy_files'] and \ not (item.format.lower() in LOSSLESS_FORMATS): return False From e5d782a3b1e79ff99512e1d3043e3871f5f258cf Mon Sep 17 00:00:00 2001 From: Aaron Jubbal Date: Wed, 29 Nov 2017 16:41:27 -0800 Subject: [PATCH 2161/2280] Added docs for dont_convert option. --- docs/plugins/convert.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 59036a38b..527bc5d01 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -73,6 +73,9 @@ file. The available options are: this does not guarantee that all converted files will have a lower bitrate---that depends on the encoder and its configuration. Default: none. +- **dont_convert**: Does not transcode items matching provided query string + (see :doc:`/reference/query`). (i.e. ``format:AAC, format:WMA`` or + ``path::\.(m4a|wma)$``) - **never_convert_lossy_files**: Cross-conversions between lossy codecs---such as mp3, ogg vorbis, etc.---makes little sense as they will decrease quality even further. If set to ``yes``, lossy files are always copied. From 0998d9f8ef5215f00db1e34562715833c2548a77 Mon Sep 17 00:00:00 2001 From: Aaron Jubbal Date: Wed, 29 Nov 2017 17:53:50 -0800 Subject: [PATCH 2162/2280] Added default value for dont_convert option, addressing crashes. --- beetsplug/convert.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 639741dc3..bb2aeae24 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -141,6 +141,7 @@ class ConvertPlugin(BeetsPlugin): u'quiet': False, u'embed': True, u'paths': {}, + u'dont_convert': u'', u'never_convert_lossy_files': False, u'copy_album_art': False, u'album_art_maxwidth': 0, From e24f732014b2ec8e00d3b79719052b4f5782f159 Mon Sep 17 00:00:00 2001 From: Aaron Jubbal Date: Wed, 29 Nov 2017 20:08:50 -0800 Subject: [PATCH 2163/2280] Changed `dont_convert` to `no_convert`. --- beetsplug/convert.py | 8 ++++---- docs/plugins/convert.rst | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index bb2aeae24..380061248 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -94,9 +94,9 @@ def should_transcode(item, fmt): """Determine whether the item should be transcoded as part of conversion (i.e., its bitrate is high or it has the wrong format). """ - dont_convert_queries = config['convert']['dont_convert'].as_str_seq() - if dont_convert_queries: - for query_string in dont_convert_queries: + no_convert_queries = config['convert']['no_convert'].as_str_seq() + if no_convert_queries: + for query_string in no_convert_queries: query, _ = parse_query_string(query_string, Item) if query.match(item): return False @@ -141,7 +141,7 @@ class ConvertPlugin(BeetsPlugin): u'quiet': False, u'embed': True, u'paths': {}, - u'dont_convert': u'', + u'no_convert': u'', u'never_convert_lossy_files': False, u'copy_album_art': False, u'album_art_maxwidth': 0, diff --git a/docs/plugins/convert.rst b/docs/plugins/convert.rst index 527bc5d01..a631f7891 100644 --- a/docs/plugins/convert.rst +++ b/docs/plugins/convert.rst @@ -73,7 +73,7 @@ file. The available options are: this does not guarantee that all converted files will have a lower bitrate---that depends on the encoder and its configuration. Default: none. -- **dont_convert**: Does not transcode items matching provided query string +- **no_convert**: Does not transcode items matching provided query string (see :doc:`/reference/query`). (i.e. ``format:AAC, format:WMA`` or ``path::\.(m4a|wma)$``) - **never_convert_lossy_files**: Cross-conversions between lossy codecs---such From 7138cae1083cf77c3b8e26795480d737f9cc8396 Mon Sep 17 00:00:00 2001 From: Aaron Jubbal Date: Wed, 29 Nov 2017 20:09:06 -0800 Subject: [PATCH 2164/2280] Updated changelog. --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index fe19403f0..9fba6392b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,9 @@ New features: * :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. :bug:`2628` +* :doc:`/plugins/convert`: Adds ``no_convert`` option which ignores transcoding + items matching provided query string. Thanks to :user:`Stunner`. + :bug:`2732` :bug:`2751` * :doc:`/plugins/fetchart`: The plugin has now a quiet switch that will only display missing album arts. Thanks to :user:`euri10`. :bug:`2683` From 1f45ea00f49ba6a9697333204dbfd67045d5a2c6 Mon Sep 17 00:00:00 2001 From: Owen Parry Date: Sat, 2 Dec 2017 11:31:31 -0800 Subject: [PATCH 2165/2280] use as_str_seq and fix line length --- beetsplug/acousticbrainz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beetsplug/acousticbrainz.py b/beetsplug/acousticbrainz.py index 982f7829c..f4960c301 100644 --- a/beetsplug/acousticbrainz.py +++ b/beetsplug/acousticbrainz.py @@ -165,7 +165,7 @@ class AcousticPlugin(plugins.BeetsPlugin): def _fetch_info(self, items, write, force): """Fetch additional information from AcousticBrainz for the `item`s. """ - tags = self.config['tags'].get() + tags = self.config['tags'].as_str_seq() for item in items: # If we're not forcing re-downloading for all tracks, check # whether the data is already present. We use one @@ -192,8 +192,8 @@ class AcousticPlugin(plugins.BeetsPlugin): val) setattr(item, attr, val) else: - self._log.debug(u'skipping attribute {} of {} (value {})' - u' due to config', + self._log.debug(u'skipping attribute {} of {}' + u' (value {}) due to config', attr, item, val) From e848adab0490621cbc5c3b3d7f7dcad0b5932ac3 Mon Sep 17 00:00:00 2001 From: tummychow Date: Thu, 7 Dec 2017 14:46:40 -0500 Subject: [PATCH 2166/2280] Implement from_scratch option Fixes #934, and also helps with #1173. --- beets/config_default.yaml | 1 + beets/importer.py | 4 ++++ beets/library.py | 5 +++++ beets/ui/commands.py | 4 ++++ docs/reference/cli.rst | 6 ++++++ docs/reference/config.rst | 9 +++++++++ test/test_importer.py | 11 +++++++++++ 7 files changed, 40 insertions(+) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 439a93f55..942459738 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -10,6 +10,7 @@ import: delete: no resume: ask incremental: no + from_scratch: no quiet_fallback: skip none_rec_action: ask timid: no diff --git a/beets/importer.py b/beets/importer.py index e91b35656..186d824b6 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -534,6 +534,10 @@ class ImportTask(BaseImportTask): def apply_metadata(self): """Copy metadata from match info to the items. """ + if config['import']['from_scratch']: + for item in self.match.mapping: + item.clear() + autotag.apply_metadata(self.match.info, self.match.mapping) def duplicate_items(self, lib): diff --git a/beets/library.py b/beets/library.py index 597cfe625..64035e642 100644 --- a/beets/library.py +++ b/beets/library.py @@ -561,6 +561,11 @@ class Item(LibModel): if self.mtime == 0 and 'mtime' in values: self.mtime = values['mtime'] + def clear(self): + """Set all key/value pairs to None.""" + for key in self._media_fields: + setattr(self, key, None) + def get_album(self): """Get the Album object that this item belongs to, if any, or None if the item is a singleton or is not associated with a diff --git a/beets/ui/commands.py b/beets/ui/commands.py index c8beb11e2..3a1811cf3 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1004,6 +1004,10 @@ import_cmd.parser.add_option( u'-I', u'--noincremental', dest='incremental', action='store_false', help=u'do not skip already-imported directories' ) +import_cmd.parser.add_option( + u'--from-scratch', dest='from_scratch', action='store_true', + help=u'erase existing metadata before applying new metadata' +) import_cmd.parser.add_option( u'--flat', dest='flat', action='store_true', help=u'import an entire tree as a single album' diff --git a/docs/reference/cli.rst b/docs/reference/cli.rst index 3e668f013..39a4b3f10 100644 --- a/docs/reference/cli.rst +++ b/docs/reference/cli.rst @@ -111,6 +111,12 @@ Optional command flags: time, when no subdirectories will be skipped. So consider enabling the ``incremental`` configuration option. +* When beets applies metadata to your music, it will retain the value of any + existing tags that weren't overwritten, and import them into the database. You + may prefer to only use existing metadata for finding matches, and to erase it + completely when new metadata is applied. You can enforce this behavior with + the ``--from-scratch`` option, or the ``from_scratch`` configuration option. + * By default, beets will proceed without asking if it finds a very close metadata match. To disable this and have the importer ask you every time, use the ``-t`` (for *timid*) option. diff --git a/docs/reference/config.rst b/docs/reference/config.rst index ce45a94ee..a4ed96699 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -475,6 +475,15 @@ Either ``yes`` or ``no``, controlling whether imported directories are recorded and whether these recorded directories are skipped. This corresponds to the ``-i`` flag to ``beet import``. +.. _from_scratch: + +from_scratch +~~~~~~~~~~~~ + +Either ``yes`` or ``no`` (default), controlling whether existing metadata is +discarded when a match is applied. This corresponds to the ``-from_scratch`` +flag to ``beet import``. + quiet_fallback ~~~~~~~~~~~~~~ diff --git a/test/test_importer.py b/test/test_importer.py index c6b021f33..e30f5609c 100644 --- a/test/test_importer.py +++ b/test/test_importer.py @@ -633,6 +633,17 @@ class ImportTest(_common.TestCase, ImportHelper): self.assert_file_in_lib( b'Applied Artist', b'Applied Album', b'Applied Title 1.mp3') + def test_apply_from_scratch_removes_other_metadata(self): + config['import']['from_scratch'] = True + + for mediafile in self.import_media: + mediafile.genre = u'Tag Genre' + mediafile.save() + + self.importer.add_choice(importer.action.APPLY) + self.importer.run() + self.assertEqual(self.lib.items().get().genre, u'') + def test_apply_with_move_deletes_import(self): config['import']['move'] = True From c9b4e9b414673ec41de93e4bd70a6bfb0569b73c Mon Sep 17 00:00:00 2001 From: Constantine Evans Date: Sun, 10 Dec 2017 12:28:47 -0800 Subject: [PATCH 2167/2280] only use tiebreak if tiebreak includes an entry for the kind being considered, otherwise use default (eg, if only items is specified, and -a is being used, use default order of priority --- beetsplug/duplicates.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 2584e6628..6913aaef6 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -253,13 +253,12 @@ class DuplicatesPlugin(BeetsPlugin): "completeness" (objects with more non-null fields come first) and Albums are ordered by their track count. """ - if tiebreak: - kind = 'items' if all(isinstance(o, Item) - for o in objs) else 'albums' + kind = 'items' if all(isinstance(o, Item) for o in objs) else 'albums' + + if tiebreak and kind in tiebreak.keys(): key = lambda x: tuple(getattr(x, k) for k in tiebreak[kind]) else: - kind = Item if all(isinstance(o, Item) for o in objs) else Album - if kind is Item: + if kind is 'items': def truthy(v): # Avoid a Unicode warning by avoiding comparison # between a bytes object and the empty Unicode From 7132ad094b78ff05a3ff83638acd95fceeee8b1e Mon Sep 17 00:00:00 2001 From: Vrihub Date: Mon, 11 Dec 2017 19:32:53 +0100 Subject: [PATCH 2168/2280] First tentative fix for issue 2738. Don't ignore anymore filenames such as "01.mp3", instead use the number in the filename as track number. --- beetsplug/fromfilename.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index 5e1b822c2..7e872ffa9 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -27,10 +27,6 @@ import six # Filename field extraction patterns. PATTERNS = [ - # "01 - Track 01" and "01": do nothing - r'^(\d+)\s*-\s*track\s*\d$', - r'^\d+$', - # Useful patterns. r'^(?P.+)-(?P.+)-(?P<tag>.*)$', r'^(?P<track>\d+)\s*-(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', @@ -45,6 +41,7 @@ PATTERNS = [ r'^(?P<track>\d+)\s*-\s*(?P<title>.+)$', r'^(?P<track>\d+)\s(?P<title>.+)$', r'^(?P<title>.+) by (?P<artist>.+)$', + r'^(?P<track>\d+).*$', ] # Titles considered "empty" and in need of replacement. From dd2b44ef20fd089fb0961a77e913ed6c033b387a Mon Sep 17 00:00:00 2001 From: Constantine Evans <cevans@evanslabs.org> Date: Mon, 11 Dec 2017 13:31:40 -0800 Subject: [PATCH 2169/2280] minor fixes and changelog entry --- beetsplug/duplicates.py | 4 ++-- docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py index 6913aaef6..b316cfda6 100644 --- a/beetsplug/duplicates.py +++ b/beetsplug/duplicates.py @@ -258,14 +258,14 @@ class DuplicatesPlugin(BeetsPlugin): if tiebreak and kind in tiebreak.keys(): key = lambda x: tuple(getattr(x, k) for k in tiebreak[kind]) else: - if kind is 'items': + if kind == 'items': def truthy(v): # Avoid a Unicode warning by avoiding comparison # between a bytes object and the empty Unicode # string ''. return v is not None and \ (v != '' if isinstance(v, six.text_type) else True) - fields = kind.all_keys() + fields = Item.all_keys() key = lambda x: sum(1 for f in fields if truthy(getattr(x, f))) else: key = lambda x: len(x.items()) diff --git a/docs/changelog.rst b/docs/changelog.rst index edeaf8140..8752ff910 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -70,6 +70,8 @@ Fixes: Python 3 on Windows with non-ASCII filenames. :bug:`2671` * :doc:`/plugins/absubmit`: Fix an occasional crash on Python 3 when the AB analysis tool produced non-ASCII metadata. :bug:`2673` +* :doc:`/plugins/duplicates`: Use default tiebreak for any kind (item/album) that + does not have a tiebreak specified in the configuration. * :doc:`/plugins/duplicates`: Fix the `--key` command line option, which was ignored. * :doc:`/plugins/replaygain`: Fix album replaygain calculation with the From 2ba3c1bec32b81b22c582e968bcb818803873094 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 12 Dec 2017 11:57:55 -0500 Subject: [PATCH 2170/2280] Add thanks & issue number for #2758 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8752ff910..e5ecc2f89 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -72,6 +72,8 @@ Fixes: analysis tool produced non-ASCII metadata. :bug:`2673` * :doc:`/plugins/duplicates`: Use default tiebreak for any kind (item/album) that does not have a tiebreak specified in the configuration. + Thanks to :user:`cgevans`. + :bug:`2758` * :doc:`/plugins/duplicates`: Fix the `--key` command line option, which was ignored. * :doc:`/plugins/replaygain`: Fix album replaygain calculation with the From 0fd27e1c543ab23a4c205ba3913117f9c0fccf6e Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Sat, 16 Dec 2017 15:00:50 -0500 Subject: [PATCH 2171/2280] Fix tiny typo in #2755 --- docs/reference/config.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/config.rst b/docs/reference/config.rst index a4ed96699..4015a4fc2 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -481,7 +481,7 @@ from_scratch ~~~~~~~~~~~~ Either ``yes`` or ``no`` (default), controlling whether existing metadata is -discarded when a match is applied. This corresponds to the ``-from_scratch`` +discarded when a match is applied. This corresponds to the ``--from_scratch`` flag to ``beet import``. quiet_fallback From 31642cd7cc9327f84d67294ea0563ef3861b464c Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Sat, 16 Dec 2017 15:02:17 -0500 Subject: [PATCH 2172/2280] Changelog entry for #2755 (fixes #934) --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index e5ecc2f89..b220acc14 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -34,6 +34,10 @@ New features: * :doc:`/plugins/acousticbrainz`: The plugin can now be configured to write only a specific list of tags. Thanks to :user:`woparry`. +* A new :ref:`from_scratch` configuration option makes the importer remove old + metadata before applying new metadata. + Thanks to :user:`tummychow`. + :bug:`934` :bug:`2755` Fixes: From a0643dc5409a6e5b68bdcda36f4708fcf4e799e9 Mon Sep 17 00:00:00 2001 From: Michael Yoo <michael@yoo.id.au> Date: Mon, 18 Dec 2017 17:37:52 +1030 Subject: [PATCH 2173/2280] Remove unnecessary escape caret in ImageMagick convert argument, Fixes #2729 --- beets/util/artresizer.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beets/util/artresizer.py b/beets/util/artresizer.py index e84b775dc..c32f0f37d 100644 --- a/beets/util/artresizer.py +++ b/beets/util/artresizer.py @@ -88,14 +88,13 @@ def im_resize(maxwidth, path_in, path_out=None): log.debug(u'artresizer: ImageMagick resizing {0} to {1}', util.displayable_path(path_in), util.displayable_path(path_out)) - # "-resize widthxheight>" shrinks images with dimension(s) larger - # than the corresponding width and/or height dimension(s). The > - # "only shrink" flag is prefixed by ^ escape char for Windows - # compatibility. + # "-resize WIDTHx>" shrinks images with the width larger + # than the given width while maintaining the aspect ratio + # with regards to the height. try: util.command_output([ 'convert', util.syspath(path_in, prefix=False), - '-resize', '{0}x^>'.format(maxwidth), + '-resize', '{0}x>'.format(maxwidth), util.syspath(path_out, prefix=False), ]) except subprocess.CalledProcessError: From 9ef0ec2a0642d9250c34cc2247dfd9dd1ef2f62f Mon Sep 17 00:00:00 2001 From: Michael Yoo <michael@yoo.id.au> Date: Tue, 19 Dec 2017 21:48:55 +1030 Subject: [PATCH 2174/2280] Add changelog for #2762 --- docs/changelog.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index b220acc14..5acd27f1f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -88,6 +88,8 @@ Fixes: "Edit Candidates" option is used. :bug:`2734` * Fix a crash when numeric metadata fields contain just a minus or plus sign with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` +* Fixed an issue where images would be resized according to their longest edge, + instead of their width. Thanks to :user:`sekjun9878`. :bug:`2729` For developers: From 84cf3361cef52224be83516ebd369c4126919104 Mon Sep 17 00:00:00 2001 From: Vrihub <Vrihub@users.noreply.github.com> Date: Thu, 21 Dec 2017 14:47:41 +0100 Subject: [PATCH 2175/2280] Refactored some regular expressions. Added changelog entry Some more changes to the regular expressions in the "PATTERNS" list. Also allow "_" as a separator, where only "-" was allowed. Replaced similar regexps containing different combinations of \s, "-", "." with a single regexp using a set of characters [\s.\-_]. --- beetsplug/fromfilename.py | 18 ++++++------------ docs/changelog.rst | 2 ++ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index 7e872ffa9..ea43129aa 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -28,18 +28,13 @@ import six # Filename field extraction patterns. PATTERNS = [ # Useful patterns. - r'^(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', - r'^(?P<track>\d+)\s*-(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', - r'^(?P<track>\d+)\s(?P<artist>.+)-(?P<title>.+)-(?P<tag>.*)$', - r'^(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\.\s*(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s*-\s*(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s*-(?P<artist>.+)-(?P<title>.+)$', - r'^(?P<track>\d+)\s(?P<artist>.+)-(?P<title>.+)$', + r'^(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<artist>.+)[\-_](?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)$', r'^(?P<title>.+)$', - r'^(?P<track>\d+)\.\s*(?P<title>.+)$', - r'^(?P<track>\d+)\s*-\s*(?P<title>.+)$', - r'^(?P<track>\d+)\s(?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<title>.+)$', + r'^(?P<track>\d+)\s+(?P<title>.+)$', r'^(?P<title>.+) by (?P<artist>.+)$', r'^(?P<track>\d+).*$', ] @@ -47,7 +42,6 @@ PATTERNS = [ # Titles considered "empty" and in need of replacement. BAD_TITLE_PATTERNS = [ r'^$', - r'\d+?\s?-?\s*track\s*\d+', ] diff --git a/docs/changelog.rst b/docs/changelog.rst index edeaf8140..a5c065131 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -80,6 +80,8 @@ Fixes: "Edit Candidates" option is used. :bug:`2734` * Fix a crash when numeric metadata fields contain just a minus or plus sign with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` +* :doc:`/plugins/fromfilename`: Allow file names such as "01.mp3" to extract the track number. + Also allow "_" as a separator. Refactor some regular expressions. :bug:`2738` For developers: From 4ee5f2ca885457d6fad4439d285557234fc8b5ea Mon Sep 17 00:00:00 2001 From: Vrihub <Vrihub@users.noreply.github.com> Date: Thu, 21 Dec 2017 15:18:25 +0100 Subject: [PATCH 2176/2280] Fix "line too long" Travis CI error --- beetsplug/fromfilename.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/beetsplug/fromfilename.py b/beetsplug/fromfilename.py index ea43129aa..56b68f756 100644 --- a/beetsplug/fromfilename.py +++ b/beetsplug/fromfilename.py @@ -27,16 +27,16 @@ import six # Filename field extraction patterns. PATTERNS = [ - # Useful patterns. - r'^(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', - r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', - r'^(?P<artist>.+)[\-_](?P<title>.+)$', - r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)$', - r'^(?P<title>.+)$', - r'^(?P<track>\d+)[\s.\-_]+(?P<title>.+)$', - r'^(?P<track>\d+)\s+(?P<title>.+)$', - r'^(?P<title>.+) by (?P<artist>.+)$', - r'^(?P<track>\d+).*$', + # Useful patterns. + r'^(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$', + r'^(?P<artist>.+)[\-_](?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)$', + r'^(?P<title>.+)$', + r'^(?P<track>\d+)[\s.\-_]+(?P<title>.+)$', + r'^(?P<track>\d+)\s+(?P<title>.+)$', + r'^(?P<title>.+) by (?P<artist>.+)$', + r'^(?P<track>\d+).*$', ] # Titles considered "empty" and in need of replacement. From d939c3e648ee9ddd8d2540722f110203a0ac09d9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 11:12:02 -0500 Subject: [PATCH 2177/2280] Expand changelog for #2759 (fix #2738) --- docs/changelog.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index dbcca7b4a..f81310467 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -88,8 +88,11 @@ Fixes: "Edit Candidates" option is used. :bug:`2734` * Fix a crash when numeric metadata fields contain just a minus or plus sign with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` -* :doc:`/plugins/fromfilename`: Allow file names such as "01.mp3" to extract the track number. - Also allow "_" as a separator. Refactor some regular expressions. :bug:`2738` +* :doc:`/plugins/fromfilename`: Recognize file names that contain *only* a + track number, such as `01.mp3`. Also, the plugin now allows underscores as a + separator between fields. + Thanks to :user:`Vrihub`. + :bug:`2738` :bug:`2759` * Fixed an issue where images would be resized according to their longest edge, instead of their width. Thanks to :user:`sekjun9878`. :bug:`2729` From 6a65722b375c98e0e281b8d7e435f90af69455f8 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 11:39:08 -0500 Subject: [PATCH 2178/2280] Switch to modd for live docs build --- docs/modd.conf | 7 +++++++ docs/serve.py | 10 ---------- 2 files changed, 7 insertions(+), 10 deletions(-) create mode 100644 docs/modd.conf delete mode 100644 docs/serve.py diff --git a/docs/modd.conf b/docs/modd.conf new file mode 100644 index 000000000..9067700d3 --- /dev/null +++ b/docs/modd.conf @@ -0,0 +1,7 @@ +**/*.rst { + prep: make html +} + +_build/html/** { + daemon: devd -m _build/html +} diff --git a/docs/serve.py b/docs/serve.py deleted file mode 100644 index 2bbf6b623..000000000 --- a/docs/serve.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import division, absolute_import, print_function - -from livereload import Server, shell - -server = Server() -server.watch('*.rst', shell('make html')) -server.serve(root='_build/html') From 6ab73b38f244f0dd65e3aaa1df132cda0922bd7d Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 11:57:07 -0500 Subject: [PATCH 2179/2280] Edit the changelog for release --- docs/changelog.rst | 111 +++++++++++++++++++++++++-------------------- 1 file changed, 63 insertions(+), 48 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index f81310467..56f23da49 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,67 +4,77 @@ Changelog 1.4.6 (in development) ---------------------- -New features: +There are some larger new features in this release: -* When the importer finds duplicate albums, you can now merge all the tracks - together and try importing them as a single album. +* When the importer finds duplicate albums, you can now merge all the + tracks---old and new---together and try importing them as a single, combined + album. Thanks to :user:`udiboy1209`. :bug:`112` :bug:`2725` * :doc:`/plugins/lyrics`: The plugin can now produce reStructuredText files for beautiful, readable books of lyrics. Thanks to :user:`anarcat`. :bug:`2628` -* :doc:`/plugins/convert`: Adds ``no_convert`` option which ignores transcoding - items matching provided query string. Thanks to :user:`Stunner`. +* A new :ref:`from_scratch` configuration option makes the importer remove old + metadata before applying new metadata. This new feature complements the + :doc:`zero </plugins/zero>` and :doc:`scrub </plugins/scrub>` plugins but is + slightly different: beets clears out all the old tags it knows about and + only keeps the new data it gets from the remote metadata source. + Thanks to :user:`tummychow`. + :bug:`934` :bug:`2755` + +There are also somewhat littler, but still great, new features: + +* :doc:`/plugins/convert`: A new ``no_convert`` option lets you skip + transcoding items matching a query. Instead, the files are just copied + as-is. Thanks to :user:`Stunner`. :bug:`2732` :bug:`2751` -* :doc:`/plugins/fetchart`: The plugin has now a quiet switch that will only - display missing album arts. Thanks to :user:`euri10`. +* :doc:`/plugins/fetchart`: A new quiet switch that only prints out messages + when album art is missing. + Thanks to :user:`euri10`. :bug:`2683` -* :doc:`/plugins/mbcollection`: The plugin now supports a custom MusicBrainz - collection via the ``collection`` configuration option. +* :doc:`/plugins/mbcollection`: You can configure a custom MusicBrainz + collection via the new ``collection`` configuration option. :bug:`2685` -* :doc:`/plugins/mbcollection`: The plugin now supports removing albums - from collections that are longer in the beets library. -* :doc:`/plugins/mpdstats`: The plugin now updates song stats when MPD switches - from a song to a stream and when it plays the same song consecutively. - :bug:`2707` +* :doc:`/plugins/mbcollection`: The collection update command can now remove + albums from collections that are longer in the beets library. * :doc:`/plugins/fetchart`: The ``clearart`` command now asks for confirmation before touching your files. Thanks to :user:`konman2`. :bug:`2708` :bug:`2427` +* :doc:`/plugins/mpdstats`: The plugin now correctly updates song statistics + when MPD switches from a song to a stream and when it plays the same song + multiple times consecutively. + :bug:`2707` * :doc:`/plugins/acousticbrainz`: The plugin can now be configured to write only a specific list of tags. Thanks to :user:`woparry`. -* A new :ref:`from_scratch` configuration option makes the importer remove old - metadata before applying new metadata. - Thanks to :user:`tummychow`. - :bug:`934` :bug:`2755` -Fixes: +There are lots and lots of bug fixes: -* :doc:`/plugins/hook`: Fixed a problem whereby accessing non-string properties of - objects such as item or album (e.g. item.track) would cause a crash. +* :doc:`/plugins/hook`: Fixed a problem where accessing non-string properties + of ``item`` or ``album`` (e.g., ``item.track``) would cause a crash. Thanks to :user:`broddo`. :bug:`2740` -* :doc:`/plugins/play`: When ``relative_to`` is set, correctly emit relative paths - even when querying for albums rather than tracks. +* :doc:`/plugins/play`: When ``relative_to`` is set, the plugin correctly + emits relative paths even when querying for albums rather than tracks. Thanks to :user:`j000`. :bug:`2702` -* Prevent Python from warning about a ``BrokenPipeError`` being ignored even - though we do take it into account. This was an issue when using beets in - simple shell scripts. +* We suppress a spurious Python warning about a ``BrokenPipeError`` being + ignored. This was an issue when using beets in simple shell scripts. Thanks to :user:`Azphreal`. :bug:`2622` :bug:`2631` * :doc:`/plugins/replaygain`: Fix a regression in the previous release related to the new R128 tags. :bug:`2615` :bug:`2623` -* :doc:`/plugins/lyrics`: The MusixMatch backend now detect and warns - the user when blocked on the server. Thanks to - :user:`anarcat`. :bug:`2634` :bug:`2632` +* :doc:`/plugins/lyrics`: The MusixMatch backend now detects and warns + when the server has blocked the client. + Thanks to :user:`anarcat`. :bug:`2634` :bug:`2632` * :doc:`/plugins/importfeeds`: Fix an error on Python 3 in certain configurations. Thanks to :user:`djl`. :bug:`2467` :bug:`2658` -* :doc:`/plugins/edit`: Fix a bug when editing items during a ``-L`` - re-import. Previously, diffs against against unrelated items could be - shown or beets could crash with a traceback. :bug:`2659` -* :doc:`/plugins/kodiupdate`: Fix server URL and add better error reporting. +* :doc:`/plugins/edit`: Fix a bug when editing items during a re-import with + the ``-L`` flag. Previously, diffs against against unrelated items could be + shown or beets could crash. :bug:`2659` +* :doc:`/plugins/kodiupdate`: Fix the server URL and add better error + reporting. :bug:`2662` * Fixed a problem where "no-op" modifications would reset files' mtimes, resulting in unnecessary writes. This most prominently affected the @@ -74,18 +84,20 @@ Fixes: Python 3 on Windows with non-ASCII filenames. :bug:`2671` * :doc:`/plugins/absubmit`: Fix an occasional crash on Python 3 when the AB analysis tool produced non-ASCII metadata. :bug:`2673` -* :doc:`/plugins/duplicates`: Use default tiebreak for any kind (item/album) that - does not have a tiebreak specified in the configuration. +* :doc:`/plugins/duplicates`: Use the default tiebreak for items or albums + when the configuration only specifies a tiebreak for the other kind of + entity. Thanks to :user:`cgevans`. :bug:`2758` -* :doc:`/plugins/duplicates`: Fix the `--key` command line option, which was +* :doc:`/plugins/duplicates`: Fix the ``--key`` command line option, which was ignored. -* :doc:`/plugins/replaygain`: Fix album replaygain calculation with the - gstreamer backend. :bug:`2636` +* :doc:`/plugins/replaygain`: Fix album ReplayGain calculation with the + GStreamer backend. :bug:`2636` * :doc:`/plugins/scrub`: Handle errors when manipulating files using newer versions of Mutagen. :bug:`2716` -* :doc:`/plugins/fetchart`: Fix: don't skip running the fetchart plugin during import, when the - "Edit Candidates" option is used. :bug:`2734` +* :doc:`/plugins/fetchart`: The plugin no longer gets skipped during import + when the "Edit Candidates" option is used from the :doc:`/plugins/edit`. + :bug:`2734` * Fix a crash when numeric metadata fields contain just a minus or plus sign with no following numbers. Thanks to :user:`eigengrau`. :bug:`2741` * :doc:`/plugins/fromfilename`: Recognize file names that contain *only* a @@ -93,19 +105,22 @@ Fixes: separator between fields. Thanks to :user:`Vrihub`. :bug:`2738` :bug:`2759` -* Fixed an issue where images would be resized according to their longest edge, - instead of their width. Thanks to :user:`sekjun9878`. :bug:`2729` +* Fixed an issue where images would be resized according to their longest + edge, instead of their width, when using the ``maxwidth`` config option in + the :doc:`/plugins/fetchart` and :doc:`/plugins/embedart`. Thanks to + :user:`sekjun9878`. :bug:`2729` +There are some changes for developers: -For developers: - -* Fixed fields in Album and Item objects are now more strict about translating +* "Fixed fields" in Album and Item objects are now more strict about translating missing values into type-specific null-like values. This should help in cases where a string field is unexpectedly `None` sometimes instead of just showing up as an empty string. :bug:`2605` -* Refactored the move functions in library.py and the `manipulate_files` function - in importer.py to use a single parameter describing the file operation instead - of multiple boolean flags. :bug:`2682` +* Refactored the move functions the `beets.library` module and the + `manipulate_files` function in `beets.importer` to use a single parameter + describing the file operation instead of multiple Boolean flags. + There is a new numerated type describing how to move, copy, or link files. + :bug:`2682` 1.4.5 (June 20, 2017) From 4488f69fede29a402e4e879ecf82aec8ed13ffa9 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 13:11:51 -0500 Subject: [PATCH 2180/2280] Changelog summary paragraph --- docs/changelog.rst | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 56f23da49..238305606 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,12 @@ Changelog 1.4.6 (in development) ---------------------- -There are some larger new features in this release: +The highlight of this release is "album merging," an oft-requested option in +the importer to add new tracks to an existing album you already have in your +library. This way, you no longer need to resort to removing the partial album +from your library, combining the files manually, and importing again. + +Here are the larger new features in this release: * When the importer finds duplicate albums, you can now merge all the tracks---old and new---together and try importing them as a single, combined From 8a453b6ec8fc79ec938e302eb021cd83abf7fe51 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 13:12:11 -0500 Subject: [PATCH 2181/2280] Release date for 1.4.6 --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 238305606..d3cfa24c9 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,8 +1,8 @@ Changelog ========= -1.4.6 (in development) ----------------------- +1.4.6 (December 21, 2017) +------------------------- The highlight of this release is "album merging," an oft-requested option in the importer to add new tracks to an existing album you already have in your From 298050f369111d4752cf0e1f2c4664567a745414 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 13:15:54 -0500 Subject: [PATCH 2182/2280] Update Pandoc wrap CLI flag --- extra/release.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extra/release.py b/extra/release.py index ce3099a69..b0b7a96e0 100755 --- a/extra/release.py +++ b/extra/release.py @@ -166,7 +166,7 @@ def rst2md(text): """Use Pandoc to convert text from ReST to Markdown. """ pandoc = subprocess.Popen( - ['pandoc', '--from=rst', '--to=markdown', '--no-wrap'], + ['pandoc', '--from=rst', '--to=markdown', '--wrap=none'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, _ = pandoc.communicate(text.encode('utf-8')) From 61a752d234f1e7e63311bb46ca7175be33b0fc24 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 21 Dec 2017 13:16:12 -0500 Subject: [PATCH 2183/2280] Version bump: 1.4.7 --- beets/__init__.py | 2 +- docs/changelog.rst | 6 ++++++ docs/conf.py | 2 +- setup.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/beets/__init__.py b/beets/__init__.py index ba2faec94..b8fe2a840 100644 --- a/beets/__init__.py +++ b/beets/__init__.py @@ -19,7 +19,7 @@ import os from beets.util import confit -__version__ = u'1.4.6' +__version__ = u'1.4.7' __author__ = u'Adrian Sampson <adrian@radbox.org>' diff --git a/docs/changelog.rst b/docs/changelog.rst index d3cfa24c9..bd084a890 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,12 @@ Changelog ========= +1.4.7 (in development) +---------------------- + +Changelog goes here! + + 1.4.6 (December 21, 2017) ------------------------- diff --git a/docs/conf.py b/docs/conf.py index 9bfab940a..8f8e6f9ab 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ project = u'beets' copyright = u'2016, Adrian Sampson' version = '1.4' -release = '1.4.6' +release = '1.4.7' pygments_style = 'sphinx' diff --git a/setup.py b/setup.py index 24c571039..903f9d17f 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ if 'sdist' in sys.argv: setup( name='beets', - version='1.4.6', + version='1.4.7', description='music tagger and library organizer', author='Adrian Sampson', author_email='adrian@radbox.org', From 01573ce913c38567dd7fb96dfabb110816dbe21b Mon Sep 17 00:00:00 2001 From: translit <4024096+translit@users.noreply.github.com> Date: Sat, 30 Dec 2017 01:21:35 +0100 Subject: [PATCH 2184/2280] Word swap --- docs/plugins/thumbnails.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/thumbnails.rst b/docs/plugins/thumbnails.rst index 67f83ce98..5753a9f7e 100644 --- a/docs/plugins/thumbnails.rst +++ b/docs/plugins/thumbnails.rst @@ -1,7 +1,7 @@ Thumbnails Plugin ================== -The ``thumbnails`` plugin creates thumbnails your for album folders with the +The ``thumbnails`` plugin creates thumbnails for your album folders with the album cover. This works on freedesktop.org-compliant file managers such as Nautilus or Thunar, and is therefore POSIX-only. From 3b491ce9b455bf2d07048a341280677869ee7113 Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Sat, 30 Dec 2017 12:16:39 -0800 Subject: [PATCH 2185/2280] Fixes #2688: Skip non-audio media from MusicBrainz Some releases have non-audio media, such as CD+DVD or CD+DVD-Video. Skip these media when fetching album info as they will never match audio tracks and will always report missing tracks. I took the naive approach of cherry-picking a list of media suspected to not contain audio from the MusicBrainz formats list: https://musicbrainz.org/doc/Release/Format --- beets/autotag/mb.py | 6 ++++++ docs/changelog.rst | 3 +++ test/test_mb.py | 25 +++++++++++++++++++++++-- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 5c484d2b3..b5ed4f358 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -36,6 +36,9 @@ if util.SNI_SUPPORTED: else: BASE_URL = 'http://musicbrainz.org/' +NON_AUDIO_FORMATS = ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', + 'SVCD', 'UMD', 'VHS'] + musicbrainzngs.set_useragent('beets', beets.__version__, 'http://beets.io/') @@ -275,6 +278,9 @@ def album_info(release): disctitle = medium.get('title') format = medium.get('format') + if format in NON_AUDIO_FORMATS: + continue + all_tracks = medium['track-list'] if 'pregap' in medium: all_tracks.insert(0, medium['pregap']) diff --git a/docs/changelog.rst b/docs/changelog.rst index bd084a890..2a7349d65 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,9 @@ Changelog Changelog goes here! +Fixes: +* Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688` + 1.4.6 (December 21, 2017) ------------------------- diff --git a/test/test_mb.py b/test/test_mb.py index ca1bf2a1a..9c51d0fe3 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -27,7 +27,7 @@ import mock class MBAlbumInfoTest(_common.TestCase): def _make_release(self, date_str='2009', tracks=None, track_length=None, - track_artist=False): + track_artist=False, medium_format='FORMAT'): release = { 'title': 'ALBUM TITLE', 'id': 'ALBUM ID', @@ -90,7 +90,7 @@ class MBAlbumInfoTest(_common.TestCase): release['medium-list'].append({ 'position': '1', 'track-list': track_list, - 'format': 'FORMAT', + 'format': medium_format, 'title': 'MEDIUM TITLE', }) return release @@ -324,6 +324,27 @@ class MBAlbumInfoTest(_common.TestCase): d = mb.album_info(release) self.assertEqual(d.data_source, 'MusicBrainz') + def test_skip_non_audio_dvd(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks, medium_format="DVD") + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 0) + + def test_skip_non_audio_dvd_video(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks, medium_format="DVD-Video") + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 0) + + def test_no_skip_dvd_audio(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks, medium_format="DVD-Audio") + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + class ParseIDTest(_common.TestCase): def test_parse_id_correct(self): From 71b4d5c7023a8c20d1308f05a70ba1d6f7882949 Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Sat, 30 Dec 2017 19:18:07 -0800 Subject: [PATCH 2186/2280] Fixes #1210: Skip non-audio tracks from MusicBrainz This ignores non-audio tracks during import: - Data tracks, based on their title `[data track]` (which seems to be the MusicBrainz convention, as there's no specific flag to indicate that a track is a data one), - Video tracks, based on the `video=true` attribute. It's similar to the Picard changes mentioned in #1210, except it doesn't deal with `[silence]` tracks: These ones will probably require a setting to let the user control if they should be imported or not. --- beets/autotag/mb.py | 11 +++++++++++ docs/changelog.rst | 3 +++ test/test_mb.py | 26 +++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index b5ed4f358..6cf2818fd 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -39,6 +39,8 @@ else: NON_AUDIO_FORMATS = ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', 'UMD', 'VHS'] +SKIPPED_TRACKS = ['[data track]'] + musicbrainzngs.set_useragent('beets', beets.__version__, 'http://beets.io/') @@ -286,6 +288,15 @@ def album_info(release): all_tracks.insert(0, medium['pregap']) for track in all_tracks: + + if ('title' in track['recording'] and + track['recording']['title'] in SKIPPED_TRACKS): + continue + + if ('video' in track['recording'] and + track['recording']['video'] == 'true'): + continue + # Basic information from the recording. index += 1 ti = track_info( diff --git a/docs/changelog.rst b/docs/changelog.rst index 2a7349d65..4ff54b222 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,7 +7,10 @@ Changelog Changelog goes here! Fixes: + * Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688` +* Non-audio tracks (data tracks, video tracks, etc.) are now skipped by the + autotagger. :bug:`1210` 1.4.6 (December 21, 2017) diff --git a/test/test_mb.py b/test/test_mb.py index 9c51d0fe3..4683793f4 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -95,7 +95,7 @@ class MBAlbumInfoTest(_common.TestCase): }) return release - def _make_track(self, title, tr_id, duration, artist=False): + def _make_track(self, title, tr_id, duration, artist=False, video=False): track = { 'title': title, 'id': tr_id, @@ -113,6 +113,8 @@ class MBAlbumInfoTest(_common.TestCase): 'name': 'RECORDING ARTIST CREDIT', } ] + if video: + track['video'] = 'true' return track def test_parse_release_with_year(self): @@ -345,6 +347,28 @@ class MBAlbumInfoTest(_common.TestCase): d = mb.album_info(release) self.assertEqual(len(d.tracks), 2) + def test_skip_data_track(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('[data track]', 'ID DATA TRACK', + 100.0 * 1000.0), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE TWO') + + def test_skip_video_track(self): + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0, + False, True), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 2) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE TWO') + class ParseIDTest(_common.TestCase): def test_parse_id_correct(self): From 05775ccac68441894d8b9d5c05b0e55bc56e279f Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Sun, 31 Dec 2017 11:27:42 +0100 Subject: [PATCH 2187/2280] Fix fragile parsing of bs1770gain output bs1770gain is sorting the filenames internally, so in some corner cases it returns the results in a different order from the command-line arguments. This patch uses the --xml option of bs1770gain (introduced in 0.4.6) in order to read the filenames reliably. --- beetsplug/replaygain.py | 81 +++++++++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 28 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index a70f9384b..d8e0e484a 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -20,12 +20,13 @@ import os import collections import sys import warnings -import re +import xml.parsers.expat from six.moves import zip from beets import ui from beets.plugins import BeetsPlugin -from beets.util import syspath, command_output, displayable_path, py3_path +from beets.util import (syspath, command_output, bytestring_path, + displayable_path, py3_path) # Utilities. @@ -194,12 +195,13 @@ class Bs1770gainBackend(Backend): # Construct shell command. cmd = [self.command] cmd += [self.method] - cmd += ['-p'] + cmd += ['--xml', '-p'] # Workaround for Windows: the underlying tool fails on paths # with the \\?\ prefix, so we don't use it here. This # prevents the backend from working with long paths. args = cmd + [syspath(i.path, prefix=False) for i in items] + path_list = [i.path for i in items] # Invoke the command. self._log.debug( @@ -208,40 +210,63 @@ class Bs1770gainBackend(Backend): output = call(args) self._log.debug(u'analysis finished: {0}', output) - results = self.parse_tool_output(output, - len(items) + is_album) + results = self.parse_tool_output(output, path_list, is_album) self._log.debug(u'{0} items, {1} results', len(items), len(results)) return results - def parse_tool_output(self, text, num_lines): + def parse_tool_output(self, text, path_list, is_album): """Given the output from bs1770gain, parse the text and return a list of dictionaries containing information about each analyzed file. """ - out = [] - data = text.decode('utf-8', errors='ignore') - regex = re.compile( - u'(\\s{2,2}\\[\\d+\\/\\d+\\].*?|\\[ALBUM\\].*?)' - '(?=\\s{2,2}\\[\\d+\\/\\d+\\]|\\s{2,2}\\[ALBUM\\]' - ':|done\\.\\s)', re.DOTALL | re.UNICODE) - results = re.findall(regex, data) - for parts in results[0:num_lines]: - part = parts.split(u'\n') - if len(part) == 0: - self._log.debug(u'bad tool output: {0!r}', text) - raise ReplayGainError(u'bs1770gain failed') + per_file_gain = {} + album_gain = {} # mutable variable so it can be set from handlers + parser = xml.parsers.expat.ParserCreate(encoding='utf-8') + state = {'file': None, 'gain': None, 'peak': None} + def start_element_handler(name, attrs): + if name == u'track': + state['file'] = bytestring_path(attrs[u'file']) + if state['file'] in per_file_gain: + raise ReplayGainError( + u'duplicate filename in bs1770gain output') + elif name == u'integrated': + state['gain'] = float(attrs[u'lu']) + elif name == u'sample-peak': + state['peak'] = float(attrs[u'factor']) + def end_element_handler(name): + if name == u'track': + if state['gain'] is None or state['peak'] is None: + raise ReplayGainError(u'could not parse gain or peak from ' + 'the output of bs1770gain') + per_file_gain[state['file']] = Gain(state['gain'], + state['peak']) + state['gain'] = state['peak'] = None + elif name == u'summary': + if state['gain'] is None or state['peak'] is None: + raise ReplayGainError(u'could not parse gain or peak from ' + 'the output of bs1770gain') + album_gain["album"] = Gain(state['gain'], state['peak']) + state['gain'] = state['peak'] = None + parser.StartElementHandler = start_element_handler + parser.EndElementHandler = end_element_handler + parser.Parse(text, True) - try: - song = { - 'file': part[0], - 'gain': float((part[1].split('/'))[1].split('LU')[0]), - 'peak': float(part[2].split('/')[1]), - } - except IndexError: - self._log.info(u'bs1770gain reports (faulty file?): {}', parts) - continue + if len(per_file_gain) != len(path_list): + raise ReplayGainError( + u'the number of results returned by bs1770gain does not match ' + 'the number of files passed to it') - out.append(Gain(song['gain'], song['peak'])) + # bs1770gain does not return the analysis results in the order that + # files are passed on the command line, because it is sorting the files + # internally. We must recover the order from the filenames themselves. + try: + out = [per_file_gain[os.path.basename(p)] for p in path_list] + except KeyError: + raise ReplayGainError( + u'unrecognized filename in bs1770gain output ' + '(bs1770gain can only deal with utf-8 file names)') + if is_album: + out.append(album_gain["album"]) return out From 1f6335581e6871513d1a1a7285df6856d8e4e635 Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Sun, 31 Dec 2017 12:00:02 +0100 Subject: [PATCH 2188/2280] Add --force, --write and --nowrite options to replaygain plugin --- beetsplug/replaygain.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index a70f9384b..18fd8db78 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -893,7 +893,7 @@ class ReplayGainPlugin(BeetsPlugin): self._log.debug(u'applied album gain {0}', album.r128_album_gain) - def handle_album(self, album, write): + def handle_album(self, album, write, force=False): """Compute album and track replay gain store it in all of the album's items. @@ -901,7 +901,7 @@ class ReplayGainPlugin(BeetsPlugin): item. If replay gain information is already present in all items, nothing is done. """ - if not self.album_requires_gain(album): + if not force and not self.album_requires_gain(album): self._log.info(u'Skipping album {0}', album) return @@ -944,14 +944,14 @@ class ReplayGainPlugin(BeetsPlugin): raise ui.UserError( u"Fatal replay gain error: {0}".format(e)) - def handle_track(self, item, write): + def handle_track(self, item, write, force=False): """Compute track replay gain and store it in the item. If ``write`` is truthy then ``item.write()`` is called to write the data to disk. If replay gain information is already present in the item, nothing is done. """ - if not self.track_requires_gain(item): + if not force and not self.track_requires_gain(item): self._log.info(u'Skipping track {0}', item) return @@ -1007,17 +1007,29 @@ class ReplayGainPlugin(BeetsPlugin): """Return the "replaygain" ui subcommand. """ def func(lib, opts, args): - write = ui.should_write() + write = ui.should_write(opts.write) + force = opts.force if opts.album: for album in lib.albums(ui.decargs(args)): - self.handle_album(album, write) + self.handle_album(album, write, force) else: for item in lib.items(ui.decargs(args)): - self.handle_track(item, write) + self.handle_track(item, write, force) cmd = ui.Subcommand('replaygain', help=u'analyze for ReplayGain') cmd.parser.add_album_option() + cmd.parser.add_option( + "-f", "--force", dest="force", action="store_true", default=False, + help=u"analyze all files, including those that " + "already have ReplayGain metadata") + cmd.parser.add_option( + "-w", "--write", dest="write", + action="store_true", + help=u"write new metadata to files' tags (default)") + cmd.parser.add_option( + "-W", "--nowrite", dest="write", action="store_false", + help=u"don't write metadata (opposite of -w)") cmd.func = func return [cmd] From 3ef4b70439a4fe17c0f52b370a438c1c760869ce Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Sun, 31 Dec 2017 14:51:14 +0100 Subject: [PATCH 2189/2280] Fix coding style --- beetsplug/replaygain.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index d8e0e484a..7e1ca4bd7 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -223,6 +223,7 @@ class Bs1770gainBackend(Backend): album_gain = {} # mutable variable so it can be set from handlers parser = xml.parsers.expat.ParserCreate(encoding='utf-8') state = {'file': None, 'gain': None, 'peak': None} + def start_element_handler(name, attrs): if name == u'track': state['file'] = bytestring_path(attrs[u'file']) @@ -233,6 +234,7 @@ class Bs1770gainBackend(Backend): state['gain'] = float(attrs[u'lu']) elif name == u'sample-peak': state['peak'] = float(attrs[u'factor']) + def end_element_handler(name): if name == u'track': if state['gain'] is None or state['peak'] is None: From d325bceb1d2d3d8d863839ac3258faa609401cec Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Sun, 31 Dec 2017 10:46:48 -0800 Subject: [PATCH 2190/2280] Added a setting to control if video tracks are ignored Users may want to keep tracking video tracks, for example if they rip the audio part of the video tracks. Added a setting to allow this. --- beets/autotag/mb.py | 3 ++- beets/config_default.yaml | 1 + docs/reference/config.rst | 11 +++++++++++ test/test_mb.py | 15 ++++++++++++++- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 6cf2818fd..e32f73329 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -294,7 +294,8 @@ def album_info(release): continue if ('video' in track['recording'] and - track['recording']['video'] == 'true'): + track['recording']['video'] == 'true' and + config['match']['ignore_video_tracks'].get(bool) is True): continue # Basic information from the recording. diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 942459738..01c1e0f65 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -126,5 +126,6 @@ match: original_year: no ignored: [] required: [] + ignore_video_tracks: yes track_length_grace: 10 track_length_max: 30 diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 4015a4fc2..84f41a385 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -774,6 +774,17 @@ want to enforce to the ``required`` setting:: No tags are required by default. +.. _ignore_video_tracks: + +ignore_video_tracks +~~~~~~~~~~~~~~~~~~~ + +By default, video tracks within a release will be ignored. If you want them to +be included (for example if you would like to track the audio-only versions of +the video tracks), set it to ``no``. + +Default: ``yes``. + .. _path-format-config: Path Format Configuration diff --git a/test/test_mb.py b/test/test_mb.py index 4683793f4..35f7c3aa2 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -358,7 +358,7 @@ class MBAlbumInfoTest(_common.TestCase): self.assertEqual(d.tracks[0].title, 'TITLE ONE') self.assertEqual(d.tracks[1].title, 'TITLE TWO') - def test_skip_video_track(self): + def test_skip_video_tracks_by_default(self): tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0, False, True), @@ -369,6 +369,19 @@ class MBAlbumInfoTest(_common.TestCase): self.assertEqual(d.tracks[0].title, 'TITLE ONE') self.assertEqual(d.tracks[1].title, 'TITLE TWO') + def test_no_skip_video_tracks_if_configured(self): + config['match']['ignore_video_tracks'] = False + tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), + self._make_track('TITLE VIDEO', 'ID VIDEO', 100.0 * 1000.0, + False, True), + self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] + release = self._make_release(tracks=tracks) + d = mb.album_info(release) + self.assertEqual(len(d.tracks), 3) + self.assertEqual(d.tracks[0].title, 'TITLE ONE') + self.assertEqual(d.tracks[1].title, 'TITLE VIDEO') + self.assertEqual(d.tracks[2].title, 'TITLE TWO') + class ParseIDTest(_common.TestCase): def test_parse_id_correct(self): From da8e17d2df040ffa4336ae8d8ffc74861b30c584 Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Sun, 31 Dec 2017 14:24:36 -0800 Subject: [PATCH 2191/2280] Simplify boolean check --- beets/autotag/mb.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index e32f73329..eb7c30808 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -295,7 +295,7 @@ def album_info(release): if ('video' in track['recording'] and track['recording']['video'] == 'true' and - config['match']['ignore_video_tracks'].get(bool) is True): + config['match']['ignore_video_tracks']): continue # Basic information from the recording. From 8975234cd89cd0b5b30ea62a8c0bf9a938543a71 Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Tue, 2 Jan 2018 10:54:13 +0100 Subject: [PATCH 2192/2280] Add version requirement for bs1770gain to the documentation --- docs/plugins/replaygain.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/replaygain.rst b/docs/plugins/replaygain.rst index 838a2ea2b..07b585d27 100644 --- a/docs/plugins/replaygain.rst +++ b/docs/plugins/replaygain.rst @@ -79,8 +79,8 @@ bs1770gain `````````` To use this backend, you will need to install the `bs1770gain`_ command-line -tool. Follow the instructions at the `bs1770gain`_ Web site and ensure that -the tool is on your ``$PATH``. +tool, version 0.4.6 or greater. Follow the instructions at the `bs1770gain`_ +Web site and ensure that the tool is on your ``$PATH``. .. _bs1770gain: http://bs1770gain.sourceforge.net/ From 3e6f7548a7566643e0c2d4d30c8495ae84d2c821 Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Tue, 2 Jan 2018 11:32:18 +0100 Subject: [PATCH 2193/2280] Add ChangeLog entry --- docs/changelog.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4ff54b222..c7e2d0ff6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -11,6 +11,7 @@ Fixes: * Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688` * Non-audio tracks (data tracks, video tracks, etc.) are now skipped by the autotagger. :bug:`1210` +* :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` version 0.4.6 or later is required. :bug:`2777` 1.4.6 (December 21, 2017) From 499cd378b7a2e7fc76821096e633e1731e9c5dbc Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Tue, 2 Jan 2018 12:11:47 +0100 Subject: [PATCH 2194/2280] fix the default write behaviour to the importer configuration --- beetsplug/replaygain.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index 18fd8db78..19ca8572e 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -1025,9 +1025,8 @@ class ReplayGainPlugin(BeetsPlugin): help=u"analyze all files, including those that " "already have ReplayGain metadata") cmd.parser.add_option( - "-w", "--write", dest="write", - action="store_true", - help=u"write new metadata to files' tags (default)") + "-w", "--write", default=None, action="store_true", + help=u"write new metadata to files' tags") cmd.parser.add_option( "-W", "--nowrite", dest="write", action="store_false", help=u"don't write metadata (opposite of -w)") From 1b247dffff8e549d9d2b544fac687fd9b9dadcb2 Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Tue, 2 Jan 2018 12:34:34 +0100 Subject: [PATCH 2195/2280] Document new options to the replaygain sub-command --- docs/plugins/replaygain.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/plugins/replaygain.rst b/docs/plugins/replaygain.rst index 838a2ea2b..44246ed50 100644 --- a/docs/plugins/replaygain.rst +++ b/docs/plugins/replaygain.rst @@ -140,11 +140,15 @@ By default, the plugin will analyze all items an albums as they are implemented. However, you can also manually analyze files that are already in your library. Use the ``beet replaygain`` command:: - $ beet replaygain [-a] [QUERY] + $ beet replaygain [-Waf] [QUERY] The ``-a`` flag analyzes whole albums instead of individual tracks. Provide a query (see :doc:`/reference/query`) to indicate which items or albums to -analyze. +analyze. Files that already have ReplayGain values are skipped unless ``-f`` is +supplied. Use ``-w`` (write tags) or ``-W`` (don't write tags) to control +whether ReplayGain tags are written into the music files, or stored in the +beets database only (the default is to use :ref:`the importer's configuration +<config-import-write>`). ReplayGain analysis is not fast, so you may want to disable it during import. Use the ``auto`` config option to control this:: From e2b920610ff3d55fa9d642335149146d89e4f579 Mon Sep 17 00:00:00 2001 From: Yann Leprince <yann.leprince@ylep.fr> Date: Tue, 2 Jan 2018 14:34:56 +0100 Subject: [PATCH 2196/2280] Add ChangeLog entry --- docs/changelog.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4ff54b222..90988785d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -6,6 +6,12 @@ Changelog Changelog goes here! +New features: + +* :doc:`/plugins/replaygain`: add ``--force``, ``--write`` and ``--nowrite`` + options to ``beet replaygain``. :bug:`2778` + + Fixes: * Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688` From 22c4f9cb97fad6afac4a2e507f294eee68567848 Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Tue, 2 Jan 2018 11:03:02 -0800 Subject: [PATCH 2197/2280] Added a setting to control which formats are ignored This is related to #2688 where a list of hard-coded non-audio formats to ignore has been added. Some users may want to rip the audio portion of video tracks (e.g. DVD-Video) so it would be beneficial to let them control exactly which formats to ignore. I added a `ignored_formats` setting for that purpose and moved the hard-coded list into the config. Test and documentation have been updated accordingly. Aside: I also clarified the changelog a bit regarding this change and the related one for #1210. --- beets/autotag/mb.py | 5 +---- beets/config_default.yaml | 1 + docs/changelog.rst | 10 +++++++--- docs/reference/config.rst | 13 +++++++++++++ test/test_mb.py | 18 +++++++----------- 5 files changed, 29 insertions(+), 18 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index eb7c30808..edd297b83 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -36,9 +36,6 @@ if util.SNI_SUPPORTED: else: BASE_URL = 'http://musicbrainz.org/' -NON_AUDIO_FORMATS = ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', - 'SVCD', 'UMD', 'VHS'] - SKIPPED_TRACKS = ['[data track]'] musicbrainzngs.set_useragent('beets', beets.__version__, @@ -280,7 +277,7 @@ def album_info(release): disctitle = medium.get('title') format = medium.get('format') - if format in NON_AUDIO_FORMATS: + if format in config['match']['ignored_formats'].as_str_seq(): continue all_tracks = medium['track-list'] diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 01c1e0f65..d84d2e32f 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -126,6 +126,7 @@ match: original_year: no ignored: [] required: [] + ignored_formats: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', 'UMD', 'VHS'] ignore_video_tracks: yes track_length_grace: 10 track_length_max: 30 diff --git a/docs/changelog.rst b/docs/changelog.rst index c7e2d0ff6..07255066a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,9 +8,13 @@ Changelog goes here! Fixes: -* Non-audio media (DVD-Video, etc.) are now skipped by the autotagger. :bug:`2688` -* Non-audio tracks (data tracks, video tracks, etc.) are now skipped by the - autotagger. :bug:`1210` +* Non-audio media (DVD-Video, etc.) are now skipped by default by the + autotagger. A new option ``ignored_formats`` controls which formats to + ignore. :bug:`2688` +* Non-audio tracks (data tracks, video tracks) are now skipped by the + autotagger. Data tracks will always be ignored, but a new option + ``ignore_video_tracks`` has been added to control if video tracks should be + ignored or not. :bug:`1210` * :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` version 0.4.6 or later is required. :bug:`2777` diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 84f41a385..cf1d262f6 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -774,6 +774,19 @@ want to enforce to the ``required`` setting:: No tags are required by default. +.. _ignored_formats: + +ignored_formats +~~~~~~~~~~~~~~~ + +By default a list of release formats considered not containing audio will be +ignored. If you want them to be included (for example if you would like to +consider the audio portion of DVD-Video tracks) you can alter the list +accordingly. + +Default: ``['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', +'UMD', 'VHS']``. + .. _ignore_video_tracks: ignore_video_tracks diff --git a/test/test_mb.py b/test/test_mb.py index 35f7c3aa2..aa8a5bb67 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -326,24 +326,20 @@ class MBAlbumInfoTest(_common.TestCase): d = mb.album_info(release) self.assertEqual(d.data_source, 'MusicBrainz') - def test_skip_non_audio_dvd(self): + def test_ignored_formats(self): + config['match']['ignored_formats'] = ['IGNORED1', 'IGNORED2'] tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] - release = self._make_release(tracks=tracks, medium_format="DVD") + release = self._make_release(tracks=tracks, medium_format="IGNORED1") d = mb.album_info(release) self.assertEqual(len(d.tracks), 0) - def test_skip_non_audio_dvd_video(self): + def test_no_ignored_formats(self): + config['match']['ignored_formats'] = ['IGNORED1', 'IGNORED2'] tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] - release = self._make_release(tracks=tracks, medium_format="DVD-Video") - d = mb.album_info(release) - self.assertEqual(len(d.tracks), 0) - - def test_no_skip_dvd_audio(self): - tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), - self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] - release = self._make_release(tracks=tracks, medium_format="DVD-Audio") + release = self._make_release(tracks=tracks, + medium_format="NON-IGNORED") d = mb.album_info(release) self.assertEqual(len(d.tracks), 2) From 3812f89b02019acc3978d911b7680a815a536d2a Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 2 Jan 2018 14:51:46 -0500 Subject: [PATCH 2198/2280] Remove changelog placeholder --- docs/changelog.rst | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b507b67e7..916c8a937 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,8 +4,6 @@ Changelog 1.4.7 (in development) ---------------------- -Changelog goes here! - New features: * :doc:`/plugins/replaygain`: add ``--force``, ``--write`` and ``--nowrite`` From 816de1c3dabc0f7ac039980c95823ad77437c1ea Mon Sep 17 00:00:00 2001 From: Nicolas Guillaumin <nicolas+github@guillaumin.me> Date: Tue, 2 Jan 2018 15:04:00 -0800 Subject: [PATCH 2199/2280] Rename setting to `ignored_media` for consistency --- beets/autotag/mb.py | 2 +- beets/config_default.yaml | 2 +- docs/changelog.rst | 2 +- docs/reference/config.rst | 10 +++++----- test/test_mb.py | 8 ++++---- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index edd297b83..385dc64fb 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -277,7 +277,7 @@ def album_info(release): disctitle = medium.get('title') format = medium.get('format') - if format in config['match']['ignored_formats'].as_str_seq(): + if format in config['match']['ignored_media'].as_str_seq(): continue all_tracks = medium['track-list'] diff --git a/beets/config_default.yaml b/beets/config_default.yaml index d84d2e32f..e988dd0e9 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -126,7 +126,7 @@ match: original_year: no ignored: [] required: [] - ignored_formats: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', 'UMD', 'VHS'] + ignored_media: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', 'UMD', 'VHS'] ignore_video_tracks: yes track_length_grace: 10 track_length_max: 30 diff --git a/docs/changelog.rst b/docs/changelog.rst index 07255066a..27a703556 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -9,7 +9,7 @@ Changelog goes here! Fixes: * Non-audio media (DVD-Video, etc.) are now skipped by default by the - autotagger. A new option ``ignored_formats`` controls which formats to + autotagger. A new option ``ignored_media`` controls which media formats to ignore. :bug:`2688` * Non-audio tracks (data tracks, video tracks) are now skipped by the autotagger. Data tracks will always be ignored, but a new option diff --git a/docs/reference/config.rst b/docs/reference/config.rst index cf1d262f6..bf60d72fc 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -774,13 +774,13 @@ want to enforce to the ``required`` setting:: No tags are required by default. -.. _ignored_formats: +.. _ignored_media: -ignored_formats -~~~~~~~~~~~~~~~ +ignored_media +~~~~~~~~~~~~~ -By default a list of release formats considered not containing audio will be -ignored. If you want them to be included (for example if you would like to +By default a list of release media formats considered not containing audio will +be ignored. If you want them to be included (for example if you would like to consider the audio portion of DVD-Video tracks) you can alter the list accordingly. diff --git a/test/test_mb.py b/test/test_mb.py index aa8a5bb67..644e7f5de 100644 --- a/test/test_mb.py +++ b/test/test_mb.py @@ -326,16 +326,16 @@ class MBAlbumInfoTest(_common.TestCase): d = mb.album_info(release) self.assertEqual(d.data_source, 'MusicBrainz') - def test_ignored_formats(self): - config['match']['ignored_formats'] = ['IGNORED1', 'IGNORED2'] + def test_ignored_media(self): + config['match']['ignored_media'] = ['IGNORED1', 'IGNORED2'] tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] release = self._make_release(tracks=tracks, medium_format="IGNORED1") d = mb.album_info(release) self.assertEqual(len(d.tracks), 0) - def test_no_ignored_formats(self): - config['match']['ignored_formats'] = ['IGNORED1', 'IGNORED2'] + def test_no_ignored_media(self): + config['match']['ignored_media'] = ['IGNORED1', 'IGNORED2'] tracks = [self._make_track('TITLE ONE', 'ID ONE', 100.0 * 1000.0), self._make_track('TITLE TWO', 'ID TWO', 200.0 * 1000.0)] release = self._make_release(tracks=tracks, From 94b779e7b48bd2ddd782990ea524aced7e35f021 Mon Sep 17 00:00:00 2001 From: Michael Yoo <michael@yoo.id.au> Date: Thu, 4 Jan 2018 21:43:39 +1030 Subject: [PATCH 2200/2280] New importer option incremental_skip_later, fixes #2773 --- beets/config_default.yaml | 1 + beets/importer.py | 3 ++- docs/changelog.rst | 4 ++++ docs/reference/config.rst | 10 ++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index e988dd0e9..69c22da28 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -10,6 +10,7 @@ import: delete: no resume: ask incremental: no + incremental_skip_later: no from_scratch: no quiet_fallback: skip none_rec_action: ask diff --git a/beets/importer.py b/beets/importer.py index 186d824b6..aa291fc30 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -577,7 +577,8 @@ class ImportTask(BaseImportTask): # Update progress. if session.want_resume: self.save_progress() - if session.config['incremental']: + if (session.config['incremental'] and + not session.config['incremental_skip_later']): self.save_history() self.cleanup(copy=session.config['copy'], diff --git a/docs/changelog.rst b/docs/changelog.rst index 9830226cf..c3e120ac1 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -8,6 +8,10 @@ New features: * :doc:`/plugins/replaygain`: add ``--force``, ``--write`` and ``--nowrite`` options to ``beet replaygain``. :bug:`2778` +* A new importer configuration ``incremental_skip_later`` allows you to avoid + recording skipped directories to the incremental list, so you can revisit them + later. Thanks to :user:`sekjun9878`. + :bug:`2773` Fixes: diff --git a/docs/reference/config.rst b/docs/reference/config.rst index bf60d72fc..8c1279b5c 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -475,6 +475,16 @@ Either ``yes`` or ``no``, controlling whether imported directories are recorded and whether these recorded directories are skipped. This corresponds to the ``-i`` flag to ``beet import``. +.. _incremental_skip_later: + +incremental_skip_later +~~~~~~~~~~~~~~~~~~~~~~ + +Either ``yes`` or ``no``, controlling whether skipped directories are +recorded in the incremental list. Set this option to ``yes`` if you would +like to revisit skipped directories later whilst using incremental +mode. Defaults to ``no``. + .. _from_scratch: from_scratch From 5f26ec6db9a852f623ea4dfeb2f99f7b43bb819b Mon Sep 17 00:00:00 2001 From: Michael Yoo <michael@yoo.id.au> Date: Sat, 13 Jan 2018 01:46:28 +1030 Subject: [PATCH 2201/2280] Fix incremental_skip_later bug from #2782 --- beets/importer.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beets/importer.py b/beets/importer.py index aa291fc30..aac21d77f 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -577,8 +577,10 @@ class ImportTask(BaseImportTask): # Update progress. if session.want_resume: self.save_progress() - if (session.config['incremental'] and - not session.config['incremental_skip_later']): + if session.config['incremental'] and not ( + # Should we skip recording to incremental list? + self.skip and session.config['incremental_skip_later'] + ): self.save_history() self.cleanup(copy=session.config['copy'], From f65a99e5512cf6fa67d1d46103fb971276ed3459 Mon Sep 17 00:00:00 2001 From: "Adam H. Sparks" <adamhsparks@gmail.com> Date: Sat, 20 Jan 2018 13:51:36 +1000 Subject: [PATCH 2202/2280] Update advanced.rst Tomahawk is abandoned according to the GitHub README.md. Suggest removing the reference to using it with Beets library. --- docs/guides/advanced.rst | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/docs/guides/advanced.rst b/docs/guides/advanced.rst index 55bda7aac..ba7ca12b6 100644 --- a/docs/guides/advanced.rst +++ b/docs/guides/advanced.rst @@ -72,16 +72,6 @@ typing ``beet web`` and head to http://localhost:8337 in a browser. You can browse your collection with queries and, if your browser supports it, play music using HTML5 audio. -But for a great listening experience, pair beets with the `Tomahawk`_ music -player. Tomahawk lets you listen to music from many different sources, -including a beets server. Just download Tomahawk and open its settings to -connect it to beets. `A post on the beets blog`_ has a more detailed guide. - -.. _A post on the beets blog: - http://beets.io/blog/tomahawk-resolver.html -.. _Tomahawk: http://www.tomahawk-player.org - - Transcode music files for media players --------------------------------------- From 9577a511cb055f143deb2ad8f2b801595b5f5c3f Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 20:50:43 -0500 Subject: [PATCH 2203/2280] Update tests for new Unidecode behavior: fix #2799 The library has started putting spaces around the expanded versions of vulgar fraction characters. --- test/test_library.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_library.py b/test/test_library.py index aaab6fe03..ea566965e 100644 --- a/test/test_library.py +++ b/test/test_library.py @@ -427,7 +427,7 @@ class DestinationTest(_common.TestCase): self.lib.directory = b'lib' self.lib.path_formats = [(u'default', u'$title')] self.i.title = u'ab\xa2\xbdd' - self.assertEqual(self.i.destination(), np('lib/abC_1_2d')) + self.assertEqual(self.i.destination(), np('lib/abC_ 1_2 d')) def test_destination_with_replacements(self): self.lib.directory = b'base' @@ -591,7 +591,7 @@ class DestinationFunctionTest(_common.TestCase, PathFormattingMixin): def test_asciify_variable(self): self._setf(u'%asciify{ab\xa2\xbdd}') - self._assert_dest(b'/base/abC_1_2d') + self._assert_dest(b'/base/abC_ 1_2 d') def test_left_variable(self): self._setf(u'%left{$title, 3}') From 2f2388fc2c82a5eea58bc588896eda2b3eceb475 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 21:52:31 -0500 Subject: [PATCH 2204/2280] py3: Use import argument paths as bytestrings --- beets/ui/commands.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 3a1811cf3..5628c8bc1 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -934,6 +934,13 @@ def import_func(lib, opts, args): if not paths: raise ui.UserError(u'no path specified') + # On Python 2, we get filenames as raw bytes, which is what we + # need. On Python 3, we need to undo the "helpful" conversion to + # Unicode strings to get the real bytestring filename. + if not six.PY2: + paths = [p.encode(util.arg_encoding(), 'surrogateescape') + for p in paths] + import_files(lib, paths, query) From b47e3ec565c1fe893414d4d1b5c028926e247e07 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:25:18 -0500 Subject: [PATCH 2205/2280] Fix lyrics docs: genius backend is default-enabled --- docs/plugins/lyrics.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index 85e3021f9..e1f00e67f 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -2,7 +2,7 @@ Lyrics Plugin ============= The ``lyrics`` plugin fetches and stores song lyrics from databases on the Web. -Namely, the current version of the plugin uses `Lyric Wiki`_, +Namely, the current version of the plugin uses `Lyric Wiki`_, `Musixmatch`_, `Genius.com`_, and, optionally, the Google custom search API. .. _Lyric Wiki: http://lyrics.wikia.com/ @@ -59,8 +59,8 @@ configuration file. The available options are: sources known to be scrapeable. - **sources**: List of sources to search for lyrics. An asterisk ``*`` expands to all available sources. - Default: ``google lyricwiki musixmatch``, i.e., all the - sources except for `genius`. The `google` source will be automatically + Default: ``google lyricwiki musixmatch genius``, i.e., all the + available sources. The `google` source will be automatically deactivated if no ``google_API_key`` is setup. Here's an example of ``config.yaml``:: From e7417e3683940f9d0870a5c342f2947c602eb05f Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:31:15 -0500 Subject: [PATCH 2206/2280] lyrics: Don't crash when BeautifulSoup isn't found --- beetsplug/lyrics.py | 7 +++++++ docs/changelog.rst | 3 +++ docs/plugins/lyrics.rst | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 1987b67e7..7dba483ba 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -659,6 +659,13 @@ class LyricsPlugin(plugins.BeetsPlugin): u'the documentation for further details.') sources.remove('google') + if 'genius' in sources and not HAS_BEAUTIFUL_SOUP: + self._log.debug( + u'The Genius backend requires BeautifulSoup, which is not ' + u'installed, so the source is disabled.' + ) + sources.remove('google') + self.config['bing_lang_from'] = [ x.lower() for x in self.config['bing_lang_from'].as_str_seq()] self.bing_auth_token = None diff --git a/docs/changelog.rst b/docs/changelog.rst index c3e120ac1..e93e644c0 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,9 @@ Fixes: ``ignore_video_tracks`` has been added to control if video tracks should be ignored or not. :bug:`1210` * :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` version 0.4.6 or later is required. :bug:`2777` +* :doc:`/plugins/lyrics`: The plugin no longer crashes in the Genius source + when BeautifulSoup is not found. Instead, it just logs a message and + disables the source. 1.4.6 (December 21, 2017) diff --git a/docs/plugins/lyrics.rst b/docs/plugins/lyrics.rst index e1f00e67f..4131c85d9 100644 --- a/docs/plugins/lyrics.rst +++ b/docs/plugins/lyrics.rst @@ -62,6 +62,8 @@ configuration file. The available options are: Default: ``google lyricwiki musixmatch genius``, i.e., all the available sources. The `google` source will be automatically deactivated if no ``google_API_key`` is setup. + Both it and the `genius` source will only be enabled if BeautifulSoup is + installed. Here's an example of ``config.yaml``:: @@ -154,6 +156,16 @@ After that, the lyrics plugin will fall back on other declared data sources. .. _pip: http://www.pip-installer.org/ .. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ +Activate Genius Lyrics +---------------------- + +Like the Google backend, the Genius backend requires the `BeautifulSoup`_ +library. Install it by typing:: + + pip install beautifulsoup4 + +The backend is enabled by default. + .. _lyrics-translation: Activate On-the-Fly Translation From 277d81b4d62a1eb301372ea9da894f930f42b773 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:33:32 -0500 Subject: [PATCH 2207/2280] lyrics: Don't write ReST by default! --- beetsplug/lyrics.py | 2 +- docs/changelog.rst | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 7dba483ba..3d5f38d9a 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -705,7 +705,7 @@ class LyricsPlugin(plugins.BeetsPlugin): ) cmd.parser.add_option( u'-r', u'--write-rest', dest='writerest', - action='store', default='.', metavar='dir', + action='store', default=None, metavar='dir', help=u'write lyrics to given directory as ReST files', ) cmd.parser.add_option( diff --git a/docs/changelog.rst b/docs/changelog.rst index e93e644c0..2c6833456 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ Fixes: * :doc:`/plugins/lyrics`: The plugin no longer crashes in the Genius source when BeautifulSoup is not found. Instead, it just logs a message and disables the source. +* :doc:`/plugins/lyrics`: The ``lyrics`` command previously write ReST files + by default. This default has been fixed. 1.4.6 (December 21, 2017) From 224d782c2c2495120b767c34fb70a0bbf4679910 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:37:44 -0500 Subject: [PATCH 2208/2280] Fix #2771: handle errors in genius lyrics source --- beetsplug/lyrics.py | 21 ++++++++++++++++++--- docs/changelog.rst | 2 ++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/beetsplug/lyrics.py b/beetsplug/lyrics.py index 3d5f38d9a..d9db8eadc 100644 --- a/beetsplug/lyrics.py +++ b/beetsplug/lyrics.py @@ -359,7 +359,12 @@ class Genius(Backend): # Gotta go regular html scraping... come on Genius. page_url = "https://genius.com" + path - page = requests.get(page_url) + try: + page = requests.get(page_url) + except requests.RequestException as exc: + self._log.debug(u'Genius page request for {0} failed: {1}', + page_url, exc) + return None html = BeautifulSoup(page.text, "html.parser") # Remove script tags that they put in the middle of the lyrics. @@ -374,8 +379,18 @@ class Genius(Backend): def fetch(self, artist, title): search_url = self.base_url + "/search" data = {'q': title} - response = requests.get(search_url, data=data, headers=self.headers) - json = response.json() + try: + response = requests.get(search_url, data=data, + headers=self.headers) + except requests.RequestException as exc: + self._log.debug(u'Genius API request failed: {0}', exc) + return None + + try: + json = response.json() + except ValueError: + self._log.debug(u'Genius API request returned invalid JSON') + return None song_info = None for hit in json["response"]["hits"]: diff --git a/docs/changelog.rst b/docs/changelog.rst index 2c6833456..d8ca02e36 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -27,6 +27,8 @@ Fixes: * :doc:`/plugins/lyrics`: The plugin no longer crashes in the Genius source when BeautifulSoup is not found. Instead, it just logs a message and disables the source. +* :doc:`/plugins/lyrics`: Handle network and API errors when communicating + with Genius. :bug:`2771` * :doc:`/plugins/lyrics`: The ``lyrics`` command previously write ReST files by default. This default has been fixed. From 4ba1127e39248884a1bffc25937b2a3444ee9b8e Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:50:53 -0500 Subject: [PATCH 2209/2280] Changelog for #2731 --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index d8ca02e36..b65253a19 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -31,6 +31,11 @@ Fixes: with Genius. :bug:`2771` * :doc:`/plugins/lyrics`: The ``lyrics`` command previously write ReST files by default. This default has been fixed. +* Plugins can now see updated import task state, such as when rejecting the + initial candidates and finding new ones via a manual search. Notably, this + means that the importer prompt options that the :doc:`/plugins/edit` + provides show up more reliably after doing a secondary import search. + :bug:`2441` :bug:`2731` 1.4.6 (December 21, 2017) From ae30b0f31bbcde45a0852d411223f07e34e12db0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 30 Jan 2018 22:56:18 -0500 Subject: [PATCH 2210/2280] Changelog/thanks for #2601 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index b65253a19..8fb09bede 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -36,6 +36,9 @@ Fixes: means that the importer prompt options that the :doc:`/plugins/edit` provides show up more reliably after doing a secondary import search. :bug:`2441` :bug:`2731` +* :doc:`/plugins/importadded`: Fix a crash on non-autotagged imports. + :bug:`2601` :bug:`1918` + Thanks to :user:`m42i`. 1.4.6 (December 21, 2017) From ace7fab4d84ffb527b96397f364f629e65699610 Mon Sep 17 00:00:00 2001 From: Kovrinic <Kovrinic@users.noreply.github.com> Date: Wed, 31 Jan 2018 00:48:28 -0600 Subject: [PATCH 2211/2280] PlexUpdate: token redacted --- beetsplug/plexupdate.py | 1 + 1 file changed, 1 insertion(+) diff --git a/beetsplug/plexupdate.py b/beetsplug/plexupdate.py index 7dbc8b018..17fd8208d 100644 --- a/beetsplug/plexupdate.py +++ b/beetsplug/plexupdate.py @@ -67,6 +67,7 @@ class PlexUpdate(BeetsPlugin): u'token': u'', u'library_name': u'Music'}) + config['plex']['token'].redact = True self.register_listener('database_change', self.listen_for_db_change) def listen_for_db_change(self, lib, model): From cb785107425ed7bfafb8a349deb3e6731deb1883 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Wed, 31 Jan 2018 09:25:16 -0500 Subject: [PATCH 2212/2280] Changelog/thanks for #2804 --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 8fb09bede..2b22f243b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -39,6 +39,10 @@ Fixes: * :doc:`/plugins/importadded`: Fix a crash on non-autotagged imports. :bug:`2601` :bug:`1918` Thanks to :user:`m42i`. +* :doc:`/plugins/plexupdate`: The Plex token is now redacted in configuration + output. + :bug:`2804` + Thanks to :user:`Kovrinic`. 1.4.6 (December 21, 2017) From 19b5a92632a3730db05c6cfb415fdcd1107406ce Mon Sep 17 00:00:00 2001 From: Reg <reg@disroot.org> Date: Sun, 4 Feb 2018 20:29:03 +0100 Subject: [PATCH 2213/2280] fixed typo seperate/separate --- extra/_beet | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extra/_beet b/extra/_beet index 9f20151f7..23155b8e5 100644 --- a/extra/_beet +++ b/extra/_beet @@ -108,7 +108,7 @@ retagopt='-L:retag items matching a query:${query[@]}' skipopt='-i:skip already-imported directories' noskipopt='-I:do not skip already-imported directories' flatopt='--flat:import an entire tree as a single album' -groupopt='-g:group tracks in a folder into seperate albums' +groupopt='-g:group tracks in a folder into separate albums' editopt='-e:edit user configuration with $EDITOR' defaultopt='-d:include the default configuration' copynomoveopt='-c:copy instead of moving' From 24956b53cc4c9c0ffb21b775448242ea383736fa Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Mon, 5 Feb 2018 11:50:46 -0500 Subject: [PATCH 2214/2280] Changelog for #2803, which fixes #2793 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2b22f243b..4381edeeb 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -43,6 +43,9 @@ Fixes: output. :bug:`2804` Thanks to :user:`Kovrinic`. +* Avoid a crash when importing a non-ASCII filename when using an ASCII locale + on Unix under Python 3. + :bug:`2793` :bug:`2803` 1.4.6 (December 21, 2017) From bfeb678e419c1499ef0775146f35eedfbb331d62 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 8 Feb 2018 17:28:05 -0500 Subject: [PATCH 2215/2280] No media are ignored by default (#2776) We determined on the PR thread that ignoring video tracks is enough, and ignoring typically-video media has more pitfalls. --- beets/config_default.yaml | 2 +- docs/reference/config.rst | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 69c22da28..27aa3d4ca 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -127,7 +127,7 @@ match: original_year: no ignored: [] required: [] - ignored_media: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', 'UMD', 'VHS'] + ignored_media: [] ignore_video_tracks: yes track_length_grace: 10 track_length_max: 30 diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 8c1279b5c..24ed1340d 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -789,13 +789,16 @@ No tags are required by default. ignored_media ~~~~~~~~~~~~~ -By default a list of release media formats considered not containing audio will -be ignored. If you want them to be included (for example if you would like to -consider the audio portion of DVD-Video tracks) you can alter the list -accordingly. +A list of media (i.e., formats) in metadata databases to ignore when matching +music. You can use this to ignore all media that usually contain video instead +of audio, for example:: + + match: + ignored_media: ['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', + 'VCD', 'SVCD', 'UMD', 'VHS'] + +No formats are ignored by default. -Default: ``['Data CD', 'DVD', 'DVD-Video', 'Blu-ray', 'HD-DVD', 'VCD', 'SVCD', -'UMD', 'VHS']``. .. _ignore_video_tracks: From b140f249c146113e165078c40111a228f04e7a72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= <koutak.m@gmail.com> Date: Mon, 19 Feb 2018 10:45:47 +0100 Subject: [PATCH 2216/2280] Allow plugins to define early import stage functions --- beets/importer.py | 2 ++ beets/plugins.py | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/beets/importer.py b/beets/importer.py index aac21d77f..4e4084eec 100644 --- a/beets/importer.py +++ b/beets/importer.py @@ -313,6 +313,8 @@ class ImportSession(object): stages += [import_asis(self)] # Plugin stages. + for stage_func in plugins.early_import_stages(): + stages.append(plugin_stage(self, stage_func)) for stage_func in plugins.import_stages(): stages.append(plugin_stage(self, stage_func)) diff --git a/beets/plugins.py b/beets/plugins.py index d62f3c011..ace5170e3 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -81,6 +81,7 @@ class BeetsPlugin(object): self.template_fields = {} if not self.album_template_fields: self.album_template_fields = {} + self.early_import_stages = [] self.import_stages = [] self._log = log.getChild(self.name) @@ -94,6 +95,17 @@ class BeetsPlugin(object): """ return () + def get_early_import_stages(self): + """Return a list of functions that should be called as importer + pipelines stages early in the pipeline. + + The callables are wrapped versions of the functions in + `self.early_import_stages`. Wrapping provides some bookkeeping for the + plugin: specifically, the logging level is adjusted to WARNING. + """ + return [self._set_log_level_and_params(logging.WARNING, import_stage) + for import_stage in self.early_import_stages] + def get_import_stages(self): """Return a list of functions that should be called as importer pipelines stages. @@ -393,6 +405,14 @@ def template_funcs(): return funcs +def early_import_stages(): + """Get a list of early import stage functions defined by plugins.""" + stages = [] + for plugin in find_plugins(): + stages += plugin.get_early_import_stages() + return stages + + def import_stages(): """Get a list of import stage functions defined by plugins.""" stages = [] From d4625bced068bfd0cadff9e4a644bab2a8500eaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= <koutak.m@gmail.com> Date: Mon, 19 Feb 2018 10:46:06 +0100 Subject: [PATCH 2217/2280] Have convert plugin run early in the pipeline --- beetsplug/convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/convert.py b/beetsplug/convert.py index 380061248..d1223596f 100644 --- a/beetsplug/convert.py +++ b/beetsplug/convert.py @@ -146,7 +146,7 @@ class ConvertPlugin(BeetsPlugin): u'copy_album_art': False, u'album_art_maxwidth': 0, }) - self.import_stages = [self.auto_convert] + self.early_import_stages = [self.auto_convert] self.register_listener('import_task_files', self._cleanup) From 492ff7359a246e8bfa4c3f226dcb102d31701b7f Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 20 Feb 2018 22:57:58 -0500 Subject: [PATCH 2218/2280] Set up date tests for #2652 --- test/test_datequery.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/test/test_datequery.py b/test/test_datequery.py index 7b7776711..b8348ca53 100644 --- a/test/test_datequery.py +++ b/test/test_datequery.py @@ -171,36 +171,41 @@ class DateQueryTest(_common.LibTestCase): class DateQueryTestRelative(_common.LibTestCase): def setUp(self): super(DateQueryTestRelative, self).setUp() - self.i.added = _parsetime(datetime.now().strftime('%Y-%m-%d %H:%M')) + + # We pick a date near a month changeover, which can reveal some time + # zone bugs. + self._now = datetime(2017, 12, 31, 22, 55, 4, 101332) + + self.i.added = _parsetime(self._now.strftime('%Y-%m-%d %H:%M')) self.i.store() def test_single_month_match_fast(self): - query = DateQuery('added', datetime.now().strftime('%Y-%m')) + query = DateQuery('added', self._now.strftime('%Y-%m')) matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_single_month_nonmatch_fast(self): - query = DateQuery('added', (datetime.now() + timedelta(days=30)) + query = DateQuery('added', (self._now + timedelta(days=30)) .strftime('%Y-%m')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) def test_single_month_match_slow(self): - query = DateQuery('added', datetime.now().strftime('%Y-%m')) + query = DateQuery('added', self._now.strftime('%Y-%m')) self.assertTrue(query.match(self.i)) def test_single_month_nonmatch_slow(self): - query = DateQuery('added', (datetime.now() + timedelta(days=30)) + query = DateQuery('added', (self._now + timedelta(days=30)) .strftime('%Y-%m')) self.assertFalse(query.match(self.i)) def test_single_day_match_fast(self): - query = DateQuery('added', datetime.now().strftime('%Y-%m-%d')) + query = DateQuery('added', self._now.strftime('%Y-%m-%d')) matched = self.lib.items(query) self.assertEqual(len(matched), 1) def test_single_day_nonmatch_fast(self): - query = DateQuery('added', (datetime.now() + timedelta(days=1)) + query = DateQuery('added', (self._now + timedelta(days=1)) .strftime('%Y-%m-%d')) matched = self.lib.items(query) self.assertEqual(len(matched), 0) From 502536f4b67b7ebdf66540db2db2475cc4e1fefe Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Tue, 20 Feb 2018 23:22:31 -0500 Subject: [PATCH 2219/2280] Fix #2652 by using local timestamps Because users write their queries in local time, we want to get a local time tuple from the timestamp stored in the database. --- beets/dbcore/query.py | 2 +- docs/changelog.rst | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index fbe6626c7..8fb64e206 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -708,7 +708,7 @@ class DateQuery(FieldQuery): if self.field not in item: return False timestamp = float(item[self.field]) - date = datetime.utcfromtimestamp(timestamp) + date = datetime.fromtimestamp(timestamp) return self.interval.contains(date) _clause_tmpl = "{0} {1} ?" diff --git a/docs/changelog.rst b/docs/changelog.rst index 4381edeeb..4f00b123b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -46,6 +46,11 @@ Fixes: * Avoid a crash when importing a non-ASCII filename when using an ASCII locale on Unix under Python 3. :bug:`2793` :bug:`2803` +* Fix a problem caused by time zone misalignment that could make date queries + fail to match certain dates that are near the edges of a range. For example, + querying for dates within a certain month would fail to match dates within + hours of the end of that month. + :bug:`2652` 1.4.6 (December 21, 2017) From 1bb1bca77911198bc31223d52737bf8dd964c7f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= <koutak.m@gmail.com> Date: Wed, 21 Feb 2018 15:54:37 +0100 Subject: [PATCH 2220/2280] Move the logging wrapper code into a helper function --- beets/plugins.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index ace5170e3..4a2475f50 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -95,6 +95,12 @@ class BeetsPlugin(object): """ return () + def _set_stage_log_level(self, stages): + """Adjust all the stages in `stages` to WARNING logging level. + """ + return [self._set_log_level_and_params(logging.WARNING, stage) + for stage in stages] + def get_early_import_stages(self): """Return a list of functions that should be called as importer pipelines stages early in the pipeline. @@ -103,8 +109,7 @@ class BeetsPlugin(object): `self.early_import_stages`. Wrapping provides some bookkeeping for the plugin: specifically, the logging level is adjusted to WARNING. """ - return [self._set_log_level_and_params(logging.WARNING, import_stage) - for import_stage in self.early_import_stages] + return self._set_stage_log_level(self.early_import_stages) def get_import_stages(self): """Return a list of functions that should be called as importer @@ -114,8 +119,7 @@ class BeetsPlugin(object): `self.import_stages`. Wrapping provides some bookkeeping for the plugin: specifically, the logging level is adjusted to WARNING. """ - return [self._set_log_level_and_params(logging.WARNING, import_stage) - for import_stage in self.import_stages] + return self._set_stage_log_level(self.import_stages) def _set_log_level_and_params(self, base_log_level, func): """Wrap `func` to temporarily set this plugin's logger level to From 305f9f2dfb30c1148889da1cbba06bfef42725da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= <koutak.m@gmail.com> Date: Wed, 21 Feb 2018 16:01:26 +0100 Subject: [PATCH 2221/2280] Document 'early_import_stages' in the docs --- docs/dev/plugins.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 4d41c8971..5b0e4d08b 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -432,6 +432,11 @@ to register it:: def stage(self, session, task): print('Importing something!') +It is also possible to request your function to run early in the pipeline by +adding the function to the plugin's ``early_import_stages`` field instead.:: + + self.early_import_stages = [self.stage] + .. _extend-query: Extend the Query Syntax From bbadb5f5e1cc2040c465330c7562affa4ed9031d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Koutensk=C3=BD?= <koutak.m@gmail.com> Date: Wed, 21 Feb 2018 16:07:58 +0100 Subject: [PATCH 2222/2280] Changelog for #2814 --- docs/changelog.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4381edeeb..44558675b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -46,6 +46,11 @@ Fixes: * Avoid a crash when importing a non-ASCII filename when using an ASCII locale on Unix under Python 3. :bug:`2793` :bug:`2803` +* Convert plugin now runs before all others in the pipeline to solve an issue + with generating ReplayGain data incompatible between the source and target + file formats. This option to request (part of) your plugin to run early in the + pipeline has been exposed in the plugin API as well (```early_import_stages```). + Thanks to :user:`autrimpo`. 1.4.6 (December 21, 2017) From d07c0ab85b6135f39fbca1c3d530556a479fa157 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 22 Feb 2018 15:50:46 -0500 Subject: [PATCH 2223/2280] Revise changelog for #2814 --- docs/changelog.rst | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index effa6d687..a38d5504a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -51,12 +51,19 @@ Fixes: querying for dates within a certain month would fail to match dates within hours of the end of that month. :bug:`2652` -* Convert plugin now runs before all others in the pipeline to solve an issue - with generating ReplayGain data incompatible between the source and target - file formats. This option to request (part of) your plugin to run early in the - pipeline has been exposed in the plugin API as well (```early_import_stages```). +* :doc:`/plugins/convert`: The plugin now runs before other plugin-provided + import stages, which addresses an issue with generating ReplayGain data + incompatible between the source and target file formats. + :bug:`2814` Thanks to :user:`autrimpo`. +For developers: + +* Plugins can now run their import stages *early*, before other plugins. Use + the ``early_import_stages`` list instead of plain ``import_stages`` to + request this behavior. + :bug:`2814` + 1.4.6 (December 21, 2017) ------------------------- From 323d90db17f4c0530eae7c6feb5dac1a3aba3d05 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 22 Feb 2018 15:51:15 -0500 Subject: [PATCH 2224/2280] Tiny ReST markup tweaks (#2814) --- docs/dev/plugins.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/dev/plugins.rst b/docs/dev/plugins.rst index 5b0e4d08b..bab0e604d 100644 --- a/docs/dev/plugins.rst +++ b/docs/dev/plugins.rst @@ -433,9 +433,9 @@ to register it:: print('Importing something!') It is also possible to request your function to run early in the pipeline by -adding the function to the plugin's ``early_import_stages`` field instead.:: +adding the function to the plugin's ``early_import_stages`` field instead:: - self.early_import_stages = [self.stage] + self.early_import_stages = [self.stage] .. _extend-query: From bd788544c20bad40421faa0b367587354e718f8a Mon Sep 17 00:00:00 2001 From: David Logie <djl@mksh.org> Date: Thu, 22 Feb 2018 18:46:14 +0000 Subject: [PATCH 2225/2280] Make sure release events are selected in preferred order. Previously, release events were selected based on the order that MusicBrainz listed them rather than the order defined in config.yaml. --- beets/autotag/mb.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beets/autotag/mb.py b/beets/autotag/mb.py index 385dc64fb..9ce449a8b 100644 --- a/beets/autotag/mb.py +++ b/beets/autotag/mb.py @@ -118,8 +118,8 @@ def _preferred_release_event(release): """ countries = config['match']['preferred']['countries'].as_str_seq() - for event in release.get('release-event-list', {}): - for country in countries: + for country in countries: + for event in release.get('release-event-list', {}): try: if country in event['area']['iso-3166-1-code-list']: return country, event['date'] From d6b6ebbeb96212d5477e6aaf5244e3ec61a836e7 Mon Sep 17 00:00:00 2001 From: David Logie <djl@mksh.org> Date: Thu, 22 Feb 2018 18:44:51 +0000 Subject: [PATCH 2226/2280] mbcollection: Make sure missing albums are removed from collections correctly. --- beetsplug/mbcollection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/mbcollection.py b/beetsplug/mbcollection.py index c01d544a4..d99c386c9 100644 --- a/beetsplug/mbcollection.py +++ b/beetsplug/mbcollection.py @@ -103,8 +103,8 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): offset = 0 albums_in_collection, release_count = _fetch(offset) for i in range(0, release_count, FETCH_CHUNK_SIZE): - offset += FETCH_CHUNK_SIZE albums_in_collection += _fetch(offset)[0] + offset += FETCH_CHUNK_SIZE return albums_in_collection @@ -122,7 +122,7 @@ class MusicBrainzCollectionPlugin(BeetsPlugin): def remove_missing(self, collection_id, lib_albums): lib_ids = set([x.mb_albumid for x in lib_albums]) albums_in_collection = self._get_albums_in_collection(collection_id) - remove_me = list(lib_ids - set(albums_in_collection)) + remove_me = list(set(albums_in_collection) - lib_ids) for i in range(0, len(remove_me), FETCH_CHUNK_SIZE): chunk = remove_me[i:i + FETCH_CHUNK_SIZE] mb_call( From 5d2e203f2487c052e7d38180c1e7fa3d84683979 Mon Sep 17 00:00:00 2001 From: David Logie <djl@mksh.org> Date: Fri, 23 Feb 2018 21:43:12 +0000 Subject: [PATCH 2227/2280] Add changelog entry for #2816. --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a38d5504a..d639b0e20 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -56,6 +56,9 @@ Fixes: incompatible between the source and target file formats. :bug:`2814` Thanks to :user:`autrimpo`. +* Importing a release with multiple release events now selects the + event based on the order of your :ref:`preferred` countries rather than + the order of release events in MusicBrainz. :bug:`2816` For developers: From a6be28a65eef474cc98af35935eb4b9545115cd7 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Fri, 23 Feb 2018 18:18:32 -0500 Subject: [PATCH 2228/2280] Fix #2817: `drop` in configuration was ignored This was overridden by the default CLI option. Now the default for the config option is None, meaning no change to the config. --- beetsplug/ftintitle.py | 2 +- docs/changelog.rst | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/ftintitle.py b/beetsplug/ftintitle.py index 1060a2dd8..9303f9cfc 100644 --- a/beetsplug/ftintitle.py +++ b/beetsplug/ftintitle.py @@ -89,7 +89,7 @@ class FtInTitlePlugin(plugins.BeetsPlugin): self._command.parser.add_option( u'-d', u'--drop', dest='drop', - action='store_true', default=False, + action='store_true', default=None, help=u'drop featuring from artists and ignore title update') if self.config['auto']: diff --git a/docs/changelog.rst b/docs/changelog.rst index a38d5504a..d09bab826 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -56,6 +56,9 @@ Fixes: incompatible between the source and target file formats. :bug:`2814` Thanks to :user:`autrimpo`. +* :doc:`/plugins/ftintitle`: The ``drop`` config option had no effect; it now + does what it says it should do. + :bug:`2817` For developers: From 2c1e4d878b79ca3bdbba125d3e17b4139a56c609 Mon Sep 17 00:00:00 2001 From: wordofglass <wordofglass@users.noreply.github.com> Date: Fri, 10 Nov 2017 11:17:27 +0100 Subject: [PATCH 2229/2280] Advanced fetchart source config: add the (still unused) match_by constructor argument --- beetsplug/fetchart.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index 8bee6e804..e4a12b84e 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -192,9 +192,12 @@ class RequestMixin(object): # ART SOURCES ################################################################ class ArtSource(RequestMixin): - def __init__(self, log, config): + VALID_MATCHING_CRITERIA = ['default'] + + def __init__(self, log, config, match_by=None): self._log = log self._config = config + self.match_by = match_by or self.VALID_MATCHING_CRITERIA def get(self, album, plugin, paths): raise NotImplementedError() @@ -289,6 +292,7 @@ class RemoteArtSource(ArtSource): class CoverArtArchive(RemoteArtSource): NAME = u"Cover Art Archive" + VALID_MATCHING_CRITERIA = ['release', 'releasegroup'] if util.SNI_SUPPORTED: URL = 'https://coverartarchive.org/release/{mbid}/front' @@ -301,10 +305,10 @@ class CoverArtArchive(RemoteArtSource): """Return the Cover Art Archive and Cover Art Archive release group URLs using album MusicBrainz release ID and release group ID. """ - if album.mb_albumid: + if 'release' in self.match_by and album.mb_albumid: yield self._candidate(url=self.URL.format(mbid=album.mb_albumid), match=Candidate.MATCH_EXACT) - if album.mb_releasegroupid: + if 'releasegroup' in self.match_by and album.mb_releasegroupid: yield self._candidate( url=self.GROUP_URL.format(mbid=album.mb_releasegroupid), match=Candidate.MATCH_FALLBACK) @@ -770,7 +774,7 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): sources_name.append(u'filesystem') except ValueError: pass - self.sources = [ART_SOURCES[s](self._log, self.config) + self.sources = [ART_SOURCES[s](self._log, self.config, None) for s in sources_name] # Asynchronous; after music is added to the library. From 971584b4b23978502d7b174a799fb8177e68e020 Mon Sep 17 00:00:00 2001 From: wordofglass <wordofglass@users.noreply.github.com> Date: Mon, 13 Nov 2017 01:54:39 +0100 Subject: [PATCH 2230/2280] Improve readability of plugins.sanitize_choices --- beets/plugins.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index 4a2475f50..1dc1f6496 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -502,9 +502,12 @@ def sanitize_choices(choices, choices_all): others = [x for x in choices_all if x not in choices] res = [] for s in choices: - if s in list(choices_all) + ['*']: - if not (s in seen or seen.add(s)): - res.extend(list(others) if s == '*' else [s]) + if s not in seen: + if s in list(choices_all): + res.append(s) + elif s == '*': + res.extend(others) + seen.add(s) return res From 5a043f28bd99ddb630967eded0a0f74dbf46f4b6 Mon Sep 17 00:00:00 2001 From: wordofglass <wordofglass@users.noreply.github.com> Date: Mon, 13 Nov 2017 01:55:15 +0100 Subject: [PATCH 2231/2280] Advanced fetchart source config: add validation function --- beets/plugins.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/beets/plugins.py b/beets/plugins.py index 1dc1f6496..5e71c532e 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -511,6 +511,44 @@ def sanitize_choices(choices, choices_all): return res +def sanitize_pairs(pairs, pairs_all): + """Clean up a single-element mapping configuration attribute as returned + by `confit`'s `Pairs` template: keep only two-element tuples present in + pairs_all, remove duplicate elements, expand ('str', '*') and ('*', '*') + wildcards while keeping the original order. Note that ('*', '*') and + ('*', 'whatever') have the same effect. + + For example, + + >>> sanitize_pairs( + ... [('foo', 'baz bar'), ('key', '*'), ('*', '*')], + ... [('foo', 'bar'), ('foo', 'baz'), ('foo', 'foobar'), + ... ('key', 'value')] + ... ) + [('foo', 'baz'), ('foo', 'bar'), ('key', 'value'), ('foo', 'foobar')] + """ + pairs_all = list(pairs_all) + seen = set() + others = [x for x in pairs_all if x not in pairs] + res = [] + for k, values in pairs: + for v in values.split(): + x = (k, v) + if x in pairs_all: + if not x in seen: + seen.add(x) + res.append(x) + elif k == '*': + new = [o for o in others if o not in seen] + seen.update(new) + res.extend(new) + elif v == '*': + new = [o for o in others if o not in seen and o[0] == k] + seen.update(new) + res.extend(new) + return res + + def notify_info_yielded(event): """Makes a generator send the event 'event' every time it yields. This decorator is supposed to decorate a generator, but any function From 60bffbadbdee3652f65ff495a0436797a5296f71 Mon Sep 17 00:00:00 2001 From: wordofglass <wordofglass@users.noreply.github.com> Date: Mon, 13 Nov 2017 01:56:57 +0100 Subject: [PATCH 2232/2280] Advanced fetchart source config: write (restore?) confit' as_pairs() --- beets/util/confit.py | 79 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/beets/util/confit.py b/beets/util/confit.py index 73ae97abc..7b5d39f29 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -413,6 +413,12 @@ class ConfigView(object): """ return self.get(StrSeq(split=split)) + def as_pairs(self, default_value=None): + """Get the value as a sequence of pairs of two strings. Equivalent to + `get(Pairs())`. + """ + return self.get(Pairs(default_value=default_value)) + def as_str(self): """Get the value as a (Unicode) string. Equivalent to `get(unicode)` on Python 2 and `get(str)` on Python 3. @@ -1242,30 +1248,75 @@ class StrSeq(Template): super(StrSeq, self).__init__() self.split = split + def _convert_value(self, x, view): + if isinstance(x, STRING): + return x + elif isinstance(x, bytes): + return x.decode('utf-8', 'ignore') + else: + self.fail(u'must be a list of strings', view, True) + def convert(self, value, view): if isinstance(value, bytes): value = value.decode('utf-8', 'ignore') if isinstance(value, STRING): if self.split: - return value.split() + value = value.split() else: - return [value] + value = [value] + else: + try: + value = list(value) + except TypeError: + self.fail(u'must be a whitespace-separated string or a list', + view, True) + return [self._convert_value(v, view) for v in value] + + +class Pairs(StrSeq): + """A template for ordered key-value pairs. + + This can either be given with the same syntax as for `StrSeq` (i.e. without + values), or as a list of strings and/or single-element mappings such as:: + + - key: value + - [key, value] + - key + + The result is a list of two-element tuples. If no value is provided, the + `default_value` will be returned as the second element. + """ + + def __init__(self, default_value=None): + """Create a new template. + + `default` is the dictionary value returned for items that are not + a mapping, but a single string. + """ + super(Pairs, self).__init__(split=True) + self.default_value = default_value + + def _convert_value(self, x, view): try: - value = list(value) - except TypeError: - self.fail(u'must be a whitespace-separated string or a list', - view, True) - - def convert(x): - if isinstance(x, STRING): - return x - elif isinstance(x, bytes): - return x.decode('utf-8', 'ignore') + return (super(Pairs, self)._convert_value(x, view), + self.default_value) + except ConfigTypeError: + if isinstance(x, collections.Mapping): + if len(x) != 1: + self.fail(u'must be a single-element mapping', view, True) + k, v = iter_first(x.items()) + elif isinstance(x, collections.Sequence): + if len(x) != 2: + self.fail(u'must be a two-element list', view, True) + k, v = x else: - self.fail(u'must be a list of strings', view, True) - return list(map(convert, value)) + # Is this even possible? -> Likely, if some !directive cause + # YAML to parse this to some custom type. + self.fail(u'must be a single string, mapping, or a list' + str(x), view, True) + return (super(Pairs, self)._convert_value(k, view), + super(Pairs, self)._convert_value(v, view)) class Filename(Template): From e7a3e27ed9528fb175579eb602b1ba29638b4ebe Mon Sep 17 00:00:00 2001 From: wordofglass <wordofglass@users.noreply.github.com> Date: Mon, 13 Nov 2017 02:03:13 +0100 Subject: [PATCH 2233/2280] Advanced fetchart source config: Actually use the new syntax --- beetsplug/fetchart.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index e4a12b84e..b98a68593 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -761,21 +761,30 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): if not self.config['google_key'].get() and \ u'google' in available_sources: available_sources.remove(u'google') - sources_name = plugins.sanitize_choices( - self.config['sources'].as_str_seq(), available_sources) + available_sources = [(s, c) + for s in available_sources + for c in ART_SOURCES[s].VALID_MATCHING_CRITERIA] + sources = plugins.sanitize_pairs( + self.config['sources'].as_pairs(default_value='*'), + available_sources) + if 'remote_priority' in self.config: self._log.warning( u'The `fetch_art.remote_priority` configuration option has ' u'been deprecated. Instead, place `filesystem` at the end of ' u'your `sources` list.') if self.config['remote_priority'].get(bool): - try: - sources_name.remove(u'filesystem') - sources_name.append(u'filesystem') - except ValueError: - pass - self.sources = [ART_SOURCES[s](self._log, self.config, None) - for s in sources_name] + fs = [] + others = [] + for s, c in sources: + if s == 'filesystem': + fs.append((s, c)) + else: + others.append((s, c)) + sources = others + fs + + self.sources = [ART_SOURCES[s](self._log, self.config, match_by=[c]) + for s, c in sources] # Asynchronous; after music is added to the library. def fetch_art(self, session, task): From 318f0c4d16710712ed49d10c621fbf52705161dd Mon Sep 17 00:00:00 2001 From: wisp3rwind <17089248+wisp3rwind@users.noreply.github.com> Date: Fri, 23 Feb 2018 16:00:41 +0100 Subject: [PATCH 2234/2280] Advanced fetchart source config: pep8 --- beets/plugins.py | 2 +- beets/util/confit.py | 4 +++- beetsplug/fetchart.py | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/beets/plugins.py b/beets/plugins.py index 5e71c532e..1bd2cacd5 100644 --- a/beets/plugins.py +++ b/beets/plugins.py @@ -535,7 +535,7 @@ def sanitize_pairs(pairs, pairs_all): for v in values.split(): x = (k, v) if x in pairs_all: - if not x in seen: + if x not in seen: seen.add(x) res.append(x) elif k == '*': diff --git a/beets/util/confit.py b/beets/util/confit.py index 7b5d39f29..b5513f48e 100644 --- a/beets/util/confit.py +++ b/beets/util/confit.py @@ -1314,7 +1314,9 @@ class Pairs(StrSeq): else: # Is this even possible? -> Likely, if some !directive cause # YAML to parse this to some custom type. - self.fail(u'must be a single string, mapping, or a list' + str(x), view, True) + self.fail(u'must be a single string, mapping, or a list' + u'' + str(x), + view, True) return (super(Pairs, self)._convert_value(k, view), super(Pairs, self)._convert_value(v, view)) diff --git a/beetsplug/fetchart.py b/beetsplug/fetchart.py index b98a68593..0e106694d 100644 --- a/beetsplug/fetchart.py +++ b/beetsplug/fetchart.py @@ -762,8 +762,8 @@ class FetchArtPlugin(plugins.BeetsPlugin, RequestMixin): u'google' in available_sources: available_sources.remove(u'google') available_sources = [(s, c) - for s in available_sources - for c in ART_SOURCES[s].VALID_MATCHING_CRITERIA] + for s in available_sources + for c in ART_SOURCES[s].VALID_MATCHING_CRITERIA] sources = plugins.sanitize_pairs( self.config['sources'].as_pairs(default_value='*'), available_sources) From dee288545758e9670c816c964b5fb6461f293296 Mon Sep 17 00:00:00 2001 From: wisp3rwind <17089248+wisp3rwind@users.noreply.github.com> Date: Sat, 24 Feb 2018 10:54:50 +0100 Subject: [PATCH 2235/2280] docs/plugins/fetchart: fix internal link target location --- docs/plugins/fetchart.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index e375f9f57..85d22078a 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -104,8 +104,6 @@ already have it; the ``-f`` or ``--force`` switch makes it search for art in Web databases regardless. If you specify a query, only matching albums will be processed; otherwise, the command processes every album in your library. -.. _image-resizing: - Display Only Missing Album Art ------------------------------ @@ -117,6 +115,8 @@ art:: By default the command will display all results, the ``-q`` or ``--quiet`` switch will only display results for album arts that are still missing. +.. _image-resizing: + Image Resizing -------------- From db85c28c7f4899e3db1c650b0fb04ff59a06c0ab Mon Sep 17 00:00:00 2001 From: wisp3rwind <17089248+wisp3rwind@users.noreply.github.com> Date: Sat, 24 Feb 2018 10:55:29 +0100 Subject: [PATCH 2236/2280] Advanced fetchart source config: documentation --- docs/plugins/fetchart.rst | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 85d22078a..58ca0b1f4 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -54,7 +54,8 @@ file. The available options are: matches at the cost of some speed. They are searched in the given order, thus in the default config, no remote (Web) art source are queried if local art is found in the filesystem. To use a local image as fallback, - move it to the end of the list. + move it to the end of the list. For even more fine-grained control over + the search order, see the section on :ref:`album-art-sources` below. - **google_key**: Your Google API key (to enable the Google Custom Search backend). Default: None. @@ -135,6 +136,8 @@ environment variable so that ImageMagick comes first or use Pillow instead. .. _Pillow: https://github.com/python-pillow/Pillow .. _ImageMagick: http://www.imagemagick.org/ +.. _album-art-sources: + Album Art Sources ----------------- @@ -150,6 +153,25 @@ file whose name contains "cover", "front", "art", "album" or "folder", but in the absence of well-known names, it will use any image file in the same folder as your music files. +For some of the art sources, the backend service can match artwork by various +criteria. If you want finer control over the search order in such cases, the +following alternative syntax for the ``sources`` option can be used:: + + fetchart: + sources: + - filesystem + - coverart: release + - itunes + - coverart: releasegroup + - '*' + +where listing a source without matching criteria will default to trying all +available strategies. Entries of the forms ``coverart: release releasegroup`` +and ``coverart: *`` are also valid. +Currently, the ``coverart`` source is the only backend to support several +such values, namely ``release`` and ``releasegroup``, which refer to the +respective MusicBrainz IDs. + When you choose to apply changes during an import, beets will search for art as described above. For "as-is" imports (and non-autotagged imports using the ``-A`` flag), beets only looks for art on the local filesystem. From a6ae1570f92437276f2fb926d32bf88badf92422 Mon Sep 17 00:00:00 2001 From: wisp3rwind <17089248+wisp3rwind@users.noreply.github.com> Date: Sat, 24 Feb 2018 11:29:36 +0100 Subject: [PATCH 2237/2280] Advanced fetchart source config: changelog --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index f423ea832..3121b3394 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,9 @@ New features: recording skipped directories to the incremental list, so you can revisit them later. Thanks to :user:`sekjun9878`. :bug:`2773` +* :doc:`/plugins/fetchart`: extended syntax for the ``sources`` option to give + fine-grained control over the search order for backends with several matching + strategies. Fixes: From 1254d48b7245f8f25560de18a36611c2cc55092a Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Sat, 24 Feb 2018 10:42:32 -0500 Subject: [PATCH 2238/2280] Revise docs for #2739 --- docs/plugins/fetchart.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/plugins/fetchart.rst b/docs/plugins/fetchart.rst index 58ca0b1f4..d6d9adeff 100644 --- a/docs/plugins/fetchart.rst +++ b/docs/plugins/fetchart.rst @@ -154,8 +154,8 @@ the absence of well-known names, it will use any image file in the same folder as your music files. For some of the art sources, the backend service can match artwork by various -criteria. If you want finer control over the search order in such cases, the -following alternative syntax for the ``sources`` option can be used:: +criteria. If you want finer control over the search order in such cases, you +can use this alternative syntax for the ``sources`` option:: fetchart: sources: @@ -168,8 +168,8 @@ following alternative syntax for the ``sources`` option can be used:: where listing a source without matching criteria will default to trying all available strategies. Entries of the forms ``coverart: release releasegroup`` and ``coverart: *`` are also valid. -Currently, the ``coverart`` source is the only backend to support several -such values, namely ``release`` and ``releasegroup``, which refer to the +Currently, only the ``coverart`` source supports multiple criteria: +namely, ``release`` and ``releasegroup``, which refer to the respective MusicBrainz IDs. When you choose to apply changes during an import, beets will search for art as From df83516086cd293e2074691fcbc77eecdb441674 Mon Sep 17 00:00:00 2001 From: waweic <hesiha@gmx.de> Date: Mon, 26 Feb 2018 17:01:06 +0100 Subject: [PATCH 2239/2280] Fix jumping time in beets.js Round was used instead of floor --- beetsplug/web/static/beets.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/static/beets.js b/beetsplug/web/static/beets.js index ec9aae9b3..51985c183 100644 --- a/beetsplug/web/static/beets.js +++ b/beetsplug/web/static/beets.js @@ -4,7 +4,7 @@ var timeFormat = function(secs) { return '0:00'; } secs = Math.round(secs); - var mins = '' + Math.round(secs / 60); + var mins = '' + Math.floor(secs / 60); secs = '' + (secs % 60); if (secs.length < 2) { secs = '0' + secs; From be96c1022a82774fbbc7d4de421c14c286ca14d8 Mon Sep 17 00:00:00 2001 From: waweic <hesiha@gmx.de> Date: Mon, 26 Feb 2018 18:33:30 +0100 Subject: [PATCH 2240/2280] Fix album_art() in __init__.py flask.send_file() expects a string, g.lib.get_album() returns bytes. Added decode() to album_art(). If g.lib.get_album() gets a non-existing id, it returns None. Python would throw an error in this case. Added check to prevent this. --- beetsplug/web/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 635c2f5a8..9de44dcb4 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -285,8 +285,8 @@ def album_query(queries): @app.route('/album/<int:album_id>/art') def album_art(album_id): album = g.lib.get_album(album_id) - if album.artpath: - return flask.send_file(album.artpath) + if album and album.artpath: + return flask.send_file(album.artpath.decode()) else: return flask.abort(404) From e3599742b44a8d2053d98e004d71a9451c001610 Mon Sep 17 00:00:00 2001 From: Samuel Loury <konubinixweb@gmail.com> Date: Mon, 26 Feb 2018 16:10:54 +0100 Subject: [PATCH 2241/2280] Add a support for supports_credentials If the web plugin is behind a credential based http server and is accessed by another in-browser client in another domain, the specification of CORS requires the server to indicate it supports such credentials. --- beetsplug/web/__init__.py | 8 +++++++- docs/changelog.rst | 3 +++ docs/plugins/web.rst | 18 +++++++++++------- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 635c2f5a8..c78e7b73b 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -341,6 +341,7 @@ class WebPlugin(BeetsPlugin): 'host': u'127.0.0.1', 'port': 8337, 'cors': '', + 'cors_supports_credentials': False, 'reverse_proxy': False, 'include_paths': False, }) @@ -372,7 +373,12 @@ class WebPlugin(BeetsPlugin): app.config['CORS_RESOURCES'] = { r"/*": {"origins": self.config['cors'].get(str)} } - CORS(app) + CORS( + app, + supports_credentials=self.config[ + 'cors_supports_credentials' + ] + ) # Allow serving behind a reverse proxy if self.config['reverse_proxy']: diff --git a/docs/changelog.rst b/docs/changelog.rst index 3121b3394..ab1d53e48 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,9 @@ New features: * :doc:`/plugins/fetchart`: extended syntax for the ``sources`` option to give fine-grained control over the search order for backends with several matching strategies. +* :doc:`/plugins/web`: added the boolean ``cors_supports_credentials`` option to + allow in-browser clients to login to the beet web server even when it is + protected by an authorization mechanism. Fixes: diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index 73a2b9147..fcf7e4934 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -63,6 +63,8 @@ configuration file. The available options are: Default: 8337. - **cors**: The CORS allowed origin (see :ref:`web-cors`, below). Default: CORS is disabled. +- **cors_supports_credentials**: Support credentials when using CORS (see :ref:`web-cors`, below). + Default: CORS_SUPPORTS_CREDENTIALS is disabled. - **reverse_proxy**: If true, enable reverse proxy support (see :ref:`reverse-proxy`, below). Default: false. @@ -100,13 +102,15 @@ default, browsers will only allow access from clients running on the same server as the API. (You will get an arcane error about ``XMLHttpRequest`` otherwise.) A technology called `CORS`_ lets you relax this restriction. -If you want to use an in-browser client hosted elsewhere (or running from -a different server on your machine), first install the `flask-cors`_ plugin by -typing ``pip install flask-cors``. Then set the ``cors`` configuration option -to the "origin" (protocol, host, and optional port number) where the client is -served. Or set it to ``'*'`` to enable access from all origins. Note that -there are security implications if you set the origin to ``'*'``, so please -research this before using it. +If you want to use an in-browser client hosted elsewhere (or running from a +different server on your machine), first install the `flask-cors`_ plugin by +typing ``pip install flask-cors``. Then set the ``cors`` configuration option to +the "origin" (protocol, host, and optional port number) where the client is +served. Or set it to ``'*'`` to enable access from all origins. Note that there +are security implications if you set the origin to ``'*'``, so please research +this before using it. In addition, if the ``web`` server is hidden via +credentials, you might want to set the ``cors_supports_credentials`` +configuration option to True for the in-browser client to be able to login. For example:: From 00f61e928130db7e33f9c8fc7652f268d1b0aa73 Mon Sep 17 00:00:00 2001 From: waweic <hesiha@gmx.de> Date: Mon, 26 Feb 2018 21:18:41 +0100 Subject: [PATCH 2242/2280] Update changelog.rst Add the changelog entry --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3121b3394..afd1ae407 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -65,6 +65,9 @@ Fixes: * Importing a release with multiple release events now selects the event based on the order of your :ref:`preferred` countries rather than the order of release events in MusicBrainz. :bug:`2816` +* :doc:`/plugins/web`: The time display in the web interface would incorrectly jump + at the 30-second mark of every minute. Now, it correctly changes over at zero + seconds. :bug:`2822` For developers: From 453fd372a3ff389ed928b54aa3c3812cf9bf781e Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Mon, 26 Feb 2018 18:00:59 -0500 Subject: [PATCH 2243/2280] Flatten a config view (#2821) --- beetsplug/web/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index c78e7b73b..fd0060f4c 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -377,7 +377,7 @@ class WebPlugin(BeetsPlugin): app, supports_credentials=self.config[ 'cors_supports_credentials' - ] + ].get(bool) ) # Allow serving behind a reverse proxy From 6d5a1e9284ed10d11158ac22160ccf4554b20d88 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Mon, 26 Feb 2018 18:02:16 -0500 Subject: [PATCH 2244/2280] web docs: Split CORS credentials paragraph (#2821) --- docs/plugins/web.rst | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/plugins/web.rst b/docs/plugins/web.rst index fcf7e4934..35287acc8 100644 --- a/docs/plugins/web.rst +++ b/docs/plugins/web.rst @@ -108,9 +108,11 @@ typing ``pip install flask-cors``. Then set the ``cors`` configuration option to the "origin" (protocol, host, and optional port number) where the client is served. Or set it to ``'*'`` to enable access from all origins. Note that there are security implications if you set the origin to ``'*'``, so please research -this before using it. In addition, if the ``web`` server is hidden via -credentials, you might want to set the ``cors_supports_credentials`` -configuration option to True for the in-browser client to be able to login. +this before using it. + +If the ``web`` server is behind a proxy that uses credentials, you might want +to set the ``cors_supports_credentials`` configuration option to true to let +in-browser clients log in. For example:: From 8793bb0882fa60c339470839ed72cf436627672e Mon Sep 17 00:00:00 2001 From: waweic <hesiha@gmx.de> Date: Tue, 27 Feb 2018 22:37:05 +0100 Subject: [PATCH 2245/2280] Update changelog.rst Add the changelog entry --- docs/changelog.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a4dfd2cb4..26de4dfaa 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -71,6 +71,10 @@ Fixes: * :doc:`/plugins/web`: The time display in the web interface would incorrectly jump at the 30-second mark of every minute. Now, it correctly changes over at zero seconds. :bug:`2822` +* :doc:`/plugins/web`: In a python 3 enviroment, the function to fetch the + album art would not work and throw an exception. It now works as expected. + Additionally, the server will now return a 404 response when the album id + is unknown, instead of a 500 response and a thrown exception. :bug:`2823` For developers: From 4df313e3cea9dea1c82da6360a27a6fd5a1b6e32 Mon Sep 17 00:00:00 2001 From: Waweic <hesiha@gmx.de> Date: Thu, 1 Mar 2018 11:56:38 +0100 Subject: [PATCH 2246/2280] Fix unicode problems in web plugin Added Exception to the web plugin to catch non latin-1 characters and change them to ascii chars. Added Description to the changelog file --- beetsplug/web/__init__.py | 11 ++++++----- docs/changelog.rst | 4 ++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index efbc3a99d..c85e6a8c0 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -24,6 +24,7 @@ import flask from flask import g from werkzeug.routing import BaseConverter, PathConverter import os +from unidecode import unidecode import json import base64 @@ -224,12 +225,12 @@ def item_file(item_id): item_path = util.syspath(item.path) else: item_path = util.py3_path(item.path) + try: + os.path.basename(util.py3_path(item.path)).encode("latin-1", "strict") #Imitate http.server behaviour + response = flask.send_file(item_path,as_attachment=True) + except UnicodeEncodeError: + response = flask.send_file(item_path,as_attachment=True, attachment_filename=unidecode(os.path.basename(util.py3_path(item.path)))) - response = flask.send_file( - item_path, - as_attachment=True, - attachment_filename=os.path.basename(util.py3_path(item.path)), - ) response.headers['Content-Length'] = os.path.getsize(item_path) return response diff --git a/docs/changelog.rst b/docs/changelog.rst index 26de4dfaa..2ae9ef074 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -75,6 +75,10 @@ Fixes: album art would not work and throw an exception. It now works as expected. Additionally, the server will now return a 404 response when the album id is unknown, instead of a 500 response and a thrown exception. :bug:`2823` +* :doc:`/plugins/web`: In a python 3 enviroment, the server would throw an + exception if non latin-1 characters where in the File name. + It now checks if non latin-1 characters are in the filename and changes + them to ascii-characters in that case :bug:`2815` For developers: From d0fd41b47484eca2fcf7c271ec35431f13cccd76 Mon Sep 17 00:00:00 2001 From: Waweic <hesiha@gmx.de> Date: Thu, 1 Mar 2018 19:45:44 +0100 Subject: [PATCH 2247/2280] Add unicode support for Python 2 and 3 Converts bytes to unicode using util.text_string, assuming that the string is a UTF-8 string. If that fails, it falls back to a hardcoded fallback filename. --- beetsplug/web/__init__.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index c85e6a8c0..f9512ddc1 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -225,12 +225,19 @@ def item_file(item_id): item_path = util.syspath(item.path) else: item_path = util.py3_path(item.path) - try: - os.path.basename(util.py3_path(item.path)).encode("latin-1", "strict") #Imitate http.server behaviour - response = flask.send_file(item_path,as_attachment=True) - except UnicodeEncodeError: - response = flask.send_file(item_path,as_attachment=True, attachment_filename=unidecode(os.path.basename(util.py3_path(item.path)))) + try: + unicode_item_path = util.text_string(item.path) + except: + unicode_item_path = u"fallback" + os.path.splitext(item_path)[1] + + try: + os.path.basename(unicode_item_path).encode("latin-1", "strict") #Imitate http.server behaviour + safe_filename = os.path.basename(unicode_item_path) + except: + safe_filename = unidecode(os.path.basename(unicode_item_path)) + + response = flask.send_file(item_path,as_attachment=True, attachment_filename=safe_filename) response.headers['Content-Length'] = os.path.getsize(item_path) return response From 3c3e579dccbe20936ad44e5a9f6c043dd496983f Mon Sep 17 00:00:00 2001 From: Waweic <hesiha@gmx.de> Date: Thu, 1 Mar 2018 20:20:38 +0100 Subject: [PATCH 2248/2280] Make programming style pep8 compliant --- beetsplug/web/__init__.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index f9512ddc1..29bb6b27a 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -228,16 +228,21 @@ def item_file(item_id): try: unicode_item_path = util.text_string(item.path) - except: + except (UnicodeDecodeError, UnicodeEncodeError): unicode_item_path = u"fallback" + os.path.splitext(item_path)[1] try: - os.path.basename(unicode_item_path).encode("latin-1", "strict") #Imitate http.server behaviour + # Imitate http.server behaviour + os.path.basename(unicode_item_path).encode("latin-1", "strict") safe_filename = os.path.basename(unicode_item_path) - except: + except (UnicodeDecodeError, UnicodeEncodeError): safe_filename = unidecode(os.path.basename(unicode_item_path)) - response = flask.send_file(item_path,as_attachment=True, attachment_filename=safe_filename) + response = flask.send_file( + item_path, + as_attachment=True, + attachment_filename=safe_filename + ) response.headers['Content-Length'] = os.path.getsize(item_path) return response From 06d4fe254d22a9f5315609f3a0908aef527a5d4c Mon Sep 17 00:00:00 2001 From: Waweic <hesiha@gmx.de> Date: Tue, 6 Mar 2018 17:49:20 +0100 Subject: [PATCH 2249/2280] Implement recommendations by sampsyo Implemented all recommendations. --- beetsplug/web/__init__.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/beetsplug/web/__init__.py b/beetsplug/web/__init__.py index 29bb6b27a..3cf43ed56 100644 --- a/beetsplug/web/__init__.py +++ b/beetsplug/web/__init__.py @@ -229,14 +229,16 @@ def item_file(item_id): try: unicode_item_path = util.text_string(item.path) except (UnicodeDecodeError, UnicodeEncodeError): - unicode_item_path = u"fallback" + os.path.splitext(item_path)[1] + unicode_item_path = util.displayable_path(item.path) + base_filename = os.path.basename(unicode_item_path) try: # Imitate http.server behaviour - os.path.basename(unicode_item_path).encode("latin-1", "strict") - safe_filename = os.path.basename(unicode_item_path) - except (UnicodeDecodeError, UnicodeEncodeError): - safe_filename = unidecode(os.path.basename(unicode_item_path)) + base_filename.encode("latin-1", "strict") + except UnicodeEncodeError: + safe_filename = unidecode(base_filename) + else: + safe_filename = base_filename response = flask.send_file( item_path, From 245cf1a74d2930a393459477907ac54ca4ca6bc8 Mon Sep 17 00:00:00 2001 From: jhermann <jh@web.de> Date: Sun, 11 Mar 2018 16:02:10 +0100 Subject: [PATCH 2250/2280] Partial fix for cmd names with dashes (ref #2836) This patch avoids errors during completion when a plugin uses names like "sub-command". It does not make completion fully working for such commands though, thus no close. --- beets/ui/commands.py | 4 ++-- beets/ui/completion_base.sh | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/beets/ui/commands.py b/beets/ui/commands.py index 338bceb83..610ae551e 100644 --- a/beets/ui/commands.py +++ b/beets/ui/commands.py @@ -1758,7 +1758,7 @@ def completion_script(commands): # Command aliases yield u" local aliases='%s'\n" % ' '.join(aliases.keys()) for alias, cmd in aliases.items(): - yield u" local alias__%s=%s\n" % (alias, cmd) + yield u" local alias__%s=%s\n" % (alias.replace('-', '_'), cmd) yield u'\n' # Fields @@ -1775,7 +1775,7 @@ def completion_script(commands): if option_list: option_list = u' '.join(option_list) yield u" local %s__%s='%s'\n" % ( - option_type, cmd, option_list) + option_type, cmd.replace('-', '_'), option_list) yield u' _beet_dispatch\n' yield u'}\n' diff --git a/beets/ui/completion_base.sh b/beets/ui/completion_base.sh index ce3fb6e27..1eaa4db3d 100644 --- a/beets/ui/completion_base.sh +++ b/beets/ui/completion_base.sh @@ -70,7 +70,7 @@ _beet_dispatch() { # Replace command shortcuts if [[ -n $cmd ]] && _list_include_item "$aliases" "$cmd"; then - eval "cmd=\$alias__$cmd" + eval "cmd=\$alias__${cmd//-/_}" fi case $cmd in @@ -94,8 +94,8 @@ _beet_dispatch() { _beet_complete() { if [[ $cur == -* ]]; then local opts flags completions - eval "opts=\$opts__$cmd" - eval "flags=\$flags__$cmd" + eval "opts=\$opts__${cmd//-/_}" + eval "flags=\$flags__${cmd//-/_}" completions="${flags___common} ${opts} ${flags}" COMPREPLY+=( $(compgen -W "$completions" -- $cur) ) else @@ -129,7 +129,7 @@ _beet_complete_global() { COMPREPLY+=( $(compgen -W "$completions" -- $cur) ) elif [[ -n $cur ]] && _list_include_item "$aliases" "$cur"; then local cmd - eval "cmd=\$alias__$cur" + eval "cmd=\$alias__${cur//-/_}" COMPREPLY+=( "$cmd" ) else COMPREPLY+=( $(compgen -W "$commands" -- $cur) ) @@ -138,7 +138,7 @@ _beet_complete_global() { _beet_complete_query() { local opts - eval "opts=\$opts__$cmd" + eval "opts=\$opts__${cmd//-/_}" if [[ $cur == -* ]] || _list_include_item "$opts" "$prev"; then _beet_complete From 2941833f2227431ea1934da1e1bfb65d57bcf179 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Sun, 11 Mar 2018 21:31:56 -0400 Subject: [PATCH 2251/2280] Changelog for #2837 --- docs/changelog.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index 2ae9ef074..b55ec4904 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -79,6 +79,9 @@ Fixes: exception if non latin-1 characters where in the File name. It now checks if non latin-1 characters are in the filename and changes them to ascii-characters in that case :bug:`2815` +* Partially fix bash completion for subcommand names that contain hyphens. + :bug:`2836` :bug:`2837` + Thanks to :user:`jhermann`. For developers: From b9bac391a91e332d7eb2de913cd21dc41fc13cc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Schieli?= <cschieli@gmail.com> Date: Sun, 18 Mar 2018 15:06:18 +0100 Subject: [PATCH 2252/2280] Really fix album replaygain calculation with gstreamer backend. Fixes #2845 --- beetsplug/replaygain.py | 21 ++++++++++----------- docs/changelog.rst | 1 + 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/beetsplug/replaygain.py b/beetsplug/replaygain.py index a7064451a..a7eb81b5c 100644 --- a/beetsplug/replaygain.py +++ b/beetsplug/replaygain.py @@ -613,16 +613,6 @@ class GStreamerBackend(Backend): self._file = self._files.pop(0) - # Disconnect the decodebin element from the pipeline, set its - # state to READY to to clear it. - self._decbin.unlink(self._conv) - self._decbin.set_state(self.Gst.State.READY) - - # Set a new file on the filesrc element, can only be done in the - # READY state - self._src.set_state(self.Gst.State.READY) - self._src.set_property("location", py3_path(syspath(self._file.path))) - # Ensure the filesrc element received the paused state of the # pipeline in a blocking manner self._src.sync_state_with_parent() @@ -633,9 +623,18 @@ class GStreamerBackend(Backend): self._decbin.sync_state_with_parent() self._decbin.get_state(self.Gst.CLOCK_TIME_NONE) + # Disconnect the decodebin element from the pipeline, set its + # state to READY to to clear it. + self._decbin.unlink(self._conv) + self._decbin.set_state(self.Gst.State.READY) + + # Set a new file on the filesrc element, can only be done in the + # READY state + self._src.set_state(self.Gst.State.READY) + self._src.set_property("location", py3_path(syspath(self._file.path))) + self._decbin.link(self._conv) self._pipe.set_state(self.Gst.State.READY) - self._pipe.set_state(self.Gst.State.PLAYING) return True diff --git a/docs/changelog.rst b/docs/changelog.rst index b55ec4904..4828bcc2d 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -82,6 +82,7 @@ Fixes: * Partially fix bash completion for subcommand names that contain hyphens. :bug:`2836` :bug:`2837` Thanks to :user:`jhermann`. +* Really fix album replaygain calculation with gstreamer backend. :bug:`2846` For developers: From 7f7124348ca0eb23b5717c24380563d03e599a4e Mon Sep 17 00:00:00 2001 From: Owen Campbell <ocampbel@sfu.ca> Date: Thu, 29 Mar 2018 00:22:04 -0700 Subject: [PATCH 2253/2280] Edit README.rst structure - Add repository title - Add `Features` header - Move installation instructions to dedicated `Install` header --- README.rst | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 8172a1b9b..a0f58cf5e 100644 --- a/README.rst +++ b/README.rst @@ -1,3 +1,5 @@ +Beets +===== .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets @@ -26,6 +28,9 @@ Here's an example of beets' brainy tag corrector doing its thing:: * White Light Generation -> Whitelightgenerator * All the Way -> All the Way... +Features +--------- + Because beets is designed as a library, it can do almost anything you can imagine for your music collection. Via `plugins`_, beets becomes a panacea: @@ -72,17 +77,21 @@ shockingly simple if you know a little Python. .. _MusicBrainz: http://musicbrainz.org/ .. _Beatport: https://www.beatport.com +Install +--------- + +You can install beets by typing ``pip install beets``. Then check out the +`Getting Started`_ guide. + +.. _Getting Started: http://beets.readthedocs.org/page/guides/main.html + Read More --------- Learn more about beets at `its Web site`_. Follow `@b33ts`_ on Twitter for news and updates. -You can install beets by typing ``pip install beets``. Then check out the -`Getting Started`_ guide. - .. _its Web site: http://beets.io/ -.. _Getting Started: http://beets.readthedocs.org/page/guides/main.html .. _@b33ts: http://twitter.com/b33ts/ Authors From cba8ae463097cffb0cdff3e414f3edf9387e9a30 Mon Sep 17 00:00:00 2001 From: Owen Campbell <ocampbel@sfu.ca> Date: Thu, 29 Mar 2018 00:31:52 -0700 Subject: [PATCH 2254/2280] Add link to wiki in contribution section --- README.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.rst b/README.rst index a0f58cf5e..cb032614e 100644 --- a/README.rst +++ b/README.rst @@ -85,6 +85,11 @@ You can install beets by typing ``pip install beets``. Then check out the .. _Getting Started: http://beets.readthedocs.org/page/guides/main.html +Contributing +--------- + +Information for developers looking to contribute to beets can be found in the `wiki <https://github.com/beetbox/beets/wiki//>`_. + Read More --------- From e4f72c92528864e78872ea9375cec8fd78225d4f Mon Sep 17 00:00:00 2001 From: Owen Campbell <ocampbel@sfu.ca> Date: Thu, 29 Mar 2018 18:13:49 -0700 Subject: [PATCH 2255/2280] Add feedback - Move header under CI images and convert to lowercase - Remove Features header - Change wording on link to wiki - Add link to Hacking wiki page --- README.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index cb032614e..c7777397c 100644 --- a/README.rst +++ b/README.rst @@ -1,5 +1,3 @@ -Beets -===== .. image:: http://img.shields.io/pypi/v/beets.svg :target: https://pypi.python.org/pypi/beets @@ -10,6 +8,9 @@ Beets :target: https://travis-ci.org/beetbox/beets +beets +===== + Beets is the media library management system for obsessive-compulsive music geeks. @@ -28,9 +29,6 @@ Here's an example of beets' brainy tag corrector doing its thing:: * White Light Generation -> Whitelightgenerator * All the Way -> All the Way... -Features ---------- - Because beets is designed as a library, it can do almost anything you can imagine for your music collection. Via `plugins`_, beets becomes a panacea: @@ -88,7 +86,9 @@ You can install beets by typing ``pip install beets``. Then check out the Contributing --------- -Information for developers looking to contribute to beets can be found in the `wiki <https://github.com/beetbox/beets/wiki//>`_. +Developers can consult the technical documentation in the `wiki <https://github.com/beetbox/beets/wiki//>`_. + +To learn how to contribute, read the `Hacking page <https://github.com/beetbox/beets/wiki/Hacking//>`_. Read More --------- From a60c40f930de0d5184794f4895eaf0717041d1a6 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 29 Mar 2018 22:11:03 -0400 Subject: [PATCH 2256/2280] Refine the contributing section --- README.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index c7777397c..24e9d57d2 100644 --- a/README.rst +++ b/README.rst @@ -76,19 +76,20 @@ shockingly simple if you know a little Python. .. _Beatport: https://www.beatport.com Install ---------- +------- You can install beets by typing ``pip install beets``. Then check out the `Getting Started`_ guide. .. _Getting Started: http://beets.readthedocs.org/page/guides/main.html -Contributing ---------- +Contribute +---------- -Developers can consult the technical documentation in the `wiki <https://github.com/beetbox/beets/wiki//>`_. +Check out the `Hacking`_ page on the wiki for tips on how to help out. +You might also be interested in the `For Developers`_ section in the docs. -To learn how to contribute, read the `Hacking page <https://github.com/beetbox/beets/wiki/Hacking//>`_. +.. _For Developers: http://docs.beets.io/page/dev/ Read More --------- From eb31d0d2072fcc4409ff42a6a0af7d175d558300 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 29 Mar 2018 22:11:46 -0400 Subject: [PATCH 2257/2280] My new URL --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 24e9d57d2..28219b6c4 100644 --- a/README.rst +++ b/README.rst @@ -107,4 +107,4 @@ Beets is by `Adrian Sampson`_ with a supporting cast of thousands. For help, please contact the `mailing list`_. .. _mailing list: https://groups.google.com/forum/#!forum/beets-users -.. _Adrian Sampson: http://homes.cs.washington.edu/~asampson/ +.. _Adrian Sampson: http://www.cs.cornell.edu/~asampson/ From b0fa39fc93e157f55fba8d5d9446645849455e2a Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 29 Mar 2018 22:13:02 -0400 Subject: [PATCH 2258/2280] Link to Discourse instead of Google Groups --- README.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 28219b6c4..2d26cef3e 100644 --- a/README.rst +++ b/README.rst @@ -104,7 +104,7 @@ Authors ------- Beets is by `Adrian Sampson`_ with a supporting cast of thousands. For help, -please contact the `mailing list`_. +please visit our `forum`_. -.. _mailing list: https://groups.google.com/forum/#!forum/beets-users +.. _forum: https://discourse.beets.io .. _Adrian Sampson: http://www.cs.cornell.edu/~asampson/ From 7b65da3e51e5fe07c8e0333da8d5b90b758c69ce Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Thu, 29 Mar 2018 22:14:08 -0400 Subject: [PATCH 2259/2280] Fix missing link --- README.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/README.rst b/README.rst index 2d26cef3e..a3ea6302f 100644 --- a/README.rst +++ b/README.rst @@ -89,6 +89,7 @@ Contribute Check out the `Hacking`_ page on the wiki for tips on how to help out. You might also be interested in the `For Developers`_ section in the docs. +.. _Hacking: https://github.com/beetbox/beets/wiki/Hacking .. _For Developers: http://docs.beets.io/page/dev/ Read More From feca2b9ffb50054b53ec9d870c7a07c7a192cb50 Mon Sep 17 00:00:00 2001 From: Laurent Kislaire <teebeenator@gmail.com> Date: Sun, 1 Apr 2018 20:27:52 +0200 Subject: [PATCH 2260/2280] Plugins doc update Sort plugins within each section. Section "other plugins" kept as is. --- docs/plugins/index.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index e37a270fa..b17c4db98 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -54,10 +54,11 @@ like this:: embyupdate export fetchart + filefilter + freedesktop fromfilename ftintitle fuzzy - freedesktop gmusic hook ihate @@ -82,7 +83,6 @@ like this:: play plexupdate random - filefilter replaygain rewrite scrub @@ -147,6 +147,7 @@ Path Formats Interoperability ---------------- +* :doc:`badfiles`: Check audio file integrity. * :doc:`embyupdate`: Automatically notifies `Emby`_ whenever the beets library changes. * :doc:`importfeeds`: Keep track of imported files via ``.m3u`` playlist file(s) or symlinks. * :doc:`ipfs`: Import libraries from friends and get albums from them via ipfs. @@ -159,7 +160,6 @@ Interoperability changes. * :doc:`smartplaylist`: Generate smart playlists based on beets queries. * :doc:`thumbnails`: Get thumbnails with the cover art on your album folders. -* :doc:`badfiles`: Check audio file integrity. .. _Emby: http://emby.media @@ -175,6 +175,8 @@ Miscellaneous a different directory. * :doc:`duplicates`: List duplicate tracks or albums. * :doc:`export`: Export data from queries to a format. +* :doc:`filefilter`: Automatically skip files during the import process based + on regular expressions. * :doc:`fuzzy`: Search albums and tracks with fuzzy string matching. * :doc:`gmusic`: Search and upload files to Google Play Music. * :doc:`hook`: Run a command when an event is emitted by beets. @@ -184,8 +186,6 @@ Miscellaneous * :doc:`mbsubmit`: Print an album's tracks in a MusicBrainz-friendly format. * :doc:`missing`: List missing tracks. * :doc:`random`: Randomly choose albums and tracks from your library. -* :doc:`filefilter`: Automatically skip files during the import process based - on regular expressions. * :doc:`spotify`: Create Spotify playlists from the Beets library. * :doc:`types`: Declare types for flexible attributes. * :doc:`web`: An experimental Web-based GUI for beets. From a829fa348f203706fd4d1852d56385402a6354ae Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Wed, 4 Apr 2018 10:41:38 -0400 Subject: [PATCH 2261/2280] Fix #2863: nonexistent identical paths are equal --- beets/util/__init__.py | 2 ++ docs/changelog.rst | 2 ++ 2 files changed, 4 insertions(+) diff --git a/beets/util/__init__.py b/beets/util/__init__.py index db341a646..69870edf2 100644 --- a/beets/util/__init__.py +++ b/beets/util/__init__.py @@ -422,6 +422,8 @@ def syspath(path, prefix=True): def samefile(p1, p2): """Safer equality for paths.""" + if p1 == p2: + return True return shutil._samefile(syspath(p1), syspath(p2)) diff --git a/docs/changelog.rst b/docs/changelog.rst index 4828bcc2d..aa930904a 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -83,6 +83,8 @@ Fixes: :bug:`2836` :bug:`2837` Thanks to :user:`jhermann`. * Really fix album replaygain calculation with gstreamer backend. :bug:`2846` +* Avoid an error when doing a "no-op" move on non-existent files (i.e., moving + a file onto itself). :bug:`2863` For developers: From 0202d762bf51d0861a2f9970fa6f5df3d807c2d2 Mon Sep 17 00:00:00 2001 From: Denis Defreyne <denis.defreyne@stoneship.org> Date: Sat, 7 Apr 2018 22:20:48 +0200 Subject: [PATCH 2262/2280] Add artist_credit config option --- beets/autotag/__init__.py | 17 ++++++++++++----- beets/config_default.yaml | 1 + docs/changelog.rst | 7 +++++-- docs/reference/config.rst | 9 +++++++++ test/test_autotag.py | 21 ++++++++++++++++++++- 5 files changed, 47 insertions(+), 8 deletions(-) diff --git a/beets/autotag/__init__.py b/beets/autotag/__init__.py index 4c5f09eb4..09564f49d 100644 --- a/beets/autotag/__init__.py +++ b/beets/autotag/__init__.py @@ -63,12 +63,19 @@ def apply_metadata(album_info, mapping): mapping from Items to TrackInfo objects. """ for item, track_info in mapping.items(): - # Album, artist, track count. - if track_info.artist: - item.artist = track_info.artist + # Artist or artist credit. + if config['artist_credit']: + item.artist = (track_info.artist_credit or + track_info.artist or + album_info.artist_credit or + album_info.artist) + item.albumartist = (album_info.artist_credit or + album_info.artist) else: - item.artist = album_info.artist - item.albumartist = album_info.artist + item.artist = (track_info.artist or album_info.artist) + item.albumartist = album_info.artist + + # Album. item.album = album_info.album # Artist sort and credit names. diff --git a/beets/config_default.yaml b/beets/config_default.yaml index 27aa3d4ca..273f94235 100644 --- a/beets/config_default.yaml +++ b/beets/config_default.yaml @@ -56,6 +56,7 @@ per_disc_numbering: no verbose: 0 terminal_encoding: original_date: no +artist_credit: no id3v23: no va_name: "Various Artists" diff --git a/docs/changelog.rst b/docs/changelog.rst index aa930904a..dd04b1d71 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -18,6 +18,9 @@ New features: * :doc:`/plugins/web`: added the boolean ``cors_supports_credentials`` option to allow in-browser clients to login to the beet web server even when it is protected by an authorization mechanism. +* A new importer configuration ``artist_credit`` will tell beets to prefer the + artist credit over the artist when autotagging. + :bug:`1249` Fixes: @@ -75,9 +78,9 @@ Fixes: album art would not work and throw an exception. It now works as expected. Additionally, the server will now return a 404 response when the album id is unknown, instead of a 500 response and a thrown exception. :bug:`2823` -* :doc:`/plugins/web`: In a python 3 enviroment, the server would throw an +* :doc:`/plugins/web`: In a python 3 enviroment, the server would throw an exception if non latin-1 characters where in the File name. - It now checks if non latin-1 characters are in the filename and changes + It now checks if non latin-1 characters are in the filename and changes them to ascii-characters in that case :bug:`2815` * Partially fix bash completion for subcommand names that contain hyphens. :bug:`2836` :bug:`2837` diff --git a/docs/reference/config.rst b/docs/reference/config.rst index 24ed1340d..94dab4345 100644 --- a/docs/reference/config.rst +++ b/docs/reference/config.rst @@ -253,6 +253,15 @@ Either ``yes`` or ``no``, indicating whether matched albums should have their That is, if this option is turned on, then ``year`` will always equal ``original_year`` and so on. Default: ``no``. +.. _artist_credit: + +artist_credit +~~~~~~~~~~~~~ + +Either ``yes`` or ``no``, indicating whether matched tracks and albums should +use the artist credit, rather than the artist. That is, if this option is turned +on, then ``artist`` will contain the artist as credited on the release. + .. _per_disc_numbering: per_disc_numbering diff --git a/test/test_autotag.py b/test/test_autotag.py index 6f107afa4..932616be1 100644 --- a/test/test_autotag.py +++ b/test/test_autotag.py @@ -616,12 +616,13 @@ class AssignmentTest(unittest.TestCase): class ApplyTestUtil(object): - def _apply(self, info=None, per_disc_numbering=False): + def _apply(self, info=None, per_disc_numbering=False, artist_credit=False): info = info or self.info mapping = {} for i, t in zip(self.items, info.tracks): mapping[i] = t config['per_disc_numbering'] = per_disc_numbering + config['artist_credit'] = artist_credit autotag.apply_metadata(info, mapping) @@ -706,6 +707,24 @@ class ApplyTest(_common.TestCase, ApplyTestUtil): self.assertEqual(self.items[0].tracktotal, 1) self.assertEqual(self.items[1].tracktotal, 1) + def test_artist_credit(self): + self._apply(artist_credit=True) + self.assertEqual(self.items[0].artist, 'trackArtistCredit') + self.assertEqual(self.items[1].artist, 'albumArtistCredit') + self.assertEqual(self.items[0].albumartist, 'albumArtistCredit') + self.assertEqual(self.items[1].albumartist, 'albumArtistCredit') + + def test_artist_credit_prefers_artist_over_albumartist_credit(self): + self.info.tracks[0].artist = 'oldArtist' + self.info.tracks[0].artist_credit = None + self._apply(artist_credit=True) + self.assertEqual(self.items[0].artist, 'oldArtist') + + def test_artist_credit_falls_back_to_albumartist(self): + self.info.artist_credit = None + self._apply(artist_credit=True) + self.assertEqual(self.items[1].artist, 'artistNew') + def test_mb_trackid_applied(self): self._apply() self.assertEqual(self.items[0].mb_trackid, From c420f6bf996c53fa8958956626c136ac0e9e55f6 Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Thu, 19 Apr 2018 23:58:40 +0200 Subject: [PATCH 2263/2280] Add sonos updater plugin. --- beetsplug/sonosupdate.py | 58 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 beetsplug/sonosupdate.py diff --git a/beetsplug/sonosupdate.py b/beetsplug/sonosupdate.py new file mode 100644 index 000000000..498ae9835 --- /dev/null +++ b/beetsplug/sonosupdate.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# This file is part of beets. +# Copyright 2018, Tobias Sauerwein. +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. + +"""Updates a Sonos library whenever the beets library is changed. +This is based on the Kodi Update plugin. + +Put something like the following in your config.yaml to configure: + kodi: + host: localhost + port: 8080 + user: user + pwd: secret +""" +from __future__ import division, absolute_import, print_function + +from beets import config +from beets.plugins import BeetsPlugin +import six +import soco + + +class SonosUpdate(BeetsPlugin): + def __init__(self): + super(SonosUpdate, self).__init__() + self.register_listener('database_change', self.listen_for_db_change) + + def listen_for_db_change(self, lib, model): + """Listens for beets db change and register the update""" + self.register_listener('cli_exit', self.update) + + def update(self, lib): + """When the client exists try to send refresh request to a Sonos + controler. + """ + self._log.info(u'Requesting a Sonos library update...') + + # Try to send update request. + try: + device = soco.discovery.any_soco() + device.music_library.start_library_update() + + except: + self._log.warning(u'Sonos update failed') + return + + self._log.info(u'Sonos update triggered') From dcce29eeb32803e745503b362ea1cc9a845d61a4 Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 00:07:40 +0200 Subject: [PATCH 2264/2280] Add documentation for the sonos updater plugin. --- docs/plugins/sonosupdate.rst | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/plugins/sonosupdate.rst diff --git a/docs/plugins/sonosupdate.rst b/docs/plugins/sonosupdate.rst new file mode 100644 index 000000000..1ecf91b92 --- /dev/null +++ b/docs/plugins/sonosupdate.rst @@ -0,0 +1,23 @@ +SonosUpdate Plugin +================= + +The ``sonosupdate`` plugin lets you automatically update `Sonos`_'s music +library whenever you change your beets library. + +To use ``sonosupdate`` plugin, enable it in your configuration +(see :ref:`using-plugins`). + +To use the ``sonosupdate`` plugin you need to install the `soco`_ library with:: + + pip install soco + +With that all in place, you'll see beets send the "update" command to your Sonos +controller every time you change your beets library. + +.. Sonos: http://sonos.com/ +.. _soco: http://python-soco.com + +Configuration +------------- + +There is nothing to configure. From 5e084b7186e3dab883bf7e7c6070303f79097bd0 Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 07:39:12 +0200 Subject: [PATCH 2265/2280] Fix exception handling and add docs to the toc. --- beetsplug/sonosupdate.py | 12 ++---------- docs/changelog.rst | 3 +++ docs/plugins/index.rst | 4 +++- docs/plugins/sonosupdate.rst | 5 ----- 4 files changed, 8 insertions(+), 16 deletions(-) diff --git a/beetsplug/sonosupdate.py b/beetsplug/sonosupdate.py index 498ae9835..622604acf 100644 --- a/beetsplug/sonosupdate.py +++ b/beetsplug/sonosupdate.py @@ -15,17 +15,9 @@ """Updates a Sonos library whenever the beets library is changed. This is based on the Kodi Update plugin. - -Put something like the following in your config.yaml to configure: - kodi: - host: localhost - port: 8080 - user: user - pwd: secret """ from __future__ import division, absolute_import, print_function -from beets import config from beets.plugins import BeetsPlugin import six import soco @@ -51,8 +43,8 @@ class SonosUpdate(BeetsPlugin): device = soco.discovery.any_soco() device.music_library.start_library_update() - except: - self._log.warning(u'Sonos update failed') + except NoneType: + self._log.warning(u'Could not find a Sonos device.') return self._log.info(u'Sonos update triggered') diff --git a/docs/changelog.rst b/docs/changelog.rst index 4381edeeb..a923bfe37 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,9 @@ New features: recording skipped directories to the incremental list, so you can revisit them later. Thanks to :user:`sekjun9878`. :bug:`2773` +* A new interoperability plugin to automatically notify Sonos controllers to + update the music library once the beets library got updated. + Thanks to :user:`cgtobi`. Fixes: diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index e37a270fa..e08a1767f 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -158,6 +158,8 @@ Interoperability * :doc:`plexupdate`: Automatically notifies `Plex`_ whenever the beets library changes. * :doc:`smartplaylist`: Generate smart playlists based on beets queries. +* :doc:`sonosupdate`: Automatically notifies `Sonos`_ whenever the beets library + changes. * :doc:`thumbnails`: Get thumbnails with the cover art on your album folders. * :doc:`badfiles`: Check audio file integrity. @@ -165,6 +167,7 @@ Interoperability .. _Emby: http://emby.media .. _Plex: http://plex.tv .. _Kodi: http://kodi.tv +.. _Sonos: http://sonos.com Miscellaneous ------------- @@ -262,4 +265,3 @@ Here are a few of the plugins written by the beets community: .. _whatlastgenre: https://github.com/YetAnotherNerd/whatlastgenre/tree/master/plugin/beets .. _beets-usertag: https://github.com/igordertigor/beets-usertag .. _beets-popularity: https://github.com/abba23/beets-popularity - diff --git a/docs/plugins/sonosupdate.rst b/docs/plugins/sonosupdate.rst index 1ecf91b92..5a7a6583b 100644 --- a/docs/plugins/sonosupdate.rst +++ b/docs/plugins/sonosupdate.rst @@ -16,8 +16,3 @@ controller every time you change your beets library. .. Sonos: http://sonos.com/ .. _soco: http://python-soco.com - -Configuration -------------- - -There is nothing to configure. From 14538e45afeeab6586f2ed00059003da11bbed5f Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 07:42:57 +0200 Subject: [PATCH 2266/2280] Fix changelog entry. --- docs/changelog.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/changelog.rst b/docs/changelog.rst index a923bfe37..3113b925b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -12,6 +12,15 @@ New features: recording skipped directories to the incremental list, so you can revisit them later. Thanks to :user:`sekjun9878`. :bug:`2773` +* :doc:`/plugins/fetchart`: extended syntax for the ``sources`` option to give + fine-grained control over the search order for backends with several matching + strategies. +* :doc:`/plugins/web`: added the boolean ``cors_supports_credentials`` option to + allow in-browser clients to login to the beet web server even when it is + protected by an authorization mechanism. +* A new importer configuration ``artist_credit`` will tell beets to prefer the + artist credit over the artist when autotagging. + :bug:`1249` * A new interoperability plugin to automatically notify Sonos controllers to update the music library once the beets library got updated. Thanks to :user:`cgtobi`. From 4748a68b6bde662245b85ecf2a52fbedffc4ffcb Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 08:16:56 +0200 Subject: [PATCH 2267/2280] Remove exception handling. --- beetsplug/sonosupdate.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/beetsplug/sonosupdate.py b/beetsplug/sonosupdate.py index 622604acf..23484c653 100644 --- a/beetsplug/sonosupdate.py +++ b/beetsplug/sonosupdate.py @@ -38,12 +38,11 @@ class SonosUpdate(BeetsPlugin): """ self._log.info(u'Requesting a Sonos library update...') - # Try to send update request. - try: - device = soco.discovery.any_soco() - device.music_library.start_library_update() + device = soco.discovery.any_soco() - except NoneType: + if device: + device.music_library.start_library_update() + else: self._log.warning(u'Could not find a Sonos device.') return From 2ac0a0024172853cf853099d36b33f735cf93ffa Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 08:24:05 +0200 Subject: [PATCH 2268/2280] Fix short title underline. --- docs/plugins/sonosupdate.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/sonosupdate.rst b/docs/plugins/sonosupdate.rst index 5a7a6583b..4b47c9a6e 100644 --- a/docs/plugins/sonosupdate.rst +++ b/docs/plugins/sonosupdate.rst @@ -1,5 +1,5 @@ SonosUpdate Plugin -================= +================== The ``sonosupdate`` plugin lets you automatically update `Sonos`_'s music library whenever you change your beets library. From 499b3867b2562ed15b80d296a41416775c8b2fe4 Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 08:25:08 +0200 Subject: [PATCH 2269/2280] Remove unused import. --- beetsplug/sonosupdate.py | 1 - 1 file changed, 1 deletion(-) diff --git a/beetsplug/sonosupdate.py b/beetsplug/sonosupdate.py index 23484c653..56a315a15 100644 --- a/beetsplug/sonosupdate.py +++ b/beetsplug/sonosupdate.py @@ -19,7 +19,6 @@ This is based on the Kodi Update plugin. from __future__ import division, absolute_import, print_function from beets.plugins import BeetsPlugin -import six import soco From ad3b5b1d7663025238040a54e2cb376f09f73f7f Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 08:38:14 +0200 Subject: [PATCH 2270/2280] Fix target name. --- docs/plugins/sonosupdate.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugins/sonosupdate.rst b/docs/plugins/sonosupdate.rst index 4b47c9a6e..97a13bd07 100644 --- a/docs/plugins/sonosupdate.rst +++ b/docs/plugins/sonosupdate.rst @@ -14,5 +14,5 @@ To use the ``sonosupdate`` plugin you need to install the `soco`_ library with:: With that all in place, you'll see beets send the "update" command to your Sonos controller every time you change your beets library. -.. Sonos: http://sonos.com/ +.. _Sonos: http://sonos.com/ .. _soco: http://python-soco.com From 8768e786af1b2705cf5e653349ff8e7e9d07fe6d Mon Sep 17 00:00:00 2001 From: Tobias Sauerwein <cgtobi@gmail.com> Date: Fri, 20 Apr 2018 08:47:43 +0200 Subject: [PATCH 2271/2280] Fix toctree. --- docs/plugins/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index d76136d52..edd82a255 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -87,6 +87,7 @@ like this:: rewrite scrub smartplaylist + sonosupdate spotify the thumbnails From 676536efa7367049d8cacdc384572f35ed47d852 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Fri, 27 Apr 2018 19:28:35 +0200 Subject: [PATCH 2272/2280] Fix incorrect indexing of two-sided mediums Fix incorrect split of a tracklist by medium for the case of two-sided mediums (#2887). Following the discussion in #2887, the 'medium_total' value should contain the number of tracks on the medium to which each particular track belongs, not the total number of different mediums present on a release. Fix unit tests accordingly. --- beetsplug/discogs.py | 8 ++++---- test/test_discogs.py | 22 +++++++++++----------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 0957b3403..515d1af8e 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -246,7 +246,7 @@ class DiscogsPlugin(BeetsPlugin): # Extract information for the optional AlbumInfo fields, if possible. va = result.data['artists'][0].get('name', '').lower() == 'various' year = result.data.get('year') - mediums = len(set(t.medium for t in tracks)) + mediums = [t.medium for t in tracks] country = result.data.get('country') data_url = result.data.get('uri') @@ -270,11 +270,11 @@ class DiscogsPlugin(BeetsPlugin): # `autotag.apply_metadata`, and set `medium_total`. for track in tracks: track.media = media - track.medium_total = mediums + track.medium_total = mediums.count(track.medium) return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, - day=None, label=label, mediums=mediums, + day=None, label=label, mediums=len(set(mediums)), artist_sort=None, releasegroup_id=None, catalognum=catalogno, script=None, language=None, country=country, albumstatus=None, media=media, @@ -351,7 +351,7 @@ class DiscogsPlugin(BeetsPlugin): # are the track index, not the medium. medium_is_index = track.medium and not track.medium_index and ( len(track.medium) != 1 or - ord(track.medium) - 64 != medium_count + 1 + ord(track.medium) - 64 != medium_count * sides_per_medium + side_count ) if not medium_is_index and medium != track.medium: diff --git a/test/test_discogs.py b/test/test_discogs.py index 74f9a5656..8b2eff9f1 100644 --- a/test/test_discogs.py +++ b/test/test_discogs.py @@ -101,9 +101,9 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(d.mediums, 1) self.assertEqual(t[0].medium, 1) - self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[0].medium_total, 2) self.assertEqual(t[1].medium, 1) - self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[0].medium_total, 2) def test_parse_medium_numbers_two_mediums(self): release = self._make_release_from_positions(['1-1', '2-1']) @@ -112,9 +112,9 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(d.mediums, 2) self.assertEqual(t[0].medium, 1) - self.assertEqual(t[0].medium_total, 2) + self.assertEqual(t[0].medium_total, 1) self.assertEqual(t[1].medium, 2) - self.assertEqual(t[1].medium_total, 2) + self.assertEqual(t[1].medium_total, 1) def test_parse_medium_numbers_two_mediums_two_sided(self): release = self._make_release_from_positions(['A1', 'B1', 'C1']) @@ -129,7 +129,7 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[1].medium_total, 2) self.assertEqual(t[1].medium_index, 2) self.assertEqual(t[2].medium, 2) - self.assertEqual(t[2].medium_total, 2) + self.assertEqual(t[2].medium_total, 1) self.assertEqual(t[2].medium_index, 1) def test_parse_track_indices(self): @@ -139,10 +139,10 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(t[0].medium_index, 1) self.assertEqual(t[0].index, 1) - self.assertEqual(t[0].medium_total, 1) + self.assertEqual(t[0].medium_total, 2) self.assertEqual(t[1].medium_index, 2) self.assertEqual(t[1].index, 2) - self.assertEqual(t[1].medium_total, 1) + self.assertEqual(t[1].medium_total, 2) def test_parse_track_indices_several_media(self): release = self._make_release_from_positions(['1-1', '1-2', '2-1', @@ -153,16 +153,16 @@ class DGAlbumInfoTest(_common.TestCase): self.assertEqual(d.mediums, 3) self.assertEqual(t[0].medium_index, 1) self.assertEqual(t[0].index, 1) - self.assertEqual(t[0].medium_total, 3) + self.assertEqual(t[0].medium_total, 2) self.assertEqual(t[1].medium_index, 2) self.assertEqual(t[1].index, 2) - self.assertEqual(t[1].medium_total, 3) + self.assertEqual(t[1].medium_total, 2) self.assertEqual(t[2].medium_index, 1) self.assertEqual(t[2].index, 3) - self.assertEqual(t[2].medium_total, 3) + self.assertEqual(t[2].medium_total, 1) self.assertEqual(t[3].medium_index, 1) self.assertEqual(t[3].index, 4) - self.assertEqual(t[3].medium_total, 3) + self.assertEqual(t[3].medium_total, 1) def test_parse_position(self): """Test the conversion of discogs `position` to medium, medium_index From 2e422122b3f08ce9ce7c69e018094472084ce378 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Fri, 27 Apr 2018 20:30:35 +0200 Subject: [PATCH 2273/2280] Invent our own track IDs for Discogs Discogs does not provide track IDs. As a workaround, invent our own IDs by combining release ID with original track position strings returned by Discogs (#2336). --- beetsplug/discogs.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 515d1af8e..cc404a326 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -271,6 +271,8 @@ class DiscogsPlugin(BeetsPlugin): for track in tracks: track.media = media track.medium_total = mediums.count(track.medium) + # Invent our own track IDs as Discogs doesn't have them + track.track_id = str(album_id) + "-" + track.track_alt return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, From 48140f11e7b86168133b1e9ad794c4ef1ef63da8 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Fri, 27 Apr 2018 21:56:51 +0200 Subject: [PATCH 2274/2280] Use releasegroup_id to store master release IDs from Discogs Master releases roughly correspond to MusicBrainz' release groups. It will be usefull to store master IDs, for example to retrieve original release dates (#1122). --- beetsplug/discogs.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index cc404a326..2d79ca754 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -274,10 +274,13 @@ class DiscogsPlugin(BeetsPlugin): # Invent our own track IDs as Discogs doesn't have them track.track_id = str(album_id) + "-" + track.track_alt + # Retrieve master release id (returns None if there isn't one) + master_id = result.data.get('master_id') + return AlbumInfo(album, album_id, artist, artist_id, tracks, asin=None, albumtype=albumtype, va=va, year=year, month=None, day=None, label=label, mediums=len(set(mediums)), - artist_sort=None, releasegroup_id=None, + artist_sort=None, releasegroup_id=master_id, catalognum=catalogno, script=None, language=None, country=country, albumstatus=None, media=media, albumdisambig=None, artist_credit=None, From 8eb50fee33044dea008408423ee0c534264db0c0 Mon Sep 17 00:00:00 2001 From: Adrian Sampson <adrian@radbox.org> Date: Fri, 27 Apr 2018 17:34:18 -0400 Subject: [PATCH 2275/2280] Avoid weird mutation in web tests This was strange and unnecessary---setting a field on the response object instead of just using a local variable---and also broke on Flask 1.0. --- test/test_web.py | 56 ++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/test/test_web.py b/test/test_web.py index 98347d8af..e7d1f334f 100644 --- a/test/test_web.py +++ b/test/test_web.py @@ -35,41 +35,41 @@ class WebPluginTest(_common.LibTestCase): def test_config_include_paths_true(self): web.app.config['INCLUDE_PATHS'] = True response = self.client.get('/item/1') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['path'], u'/path_1') + self.assertEqual(res_json['path'], u'/path_1') def test_config_include_paths_false(self): web.app.config['INCLUDE_PATHS'] = False response = self.client.get('/item/1') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertNotIn('path', response.json) + self.assertNotIn('path', res_json) def test_get_all_items(self): response = self.client.get('/item/') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) + self.assertEqual(len(res_json['items']), 2) def test_get_single_item_by_id(self): response = self.client.get('/item/1') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['id'], 1) - self.assertEqual(response.json['title'], u'title') + self.assertEqual(res_json['id'], 1) + self.assertEqual(res_json['title'], u'title') def test_get_multiple_items_by_id(self): response = self.client.get('/item/1,2') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) - response_titles = [item['title'] for item in response.json['items']] + self.assertEqual(len(res_json['items']), 2) + response_titles = [item['title'] for item in res_json['items']] assertCountEqual(self, response_titles, [u'title', u'another title']) def test_get_single_item_not_found(self): @@ -80,10 +80,10 @@ class WebPluginTest(_common.LibTestCase): data_path = os.path.join(_common.RSRC, b'full.mp3') self.lib.add(Item.from_path(data_path)) response = self.client.get('/item/path/' + data_path.decode('utf-8')) - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['title'], u'full') + self.assertEqual(res_json['title'], u'full') def test_get_single_item_by_path_not_found_if_not_in_library(self): data_path = os.path.join(_common.RSRC, b'full.mp3') @@ -95,50 +95,50 @@ class WebPluginTest(_common.LibTestCase): def test_get_item_empty_query(self): response = self.client.get('/item/query/') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['items']), 2) + self.assertEqual(len(res_json['items']), 2) def test_get_simple_item_query(self): response = self.client.get('/item/query/another') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['results']), 1) - self.assertEqual(response.json['results'][0]['title'], + self.assertEqual(len(res_json['results']), 1) + self.assertEqual(res_json['results'][0]['title'], u'another title') def test_get_all_albums(self): response = self.client.get('/album/') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - response_albums = [album['album'] for album in response.json['albums']] + response_albums = [album['album'] for album in res_json['albums']] assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_single_album_by_id(self): response = self.client.get('/album/2') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(response.json['id'], 2) - self.assertEqual(response.json['album'], u'another album') + self.assertEqual(res_json['id'], 2) + self.assertEqual(res_json['album'], u'another album') def test_get_multiple_albums_by_id(self): response = self.client.get('/album/1,2') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - response_albums = [album['album'] for album in response.json['albums']] + response_albums = [album['album'] for album in res_json['albums']] assertCountEqual(self, response_albums, [u'album', u'another album']) def test_get_album_empty_query(self): response = self.client.get('/album/query/') - response.json = json.loads(response.data.decode('utf-8')) + res_json = json.loads(response.data.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json['albums']), 2) + self.assertEqual(len(res_json['albums']), 2) def suite(): From 09ee194142bd2fdffb7a6885a402c334b62fe0c4 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Sat, 28 Apr 2018 02:23:46 +0200 Subject: [PATCH 2276/2280] Make Discogs medium indexing code easier to understand --- beetsplug/discogs.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 2d79ca754..cdc80ff83 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -347,30 +347,34 @@ class DiscogsPlugin(BeetsPlugin): # a 2-sided medium. if ''.join(m) in ascii_lowercase: sides_per_medium = 2 - side_count = 1 # Force for first item, where medium == None for track in tracks: # Handle special case where a different medium does not indicate a # new disc, when there is no medium_index and the ordinal of medium # is not sequential. For example, I, II, III, IV, V. Assume these # are the track index, not the medium. + + # side_count is the number of mediums or medium sides (in the case + # of two-sided mediums) that were seen before medium_is_index = track.medium and not track.medium_index and ( len(track.medium) != 1 or - ord(track.medium) - 64 != medium_count * sides_per_medium + side_count + # Not witin standard incremental medium values (A, B, C, ...) + ord(track.medium) - 64 != side_count + 1 ) if not medium_is_index and medium != track.medium: - if side_count < (sides_per_medium - 1): - # Increment side count: side changed, but not medium. - side_count += 1 - medium = track.medium + side_count += 1 + if sides_per_medium == 2: + if side_count % sides_per_medium: + # Two-sided medium changed. Reset index_count + index_count = 0 + medium_count += 1 else: - # Increment medium_count and reset index_count and side - # count when medium changes. - medium = track.medium + # Medium changed. Reset index_count medium_count += 1 index_count = 0 - side_count = 0 + medium = track.medium + index_count += 1 medium_count = 1 if medium_count == 0 else medium_count track.medium, track.medium_index = medium_count, index_count From 0ea5882bc03d8de798e56b8cd55b916e268d43a1 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Sat, 28 Apr 2018 02:32:42 +0200 Subject: [PATCH 2277/2280] Better comments in code explaining Discogs track IDs (#2336) --- beetsplug/discogs.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index cdc80ff83..740948348 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -271,7 +271,8 @@ class DiscogsPlugin(BeetsPlugin): for track in tracks: track.media = media track.medium_total = mediums.count(track.medium) - # Invent our own track IDs as Discogs doesn't have them + # Discogs does not have track IDs. Invent our own IDs as proposed + # in #2336. track.track_id = str(album_id) + "-" + track.track_alt # Retrieve master release id (returns None if there isn't one) From 8c42c458a71bbe8fcd77e8ed5348cc3268aadde8 Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Sat, 28 Apr 2018 03:34:34 +0200 Subject: [PATCH 2278/2280] Update changelog --- docs/changelog.rst | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b1c0d4c29..fafbbbda6 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -24,6 +24,10 @@ New features: * A new interoperability plugin to automatically notify Sonos controllers to update the music library once the beets library got updated. Thanks to :user:`cgtobi`. +* :doc:`/plugins/discogs`: The plugin now stores master release ids into + ``mb_releasegroupid`` as well as simulates track ids using release id + and tracklist positions. Track ids are stored in ``mb_trackid``. :bug:`#2336` + Thanks to :user:`dbogdanov`. Fixes: @@ -35,7 +39,9 @@ Fixes: autotagger. Data tracks will always be ignored, but a new option ``ignore_video_tracks`` has been added to control if video tracks should be ignored or not. :bug:`1210` -* :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` version 0.4.6 or later is required. :bug:`2777` +* :doc:`/plugins/replaygain`: Fix a corner-case with the ``bs1770gain`` backend + where ReplayGain values were assigned to the wrong files. Now ``bs1770gain`` + version 0.4.6 or later is required. :bug:`2777` * :doc:`/plugins/lyrics`: The plugin no longer crashes in the Genius source when BeautifulSoup is not found. Instead, it just logs a message and disables the source. @@ -91,6 +97,13 @@ Fixes: * Really fix album replaygain calculation with gstreamer backend. :bug:`2846` * Avoid an error when doing a "no-op" move on non-existent files (i.e., moving a file onto itself). :bug:`2863` +* :doc:`/plugins/discogs`: Fix ``medium`` and ``medium_index`` values which + were occasionally incorrect for releases with two-sided mediums. Fix + 'medium_total' value. It now contains total number of tracks on the medium + to which a track belongs, not the total number of different mediums present + on the release. :bug:`2887` + Thanks to :user:`dbogdanov`. + For developers: From 7ac2aff50c9ed9a02ebcfb529ccec9b677403e9c Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Sat, 28 Apr 2018 14:06:29 +0200 Subject: [PATCH 2279/2280] Fix a few code style issues --- beetsplug/discogs.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index 740948348..afb054081 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -354,8 +354,7 @@ class DiscogsPlugin(BeetsPlugin): # new disc, when there is no medium_index and the ordinal of medium # is not sequential. For example, I, II, III, IV, V. Assume these # are the track index, not the medium. - - # side_count is the number of mediums or medium sides (in the case + # side_count is the number of mediums or medium sides (in the case # of two-sided mediums) that were seen before medium_is_index = track.medium and not track.medium_index and ( len(track.medium) != 1 or From f9b6473893f11ef278e0157d4f8b017e7e6f3b4e Mon Sep 17 00:00:00 2001 From: Dmitry Bogdanov <dmitry.bogdanov@upf.edu> Date: Sat, 28 Apr 2018 19:03:32 +0200 Subject: [PATCH 2280/2280] Some more code style fixes --- beetsplug/discogs.py | 10 +++++----- docs/changelog.rst | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/beetsplug/discogs.py b/beetsplug/discogs.py index afb054081..82c79a023 100644 --- a/beetsplug/discogs.py +++ b/beetsplug/discogs.py @@ -354,11 +354,11 @@ class DiscogsPlugin(BeetsPlugin): # new disc, when there is no medium_index and the ordinal of medium # is not sequential. For example, I, II, III, IV, V. Assume these # are the track index, not the medium. - # side_count is the number of mediums or medium sides (in the case - # of two-sided mediums) that were seen before + # side_count is the number of mediums or medium sides (in the case + # of two-sided mediums) that were seen before. medium_is_index = track.medium and not track.medium_index and ( len(track.medium) != 1 or - # Not witin standard incremental medium values (A, B, C, ...) + # Not within standard incremental medium values (A, B, C, ...). ord(track.medium) - 64 != side_count + 1 ) @@ -366,11 +366,11 @@ class DiscogsPlugin(BeetsPlugin): side_count += 1 if sides_per_medium == 2: if side_count % sides_per_medium: - # Two-sided medium changed. Reset index_count + # Two-sided medium changed. Reset index_count. index_count = 0 medium_count += 1 else: - # Medium changed. Reset index_count + # Medium changed. Reset index_count. medium_count += 1 index_count = 0 medium = track.medium diff --git a/docs/changelog.rst b/docs/changelog.rst index fafbbbda6..8f45aa69c 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -99,7 +99,7 @@ Fixes: a file onto itself). :bug:`2863` * :doc:`/plugins/discogs`: Fix ``medium`` and ``medium_index`` values which were occasionally incorrect for releases with two-sided mediums. Fix - 'medium_total' value. It now contains total number of tracks on the medium + ``medium_total`` value. It now contains total number of tracks on the medium to which a track belongs, not the total number of different mediums present on the release. :bug:`2887` Thanks to :user:`dbogdanov`.

- download + download