make command parameter names more descriptive

This commit is contained in:
Maximilian Hils 2019-11-18 02:55:37 +01:00
parent cb22fc68d1
commit 8a6370f1c2
4 changed files with 85 additions and 84 deletions

View File

@ -83,7 +83,7 @@ class Core:
) )
@command.command("set") @command.command("set")
def set(self, *spec: str) -> None: def set(self, *options: str) -> None:
""" """
Set an option of the form "key[=value]". When the value is omitted, Set an option of the form "key[=value]". When the value is omitted,
booleans are set to true, strings and integers are set to None (if booleans are set to true, strings and integers are set to None (if
@ -91,7 +91,7 @@ class Core:
false or toggle. If multiple specs are passed, they are joined false or toggle. If multiple specs are passed, they are joined
into one separated by spaces. into one separated by spaces.
""" """
strspec = " ".join(spec) strspec = " ".join(options)
try: try:
ctx.options.set(strspec) ctx.options.set(strspec)
except exceptions.OptionsError as e: except exceptions.OptionsError as e:
@ -109,14 +109,14 @@ class Core:
# FIXME: this will become view.mark later # FIXME: this will become view.mark later
@command.command("flow.mark") @command.command("flow.mark")
def mark(self, flows: typing.Sequence[flow.Flow], val: bool) -> None: def mark(self, flows: typing.Sequence[flow.Flow], boolean: bool) -> None:
""" """
Mark flows. Mark flows.
""" """
updated = [] updated = []
for i in flows: for i in flows:
if i.marked != val: if i.marked != boolean:
i.marked = val i.marked = boolean
updated.append(i) updated.append(i)
ctx.master.addons.trigger("update", updated) ctx.master.addons.trigger("update", updated)
@ -168,19 +168,20 @@ class Core:
"reason", "reason",
] ]
@command.command("flow.set") @command.command(
@command.argument("spec", type=mitmproxy.types.Choice("flow.set.options")) "flow.set")
@command.argument("attr", type=mitmproxy.types.Choice("flow.set.options"))
def flow_set( def flow_set(
self, self,
flows: typing.Sequence[flow.Flow], flows: typing.Sequence[flow.Flow],
spec: str, attr: str,
sval: str value: str
) -> None: ) -> None:
""" """
Quickly set a number of common values on flows. Quickly set a number of common values on flows.
""" """
val: typing.Union[int, str] = sval val: typing.Union[int, str] = value
if spec == "status_code": if attr == "status_code":
try: try:
val = int(val) # type: ignore val = int(val) # type: ignore
except ValueError as v: except ValueError as v:
@ -193,13 +194,13 @@ class Core:
req = getattr(f, "request", None) req = getattr(f, "request", None)
rupdate = True rupdate = True
if req: if req:
if spec == "method": if attr == "method":
req.method = val req.method = val
elif spec == "host": elif attr == "host":
req.host = val req.host = val
elif spec == "path": elif attr == "path":
req.path = val req.path = val
elif spec == "url": elif attr == "url":
try: try:
req.url = val req.url = val
except ValueError as e: except ValueError as e:
@ -212,11 +213,11 @@ class Core:
resp = getattr(f, "response", None) resp = getattr(f, "response", None)
supdate = True supdate = True
if resp: if resp:
if spec == "status_code": if attr == "status_code":
resp.status_code = val resp.status_code = val
if val in status_codes.RESPONSES: if val in status_codes.RESPONSES:
resp.reason = status_codes.RESPONSES[val] # type: ignore resp.reason = status_codes.RESPONSES[val] # type: ignore
elif spec == "reason": elif attr == "reason":
resp.reason = val resp.reason = val
else: else:
supdate = False supdate = False
@ -225,7 +226,7 @@ class Core:
updated.append(f) updated.append(f)
ctx.master.addons.trigger("update", updated) ctx.master.addons.trigger("update", updated)
ctx.log.alert("Set %s on %s flows." % (spec, len(updated))) ctx.log.alert("Set %s on %s flows." % (attr, len(updated)))
@command.command("flow.decode") @command.command("flow.decode")
def decode(self, flows: typing.Sequence[flow.Flow], part: str) -> None: def decode(self, flows: typing.Sequence[flow.Flow], part: str) -> None:
@ -262,12 +263,12 @@ class Core:
ctx.log.alert("Toggled encoding on %s flows." % len(updated)) ctx.log.alert("Toggled encoding on %s flows." % len(updated))
@command.command("flow.encode") @command.command("flow.encode")
@command.argument("enc", type=mitmproxy.types.Choice("flow.encode.options")) @command.argument("encoding", type=mitmproxy.types.Choice("flow.encode.options"))
def encode( def encode(
self, self,
flows: typing.Sequence[flow.Flow], flows: typing.Sequence[flow.Flow],
part: str, part: str,
enc: str, encoding: str,
) -> None: ) -> None:
""" """
Encode flows with a specified encoding. Encode flows with a specified encoding.
@ -279,7 +280,7 @@ class Core:
current_enc = p.headers.get("content-encoding", "identity") current_enc = p.headers.get("content-encoding", "identity")
if current_enc == "identity": if current_enc == "identity":
f.backup() f.backup()
p.encode(enc) p.encode(encoding)
updated.append(f) updated.append(f)
ctx.master.addons.trigger("update", updated) ctx.master.addons.trigger("update", updated)
ctx.log.alert("Encoded %s flows." % len(updated)) ctx.log.alert("Encoded %s flows." % len(updated))

View File

@ -73,14 +73,14 @@ class Export():
return list(sorted(formats.keys())) return list(sorted(formats.keys()))
@command.command("export.file") @command.command("export.file")
def file(self, fmt: str, f: flow.Flow, path: mitmproxy.types.Path) -> None: def file(self, format: str, flow: flow.Flow, path: mitmproxy.types.Path) -> None:
""" """
Export a flow to path. Export a flow to path.
""" """
if fmt not in formats: if format not in formats:
raise exceptions.CommandError("No such export format: %s" % fmt) raise exceptions.CommandError("No such export format: %s" % format)
func: typing.Any = formats[fmt] func: typing.Any = formats[format]
v = func(f) v = func(flow)
try: try:
with open(path, "wb") as fp: with open(path, "wb") as fp:
if isinstance(v, bytes): if isinstance(v, bytes):
@ -91,14 +91,14 @@ class Export():
ctx.log.error(str(e)) ctx.log.error(str(e))
@command.command("export.clip") @command.command("export.clip")
def clip(self, fmt: str, f: flow.Flow) -> None: def clip(self, format: str, flow: flow.Flow) -> None:
""" """
Export a flow to the system clipboard. Export a flow to the system clipboard.
""" """
if fmt not in formats: if format not in formats:
raise exceptions.CommandError("No such export format: %s" % fmt) raise exceptions.CommandError("No such export format: %s" % format)
func: typing.Any = formats[fmt] func: typing.Any = formats[format]
v = strutils.always_str(func(f)) v = strutils.always_str(func(flow))
try: try:
pyperclip.copy(v) pyperclip.copy(v)
except pyperclip.PyperclipException as e: except pyperclip.PyperclipException as e:

View File

@ -217,7 +217,7 @@ class View(collections.abc.Sequence):
# Focus # Focus
@command.command("view.focus.go") @command.command("view.focus.go")
def go(self, dst: int) -> None: def go(self, offset: int) -> None:
""" """
Go to a specified offset. Positive offests are from the beginning of Go to a specified offset. Positive offests are from the beginning of
the view, negative from the end of the view, so that 0 is the first the view, negative from the end of the view, so that 0 is the first
@ -225,13 +225,13 @@ class View(collections.abc.Sequence):
""" """
if len(self) == 0: if len(self) == 0:
return return
if dst < 0: if offset < 0:
dst = len(self) + dst offset = len(self) + offset
if dst < 0: if offset < 0:
dst = 0 offset = 0
if dst > len(self) - 1: if offset > len(self) - 1:
dst = len(self) - 1 offset = len(self) - 1
self.focus.flow = self[dst] self.focus.flow = self[offset]
@command.command("view.focus.next") @command.command("view.focus.next")
def focus_next(self) -> None: def focus_next(self) -> None:
@ -266,20 +266,20 @@ class View(collections.abc.Sequence):
return list(sorted(self.orders.keys())) return list(sorted(self.orders.keys()))
@command.command("view.order.reverse") @command.command("view.order.reverse")
def set_reversed(self, value: bool) -> None: def set_reversed(self, boolean: bool) -> None:
self.order_reversed = value self.order_reversed = boolean
self.sig_view_refresh.send(self) self.sig_view_refresh.send(self)
@command.command("view.order.set") @command.command("view.order.set")
def set_order(self, order: str) -> None: def set_order(self, order_key: str) -> None:
""" """
Sets the current view order. Sets the current view order.
""" """
if order not in self.orders: if order_key not in self.orders:
raise exceptions.CommandError( raise exceptions.CommandError(
"Unknown flow order: %s" % order "Unknown flow order: %s" % order_key
) )
order_key = self.orders[order] order_key = self.orders[order_key]
self.order_key = order_key self.order_key = order_key
newview = sortedcontainers.SortedListWithKey(key=order_key) newview = sortedcontainers.SortedListWithKey(key=order_key)
newview.update(self._view) newview.update(self._view)
@ -298,16 +298,16 @@ class View(collections.abc.Sequence):
# Filter # Filter
@command.command("view.filter.set") @command.command("view.filter.set")
def set_filter_cmd(self, f: str) -> None: def set_filter_cmd(self, filtstr: str) -> None:
""" """
Sets the current view filter. Sets the current view filter.
""" """
filt = None filt = None
if f: if filtstr:
filt = flowfilter.parse(f) filt = flowfilter.parse(filtstr)
if not filt: if not filt:
raise exceptions.CommandError( raise exceptions.CommandError(
"Invalid interception filter: %s" % f "Invalid interception filter: %s" % filtstr
) )
self.set_filter(filt) self.set_filter(filt)
@ -340,11 +340,11 @@ class View(collections.abc.Sequence):
# View Settings # View Settings
@command.command("view.settings.getval") @command.command("view.settings.getval")
def getvalue(self, f: mitmproxy.flow.Flow, key: str, default: str) -> str: def getvalue(self, flow: mitmproxy.flow.Flow, key: str, default: str) -> str:
""" """
Get a value from the settings store for the specified flow. Get a value from the settings store for the specified flow.
""" """
return self.settings[f].get(key, default) return self.settings[flow].get(key, default)
@command.command("view.settings.setval.toggle") @command.command("view.settings.setval.toggle")
def setvalue_toggle( def setvalue_toggle(
@ -412,26 +412,26 @@ class View(collections.abc.Sequence):
ctx.log.alert("Removed %s flows" % len(flows)) ctx.log.alert("Removed %s flows" % len(flows))
@command.command("view.flows.resolve") @command.command("view.flows.resolve")
def resolve(self, spec: str) -> typing.Sequence[mitmproxy.flow.Flow]: def resolve(self, flowspec: str) -> typing.Sequence[mitmproxy.flow.Flow]:
""" """
Resolve a flow list specification to an actual list of flows. Resolve a flow list specification to an actual list of flows.
""" """
if spec == "@all": if flowspec == "@all":
return [i for i in self._store.values()] return [i for i in self._store.values()]
if spec == "@focus": if flowspec == "@focus":
return [self.focus.flow] if self.focus.flow else [] return [self.focus.flow] if self.focus.flow else []
elif spec == "@shown": elif flowspec == "@shown":
return [i for i in self] return [i for i in self]
elif spec == "@hidden": elif flowspec == "@hidden":
return [i for i in self._store.values() if i not in self._view] return [i for i in self._store.values() if i not in self._view]
elif spec == "@marked": elif flowspec == "@marked":
return [i for i in self._store.values() if i.marked] return [i for i in self._store.values() if i.marked]
elif spec == "@unmarked": elif flowspec == "@unmarked":
return [i for i in self._store.values() if not i.marked] return [i for i in self._store.values() if not i.marked]
else: else:
filt = flowfilter.parse(spec) filt = flowfilter.parse(flowspec)
if not filt: if not filt:
raise exceptions.CommandError("Invalid flow filter: %s" % spec) raise exceptions.CommandError("Invalid flow filter: %s" % flowspec)
return [i for i in self._store.values() if filt(i)] return [i for i in self._store.values() if filt(i)]
@command.command("view.flows.create") @command.command("view.flows.create")

View File

@ -287,21 +287,21 @@ class ConsoleAddon:
) )
@command.command("console.command") @command.command("console.command")
def console_command(self, *partial: str) -> None: def console_command(self, *cmdstr: str) -> None:
""" """
Prompt the user to edit a command with a (possibly empty) starting value. Prompt the user to edit a command with a (possibly empty) starting value.
""" """
signals.status_prompt_command.send(partial=" ".join(partial)) # type: ignore signals.status_prompt_command.send(partial=" ".join(cmdstr)) # type: ignore
@command.command("console.command.set") @command.command("console.command.set")
def console_command_set(self, option: str) -> None: def console_command_set(self, option_name: str) -> None:
""" """
Prompt the user to set an option of the form "key[=value]". Prompt the user to set an option of the form "key[=value]".
""" """
option_value = getattr(self.master.options, option, None) option_value = getattr(self.master.options, option_name, None)
current_value = option_value if option_value else "" current_value = option_value if option_value else ""
self.master.commands.execute( self.master.commands.execute(
"console.command set %s=%s" % (option, current_value) "console.command set %s=%s" % (option_name, current_value)
) )
@command.command("console.view.keybindings") @command.command("console.view.keybindings")
@ -351,14 +351,14 @@ class ConsoleAddon:
@command.command("console.bodyview") @command.command("console.bodyview")
@command.argument("part", type=mitmproxy.types.Choice("console.bodyview.options")) @command.argument("part", type=mitmproxy.types.Choice("console.bodyview.options"))
def bodyview(self, f: flow.Flow, part: str) -> None: def bodyview(self, flow: flow.Flow, part: str) -> None:
""" """
Spawn an external viewer for a flow request or response body based Spawn an external viewer for a flow request or response body based
on the detected MIME type. We use the mailcap system to find the on the detected MIME type. We use the mailcap system to find the
correct viewier, and fall back to the programs in $PAGER or $EDITOR correct viewier, and fall back to the programs in $PAGER or $EDITOR
if necessary. if necessary.
""" """
fpart = getattr(f, part, None) fpart = getattr(flow, part, None)
if not fpart: if not fpart:
raise exceptions.CommandError("Part must be either request or response, not %s." % part) raise exceptions.CommandError("Part must be either request or response, not %s." % part)
t = fpart.headers.get("content-type") t = fpart.headers.get("content-type")
@ -397,8 +397,8 @@ class ConsoleAddon:
] ]
@command.command("console.edit.focus") @command.command("console.edit.focus")
@command.argument("part", type=mitmproxy.types.Choice("console.edit.focus.options")) @command.argument("flow_part", type=mitmproxy.types.Choice("console.edit.focus.options"))
def edit_focus(self, part: str) -> None: def edit_focus(self, flow_part: str) -> None:
""" """
Edit a component of the currently focused flow. Edit a component of the currently focused flow.
""" """
@ -410,27 +410,27 @@ class ConsoleAddon:
flow.backup() flow.backup()
require_dummy_response = ( require_dummy_response = (
part in ("response-headers", "response-body", "set-cookies") and flow_part in ("response-headers", "response-body", "set-cookies") and
flow.response is None flow.response is None
) )
if require_dummy_response: if require_dummy_response:
flow.response = http.HTTPResponse.make() flow.response = http.HTTPResponse.make()
if part == "cookies": if flow_part == "cookies":
self.master.switch_view("edit_focus_cookies") self.master.switch_view("edit_focus_cookies")
elif part == "urlencoded form": elif flow_part == "urlencoded form":
self.master.switch_view("edit_focus_urlencoded_form") self.master.switch_view("edit_focus_urlencoded_form")
elif part == "multipart form": elif flow_part == "multipart form":
self.master.switch_view("edit_focus_multipart_form") self.master.switch_view("edit_focus_multipart_form")
elif part == "path": elif flow_part == "path":
self.master.switch_view("edit_focus_path") self.master.switch_view("edit_focus_path")
elif part == "query": elif flow_part == "query":
self.master.switch_view("edit_focus_query") self.master.switch_view("edit_focus_query")
elif part == "request-headers": elif flow_part == "request-headers":
self.master.switch_view("edit_focus_request_headers") self.master.switch_view("edit_focus_request_headers")
elif part == "response-headers": elif flow_part == "response-headers":
self.master.switch_view("edit_focus_response_headers") self.master.switch_view("edit_focus_response_headers")
elif part in ("request-body", "response-body"): elif flow_part in ("request-body", "response-body"):
if part == "request-body": if flow_part == "request-body":
message = flow.request message = flow.request
else: else:
message = flow.response message = flow.response
@ -442,16 +442,16 @@ class ConsoleAddon:
# just strip the newlines off the end of the body when we return # just strip the newlines off the end of the body when we return
# from an editor. # from an editor.
message.content = c.rstrip(b"\n") message.content = c.rstrip(b"\n")
elif part == "set-cookies": elif flow_part == "set-cookies":
self.master.switch_view("edit_focus_setcookies") self.master.switch_view("edit_focus_setcookies")
elif part == "url": elif flow_part == "url":
url = flow.request.url.encode() url = flow.request.url.encode()
edited_url = self.master.spawn_editor(url) edited_url = self.master.spawn_editor(url)
url = edited_url.rstrip(b"\n") url = edited_url.rstrip(b"\n")
flow.request.url = url.decode() flow.request.url = url.decode()
elif part in ["method", "status_code", "reason"]: elif flow_part in ["method", "status_code", "reason"]:
self.master.commands.execute( self.master.commands.execute(
"console.command flow.set @focus %s " % part "console.command flow.set @focus %s " % flow_part
) )
def _grideditor(self): def _grideditor(self):