summaryrefslogtreecommitdiffstats
path: root/deluge/ui/console/parser.py
diff options
context:
space:
mode:
authorbendikro <bro.devel+deluge@gmail.com>2016-04-30 03:04:40 +0200
committerCalum Lind <calumlind+deluge@gmail.com>2016-10-30 12:45:04 +0000
commit20bae1bf9075f8fbcabb3bbaaeaaa1d8cda1c400 (patch)
tree464aca0ccaac57b835a5dd017f79868e3e1a38b8 /deluge/ui/console/parser.py
parent2f8b4732b45cb3e5c13d84530b1a3fa865985291 (diff)
downloaddeluge-20bae1bf9075f8fbcabb3bbaaeaaa1d8cda1c400.tar.gz
deluge-20bae1bf9075f8fbcabb3bbaaeaaa1d8cda1c400.tar.bz2
deluge-20bae1bf9075f8fbcabb3bbaaeaaa1d8cda1c400.zip
[Console] Rewrite of the console code
This commit is a rewrite of larger parts of the console code. The motivation behind the rewrite is to cleanup the code and reduce code duplication to make it easier to understand and modify, and allow any form of code reuse. Most changes are to the interactive console, but also to how the different modes (BaseMode subclasses) are used and set up. * Address [#2097] - Improve match_torrent search match: Instead of matching e.g. torrent name with name.startswith(pattern) now check for asterix at beginning and end of pattern and search with startswith, endswith or __contains__ according to the pattern. Various smaller fixes: * Add errback handler to connection failed * Fix cmd line console mixing str and unicode input * Fix handling delete backwards with ALT+Backspace * Fix handling resizing of message popups * Fix docs generation warnings * Lets not stop the reactor on exception in basemode.. * Markup for translation arg help strings * Main functionality improvements: - Add support for indentation in formatting code in popup messages (like help) - Add filter sidebar - Add ComboBox and UI language selection - Add columnsview to allow rearranging the torrentlist columns and changing column widths. - Removed Columns pane in preferences as columnsview.py is sufficient - Remove torrent info panel (short cut 'i') as the torrent detail view is sufficient * Cleanups and code restructuring - Made BaseModes subclass of Component - Rewrite of most of basic window/panel to allow easier code reuse - Implemented better handling of multple popups by stacking popups. This makes it easier to return to previous popup when opening multiple popups. * Refactured console code: - modes/ for the different modes - Renamed Legacy mode to CmdLine - Renamed alltorrent.py to torrentlist.py and split the code into - torrentlist/columnsview.py - torrentlist/torrentsview.py - torrentlist/search_mode.py (minor mode) - torrentlist/queue_mode.py (minor mode) - cmdline/ for cmd line commands - utils/ for utility files - widgets/ for reusable GUI widgets - fields.py: Base widgets like TextInput, SelectInput, ComboInput - popup.py: Popup windows - inputpane.py: The BaseInputPane used to manage multiple base widgets in a panel - window.py: The BaseWindow used by all panels needing a curses screen - sidebar.py: The Sidebar panel - statusbars.py: The statusbars - Moved option parsing code from main.py to parser.py
Diffstat (limited to 'deluge/ui/console/parser.py')
-rw-r--r--deluge/ui/console/parser.py145
1 files changed, 145 insertions, 0 deletions
diff --git a/deluge/ui/console/parser.py b/deluge/ui/console/parser.py
new file mode 100644
index 000000000..94f911c55
--- /dev/null
+++ b/deluge/ui/console/parser.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2016 bendikro <bro.devel+deluge@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.
+#
+
+from __future__ import print_function
+
+import argparse
+import shlex
+
+import deluge.component as component
+from deluge.ui.console.utils.colors import ConsoleColorFormatter
+
+
+class OptionParserError(Exception):
+ pass
+
+
+class ConsoleBaseParser(argparse.ArgumentParser):
+
+ def format_help(self):
+ """Differs from ArgumentParser.format_help by adding the raw epilog
+ as formatted in the string. Default bahavior mangles the formatting.
+
+ """
+ # Handle epilog manually to keep the text formatting
+ epilog = self.epilog
+ self.epilog = ""
+ help_str = super(ConsoleBaseParser, self).format_help()
+ if epilog is not None:
+ help_str += epilog
+ self.epilog = epilog
+ return help_str
+
+
+class ConsoleCommandParser(ConsoleBaseParser):
+
+ def _split_args(self, args):
+ command_options = []
+ for a in args:
+ if not a:
+ continue
+ if ";" in a:
+ cmd_lines = [arg.strip() for arg in a.split(";")]
+ elif " " in a:
+ cmd_lines = [a]
+ else:
+ continue
+
+ for cmd_line in cmd_lines:
+ cmds = shlex.split(cmd_line)
+ cmd_options = super(ConsoleCommandParser, self).parse_args(args=cmds)
+ cmd_options.command = cmds[0]
+ command_options.append(cmd_options)
+
+ return command_options
+
+ def parse_args(self, args=None):
+ """Parse known UI args and handle common and process group options.
+
+ Notes:
+ If started by deluge entry script this has already been done.
+
+ Args:
+ args (list, optional): The arguments to parse.
+
+ Returns:
+ argparse.Namespace: The parsed arguments.
+ """
+ from deluge.ui.ui_entry import AMBIGUOUS_CMD_ARGS
+ self.base_parser.parse_known_ui_args(args, withhold=AMBIGUOUS_CMD_ARGS)
+
+ multi_command = self._split_args(args)
+ # If multiple commands were passed to console
+ if multi_command:
+ # With multiple commands, normal parsing will fail, so only parse
+ # known arguments using the base parser, and then set
+ # options.parsed_cmds to the already parsed commands
+ options, remaining = self.base_parser.parse_known_args(args=args)
+ options.parsed_cmds = multi_command
+ else:
+ subcommand = False
+ if hasattr(self.base_parser, "subcommand"):
+ subcommand = getattr(self.base_parser, "subcommand")
+ if not subcommand:
+ # We must use parse_known_args to handle case when no subcommand
+ # is provided, because argparse does not support parsing without
+ # a subcommand
+ options, remaining = self.base_parser.parse_known_args(args=args)
+ # If any options remain it means they do not exist. Reparse with
+ # parse_args to trigger help message
+ if remaining:
+ options = self.base_parser.parse_args(args=args)
+ options.parsed_cmds = []
+ else:
+ options = super(ConsoleCommandParser, self).parse_args(args=args)
+ options.parsed_cmds = [options]
+
+ if not hasattr(options, "remaining"):
+ options.remaining = []
+
+ return options
+
+
+class OptionParser(ConsoleBaseParser):
+
+ def __init__(self, **kwargs):
+ super(OptionParser, self).__init__(**kwargs)
+ self.formatter = ConsoleColorFormatter()
+
+ def exit(self, status=0, msg=None):
+ self._exit = True
+ if msg:
+ print(msg)
+
+ def error(self, msg):
+ """error(msg : string)
+
+ Print a usage message incorporating 'msg' to stderr and exit.
+ If you override this in a subclass, it should not return -- it
+ should either exit or raise an exception.
+ """
+ raise OptionParserError(msg)
+
+ def print_usage(self, _file=None):
+ console = component.get("ConsoleUI")
+ if self.usage:
+ for line in self.format_usage().splitlines():
+ console.write(line)
+
+ def print_help(self, _file=None):
+ console = component.get("ConsoleUI")
+ console.set_batch_write(True)
+ for line in self.format_help().splitlines():
+ console.write(line)
+ console.set_batch_write(False)
+
+ def format_help(self):
+ """Return help formatted with colors."""
+ help_str = super(OptionParser, self).format_help()
+ return self.formatter.format_colors(help_str)