# -*- coding: utf-8 -*-
# This file is part of beets.
# 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
# "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.

"""List duplicate tracks or albums.
"""
from __future__ import division, absolute_import, print_function

import shlex
import six

from beets.plugins import BeetsPlugin
from beets.ui import decargs, print_, Subcommand, UserError
from beets.util import command_output, displayable_path, subprocess, \
    bytestring_path, MoveOperation, decode_commandline_path
from beets.library import Item, Album


PLUGIN = 'duplicates'


class DuplicatesPlugin(BeetsPlugin):
    """List duplicate tracks or albums
    """
    def __init__(self):
        super(DuplicatesPlugin, self).__init__()

        self.config.add({
            'album': False,
            'checksum': '',
            'copy': '',
            'count': False,
            'delete': False,
            'format': '',
            'full': False,
            'keys': [],
            'merge': False,
            'move': '',
            'path': False,
            'tiebreak': {},
            'strict': False,
            'tag': '',
        })

        self._command = Subcommand('duplicates',
                                   help=__doc__,
                                   aliases=['dup'])
        self._command.parser.add_option(
            u'-c', u'--count', dest='count',
            action='store_true',
            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',
        )
        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(
            u'-F', u'--full', dest='full',
            action='store_true',
            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',
        )
        self._command.parser.add_option(
            u'-k', u'--key', dest='keys',
            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',
            action='store_true',
            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',
        )
        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(
            u'-t', u'--tag', dest='tag',
            action='store',
            help=u'tag matched items with \'k=v\' attribute',
        )
        self._command.parser.add_all_common_options()

    def commands(self):

        def _dup(lib, opts, args):
            self.config.set_args(opts)
            album = self.config['album'].get(bool)
            checksum = self.config['checksum'].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 = 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)
            tag = self.config['tag'].get(str)

            if album:
                if not keys:
                    keys = ['mb_albumid']
                items = lib.albums(decargs(args))
            else:
                if not keys:
                    keys = ['mb_trackid', 'mb_albumid']
                items = lib.items(decargs(args))

            if path:
                fmt = u'$path'

            # Default format string for count mode.
            if count and not fmt:
                if album:
                    fmt = u'$albumartist - $album'
                else:
                    fmt = u'$albumartist - $album - $title'
                fmt += u': {0}'

            if checksum:
                for i in items:
                    k, _ = self._checksum(i, checksum)
                keys = [k]

            for obj_id, obj_count, objs in self._duplicates(items,
                                                            keys=keys,
                                                            full=full,
                                                            strict=strict,
                                                            tiebreak=tiebreak,
                                                            merge=merge):
                if obj_id:  # Skip empty IDs.
                    for o in objs:
                        self._process_item(o,
                                           copy=copy,
                                           move=move,
                                           delete=delete,
                                           tag=tag,
                                           fmt=fmt.format(obj_count))

        self._command.func = _dup
        return [self._command]

    def _process_item(self, item, copy=False, move=False, delete=False,
                      tag=False, fmt=u''):
        """Process Item `item`.
        """
        print_(format(item, fmt))
        if copy:
            item.move(basedir=copy, operation=MoveOperation.COPY)
            item.store()
        if move:
            item.move(basedir=move)
            item.store()
        if delete:
            item.remove(delete=True)
        if tag:
            try:
                k, v = tag.split('=')
            except Exception:
                raise UserError(
                    u"{}: can't parse k=v tag: {}".format(PLUGIN, tag)
                )
            setattr(item, k, v)
            item.store()

    def _checksum(self, item, prog):
        """Run external `prog` on file path associated with `item`, cache
        output as flexattr on a key that is the name of the program, and
        return the key, checksum tuple.
        """
        args = [p.format(file=decode_commandline_path(item.path))
                for p in shlex.split(prog)]
        key = args[0]
        checksum = getattr(item, key, False)
        if not checksum:
            self._log.debug(u'key {0} on item {1} not cached:'
                            u'computing checksum',
                            key, displayable_path(item.path))
            try:
                checksum = command_output(args).stdout
                setattr(item, key, checksum)
                item.store()
                self._log.debug(u'computed checksum for {0} using {1}',
                                item.title, key)
            except subprocess.CalledProcessError as e:
                self._log.debug(u'failed to checksum {0}: {1}',
                                displayable_path(item.path), e)
        else:
            self._log.debug(u'key {0} on item {1} cached:'
                            u'not computing checksum',
                            key, displayable_path(item.path))
        return key, checksum

    def _group_by(self, objs, keys, strict):
        """Return a dictionary with keys arbitrary concatenations of attributes
        and values lists of objects (Albums or Items) with those keys.

        If strict, all attributes must be defined for a duplicate match.
        """
        import collections
        counts = collections.defaultdict(list)
        for obj in objs:
            values = [getattr(obj, k, None) for k in keys]
            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:'
                                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:'
                                u' skipping',
                                keys, displayable_path(obj.path))
            else:
                key = tuple(values)
                counts[key].append(obj)

        return counts

    def _order(self, objs, tiebreak=None):
        """Return the objects (Items or Albums) sorted by descending
        order of priority.

        If provided, the `tiebreak` dict indicates the field to use to
        prioritize the objects. Otherwise, Items are placed in order of
        "completeness" (objects with more non-null fields come first)
        and Albums are ordered by their track count.
        """
        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:
            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 = Item.all_keys()
                key = lambda x: sum(1 for f in fields if truthy(getattr(x, f)))
            else:
                key = lambda x: len(x.items())

        return sorted(objs, key=key, reverse=True)

    def _merge_items(self, objs):
        """Merge Item objs by copying missing fields from items in the tail to
        the head item.

        Return same number of items, with the head item modified.
        """
        fields = Item.all_keys()
        for f in fields:
            for o in objs[1:]:
                if getattr(objs[0], f, None) in (None, ''):
                    value = getattr(o, f, None)
                    if value:
                        self._log.debug(u'key {0} on item {1} is null '
                                        u'or empty: setting from item {2}',
                                        f, displayable_path(objs[0].path),
                                        displayable_path(o.path))
                        setattr(objs[0], f, value)
                        objs[0].store()
                        break
        return objs

    def _merge_albums(self, objs):
        """Merge Album objs by copying missing items from albums in the tail
        to the head album.

        Return same number of albums, with the head album modified."""
        ids = [i.mb_trackid for i in objs[0].items()]
        for o in objs[1:]:
            for i in o.items():
                if i.mb_trackid not in ids:
                    missing = Item.from_path(i.path)
                    missing.album_id = objs[0].id
                    missing.add(i._db)
                    self._log.debug(u'item {0} missing from album {1}:'
                                    u' merging from {2} into {3}',
                                    missing,
                                    objs[0],
                                    displayable_path(o.path),
                                    displayable_path(missing.destination()))
                    missing.move(operation=MoveOperation.COPY)
        return objs

    def _merge(self, objs):
        """Merge duplicate items. See ``_merge_items`` and ``_merge_albums``
        for the relevant strategies.
        """
        kind = Item if all(isinstance(o, Item) for o in objs) else Album
        if kind is Item:
            objs = self._merge_items(objs)
        else:
            objs = self._merge_albums(objs)
        return objs

    def _duplicates(self, objs, keys, full, strict, tiebreak, merge):
        """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).items():
            if len(objs) > 1:
                objs = self._order(objs, tiebreak)
                if merge:
                    objs = self._merge(objs)
                yield (k, len(objs) - offset, objs[offset:])

beetsplug/duplicates.py
# -*- coding: utf-8 -*-
# This file is part of beets.
# 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
# "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.

"""List duplicate tracks or albums.
"""
from __future__ import division, absolute_import, print_function

import shlex
import six

from beets.plugins import BeetsPlugin
from beets.ui import decargs, print_, Subcommand, UserError
from beets.util import command_output, displayable_path, subprocess, \
    bytestring_path, MoveOperation, decode_commandline_path
from beets.library import Item, Album


PLUGIN = 'duplicates'


class DuplicatesPlugin(BeetsPlugin):
    """List duplicate tracks or albums
    """
    def __init__(self):
        super(DuplicatesPlugin, self).__init__()

        self.config.add({
            'album': False,
            'checksum': '',
            'copy': '',
            'count': False,
            'delete': False,
            'format': '',
            'full': False,
            'keys': [],
            'merge': False,
            'move': '',
            'path': False,
            'tiebreak': {},
            'strict': False,
            'tag': '',
        })

        self._command = Subcommand('duplicates',
                                   help=__doc__,
                                   aliases=['dup'])
        self._command.parser.add_option(
            u'-c', u'--count', dest='count',
            action='store_true',
            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',
        )
        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(
            u'-F', u'--full', dest='full',
            action='store_true',
            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',
        )
        self._command.parser.add_option(
            u'-k', u'--key', dest='keys',
            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',
            action='store_true',
            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',
        )
        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(
            u'-t', u'--tag', dest='tag',
            action='store',
            help=u'tag matched items with \'k=v\' attribute',
        )
        self._command.parser.add_all_common_options()

    def commands(self):

        def _dup(lib, opts, args):
            self.config.set_args(opts)
            album = self.config['album'].get(bool)
            checksum = self.config['checksum'].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 = 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)
            tag = self.config['tag'].get(str)

            if album:
                if not keys:
                    keys = ['mb_albumid']
                items = lib.albums(decargs(args))
            else:
                if not keys:
                    keys = ['mb_trackid', 'mb_albumid']
                items = lib.items(decargs(args))

            # If there's nothing to do, return early. The code below assumes
            # `items` to be non-empty.
            if not items:
                return

            if path:
                fmt = u'$path'

            # Default format string for count mode.
            if count and not fmt:
                if album:
                    fmt = u'$albumartist - $album'
                else:
                    fmt = u'$albumartist - $album - $title'
                fmt += u': {0}'

            if checksum:
                for i in items:
                    k, _ = self._checksum(i, checksum)
                keys = [k]

            for obj_id, obj_count, objs in self._duplicates(items,
                                                            keys=keys,
                                                            full=full,
                                                            strict=strict,
                                                            tiebreak=tiebreak,
                                                            merge=merge):
                if obj_id:  # Skip empty IDs.
                    for o in objs:
                        self._process_item(o,
                                           copy=copy,
                                           move=move,
                                           delete=delete,
                                           tag=tag,
                                           fmt=fmt.format(obj_count))

        self._command.func = _dup
        return [self._command]

    def _process_item(self, item, copy=False, move=False, delete=False,
                      tag=False, fmt=u''):
        """Process Item `item`.
        """
        print_(format(item, fmt))
        if copy:
            item.move(basedir=copy, operation=MoveOperation.COPY)
            item.store()
        if move:
            item.move(basedir=move)
            item.store()
        if delete:
            item.remove(delete=True)
        if tag:
            try:
                k, v = tag.split('=')
            except Exception:
                raise UserError(
                    u"{}: can't parse k=v tag: {}".format(PLUGIN, tag)
                )
            setattr(item, k, v)
            item.store()

    def _checksum(self, item, prog):
        """Run external `prog` on file path associated with `item`, cache
        output as flexattr on a key that is the name of the program, and
        return the key, checksum tuple.
        """
        args = [p.format(file=decode_commandline_path(item.path))
                for p in shlex.split(prog)]
        key = args[0]
        checksum = getattr(item, key, False)
        if not checksum:
            self._log.debug(u'key {0} on item {1} not cached:'
                            u'computing checksum',
                            key, displayable_path(item.path))
            try:
                checksum = command_output(args).stdout
                setattr(item, key, checksum)
                item.store()
                self._log.debug(u'computed checksum for {0} using {1}',
                                item.title, key)
            except subprocess.CalledProcessError as e:
                self._log.debug(u'failed to checksum {0}: {1}',
                                displayable_path(item.path), e)
        else:
            self._log.debug(u'key {0} on item {1} cached:'
                            u'not computing checksum',
                            key, displayable_path(item.path))
        return key, checksum

    def _group_by(self, objs, keys, strict):
        """Return a dictionary with keys arbitrary concatenations of attributes
        and values lists of objects (Albums or Items) with those keys.

        If strict, all attributes must be defined for a duplicate match.
        """
        import collections
        counts = collections.defaultdict(list)
        for obj in objs:
            values = [getattr(obj, k, None) for k in keys]
            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:'
                                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:'
                                u' skipping',
                                keys, displayable_path(obj.path))
            else:
                key = tuple(values)
                counts[key].append(obj)

        return counts

    def _order(self, objs, tiebreak=None):
        """Return the objects (Items or Albums) sorted by descending
        order of priority.

        If provided, the `tiebreak` dict indicates the field to use to
        prioritize the objects. Otherwise, Items are placed in order of
        "completeness" (objects with more non-null fields come first)
        and Albums are ordered by their track count.
        """
        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:
            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 = Item.all_keys()
                key = lambda x: sum(1 for f in fields if truthy(getattr(x, f)))
            else:
                key = lambda x: len(x.items())

        return sorted(objs, key=key, reverse=True)

    def _merge_items(self, objs):
        """Merge Item objs by copying missing fields from items in the tail to
        the head item.

        Return same number of items, with the head item modified.
        """
        fields = Item.all_keys()
        for f in fields:
            for o in objs[1:]:
                if getattr(objs[0], f, None) in (None, ''):
                    value = getattr(o, f, None)
                    if value:
                        self._log.debug(u'key {0} on item {1} is null '
                                        u'or empty: setting from item {2}',
                                        f, displayable_path(objs[0].path),
                                        displayable_path(o.path))
                        setattr(objs[0], f, value)
                        objs[0].store()
                        break
        return objs

    def _merge_albums(self, objs):
        """Merge Album objs by copying missing items from albums in the tail
        to the head album.

        Return same number of albums, with the head album modified."""
        ids = [i.mb_trackid for i in objs[0].items()]
        for o in objs[1:]:
            for i in o.items():
                if i.mb_trackid not in ids:
                    missing = Item.from_path(i.path)
                    missing.album_id = objs[0].id
                    missing.add(i._db)
                    self._log.debug(u'item {0} missing from album {1}:'
                                    u' merging from {2} into {3}',
                                    missing,
                                    objs[0],
                                    displayable_path(o.path),
                                    displayable_path(missing.destination()))
                    missing.move(operation=MoveOperation.COPY)
        return objs

    def _merge(self, objs):
        """Merge duplicate items. See ``_merge_items`` and ``_merge_albums``
        for the relevant strategies.
        """
        kind = Item if all(isinstance(o, Item) for o in objs) else Album
        if kind is Item:
            objs = self._merge_items(objs)
        else:
            objs = self._merge_albums(objs)
        return objs

    def _duplicates(self, objs, keys, full, strict, tiebreak, merge):
        """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).items():
            if len(objs) > 1:
                objs = self._order(objs, tiebreak)
                if merge:
                    objs = self._merge(objs)
                yield (k, len(objs) - offset, objs[offset:])

beetsplug/duplicates.py
diff --git a/beetsplug/duplicates.py b/beetsplug/duplicates.py
index bc9e3ff3c6..d608ddd4bb 100644
--- a/beetsplug/duplicates.py
+++ b/beetsplug/duplicates.py
@@ -136,6 +136,11 @@ def _dup(lib, opts, args):
                     keys = ['mb_trackid', 'mb_albumid']
                 items = lib.items(decargs(args))
 
+            # If there's nothing to do, return early. The code below assumes
+            # `items` to be non-empty.
+            if not items:
+                return
+
             if path:
                 fmt = u'$path'
 
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 5ca9a8f9cc..dcfcda98ce 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -383,6 +383,9 @@ Fixes:
 * :doc:`/plugins/lyrics`: Fix crashes when a website could not be retrieved,
   affecting at least the Genius source
   :bug:`3970`
+* :doc:`/plugins/duplicates`: Fix a crash when running the ``dup`` command with
+  a query that returns no results.
+  :bug:`3943`
 
 For plugin developers:
 

Duplicate Plugin: beet dup -C "md5sum {file}" doesn't calculate checksum on Win10 cmd (incl ad-hoc fix)
I was trying to check for duplicates with md5sum. And ran into several problems.

### Problem

Running this command in verbose (`-vv`) mode:
(copied like its shown in this doc https://beets.readthedocs.io/en/stable/plugins/duplicates.html)
```cmd
$ beet -vv dup -C 'md5sum {file}'
```

Led to this problem:

```
user configuration: F:\Users\yasok\AppData\Roaming\beets\config.yaml
data directory: F:\Users\yasok\AppData\Roaming\beets
plugin paths:
Sending event: pluginload
library database: F:\Users\yasok\AppData\Roaming\beets\library.db
library directory: G:\MusicNoDupes
Sending event: library_opened
Traceback (most recent call last):
  File "f:\users\yasok\anaconda3\envs\tagging\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "f:\users\yasok\anaconda3\envs\tagging\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "F:\Users\yasok\anaconda3\envs\tagging\Scripts\beet.exe\__main__.py", line 7, in <module>
  File "f:\users\yasok\anaconda3\envs\tagging\lib\site-packages\beets\ui\__init__.py", line 1291, in main
    _raw_main(args)
  File "f:\users\yasok\anaconda3\envs\tagging\lib\site-packages\beets\ui\__init__.py", line 1278, in _raw_main
    subcommand.func(lib, suboptions, subargs)
  File "f:\users\yasok\anaconda3\envs\tagging\lib\site-packages\beetsplug\duplicates.py", line 152, in _dup
    keys = [k]
UnboundLocalError: local variable 'k' referenced before assignment
```

After debugging I noticed that the command it's trying to run is:
```
'md5sum
```
missing the "{file}", so I figured I'll try it with 
```cmd
$ beet -vv dup -C "md5sum {file}"
```
which didn't crash, but led to:

```
duplicates: key md5sum on item G:\MusicNoDupes\SWR3.online\Jogis Jungs\00 Jogis Jungs 026 Masern in der Schweiz.mp3 not cached:computing checksum
duplicates: failed to checksum G:\MusicNoDupes\SWR3.online\Jogis Jungs\00 Jogis Jungs 026 Masern in der Schweiz.mp3: Command 'md5sum b'G:\\MusicNoDupes\\SWR3.online\\Jogis Jungs\\00 Jogis Jungs 026 Masern in der Schweiz.mp3'' returned non-zero exit status 1.
```

I debugged again and realized it tries to run the command as:
```
md5sum b'G:\\MusicNoDupes\\SWR3.online\\Jogis Jungs\\00 Jogis Jungs 026 Masern in der Schweiz.mp3
```
The "b' " at the start confuses md5sum and leads to it not finding the file.

### ad-hoc fix
I changed the following line:
F:\Users\yasok\anaconda3\envs\tagging\Lib\site-packages\beetsplug\duplicates.py:200
From
```python
        args = [p.format(file=item.path) for p in shlex.split(prog)]
```
To
```python
        args = [p.format(file=displayable_path(item.path)) for p in shlex.split(prog)]
```

Now `$ beet -vv dup -C "md5sum {file}"` works.

### Setup

* OS: Windows 10 Pro 20H2
* beets version 1.5.0
* Python version 3.8.8
* plugins: duplicates
* Turning off plugins made problem go away (yes/no): not applicable

My configuration (output of `beet config`) is:

```yaml
duplicates:
  tiebreak: 
    items: [bitrate]
directory: G:\MusicNoDupes
import:
    move: yes
plugins: duplicates
terminal_encoding: utf-8
```

