2021-05-29 07:12:54 +00:00
|
|
|
"""
|
|
|
|
MicroPython Remote - Interaction and automation tool for MicroPython
|
2022-06-07 13:22:04 +00:00
|
|
|
MIT license; Copyright (c) 2019-2022 Damien P. George
|
2021-05-29 07:12:54 +00:00
|
|
|
|
|
|
|
This program provides a set of utilities to interact with and automate a
|
|
|
|
MicroPython device over a serial connection. Commands supported are:
|
|
|
|
|
|
|
|
mpremote -- auto-detect, connect and enter REPL
|
|
|
|
mpremote <device-shortcut> -- connect to given device
|
|
|
|
mpremote connect <device> -- connect to given device
|
|
|
|
mpremote disconnect -- disconnect current device
|
|
|
|
mpremote mount <local-dir> -- mount local directory on device
|
|
|
|
mpremote eval <string> -- evaluate and print the string
|
|
|
|
mpremote exec <string> -- execute the string
|
|
|
|
mpremote run <script> -- run the given local script
|
|
|
|
mpremote fs <command> <args...> -- execute filesystem commands on the device
|
|
|
|
mpremote repl -- enter REPL
|
|
|
|
"""
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
import argparse
|
2023-05-30 03:23:12 +00:00
|
|
|
import os, sys, time
|
2021-09-05 12:11:35 +00:00
|
|
|
from collections.abc import Mapping
|
|
|
|
from textwrap import dedent
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
from .commands import (
|
|
|
|
CommandError,
|
|
|
|
do_connect,
|
|
|
|
do_disconnect,
|
|
|
|
do_edit,
|
|
|
|
do_filesystem,
|
|
|
|
do_mount,
|
|
|
|
do_umount,
|
|
|
|
do_exec,
|
|
|
|
do_eval,
|
|
|
|
do_run,
|
|
|
|
do_resume,
|
2023-05-30 03:45:45 +00:00
|
|
|
do_rtc,
|
2022-09-30 01:46:23 +00:00
|
|
|
do_soft_reset,
|
2022-03-03 23:57:46 +00:00
|
|
|
do_deploy_mapfs,
|
2022-09-30 01:46:23 +00:00
|
|
|
)
|
2022-09-28 14:45:34 +00:00
|
|
|
from .mip import do_mip
|
2022-09-30 01:46:23 +00:00
|
|
|
from .repl import do_repl
|
2021-05-29 07:12:54 +00:00
|
|
|
|
|
|
|
_PROG = "mpremote"
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
|
2023-05-30 03:23:12 +00:00
|
|
|
def do_sleep(state, args):
|
|
|
|
time.sleep(args.ms[0])
|
|
|
|
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def do_help(state, _args=None):
|
2022-09-30 04:36:39 +00:00
|
|
|
def print_commands_help(cmds, help_key):
|
2022-09-30 01:46:23 +00:00
|
|
|
max_command_len = max(len(cmd) for cmd in cmds.keys())
|
|
|
|
for cmd in sorted(cmds.keys()):
|
2022-09-30 04:36:39 +00:00
|
|
|
help_message_lines = dedent(help_key(cmds[cmd])).split("\n")
|
2022-09-30 01:46:23 +00:00
|
|
|
help_message = help_message_lines[0]
|
|
|
|
for line in help_message_lines[1:]:
|
|
|
|
help_message = "{}\n{}{}".format(help_message, " " * (max_command_len + 4), line)
|
|
|
|
print(" ", cmd, " " * (max_command_len - len(cmd) + 2), help_message, sep="")
|
|
|
|
|
|
|
|
print(_PROG, "-- MicroPython remote control")
|
|
|
|
print("See https://docs.micropython.org/en/latest/reference/mpremote.html")
|
|
|
|
|
|
|
|
print("\nList of commands:")
|
2022-09-30 04:36:39 +00:00
|
|
|
print_commands_help(
|
|
|
|
_COMMANDS, lambda x: x[1]().description
|
|
|
|
) # extract description from argparse
|
2022-09-30 01:46:23 +00:00
|
|
|
|
|
|
|
print("\nList of shortcuts:")
|
2022-09-30 04:36:39 +00:00
|
|
|
print_commands_help(_command_expansions, lambda x: x[2]) # (args, sub, help_message)
|
2022-09-30 01:46:23 +00:00
|
|
|
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
|
|
|
|
def do_version(state, _args=None):
|
|
|
|
from . import __version__
|
|
|
|
|
|
|
|
print(f"{_PROG} {__version__}")
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
def _bool_flag(cmd_parser, name, short_name, default, description):
|
|
|
|
# In Python 3.9+ this can be replaced with argparse.BooleanOptionalAction.
|
|
|
|
group = cmd_parser.add_mutually_exclusive_group()
|
|
|
|
group.add_argument(
|
|
|
|
"--" + name,
|
|
|
|
"-" + short_name,
|
|
|
|
action="store_true",
|
|
|
|
default=default,
|
|
|
|
help=description,
|
|
|
|
)
|
|
|
|
group.add_argument(
|
|
|
|
"--no-" + name,
|
|
|
|
action="store_false",
|
|
|
|
dest=name,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_connect():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="connect to given device")
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"device", nargs=1, help="Either list, auto, id:x, port:x, or any valid device name/path"
|
|
|
|
)
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2023-05-30 03:23:12 +00:00
|
|
|
def argparse_sleep():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="sleep before executing next command")
|
|
|
|
cmd_parser.add_argument("ms", nargs=1, type=float, help="milliseconds to sleep for")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
def argparse_edit():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="edit files on the device")
|
|
|
|
cmd_parser.add_argument("files", nargs="+", help="list of remote paths")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_mount():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="mount local directory on device")
|
|
|
|
_bool_flag(
|
|
|
|
cmd_parser,
|
|
|
|
"unsafe-links",
|
|
|
|
"l",
|
|
|
|
False,
|
|
|
|
"follow symbolic links pointing outside of local directory",
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument("path", nargs=1, help="local path to mount")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_repl():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="connect to given device")
|
2023-05-11 03:24:14 +00:00
|
|
|
_bool_flag(cmd_parser, "escape-non-printable", "e", False, "escape non-printable characters")
|
2022-10-05 11:30:29 +00:00
|
|
|
cmd_parser.add_argument(
|
|
|
|
"--capture",
|
|
|
|
type=str,
|
|
|
|
required=False,
|
|
|
|
help="saves a copy of the REPL session to the specified path",
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"--inject-code", type=str, required=False, help="code to be run when Ctrl-J is pressed"
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"--inject-file",
|
|
|
|
type=str,
|
|
|
|
required=False,
|
|
|
|
help="path to file to be run when Ctrl-K is pressed",
|
|
|
|
)
|
2022-09-30 04:36:39 +00:00
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_eval():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="evaluate and print the string")
|
|
|
|
cmd_parser.add_argument("expr", nargs=1, help="expression to execute")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_exec():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="execute the string")
|
2022-10-05 11:30:29 +00:00
|
|
|
_bool_flag(
|
|
|
|
cmd_parser, "follow", "f", True, "follow output until the expression completes (default)"
|
|
|
|
)
|
2022-09-30 04:36:39 +00:00
|
|
|
cmd_parser.add_argument("expr", nargs=1, help="expression to execute")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
|
|
|
def argparse_run():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="run the given local script")
|
2022-10-05 11:30:29 +00:00
|
|
|
_bool_flag(
|
|
|
|
cmd_parser, "follow", "f", True, "follow output until the script completes (default)"
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument("path", nargs=1, help="path to script to execute")
|
2022-09-30 04:36:39 +00:00
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2023-05-30 03:45:45 +00:00
|
|
|
def argparse_rtc():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="get (default) or set the device RTC")
|
|
|
|
_bool_flag(cmd_parser, "set", "s", False, "set the RTC to the current local time")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
def argparse_filesystem():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="execute filesystem commands on the device")
|
|
|
|
_bool_flag(cmd_parser, "recursive", "r", False, "recursive copy (for cp command only)")
|
|
|
|
_bool_flag(
|
|
|
|
cmd_parser,
|
|
|
|
"verbose",
|
|
|
|
"v",
|
|
|
|
None,
|
|
|
|
"enable verbose output (defaults to True for all commands except cat)",
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"command", nargs=1, help="filesystem command (e.g. cat, cp, ls, rm, touch)"
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument("path", nargs="+", help="local and remote paths")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2022-09-28 14:45:34 +00:00
|
|
|
def argparse_mip():
|
|
|
|
cmd_parser = argparse.ArgumentParser(
|
|
|
|
description="install packages from micropython-lib or third-party sources"
|
|
|
|
)
|
|
|
|
_bool_flag(cmd_parser, "mpy", "m", True, "download as compiled .mpy files (default)")
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"--target", type=str, required=False, help="destination direction on the device"
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"--index",
|
|
|
|
type=str,
|
|
|
|
required=False,
|
|
|
|
help="package index to use (defaults to micropython-lib)",
|
|
|
|
)
|
|
|
|
cmd_parser.add_argument("command", nargs=1, help="mip command (e.g. install)")
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"packages",
|
|
|
|
nargs="+",
|
|
|
|
help="list package specifications, e.g. name, name@version, github:org/repo, github:org/repo@branch",
|
|
|
|
)
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2022-03-03 23:57:46 +00:00
|
|
|
def argparse_deploy_mapfs():
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="deploy a directory to /mapfs on the device")
|
|
|
|
cmd_parser.add_argument("path", nargs=1, help="path to directory to deploy")
|
|
|
|
return cmd_parser
|
|
|
|
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
def argparse_none(description):
|
|
|
|
return lambda: argparse.ArgumentParser(description=description)
|
|
|
|
|
|
|
|
|
|
|
|
# Map of "command" to tuple of (handler_func, argparse_func).
|
2021-09-05 12:11:35 +00:00
|
|
|
_COMMANDS = {
|
|
|
|
"connect": (
|
2022-09-30 01:46:23 +00:00
|
|
|
do_connect,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_connect,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
2023-05-30 03:23:12 +00:00
|
|
|
"sleep": (
|
|
|
|
do_sleep,
|
|
|
|
argparse_sleep,
|
|
|
|
),
|
2022-09-30 01:46:23 +00:00
|
|
|
"disconnect": (
|
|
|
|
do_disconnect,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("disconnect current device"),
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"edit": (
|
|
|
|
do_edit,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_edit,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"resume": (
|
|
|
|
do_resume,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("resume a previous mpremote session (will not auto soft-reset)"),
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"soft-reset": (
|
|
|
|
do_soft_reset,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("perform a soft-reset of the device"),
|
2021-09-05 12:11:35 +00:00
|
|
|
),
|
2022-04-06 17:56:28 +00:00
|
|
|
"mount": (
|
2022-09-30 01:46:23 +00:00
|
|
|
do_mount,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_mount,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"umount": (
|
|
|
|
do_umount,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("unmount the local directory"),
|
2022-04-06 17:56:28 +00:00
|
|
|
),
|
2021-09-05 12:11:35 +00:00
|
|
|
"repl": (
|
2022-09-30 01:46:23 +00:00
|
|
|
do_repl,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_repl,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"eval": (
|
|
|
|
do_eval,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_eval,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"exec": (
|
|
|
|
do_exec,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_exec,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"run": (
|
|
|
|
do_run,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_run,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
2023-05-30 03:45:45 +00:00
|
|
|
"rtc": (
|
|
|
|
do_rtc,
|
|
|
|
argparse_rtc,
|
|
|
|
),
|
2022-09-30 01:46:23 +00:00
|
|
|
"fs": (
|
|
|
|
do_filesystem,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_filesystem,
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
2022-09-28 14:45:34 +00:00
|
|
|
"mip": (
|
|
|
|
do_mip,
|
|
|
|
argparse_mip,
|
|
|
|
),
|
2022-09-30 01:46:23 +00:00
|
|
|
"help": (
|
|
|
|
do_help,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("print help and exit"),
|
2022-09-30 01:46:23 +00:00
|
|
|
),
|
|
|
|
"version": (
|
|
|
|
do_version,
|
2022-09-30 04:36:39 +00:00
|
|
|
argparse_none("print version and exit"),
|
2021-09-05 12:11:35 +00:00
|
|
|
),
|
2022-03-03 23:57:46 +00:00
|
|
|
"deploy-mapfs": (
|
|
|
|
do_deploy_mapfs,
|
|
|
|
argparse_deploy_mapfs,
|
|
|
|
),
|
2021-09-05 12:11:35 +00:00
|
|
|
}
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
# Additional commands aliases.
|
|
|
|
# The value can either be:
|
|
|
|
# - A command string.
|
|
|
|
# - A list of command strings, each command will be executed sequentially.
|
|
|
|
# - A dict of command: { [], help: ""}
|
2021-05-29 07:12:54 +00:00
|
|
|
_BUILTIN_COMMAND_EXPANSIONS = {
|
|
|
|
# Device connection shortcuts.
|
2021-09-05 12:11:35 +00:00
|
|
|
"devs": {
|
|
|
|
"command": "connect list",
|
|
|
|
"help": "list available serial ports",
|
|
|
|
},
|
2023-05-30 07:31:05 +00:00
|
|
|
# Filesystem shortcuts (use `cp` instead of `fs cp`).
|
2021-05-29 07:12:54 +00:00
|
|
|
"cat": "fs cat",
|
|
|
|
"ls": "fs ls",
|
|
|
|
"cp": "fs cp",
|
|
|
|
"rm": "fs rm",
|
2022-08-18 02:36:42 +00:00
|
|
|
"touch": "fs touch",
|
2021-05-29 07:12:54 +00:00
|
|
|
"mkdir": "fs mkdir",
|
|
|
|
"rmdir": "fs rmdir",
|
2023-05-30 07:31:05 +00:00
|
|
|
# Disk used/free.
|
2021-05-29 07:12:54 +00:00
|
|
|
"df": [
|
|
|
|
"exec",
|
2022-08-19 12:58:37 +00:00
|
|
|
"import os\nprint('mount \\tsize \\tused \\tavail \\tuse%')\nfor _m in [''] + os.listdir('/'):\n _s = os.stat('/' + _m)\n if not _s[0] & 1 << 14: continue\n _s = os.statvfs(_m)\n if _s[0]:\n _size = _s[0] * _s[2]; _free = _s[0] * _s[3]; print(_m, _size, _size - _free, _free, int(100 * (_size - _free) / _size), sep='\\t')",
|
2021-05-29 07:12:54 +00:00
|
|
|
],
|
|
|
|
# Other shortcuts.
|
2023-05-30 03:23:12 +00:00
|
|
|
"reset": {
|
2021-09-05 12:11:35 +00:00
|
|
|
"command": [
|
|
|
|
"exec",
|
|
|
|
"--no-follow",
|
2023-05-30 03:23:12 +00:00
|
|
|
"import time, machine; time.sleep_ms(100); machine.reset()",
|
2021-09-05 12:11:35 +00:00
|
|
|
],
|
2023-05-30 03:23:12 +00:00
|
|
|
"help": "hard reset the device",
|
2021-09-05 12:11:35 +00:00
|
|
|
},
|
2023-05-30 03:23:12 +00:00
|
|
|
"bootloader": {
|
2021-09-05 12:11:35 +00:00
|
|
|
"command": [
|
|
|
|
"exec",
|
|
|
|
"--no-follow",
|
2023-05-30 03:23:12 +00:00
|
|
|
"import time, machine; time.sleep_ms(100); machine.bootloader()",
|
2021-09-05 12:11:35 +00:00
|
|
|
],
|
|
|
|
"help": "make the device enter its bootloader",
|
|
|
|
},
|
2023-05-30 03:45:45 +00:00
|
|
|
# Simple aliases.
|
2022-02-02 10:20:05 +00:00
|
|
|
"--help": "help",
|
2022-06-07 13:22:04 +00:00
|
|
|
"--version": "version",
|
2021-05-29 07:12:54 +00:00
|
|
|
}
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
# Add "a0", "a1", ..., "u0", "u1", ..., "c0", "c1", ... as aliases
|
|
|
|
# for "connect /dev/ttyACMn" (and /dev/ttyUSBn, COMn) etc.
|
2021-09-05 12:11:35 +00:00
|
|
|
for port_num in range(4):
|
|
|
|
for prefix, port in [("a", "/dev/ttyACM"), ("u", "/dev/ttyUSB"), ("c", "COM")]:
|
|
|
|
_BUILTIN_COMMAND_EXPANSIONS["{}{}".format(prefix, port_num)] = {
|
|
|
|
"command": "connect {}{}".format(port, port_num),
|
|
|
|
"help": 'connect to serial port "{}{}"'.format(port, port_num),
|
|
|
|
}
|
|
|
|
|
2021-05-29 07:12:54 +00:00
|
|
|
|
|
|
|
def load_user_config():
|
|
|
|
# Create empty config object.
|
|
|
|
config = __build_class__(lambda: None, "Config")()
|
|
|
|
config.commands = {}
|
|
|
|
|
|
|
|
# Get config file name.
|
|
|
|
path = os.getenv("XDG_CONFIG_HOME")
|
|
|
|
if path is None:
|
|
|
|
path = os.getenv("HOME")
|
|
|
|
if path is None:
|
|
|
|
return config
|
|
|
|
path = os.path.join(path, ".config")
|
|
|
|
path = os.path.join(path, _PROG)
|
|
|
|
config_file = os.path.join(path, "config.py")
|
|
|
|
|
|
|
|
# Check if config file exists.
|
|
|
|
if not os.path.exists(config_file):
|
|
|
|
return config
|
|
|
|
|
|
|
|
# Exec the config file in its directory.
|
|
|
|
with open(config_file) as f:
|
|
|
|
config_data = f.read()
|
|
|
|
prev_cwd = os.getcwd()
|
|
|
|
os.chdir(path)
|
|
|
|
exec(config_data, config.__dict__)
|
|
|
|
os.chdir(prev_cwd)
|
|
|
|
|
|
|
|
return config
|
|
|
|
|
|
|
|
|
|
|
|
def prepare_command_expansions(config):
|
|
|
|
global _command_expansions
|
|
|
|
|
|
|
|
_command_expansions = {}
|
|
|
|
|
|
|
|
for command_set in (_BUILTIN_COMMAND_EXPANSIONS, config.commands):
|
|
|
|
for cmd, sub in command_set.items():
|
|
|
|
cmd = cmd.split()
|
|
|
|
if len(cmd) == 1:
|
|
|
|
args = ()
|
|
|
|
else:
|
|
|
|
args = tuple(c.split("=") for c in cmd[1:])
|
2021-09-05 12:11:35 +00:00
|
|
|
|
|
|
|
help_message = ""
|
|
|
|
if isinstance(sub, Mapping):
|
|
|
|
help_message = sub.get("help", "")
|
|
|
|
sub = sub["command"]
|
2021-05-29 07:12:54 +00:00
|
|
|
if isinstance(sub, str):
|
|
|
|
sub = sub.split()
|
2021-09-05 12:11:35 +00:00
|
|
|
_command_expansions[cmd[0]] = (args, sub, help_message)
|
2021-05-29 07:12:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
def do_command_expansion(args):
|
|
|
|
def usage_error(cmd, exp_args, msg):
|
|
|
|
print(f"Command {cmd} {msg}; signature is:")
|
|
|
|
print(" ", cmd, " ".join("=".join(a) for a in exp_args))
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
last_arg_idx = len(args)
|
|
|
|
pre = []
|
|
|
|
while args and args[0] in _command_expansions:
|
|
|
|
cmd = args.pop(0)
|
2021-09-05 12:11:35 +00:00
|
|
|
exp_args, exp_sub, _ = _command_expansions[cmd]
|
2021-05-29 07:12:54 +00:00
|
|
|
for exp_arg in exp_args:
|
2023-05-30 03:25:29 +00:00
|
|
|
if args and args[0] == "+":
|
|
|
|
break
|
2021-05-29 07:12:54 +00:00
|
|
|
exp_arg_name = exp_arg[0]
|
|
|
|
if args and "=" not in args[0]:
|
|
|
|
# Argument given without a name.
|
|
|
|
value = args.pop(0)
|
|
|
|
elif args and args[0].startswith(exp_arg_name + "="):
|
|
|
|
# Argument given with correct name.
|
|
|
|
value = args.pop(0).split("=", 1)[1]
|
|
|
|
else:
|
|
|
|
# No argument given, or argument given with a different name.
|
|
|
|
if len(exp_arg) == 1:
|
|
|
|
# Required argument (it has no default).
|
|
|
|
usage_error(cmd, exp_args, f"missing argument {exp_arg_name}")
|
|
|
|
else:
|
|
|
|
# Optional argument with a default.
|
|
|
|
value = exp_arg[1]
|
|
|
|
pre.append(f"{exp_arg_name}={value}")
|
|
|
|
|
|
|
|
args[0:0] = exp_sub
|
|
|
|
last_arg_idx = len(exp_sub)
|
|
|
|
|
|
|
|
if last_arg_idx < len(args) and "=" in args[last_arg_idx]:
|
|
|
|
# Extra unknown arguments given.
|
|
|
|
arg = args[last_arg_idx].split("=", 1)[0]
|
|
|
|
usage_error(cmd, exp_args, f"given unexpected argument {arg}")
|
|
|
|
|
|
|
|
# Insert expansion with optional setting of arguments.
|
|
|
|
if pre:
|
|
|
|
args[0:0] = ["exec", ";".join(pre)]
|
|
|
|
|
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
class State:
|
|
|
|
def __init__(self):
|
2023-05-31 04:19:14 +00:00
|
|
|
self.transport = None
|
2022-09-30 01:46:23 +00:00
|
|
|
self._did_action = False
|
|
|
|
self._auto_soft_reset = True
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def did_action(self):
|
|
|
|
self._did_action = True
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def run_repl_on_completion(self):
|
|
|
|
return not self._did_action
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def ensure_connected(self):
|
2023-05-31 04:19:14 +00:00
|
|
|
if self.transport is None:
|
2022-09-30 04:36:39 +00:00
|
|
|
do_connect(self)
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def ensure_raw_repl(self, soft_reset=None):
|
|
|
|
self.ensure_connected()
|
|
|
|
soft_reset = self._auto_soft_reset if soft_reset is None else soft_reset
|
2023-05-31 04:19:14 +00:00
|
|
|
if soft_reset or not self.transport.in_raw_repl:
|
|
|
|
self.transport.enter_raw_repl(soft_reset=soft_reset)
|
2022-09-30 01:46:23 +00:00
|
|
|
self._auto_soft_reset = False
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 01:46:23 +00:00
|
|
|
def ensure_friendly_repl(self):
|
|
|
|
self.ensure_connected()
|
2023-05-31 04:19:14 +00:00
|
|
|
if self.transport.in_raw_repl:
|
|
|
|
self.transport.exit_raw_repl()
|
2022-06-07 13:22:04 +00:00
|
|
|
|
|
|
|
|
2021-05-29 07:12:54 +00:00
|
|
|
def main():
|
|
|
|
config = load_user_config()
|
|
|
|
prepare_command_expansions(config)
|
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
remaining_args = sys.argv[1:]
|
2022-09-30 01:46:23 +00:00
|
|
|
state = State()
|
2021-05-29 07:12:54 +00:00
|
|
|
|
|
|
|
try:
|
2022-09-30 04:36:39 +00:00
|
|
|
while remaining_args:
|
|
|
|
# Skip the terminator.
|
|
|
|
if remaining_args[0] == "+":
|
|
|
|
remaining_args.pop(0)
|
|
|
|
continue
|
|
|
|
|
|
|
|
# Rewrite the front of the list with any matching expansion.
|
|
|
|
do_command_expansion(remaining_args)
|
|
|
|
|
|
|
|
# The (potentially rewritten) command must now be a base command.
|
|
|
|
cmd = remaining_args.pop(0)
|
2021-05-29 07:12:54 +00:00
|
|
|
try:
|
2022-09-30 04:36:39 +00:00
|
|
|
handler_func, parser_func = _COMMANDS[cmd]
|
2021-05-29 07:12:54 +00:00
|
|
|
except KeyError:
|
2022-09-30 01:46:23 +00:00
|
|
|
raise CommandError(f"'{cmd}' is not a command")
|
2021-05-29 07:12:54 +00:00
|
|
|
|
2022-09-30 04:36:39 +00:00
|
|
|
# If this command (or any down the chain) has a terminator, then
|
|
|
|
# limit the arguments passed for this command. They will be added
|
|
|
|
# back after processing this command.
|
|
|
|
try:
|
|
|
|
terminator = remaining_args.index("+")
|
|
|
|
command_args = remaining_args[:terminator]
|
|
|
|
extra_args = remaining_args[terminator:]
|
|
|
|
except ValueError:
|
|
|
|
command_args = remaining_args
|
|
|
|
extra_args = []
|
|
|
|
|
|
|
|
# Special case: "fs ls" allowed have no path specified.
|
|
|
|
if cmd == "fs" and len(command_args) == 1 and command_args[0] == "ls":
|
|
|
|
command_args.append("")
|
|
|
|
|
|
|
|
# Use the command-specific argument parser.
|
|
|
|
cmd_parser = parser_func()
|
|
|
|
cmd_parser.prog = cmd
|
|
|
|
# Catch all for unhandled positional arguments (this is the next command).
|
|
|
|
cmd_parser.add_argument(
|
|
|
|
"next_command", nargs=argparse.REMAINDER, help=f"Next {_PROG} command"
|
|
|
|
)
|
|
|
|
args = cmd_parser.parse_args(command_args)
|
|
|
|
|
|
|
|
# Execute command.
|
|
|
|
handler_func(state, args)
|
|
|
|
|
|
|
|
# Get any leftover unprocessed args.
|
|
|
|
remaining_args = args.next_command + extra_args
|
|
|
|
|
|
|
|
# If no commands were "actions" then implicitly finish with the REPL
|
|
|
|
# using default args.
|
2022-09-30 01:46:23 +00:00
|
|
|
if state.run_repl_on_completion():
|
2022-09-30 04:36:39 +00:00
|
|
|
do_repl(state, argparse_repl().parse_args([]))
|
2022-09-30 01:46:23 +00:00
|
|
|
|
|
|
|
return 0
|
|
|
|
except CommandError as e:
|
|
|
|
print(f"{_PROG}: {e}", file=sys.stderr)
|
|
|
|
return 1
|
2021-05-29 07:12:54 +00:00
|
|
|
finally:
|
2022-09-30 01:46:23 +00:00
|
|
|
do_disconnect(state)
|