示例#1
0
def _load_plugins(options, config):
    """Load the plugins specified on the command line or in the configuration.
    """
    paths = config['pluginpath'].as_str_seq(split=False)
    paths = [util.normpath(p) for p in paths]
    log.debug('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 + list(beetsplug.__path__)

    # For backwards compatibility, also support plugin paths that
    # *contain* a `beetsplug` package.
    sys.path += paths

    # If we were given any plugins on the command line, use those.
    if options.plugins is not None:
        plugin_list = (options.plugins.split(',')
                       if len(options.plugins) > 0 else [])
    else:
        plugin_list = config['plugins'].as_str_seq()

    plugins.load_plugins(plugin_list)
    plugins.send("pluginload")
    return plugins
示例#2
0
文件: __init__.py 项目: nijotz/beets
def _raw_main(args):
    """A helper function for `main` without top-level exception
    handling.
    """
    # Temporary: Migrate from 1.0-style configuration.
    from beets.ui import migrate

    migrate.automigrate()

    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Add plugin paths.
    sys.path += get_plugin_paths()
    # Load requested plugins.
    plugins.load_plugins(config["plugins"].as_str_seq())
    plugins.send("pluginload")

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    commands.append(migrate.migrate_cmd)  # Temporary.
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option("-l", "--library", dest="library", help="library database file to use")
    parser.add_option("-d", "--directory", dest="directory", help="destination music directory")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="print debugging information")

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)
    config.set_args(options)

    # Open library file.
    dbpath = config["library"].as_filename()
    try:
        lib = library.Library(dbpath, config["directory"].as_filename(), get_path_formats(), get_replacements())
    except sqlite3.OperationalError:
        raise UserError(u"database file {0} could not be opened".format(util.displayable_path(dbpath)))
    plugins.send("library_opened", lib=lib)

    # Configure the logger.
    if config["verbose"].get(bool):
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(
        u"data directory: {0}\n"
        u"library database: {1}\n"
        u"library directory: {2}".format(
            util.displayable_path(config.config_dir()),
            util.displayable_path(lib.path),
            util.displayable_path(lib.directory),
        )
    )

    # Configure the MusicBrainz API.
    mb.configure()

    # Invoke the subcommand.
    subcommand.func(lib, suboptions, subargs)
    plugins.send("cli_exit", lib=lib)
    def setup_beets(self, cfg=None):
        if cfg is not None and type(cfg) is dict:
            self._CFG.update(cfg)

        plugins._classes = {self._CFG["plugin"]}
        if self._CFG["extra_plugins"]:
            plugins.load_plugins(self._CFG["extra_plugins"])

        # copy configuration file to beets dir
        config_file = os.path.join(self._test_config_dir_,
                                   self._CFG["config_file"]).decode()
        file_list = [{'file_name': 'config.yaml', 'file_path': config_file}]
        self._copy_files_to_beetsdir(file_list)

        self.config = beets.config
        self.config.clear()
        self.config.read()

        self.config['plugins'] = []
        self.config['verbose'] = True
        self.config['ui']['color'] = False
        self.config['threaded'] = False
        self.config['import']['copy'] = False

        self.config['directory'] = self.beetsdir.decode()
        self.lib = beets.library.Library(':memory:', self.beetsdir.decode())

        # This will initialize the plugins
        plugins.find_plugins()
示例#4
0
def _load_plugins():
    """Load the plugins specified in the configuration.
    """
    # Add plugin paths.
    import beetsplug
    beetsplug.__path__ = get_plugin_paths() + beetsplug.__path__

    # For backwards compatibility.
    sys.path += get_plugin_paths()

    # Load requested plugins.
    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
示例#5
0
def _load_plugins():
    """Load the plugins specified in the configuration.
    """
    # Add plugin paths.
    import beetsplug
    beetsplug.__path__ = get_plugin_paths() + beetsplug.__path__

    # For backwards compatibility.
    sys.path += get_plugin_paths()

    # Load requested plugins.
    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
示例#6
0
def _load_plugins(config):
    """Load the plugins specified in the configuration.
    """
    paths = config['pluginpath'].get(confit.StrSeq(split=False))
    paths = map(util.normpath, paths)

    import beetsplug
    beetsplug.__path__ = paths + beetsplug.__path__
    # For backwards compatibility.
    sys.path += paths

    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
    return plugins
示例#7
0
def _load_plugins(config):
    """Load the plugins specified in the configuration.
    """
    paths = config['pluginpath'].get(confit.StrSeq(split=False))
    paths = map(util.normpath, paths)

    import beetsplug
    beetsplug.__path__ = paths + beetsplug.__path__
    # For backwards compatibility.
    sys.path += paths

    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
    return plugins
示例#8
0
def _load_plugins(config):
    """Load the plugins specified in the configuration.
    """
    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))

    # 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, also support plugin paths that
    # *contain* a `beetsplug` package.
    sys.path += paths

    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
    return plugins
示例#9
0
文件: __init__.py 项目: arogl/beets
def _load_plugins(config):
    """Load the plugins specified in the configuration.
    """
    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))

    # 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, also support plugin paths that
    # *contain* a `beetsplug` package.
    sys.path += paths

    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")
    return plugins
示例#10
0
文件: __init__.py 项目: encukou/beets
def main(args=None, configfh=None):
    """Run the main command-line interface for beets."""
    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Get default file paths.
    default_config, default_libpath, default_dir = default_paths()

    # Read defaults from config file.
    config = ConfigParser.SafeConfigParser()
    if configfh:
        configpath = None
    elif CONFIG_PATH_VAR in os.environ:
        configpath = os.path.expanduser(os.environ[CONFIG_PATH_VAR])
    else:
        configpath = default_config
    if configpath:
        configpath = util.syspath(configpath)
        if os.path.exists(util.syspath(configpath)):
            configfh = codecs.open(configpath, 'r', encoding='utf-8')
        else:
            configfh = None
    if configfh:
        config.readfp(configfh)

    # Add plugin paths.
    plugpaths = config_val(config, 'beets', 'pluginpath', '')
    for plugpath in plugpaths.split(':'):
        sys.path.append(os.path.expanduser(plugpath))
    # Load requested plugins.
    plugnames = config_val(config, 'beets', 'plugins', '')
    plugins.load_plugins(plugnames.split())
    plugins.load_listeners()
    plugins.send("pluginload")
    plugins.configure(config)

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l',
                      '--library',
                      dest='libpath',
                      help='library database file to use')
    parser.add_option('-d',
                      '--directory',
                      dest='directory',
                      help="destination music directory")
    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      action='store_true',
                      help='print debugging information')

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)

    # Open library file.
    libpath = options.libpath or \
        config_val(config, 'beets', 'library', default_libpath)
    directory = options.directory or \
        config_val(config, 'beets', 'directory', default_dir)
    path_formats = _get_path_formats(config)
    art_filename = \
        config_val(config, 'beets', 'art_filename', DEFAULT_ART_FILENAME)
    lib_timeout = config_val(config, 'beets', 'timeout', DEFAULT_TIMEOUT)
    replacements = _get_replacements(config)
    try:
        lib_timeout = float(lib_timeout)
    except ValueError:
        lib_timeout = DEFAULT_TIMEOUT
    db_path = os.path.expanduser(libpath)
    try:
        lib = library.Library(db_path, directory, path_formats, art_filename,
                              lib_timeout, replacements)
    except sqlite3.OperationalError:
        raise UserError("database file %s could not be opened" % db_path)
    plugins.send("library_opened", lib=lib)

    # Configure the logger.
    log = logging.getLogger('beets')
    if options.verbose:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u'config file: %s' % util.displayable_path(configpath))
    log.debug(u'library database: %s' % util.displayable_path(lib.path))
    log.debug(u'library directory: %s' % util.displayable_path(lib.directory))

    # Invoke the subcommand.
    try:
        subcommand.func(lib, config, suboptions, subargs)
    except UserError as exc:
        message = exc.args[0] if exc.args else None
        subcommand.parser.error(message)
    except util.HumanReadableException as exc:
        exc.log(log)
        sys.exit(1)
    except IOError as exc:
        if exc.errno == errno.EPIPE:
            # "Broken pipe". End silently.
            pass
        else:
            raise
示例#11
0
文件: __init__.py 项目: encukou/beets
def main(args=None, configfh=None):
    """Run the main command-line interface for beets."""
    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Get default file paths.
    default_config, default_libpath, default_dir = default_paths()

    # Read defaults from config file.
    config = ConfigParser.SafeConfigParser()
    if configfh:
        configpath = None
    elif CONFIG_PATH_VAR in os.environ:
        configpath = os.path.expanduser(os.environ[CONFIG_PATH_VAR])
    else:
        configpath = default_config
    if configpath:
        configpath = util.syspath(configpath)
        if os.path.exists(util.syspath(configpath)):
            configfh = codecs.open(configpath, "r", encoding="utf-8")
        else:
            configfh = None
    if configfh:
        config.readfp(configfh)

    # Add plugin paths.
    plugpaths = config_val(config, "beets", "pluginpath", "")
    for plugpath in plugpaths.split(":"):
        sys.path.append(os.path.expanduser(plugpath))
    # Load requested plugins.
    plugnames = config_val(config, "beets", "plugins", "")
    plugins.load_plugins(plugnames.split())
    plugins.load_listeners()
    plugins.send("pluginload")
    plugins.configure(config)

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option("-l", "--library", dest="libpath", help="library database file to use")
    parser.add_option("-d", "--directory", dest="directory", help="destination music directory")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="print debugging information")

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)

    # Open library file.
    libpath = options.libpath or config_val(config, "beets", "library", default_libpath)
    directory = options.directory or config_val(config, "beets", "directory", default_dir)
    path_formats = _get_path_formats(config)
    art_filename = config_val(config, "beets", "art_filename", DEFAULT_ART_FILENAME)
    lib_timeout = config_val(config, "beets", "timeout", DEFAULT_TIMEOUT)
    replacements = _get_replacements(config)
    try:
        lib_timeout = float(lib_timeout)
    except ValueError:
        lib_timeout = DEFAULT_TIMEOUT
    db_path = os.path.expanduser(libpath)
    try:
        lib = library.Library(db_path, directory, path_formats, art_filename, lib_timeout, replacements)
    except sqlite3.OperationalError:
        raise UserError("database file %s could not be opened" % db_path)
    plugins.send("library_opened", lib=lib)

    # Configure the logger.
    log = logging.getLogger("beets")
    if options.verbose:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u"config file: %s" % util.displayable_path(configpath))
    log.debug(u"library database: %s" % util.displayable_path(lib.path))
    log.debug(u"library directory: %s" % util.displayable_path(lib.directory))

    # Invoke the subcommand.
    try:
        subcommand.func(lib, config, suboptions, subargs)
    except UserError as exc:
        message = exc.args[0] if exc.args else None
        subcommand.parser.error(message)
    except util.HumanReadableException as exc:
        exc.log(log)
        sys.exit(1)
    except IOError as exc:
        if exc.errno == errno.EPIPE:
            # "Broken pipe". End silently.
            pass
        else:
            raise
示例#12
0
# Put the beets directory at the front of the search path
sys.path.insert(0, beetspath)

from testsupport import CopyArtifactsTestCase
from beets import plugins
from beets import config

import beetsplug

# Add copyartifacts path to pluginpath and load
beetsplug.__path__.insert(
    0,
    os.path.abspath(
        os.path.join(os.path.dirname(__file__), os.pardir, 'beetsplug')))
plugins.load_plugins(['copyartifacts'])


class CopyArtifactsReimportTest(CopyArtifactsTestCase):
    """
    Tests to check that copyartifacts handles reimports correctly
    """
    def setUp(self):
        super(CopyArtifactsReimportTest, self).setUp()

        self._create_flat_import_dir()
        self._setup_import_session(autotag=False)

        config['copyartifacts']['extensions'] = '.file'

        # Initial import
示例#13
0
文件: __init__.py 项目: sbuser/beets
def main(args=None, configfh=None):
    """Run the main command-line interface for beets."""
    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Get default file paths.
    default_config, default_libpath, default_dir = default_paths()

    # Read defaults from config file.
    config = ConfigParser.SafeConfigParser()
    if configfh:
        configpath = None
    elif CONFIG_PATH_VAR in os.environ:
        configpath = os.path.expanduser(os.environ[CONFIG_PATH_VAR])
    else:
        configpath = default_config
    if configpath:
        configpath = util.syspath(configpath)
        if os.path.exists(util.syspath(configpath)):
            configfh = open(configpath)
        else:
            configfh = None
    if configfh:
        config.readfp(configfh)

    # Add plugin paths.
    plugpaths = config_val(config, 'beets', 'pluginpath', '')
    for plugpath in plugpaths.split(':'):
        sys.path.append(os.path.expanduser(plugpath))
    # Load requested plugins.
    plugnames = config_val(config, 'beets', 'plugins', '')
    plugins.load_plugins(plugnames.split())
    plugins.load_listeners()
    plugins.send("pluginload")
    plugins.configure(config)

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l', '--library', dest='libpath',
                      help='library database file to use')
    parser.add_option('-d', '--directory', dest='directory',
                      help="destination music directory")
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                      help='print debugging information')
    
    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)
    
    # Open library file.
    libpath = options.libpath or \
        config_val(config, 'beets', 'library', default_libpath)
    directory = options.directory or \
        config_val(config, 'beets', 'directory', default_dir)
    path_formats = _get_path_formats(config)
    art_filename = \
        config_val(config, 'beets', 'art_filename', DEFAULT_ART_FILENAME)
    lib_timeout = config_val(config, 'beets', 'timeout', DEFAULT_TIMEOUT)
    replacements = _get_replacements(config)
    try:
        lib_timeout = float(lib_timeout)
    except ValueError:
        lib_timeout = DEFAULT_TIMEOUT
    db_path = os.path.expanduser(libpath)
    try:
        lib = library.Library(db_path,
                              directory,
                              path_formats,
                              art_filename,
                              lib_timeout,
                              replacements)
    except sqlite3.OperationalError:
        raise UserError("database file %s could not be opened" % db_path)
    
    # Configure the logger.
    log = logging.getLogger('beets')
    if options.verbose:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u'config file: %s' % util.displayable_path(configpath))
    log.debug(u'library database: %s' % util.displayable_path(lib.path))
    log.debug(u'library directory: %s' % util.displayable_path(lib.directory))
    
    # Invoke the subcommand.
    try:
        subcommand.func(lib, config, suboptions, subargs)
    except UserError, exc:
        message = exc.args[0] if exc.args else None
        subcommand.parser.error(message)
示例#14
0
文件: __init__.py 项目: flz/beets
def _raw_main(args, load_config=True):
    """A helper function for `main` without top-level exception
    handling.
    """
    # Load global configuration files.
    if load_config:
        config.read()

    # Temporary: Migrate from 1.0-style configuration.
    from beets.ui import migrate
    if load_config:
        migrate.automigrate()

    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Add plugin paths.
    sys.path += get_plugin_paths()
    # Load requested plugins.
    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    commands.append(migrate.migrate_cmd)  # Temporary.
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l', '--library', dest='library',
                      help='library database file to use')
    parser.add_option('-d', '--directory', dest='directory',
                      help="destination music directory")
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                      help='print debugging information')

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)
    config.set_args(options)

    # Open library file.
    dbpath = config['library'].as_filename()
    try:
        lib = library.Library(
            dbpath,
            config['directory'].as_filename(),
            get_path_formats(),
            Template(config['art_filename'].get(unicode)),
            config['timeout'].as_number(),
            get_replacements(),
        )
    except sqlite3.OperationalError:
        raise UserError(u"database file {0} could not be opened".format(
            util.displayable_path(dbpath)
        ))
    plugins.send("library_opened", lib=lib)

    # Configure the logger.
    if config['verbose'].get(bool):
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u'data directory: {0}\n'
              u'library database: {1}\n'
              u'library directory: {2}'.format(
        util.displayable_path(config.config_dir()),
        util.displayable_path(lib.path),
        util.displayable_path(lib.directory),
    ))

    # Invoke the subcommand.
    subcommand.func(lib, suboptions, subargs)
# Check that the beets directory exists
if not os.path.isdir(beetspath):
    raise RuntimeError("A directory named beets with the beets source needs to be parallel to this plugin's source directory")

# Put the beets directory at the front of the search path
sys.path.insert(0, beetspath)

from testsupport import CopyArtifactsTestCase
from beets import plugins
from beets import config

import beetsplug

# Add copyartifacts path to pluginpath and load
beetsplug.__path__.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'beetsplug')))
plugins.load_plugins(['copyartifacts'])

class CopyArtifactsReimportTest(CopyArtifactsTestCase):
    """
    Tests to check that copyartifacts handles reimports correctly
    """
    def setUp(self):
        super(CopyArtifactsReimportTest, self).setUp()
        
        self._create_flat_import_dir()
        self._setup_import_session(autotag=False)

        config['copyartifacts']['extensions'] = '.file'
        
        # Initial import
        self._run_importer()
示例#16
0
def main(args=None, configfh=None):
    """Run the main command-line interface for beets."""
    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Read defaults from config file.
    config = ConfigParser.SafeConfigParser()
    if configfh:
        configpath = None
    elif CONFIG_PATH_VAR in os.environ:
        configpath = os.path.expanduser(os.environ[CONFIG_PATH_VAR])
    else:
        configpath = DEFAULT_CONFIG_FILE
    if configpath:
        configpath = util.syspath(configpath)
        if os.path.exists(util.syspath(configpath)):
            configfh = open(configpath)
        else:
            configfh = None
    if configfh:
        config.readfp(configfh)

    # Add plugin paths.
    plugpaths = config_val(config, 'beets', 'pluginpath', '')
    for plugpath in plugpaths.split(':'):
        sys.path.append(os.path.expanduser(plugpath))
    # Load requested plugins.
    plugnames = config_val(config, 'beets', 'plugins', '')
    plugins.load_plugins(plugnames.split())
    plugins.load_listeners()
    plugins.send("pluginload")
    plugins.configure(config)

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l', '--library', dest='libpath',
                      help='library database file to use')
    parser.add_option('-d', '--directory', dest='directory',
                      help="destination music directory")
    parser.add_option('-p', '--pathformat', dest='path_format',
                      help="destination path format string")
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
                      help='print debugging information')
    
    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)
    
    # Open library file.
    libpath = options.libpath or \
        config_val(config, 'beets', 'library', DEFAULT_LIBRARY)
    directory = options.directory or \
        config_val(config, 'beets', 'directory', DEFAULT_DIRECTORY)
    legacy_path_format = config_val(config, 'beets', 'path_format', None)
    if options.path_format:
        # If given, -p overrides all path format settings
        path_formats = {'default': options.path_format}
    else:
        if legacy_path_format:
            # Old path formats override the default values.
            path_formats = {'default': legacy_path_format}
        else:
            # If no legacy path format, use the defaults instead.
            path_formats = DEFAULT_PATH_FORMATS
        if config.has_section('paths'):
            path_formats.update(config.items('paths'))
    art_filename = \
        config_val(config, 'beets', 'art_filename', DEFAULT_ART_FILENAME)
    db_path = os.path.expanduser(libpath)
    try:
        lib = library.Library(db_path,
                              directory,
                              path_formats,
                              art_filename)
    except sqlite3.OperationalError:
        raise UserError("database file %s could not be opened" % db_path)
    
    # Configure the logger.
    log = logging.getLogger('beets')
    if options.verbose:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    
    # Invoke the subcommand.
    try:
        subcommand.func(lib, config, suboptions, subargs)
    except UserError, exc:
        message = exc.args[0] if exc.args else None
        subcommand.parser.error(message)
示例#17
0
文件: __init__.py 项目: silky/beets
def _raw_main(args):
    """A helper function for `main` without top-level exception
    handling.
    """
    # Temporary: Migrate from 1.0-style configuration.
    from beets.ui import migrate
    migrate.automigrate()

    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Add plugin paths.
    sys.path += get_plugin_paths()
    # Load requested plugins.
    plugins.load_plugins(config['plugins'].as_str_seq())
    plugins.send("pluginload")

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    commands.append(migrate.migrate_cmd)  # Temporary.
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l',
                      '--library',
                      dest='library',
                      help='library database file to use')
    parser.add_option('-d',
                      '--directory',
                      dest='directory',
                      help="destination music directory")
    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      action='store_true',
                      help='print debugging information')

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)
    config.set_args(options)

    # Open library file.
    dbpath = config['library'].as_filename()
    try:
        lib = library.Library(
            dbpath,
            config['directory'].as_filename(),
            get_path_formats(),
            get_replacements(),
        )
    except sqlite3.OperationalError:
        raise UserError(u"database file {0} could not be opened".format(
            util.displayable_path(dbpath)))
    plugins.send("library_opened", lib=lib)

    # Configure the logger.
    if config['verbose'].get(bool):
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u'data directory: {0}\n'
              u'library database: {1}\n'
              u'library directory: {2}'.format(
                  util.displayable_path(config.config_dir()),
                  util.displayable_path(lib.path),
                  util.displayable_path(lib.directory),
              ))

    # Configure the MusicBrainz API.
    mb.configure()

    # Invoke the subcommand.
    subcommand.func(lib, suboptions, subargs)
    plugins.send('cli_exit', lib=lib)
示例#18
0
def main(args=None, configfh=None):
    """Run the main command-line interface for beets."""
    # Get the default subcommands.
    from beets.ui.commands import default_commands

    # Get default file paths.
    default_config, default_libpath, default_dir = default_paths()

    # Read defaults from config file.
    config = ConfigParser.SafeConfigParser()
    if configfh:
        configpath = None
    elif CONFIG_PATH_VAR in os.environ:
        configpath = os.path.expanduser(os.environ[CONFIG_PATH_VAR])
    else:
        configpath = default_config
    if configpath:
        configpath = util.syspath(configpath)
        if os.path.exists(util.syspath(configpath)):
            configfh = open(configpath)
        else:
            configfh = None
    if configfh:
        config.readfp(configfh)

    # Add plugin paths.
    plugpaths = config_val(config, 'beets', 'pluginpath', '')
    for plugpath in plugpaths.split(':'):
        sys.path.append(os.path.expanduser(plugpath))
    # Load requested plugins.
    plugnames = config_val(config, 'beets', 'plugins', '')
    plugins.load_plugins(plugnames.split())
    plugins.load_listeners()
    plugins.send("pluginload")
    plugins.configure(config)

    # Construct the root parser.
    commands = list(default_commands)
    commands += plugins.commands()
    parser = SubcommandsOptionParser(subcommands=commands)
    parser.add_option('-l',
                      '--library',
                      dest='libpath',
                      help='library database file to use')
    parser.add_option('-d',
                      '--directory',
                      dest='directory',
                      help="destination music directory")
    parser.add_option('-p',
                      '--pathformat',
                      dest='path_format',
                      help="destination path format string")
    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      action='store_true',
                      help='print debugging information')

    # Parse the command-line!
    options, subcommand, suboptions, subargs = parser.parse_args(args)

    # Open library file.
    libpath = options.libpath or \
        config_val(config, 'beets', 'library', default_libpath)
    directory = options.directory or \
        config_val(config, 'beets', 'directory', default_dir)
    legacy_path_format = config_val(config, 'beets', 'path_format', None)
    if options.path_format:
        # If given, -p overrides all path format settings
        path_formats = {'default': options.path_format}
    else:
        if legacy_path_format:
            # Old path formats override the default values.
            path_formats = {'default': legacy_path_format}
        else:
            # If no legacy path format, use the defaults instead.
            path_formats = DEFAULT_PATH_FORMATS
        if config.has_section('paths'):
            path_formats.update(config.items('paths'))
    art_filename = \
        config_val(config, 'beets', 'art_filename', DEFAULT_ART_FILENAME)
    lib_timeout = config_val(config, 'beets', 'timeout', DEFAULT_TIMEOUT)
    try:
        lib_timeout = float(lib_timeout)
    except ValueError:
        lib_timeout = DEFAULT_TIMEOUT
    db_path = os.path.expanduser(libpath)
    try:
        lib = library.Library(db_path, directory, path_formats, art_filename,
                              lib_timeout)
    except sqlite3.OperationalError:
        raise UserError("database file %s could not be opened" % db_path)

    # Configure the logger.
    log = logging.getLogger('beets')
    if options.verbose:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    log.debug(u'config file: %s' % configpath)
    log.debug(u'library database: %s' % lib.path)
    log.debug(u'library directory: %s' % lib.directory)

    # Invoke the subcommand.
    try:
        subcommand.func(lib, config, suboptions, subargs)
    except UserError, exc:
        message = exc.args[0] if exc.args else None
        subcommand.parser.error(message)