[#1971] [UI] Unify common cmd options handling.

Add a CommonOptionParser which handles the standard set of options
for all UIs.
This commit is contained in:
Jamie Lennox 2011-11-19 16:27:56 +11:00 committed by bendikro
parent 38a480ac14
commit 7af8a4cf14
3 changed files with 134 additions and 159 deletions

79
deluge/commonoptions.py Normal file
View File

@ -0,0 +1,79 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Andrew Resch <andrewresch@gmail.com>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import logging
import optparse
import os
import platform
import sys
import deluge.common
import deluge.configmanager
from deluge.log import setup_logger
def version_callback(option, opt_str, value, parser):
print(os.path.basename(sys.argv[0]) + ": " + deluge.common.get_version())
try:
from deluge._libtorrent import lt
print("libtorrent: %s" % lt.version)
except ImportError:
pass
print("Python: %s" % platform.python_version())
for version in (platform.linux_distribution(), platform.win32_ver(), platform.mac_ver(), ("n/a",)):
if filter(None, version): # pylint: disable=bad-builtin
print("OS: %s %s" % (platform.system(), " ".join(version)))
break
raise SystemExit
class CommonOptionParser(optparse.OptionParser):
def __init__(self, *args, **kwargs):
optparse.OptionParser.__init__(self, *args, **kwargs)
self.common_group = optparse.OptionGroup(self, _("Common Options"))
self.common_group.add_option("-v", "--version", action="callback", callback=version_callback,
help="Show program's version number and exit")
self.common_group.add_option("-c", "--config", dest="config", action="store", type="str",
help="Set the config folder location")
self.common_group.add_option("-l", "--logfile", dest="logfile", action="store", type="str",
help="Output to designated logfile instead of stdout")
self.common_group.add_option("-L", "--loglevel", dest="loglevel", action="store", type="str",
help="Set the log level: none, info, warning, error, critical, debug")
self.common_group.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
help="Sets the log level to 'none', this is the same as `-L none`")
self.common_group.add_option("-r", "--rotate-logs", action="store_true", default=False,
help="Rotate logfiles.")
self.add_option_group(self.common_group)
def parse_args(self, *args):
options, args = optparse.OptionParser.parse_args(self, *args)
# Setup the logger
if options.quiet:
options.loglevel = "none"
if options.loglevel:
options.loglevel = options.loglevel.lower()
logfile_mode = 'w'
if options.rotate_logs:
logfile_mode = 'a'
# Setup the logger
setup_logger(level=options.loglevel, filename=options.logfile, filemode=logfile_mode)
if options.config:
if not deluge.configmanager.set_config_dir(options.config):
log = logging.getLogger(__name__)
log.error("There was an error setting the config dir! Exiting..")
sys.exit(1)
else:
if not os.path.exists(deluge.common.get_default_config_dir()):
os.makedirs(deluge.common.get_default_config_dir())
return options, args

View File

@ -15,104 +15,52 @@
"""Main starting point for Deluge. Contains the main() entry point.""" """Main starting point for Deluge. Contains the main() entry point."""
from __future__ import print_function from __future__ import print_function
import optparse
import os import os
import platform
import sys import sys
from errno import EEXIST
from logging import FileHandler, getLogger from logging import FileHandler, getLogger
from optparse import OptionParser
import deluge.common import deluge.common
import deluge.configmanager import deluge.configmanager
import deluge.error import deluge.error
from deluge.log import setup_logger from deluge.commonoptions import CommonOptionParser
def version_callback(option, opt_str, value, parser):
print(os.path.basename(sys.argv[0]) + ": " + deluge.common.get_version())
try:
from deluge._libtorrent import lt
print("libtorrent: %s" % lt.version)
except ImportError:
pass
print("Python: %s" % platform.python_version())
for version in (platform.linux_distribution(), platform.win32_ver(), platform.mac_ver(), ("n/a",)):
if filter(None, version): # pylint: disable=bad-builtin
print("OS: %s %s" % (platform.system(), " ".join(version)))
break
raise SystemExit
def start_ui(): def start_ui():
"""Entry point for ui script""" """Entry point for ui script"""
deluge.common.setup_translations()
# Setup the argument parser # Setup the argument parser
parser = OptionParser(usage="%prog [options] [actions]") parser = CommonOptionParser()
parser.add_option("-v", "--version", action="callback", callback=version_callback, group = optparse.OptionGroup(parser, _("Default Options"))
help="Show program's version number and exit")
parser.add_option("-u", "--ui", dest="ui", group.add_option("-u", "--ui", dest="ui",
help="""The UI that you wish to launch. The UI choices are:\n help="""The UI that you wish to launch. The UI choices are:\n
\t gtk -- A GTK-based graphical user interface (default)\n \t gtk -- A GTK-based graphical user interface (default)\n
\t web -- A web-based interface (http://localhost:8112)\n \t web -- A web-based interface (http://localhost:8112)\n
\t console -- A console or command-line interface""") \t console -- A console or command-line interface""", action="store", type="str")
parser.add_option("-s", "--set-default-ui", dest="default_ui", group.add_option("-a", "--args", dest="args",
help="Sets the default UI to be run when no UI is specified") help="Arguments to pass to UI, -a '--option args'", action="store", type="str")
parser.add_option("-a", "--args", dest="args", group.add_option("-s", "--set-default-ui", dest="default_ui",
help="Arguments to pass to UI, -a '--option args'") help="Sets the default UI to be run when no UI is specified", action="store", type="str")
parser.add_option("-c", "--config", dest="config",
help="Set the config folder location") parser.add_option_group(group)
parser.add_option("-l", "--logfile", dest="logfile",
help="Output to designated logfile instead of stdout")
parser.add_option("-L", "--loglevel", dest="loglevel",
help="Set the log level: none, info, warning, error, critical, debug")
parser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
help="Sets the log level to 'none', this is the same as `-L none`")
parser.add_option("-r", "--rotate-logs",
help="Rotate logfiles.", action="store_true", default=False)
# Get the options and args from the OptionParser # Get the options and args from the OptionParser
(options, args) = parser.parse_args(deluge.common.unicode_argv()[1:]) (options, args) = parser.parse_args(deluge.common.unicode_argv()[1:])
# Setup the logger config = deluge.configmanager.ConfigManager("ui.conf")
if options.quiet:
options.loglevel = "none"
if options.loglevel:
options.loglevel = options.loglevel.lower()
logfile_mode = 'w'
if options.rotate_logs:
logfile_mode = 'a'
setup_logger(level=options.loglevel, filename=options.logfile, filemode=logfile_mode)
log = getLogger(__name__) log = getLogger(__name__)
if options.config:
if not os.path.exists(options.config):
# Try to create the config folder if it doesn't exist
try:
os.makedirs(options.config)
except OSError:
pass
elif not os.path.isdir(options.config):
log.error("Config option needs to be a directory!")
sys.exit(1)
else:
if not os.path.exists(deluge.common.get_default_config_dir()):
os.makedirs(deluge.common.get_default_config_dir())
if options.default_ui: if options.default_ui:
if options.config:
deluge.configmanager.set_config_dir(options.config)
config = deluge.configmanager.ConfigManager("ui.conf")
config["default_ui"] = options.default_ui config["default_ui"] = options.default_ui
config.save() config.save()
print("The default UI has been changed to", options.default_ui) log.info("The default UI has been changed to %s", options.default_ui)
sys.exit(0) sys.exit(0)
version = deluge.common.get_version() log.info("Deluge ui %s", deluge.common.get_version())
log.info("Deluge ui %s", version)
log.debug("options: %s", options) log.debug("options: %s", options)
log.debug("args: %s", args) log.debug("args: %s", args)
log.debug("ui_args: %s", args)
from deluge.ui.ui import UI from deluge.ui.ui import UI
log.info("Starting ui..") log.info("Starting ui..")
@ -137,44 +85,39 @@ def start_daemon(skip_start=False):
warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted') warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted')
# Setup the argument parser # Setup the argument parser
parser = OptionParser(usage="%prog [options] [actions]") parser = CommonOptionParser(usage="%prog [options] [actions]")
parser.add_option("-v", "--version", action="callback", callback=version_callback,
help="Show program's version number and exit") group = optparse.OptionGroup(parser, _("Daemon Options"))
parser.add_option("-p", "--port", dest="port", group.add_option("-p", "--port", dest="port",
help="Port daemon will listen on", type="int") help="Port daemon will listen on", action="store", type="int")
parser.add_option("-i", "--interface", dest="listen_interface", group.add_option("-i", "--interface", dest="listen_interface",
help="Interface daemon will listen for bittorrent connections on," help="Interface daemon will listen for bittorrent connections on, "
"this should be an IP address", metavar="IFACE") "this should be an IP address", metavar="IFACE",
parser.add_option("-u", "--ui-interface", dest="ui_interface", metavar="IFACE", action="store", type="str")
help="Interface daemon will listen for UI connections on, this should be an IP address") group.add_option("-u", "--ui-interface", dest="ui_interface",
help="Interface daemon will listen for UI connections on, this should be "
"an IP address", metavar="IFACE", action="store", type="str")
if not (deluge.common.windows_check() or deluge.common.osx_check()): if not (deluge.common.windows_check() or deluge.common.osx_check()):
parser.add_option("-d", "--do-not-daemonize", dest="donot", group.add_option("-d", "--do-not-daemonize", dest="donot",
help="Do not daemonize", action="store_true", default=False) help="Do not daemonize", action="store_true", default=False)
parser.add_option("-c", "--config", dest="config", help="Set the config location") group.add_option("-P", "--pidfile", dest="pidfile",
parser.add_option("-P", "--pidfile", dest="pidfile", help="Use pidfile to store process id") help="Use pidfile to store process id", action="store", type="str")
if not deluge.common.windows_check(): if not deluge.common.windows_check():
parser.add_option("-U", "--user", dest="user", help="User to switch to. Only use it when starting as root") group.add_option("-U", "--user", dest="user",
parser.add_option("-g", "--group", dest="group", help="Group to switch to. Only use it when starting as root") help="User to switch to. Only use it when starting as root", action="store", type="str")
parser.add_option("-l", "--logfile", dest="logfile", help="Set the logfile location") group.add_option("-g", "--group", dest="group",
parser.add_option("-L", "--loglevel", dest="loglevel", help="Group to switch to. Only use it when starting as root", action="store", type="str")
help="Set the log level: none, info, warning, error, critical, debug") group.add_option("--read-only-config-keys",
parser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False, help="List of comma-separated config keys that will not be modified by set_config RPC.",
help="Sets the log level to 'none', this is the same as `-L none`") action="store", type="str", default="")
parser.add_option("-r", "--rotate-logs", help="Rotate logfiles.", action="store_true", default=False) group.add_option("--profile", dest="profile", action="store_true", default=False,
parser.add_option("--profile", dest="profile", action="store_true", default=False, help="Profiles the daemon") help="Profiles the daemon")
parser.add_option("--read-only-config-keys", dest="read_only_config_keys",
help="List of comma-separated config keys that will not be modified by \ parser.add_option_group(group)
set_config RPC.",
action="store", type="str", default="")
# Get the options and args from the OptionParser # Get the options and args from the OptionParser
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if options.config:
if not deluge.configmanager.set_config_dir(options.config):
print("There was an error setting the config directory! Exiting...")
sys.exit(1)
# Check for any daemons running with this same config # Check for any daemons running with this same config
from deluge.core.daemon import check_running_daemon from deluge.core.daemon import check_running_daemon
pid_file = deluge.configmanager.get_config_dir("deluged.pid") pid_file = deluge.configmanager.get_config_dir("deluged.pid")
@ -185,22 +128,6 @@ def start_daemon(skip_start=False):
print("If you believe this is an error, you can force a start by deleting: %s" % pid_file) print("If you believe this is an error, you can force a start by deleting: %s" % pid_file)
sys.exit(1) sys.exit(1)
# Setup the logger
if options.quiet:
options.loglevel = "none"
if options.logfile:
# Try to create the logfile's directory if it doesn't exist
try:
os.makedirs(os.path.abspath(os.path.dirname(options.logfile)))
except OSError as ex:
if ex.errno != EEXIST:
print("There was an error creating the log directory, exiting... (%s)" % ex)
sys.exit(1)
logfile_mode = 'w'
if options.rotate_logs:
logfile_mode = 'a'
setup_logger(level=options.loglevel, filename=options.logfile, filemode=logfile_mode)
log = getLogger(__name__) log = getLogger(__name__)
# If no logfile specified add logging to default location (as well as stdout) # If no logfile specified add logging to default location (as well as stdout)

View File

@ -11,12 +11,11 @@ from __future__ import print_function
import logging import logging
import sys import sys
from optparse import OptionGroup, OptionParser
import deluge.common import deluge.common
import deluge.configmanager import deluge.configmanager
import deluge.log import deluge.log
from deluge.main import version_callback from deluge.commonoptions import CommonOptionParser
try: try:
from setproctitle import setproctitle from setproctitle import setproctitle
@ -24,7 +23,6 @@ except ImportError:
def setproctitle(title): def setproctitle(title):
return return
DEFAULT_PREFS = { DEFAULT_PREFS = {
"default_ui": "gtk" "default_ui": "gtk"
} }
@ -39,18 +37,12 @@ class _UI(object):
def __init__(self, name="gtk"): def __init__(self, name="gtk"):
self.__name = name self.__name = name
self.__parser = OptionParser(usage="%prog [options] [actions]") if name == "gtk":
self.__parser.add_option("-v", "--version", action="callback", callback=version_callback, deluge.common.setup_translations(setup_pygtk=True)
help="Show program's version number and exit") else:
group = OptionGroup(self.__parser, "Common Options") deluge.common.setup_translations()
group.add_option("-c", "--config", dest="config", help="Set the config folder location")
group.add_option("-l", "--logfile", dest="logfile", help="Output to designated logfile instead of stdout") self.__parser = CommonOptionParser()
group.add_option("-L", "--loglevel", dest="loglevel",
help="Set the log level: none, info, warning, error, critical, debug")
group.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
help="Sets the log level to 'none', this is the same as `-L none`")
group.add_option("-r", "--rotate-logs", help="Rotate logfiles.", action="store_true", default=False)
self.__parser.add_option_group(group)
@property @property
def name(self): def name(self):
@ -73,31 +65,8 @@ class _UI(object):
argv = deluge.common.unicode_argv()[1:] argv = deluge.common.unicode_argv()[1:]
(self.__options, self.__args) = self.__parser.parse_args(argv) (self.__options, self.__args) = self.__parser.parse_args(argv)
if self.__options.quiet:
self.__options.loglevel = "none"
logfile_mode = 'w'
if self.__options.rotate_logs:
logfile_mode = 'a'
if self.__options.loglevel:
self.__options.loglevel = self.__options.loglevel.lower()
# Setup the logger
deluge.log.setup_logger(level=self.__options.loglevel,
filename=self.__options.logfile,
filemode=logfile_mode)
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
if self.__options.config:
if not deluge.configmanager.set_config_dir(self.__options.config):
log.error("There was an error setting the config dir! Exiting..")
sys.exit(1)
# Setup gettext
deluge.common.setup_translations()
setproctitle("deluge-%s" % self.__name) setproctitle("deluge-%s" % self.__name)
log.info("Deluge ui %s", deluge.common.get_version()) log.info("Deluge ui %s", deluge.common.get_version())