Changeset - 5a7d52cf084d
[Not reviewed]
beta
0 3 0
Marcin Kuzminski - 12 years ago 2013-05-19 19:46:54
marcin@python-works.com
Added --format into gist CLI

- default --pretty format will give a nice message about gist creation
- api_call shouldn't do any printing let the CLI decide about that
- return pure json with --json format
3 files changed with 34 insertions and 17 deletions:
0 comments (0 inline, 0 general)
rhodecode/bin/base.py
Show inline comments
 
@@ -17,21 +17,22 @@ except ImportError:
 

	
 
CONFIG_NAME = '.rhodecode'
 
FORMAT_PRETTY = 'pretty'
 
FORMAT_JSON = 'json'
 

	
 

	
 
def api_call(apikey, apihost, format, method=None, **kw):
 
def api_call(apikey, apihost, method=None, **kw):
 
    """
 
    Api_call wrapper for RhodeCode
 
    Api_call wrapper for RhodeCode.
 

	
 
    :param apikey:
 
    :param apihost:
 
    :param format: formatting, pretty means prints and pprint of json
 
     json returns unparsed json
 
    :param method:
 
    :returns: json response from server
 
    """
 
    def _build_data(random_id):
 
        """
 
        Builds API data with given random ID
 

	
 
        :param random_id:
 
@@ -42,30 +43,26 @@ def api_call(apikey, apihost, format, me
 
            "method": method,
 
            "args": kw
 
        }
 

	
 
    if not method:
 
        raise Exception('please specify method name !')
 

	
 
    id_ = random.randrange(1, 9999)
 
    req = urllib2.Request('%s/_admin/api' % apihost,
 
                      data=json.dumps(_build_data(id_)),
 
                      headers={'content-type': 'text/plain'})
 
    if format == FORMAT_PRETTY:
 
        sys.stdout.write('calling %s to %s \n' % (req.get_data(), apihost))
 
    ret = urllib2.urlopen(req)
 
    raw_json = ret.read()
 
    json_data = json.loads(raw_json)
 
    id_ret = json_data['id']
 
    _formatted_json = pprint.pformat(json_data)
 
    if id_ret == id_:
 
        if format == FORMAT_JSON:
 
            sys.stdout.write(str(raw_json))
 
        else:
 
            sys.stdout.write('rhodecode returned:\n%s\n' % (_formatted_json))
 
        return json_data
 

	
 
    else:
 
        _formatted_json = pprint.pformat(json_data)
 
        raise Exception('something went wrong. '
 
                        'ID mismatch got %s, expected %s | %s' % (
 
                                            id_ret, id_, _formatted_json))
 

	
 

	
 
class RcConf(object):
rhodecode/bin/rhodecode_api.py
Show inline comments
 
@@ -24,13 +24,13 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
from __future__ import with_statement
 
import sys
 
import argparse
 

	
 
from rhodecode.bin.base import api_call, RcConf, FORMAT_JSON, FORMAT_PRETTY
 
from rhodecode.bin.base import json, api_call, RcConf, FORMAT_JSON, FORMAT_PRETTY
 

	
 

	
 
def argparser(argv):
 
    usage = (
 
      "rhodecode-api [-h] [--format=FORMAT] [--apikey=APIKEY] [--apihost=APIHOST] "
 
      "[--config=CONFIG] [--save-config] "
 
@@ -50,14 +50,14 @@ def argparser(argv):
 

	
 
    group = parser.add_argument_group('API')
 
    group.add_argument('method', metavar='METHOD', nargs='?', type=str, default=None,
 
            help='API method name to call followed by key:value attributes',
 
    )
 
    group.add_argument('--format', dest='format', type=str,
 
            help='output format default: `pretty` can '
 
                 'be also `%s`' % FORMAT_JSON,
 
            help='output format default: `%s` can '
 
                 'be also `%s`' % (FORMAT_PRETTY, FORMAT_JSON),
 
            default=FORMAT_PRETTY
 
    )
 
    args, other = parser.parse_known_args()
 
    return parser, args, other
 

	
 

	
 
@@ -87,20 +87,31 @@ def main(argv=None):
 
        if not conf:
 
            if not api_credentials_given:
 
                parser.error('Could not find config file and missing '
 
                             '--apikey or --apihost in params')
 

	
 
    apikey = args.apikey or conf['apikey']
 
    host = args.apihost or conf['apihost']
 
    apihost = args.apihost or conf['apihost']
 
    method = args.method
 

	
 
    # if we don't have method here it's an error
 
    if not method:
 
        parser.error('Please specify method name')
 

	
 
    try:
 
        margs = dict(map(lambda s: s.split(':', 1), other))
 
    except Exception:
 
        sys.stderr.write('Error parsing arguments \n')
 
        sys.exit()
 
    if args.format == FORMAT_PRETTY:
 
        print 'Calling method %s => %s' % (method, apihost)
 

	
 
    api_call(apikey, host, args.format, method, **margs)
 
    json_data = api_call(apikey, apihost, method, **margs)['result']
 
    if args.format == FORMAT_JSON:
 
        print json.dumps(json_data)
 
    elif args.format == FORMAT_PRETTY:
 
        print 'Server response \n%s' % (
 
                json.dumps(json_data, indent=4, sort_keys=True))
 
    return 0
 

	
 
if __name__ == '__main__':
 
    sys.exit(main(sys.argv))
rhodecode/bin/rhodecode_gist.py
Show inline comments
 
@@ -27,13 +27,13 @@ from __future__ import with_statement
 
import os
 
import sys
 
import stat
 
import argparse
 
import fileinput
 

	
 
from rhodecode.bin.base import api_call, RcConf
 
from rhodecode.bin.base import json, api_call, RcConf, FORMAT_JSON, FORMAT_PRETTY
 

	
 

	
 
def argparser(argv):
 
    usage = (
 
      "rhodecode-gist [-h] [--format=FORMAT] [--apikey=APIKEY] [--apihost=APIHOST] "
 
      "[--config=CONFIG] [--save-config] "
 
@@ -56,13 +56,17 @@ def argparser(argv):
 
    group.add_argument('-f', '--filename', help='set uploaded gist filename')
 
    group.add_argument('-p', '--private', action='store_true',
 
                       help='Create private Gist')
 
    group.add_argument('-d', '--description', help='Gist description')
 
    group.add_argument('-l', '--lifetime', metavar='MINUTES',
 
                       help='Gist lifetime in minutes, -1 (Default) is forever')
 

	
 
    group.add_argument('--format', dest='format', type=str,
 
            help='output format default: `%s` can '
 
                 'be also `%s`' % (FORMAT_PRETTY, FORMAT_JSON),
 
            default=FORMAT_PRETTY
 
    )
 
    args, other = parser.parse_known_args()
 
    return parser, args, other
 

	
 

	
 
def _run(argv):
 
    conf = None
 
@@ -132,13 +136,18 @@ def _run(argv):
 
            gist_lifetime=args.lifetime,
 
            gist_description=args.description,
 
            gist_type='private' if args.private else 'public',
 
            files=files
 
        )
 

	
 
        api_call(apikey, host, 'json', 'create_gist', **margs)
 
        json_data = api_call(apikey, host, 'create_gist', **margs)['result']
 
        if args.format == FORMAT_JSON:
 
            print json.dumps(json_data)
 
        elif args.format == FORMAT_PRETTY:
 
            print 'Created %s gist %s' % (json_data['gist_type'],
 
                                          json_data['gist_url'])
 
    return 0
 

	
 

	
 
def main(argv=None):
 
    """
 
    Main execution function for cli
0 comments (0 inline, 0 general)