| 1 | """Command line interface for echo server.""" |
| 2 | |
| 3 | import fnmatch |
| 4 | import asyncio |
| 5 | import argparse |
| 6 | |
| 7 | from aioconsole import AsynchronousCli, start_interactive_server |
| 8 | from aioconsole.server import parse_server, print_server |
| 9 | |
| 10 | from . import echo |
| 11 | |
| 12 | |
| 13 | async def get_history(reader, writer, pattern=None): |
| 14 | history = asyncio.get_event_loop().history |
| 15 | if not history: |
| 16 | return "No message in the history" |
| 17 | if pattern: |
| 18 | history = {host: history[host] for host in fnmatch.filter(history, pattern)} |
| 19 | if not history: |
| 20 | return "No host match the given pattern" |
| 21 | for host in history: |
| 22 | writer.write(f"Host {host}:\n".encode()) |
| 23 | for i, message in enumerate(history[host]): |
| 24 | writer.write(f" {i}. {message}\n".encode()) |
| 25 | |
| 26 | |
| 27 | def make_cli(streams=None): |
| 28 | parser = argparse.ArgumentParser(description="Display the message history") |
| 29 | parser.add_argument("--pattern", "-p", type=str, help="pattern to filter hostnames") |
| 30 | commands = {"history": (get_history, parser)} |
| 31 | return AsynchronousCli(commands, streams, prog="echo") |
| 32 | |
| 33 | |
| 34 | def parse_args(args=None): |
| 35 | parser = argparse.ArgumentParser( |
| 36 | description="Run the echo server and a command line interface." |
| 37 | ) |
| 38 | parser.add_argument( |
| 39 | "server", |
| 40 | metavar="[HOST:]PORT", |
| 41 | type=str, |
| 42 | help="interface for the echo server, default host is localhost", |
| 43 | ) |
| 44 | parser.add_argument( |
| 45 | "--serve-cli", |
| 46 | metavar="[HOST:]PORT", |
| 47 | type=str, |
| 48 | help="serve the command line interface on the given host+port " |
| 49 | "instead of using the standard streams", |
| 50 | ) |
| 51 | namespace = parser.parse_args(args) |
| 52 | host, port = parse_server(namespace.server, parser) |
| 53 | if namespace.serve_cli is not None: |
| 54 | serve_cli = parse_server(namespace.serve_cli, parser) |
| 55 | else: |
| 56 | serve_cli = None |
| 57 | return host, port, serve_cli |
| 58 | |
| 59 | |
| 60 | def main(args=None): |
| 61 | host, port, serve_cli = parse_args(args) |
| 62 | if serve_cli: |
| 63 | cli_host, cli_port = serve_cli |
| 64 | coro = start_interactive_server(make_cli, cli_host, cli_port) |
| 65 | server = asyncio.get_event_loop().run_until_complete(coro) |
| 66 | print_server(server, "command line interface") |
| 67 | else: |
| 68 | asyncio.ensure_future(make_cli().interact()) |
| 69 | return echo.run(host, port) |
| 70 | |
| 71 | |
| 72 | if __name__ == "__main__": |
| 73 | main() |