1
0

cli.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python2
  2. # You may redistribute this program and/or modify it under the terms of
  3. # the GNU General Public License as published by the Free Software Foundation,
  4. # either version 3 of the License, or (at your option) any later version.
  5. #
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. #
  11. # You should have received a copy of the GNU General Public License
  12. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. import sys
  14. import os
  15. import cjdnsadmin
  16. import json
  17. import getopt
  18. import string
  19. def usage():
  20. """ print usage information """
  21. print """
  22. Cjdns admin command line interface.
  23. Usage: [OPTION]... RPC
  24. RPC the function name w/ arguments of the RPC you want to make.
  25. options:
  26. -c --config= the cjdnsadmin file to use. Defaults to ~/.cjdnsadmin
  27. -h, --help display this help and exit
  28. -p, --pretty format the output of the RPC as formatted JSON
  29. Example:
  30. 'functions()' Prints the list of functions available.
  31. """
  32. def parse(args):
  33. """ parse the command line arguments """
  34. try:
  35. return getopt.getopt(args, 'phc:', ['pretty','help','config='])
  36. except getopt.GetoptError:
  37. usage()
  38. sys.exit(2)
  39. if __name__ == "__main__":
  40. options, remainder = parse(sys.argv[1:])
  41. transform = lambda s: s
  42. connect = lambda : cjdnsadmin.connectWithAdminInfo()
  43. for opt, arg in options:
  44. if opt in ('-c', '--config'):
  45. connect = lambda : cjdnsadmin.connectWithAdminInfo(arg)
  46. elif opt in ('-h', '--help'):
  47. usage()
  48. sys.exit(0)
  49. elif opt in ('-p', '--pretty'):
  50. transform = lambda s: json.dumps(s, sort_keys=True, indent=4, separators=(',', ': '))
  51. if remainder:
  52. s = connect()
  53. result = eval('s.' + string.join(remainder," "))
  54. if result:
  55. print transform(result)
  56. else:
  57. usage()