def _setup(options, lib=None): """Prepare and global state and updates it with command line options. Returns a list of subcommands, a list of plugins, and a library instance. """ # Configure the MusicBrainz API. mb.configure() config = _configure(options) plugins = _load_plugins(config) # 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 subcommands = list(default_commands) subcommands.append(migrate.migrate_cmd) subcommands.extend(plugins.commands()) if lib is None: lib = _open_library(config) plugins.send("library_opened", lib=lib) return subcommands, plugins, lib
def _setup(options, lib=None): """Prepare and global state and updates it with command line options. Returns a list of subcommands, a list of plugins, and a library instance. """ # Configure the MusicBrainz API. mb.configure() config = _configure(options) plugins = _load_plugins(config) # Get the default subcommands. from beets.ui.commands import default_commands subcommands = list(default_commands) subcommands.extend(plugins.commands()) if lib is None: lib = _open_library(config) plugins.send("library_opened", lib=lib) library.Item._types.update(plugins.types(library.Item)) library.Album._types.update(plugins.types(library.Album)) return subcommands, plugins, lib
def _configure(args): """Parse the command line, load configuration files (including loading any indicated plugins), and return the invoked subcomand, the subcommand options, and the subcommand arguments. """ # 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 # Construct the root parser. parser = SubcommandsOptionParser() 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') parser.add_option('-c', '--config', dest='config', help='path to configuration file') # Parse the command-line! options, subargs = parser.parse_global_options(args) # 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, 'config', None) is not None: config_path = options.config del options.config config.set_file(config_path) config.set_args(options) # Configure the logger. if config['verbose'].get(bool): log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) config_path = config.user_config_path() if os.path.isfile(config_path): log.debug('user configuration: {0}'.format( util.displayable_path(config_path))) else: log.debug('no user configuration found at {0}'.format( util.displayable_path(config_path))) # Add builtin subcommands parser.add_subcommand(*default_commands) parser.add_subcommand(migrate.migrate_cmd) # Now add the plugin commands to the parser. _load_plugins() for cmd in plugins.commands(): parser.add_subcommand(cmd) # Parse the remainder of the command line with loaded plugins. return parser.parse_subcommand(subargs)
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 print_completion(*args): for line in completion_script(default_commands + plugins.commands()): print(line, end='') if not (os.path.isfile(u'/etc/bash_completion') or os.path.isfile(u'/usr/share/bash-completion/bash_completion') or os.path.isfile(u'/usr/share/local/bash-completion/bash_completion')): log.warn(u'Warning: Unable to find the bash-completion package. ' u'Command line completion might not work.')
def _configure(args): """Parse the command line, load configuration files (including loading any indicated plugins), and return the invoked subcomand, the subcommand options, and the subcommand arguments. """ # 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 # Construct the root parser. commands = list(default_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') parser.add_option('-c', '--config', dest='config', help='path to configuration file') # Parse the command-line! options, args = optparse.OptionParser.parse_args(parser, args) # 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, 'config', None) is not None: config_path = options.config del options.config config.set_file(config_path) config.set_args(options) # Configure the logger. if config['verbose'].get(bool): log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) config_path = config.user_config_path() if os.path.isfile(config_path): log.debug('user configuration: {0}'.format( util.displayable_path(config_path))) else: log.debug('no user configuration found at {0}'.format( util.displayable_path(config_path))) # Now add the plugin commands to the parser. _load_plugins() for cmd in plugins.commands(): parser.add_subcommand(cmd) # Parse the remainder of the command line with loaded plugins. return parser._parse_sub(args)
def _configure(args): """Parse the command line, load configuration files (including loading any indicated plugins), and return the invoked subcomand, the subcommand options, and the subcommand arguments. """ # 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 # Construct the root parser. commands = list(default_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") parser.add_option("-c", "--config", dest="config", help="path to configuration file") # Parse the command-line! options, args = optparse.OptionParser.parse_args(parser, args) # 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, "config", None) is not None: config_path = options.config del options.config config.set_file(config_path) config.set_args(options) # Configure the logger. if config["verbose"].get(bool): log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) config_path = config.user_config_path() if os.path.isfile(config_path): log.debug("user configuration: {0}".format(util.displayable_path(config_path))) else: log.debug("no user configuration found at {0}".format(util.displayable_path(config_path))) # Now add the plugin commands to the parser. _load_plugins() for cmd in plugins.commands(): parser.add_subcommand(cmd) # Parse the remainder of the command line with loaded plugins. return parser._parse_sub(args)
def _configure(args): """Parse the command line, load configuration files (including loading any indicated plugins), and return the invoked subcomand, the subcommand options, and the subcommand arguments. """ # 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 # Construct the root parser. commands = list(default_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') parser.add_option('-c', '--config', dest='config', help='path to configuration file') # Parse the command-line! options, args = optparse.OptionParser.parse_args(parser, args) # 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, 'config', None) is not None: config_path = options.config del options.config config.set_file(config_path) config.set_args(options) # Now add the plugin commands to the parser. _load_plugins() for cmd in plugins.commands(): parser.add_subcommand(cmd) # Parse the remainder of the command line with loaded plugins. return parser._parse_sub(args)
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 func(self, lib, opts, args=None): if args is None: args = [] split_command = shlex.split(self.command) command = split_command[0] command_args = split_command[1:] # loop through beet arguments, starting from behind for i in range(len(args) - 1, -1, -1): # replace all occurences of token {X} with parameter (if it exists) token = "{i}".replace("i", str(i)) token_replaced = False for j in range(0, len(command_args), 1): if token in command_args[j]: command_args[j] = command_args[j].replace(token, args[i]) token_replaced = True # remove parameter if it has been used for a replacement if token_replaced: del args[i] # search for token {} and replace it with the rest of the arguments, if it exists or append otherwise if '{}' in command_args: for i in range(len(command_args) - 1, -1, -1): if command_args[i] == '{}': command_args[i:i + 1] = args else: command_args = command_args + args args = command_args if command.startswith('!'): command = command[1:] argv = [command] + args if self.log: self.log.debug('Running {}', subprocess.list2cmdline(argv)) try: return subprocess.check_call(argv) except subprocess.CalledProcessError as exc: if self.log: self.log.debug(u'command `{0}` failed with {1}', subprocess.list2cmdline(argv), exc.returncode) plugins.send('cli_exit', lib=lib) lib._close() sys.exit(exc.returncode) else: argv = [command] + args cmdname = argv[0] subcommands = list(default_commands) subcommands.extend(plugins.commands()) for subcommand in subcommands: if cmdname == subcommand.name or cmdname in subcommand.aliases: break else: raise ui.UserError(u"unknown command '{0}'".format(cmdname)) if self.log: self.log.debug('Running {}', subprocess.list2cmdline(argv)) suboptions, subargs = subcommand.parse_args(argv[1:]) return subcommand.func(lib, suboptions, subargs)
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)
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
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)
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)
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
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)