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
 
@@ -11,67 +11,64 @@ try:
 
    from rhodecode.lib.ext_json import json
 
except ImportError:
 
    try:
 
        import simplejson as json
 
    except ImportError:
 
        import json
 

	
 
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:
 
        """
 
        return {
 
            "id": random_id,
 
            "api_key": apikey,
 
            "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 config for API
 

	
 
    conf = RcConf()
 
    conf['key']
 

	
rhodecode/bin/rhodecode_api.py
Show inline comments
 
@@ -18,25 +18,25 @@
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# 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] "
 
      "METHOD <key:val> <key2:val> ...\n"
 
      "Create config file: rhodecode-gist --apikey=<key> --apihost=http://rhodecode.server --save-config"
 
    )
 

	
 
    parser = argparse.ArgumentParser(description='RhodeCode API cli',
 
                                     usage=usage)
 
@@ -44,26 +44,26 @@ def argparser(argv):
 
    ## config
 
    group = parser.add_argument_group('config')
 
    group.add_argument('--apikey', help='api access key')
 
    group.add_argument('--apihost', help='api host')
 
    group.add_argument('--config', help='config file')
 
    group.add_argument('--save-config', action='store_true', help='save the given config into a file')
 

	
 
    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
 

	
 

	
 
def main(argv=None):
 
    """
 
    Main execution function for cli
 

	
 
    :param argv:
 
    """
 
@@ -81,26 +81,37 @@ def main(argv=None):
 
                      autocreate=True, config={'apikey': args.apikey,
 
                                               'apihost': args.apihost})
 
        sys.exit()
 

	
 
    if not conf:
 
        conf = RcConf(config_location=args.config, autoload=True)
 
        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
 
@@ -21,25 +21,25 @@
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
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] "
 
      "[filename or stdin use - for terminal stdin ]\n"
 
      "Create config file: rhodecode-gist --apikey=<key> --apihost=http://rhodecode.server --save-config"
 
    )
 

	
 
    parser = argparse.ArgumentParser(description='RhodeCode Gist cli',
 
                                     usage=usage)
 
@@ -50,25 +50,29 @@ def argparser(argv):
 
    group.add_argument('--apihost', help='api host')
 
    group.add_argument('--config', help='config file')
 
    group.add_argument('--save-config', action='store_true',
 
                       help='save the given config into a file')
 

	
 
    group = parser.add_argument_group('GIST')
 
    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
 
    parser, args, other = argparser(argv)
 

	
 
    api_credentials_given = (args.apikey and args.apihost)
 
    if args.save_config:
 
        if not api_credentials_given:
 
            raise parser.error('--save-config requires --apikey and --apihost')
 
@@ -126,25 +130,30 @@ def _run(argv):
 
                'content': gist_content,
 
                'lexer': None
 
            }
 
        }
 

	
 
        margs = dict(
 
            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
 

	
 
    :param argv:
 
    """
 
    if argv is None:
 
        argv = sys.argv
 

	
0 comments (0 inline, 0 general)