# -*- coding: utf-8 -
#
# This file is part of restkit released under the MIT license. 
# See the NOTICE for more information.

import os
import optparse as op
import sys

from restkit import __version__, request

__usage__ = "'%prog [options] url [METHOD] [filename]'"

def options():
    """ build command lines options """
    return [
        op.make_option('-H', '--header', action='append', dest='headers',
                help='http string header in the form of Key:Value. '+
                'For example: "Accept: application/json" '),
        op.make_option('-i', '--input', action='store', dest='input', 
                metavar='FILE', help='the name of the file to read from'),
        op.make_option('-o', '--output', action='store', dest='output',
                help='the name of the file to write to'),
        op.make_option('--follow-redirect', action='store_false', 
                dest='follow_redirect', default=True)
    ]

def main():
    """ function to manage restkit command line """
    parser = op.OptionParser(usage=__usage__, option_list=options(),
                    version="%prog " + __version__)
 
    opts, args = parser.parse_args()
    args_len = len(args)
    
    if args_len < 1:
        return parser.error('incorrect number of arguments')

    body = None
    headers = []
    if opts.input:
        if opts.input == '-':
            body = sys.stdin.read()
            headers.append(("Content-Length", str(len(body))))
        else:
            fname = os.path.normpath(os.path.join(os.getcwd(),opts.input))
            body = open(fname, 'r')
    
    if opts.headers:
        for header in opts.headers:
            try:
                k, v = header.split(':')
                headers.append((k, v))
            except ValueError:
                pass

    try:
        if args_len == 3:
            resp = request(args[0], method=args[1], body=body,
                        headers=headers, follow_redirect=opts.follow_redirect)
        elif len(args) == 2:
            if args[1] == "-":
                body = sys.stdin.read()
                headers.append(("Content-Length", str(len(body))))
        
            resp = request(args[0], method=args[1], body=body,
                        headers=headers, follow_redirect=opts.follow_redirect)
        else:
            if opts.input:
                method = 'POST'
            else:
                method='GET'
            resp = request(args[0], method=method, body=body,
                        headers=headers, follow_redirect=opts.follow_redirect)
                        
        if opts.output:
            f = open(opts.output, 'wb')
            for block in resp.body_file:
                f.write(block)
            f.close()
        else:
            print resp.body
        
    except Exception, e:
        sys.stderr.write("An error happened: %s" % str(e))
        sys.stderr.flush()
        sys.exit(1)

    sys.exit(0)
    
@@ -121,16 +121,54 @@
 ation.%0A%0A
+from __future__ import with_statement%0A
 import o
@@ -243,16 +243,29 @@
  request
+, set_logging
 %0A%0A__usag
@@ -584,24 +584,362 @@
 n/json%22 '),%0A
+        op.make_option('-S', '--server-response', action='store_true', %0A                default=False, dest='server_response', %0A                help='print server response'),%0A        op.make_option('--log-level', dest=%22log_level%22,%0A                help=%22Log level below which to silence messages. %5Binfo%5D%22,%0A                default=%22info%22),%0A
         op.m
@@ -1665,16 +1665,57 @@
 uments')
+%0A        %0A    set_logging(opts.log_level)
 %0A%0A    bo
@@ -3047,11 +3047,12 @@
     
-f =
+with
  ope
@@ -3071,17 +3071,265 @@
 t, 'wb')
-%0A
+ as f:%0A                if opts.log_level:%0A                    f.write(%22Server response from %25s:%5Cn%22 %25 resp.final_url)%0A                    for k, v in resp.headerslist:%0A                        f.write( %22%25s: %25s%22 %25 (k, v))%0A                else:%0A        
         
@@ -3361,16 +3361,24 @@
 y_file:%0A
+        
         
@@ -3412,22 +3412,278 @@
     
-    f.close()%0A
+else:%0A            if opts.log_level:%0A                print %22%5Cn%5C033%5B0m%5C033%5B95mServer response from %25s:%5Cn%5C033%5B0m%22 %25 resp.final_url%0A                for k, v in resp.headerslist:%0A                    print %22%5C033%5B94m%25s%5C033%5B0m: %25s%22 %25 (k, v)%0A                print %22%5C033%5B0m%22%0A    
     
@@ -3684,32 +3684,36 @@
           else:%0A
+    
             prin

improve restcli. now you can display debug info and print server headers