From 4f69eef8f310b87a45782b8d097dd148e815486a Mon Sep 17 00:00:00 2001 From: Aldo Cortesi Date: Mon, 13 Jan 2014 14:15:17 +1300 Subject: [PATCH] Extract command parsing and use in script grid editor --- libmproxy/console/grideditor.py | 11 ++++++----- libmproxy/script.py | 19 ++++++++++++------- test/test_script.py | 2 +- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/libmproxy/console/grideditor.py b/libmproxy/console/grideditor.py index fa5142f39..bbdde4e3e 100644 --- a/libmproxy/console/grideditor.py +++ b/libmproxy/console/grideditor.py @@ -1,7 +1,7 @@ import copy, re, os import urwid import common -from .. import utils, filt +from .. import utils, filt, script from netlib import http_uastrings @@ -486,8 +486,9 @@ class PathEditor(GridEditor): class ScriptEditor(GridEditor): title = "Editing scripts" columns = 1 - headings = ("Path",) + headings = ("Command",) def is_error(self, col, val): - return False - - + try: + script.Script.parse_command(val) + except script.ScriptError, v: + return str(v) diff --git a/libmproxy/script.py b/libmproxy/script.py index a80f4694d..0912c9ae6 100644 --- a/libmproxy/script.py +++ b/libmproxy/script.py @@ -47,11 +47,21 @@ class Script: """ def __init__(self, command, master): self.command = command - self.argv = shlex.split(command, posix=(os.name != "nt")) + self.argv = self.parse_command(command) self.ctx = ScriptContext(master) self.ns = None self.load() + @classmethod + def parse_command(klass, command): + args = shlex.split(command, posix=(os.name != "nt")) + args[0] = os.path.expanduser(args[0]) + if not os.path.exists(args[0]): + raise ScriptError("Command not found.") + elif not os.path.isfile(args[0]): + raise ScriptError("Not a file: %s" % args[0]) + return args + def load(self): """ Loads a module. @@ -59,14 +69,9 @@ class Script: Raises ScriptError on failure, with argument equal to an error message that may be a formatted traceback. """ - path = os.path.expanduser(self.argv[0]) - if not os.path.exists(path): - raise ScriptError("No such file: %s" % path) - if not os.path.isfile(path): - raise ScriptError("Not a file: %s" % path) ns = {} try: - execfile(path, ns, ns) + execfile(self.argv[0], ns, ns) except Exception, v: raise ScriptError(traceback.format_exc(v)) self.ns = ns diff --git a/test/test_script.py b/test/test_script.py index 39aa12e9c..025e9f377 100644 --- a/test/test_script.py +++ b/test/test_script.py @@ -40,7 +40,7 @@ class TestScript: fm = flow.FlowMaster(None, s) tutils.raises( - "no such file", + "not found", script.Script, "nonexistent", fm )