Skip to content

Commit b7f8e2c

Browse files
author
Sam Clements
committed
Refactored command line parser to work better with subcommands
Environment variable support is now part of the command line tool only, not the library itself.
1 parent d587f7d commit b7f8e2c

2 files changed

Lines changed: 56 additions & 48 deletions

File tree

riemann_client/command.py

Lines changed: 53 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import argparse
66
import json
7+
import os
78

89
import riemann_client.client
910
import riemann_client.transport
@@ -13,64 +14,41 @@
1314
'tcp': riemann_client.transport.TCPTransport
1415
}
1516

17+
parser = argparse.ArgumentParser(add_help=False, description=(
18+
"Uses the RIEMANN_HOST and RIEMANN_PORT environment variables "
19+
"if no host and port are given. If they are not set, the transports "
20+
"will use a default host and port of localhost:5555."))
1621

17-
def wide_formatter(*args, **kwargs):
18-
kwargs.setdefault('max_help_position', 32)
19-
kwargs.setdefault('width', 96)
20-
return argparse.HelpFormatter(*args, **kwargs)
22+
parser.add_argument(
23+
'-h', '--help', action='help',
24+
help="show this help message and exit")
2125

22-
parser = argparse.ArgumentParser(
23-
formatter_class=wide_formatter, description=(
24-
"Uses the RIEMANN_HOST and RIEMANN_PORT environment variables "
25-
"if no host and port are given. If they are not set, the transports "
26-
"will use a default host and port of localhost:5555."))
2726
parser.add_argument(
2827
'-v', '--version', action='version',
2928
version='python-riemann-client v{version} by {author}'.format(
3029
version=riemann_client.__version__,
3130
author=riemann_client.__author__),
3231
help="Show this program's version and exit")
32+
3333
parser.add_argument(
34-
'host', type=str, nargs='?', default=None,
35-
help="The hostname of a Riemann server (default: localhost)")
34+
'-H', '--host', type=str,
35+
default=os.environ.get('RIEMANN_HOST', 'localhost'),
36+
help="The hostname of a Riemann server (environ: %(default)s)")
37+
3638
parser.add_argument(
37-
'port', type=int, nargs='?', default=None,
38-
help="The port to connect to the Riemann server on (default: 5555)")
39+
'-P', '--port', type=int,
40+
default=os.environ.get('RIEMANN_PORT', 5555),
41+
help="The port to connect to the Riemann server on (environ: %(default)s)")
42+
3943
parser.add_argument(
4044
'-t', '--transport', choices=TRANSPORT_CLASSES.keys(), default='tcp',
4145
help="The transport to use (default: %(default)s)")
4246

4347
subparsers = parser.add_subparsers(dest='subparser')
4448

45-
send = subparsers.add_parser(
46-
'send', formatter_class=wide_formatter,
47-
help='Send an event to Riemann')
48-
send.add_argument(
49-
'-p', '--print', action='store_true', dest='print_message',
50-
help="Print the message that is sent to Riemann")
51-
52-
for arg_names, arg_type, arg_help in [
53-
(['-u', '--time'], int, "Unix timestamp"),
54-
(['-S', '--state'], str, "State"),
55-
(['-e', '--event-host'], str, "Host"),
56-
(['-D', '--description'], str, "Description"),
57-
(['-s', '--service'], str, "Service"),
58-
(['-T', '--tags'], list, "Tags"),
59-
(['-l', '--ttl'], int, "Time to live"),
60-
(['-m', '--metric'], float, "Value")]:
61-
send.add_argument(
62-
*arg_names, metavar=arg_type.__name__, type=arg_type, help=arg_help)
63-
64-
query = subparsers.add_parser('query', help='Query the Riemann index')
65-
query.add_argument(
66-
'query', type=str,
67-
help="The query to send")
68-
query.add_argument(
69-
'-pp', '--pretty-print', action='store_true',
70-
help="Pretty print output")
71-
7249

73-
def send(args, client):
50+
def send_function(args, client):
51+
"""Sends a single command to Riemann"""
7452
event = client.event(
7553
time=args.time,
7654
state=args.state,
@@ -84,13 +62,44 @@ def send(args, client):
8462
if args.print_message:
8563
print(str(event).strip())
8664

65+
send = subparsers.add_parser('send', help='Send an event to Riemann')
66+
67+
send.add_argument(
68+
'-p', '--print', action='store_true', dest='print_message',
69+
help="Print the message that is sent to Riemann")
70+
71+
send_arguments = [
72+
(['-u', '--time'], int, "Unix timestamp"),
73+
(['-S', '--state'], str, "State"),
74+
(['-e', '--event-host'], str, "Host"),
75+
(['-D', '--description'], str, "Description"),
76+
(['-s', '--service'], str, "Service"),
77+
(['-T', '--tags'], list, "Tags"),
78+
(['-l', '--ttl'], int, "Time to live"),
79+
(['-m', '--metric'], float, "Value")]
80+
81+
for flags, atype, ahelp in send_arguments:
82+
send.add_argument(*flags, metavar=atype.__name__, type=atype, help=ahelp)
83+
84+
send.set_defaults(function=send_function)
8785

88-
def query(args, client):
86+
87+
def query_function(args, client):
88+
"""Queries the Riemann index and outputs the returned events as JSON
89+
90+
UDP is not supported when querying"""
8991
print(json.dumps(client.query(args.query), sort_keys=True, indent=2))
9092

93+
query = subparsers.add_parser('query', help='Query the Riemann index')
94+
query.add_argument('query', type=str, help="The query to send")
95+
query.set_defaults(function=query_function)
96+
9197

9298
def main():
9399
args = parser.parse_args()
94-
transport = TRANSPORT_CLASSES[args.transport](args.host, args.port)
100+
101+
transport_class = TRANSPORT_CLASSES[args.transport]
102+
transport = transport_class(args.host, args.port)
103+
95104
with riemann_client.client.Client(transport=transport) as client:
96-
{'send': send, 'query': query}[args.subparser](args, client)
105+
args.function(args, client)

riemann_client/transport.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import absolute_import
44

55
import abc
6-
import os
76
import socket
87
import struct
98

@@ -18,9 +17,9 @@ class RiemannError(Exception):
1817
class Transport(object):
1918
__metaclass__ = abc.ABCMeta
2019

21-
def __init__(self, host=None, port=None):
22-
self.host = host or os.environ.get('RIEMANN_HOST', 'localhost')
23-
self.port = port or os.environ.get('RIEMANN_PORT', 5555)
20+
def __init__(self, host='localhost', port=5555):
21+
self.host = host
22+
self.port = port
2423

2524
def __enter__(self):
2625
self.connect()

0 commit comments

Comments
 (0)