2012-04-25 01:32:53 +02:00
|
|
|
"""
|
|
|
|
CLI argument parsing logic.
|
|
|
|
|
|
|
|
"""
|
|
|
|
import os
|
2012-06-24 01:25:30 +02:00
|
|
|
import sys
|
2012-04-25 01:32:53 +02:00
|
|
|
import re
|
2012-04-28 14:18:59 +02:00
|
|
|
import json
|
|
|
|
import argparse
|
2012-06-29 00:45:31 +02:00
|
|
|
import mimetypes
|
2012-07-16 23:41:27 +02:00
|
|
|
import getpass
|
2012-04-28 14:18:59 +02:00
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
try:
|
|
|
|
from collections import OrderedDict
|
|
|
|
except ImportError:
|
|
|
|
OrderedDict = dict
|
2012-04-28 14:18:59 +02:00
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
from requests.structures import CaseInsensitiveDict
|
2012-04-28 14:18:59 +02:00
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
from . import __version__
|
|
|
|
|
|
|
|
|
|
|
|
SEP_COMMON = ':'
|
|
|
|
SEP_HEADERS = SEP_COMMON
|
|
|
|
SEP_DATA = '='
|
|
|
|
SEP_DATA_RAW_JSON = ':='
|
|
|
|
SEP_FILES = '@'
|
2012-07-19 03:44:09 +02:00
|
|
|
SEP_QUERY = '=:'
|
2012-06-24 03:43:08 +02:00
|
|
|
DATA_ITEM_SEPARATORS = [
|
2012-06-24 01:25:30 +02:00
|
|
|
SEP_DATA,
|
|
|
|
SEP_DATA_RAW_JSON,
|
|
|
|
SEP_FILES
|
2012-06-24 03:43:08 +02:00
|
|
|
]
|
2012-04-25 01:32:53 +02:00
|
|
|
|
|
|
|
|
|
|
|
OUT_REQ_HEADERS = 'H'
|
|
|
|
OUT_REQ_BODY = 'B'
|
|
|
|
OUT_RESP_HEADERS = 'h'
|
|
|
|
OUT_RESP_BODY = 'b'
|
|
|
|
OUTPUT_OPTIONS = [OUT_REQ_HEADERS,
|
|
|
|
OUT_REQ_BODY,
|
|
|
|
OUT_RESP_HEADERS,
|
|
|
|
OUT_RESP_BODY]
|
|
|
|
|
|
|
|
|
|
|
|
PRETTIFY_STDOUT_TTY_ONLY = object()
|
|
|
|
|
|
|
|
DEFAULT_UA = 'HTTPie/%s' % __version__
|
|
|
|
|
|
|
|
|
2012-06-24 03:43:08 +02:00
|
|
|
class Parser(argparse.ArgumentParser):
|
2012-04-25 01:32:53 +02:00
|
|
|
|
2012-06-24 01:25:30 +02:00
|
|
|
def parse_args(self, args=None, namespace=None,
|
|
|
|
stdin=sys.stdin,
|
|
|
|
stdin_isatty=sys.stdin.isatty()):
|
2012-07-16 23:41:27 +02:00
|
|
|
|
2012-06-24 03:43:08 +02:00
|
|
|
args = super(Parser, self).parse_args(args, namespace)
|
2012-07-16 23:41:27 +02:00
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
self._validate_output_options(args)
|
|
|
|
self._validate_auth_options(args)
|
2012-06-24 01:25:30 +02:00
|
|
|
self._guess_method(args, stdin_isatty)
|
2012-04-25 01:32:53 +02:00
|
|
|
self._parse_items(args)
|
2012-07-16 23:41:27 +02:00
|
|
|
|
2012-06-24 01:25:30 +02:00
|
|
|
if not stdin_isatty:
|
2012-06-29 00:45:31 +02:00
|
|
|
self._body_from_file(args, stdin)
|
2012-07-16 23:41:27 +02:00
|
|
|
|
|
|
|
if args.auth and not args.auth.has_password():
|
|
|
|
# stdin has already been read (if not a tty) so
|
|
|
|
# it's save to prompt now.
|
|
|
|
args.auth.prompt_password()
|
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
return args
|
|
|
|
|
2012-06-29 00:45:31 +02:00
|
|
|
def _body_from_file(self, args, f):
|
2012-06-24 01:25:30 +02:00
|
|
|
if args.data:
|
2012-06-29 00:45:31 +02:00
|
|
|
self.error('Request body (from stdin or a file) and request '
|
2012-06-24 01:25:30 +02:00
|
|
|
'data (key=value) cannot be mixed.')
|
2012-06-29 00:45:31 +02:00
|
|
|
args.data = f.read()
|
2012-06-24 01:25:30 +02:00
|
|
|
|
|
|
|
def _guess_method(self, args, stdin_isatty=sys.stdin.isatty()):
|
2012-06-24 03:43:08 +02:00
|
|
|
"""
|
|
|
|
Set `args.method`, if not specified, to either POST or GET
|
|
|
|
based on whether the request has data or not.
|
2012-06-24 01:25:30 +02:00
|
|
|
|
2012-06-17 19:46:56 +02:00
|
|
|
"""
|
|
|
|
if args.method is None:
|
2012-06-24 01:25:30 +02:00
|
|
|
# Invoked as `http URL'.
|
2012-06-17 19:46:56 +02:00
|
|
|
assert not args.items
|
2012-06-24 01:25:30 +02:00
|
|
|
if not stdin_isatty:
|
|
|
|
args.method = 'POST'
|
|
|
|
else:
|
|
|
|
args.method = 'GET'
|
|
|
|
# FIXME: False positive, e.g., "localhost" matches but is a valid URL.
|
2012-06-17 19:46:56 +02:00
|
|
|
elif not re.match('^[a-zA-Z]+$', args.method):
|
2012-06-24 01:25:30 +02:00
|
|
|
# Invoked as `http URL item+':
|
|
|
|
# - The URL is now in `args.method`.
|
|
|
|
# - The first item is now in `args.url`.
|
|
|
|
#
|
|
|
|
# So we need to:
|
|
|
|
# - Guess the HTTP method.
|
|
|
|
# - Set `args.url` correctly.
|
|
|
|
# - Parse the first item and move it to `args.items[0]`.
|
|
|
|
|
2012-06-17 19:46:56 +02:00
|
|
|
item = KeyValueType(
|
|
|
|
SEP_COMMON,
|
2012-07-19 03:44:09 +02:00
|
|
|
SEP_QUERY,
|
2012-06-17 19:46:56 +02:00
|
|
|
SEP_DATA,
|
|
|
|
SEP_DATA_RAW_JSON,
|
2012-06-24 01:25:30 +02:00
|
|
|
SEP_FILES).__call__(args.url)
|
|
|
|
|
2012-06-17 19:46:56 +02:00
|
|
|
args.url = args.method
|
|
|
|
args.items.insert(0, item)
|
2012-06-24 01:25:30 +02:00
|
|
|
|
|
|
|
has_data = not stdin_isatty or any(
|
|
|
|
item.sep in DATA_ITEM_SEPARATORS for item in args.items)
|
|
|
|
if has_data:
|
2012-06-17 19:46:56 +02:00
|
|
|
args.method = 'POST'
|
|
|
|
else:
|
|
|
|
args.method = 'GET'
|
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
def _parse_items(self, args):
|
2012-06-24 01:25:30 +02:00
|
|
|
"""
|
2012-07-19 03:44:09 +02:00
|
|
|
Parse `args.items` into `args.headers`, `args.data`, `args.queries`, and `args.files`.
|
2012-06-24 01:25:30 +02:00
|
|
|
|
|
|
|
"""
|
2012-04-25 01:32:53 +02:00
|
|
|
args.headers = CaseInsensitiveDict()
|
|
|
|
args.headers['User-Agent'] = DEFAULT_UA
|
|
|
|
args.data = OrderedDict()
|
|
|
|
args.files = OrderedDict()
|
2012-07-19 03:44:09 +02:00
|
|
|
args.queries = CaseInsensitiveDict()
|
2012-04-25 01:32:53 +02:00
|
|
|
try:
|
|
|
|
parse_items(items=args.items, headers=args.headers,
|
2012-07-19 03:44:09 +02:00
|
|
|
data=args.data, files=args.files, queries=args.queries)
|
2012-04-25 01:32:53 +02:00
|
|
|
except ParseError as e:
|
|
|
|
if args.traceback:
|
|
|
|
raise
|
|
|
|
self.error(e.message)
|
|
|
|
|
|
|
|
if args.files and not args.form:
|
2012-06-29 00:45:31 +02:00
|
|
|
# `http url @/path/to/file`
|
|
|
|
# It's not --form so the file contents will be used as the
|
|
|
|
# body of the requests. Also, we try to detect the appropriate
|
|
|
|
# Content-Type.
|
|
|
|
if len(args.files) > 1:
|
|
|
|
self.error(
|
|
|
|
'Only one file can be specified unless'
|
|
|
|
' --form is used. File fields: %s'
|
|
|
|
% ','.join(args.files.keys()))
|
|
|
|
f = list(args.files.values())[0]
|
|
|
|
self._body_from_file(args, f)
|
|
|
|
args.files = {}
|
|
|
|
if 'Content-Type' not in args.headers:
|
|
|
|
mime, encoding = mimetypes.guess_type(f.name, strict=False)
|
|
|
|
if mime:
|
|
|
|
content_type = mime
|
|
|
|
if encoding:
|
|
|
|
content_type = '%s; charset=%s' % (mime, encoding)
|
|
|
|
args.headers['Content-Type'] = content_type
|
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
def _validate_output_options(self, args):
|
2012-07-17 07:01:30 +02:00
|
|
|
unknown = set(args.output_options) - set(OUTPUT_OPTIONS)
|
|
|
|
if unknown:
|
|
|
|
self.error(
|
|
|
|
'Unknown output options: %s' %
|
|
|
|
','.join(unknown)
|
|
|
|
)
|
2012-04-25 01:32:53 +02:00
|
|
|
|
|
|
|
def _validate_auth_options(self, args):
|
|
|
|
if args.auth_type and not args.auth:
|
|
|
|
self.error('--auth-type can only be used with --auth')
|
|
|
|
|
|
|
|
|
|
|
|
class ParseError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2012-07-16 23:41:27 +02:00
|
|
|
class KeyValue(object):
|
|
|
|
"""Base key-value pair parsed from CLI."""
|
|
|
|
|
|
|
|
def __init__(self, key, value, sep, orig):
|
|
|
|
self.key = key
|
|
|
|
self.value = value
|
|
|
|
self.sep = sep
|
|
|
|
self.orig = orig
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return self.__dict__ == other.__dict__
|
2012-04-25 01:32:53 +02:00
|
|
|
|
|
|
|
|
|
|
|
class KeyValueType(object):
|
|
|
|
"""A type used with `argparse`."""
|
|
|
|
|
2012-07-16 23:41:27 +02:00
|
|
|
key_value_class = KeyValue
|
|
|
|
|
2012-04-25 01:32:53 +02:00
|
|
|
def __init__(self, *separators):
|
|
|
|
self.separators = separators
|
|
|
|
self.escapes = ['\\\\' + sep for sep in separators]
|
|
|
|
|
|
|
|
def __call__(self, string):
|
|
|
|
found = {}
|
|
|
|
found_escapes = []
|
|
|
|
for esc in self.escapes:
|
|
|
|
found_escapes += [m.span() for m in re.finditer(esc, string)]
|
|
|
|
for sep in self.separators:
|
|
|
|
matches = re.finditer(sep, string)
|
|
|
|
for match in matches:
|
|
|
|
start, end = match.span()
|
|
|
|
inside_escape = False
|
|
|
|
for estart, eend in found_escapes:
|
|
|
|
if start >= estart and end <= eend:
|
|
|
|
inside_escape = True
|
|
|
|
break
|
2012-07-19 03:44:09 +02:00
|
|
|
if start in found and len(found[start]) > len(sep):
|
|
|
|
break
|
2012-04-25 01:32:53 +02:00
|
|
|
if not inside_escape:
|
|
|
|
found[start] = sep
|
|
|
|
|
|
|
|
if not found:
|
|
|
|
raise argparse.ArgumentTypeError(
|
|
|
|
'"%s" is not a valid value' % string)
|
|
|
|
|
|
|
|
# split the string at the earliest non-escaped separator.
|
|
|
|
seploc = min(found.keys())
|
|
|
|
sep = found[seploc]
|
|
|
|
key = string[:seploc]
|
|
|
|
value = string[seploc + len(sep):]
|
|
|
|
|
|
|
|
# remove escape chars
|
|
|
|
for sepstr in self.separators:
|
|
|
|
key = key.replace('\\' + sepstr, sepstr)
|
|
|
|
value = value.replace('\\' + sepstr, sepstr)
|
2012-07-16 23:41:27 +02:00
|
|
|
return self.key_value_class(key=key, value=value, sep=sep, orig=string)
|
|
|
|
|
|
|
|
|
|
|
|
class AuthCredentials(KeyValue):
|
|
|
|
"""
|
|
|
|
Represents parsed credentials.
|
|
|
|
|
|
|
|
"""
|
|
|
|
def _getpass(self, prompt):
|
2012-07-17 00:05:09 +02:00
|
|
|
# To allow mocking.
|
2012-07-16 23:41:27 +02:00
|
|
|
return getpass.getpass(prompt)
|
|
|
|
|
|
|
|
def has_password(self):
|
|
|
|
return self.value is not None
|
|
|
|
|
|
|
|
def prompt_password(self):
|
|
|
|
try:
|
|
|
|
self.value = self._getpass("Password for user '%s': " % self.key)
|
|
|
|
except (EOFError, KeyboardInterrupt):
|
|
|
|
sys.stderr.write('\n')
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
|
|
|
|
class AuthCredentialsType(KeyValueType):
|
2012-04-25 01:32:53 +02:00
|
|
|
|
2012-07-16 23:41:27 +02:00
|
|
|
key_value_class = AuthCredentials
|
2012-04-25 01:32:53 +02:00
|
|
|
|
2012-07-16 10:40:36 +02:00
|
|
|
def __call__(self, string):
|
|
|
|
try:
|
2012-07-16 23:41:27 +02:00
|
|
|
return super(AuthCredentialsType, self).__call__(string)
|
2012-07-16 10:40:36 +02:00
|
|
|
except argparse.ArgumentTypeError:
|
2012-07-16 23:41:27 +02:00
|
|
|
# No password provided, will prompt for it later.
|
|
|
|
return self.key_value_class(
|
|
|
|
key=string,
|
|
|
|
value=None,
|
|
|
|
sep=SEP_COMMON,
|
|
|
|
orig=string
|
|
|
|
)
|
2012-07-16 10:40:36 +02:00
|
|
|
|
|
|
|
|
2012-07-19 03:44:09 +02:00
|
|
|
def parse_items(items, data=None, headers=None, files=None, queries=None):
|
|
|
|
"""Parse `KeyValueType` `items` into `data`, `headers`, `files`, and `queries`."""
|
2012-04-25 01:32:53 +02:00
|
|
|
if headers is None:
|
|
|
|
headers = {}
|
|
|
|
if data is None:
|
|
|
|
data = {}
|
|
|
|
if files is None:
|
|
|
|
files = {}
|
2012-07-19 03:44:09 +02:00
|
|
|
if queries is None:
|
|
|
|
queries = {}
|
2012-04-25 01:32:53 +02:00
|
|
|
for item in items:
|
|
|
|
value = item.value
|
|
|
|
key = item.key
|
|
|
|
if item.sep == SEP_HEADERS:
|
|
|
|
target = headers
|
2012-07-19 03:44:09 +02:00
|
|
|
elif item.sep == SEP_QUERY:
|
|
|
|
target = queries
|
2012-04-25 01:32:53 +02:00
|
|
|
elif item.sep == SEP_FILES:
|
|
|
|
try:
|
|
|
|
value = open(os.path.expanduser(item.value), 'r')
|
|
|
|
except IOError as e:
|
|
|
|
raise ParseError(
|
|
|
|
'Invalid argument %r. %s' % (item.orig, e))
|
|
|
|
if not key:
|
|
|
|
key = os.path.basename(value.name)
|
|
|
|
target = files
|
|
|
|
elif item.sep in [SEP_DATA, SEP_DATA_RAW_JSON]:
|
|
|
|
if item.sep == SEP_DATA_RAW_JSON:
|
|
|
|
try:
|
|
|
|
value = json.loads(item.value)
|
|
|
|
except ValueError:
|
|
|
|
raise ParseError('%s is not valid JSON' % item.orig)
|
|
|
|
target = data
|
|
|
|
else:
|
|
|
|
raise ParseError('%s is not valid item' % item.orig)
|
|
|
|
|
|
|
|
if key in target:
|
|
|
|
ParseError('duplicate item %s (%s)' % (item.key, item.orig))
|
|
|
|
|
|
|
|
target[key] = value
|
|
|
|
|
2012-07-19 03:44:09 +02:00
|
|
|
return headers, data, files, queries
|