Files

79 lines
2.0 KiB
Python
Raw Permalink Normal View History

2014-04-04 14:27:33 -07:00
#!/usr/bin/env python
import cmd
import json
import optparse
import pydoc
import sys
2014-04-21 16:57:13 -04:00
import os
2014-04-24 12:51:23 -04:00
import logging
2014-04-04 14:27:33 -07:00
2014-04-24 12:51:23 -04:00
from pydiscourse.client import DiscourseClient, DiscourseError
2014-04-04 14:27:33 -07:00
class DiscourseCmd(cmd.Cmd):
prompt = 'discourse>'
output = sys.stdout
def __init__(self, client):
cmd.Cmd.__init__(self)
self.client = client
self.prompt = '%s>' % self.client.host
def __getattr__(self, attr):
if attr.startswith('do_'):
method = getattr(self.client, attr[3:])
def wrapper(arg):
args = arg.split()
2014-04-21 16:57:13 -04:00
kwargs = dict(a.split('=') for a in args if '=' in a)
args = [a for a in args if '=' not in a]
try:
return method(*args, **kwargs)
2014-04-24 12:51:23 -04:00
except DiscourseError as e:
2014-04-21 16:57:13 -04:00
print e, e.response.text
return e.response
2014-04-04 14:27:33 -07:00
return wrapper
2014-04-21 16:57:13 -04:00
2014-04-04 14:27:33 -07:00
elif attr.startswith('help_'):
method = getattr(self.client, attr[5:])
def wrapper():
self.output.write(pydoc.render_doc(method))
return wrapper
raise AttributeError
def postcmd(self, result, line):
try:
json.dump(result, self.output, sort_keys=True, indent=4, separators=(',', ': '))
except TypeError:
self.output.write(result.text)
def main():
op = optparse.OptionParser()
2014-04-21 16:57:13 -04:00
op.add_option('--host', default='http://localhost:4000')
2014-04-04 14:27:33 -07:00
op.add_option('--api-user', default='system')
2014-04-24 12:51:23 -04:00
op.add_option('-v', '--verbose', action='store_true')
2014-04-04 14:27:33 -07:00
2014-04-21 16:57:13 -04:00
api_key = os.environ['DISCOURSE_API_KEY']
2014-04-04 14:27:33 -07:00
options, args = op.parse_args()
2014-04-21 16:57:13 -04:00
client = DiscourseClient(options.host, options.api_user, api_key)
2014-04-04 14:27:33 -07:00
2014-04-24 12:51:23 -04:00
if options.verbose:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
2014-04-04 14:27:33 -07:00
c = DiscourseCmd(client)
if args:
line = ' '.join(args)
result = c.onecmd(line)
c.postcmd(result, line)
else:
c.cmdloop()
if __name__ == '__main__':
main()