|
- """Command line client functionality"""
-
- import nilmdb.client
-
- from nilmdb.utils.printf import *
- from nilmdb.utils import datetime_tz
- import nilmdb.utils.time
-
- import sys
- import os
- import argparse
- from argparse import ArgumentDefaultsHelpFormatter as def_form
-
- # Valid subcommands. Defined in separate files just to break
- # things up -- they're still called with Cmdline as self.
- subcommands = [ "help", "info", "create", "list", "metadata",
- "insert", "extract", "remove", "destroy",
- "intervals", "rename" ]
-
- # Import the subcommand modules
- subcmd_mods = {}
- for cmd in subcommands:
- subcmd_mods[cmd] = __import__("nilmdb.cmdline." + cmd, fromlist = [ cmd ])
-
- class JimArgumentParser(argparse.ArgumentParser):
- def error(self, message):
- self.print_usage(sys.stderr)
- self.exit(2, sprintf("error: %s\n", message))
-
- class Cmdline(object):
-
- def __init__(self, argv = None):
- self.argv = argv or sys.argv[1:]
- self.client = None
- self.def_url = os.environ.get("NILMDB_URL", "http://localhost:12380")
- self.subcmd = {}
-
- def arg_time(self, toparse):
- """Parse a time string argument"""
- try:
- return nilmdb.utils.time.parse_time(toparse).totimestamp()
- except ValueError as e:
- raise argparse.ArgumentTypeError(sprintf("%s \"%s\"",
- str(e), toparse))
-
- def parser_setup(self):
- self.parser = JimArgumentParser(add_help = False,
- formatter_class = def_form)
-
- group = self.parser.add_argument_group("General options")
- group.add_argument("-h", "--help", action='help',
- help='show this help message and exit')
- group.add_argument("-V", "--version", action="version",
- version = nilmdb.__version__)
-
- group = self.parser.add_argument_group("Server")
- group.add_argument("-u", "--url", action="store",
- default=self.def_url,
- help="NilmDB server URL (default: %(default)s)")
-
- sub = self.parser.add_subparsers(
- title="Commands", dest="command",
- description="Use 'help command' or 'command --help' for more "
- "details on a particular command.")
-
- # Set up subcommands (defined in separate files)
- for cmd in subcommands:
- self.subcmd[cmd] = subcmd_mods[cmd].setup(self, sub)
-
- def die(self, formatstr, *args):
- fprintf(sys.stderr, formatstr + "\n", *args)
- if self.client:
- self.client.close()
- sys.exit(-1)
-
- def run(self):
- # Clear cached timezone, so that we can pick up timezone changes
- # while running this from the test suite.
- datetime_tz._localtz = None
-
- # Run parser
- self.parser_setup()
- self.args = self.parser.parse_args(self.argv)
-
- # Run arg verify handler if there is one
- if "verify" in self.args:
- self.args.verify(self)
-
- self.client = nilmdb.client.Client(self.args.url)
-
- # Make a test connection to make sure things work,
- # unless the particular command requests that we don't.
- if "no_test_connect" not in self.args:
- try:
- server_version = self.client.version()
- except nilmdb.client.Error as e:
- self.die("error connecting to server: %s", str(e))
-
- # Now dispatch client request to appropriate function. Parser
- # should have ensured that we don't have any unknown commands
- # here.
- retval = self.args.handler(self) or 0
-
- self.client.close()
- sys.exit(retval)
|